Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for Google Tag Manager environment config #2045

Merged
merged 5 commits into from
Feb 21, 2025

Conversation

sandeepdsvs
Copy link
Contributor

@sandeepdsvs sandeepdsvs commented Feb 18, 2025

PR Description

Add support for Google Tag Manager environment config
Resolves INT-3252

Linear task (optional)

Linear task link

Cross Browser Tests

Please confirm you have tested for the following browsers:

  • Chrome
  • Firefox
  • IE11

Sanity Suite

  • All sanity suite test cases pass locally

Security

  • The code changed/added as part of this pull request won't create any security issues with how the software is being used.

Summary by CodeRabbit

  • New Features
    • Enhanced the Google Tag Manager integration by adding configuration options for specifying environment and authorization details.
    • Improved the script-loading process to accommodate these additional settings for a more robust integration experience.
  • Tests
    • Updated test cases to validate the new configuration properties for the Google Tag Manager integration.
    • Introduced new tests to verify the functionality of the script loading process with the updated parameters.

Copy link
Contributor

coderabbitai bot commented Feb 18, 2025

Warning

Rate limit exceeded

@sandeepdsvs has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 6 minutes and 28 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 50c23e3 and 2c31fc2.

📒 Files selected for processing (1)
  • packages/analytics-js-integrations/__tests__/integrations/GoogleTagManager/nativeSdkLoader.test.js (1 hunks)
📝 Walkthrough

Walkthrough

The changes update the GoogleTagManager integration by introducing two new configuration parameters: environmentID and authorizationToken. The constructor of the GoogleTagManager class now assigns these properties from the passed config object. The init method is modified to forward these values to the loadNativeSdk function. In the SDK loader, the function signature is updated to accept the new parameters, and the script URL construction is enhanced to conditionally include additional query parameters based on their values.

Changes

File(s) Change Summary
packages/analytics-js-integrations/.../GoogleTagManager/browser.js
packages/analytics-js-integrations/.../GoogleTagManager/nativeSdkLoader.js
Added new properties (environmentID, authorizationToken) to the GoogleTagManager class constructor and updated the init method to pass these parameters. Modified loadNativeSdk to accept and process the new parameters for conditional URL construction.
packages/analytics-js-integrations/.../GoogleTagManager/browser.test.js Updated test suite to include new properties in the config object and modified expectations for the loadNativeSdk function call to include the new parameters.
packages/analytics-js-integrations/.../GoogleTagManager/nativeSdkLoader.test.js Introduced a new test file for loadNativeSdk, verifying the function's behavior with respect to the new parameters and ensuring correct URL construction and script loading.

Sequence Diagram(s)

sequenceDiagram
    participant GM as GoogleTagManager
    participant NSL as NativeSdkLoader
    participant SL as Script Loader

    Note over GM: Config includes environmentID & authorizationToken
    GM->>GM: Instantiate GoogleTagManager(config, analytics, destinationInfo)
    GM->>NSL: init() calls loadNativeSdk(containerID, serverUrl, environmentID, authorizationToken)
    NSL-->>NSL: Construct script URL with new query parameters if values exist
    NSL->>SL: Request script load
    SL-->>NSL: Script loaded
    NSL-->>GM: Return load result
Loading

Possibly related PRs

Suggested labels

DO NOT MERGE

Suggested reviewers

  • ItsSudip
  • koladilip
  • shrouti1507

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js (1)

20-21: Consider adding parameter validation.

While the property assignments are correct, consider adding validation for environmentID and authorizationToken to ensure they meet GTM's requirements when provided.

-    this.environmentID = config.environmentID;
-    this.authorizationToken = config.authorizationToken;
+    this.environmentID = config.environmentID ? String(config.environmentID).trim() : undefined;
+    this.authorizationToken = config.authorizationToken ? String(config.authorizationToken).trim() : undefined;
+    
+    if (this.environmentID && !/^[a-zA-Z0-9-_]+$/.test(this.environmentID)) {
+      logger.warn('Invalid environmentID format. It should only contain alphanumeric characters, hyphens, and underscores.');
+    }
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c676168 and 28066ad.

