Skip to content

refactor: postscript utils functions - #4562

Merged
maheshkutty merged 10 commits into
developfrom
fix.postscript_implemntation
Aug 18, 2025
Merged

maheshkutty merged 10 commits into
developfrom
fix.postscript_implemntation

Conversation

@maheshkutty

@maheshkutty maheshkutty commented Aug 14, 2025 •

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

This pull request updates the Postscript destination integration to align with recent API changes and improve payload formatting and error handling. The main updates include switching custom event endpoints, updating response handling for subscriber lookups, and ensuring timestamps are formatted as required by Postscript. Test cases have also been updated to reflect these changes.

API endpoint and payload formatting updates:

  • Changed the custom events API endpoint from /custom-events to /events in both config.ts and all related test cases, ensuring requests match the latest Postscript API specification. [1] [2] [3] [4] [5] [6]
  • Updated the timestamp formatting for custom event payloads to the UTC format %Y-%m-%d %H:%M:%S.%f as required by Postscript, replacing previous ISO string formatting. [1] [2] [3] [4] [5] [6]

Subscriber lookup improvements:

  • Changed the response field for subscriber lookup from data to subscribers in both the TypeScript type definition and lookup logic, matching the latest API response structure. [1] [2]
  • Updated subscriber lookup logic to use the correct filter parameter (phone_number__in instead of phone_in) and improved error handling to ensure all events are marked as non-existing subscribers if the API call fails. [1] [2] [3]

Code quality and maintainability:

  • Refactored custom event payload construction to use utility functions for removing undefined/null values and for consistent timestamp formatting, and simplified the extraction of custom properties. [1] [2] [3]

These changes ensure the integration remains compatible with the latest Postscript API and improve both reliability and maintainability.

What is the related Linear task?

Resolves INT-3835

Please explain the objectives of your changes below

Put down any required details on the broader aspect of your changes. If there are any dependent changes, mandatorily mention them here

Any changes to existing capabilities/behaviour, mention the reason & what are the changes ?

N/A

Any new dependencies introduced with this change?

N/A

Any new generic utility introduced or modified. Please explain the changes.

N/A

Any technical or performance related pointers to consider with the change?

N/A

@coderabbitai review


Developer checklist

  • My code follows the style guidelines of this project

  • No breaking changes are being introduced.

  • All related docs linked with the PR?

  • All changes manually tested?

  • Any documentation changes needed with this change?

  • Is the PR limited to 10 file changes?

  • Is the PR limited to one linear task?

  • Are relevant unit and component test-cases added in new readability format?

Reviewer checklist

  • Is the type of change in the PR title appropriate as per the changes?

  • Verified that there are no credentials or confidential data exposed with the changes.

@maheshkutty
maheshkutty requested review from a team and sivashanmukh as code owners August 14, 2025 09:55
@maheshkutty
maheshkutty requested review from a team, ItsSudip and krishna2020 August 14, 2025 09:55
@coderabbitai

coderabbitai Bot commented Aug 14, 2025 •

Copy link
Copy Markdown
Contributor

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Summary by CodeRabbit

  • New Features

    • Custom events now sent to /events.
    • Event payloads include occurred_at and cleaned custom properties.
    • Optional partner key header supported via environment variable.
    • Stricter validation: requires non-empty event name.
  • Bug Fixes

    • More reliable subscriber lookup with graceful error handling and logging.
    • Payloads sanitized to remove undefined/null values.
  • Tests

    • Expanded coverage for headers, payload construction, timestamp formatting, subscriber lookup, and required-field validation.

Walkthrough

Replaces Postscript custom-events endpoint with /events; renames lookup response field data → subscribers; removes connection-related types/usages; adds validateRequiredFields; adjusts payload construction (timestamp formatting, inclusion of email/phone, custom fields extraction and sanitization); changes subscriber lookup to use phone_number__in; removes connection parameter from batching; updates tests and header behavior to honor POSTSCRIPT_PARTNER_API_KEY.

Changes

Cohort / File(s) Summary
Config endpoint update
src/v0/destinations/postscript/config.ts
CUSTOM_EVENTS_ENDPOINT changed from ${BASE_ENDPOINT}/custom-events → ${BASE_ENDPOINT}/events.
Types & public API surface
src/v0/destinations/postscript/types.ts
PostscriptLookupResponse.data renamed to subscribers; removed PostscriptConnectionConfigSchema, PostscriptConnectionConfig, and PostscriptConnection exports; simplified PostscriptRouterRequest by removing the connection generic.
Utils: headers, payloads, lookup, validation, batching
src/v0/destinations/postscript/utils.ts
Added imports isObject, formatTimeStamp; conditional X-Postscript-Partner-Key header from env var; buildSubscriberPayload extracts custom fields from explicit sources and sanitizes payload; buildCustomEventPayload includes email/phone and formatted occurred_at; performSubscriberLookup queries /v2/subscribers?phone_number__in=..., reads subscribers, logs on HTTP error and returns fallback mapping; added validateRequiredFields; removed connection param from batchResponseBuilder.
Transform: remove connection usage & validation
src/v0/destinations/postscript/transform.ts
Removed destructuring/usage of connection; tightened track event name validation to require a non-empty trimmed string; updated batchResponseBuilder calls to omit connection.
Tests: align to new logic & API
src/v0/destinations/postscript/utils.test.ts
Reduced internal mocking to network/logger only; updated tests for subscribers response shape, phone_number__in lookup, partner-key header behavior, timestamp formatting, payload shapes, required-field validation, and new batching semantics.

Sequence Diagram(s)

sequenceDiagram
  participant Processor as Rudder Processor
  participant Utils as Postscript Utils
  participant API as Postscript API
  participant Logger as Logger

  Processor->>Utils: performSubscriberLookup(events[])
  Utils->>API: GET /v2/subscribers?phone_number__in=...
  API-->>Utils: 200 { subscribers: [...] } / 4xx/5xx
  alt success
    Utils->>Utils: map subscribers by phone_number -> event mapping
    Utils-->>Processor: mapping with exists/subscriber info
  else error
    Utils->>Logger: logger.warn("PostScript subscriber lookup failed", ...)
    Utils-->>Processor: mapping marking events as non-existing
  end
Loading
sequenceDiagram
  participant Processor as Rudder Processor
  participant Utils as Postscript Utils

  Processor->>Utils: buildCustomEventPayload(message)
  Utils->>Utils: format timestamp -> occurred_at
  Utils->>Utils: include email, phone, sanitized properties
  Utils-->>Processor: event payload

  Processor->>Utils: buildSubscriberPayload(message, mapping, opts)
  Utils->>Utils: compute exclusions, extract custom fields (traits/context), sanitize
  Utils-->>Processor: subscriber payload
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~35 minutes

Possibly related PRs

Suggested reviewers

  • sivashanmukh
  • krishna2020
  • utsabc
  • koladilip

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix.postscript_implemntation

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@maheshkutty
maheshkutty force-pushed the fix.postscript_implemntation branch from 3402457 to f13aa10 Compare August 14, 2025 09:55
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@codecov

codecov Bot commented Aug 14, 2025 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.80%. Comparing base (7ae313f) to head (4a166b6).
⚠️ Report is 42 commits behind head on develop.

Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #4562      +/-   ##
===========================================
+ Coverage    91.63%   91.80%   +0.17%     
===========================================
  Files          643      642       -1     
  Lines        34020    33908     -112     
  Branches      8048     8022      -26     
===========================================
- Hits         31174    31130      -44     
+ Misses        2588     2548      -40     
+ Partials       258      230      -28     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (7)
src/v0/destinations/postscript/utils.ts (5)

46-51: Don't send partner key header when unset

Currently, the header is included with an undefined value. Prefer omitting the header entirely to avoid sending a literal "undefined" value through the adapter.

Apply this diff:

-export const buildHeaders = (apiKey: string): PostscriptHeaders => ({
-  'Content-type': 'application/json',
-  Accept: 'application/json',
-  Authorization: `Bearer ${apiKey}`,
-  'X-Postscript-Partner-Key': process.env.POSTSCRIPT_PARTNER_API_KEY,
-});
+export const buildHeaders = (apiKey: string): PostscriptHeaders => {
+  const headers: PostscriptHeaders = {
+    'Content-type': 'application/json',
+    Accept: 'application/json',
+    Authorization: `Bearer ${apiKey}`,
+  };
+  if (process.env.POSTSCRIPT_PARTNER_API_KEY) {
+    headers['X-Postscript-Partner-Key'] = process.env.POSTSCRIPT_PARTNER_API_KEY;
+  }
+  return headers;
+};

60-69: Required-fields check: make lookup more resilient across traits/context

Using getFieldValueFromMessage(message, field) assumes MESSAGE_MAPPING has the key (e.g., "email"). Add fallbacks to traits/context.traits and avoid treating empty strings as present.

Apply this diff:

 export const validateRequiredFields = (message: RudderMessage, requiredFields: string[]): void => {
   const missingFields = requiredFields.filter((field) => {
-    const value = getFieldValueFromMessage(message, field);
-    return !value;
+    // Try standard mapping first
+    const candidates = [
+      getFieldValueFromMessage(message, field),
+      getFieldValueFromMessage(message, `traits.${field}`),
+      getFieldValueFromMessage(message, `context.traits.${field}`),
+    ];
+    const value = candidates.find((v) => v !== null && v !== undefined && v !== '');
+    return value === undefined || value === null || value === '';
   });
 
   if (missingFields.length > 0) {
     throw new Error(`Missing required fields: ${missingFields.join(', ')}`);
   }
 };

109-116: Avoid setting shopify_customer_id to NaN

If the external ID is a non-numeric value (e.g., mocks returning same value for all types), Number() yields NaN, which leaks into the payload. Only set when it’s a finite number.

Apply this diff:

-  if (shopifyCustomerId) {
-    payload.shopify_customer_id = Number(shopifyCustomerId);
-  }
+  if (shopifyCustomerId !== null && shopifyCustomerId !== undefined) {
+    const shopifyIdNum = Number(shopifyCustomerId);
+    if (Number.isFinite(shopifyIdNum)) {
+      payload.shopify_customer_id = shopifyIdNum;
+    }
+  }

216-234: Lookup should support both phone and email; deduplicate params

Currently, only phone_number__in is used and identifierType isn’t respected. Support email__in too, and de-duplicate values to avoid redundant params.

Apply this diff:

-  // Extract phone numbers from events for batch lookup
-  const phoneNumbers = events
-    .map((event) => event.identifierValue)
-    .filter((phone) => phone) as string[];
+  // Extract identifiers by type
+  const phoneNumbers = Array.from(
+    new Set(
+      events
+        .filter((e) => e.identifierType === 'phone')
+        .map((e) => e.identifierValue)
+        .filter(Boolean) as string[],
+    ),
+  );
+  const emails = Array.from(
+    new Set(
+      events
+        .filter((e) => e.identifierType === 'email')
+        .map((e) => e.identifierValue)
+        .filter(Boolean) as string[],
+    ),
+  );
 
