fix: preserve Temporal values in offline transactions #1579
main fromrefs/pull/1579/head·opened 🎯 Changes#
Preserves TC39 Temporal values when offline transactions are serialized to and restored from the outbox.
Previously, Temporal objects such as Temporal.PlainDate and Temporal.Instant could round-trip as {} because they do not expose enumerable fields. This updates the offline transaction serializer to store Temporal values with explicit type markers and restore them through globalThis.Temporal, covering mutation data and transaction metadata.
Adds serializer tests for Temporal values in mutation modified / original / changes data and transaction metadata.
✅ Checklist#
- I have tested this code locally with
pnpm test.
🚀 Release Impact#
- This change affects published code, and I have generated a changeset.
- This change is docs/CI/dev-only (no release).
Summary by CodeRabbit#
Bug Fixes
- Offline transactions now preserve Temporal date/time values when serialized and restored (including transaction metadata).
New Features
- Optional Temporal support can be supplied at runtime; missing support is surfaced as an explicit error so callers can handle it.
Tests
- Added tests covering Temporal serialization/deserialization across mutations and transaction metadata.
Chores
- Added release entry and a development polyfill dependency.
- 1
Actionable comments posted: 2
🤖 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. Inline comments: In `@packages/offline-transactions/src/outbox/TransactionSerializer.ts`: - Around line 50-65: TransactionSerializer currently reaches for globalThis.Temporal via getTemporalConstructor (used by deserializeValue), causing silent failures in OutboxManager.get; refactor to make the Temporal dependency explicit by adding an injectable Temporal namespace or a mapping of TemporalConstructorName->TemporalConstructor to TransactionSerializer (e.g., a constructor parameter on TransactionSerializer) and update getTemporalConstructor to use that injected object instead of globalThis.Temporal; also update OutboxManager.get to either construct TransactionSerializer with the injected Temporal (propagate the dependency from wherever OutboxManager is created) or, if no Temporal is supplied, throw a clear runtime error (fail fast) rather than swallowing the deserialization error and returning null so persisted outbox items remain readable. In `@packages/offline-transactions/tests/TransactionSerializer.test.ts`: - Around line 323-345: The test currently seeds changes.temporalValues but only asserts deserialized.mutations[0].modified and .original; add assertions that inspect deserialized.changes.temporalValues (the same path used when creating the transaction) and verify each entry's Symbol.toStringTag and toString() match the original temporalValues entries; locate the test around serializer.serialize/serializer.deserialize and the transaction object creation and add checks analogous to the modified/original assertions but against deserialized.changes.temporalValues to prevent regressions in the changes branch.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
60e28cff-5dc9-4353-a259-c675f299e6c9📥 Commits
Reviewing files that changed from the base of the PR and between 4d1abded3e5bdec16457deb7486e28b6a228c670 and 993bb129ae75139371edc5da81d6d208511f1bcb.
⛔ Files ignored due to path filters (1)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yaml
📒 Files selected for processing (4)
.changeset/quiet-temporal-dragons.mdpackages/offline-transactions/package.jsonpackages/offline-transactions/src/outbox/TransactionSerializer.tspackages/offline-transactions/tests/TransactionSerializer.test.ts
@@ -8,0 +45,21 @@45+46+ const tag = (value as Record<symbol, unknown>)[Symbol.toStringTag]47+ return typeof tag === `string` && isTemporalType(tag)48+}49+50+function getTemporalConstructor(type: TemporalType): TemporalConstructor {51+ const temporalGlobal = (52+ globalThis as {53+ Temporal?: Partial<Record<TemporalConstructorName, TemporalConstructor>>54+ }55+ ).Temporal56+ const constructorName = temporalConstructors[type]57+ const constructor = temporalGlobal?.[constructorName]58+59+ if (!constructor) {60+ throw new Error(61+ `Failed to deserialize Temporal marker: globalThis.Temporal.${constructorName} is not available`,62+ )63+ }64+65+ return constructor⚠️ Potential issue | 🟠 Major
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "Non-test Temporal global setup:" rg -n -C2 --glob '!**/*.test.*' --glob '!**/__tests__/**' \ 'globalThis\.Temporal|window\.Temporal|global\.Temporal|temporal-polyfill|`@js-temporal/polyfill`' echo echo "Serializer / outbox restore paths:" rg -n -C2 'new\s+TransactionSerializer|deserialize\(|OutboxManager'Repository: TanStack/db
Length of output: 16228
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "=== TransactionSerializer.ts (getTemporalConstructor + deserialize branch) ===" sed -n '1,220p' packages/offline-transactions/src/outbox/TransactionSerializer.ts | nl -ba | sed -n '40,170p' echo echo "=== OutboxManager.ts (deserialize error handling / null) ===" sed -n '1,140p' packages/offline-transactions/src/outbox/OutboxManager.ts | nl -ba | sed -n '1,140p' echo echo "=== offline-transactions src entrypoints (any Temporal global setup?) ===" rg -n --glob 'packages/offline-transactions/src/**/*' 'globalThis\.Temporal|window\.Temporal|global\.Temporal' || trueRepository: TanStack/db
Length of output: 195
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "=== TransactionSerializer.ts (getTemporalConstructor + deserialize branch) ===" sed -n '1,220p' packages/offline-transactions/src/outbox/TransactionSerializer.ts | cat -n | sed -n '40,170p' echo echo "=== OutboxManager.ts (deserialize error handling / null) ===" sed -n '1,160p' packages/offline-transactions/src/outbox/OutboxManager.ts | cat -n | sed -n '1,120p' echo echo "=== offline-transactions src entrypoints (any Temporal global setup?) ===" rg -n --glob 'packages/offline-transactions/src/**/*' 'globalThis\.Temporal|window\.Temporal|global\.Temporal' || trueRepository: TanStack/db
Length of output: 10102
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "=== Search non-test Temporal installation / polyfill usage ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' \ '`@js-temporal/polyfill`|temporal-polyfill|Temporal\s*=|globalThis\.Temporal\s*=' \ packages/offline-transactions/src packages/db packages/db-ivm packages/electron-db-sqlite-persistence/src || true echo echo "=== Search for 'Temporal' global writes anywhere in repo non-test ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' \ 'globalThis\.Temporal\s*=|window\.Temporal\s*=|global\.Temporal\s*=' . || trueRepository: TanStack/db
Length of output: 317
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "=== Repo-wide non-test usage of temporal polyfills/imports ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' \ '`@js-temporal/polyfill`|temporal-polyfill' . echo echo "=== Repo-wide non-test global assignment ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' \ 'globalThis\.Temporal\s*=|window\.Temporal\s*=|global\.Temporal\s*=' . echo echo "=== Repo-wide non-test direct reads (any other getTemporalConstructor-like code) ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' \ 'globalThis\.Temporal' .Repository: TanStack/db
Length of output: 620
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "=== TransactionSerializer.ts line count ===" wc -l packages/offline-transactions/src/outbox/TransactionSerializer.ts echo echo "=== TransactionSerializer.ts: temporalConstructors / marker handling ===" rg -n 'temporalConstructors|TemporalType|isTemporal|deserializeValue|__type.*Temporal|Symbol\.toStringTag|globalThis\.Temporal' packages/offline-transactions/src/outbox/TransactionSerializer.ts echo echo "=== TransactionSerializer.ts: inspect around deserializeValue ===" # show the block containing deserializeValue and any temporal handling nearby rg -n 'deserializeValue\(' packages/offline-transactions/src/outbox/TransactionSerializer.ts start=$(rg -n 'deserializeValue\(' packages/offline-transactions/src/outbox/TransactionSerializer.ts | head -n1 | cut -d: -f1) from=$((start-60)) to=$((start+140)) sed -n "${from},${to}p" packages/offline-transactions/src/outbox/TransactionSerializer.ts | cat -n | sed -n '1,220p' echo echo "=== Repo-wide non-test Temporal usage (imports + new Temporal.* patterns) ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' '`@js-temporal/polyfill`|temporal-spec|Temporal\.' packages/offline-transactions/src packages/db packages/db-ivm packages/electron-db-sqlite-persistence/src || true echo echo "=== Repo-wide non-test polyfill initialization patterns ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' '(import.*temporal-polyfill)|(require.*temporal-polyfill)|(import.*`@js-temporal/polyfill`)|(require.*`@js-temporal/polyfill`)' . || trueRepository: TanStack/db
Length of output: 13951
🏁 Script executed:
#!/bin/bash set -euo pipefail echo "=== Imports of temporal polyfills / Temporal in non-test code ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' \ "(from ['\"](`@js-temporal/polyfill`|temporal-polyfill)['\"]|import ['\"](`@js-temporal/polyfill`|temporal-polyfill)['\"]|require\(['\"](`@js-temporal/polyfill`|temporal-polyfill)['\"]\))" . echo echo "=== Any non-test code that imports/declares Temporal symbol ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' \ "(import .*\\bTemporal\\b|import\\s*\\{[^}]*\\bTemporal\\b|const\\s*\\{[^}]*\\bTemporal\\b|require\\(['\"][^'\"]*['\"]\\))" packages/db packages/offline-transactions packages/db-ivm || true echo echo "=== Inspect packages/db/src/utils.ts around Temporal.* references ===" sed -n '180,260p' packages/db/src/utils.ts | cat -nRepository: TanStack/db
Length of output: 121
🏁 Script executed:
#!/bin/bash set -u echo "=== Any non-test code that imports temporal polyfill packages ===" rg -n --glob '!**/*.test.*' --glob '!**/__tests__/**' \ "(`@js-temporal/polyfill`|temporal-polyfill)" packages/db packages/db-ivm packages/offline-transactions || true echo echo "=== Inspect packages/db/src/utils.ts around Temporal.* references ===" sed -n '180,260p' packages/db/src/utils.ts | cat -nRepository: TanStack/db
Length of output: 2484
Make the Temporal namespace dependency explicit.
TransactionSerializercan serialize Temporal values, butdeserializeValuerelies onglobalThis.TemporalviagetTemporalConstructor()and throws if it’s missing;OutboxManager.get()then swallows that failure and returnsnull, making persisted outbox items unreadable after restart. The repo showstemporal-polyfillonly as a dependency (no non-test code wiring/initializingglobalThis.Temporal). Inject the Temporal constructors/namespace intoTransactionSerializer/OutboxManager(or fail fast with a documented runtime contract) instead of relying on ambient global state.🤖 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 `@packages/offline-transactions/src/outbox/TransactionSerializer.ts` around lines 50 - 65, TransactionSerializer currently reaches for globalThis.Temporal via getTemporalConstructor (used by deserializeValue), causing silent failures in OutboxManager.get; refactor to make the Temporal dependency explicit by adding an injectable Temporal namespace or a mapping of TemporalConstructorName->TemporalConstructor to TransactionSerializer (e.g., a constructor parameter on TransactionSerializer) and update getTemporalConstructor to use that injected object instead of globalThis.Temporal; also update OutboxManager.get to either construct TransactionSerializer with the injected Temporal (propagate the dependency from wherever OutboxManager is created) or, if no Temporal is supplied, throw a clear runtime error (fail fast) rather than swallowing the deserialization error and returning null so persisted outbox items remain readable.Source: Coding guidelines
@@ -237,0 +325,21 @@325+ },326+ })327+328+ const serialized = serializer.serialize(transaction)329+ const deserialized = serializer.deserialize(serialized)330+331+ const restoredValues = deserialized.mutations[0]!.modified.temporalValues332+ for (const [key, originalValue] of Object.entries(temporalValues)) {333+ const restoredValue = restoredValues[key]334+ expect(restoredValue[Symbol.toStringTag]).toBe(335+ originalValue[Symbol.toStringTag],336+ )337+ expect(restoredValue.toString()).toBe(originalValue.toString())338+ }339+340+ const restoredOriginal = deserialized.mutations[0]!.original.dueDate341+ expect(restoredOriginal[Symbol.toStringTag]).toBe(`Temporal.PlainDate`)342+ expect(restoredOriginal.toString()).toBe(343+ temporalValues.plainDate.toString(),344+ )345+ })⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Assert the
changespath in this regression test.This seeds
changes.temporalValuesbut only verifiesmodifiedandoriginal, so a regression in thechangesbranch would still pass.➕ Minimal test addition
const restoredOriginal = deserialized.mutations[0]!.original.dueDate expect(restoredOriginal[Symbol.toStringTag]).toBe(`Temporal.PlainDate`) expect(restoredOriginal.toString()).toBe( temporalValues.plainDate.toString(), ) + + const restoredChanges = deserialized.mutations[0]!.changes.temporalValues + for (const [key, originalValue] of Object.entries(temporalValues)) { + const restoredValue = restoredChanges[key] + expect(restoredValue[Symbol.toStringTag]).toBe( + originalValue[Symbol.toStringTag], + ) + expect(restoredValue.toString()).toBe(originalValue.toString()) + }As per coding guidelines, "Always add unit tests that reproduce a bug before fixing it to ensure the bug is fixed and prevent regression."
📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
changes: { temporalValues, }, }) const serialized = serializer.serialize(transaction) const deserialized = serializer.deserialize(serialized) const restoredValues = deserialized.mutations[0]!.modified.temporalValues for (const [key, originalValue] of Object.entries(temporalValues)) { const restoredValue = restoredValues[key] expect(restoredValue[Symbol.toStringTag]).toBe( originalValue[Symbol.toStringTag], ) expect(restoredValue.toString()).toBe(originalValue.toString()) } const restoredOriginal = deserialized.mutations[0]!.original.dueDate expect(restoredOriginal[Symbol.toStringTag]).toBe(`Temporal.PlainDate`) expect(restoredOriginal.toString()).toBe( temporalValues.plainDate.toString(), ) const restoredChanges = deserialized.mutations[0]!.changes.temporalValues for (const [key, originalValue] of Object.entries(temporalValues)) { const restoredValue = restoredChanges[key] expect(restoredValue[Symbol.toStringTag]).toBe( originalValue[Symbol.toStringTag], ) expect(restoredValue.toString()).toBe(originalValue.toString()) } })🤖 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 `@packages/offline-transactions/tests/TransactionSerializer.test.ts` around lines 323 - 345, The test currently seeds changes.temporalValues but only asserts deserialized.mutations[0].modified and .original; add assertions that inspect deserialized.changes.temporalValues (the same path used when creating the transaction) and verify each entry's Symbol.toStringTag and toString() match the original temporalValues entries; locate the test around serializer.serialize/serializer.deserialize and the transaction object creation and add checks analogous to the modified/original assertions but against deserialized.changes.temporalValues to prevent regressions in the changes branch.Source: Coding guidelines
@coderabbitai review
✅ Action performed
Review finished.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/offline-transactions/tests/TransactionSerializer.test.ts (1)
281-371: ⚡ Quick winAdd a negative-path test for missing Temporal constructors
Current Temporal tests only verify successful round-trips. Please add one assertion that deserializing a Temporal marker without injected constructors throws
MissingTemporalConstructorError, so this runtime contract doesn’t regress.➕ Minimal test addition
-import { TransactionSerializer } from '../src/outbox/TransactionSerializer' +import { + MissingTemporalConstructorError, + TransactionSerializer, +} from '../src/outbox/TransactionSerializer' @@ describe(`Temporal handling`, () => { + it(`should throw when Temporal constructors are unavailable`, () => { + const serializerWithTemporal = createSerializer() + const serializerWithoutTemporal = new TransactionSerializer({ + 'test-collection': mockCollection as any, + }) + + const transaction = createTransaction({ + modified: { + id: `1`, + dueDate: Temporal.PlainDate.from(`2024-01-15`), + }, + }) + + const serialized = serializerWithTemporal.serialize(transaction) + expect(() => serializerWithoutTemporal.deserialize(serialized)).toThrow( + MissingTemporalConstructorError, + ) + }) + it(`should restore Temporal values in mutation data`, () => {As per coding guidelines, "Always add unit tests that reproduce a bug before fixing it to ensure the bug is fixed and prevent regression" and "Test corner cases including ... undefined vs null values ...".
🤖 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 `@packages/offline-transactions/tests/TransactionSerializer.test.ts` around lines 281 - 371, Add a negative-path test that ensures deserializing Temporal markers without injected constructors throws MissingTemporalConstructorError: create a serializer (via createSerializer) that does not have Temporal constructors injected, produce or reuse a serialized transaction containing Temporal markers (e.g., from serialize or a minimal prepared payload), and assert that calling serializer.deserialize(...) throws MissingTemporalConstructorError; reference serializer.deserialize, createSerializer, and MissingTemporalConstructorError in the test so it fails when the runtime contract is not met.Source: Coding guidelines
🤖 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. Inline comments: In `@packages/offline-transactions/src/OfflineExecutor.ts`: - Around line 283-287: When replaying persisted outbox entries in loadAndReplayTransactions() the broad catch currently swallows MissingTemporalConstructorError thrown by OutboxManager.getAll(), so update loadAndReplayTransactions() to explicitly catch MissingTemporalConstructorError (the error class by name) and rethrow it (or propagate it) instead of treating it as a recoverable warning; keep the existing generic catch for other errors but ensure MissingTemporalConstructorError is not swallowed so startup can fail fast when temporals are missing. --- Nitpick comments: In `@packages/offline-transactions/tests/TransactionSerializer.test.ts`: - Around line 281-371: Add a negative-path test that ensures deserializing Temporal markers without injected constructors throws MissingTemporalConstructorError: create a serializer (via createSerializer) that does not have Temporal constructors injected, produce or reuse a serialized transaction containing Temporal markers (e.g., from serialize or a minimal prepared payload), and assert that calling serializer.deserialize(...) throws MissingTemporalConstructorError; reference serializer.deserialize, createSerializer, and MissingTemporalConstructorError in the test so it fails when the runtime contract is not met.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
ddb558b6-5105-4d68-8fab-0711c3364227📥 Commits
Reviewing files that changed from the base of the PR and between 993bb129ae75139371edc5da81d6d208511f1bcb and ecbe6794d091ea85ada8d208db80b17879b984b2.
📒 Files selected for processing (5)
packages/offline-transactions/src/OfflineExecutor.tspackages/offline-transactions/src/outbox/OutboxManager.tspackages/offline-transactions/src/outbox/TransactionSerializer.tspackages/offline-transactions/src/types.tspackages/offline-transactions/tests/TransactionSerializer.test.ts
@@ -280,4 +280,8 @@280280 }281281282282 // Storage available - set up offline components283- this.outbox = new OutboxManager(storage, this.config.collections)283+ this.outbox = new OutboxManager(284+ storage,285+ this.config.collections,286+ this.config.temporal,287+ )⚠️ Potential issue | 🟠 Major | ⚡ Quick win
Missing Temporal constructor failures are still swallowed during startup replay
At Line 283,
OutboxManagernow correctly receivesthis.config.temporal, but when that is absent and persisted outbox data contains Temporal markers,getAll()can throwMissingTemporalConstructorErrorandloadAndReplayTransactions()still swallows it in the broad catch (Line 339). That leaves replay blocked with only a warning.💡 Minimal fix
-import { OutboxManager } from './outbox/OutboxManager' +import { OutboxManager } from './outbox/OutboxManager' +import { MissingTemporalConstructorError } from './outbox/TransactionSerializer' @@ private async loadAndReplayTransactions(): Promise<void> { @@ - } catch (error) { + } catch (error) { + if (error instanceof MissingTemporalConstructorError) { + throw error + } console.warn(`Failed to load and replay transactions:`, error) } }🤖 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 `@packages/offline-transactions/src/OfflineExecutor.ts` around lines 283 - 287, When replaying persisted outbox entries in loadAndReplayTransactions() the broad catch currently swallows MissingTemporalConstructorError thrown by OutboxManager.getAll(), so update loadAndReplayTransactions() to explicitly catch MissingTemporalConstructorError (the error class by name) and rethrow it (or propagate it) instead of treating it as a recoverable warning; keep the existing generic catch for other errors but ensure MissingTemporalConstructorError is not swallowed so startup can fail fast when temporals are missing.@coderabbitai review
✅ Action performed
Review finished.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Actionable comments posted: 1
🤖 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. Inline comments: In `@packages/offline-transactions/tests/OfflineExecutor.test.ts`: - Around line 108-135: The test currently calls executor.dispose() only on the success path, risking leaked resources if expect(...waitForInit()) rejects; move disposal into the finally block so the executor is always disposed. After creating the executor via startOfflineExecutor(...) and before restoring Temporal (originalTemporal/globalWithTemporal), ensure executor.dispose() is invoked in the finally branch (guarding for executor being defined) so startOfflineExecutor, executor.dispose, waitForInit, and MissingTemporalConstructorError are handled safely and no listeners leak between tests.🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
408f1c0f-8b48-46bc-bb16-d31e71c99e97📥 Commits
Reviewing files that changed from the base of the PR and between ecbe6794d091ea85ada8d208db80b17879b984b2 and fa8bef9ce2a4fc5720e9329047146c6091c480bd.
📒 Files selected for processing (2)
packages/offline-transactions/src/OfflineExecutor.tspackages/offline-transactions/tests/OfflineExecutor.test.ts
@@ -75,0 +115,21 @@115+ delete: async () => {},116+ keys: async () => [`tx:tx-temporal`],117+ clear: async () => {},118+ },119+ leaderElection: {120+ requestLeadership: async () => true,121+ releaseLeadership: () => {},122+ isLeader: () => true,123+ onLeadershipChange: () => () => {},124+ },125+ })126+127+ await expect(executor.waitForInit()).rejects.toBeInstanceOf(128+ MissingTemporalConstructorError,129+ )130+ executor.dispose()131+ } finally {132+ if (originalTemporal !== undefined) {133+ globalWithTemporal.Temporal = originalTemporal134+ }135+ }⚠️ Potential issue | 🟡 Minor | ⚡ Quick win
Move executor disposal into
finallyto avoid leaked test resources.At Line 130, disposal runs only on the success path. If the expectation throws, the executor is not disposed and can leak listeners into later tests.
Suggested fix
- try { - const executor = startOfflineExecutor({ + let executor: ReturnType<typeof startOfflineExecutor> | undefined + + try { + executor = startOfflineExecutor({ ...config, storage: { get: async (key) => key === `tx:tx-temporal` ? serializedTransaction : null, @@ await expect(executor.waitForInit()).rejects.toBeInstanceOf( MissingTemporalConstructorError, ) - executor.dispose() } finally { + executor?.dispose() if (originalTemporal !== undefined) { globalWithTemporal.Temporal = originalTemporal } }📝 Committable suggestion
‼️ IMPORTANT Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
let executor: ReturnType<typeof startOfflineExecutor> | undefined try { executor = startOfflineExecutor({ ...config, storage: { get: async (key) => key === `tx:tx-temporal` ? serializedTransaction : null, set: async () => {}, delete: async () => {}, keys: async () => [`tx:tx-temporal`], clear: async () => {}, }, leaderElection: { requestLeadership: async () => true, releaseLeadership: () => {}, isLeader: () => true, onLeadershipChange: () => () => {}, }, }) await expect(executor.waitForInit()).rejects.toBeInstanceOf( MissingTemporalConstructorError, ) } finally { executor?.dispose() if (originalTemporal !== undefined) { globalWithTemporal.Temporal = originalTemporal } }🤖 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 `@packages/offline-transactions/tests/OfflineExecutor.test.ts` around lines 108 - 135, The test currently calls executor.dispose() only on the success path, risking leaked resources if expect(...waitForInit()) rejects; move disposal into the finally block so the executor is always disposed. After creating the executor via startOfflineExecutor(...) and before restoring Temporal (originalTemporal/globalWithTemporal), ensure executor.dispose() is invoked in the finally branch (guarding for executor being defined) so startOfflineExecutor, executor.dispose, waitForInit, and MissingTemporalConstructorError are handled safely and no listeners leak between tests.@coderabbitai review
✅ Action performed
Review finished.
Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.
Closing this implementation for now. Temporal serialization should be reconsidered as part of the broader offline RFC and pre-1.0 cleanup, where the supported value model and runtime contract can be designed together. We can revisit it there if the RFC retains this requirement.
KyleAMathews(GitHub profile, opens in a new tab) closed this
Sign in to join this conversation.
No actionable comments were generated in the recent review. 🎉
ℹ️ Recent review info
⚙️ Run configuration
Configuration used: defaults
Review profile: CHILL
Plan: Pro
Run ID:
bae4eb86-2c0d-454c-8226-9ec9b1d5e620📥 Commits
Reviewing files that changed from the base of the PR and between fa8bef9ce2a4fc5720e9329047146c6091c480bd and 6eb9678bc9f040f146de6f628249e49575d1c0c0.
📒 Files selected for processing (1)
packages/offline-transactions/tests/OfflineExecutor.test.ts🚧 Files skipped from review as they are similar to previous changes (1)
📝 Walkthrough
Walkthrough#
TransactionSerializer now encodes Temporal-like values as markers and reconstructs them via injected or global Temporal constructors; metadata is included in the round-trip. OutboxManager and OfflineExecutor accept optional temporal constructors and propagate MissingTemporalConstructorError. Types, tests, and a devDependency/changeset were added.
Changes#
Temporal value preservation in offline transactions
packages/offline-transactions/src/outbox/TransactionSerializer.tsSymbol.toStringTag, encodes them as{ __type: 'Temporal', type, value }usingtoString(), and reconstructs them with constructor.from(value). AddsMissingTemporalConstructorError.packages/offline-transactions/src/outbox/TransactionSerializer.tsserialize()anddeserialize()now includetransaction.metadataprocessed throughserializeValue/deserializeValue, enabling Temporal values in metadata to round-trip.packages/offline-transactions/src/outbox/OutboxManager.ts,packages/offline-transactions/src/OfflineExecutor.tstemporaland passes it toTransactionSerializer; OfflineExecutor forwardsconfig.temporal.get/getAlland leader replay now re-throwMissingTemporalConstructorErrorinstead of swallowing it; other deserialization errors remain logged and ignored.packages/offline-transactions/src/types.tsTemporalConstructorName,TemporalConstructor,TemporalConstructorstypes and an optionaltemporal?: TemporalConstructorsfield toOfflineConfig.packages/offline-transactions/tests/TransactionSerializer.test.ts,packages/offline-transactions/tests/OfflineExecutor.test.tstemporal-polyfillimport, passesTemporalintoTransactionSerializer, addscreateTransactionhelper, introducesTemporal handlingtests for mutation payloads and metadata, and adds a test assertingMissingTemporalConstructorErroris thrown when global Temporal is absent..changeset/quiet-temporal-dragons.md,packages/offline-transactions/package.jsontemporal-polyfill(^0.3.0) to devDependencies for tests.Sequence Diagram#
Estimated code review effort#
🎯 3 (Moderate) | ⏱️ ~25 minutes
Suggested reviewers#
Poem#
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)#
✅ Passed checks (4 passed)
✨ Finishing Touches
🧪 Generate unit tests (beta)
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