📒 Files selected for processing (2)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js (2 hunks)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js (2 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Security and code quality checks
  • GitHub Check: Bundle size checks
  • GitHub Check: Unit Tests and Lint
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js (3)

3-3: LGTM! Function signature updated correctly.

The addition of environmentID and authorizationToken parameters aligns with GTM's environment configuration requirements.


19-19: LGTM! Script source URL constructed correctly.

The URL construction properly combines all parameters in a clean and maintainable way.


14-16:

❓ Verification inconclusive

LGTM! URL parameters constructed securely.

The implementation correctly:

  • Follows GTM's URL parameter format
  • Uses proper URL encoding for security
  • Handles optional parameters gracefully

Please verify the GTM environment configuration format:


🌐 Web query:

What is the correct format for Google Tag Manager environment preview URL parameters?

💡 Result:

Google Tag Manager's environment preview URLs use specific parameters to enable debugging and testing. Based on search results:

Standard preview mode URL format:

https://example.com/?gtm_auth=AUTH_TOKEN&gtm_preview=ENV_ID&gtm_debug=x

Key parameters:

  • gtm_auth: Authentication token generated when creating/sharing a preview link [6][9]
  • gtm_preview: Environment ID indicating which container configuration to load [3][9]
  • gtm_debug=x: Flag enabling debug mode interface [7][8]

For server-side tagging, additional parameters appear in requests:

https://sgtm.example.com?id=GTM_SERVER_ID&gtm_auth=AUTH_TOKEN&gtm_preview=ENV_ID

This structure routes requests through load balancers while maintaining preview context[3].

Important implementation details:

  1. Parameters are automatically appended when using GTM's native preview mode[7]
  2. Multiple environments require distinct auth tokens and environment IDs[6][9]
  3. Server-side configurations use environment variables like PREVIEW_SERVER_URL to manage routing[3]
  4. Debug parameters can be manually removed if they break site functionality (&gtm_debug=)[7]

For shared preview links, GTM generates URLs with these parameters pre-configured for specific environments[6][9]. The authentication tokens ensure only authorized users can access unpublished container configurations.

Citations:


URL Parameter Construction: Please Verify GTM Parameters

The URL parameters are built securely with appropriate encoding and optional handling. However, note two potential discrepancies versus the standard GTM preview URL format:

  • Environment Parameter: Your code constructs the environment segment as
    &gtm_preview=env-${encodeURIComponent(environmentID)}
    whereas the standard format is typically
    &gtm_preview=${encodeURIComponent(environmentID)}.

  • Debug Flag: Instead of using the standard debug parameter (&gtm_debug=x), your implementation uses a constant parameter
    &gtm_cookies_win=x.

Please verify that these differences are intentional for your specific GTM configuration. If not, consider aligning with the documented format:

?gtm_auth=AUTH_TOKEN&gtm_preview=ENV_ID&gtm_debug=x
packages/analytics-js-integrations/src/integrations/GoogleTagManager/browser.js (1)

30-30: LGTM! Init method updated correctly.

The loadNativeSdk call properly forwards the new configuration parameters.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 18, 2025
Copy link

github-actions bot commented Feb 18, 2025

size-limit report 📦

Name Size (Base) Size (Current) Size Limit Status
Cookies Utils - Legacy - NPM (ESM) 1.54 KB 1.54 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (CJS) 1.75 KB 1.75 KB (0%) 2 KB
Cookies Utils - Legacy - NPM (UMD) 1.54 KB 1.54 KB (0%) 2 KB
Cookies Utils - Modern - NPM (ESM) 1.17 KB 1.17 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (CJS) 1.4 KB 1.4 KB (0%) 1.5 KB
Cookies Utils - Modern - NPM (UMD) 1.16 KB 1.16 KB (0%) 1.5 KB
Plugins Module Federation Mapping - Legacy - CDN 332 B 332 B (0%) 512 B
Plugins Module Federation Mapping - Modern - CDN 331 B 331 B (0%) 512 B
Plugins - Legacy - CDN 13.66 KB 13.66 KB (0%) 14 KB
Plugins - Modern - CDN 5.64 KB 5.64 KB (0%) 6 KB
Common - No bundling 17.93 KB 17.93 KB (0%) 18.4 KB
Load Snippet 765 B 765 B (0%) 1 KB
Core (v1.1) - NPM (ESM) 30.16 KB 30.16 KB (0%) 32 KB
Core (v1.1) - NPM (CJS) 30.32 KB 30.32 KB (0%) 32 KB
Core (v1.1) - NPM (UMD) 30.23 KB 30.23 KB (0%) 32 KB
Core (Content Script - v1.1) - NPM (ESM) 29.59 KB 29.59 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (CJS) 29.84 KB 29.84 KB (0%) 30.5 KB
Core (Content Script - v1.1) - NPM (UMD) 29.71 KB 29.71 KB (0%) 30.5 KB
Core (v1.1) - Legacy - CDN 32.03 KB 32.03 KB (0%) 32.5 KB
Core (v1.1) - Modern - CDN 30 KB 30 KB (0%) 32 KB
Service Worker - Legacy - NPM (ESM) 30.54 KB 30.54 KB (0%) 31 KB
Service Worker - Legacy - NPM (CJS) 30.85 KB 30.85 KB (0%) 31 KB
Service Worker - Legacy - NPM (UMD) 30.69 KB 30.69 KB (0%) 31 KB
Service Worker - Modern - NPM (ESM) 25.73 KB 25.73 KB (0%) 26 KB
Service Worker - Modern - NPM (CJS) 26 KB 26 KB (0%) 26.5 KB
Service Worker - Modern - NPM (UMD) 25.75 KB 25.75 KB (0%) 26 KB
Core - Legacy - NPM (ESM) 47.42 KB 47.42 KB (0%) 48 KB
Core - Legacy - NPM (CJS) 47.64 KB 47.64 KB (0%) 48 KB
Core - Legacy - NPM (UMD) 47.41 KB 47.41 KB (0%) 48 KB
Core - Legacy - CDN 47.53 KB 47.53 KB (0%) 47.6 KB
Core - Modern - NPM (ESM) 26.85 KB 26.85 KB (0%) 27 KB
Core - Modern - NPM (CJS) 27.06 KB 27.06 KB (0%) 27.1 KB
Core - Modern - NPM (UMD) 26.89 KB 26.89 KB (0%) 27 KB
Core - Modern - CDN 27.13 KB 27.13 KB (0%) 27.5 KB
Core (Bundled) - Legacy - NPM (ESM) 47.42 KB 47.42 KB (0%) 48 KB
Core (Bundled) - Legacy - NPM (CJS) 47.67 KB 47.67 KB (0%) 48 KB
Core (Bundled) - Legacy - NPM (UMD) 47.41 KB 47.41 KB (0%) 48 KB
Core (Bundled) - Modern - NPM (ESM) 38.57 KB 38.57 KB (0%) 39 KB
Core (Bundled) - Modern - NPM (CJS) 38.88 KB 38.88 KB (0%) 39 KB
Core (Bundled) - Modern - NPM (UMD) 38.56 KB 38.56 KB (0%) 39 KB
Core (Content Script) - Legacy - NPM (ESM) 47.32 KB 47.32 KB (0%) 48 KB
Core (Content Script) - Legacy - NPM (CJS) 47.59 KB 47.59 KB (0%) 48 KB
Core (Content Script) - Legacy - NPM (UMD) 47.38 KB 47.38 KB (0%) 48 KB
Core (Content Script) - Modern - NPM (ESM) 38.5 KB 38.5 KB (0%) 39 KB
Core (Content Script) - Modern - NPM (CJS) 38.78 KB 38.78 KB (0%) 39 KB
Core (Content Script) - Modern - NPM (UMD) 38.54 KB 38.54 KB (0%) 39 KB
All Integrations - Legacy - CDN 94.98 KB 95.1 KB (+0.13% ▲) 95.3 KB
All Integrations - Modern - CDN 90.63 KB 90.67 KB (+0.05% ▲) 91 KB

@sandeepdsvs sandeepdsvs marked this pull request as ready for review February 21, 2025 05:03
@sandeepdsvs sandeepdsvs requested a review from a team as a code owner February 21, 2025 05:03
Copy link

codecov bot commented Feb 21, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 61.42%. Comparing base (a53a9e1) to head (2c31fc2).
Report is 1 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #2045   +/-   ##
========================================
  Coverage    61.41%   61.42%           
========================================
  Files          478      478           
  Lines        16404    16406    +2     
  Branches      3238     3230    -8     
========================================
+ Hits         10075    10077    +2     
- Misses        5113     5140   +27     
+ Partials      1216     1189   -27     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/analytics-js-integrations/__tests__/integrations/GoogleTagManager/browser.test.js (1)

47-55: Update test description and add edge cases for GTM environment config.

The test description is outdated and doesn't reflect the new environment parameters. Additionally, consider testing edge cases:

  1. When environment config is missing
  2. When only one of the environment parameters is provided

Update the test suite:

-it('should call loadNativeSdk with containerID and serverUrl', () => {
+it('should call loadNativeSdk with container and environment config', () => {
   googleTagManager.init();
   expect(loadNativeSdk).toHaveBeenCalledWith(
     config.containerID,
     config.serverUrl,
     config.environmentID,
     config.authorizationToken,
   );
 });

+it('should handle missing environment config gracefully', () => {
+  const minimalConfig = {
+    containerID: 'DUMMY_CONTAINER_ID',
+    serverUrl: 'DUMMY_SERVER_URL',
+  };
+  const gtm = new GoogleTagManager(minimalConfig, analytics, destinationInfo);
+  gtm.init();
+  expect(loadNativeSdk).toHaveBeenCalledWith(
+    minimalConfig.containerID,
+    minimalConfig.serverUrl,
+    undefined,
+    undefined,
+  );
+});
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 28066ad and 1f21962.

📒 Files selected for processing (2)
  • packages/analytics-js-integrations/__tests__/integrations/GoogleTagManager/browser.test.js (2 hunks)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Security and code quality checks
  • GitHub Check: Unit Tests and Lint
  • GitHub Check: Bundle size checks
🔇 Additional comments (1)
packages/analytics-js-integrations/__tests__/integrations/GoogleTagManager/browser.test.js (1)

81-173: Well-structured test coverage for core GTM functionality!

The test suite demonstrates thorough coverage of core GTM functionality including:

  • Proper dataLayer initialization and cleanup
  • Comprehensive testing of identify, track, and page methods
  • Good validation of event properties and user traits
  • Edge case handling for page views

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 21, 2025
@sandeepdsvs sandeepdsvs force-pushed the feat.gtag-env-config-support branch from 18712e0 to 0656731 Compare February 21, 2025 06:13
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
packages/analytics-js-integrations/__tests__/integrations/GoogleTagManager/nativeSdkLoader.test.js (2)

19-35: Consider adding more test coverage.

While the basic functionality tests are good, consider adding:

  • Negative test cases (e.g., invalid containerID)
  • Error handling scenarios
  • More assertions for dataLayer event properties (e.g., verify all expected properties are present)

Example test case:

test('should handle invalid containerID gracefully', () => {
  expect(() => loadNativeSdk('', null, null, null)).toThrow();
  expect(() => loadNativeSdk(null, null, null, null)).toThrow();
});

37-51: Add more script element validations.

Consider adding assertions for:

  1. Script element position in DOM (verify it's inserted before the first script)
  2. The 'l' parameter defaulting to "dataLayer"

Example assertions:

// Verify script position
const allScripts = document.getElementsByTagName('script');
expect(allScripts[0]).toBe(insertedScript);
expect(allScripts[1].id).toBe('dummy-script');

// Verify dataLayer parameter
expect(insertedScript.src).toContain('l=dataLayer');
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0656731 and 50c23e3.

📒 Files selected for processing (2)
  • packages/analytics-js-integrations/__tests__/integrations/GoogleTagManager/nativeSdkLoader.test.js (1 hunks)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/analytics-js-integrations/src/integrations/GoogleTagManager/nativeSdkLoader.js
🧰 Additional context used
🧠 Learnings (1)
packages/analytics-js-integrations/__tests__/integrations/GoogleTagManager/nativeSdkLoader.test.js (1)
Learnt from: saikumarrs
PR: rudderlabs/rudder-sdk-js#1708
File: packages/analytics-js/__tests__/nativeSdkLoader.js:31-33
Timestamp: 2024-11-12T15:14:23.319Z
Learning: The loading snippet in `packages/analytics-js/__tests__/nativeSdkLoader.js` is a standard part of the SDK, and no changes are desired on it.
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Security and code quality checks
  • GitHub Check: Unit Tests and Lint
  • GitHub Check: Bundle size checks
🔇 Additional comments (1)
packages/analytics-js-integrations/__tests__/integrations/GoogleTagManager/nativeSdkLoader.test.js (1)

1-18: Well-structured test setup!

The test setup and teardown procedures are thorough, properly managing both DOM elements and global state between tests.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 21, 2025
@sandeepdsvs sandeepdsvs merged commit 148a22a into develop Feb 21, 2025
10 checks passed
@sandeepdsvs sandeepdsvs deleted the feat.gtag-env-config-support branch February 21, 2025 07:21
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants