Skip to content

chore: migrate customerio to typescript - #5299

Merged
maheshkutty merged 2 commits into
developfrom
feature/int-6568-customerio-vdm-v2-migrate-transformer-from-javascript-to
Jun 17, 2026
Merged

maheshkutty merged 2 commits into
developfrom
feature/int-6568-customerio-vdm-v2-migrate-transformer-from-javascript-to

Conversation

@maheshkutty

Copy link
Copy Markdown
Contributor

What are the changes introduced in this PR?

Used the memory bank migrate customerio to typescript implementation

What is the related Linear task?

Resolves INT-6568

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 a review from a team as a code owner June 17, 2026 07:53
@coderabbitai

coderabbitai Bot commented Jun 17, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key: "auto_resolve_threads"
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • 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

Summary by CodeRabbit

  • Bug Fixes
    • Updated Customer.io EU datacenter routing to ensure consistent and reliable behavior.

Walkthrough

The CustomerIO destination module (config.ts, util.ts, transform.ts) is migrated from CommonJS to ES modules. A new types.ts file introduces a Zod-backed destination config schema and typed payload, batching, and response shapes. TypeScript annotations are added across helper and response builder functions. The EU datacenter routing condition drops the datacenterEU boolean fallback. Tests are updated to match.

Changes

CustomerIO ESM Migration and TypeScript Typing

Layer / File(s) Summary
New types.ts: Zod config schema and all payload/response types
src/v0/destinations/customerio/types.ts
Introduces CustomerIODestinationConfigSchema (Zod), all raw API payload shapes (identify, merge, track, device, object), union CustomerIOPayload, CustomerIORequestBody, batching types (CustomerIOBatchedRequest, CustomerIOBatchResponse), and internal processing types (EndpointDetails, ResponseDetails, CustomerIOSuccessfulEvent).
config.ts ESM migration and util.ts typed helper functions
src/v0/destinations/customerio/config.ts, src/v0/destinations/customerio/util.ts
config.ts replaces require/module.exports with ES import/export. util.ts imports are migrated and core helpers (getEndpointDetails, encodePathParameter, getSizeInBytes, getEventChunks) gain TypeScript parameter and return type annotations.
util.ts: typed response builders and ESM export
src/v0/destinations/customerio/util.ts
identifyResponseBuilder, aliasResponseBuilder, groupResponseBuilder, and defaultResponseBuilder receive explicit ResponseDetails return types and typed rawPayload construction. Module export switches to ES named exports.
transform.ts: ESM migration, typing, and datacenterEU removal
src/v0/destinations/customerio/transform.ts
All imports converted to ES module form with types from ./types. EU routing condition narrowed to datacenter === 'EU' only, dropping the datacenterEU boolean fallback. Accumulator variables in batchEvents and processRouterDest are explicitly typed. Public export converted to export { process, processRouterDest }.
util.test.ts: import and fixture updates
src/v0/destinations/customerio/util.test.ts
Test imports migrated to ES module form. datacenterEU: true removed from isdeviceRelatedEventName fixtures. groupResponseBuilder call drops the unused second argument. catch clauses typed as error: any. Non-null assertion added on endpointDetails in defaultResponseBuilder assertion.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • arpl
  • ItsSudip
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title 'chore: migrate customerio to typescript' clearly and accurately describes the main objective of the PR, which is a TypeScript migration of the customerio destination module.
Description check ✅ Passed The description covers the core requirements including what changes were made, the related Linear task, and acknowledges that no breaking changes are being introduced. However, several developer checklist items remain unchecked, suggesting incomplete preparation for review.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/int-6568-customerio-vdm-v2-migrate-transformer-from-javascript-to

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Jun 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 92.65%. Comparing base (d8363b4) to head (a4dfaef).
⚠️ Report is 3 commits behind head on develop.

Additional details and impacted files
@@           Coverage Diff            @@
##           develop    #5299   +/-   ##
========================================
  Coverage    92.64%   92.65%           
========================================
  Files          690      690           
  Lines        37586    37602   +16     
  Branches      8799     8800    +1     