-  if (phoneNumbers.length === 0) {
+  if (phoneNumbers.length === 0 && emails.length === 0) {
     return [];
   }
 
   try {
     // Build lookup request with PostScript's filter parameters
     const headers = buildHeaders(apiKey);
     const params = new URLSearchParams();
 
-    // https://developers.postscript.io/reference/get-subscribers
-    phoneNumbers.forEach((phone) => {
-      params.append('phone_number__in', phone);
-    });
+    // https://developers.postscript.io/reference/get-subscribers
+    phoneNumbers.forEach((phone) => params.append('phone_number__in', phone));
+    emails.forEach((email) => params.append('email__in', email));

257-269: Respect identifierType and match on email when appropriate

The result always reports identifierType as phone and only matches by phone_number. Use the event’s identifierType to determine the match field and return type.

Apply this diff:

-    return events.map((event) => {
-      const phone = event.identifierValue;
-
-      // Find existing subscriber by phone
-      const existingSubscriber = subscribers.find((sub) => phone && sub.phone_number === phone);
-
-      return {
-        exists: !!existingSubscriber,
-        subscriberId: existingSubscriber?.id,
-        identifierValue: phone ?? '',
-        identifierType: 'phone' as const,
-      };
-    });
+    return events.map((event) => {
+      const identifierValue = event.identifierValue ?? '';
+      const type = event.identifierType === 'email' ? 'email' : 'phone';
+
+      let existingSubscriber: typeof subscribers[number] | undefined;
+      if (type === 'phone') {
+        existingSubscriber = subscribers.find((sub) => sub.phone_number === identifierValue);
+      } else {
+        existingSubscriber = subscribers.find((sub) => sub.email === identifierValue);
+      }
+
+      return {
+        exists: !!existingSubscriber,
+        subscriberId: existingSubscriber?.id,
+        identifierValue,
+        identifierType: type as 'phone' | 'email',
+      };
+    });
src/v0/destinations/postscript/utils.test.ts (2)

136-153: Adjust header test to expect omission (not undefined) when partner key is unset

With the proposed header change, the partner key header shouldn’t be present at all if the env var is missing.

Apply this diff:

-      expect(headers).toEqual({
-        'Content-type': 'application/json',
-        Accept: 'application/json',
-        Authorization: 'Bearer test_api_key_123',
-        'X-Postscript-Partner-Key': undefined,
-      });
+      expect(headers).toEqual({
+        'Content-type': 'application/json',
+        Accept: 'application/json',
+        Authorization: 'Bearer test_api_key_123',
+      });

275-311: Avoid asserting NaN for shopify_customer_id

Per the payload fix, shopify_customer_id will only be set when numeric. Update the expectation to omit this field when not present.

Apply this diff:

       expect(payload).toEqual({
         phone_number: '+1234567890',
         email: '[email protected]',
         external_id: 'sub_123',
-        shopify_customer_id: NaN,
       });
🧹 Nitpick comments (5)
src/v0/destinations/postscript/utils.ts (1)

141-147: Type customPropertiesPayload for clarity

Minor typing improvement for maintainability.

Apply this diff:

-  const customPropertiesPayload = {};
+  const customPropertiesPayload: Record<string, unknown> = {};
src/v0/destinations/postscript/utils.test.ts (4)

654-667: Keep subscriberId expectation consistent (undefined vs omitted)

performSubscriberLookup returns subscriberId: undefined for non-matches. Align this test with the function’s shape for consistency.

Apply this diff:

       expect(results).toEqual([
-        { exists: false, identifierValue: '+1234567890', identifierType: 'phone' },
-        { exists: false, identifierValue: '+0987654321', identifierType: 'phone' },
+        { exists: false, subscriberId: undefined, identifierValue: '+1234567890', identifierType: 'phone' },
+        { exists: false, subscriberId: undefined, identifierValue: '+0987654321', identifierType: 'phone' },
       ]);

724-729: Update test fixture endpoint to /events to match config

The config now exports /events. Keep test inputs in sync to avoid confusion.

Apply this diff:

         {
           eventType: 'track',
-          endpoint: 'https://api.postscript.io/api/v2/custom-events',
+          endpoint: 'https://api.postscript.io/api/v2/events',
           method: 'POST',
           payload: { type: 'Purchase' },
           metadata: { jobId: 2 },
         },

360-363: Mocking the JSON mapping mid-test likely has no effect

jest.doMock after the module under test has already imported the JSON won’t affect the in-memory subscriberMapping. The test already controls mapping via constructPayload and generateExclusionList; consider removing this to reduce confusion.


22-33: Optional: tighten mocks to only what’s asserted

Good move to limit mocking scope. As a further cleanup, remove unused mocked logger methods or add assertions for warn in the lookup error path to make the mock purposeful.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5fba787 and f13aa10.

⛔ Files ignored due to path filters (2)
  • test/integrations/destinations/postscript/router/mixedEventsTestData.ts is excluded by !**/test/**
  • test/integrations/destinations/postscript/router/trackTestData.ts is excluded by !**/test/**
📒 Files selected for processing (4)
  • src/v0/destinations/postscript/config.ts (1 hunks)
  • src/v0/destinations/postscript/types.ts (1 hunks)
  • src/v0/destinations/postscript/utils.test.ts (16 hunks)
  • src/v0/destinations/postscript/utils.ts (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/v0/destinations/postscript/utils.ts (2)
src/v0/util/index.js (3)
  • getFieldValueFromMessage (687-693)
  • formatTimeStamp (390-399)
  • removeUndefinedAndNullValues (55-55)
src/v0/destinations/postscript/types.ts (1)
  • PostscriptCustomEventPayload (92-100)
src/v0/destinations/postscript/utils.test.ts (2)
src/types/rudderEvents.ts (1)
  • RudderMessage (43-43)
src/v0/destinations/postscript/utils.ts (2)
  • validateRequiredFields (60-69)
  • buildCustomEventPayload (166-201)
🪛 Gitleaks (8.27.2)
src/v0/destinations/postscript/utils.test.ts

90-90: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
🔇 Additional comments (8)
src/v0/destinations/postscript/config.ts (1)

12-12: Endpoint path update to /events looks correct

Switching to /events aligns with Postscript’s current custom events API. No issues spotted in this file.

src/v0/destinations/postscript/types.ts (2)

130-136: Renaming lookup response field to subscribers matches downstream usage

The change to subscribers: PostscriptSubscriberResponse[] is consistent with utils.performSubscriberLookup.


130-136: Confirmed — no remaining usages of Postscript lookup .data; code reads from .subscribers

Checked the repo for Postscript lookup response usages. Findings (short):

  • src/v0/destinations/postscript/types.ts — PostscriptLookupResponse exposes subscribers: PostscriptSubscriberResponse[].
  • src/v0/destinations/postscript/utils.ts — lookup code casts to PostscriptLookupResponse and uses lookupData.subscribers (e.g., lines ~253–254).
  • src/v0/destinations/postscript/transform.ts — contains if (result.success && result.data) { processedEvents.push(result.data); } (lines ~206–207). This result.data is for processed events, not the Postscript lookup response.

Action: No fixes required for the lookup response change. Suggestion: consider renaming generic result.data (in transform) to a clearer name (e.g., result.payload or result.processed) to avoid future confusion between generic .data and the Postscript-specific .subscribers.

src/v0/destinations/postscript/utils.ts (2)

174-185: Timestamp handling for occurred_at is on point

Using formatTimeStamp with 'YYYY-MM-DD HH:mm:ss.SSS' aligns with the expected Postscript format.


187-195: Double-check fallback identifier semantics

You’re falling back to setting subscriber_id = userId when no external IDs exist. Verify this matches Postscript semantics; in many APIs, userId should map to external_id instead of subscriber_id if it’s not a Postscript subscriber ID.

Would you confirm via the Postscript docs whether user-origin IDs should populate external_id (preferred) rather than subscriber_id when no Postscript ID is present? If needed, I can provide a patch to switch the fallback.

src/v0/destinations/postscript/utils.test.ts (3)

596-637: Nice: request verification for the exact URL query

Asserting the exact query string with multiple phone_number__in params prevents regressions in encoding and parameterization.


490-551: Great coverage on timestamp formatting cases

The occurred_at format assertions across ISO variants are thorough.


90-101: Gitleaks false-positive on test keys; add ignore or use clearly fake patterns

Static analysis flagged a generic API key. These are test-only values, but consider:

  • Prefixing with obvious non-secret markers (e.g., dummy_, test_) or
  • Adding a gitleaks allowlist entry for these test files/strings.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (1)
src/v0/destinations/postscript/utils.ts (1)

121-140: Consider simplifying the exclusion list construction

The current implementation builds exclusions in two separate loops with different logic branches. This could be simplified for better maintainability.

Consider consolidating the exclusion list building:

-  // Create a comprehensive exclusion list for traits extraction
-  const traitsExclusions = new Set();
-
-  // Add all field names from the mapping configuration
-  subscriberMapping.forEach((mapping) => {
-    if (Array.isArray(mapping.sourceKeys)) {
-      mapping.sourceKeys.forEach((sourceKey) => {
-        if (sourceKey.startsWith('traits.')) {
-          // Extract the field name after 'traits.'
-          traitsExclusions.add(sourceKey.replace('traits.', ''));
-        }
-      });
-    } else if (mapping.sourceFromGenericMap) {
-      // For generic map fields, exclude the sourceKeys directly
-      traitsExclusions.add(mapping.sourceKeys);
-    }
-  });
-
-  // Convert Set to Array for extractCustomFields
-  const allExclusions = [...exclusionFields, ...Array.from(traitsExclusions)];
+  // Build comprehensive exclusion list from mapping configuration
+  const traitsExclusions = subscriberMapping.reduce((acc, mapping) => {
+    if (Array.isArray(mapping.sourceKeys)) {
+      mapping.sourceKeys.forEach((sourceKey) => {
+        if (sourceKey.startsWith('traits.')) {
+          acc.add(sourceKey.replace('traits.', ''));
+        }
+      });
+    } else if (mapping.sourceFromGenericMap) {
+      acc.add(mapping.sourceKeys);
+    }
+    return acc;
+  }, new Set());
+
+  const allExclusions = [...exclusionFields, ...traitsExclusions];
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f13aa10 and d328a33.

📒 Files selected for processing (2)
  • src/v0/destinations/postscript/utils.test.ts (10 hunks)
  • src/v0/destinations/postscript/utils.ts (5 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.

Applied to files:

  • src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (2)
src/v0/destinations/postscript/utils.test.ts (1)
src/v0/destinations/postscript/utils.ts (6)
  • buildHeaders (46-51)
  • validateRequiredFields (60-69)
  • buildSubscriberPayload (80-155)
  • buildCustomEventPayload (166-201)
  • performSubscriberLookup (212-284)
  • batchResponseBuilder (297-329)
src/v0/destinations/postscript/utils.ts (3)
src/v0/util/index.js (3)
  • getFieldValueFromMessage (687-693)
  • formatTimeStamp (390-399)
  • removeUndefinedAndNullValues (55-55)
src/v0/destinations/postscript/types.ts (2)
  • PostscriptCustomEventPayload (92-100)
  • PostscriptLookupResponse (129-136)
src/v0/destinations/postscript/config.ts (1)
  • SUBSCRIBERS_ENDPOINT (11-11)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (7)
src/v0/destinations/postscript/utils.ts (4)

32-33: Good additions for payload building and timestamp formatting

The imports of isObject and formatTimeStamp are appropriate for the new functionality in building custom event payloads with proper timestamp handling.


60-69: Well-implemented validation function

The validateRequiredFields function provides clean validation logic using the existing getFieldValueFromMessage utility. The error message clearly lists all missing fields, which will help with debugging.


174-185: Excellent timestamp formatting implementation

The occurred_at field is properly formatted using the formatTimeStamp utility with the correct format string. The conditional spread syntax ensures the field is only included when a timestamp exists, keeping the payload clean.


225-283: Robust error handling in subscriber lookup

The refactored performSubscriberLookup function properly handles API errors by logging warnings and returning safe defaults. The per-phone lookup approach using phone_number__in parameters is efficient and aligns with the PostScript API documentation.

src/v0/destinations/postscript/utils.test.ts (3)

16-29: Good test isolation with minimal mocking

The refactored mocking strategy that only mocks external dependencies (network and logger) while using real implementations for utility functions is a solid testing approach. This ensures the tests validate actual behavior rather than mock implementations.


275-306: Comprehensive timestamp format testing

The test cases effectively cover various timestamp formats including edge cases like end-of-year timestamps. The structured approach with test case descriptions makes the tests maintainable and clear.


438-475: Well-structured error handling test

The new test case for API error handling properly validates that the function logs warnings and returns safe defaults when the API fails. This ensures graceful degradation in production.

Comment thread src/v0/destinations/postscript/utils.ts Resolved
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@maheshkutty
maheshkutty requested a review from Copilot August 14, 2025 14:35

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

♻️ Duplicate comments (1)
src/v0/destinations/postscript/utils.test.ts (1)

39-65: Ensure environment variable cleanup in unit tests (duplicate of earlier feedback)

The test deletes process.env.POSTSCRIPT_PARTNER_API_KEY but doesn’t restore it if an exception occurs, which can leak state across tests.

Apply this diff to wrap the mutation in try/finally:

 it('should build headers without partner key when env var is not set', () => {
-  delete process.env.POSTSCRIPT_PARTNER_API_KEY;
-
-  const apiKey = 'test_api_key_123';
-  const headers = buildHeaders(apiKey);
-
-  expect(headers).toMatchObject({
-    'Content-type': 'application/json',
-    Accept: 'application/json',
-    Authorization: 'Bearer test_api_key_123',
-    'X-Postscript-Partner-Key': undefined,
-  });
+  const originalPartnerKey = process.env.POSTSCRIPT_PARTNER_API_KEY;
+  try {
+    delete process.env.POSTSCRIPT_PARTNER_API_KEY;
+
+    const apiKey = 'test_api_key_123';
+    const headers = buildHeaders(apiKey);
+
+    expect(headers).toMatchObject({
+      'Content-type': 'application/json',
+      Accept: 'application/json',
+      Authorization: 'Bearer test_api_key_123',
+      'X-Postscript-Partner-Key': undefined,
+    });
+  } finally {
+    if (originalPartnerKey !== undefined) {
+      process.env.POSTSCRIPT_PARTNER_API_KEY = originalPartnerKey;
+    } else {
+      delete process.env.POSTSCRIPT_PARTNER_API_KEY;
+    }
+  }
 });
🧹 Nitpick comments (5)
src/v0/destinations/postscript/transform.ts (2)

159-162: Extracting destination from the first input: add a uniformity guard (optional)

Assuming all inputs share the same destination is typical, but adding a sanity check can prevent hard-to-debug misroutes if invariants break upstream.

Apply this diff to defensively assert uniform destination IDs:

   // Extract destination configuration from first event
   const { destination } = inputs[0];
   const postscriptDestination = destination;
+  // Optional: assert uniform destination across inputs to avoid cross-destination mixing
+  const firstDestId = postscriptDestination.ID;
+  const mixedDest = inputs.some((i) => i.destination?.ID !== firstDestId);
+  if (mixedDest) {
+    throw new ConfigurationError('All inputs must target the same Postscript destination instance');
+  }

221-244: Index-based correlation of lookup results: add length guard (optional)

performSubscriberLookup should return a result per identify event; a defensive check can avoid undefined indexing if upstream logic changes or API returns unexpected shapes.

Consider guarding length mismatch and defaulting to create on missing results:

-  const updatedIdentifyEvents = identifyEvents.map((event, index) => {
-    const lookupResult = lookupResults[index];
+  const updatedIdentifyEvents = identifyEvents.map((event, index) => {
+    const lookupResult = lookupResults[index] ?? { exists: false };
     if (lookupResult?.exists) {
       return {
         ...event,
         method: 'PATCH' as const,
         endpoint: `${SUBSCRIBERS_ENDPOINT}/${lookupResult.subscriberId}`,
       };
     }
     return {
       ...event,
       method: 'POST' as const,
       endpoint: SUBSCRIBERS_ENDPOINT,
     };
   });
src/v0/destinations/postscript/utils.test.ts (3)

34-37: Avoid secret scanner false positives in tests (Gitleaks)

Gitleaks flagged a “Generic API Key” here. It’s a benign test value, but prefer obvious dummy strings to prevent CI noise.

Consider changing the setup value:

-    process.env.POSTSCRIPT_PARTNER_API_KEY = 'partner_key_123';
+    process.env.POSTSCRIPT_PARTNER_API_KEY = 'DUMMY_PARTNER_KEY';

And, if needed, add a repository-level allowlist entry for clearly dummy tokens used in tests.


300-313: Note: utils allows unnamed events; router rejects them

This test is valid for buildCustomEventPayload in isolation. Just be aware processTrackEvent in transform.ts throws if message.event is missing, so this payload shape won’t be emitted by router code paths.

If the intention is to keep utils resilient for reuse, add a short comment in the test clarifying the discrepancy to avoid confusion for future maintainers.


517-533: Strengthen header assertions to cover partner key propagation (optional)

Since buildHeaders attaches the partner key when set, asserting its presence here increases confidence that batchResponseBuilder wires headers correctly.

Apply this diff to extend assertions:

   const responses = batchResponseBuilder(events, mockDestination);

   expect(responses).toHaveLength(1);
   expect(responses[0].batchedRequest.headers).toHaveProperty('Authorization');
   expect(responses[0].batchedRequest.headers).toHaveProperty('Content-type');
+  expect(responses[0].batchedRequest.headers).toHaveProperty('X-Postscript-Partner-Key', 'partner_key_123');
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these settings in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between d328a33 and 76cad09.

📒 Files selected for processing (4)
  • src/v0/destinations/postscript/transform.ts (2 hunks)
  • src/v0/destinations/postscript/types.ts (2 hunks)
  • src/v0/destinations/postscript/utils.test.ts (10 hunks)
  • src/v0/destinations/postscript/utils.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/v0/destinations/postscript/utils.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.

Applied to files:

  • src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (2)
src/v0/destinations/postscript/transform.ts (1)
src/v0/destinations/postscript/utils.ts (1)
  • batchResponseBuilder (300-330)
src/v0/destinations/postscript/utils.test.ts (1)
src/v0/destinations/postscript/utils.ts (6)
  • buildHeaders (45-52)
  • validateRequiredFields (61-70)
  • buildSubscriberPayload (81-156)
  • buildCustomEventPayload (167-204)
  • performSubscriberLookup (215-287)
  • batchResponseBuilder (300-330)
🪛 Gitleaks (8.27.2)
src/v0/destinations/postscript/utils.test.ts

36-36: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (3)
src/v0/destinations/postscript/types.ts (2)

169-172: Router generics simplification looks good

Dropping the connection generic keeps the type surface lean and reflects the actual usage.


115-121: Lookup rename verified — no remaining .data lookup references

Ran the provided grep script against src/v0/destinations/postscript. Summary:

  • No matches for .data as the lookup response field.
  • subscribers is used consistently (types, utils, and tests).
  • No /custom-events references found.
  • The only mention of phone_in is in a comment.

Files/locations of interest:

  • src/v0/destinations/postscript/types.ts — defines lookup response with subscribers (lines ~115–121).
  • src/v0/destinations/postscript/utils.ts — builds phone_number__in params, calls /subscribers, and reads lookupData.subscribers (comments around ~207 and logic ~232–279).
  • src/v0/destinations/postscript/config.ts — SUBSCRIBERS_ENDPOINT and CUSTOM_EVENTS_ENDPOINT (/events) set.
  • Tests updated to expect subscribers (utils.test.ts, transform.test.ts).

Suggestion:

  • Update or remove the inline comment in utils.ts that mentions phone_in (around line ~209) to avoid confusion — the code uses phone_number__in.
src/v0/destinations/postscript/transform.ts (1)

256-257: batchResponseBuilder signature change handled correctly

The updated two-argument call aligns with the refactor in utils; response building remains per-event as intended.

This comment was marked as outdated.

Comment thread src/v0/destinations/postscript/utils.ts Resolved
@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
src/v0/destinations/postscript/utils.test.ts (2)

22-24: Update logger mock to be ESM/CJS-safe

The mock only provides named exports which can break consumers that import the logger as a default export, depending on module interop settings.


53-64: Environment variable cleanup needs try-finally protection

The test modifies a global environment variable but the restoration logic could fail if an exception occurs before the test completes.

🧹 Nitpick comments (2)
src/v0/destinations/postscript/utils.test.ts (2)

28-31: Type assertion for logger may cause issues

The logger is imported as a default export but then cast to jest.Mocked<typeof logger>, which may not match the actual structure if the mock doesn't properly expose the default export.

Consider updating the logger import and casting to be more explicit:

-import logger from '../../../logger';
-
-const mockHandleHttpRequest = handleHttpRequest as jest.MockedFunction<typeof handleHttpRequest>;
-const mockLogger = logger as jest.Mocked<typeof logger>;
+import * as logger from '../../../logger';

+const mockHandleHttpRequest = handleHttpRequest as jest.MockedFunction<typeof handleHttpRequest>;
+const mockLogger = logger.warn as jest.MockedFunction<typeof logger.warn>;

36-36: Consider using a test-specific environment variable

The static analysis tool flagged this as a potential API key exposure. While this is test code, consider using a clearly test-prefixed value to make it obvious this is not a real credential.

-    process.env.POSTSCRIPT_PARTNER_API_KEY = 'partner_key_123';
+    process.env.POSTSCRIPT_PARTNER_API_KEY = 'test_partner_key_123';
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 76cad09 and 171d255.

📒 Files selected for processing (3)
  • src/v0/destinations/postscript/transform.ts (3 hunks)
  • src/v0/destinations/postscript/utils.test.ts (10 hunks)
  • src/v0/destinations/postscript/utils.ts (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/v0/destinations/postscript/transform.ts
  • src/v0/destinations/postscript/utils.ts
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.

Applied to files:

  • src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/utils.test.ts (4)
src/util/prometheus.js (1)
  • logger (2-2)
src/v0/destinations/postscript/utils.ts (2)
  • buildHeaders (45-52)
  • validateRequiredFields (61-70)
src/types/rudderEvents.ts (1)
  • RudderMessage (43-43)
src/v0/destinations/postscript/types.ts (1)
  • ProcessedEvent (128-137)
🪛 Gitleaks (8.27.2)
src/v0/destinations/postscript/utils.test.ts

36-36: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: test_and_publish
  • GitHub Check: UT Tests
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (10)
src/v0/destinations/postscript/utils.test.ts (10)

69-85: Good test coverage for validateRequiredFields

The test cases comprehensively cover the new validateRequiredFields function, including positive cases (all fields present) and negative cases (missing fields). The inline RudderMessage construction is appropriate for unit tests.


132-138: Excellent property extraction testing

The test properly validates that custom fields are extracted into the properties object while standard fields are mapped to their correct payload keys. This aligns well with the updated payload construction logic.


177-187: Verify timestamp format expectations

The test expects occurred_at: '2025-01-15 10:00:00.000' format, which appears to match the UTC formatting described in the PR objectives. Good coverage of the new timestamp formatting requirements.


267-298: Comprehensive timestamp format testing

Excellent test coverage for different timestamp formats. The test cases cover standard ISO with milliseconds, ISO without milliseconds, and edge cases like end-of-year timestamps. This ensures the timestamp formatting logic handles various input formats correctly.


329-336: Response structure updated to match API changes

The test correctly uses subscribers array in the mock response, which aligns with the API changes mentioned in the PR objectives (replacing the previous data field).


347-347: API endpoint and parameter updates verified

The test correctly uses the new phone_number__in parameter format and the updated API endpoint structure, matching the changes described in the PR objectives.


415-452: Good error handling test coverage

The new test case for API errors properly verifies that the function logs warnings and returns non-existing results for all events when the lookup API fails. This matches the error handling strategy described in the PR objectives.


482-482: Events endpoint updated correctly

The test uses the new /api/v2/events endpoint, which aligns with the API changes mentioned in the PR objectives (changed from /custom-events to /events).


489-489: Batch response builder signature simplified

The function call only passes events and destination parameters, which matches the updated signature mentioned in the AI summary (no connection parameter).


100-100: Test assertion doesn't match the test case description

The test includes traits.keyword in the required fields array but expects it to be missing from the error message. However, according to the test data on Line 96, traits.keyword is actually present with value 'WELCOME'.

-        validateRequiredFields(mockMessage, ['email', 'phone', 'traits.keyword']);
-      }).toThrow('Missing required fields: email, phone');
+        validateRequiredFields(mockMessage, ['email', 'phone']);
+      }).toThrow('Missing required fields: email, phone');

Likely an incorrect or invalid review comment.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/v0/destinations/postscript/transform.ts (1)

159-161: Good call extracting destination from the first input; aligns with prior feedback.

This drops the unused connection dependency and matches the router pattern we use elsewhere.

🧹 Nitpick comments (2)
src/v0/destinations/postscript/transform.ts (2)

111-121: Stricter validation is great; also normalize the event name before building payload.

You already reject blank/whitespace-only names. To keep payloads consistent, pass a trimmed event name to the builder without mutating the original message.

   // Event name is required for track events
-  if (typeof message?.event !== 'string' || !message.event.trim()) {
+  // Event name is required for track events; normalize to trimmed value
+  if (typeof message?.event !== 'string' || !message.event.trim()) {
     throw new InstrumentationError('Event name is required for track events');
   }

   // Build the custom event payload using our mapping configuration
-  const payload = buildCustomEventPayload(message);
+  const sanitizedMessage = { ...message, event: message.event.trim() };
+  const payload = buildCustomEventPayload(sanitizedMessage);

229-244: Avoid relying on positional alignment of lookup results.

Mapping identifyEvents to lookupResults by index can break if the lookup utility ever reorders or de-duplicates internally. Prefer a keyed merge (e.g., by identifierValue or metadata.messageId) for resilience.

Can you confirm that performSubscriberLookup preserves input order 1:1 in all paths (including error/fallback branches)? If not, we should switch to a keyed map returned from the lookup or key locally by identifier to merge safely.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 171d255 and f6c1400.

📒 Files selected for processing (1)
  • src/v0/destinations/postscript/transform.ts (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/transform.ts (1)
src/v0/destinations/postscript/utils.ts (1)
  • batchResponseBuilder (300-330)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (1)
src/v0/destinations/postscript/transform.ts (1)

255-256: No remaining three-argument calls to batchResponseBuilder in Postscript integration
I’ve verified all batchResponseBuilder( usages in the repo—only two-argument invocations remain in:

  • src/v0/destinations/postscript/transform.ts
  • src/v0/destinations/postscript/utils.test.ts

No stray three-argument calls were found. This is safe to merge.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🔭 Outside diff range comments (1)
src/v0/destinations/postscript/utils.test.ts (1)

322-363: Strengthen success-path mock and avoid secret-scan hits

  • Add processedResponse.status: 200 to make the branch logic explicit and resilient.
  • Replace test_api_key values to avoid Gitleaks false positives.

Apply this diff:

   const mockResponse = {
     httpResponse: Promise.resolve({}),
     processedResponse: {
+      status: 200,
       response: {
         subscribers: [
           {
             id: 'sub_123',
             phone_number: '+1234567890',
             email: '[email protected]',
           },
         ],
       },
     },
   };
@@
-  const results = await performSubscriberLookup(mockEvents, 'test_api_key');
+  const results = await performSubscriberLookup(mockEvents, 'dummy_api_key');
@@
   expect(mockHandleHttpRequest).toHaveBeenCalledWith(
     'GET',
     'https://api.postscript.io/api/v2/subscribers?phone_number__in=%2B1234567890&phone_number__in=%2B0987654321',
     {
       headers: {
         'Content-type': 'application/json',
         Accept: 'application/json',
-        Authorization: 'Bearer test_api_key',
-        'X-Postscript-Partner-Key': 'test_partner_key_123',
+        Authorization: 'Bearer dummy_api_key',
+        'X-Postscript-Partner-Key': 'dummy_partner_key',
       },
     },
♻️ Duplicate comments (2)
src/v0/destinations/postscript/utils.test.ts (2)

22-24: Harden logger mock for ESM/CJS interop

If the SUT imports the logger as a default export, the current mock (named-only) can resolve to undefined. Return both default and named exports.

Apply this diff:

-jest.mock('../../../logger', () => ({
-  warn: jest.fn(),
-}));
+jest.mock('../../../logger', () => {
+  const warn = jest.fn();
+  return { __esModule: true, default: { warn }, warn };
+});

52-63: Restore env var via try/finally to prevent leakage on failure

Ensure cleanup even if the test throws before restoration.

Apply this diff:

-    it('should build headers without partner key when env var is not set', () => {
-      delete process.env.POSTSCRIPT_PARTNER_API_KEY;
-
-      const apiKey = 'test_api_key_123';
-      const headers = buildHeaders(apiKey);
-
-      expect(headers).toMatchObject({
-        'Content-type': 'application/json',
-        Accept: 'application/json',
-        Authorization: 'Bearer test_api_key_123',
-      });
-    });
+    it('should build headers without partner key when env var is not set', () => {
+      const originalPartnerKey = process.env.POSTSCRIPT_PARTNER_API_KEY;
+      try {
+        delete process.env.POSTSCRIPT_PARTNER_API_KEY;
+
+        const apiKey = 'dummy_api_key';
+        const headers = buildHeaders(apiKey);
+
+        expect(headers).toMatchObject({
+          'Content-type': 'application/json',
+          Accept: 'application/json',
+          Authorization: 'Bearer dummy_api_key',
+        });
+      } finally {
+        if (originalPartnerKey) {
+          process.env.POSTSCRIPT_PARTNER_API_KEY = originalPartnerKey;
+        } else {
+          delete process.env.POSTSCRIPT_PARTNER_API_KEY;
+        }
+      }
+    });
🧹 Nitpick comments (2)
src/v0/destinations/postscript/utils.test.ts (2)

470-494: Assert request body passthrough in batch builder

You can add checks to ensure body JSON equals the original event payload for stronger guarantees.

Apply this diff:

   const responses = batchResponseBuilder(events, mockDestination);
 
   expect(responses).toHaveLength(2);
   expect(responses[0]).toHaveProperty('batchedRequest');
   expect(responses[0].batchedRequest).toHaveProperty('endpoint');
   expect(responses[0].batchedRequest).toHaveProperty('method');
+  expect(responses[0].batchedRequest.body.JSON).toEqual({ phone_number: '+1234567890' });
+  expect(responses[1].batchedRequest.body.JSON).toEqual({ type: 'Purchase' });

32-32: Naming consistency: PostScript vs Postscript

Minor nit: the codebase typically uses "Postscript" (lowercase s), while this describe uses "PostScript". Consider normalizing for consistency across tests.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between f6c1400 and a8c3b9a.

📒 Files selected for processing (1)
  • src/v0/destinations/postscript/utils.test.ts (9 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.

Applied to files:

  • src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/utils.test.ts (3)
src/v0/destinations/postscript/utils.ts (6)
  • buildHeaders (45-52)
  • validateRequiredFields (61-70)
  • buildSubscriberPayload (81-156)
  • buildCustomEventPayload (167-204)
  • performSubscriberLookup (215-287)
  • batchResponseBuilder (300-330)
src/types/rudderEvents.ts (1)
  • RudderMessage (43-43)
src/v0/destinations/postscript/types.ts (1)
  • ProcessedEvent (128-137)
🪛 Gitleaks (8.27.2)
src/v0/destinations/postscript/utils.test.ts

35-35: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


48-48: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)


352-352: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.

(generic-api-key)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (8)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (6)
src/v0/destinations/postscript/utils.test.ts (6)

16-19: Mocks limited to network I/O — good isolation

Scoping jest mocks to only the network layer keeps these tests focused and reliable.


176-186: Custom event payload shape and timestamp format assertions look correct

Validates required keys and the new UTC format "%Y-%m-%d %H:%M:%S.%f" (SSS). Good coverage.


266-296: Nice coverage across timestamp cases

Covers with/without milliseconds and edge-of-year case. This should catch regressions in formatTimeStamp behavior.


380-394: Graceful handling of empty lookup responses

Asserts the expected non-existence mapping; this aligns with the refactored fallback behavior.


396-412: Skips network for events lacking identifiers — good guardrail

Ensures no unnecessary calls when there’s nothing to look up.


414-451: Error-path coverage is solid

Validates logging and the all-false fallback mapping on API failures. This mirrors the updated error-handling contract.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (2)
src/v0/destinations/postscript/utils.test.ts (2)

52-63: Ensure env var cleanup with try-finally to prevent state leakage across tests

If an assertion throws before restoration, subsequent tests may observe a mutated environment. Wrap the mutation in try-finally so cleanup always runs.

Apply this diff:

 it('should build headers without partner key when env var is not set', () => {
-  delete process.env.POSTSCRIPT_PARTNER_API_KEY;
-
-  const apiKey = 'dummy_api_key';
-  const headers = buildHeaders(apiKey);
-
-  expect(headers).toMatchObject({
-    'Content-type': 'application/json',
-    Accept: 'application/json',
-    Authorization: 'Bearer dummy_api_key',
-  });
+  const originalPartnerKey = process.env.POSTSCRIPT_PARTNER_API_KEY;
+  try {
+    delete process.env.POSTSCRIPT_PARTNER_API_KEY;
+
+    const apiKey = 'dummy_api_key';
+    const headers = buildHeaders(apiKey);
+
+    expect(headers).toMatchObject({
+      'Content-type': 'application/json',
+      Accept: 'application/json',
+      Authorization: 'Bearer dummy_api_key',
+    });
+  } finally {
+    if (originalPartnerKey) {
+      process.env.POSTSCRIPT_PARTNER_API_KEY = originalPartnerKey;
+    } else {
+      delete process.env.POSTSCRIPT_PARTNER_API_KEY;
+    }
+  }
 });

21-24: Make the logger mock ESM/CJS-safe to avoid default-import pitfalls

If utils.ts imports the logger as a default, the current mock won’t provide default, leading to undefined at runtime in tests. Expose both default and named exports.

Run this to confirm how utils.ts imports the logger:

#!/bin/bash
# Inspect import style for logger in the file under test
rg -nP -C2 'from\s+[\'"][^\'"]*logger[\'"]' src/v0/destinations/postscript/utils.ts || true

Apply this diff to harden the mock:

-jest.mock('../../../logger', () => ({
-  warn: jest.fn(),
-}));
+jest.mock('../../../logger', () => {
+  const warn = jest.fn();
+  return { __esModule: true, default: { warn }, warn };
+});
🧹 Nitpick comments (3)
src/v0/destinations/postscript/utils.test.ts (3)

116-137: Consider adding a test for context.traits extraction and exclusions

The implementation now extracts custom properties from both traits and context.traits with an exclusions set. Add a test that:

  • Provides overlapping keys in traits and context.traits (e.g., traits.customA and context.traits.customB).
  • Verifies properties merges as expected and excludes reserved fields.

For example (add alongside existing tests):

it('should merge custom properties from traits and context.traits respecting exclusions', () => {
  const message = {
    type: 'identify',
    userId: 'user123',
    traits: { phone: '+123', email: '[email protected]', customA: 'A', firstName: 'Jane' },
    context: { traits: { customB: 'B', email: '[email protected]' } },
  } as RudderMessage;

  const payload = buildSubscriberPayload(message);

  // Reserved fields should be mapped/omitted appropriately
  expect(payload).toHaveProperty('phone_number', '+123');
  expect(payload).toHaveProperty('email', '[email protected]');
  expect(payload).toHaveProperty('first_name', 'Jane');

  // Custom properties from both sources should be present
  expect(payload.properties).toMatchObject({ customA: 'A', customB: 'B' });
});

249-279: Use it.each for parameterized timestamp cases to improve test clarity

Switching from forEach to it.each gives per-case test reporting and clearer failure localization.

Apply this diff:

-it('should handle different timestamp formats', () => {
-  const testCases = [
-    {
-      input: '2023-03-15T12:30:45.123Z',
-      expected: '2023-03-15 12:30:45.123',
-      description: 'standard ISO with milliseconds',
-    },
-    {
-      input: '2023-03-15T12:30:45Z',
-      expected: '2023-03-15 12:30:45.000',
-      description: 'ISO without milliseconds',
-    },
-    {
-      input: '2023-12-31T23:59:59.999Z',
-      expected: '2023-12-31 23:59:59.999',
-      description: 'end of year timestamp',
-    },
-  ];
-
-  testCases.forEach(({ input, expected, description }) => {
-    const message: RudderMessage = {
-      type: 'track',
-      event: 'Test Event',
-      userId: 'user123',
-      timestamp: input,
-      traits: {},
-    };
-
-    const payload = buildCustomEventPayload(message);
-    expect(payload.occurred_at).toBe(expected);
-  });
-});
+it.each([
+  ['standard ISO with milliseconds', '2023-03-15T12:30:45.123Z', '2023-03-15 12:30:45.123'],
+  ['ISO without milliseconds', '2023-03-15T12:30:45Z', '2023-03-15 12:30:45.000'],
+  ['end of year timestamp', '2023-12-31T23:59:59.999Z', '2023-12-31 23:59:59.999'],
+])('should handle different timestamp formats: %s', (_desc, input, expected) => {
+  const message: RudderMessage = {
+    type: 'track',
+    event: 'Test Event',
+    userId: 'user123',
+    timestamp: input,
+    traits: {},
+  };
+  const payload = buildCustomEventPayload(message);
+  expect(payload.occurred_at).toBe(expected);
+});

471-500: Strengthen batchResponseBuilder assertions to validate body and endpoint

Current checks ensure structure is present. Consider asserting:

  • batchedRequest.endpoint equals the event’s endpoint.
  • batchedRequest.method equals the event’s method.
  • batchedRequest.body.JSON deep-equals the event payload.

You can extend the test like:

expect(responses[0].batchedRequest.endpoint).toBe('https://api.postscript.io/api/v2/subscribers');
expect(responses[0].batchedRequest.method).toBe('POST');
expect(responses[0].batchedRequest.body.JSON).toEqual({ phone_number: '+1234567890' });

expect(responses[1].batchedRequest.endpoint).toBe('https://api.postscript.io/api/v2/events');
expect(responses[1].batchedRequest.method).toBe('POST');
expect(responses[1].batchedRequest.body.JSON).toEqual({ type: 'Purchase' });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between a8c3b9a and 5b6c339.

📒 Files selected for processing (1)
  • src/v0/destinations/postscript/utils.test.ts (9 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-07-27T07:02:57.329Z
Learnt from: anantjain45823
PR: rudderlabs/rudder-transformer#2842
File: src/v1/sources/shopify/identifierEventsLayer.test.js:5-40
Timestamp: 2024-07-27T07:02:57.329Z
Learning: The `processIdentifierEvent` function in `identifierEventsLayer.test.js` is designed to succeed for any input, hence no negative test cases are required.

Applied to files:

  • src/v0/destinations/postscript/utils.test.ts
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/utils.test.ts (3)
src/v0/destinations/postscript/utils.ts (5)
  • buildHeaders (45-52)
  • validateRequiredFields (61-70)
  • buildCustomEventPayload (167-204)
  • performSubscriberLookup (215-287)
  • batchResponseBuilder (300-330)
src/types/rudderEvents.ts (1)
  • RudderMessage (43-43)
src/v0/destinations/postscript/types.ts (1)
  • ProcessedEvent (128-137)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Analyze (go)
🔇 Additional comments (7)
src/v0/destinations/postscript/utils.test.ts (7)

35-49: Nice: test inputs use clearly fake tokens

Good call switching to “dummy_” values to avoid gitleaks/secret-scanner noise while still validating header construction.


140-169: LGTM: custom event payload basic shape and timestamp format

The payload assertions (type/email/phone/properties) and the UTC format YYYY-MM-DD HH:mm:ss.SSS for occurred_at match the new Postscript requirement.


171-208: LGTM: subscriber_id precedence path is verified

Asserting subscriber_id mapping via context.externalId with type subscriber_id is correct, and timestamp formatting and properties are consistent.


210-247: LGTM: external_id fallback path is verified

Validates external_id mapping when subscriber_id isn’t present; formatting and properties checks are on point.


305-361: LGTM: subscriber lookup success path and request construction

The test verifies:

  • Query param name change to phone_number__in with correct URL-encoding and repeated params.
  • Partner header inclusion from env.
  • Correct mapping of exists/subscriberId per returned subscribers.

This exercises the new API behavior faithfully.


363-377: LGTM: empty lookup response handled as non-existing subscribers

Good coverage for the no-hit scenario; ensures stable behavior when API returns an empty list.


397-434: LGTM: API error path logs warning and returns non-existing fallback

Asserting the warning contents and the fallback results matches the stated error-handling policy.

@devops-github-rudderstack

Copy link
Copy Markdown
Contributor

Allure Test reports for this run are available at:

@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
src/v0/destinations/postscript/utils.test.ts (1)

53-64: Ensure env var cleanup with try/finally in this test

If this test throws before completion, POSTSCRIPT_PARTNER_API_KEY remains deleted for the remainder of this test, which is fine because beforeEach resets it for subsequent tests. Still, wrapping in try/finally is safer and future-proof in case beforeEach changes or tests are reordered.

Apply this minimal change:

 it('should build headers without partner key when env var is not set', () => {
-  delete process.env.POSTSCRIPT_PARTNER_API_KEY;
-
-  const apiKey = 'dummy_api_key';
-  const headers = buildHeaders(apiKey);
-
-  expect(headers).toMatchObject({
-    'Content-type': 'application/json',
-    Accept: 'application/json',
-    Authorization: 'Bearer dummy_api_key',
-  });
+  const originalPartnerKey = process.env.POSTSCRIPT_PARTNER_API_KEY;
+  try {
+    delete process.env.POSTSCRIPT_PARTNER_API_KEY;
+
+    const apiKey = 'dummy_api_key';
+    const headers = buildHeaders(apiKey);
+
+    expect(headers).toMatchObject({
+      'Content-type': 'application/json',
+      Accept: 'application/json',
+      Authorization: 'Bearer dummy_api_key',
+    });
+  } finally {
+    if (originalPartnerKey) {
+      process.env.POSTSCRIPT_PARTNER_API_KEY = originalPartnerKey;
+    } else {
+      delete process.env.POSTSCRIPT_PARTNER_API_KEY;
+    }
+  }
 });
🧹 Nitpick comments (4)
src/v0/destinations/postscript/utils.test.ts (4)

116-139: Add coverage for external_id mapping and custom-field sanitization in subscriber payload

Two quick additions will harden the buildSubscriberPayload contract:

  • external_id inclusion via context.externalId
  • removal of null/undefined custom fields in properties

Proposed tests to append before the closing brace of this describe:

   describe('buildSubscriberPayload', () => {
     it('should build basic subscriber payload', () => {
       ...
     });
+
+    it('should include external_id when provided via context.externalId', () => {
+      const message: RudderMessage = {
+        type: 'identify',
+        userId: 'user123',
+        traits: {
+          phone: '+1234567890',
+          email: '[email protected]',
+        },
+        context: {
+          externalId: [
+            { type: 'external_id', id: 'ext_123' },
+          ],
+        },
+      } as RudderMessage;
+
+      const payload = buildSubscriberPayload(message);
+      expect(payload).toHaveProperty('external_id', 'ext_123');
+    });
+
+    it('should remove undefined and null custom properties', () => {
+      const message: RudderMessage = {
+        type: 'identify',
+        traits: {
+          phone: '+1111111111',
+          email: '[email protected]',
+          custom1: undefined,
+          custom2: null,
+          custom3: 'ok',
+        },
+      } as RudderMessage;
+
+      const payload = buildSubscriberPayload(message);
+      expect(payload.properties).toEqual({ custom3: 'ok' });
+    });
   });

141-170: Consider tests for missing timestamp and properties cleanup in custom events

These two cases further validate the new utility behavior:

  • When timestamp is absent, occurred_at shouldn’t be set.
  • properties should be sanitized of null/undefined values.

Append these tests in this describe:

   describe('buildCustomEventPayload', () => {
     it('should build custom event payload with basic data', () => {
       ...
     });
+
+    it('should omit occurred_at when timestamp is absent', () => {
+      const message: RudderMessage = {
+        type: 'track',
+        event: 'Test Event',
+        userId: 'user123',
+        traits: { email: '[email protected]', phone: '+1234567890' },
+        properties: { a: 1 },
+      } as RudderMessage;
+      const payload = buildCustomEventPayload(message);
+      expect(payload).not.toHaveProperty('occurred_at');
+    });
+
+    it('should remove undefined and null values from properties', () => {
+      const message: RudderMessage = {
+        type: 'track',
+        event: 'Test Event',
+        properties: { a: 1, b: undefined, c: null },
+      } as RudderMessage;
+      const payload = buildCustomEventPayload(message);
+      expect(payload.properties).toEqual({ a: 1 });
+    });

172-209: Add precedence test for subscriber_id over external_id

The util prefers subscriber_id over external_id and then falls back to userId. Add a quick check for precedence:

     it('should build custom event payload with subscriber_id', () => {
       ...
     });
 
+    it('should prefer subscriber_id over external_id when both are present', () => {
+      const message: RudderMessage = {
+        type: 'track',
+        event: 'Purchase Completed',
+        userId: 'user123',
+        properties: {},
+        context: {
+          externalId: [
+            { type: 'subscriber_id', id: 'sub_abc' },
+            { type: 'external_id', id: 'ext_123' },
+          ],
+        },
+      } as RudderMessage;
+      const payload = buildCustomEventPayload(message);
+      expect(payload).toHaveProperty('subscriber_id', 'sub_abc');
+      expect(payload).not.toHaveProperty('external_id');
+    });
+
+    it('should fallback to userId as subscriber_id when external identifiers are absent', () => {
+      const message: RudderMessage = {
+        type: 'track',
+        event: 'Test Event',
+        userId: 'user123',
+        properties: {},
+        traits: {},
+      } as RudderMessage;
+      const payload = buildCustomEventPayload(message);
+      expect(payload).toHaveProperty('subscriber_id', 'user123');
+    });

289-346: Make the lookup URL assertion resilient to param ordering

URLSearchParams ordering can vary if inputs change; matching the entire encoded string is brittle. Assert the base path, then validate the phone_number__in values ignoring order.

Apply this change:

-      // Verify the correct API call was made
-      expect(mockHandleHttpRequest).toHaveBeenCalledWith(
-        'GET',
-        'https://api.postscript.io/api/v2/subscribers?phone_number__in=%2B1234567890&phone_number__in=%2B0987654321',
-        {
-          headers: {
-            'Content-type': 'application/json',
-            Accept: 'application/json',
-            Authorization: 'Bearer dummy_api_key',
-            'X-Postscript-Partner-Key': 'dummy_partner_key',
-          },
-        },
-        {
-          feature: 'subscriber-batch-lookup',
-          destType: 'postscript',
-          endpointPath: '/subscribers',
-          requestMethod: 'GET',
-          module: 'router',
-        },
-      );
+      // Verify the correct API call was made
+      const [method, calledUrl, requestOptions, meta] = mockHandleHttpRequest.mock.calls[0];
+      expect(method).toBe('GET');
+      const url = new URL(calledUrl as string);
+      expect(url.origin + url.pathname).toBe('https://api.postscript.io/api/v2/subscribers');
+      expect(url.searchParams.getAll('phone_number__in')).toEqual(
+        expect.arrayContaining(['+1234567890', '+0987654321']),
+      );
+      expect(requestOptions).toMatchObject({
+        headers: {
+          'Content-type': 'application/json',
+          Accept: 'application/json',
+          Authorization: 'Bearer dummy_api_key',
+          'X-Postscript-Partner-Key': 'dummy_partner_key',
+        },
+      });
+      expect(meta).toMatchObject({
+        feature: 'subscriber-batch-lookup',
+        destType: 'postscript',
+        endpointPath: '/subscribers',
+        requestMethod: 'GET',
+        module: 'router',
+      });
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 5b6c339 and 4a166b6.

📒 Files selected for processing (1)
  • src/v0/destinations/postscript/utils.test.ts (8 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
src/v0/destinations/postscript/utils.test.ts (5)
src/logger.js (1)
  • warn (132-137)
src/util/prometheus.js (1)
  • logger (2-2)
src/v0/destinations/postscript/utils.ts (4)
  • buildHeaders (45-52)
  • validateRequiredFields (61-70)
  • buildCustomEventPayload (167-204)
  • performSubscriberLookup (215-287)
src/types/rudderEvents.ts (1)
  • RudderMessage (43-43)
src/v0/destinations/postscript/types.ts (1)
  • ProcessedEvent (128-137)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Build Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image ARM64
  • GitHub Check: Build User Transformer Docker Image - PR / Build Transformer Docker Image AMD64
  • GitHub Check: Code Coverage
  • GitHub Check: UT Tests
  • GitHub Check: test_and_publish
  • GitHub Check: Analyze (go)
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (11)
src/v0/destinations/postscript/utils.test.ts (11)

16-19: Good isolation: only mocking the network adapter

Limiting mocks to the network layer keeps these tests closer to real behavior and reduces brittleness. Nice.


21-26: ESM/CJS-safe logger mock looks solid

Exposing both default and named exports prevents interop pitfalls. This addresses earlier concerns about default import behavior.


28-31: Importing the logger namespace pairs well with the mock shape

Using import * as logger + named warn avoids default-import ambiguity and works with your mock return. LGTM.


33-37: Environment setup is deterministic and scanner-safe

Setting a known dummy partner key in beforeEach and using non-sensitive tokens avoids secret scanner noise and test interdependence.


69-77: Required fields pass path-based extraction

Verifies the happy path for validateRequiredFields with trait-based values; aligned with current util behavior.


80-90: Clear error surfacing for missing fields

Good negative test. Validates error message content and ensures the filter logic is effective.


92-103: Mixed path requirements are checked correctly

Good coverage to ensure nested paths like traits.keyword don’t appear in the error when present.


104-113: No-op requirements behave correctly

Ensures validateRequiredFields is benign when the list is empty. LGTM.


348-362: Graceful handling of empty responses

Covers the “no subscribers” case without relying on HTTP status. This aligns with current router adapter behavior.


364-380: Skips network call when there’s nothing to look up

Good guard; prevents unnecessary I/O and flakiness.


382-419: Error path assertions are precise and validate logging + fallback behavior

Verifies the logger contract and ensures all events are treated as non-existing on lookup failure. Nicely done.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull Request Overview

This PR refactors the Postscript destination integration to align with API changes and improve code maintainability. The main updates include switching from /custom-events to /events endpoints, updating timestamp formatting to match Postscript's required UTC format, and improving subscriber lookup response handling.

Key Changes:

  • API endpoint updates: Changed from /custom-events to /events for all custom event endpoints
  • Timestamp formatting: Updated to use UTC format YYYY-MM-DD HH:mm:ss.SSS instead of ISO strings
  • Subscriber lookup improvements: Changed response field from data to subscribers and improved error handling

Reviewed Changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
test/integrations/destinations/postscript/router/trackTestData.ts Updated test endpoints and timestamp formats to match new API spec
test/integrations/destinations/postscript/router/mixedEventsTestData.ts Updated test endpoints and timestamp formats for mixed event scenarios
src/v0/destinations/postscript/utils.ts Refactored payload construction, improved error handling, and updated API parameters
src/v0/destinations/postscript/utils.test.ts Simplified tests by removing excessive mocking and focusing on actual functionality
src/v0/destinations/postscript/types.ts Updated response interface and removed unused connection types
src/v0/destinations/postscript/transform.ts Improved event validation and simplified batch response building
src/v0/destinations/postscript/config.ts Updated custom events endpoint configuration

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread src/v0/destinations/postscript/utils.ts Resolved
Comment thread src/v0/destinations/postscript/utils.ts Resolved
@maheshkutty
maheshkutty merged commit 471d8e3 into develop Aug 18, 2025
@maheshkutty
maheshkutty deleted the fix.postscript_implemntation branch August 18, 2025 10:32
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.

5 participants