========================================
+ Hits         34823    34839   +16     
  Misses        2535     2535           
  Partials       228      228           

☔ View full report in Codecov by Harness.
📢 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.

@shekhar-rudder shekhar-rudder left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Clean JS→TS migration; CI is green and I found no correctness issues. One question on a config-schema field.

Comment thread src/v0/destinations/customerio/types.ts Resolved
🔒 Scanned for secrets using gitleaks 8.30.1

@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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
src/v0/destinations/customerio/util.ts (1)

85-95: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Keep the current event’s bytes when rolling over batches.

size already includes objSize before the rollover, then gets reset before the current event is added. That can let the next chunk exceed the 500 KB guard and can emit an empty chunk when the first event crosses the limit.

Proposed fix
   groupEvents.forEach((events) => {
     const objSize = getSizeInBytes(events);
-    size += objSize;
-    if (batchedData.length === MAX_BATCH_SIZE || size > 500000) {
+    const shouldFlush = batchedData.length === MAX_BATCH_SIZE || size + objSize > 500000;
+    if (batchedData.length > 0 && shouldFlush) {
       eventChunks.push({ data: batchedData, metadata });
       batchedData = [];
       metadata = [];
       size = 0;
     }
     metadata.push(events.metadata);
     batchedData.push(events.message.body.JSON);
+    size += objSize;
   });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/v0/destinations/customerio/util.ts` around lines 85 - 95, In the
groupEvents.forEach loop, when the batch size limit is exceeded and the batch
rolls over, the size variable is reset to 0 after pushing the current
batchedData to eventChunks. However, the current event's bytes (objSize) have
already been added to size before the rollover check, so after resetting the
batch arrays, you need to preserve objSize by setting size equal to objSize
instead of setting it to 0. This ensures the next chunk correctly accounts for
the current event's bytes and prevents subsequent chunks from exceeding the
500KB limit.
src/v0/destinations/customerio/transform.ts (1)

168-175: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve the EU endpoint when rebuilding group batch requests.

processSingleMessage rewrites EU endpoints at Lines 124-126, but this batch reconstruction discards that transformed endpoint and always uses the default track.customer.io object endpoint. EU group batches can be routed to the US host.

Proposed fix
       const request = defaultRequestConfig();
-      request.endpoint = endpointDetails.endpoint;
-      request.endpointPath = endpointDetails.path;
+      request.endpoint = message.endpoint || endpointDetails.endpoint;
+      request.endpointPath = message.endpointPath || endpointDetails.path;
       request.headers = { ...headers, 'Content-Type': JSON_MIME_TYPE };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/v0/destinations/customerio/transform.ts` around lines 168 - 175, The
batch request reconstruction in the code block (where request.endpoint is set
from endpointDetails.endpoint) is not preserving the EU endpoint transformation
that was applied earlier in processSingleMessage at lines 124-126. When
defaultRequestConfig() is called and the endpoint is set from endpointDetails,
it defaults to the US endpoint instead of maintaining the EU endpoint if one was
determined. You need to apply the same EU endpoint logic that exists in
processSingleMessage to this batch request construction so that if an EU
endpoint was previously set, it is preserved in the batch request endpoint
assignment.
src/v0/destinations/customerio/util.test.ts (1)

121-143: ⚠️ Potential issue | 🟡 Minor

Refactor exception assertions to use expect().toThrow() to prevent silent test failures.

These three tests check that identifyResponseBuilder throws specific errors, but the current try/catch pattern allows the test to pass silently if the function stops throwing. If no exception is thrown, the catch block never executes and no assertion runs. Use Jest's expect().toThrow() instead.

Additionally, the first two tests have identical descriptions; consider making them more distinct for clarity during debugging.

Proposed fix
   it('No Identifier to send for Identify Call', async () => {
     let expectedOutput = 'userId or email is not present';
-    try {
-      identifyResponseBuilder(null, getIdentifyTestMessage());
-    } catch (error: any) {
-      expect(error.message).toEqual(expectedOutput);
-    }
+    expect(() => identifyResponseBuilder(null, getIdentifyTestMessage())).toThrow(expectedOutput);
   });
   it('No Identifier to send for Identify Call', async () => {
     let expectedOutput = 'userId or email is not present';
-    try {
-      identifyResponseBuilder('', getIdentifyTestMessage());
-    } catch (error: any) {
-      expect(error.message).toEqual(expectedOutput);
-    }
+    expect(() => identifyResponseBuilder('', getIdentifyTestMessage())).toThrow(expectedOutput);
   });
   it('Should throw error for null userId before encoding', async () => {
     let expectedOutput = 'userId or email is not present';
-    try {
-      identifyResponseBuilder(null, getIdentifyTestMessage());
-    } catch (error: any) {
-      expect(error.message).toEqual(expectedOutput);
-    }
+    expect(() => identifyResponseBuilder(null, getIdentifyTestMessage())).toThrow(expectedOutput);
   });
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/v0/destinations/customerio/util.test.ts` around lines 121 - 143, The
three test cases for identifyResponseBuilder are using try/catch blocks to
verify exceptions, which can silently pass if the function stops throwing.
Replace the try/catch pattern with Jest's expect().toThrow() method by wrapping
the identifyResponseBuilder calls in arrow functions within the expect
assertion. Additionally, the first two tests have identical descriptions ('No
Identifier to send for Identify Call'); rename them to be distinct - the first
testing null userId and the second testing empty string userId - so they are
clear during debugging.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/v0/destinations/customerio/transform.ts`:
- Around line 168-175: The batch request reconstruction in the code block (where
request.endpoint is set from endpointDetails.endpoint) is not preserving the EU
endpoint transformation that was applied earlier in processSingleMessage at
lines 124-126. When defaultRequestConfig() is called and the endpoint is set
from endpointDetails, it defaults to the US endpoint instead of maintaining the
EU endpoint if one was determined. You need to apply the same EU endpoint logic
that exists in processSingleMessage to this batch request construction so that
if an EU endpoint was previously set, it is preserved in the batch request
endpoint assignment.

In `@src/v0/destinations/customerio/util.test.ts`:
- Around line 121-143: The three test cases for identifyResponseBuilder are
using try/catch blocks to verify exceptions, which can silently pass if the
function stops throwing. Replace the try/catch pattern with Jest's
expect().toThrow() method by wrapping the identifyResponseBuilder calls in arrow
functions within the expect assertion. Additionally, the first two tests have
identical descriptions ('No Identifier to send for Identify Call'); rename them
to be distinct - the first testing null userId and the second testing empty
string userId - so they are clear during debugging.

In `@src/v0/destinations/customerio/util.ts`:
- Around line 85-95: In the groupEvents.forEach loop, when the batch size limit
is exceeded and the batch rolls over, the size variable is reset to 0 after
pushing the current batchedData to eventChunks. However, the current event's
bytes (objSize) have already been added to size before the rollover check, so
after resetting the batch arrays, you need to preserve objSize by setting size
equal to objSize instead of setting it to 0. This ensures the next chunk
correctly accounts for the current event's bytes and prevents subsequent chunks
from exceeding the 500KB limit.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 12541bb1-8f8d-40f7-8ec3-ece9ec5f7b00

📥 Commits

Reviewing files that changed from the base of the PR and between d8363b4 and a4dfaef.

⛔ Files ignored due to path filters (2)
  • test/integrations/destinations/customerio/processor/data.ts is excluded by !**/test/**
  • test/integrations/destinations/customerio/router/data.ts is excluded by !**/test/**
📒 Files selected for processing (5)
  • src/v0/destinations/customerio/config.ts
  • src/v0/destinations/customerio/transform.ts
  • src/v0/destinations/customerio/types.ts
  • src/v0/destinations/customerio/util.test.ts
  • src/v0/destinations/customerio/util.ts

@sonarqubecloud

Copy link
Copy Markdown

@maheshkutty
maheshkutty merged commit cd1ae3f into develop Jun 17, 2026
34 checks passed
@maheshkutty
maheshkutty deleted the feature/int-6568-customerio-vdm-v2-migrate-transformer-from-javascript-to branch June 17, 2026 14:57
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