{"version":3,"file":"transactions.cjs","names":["codedMessage","sameRowValue","MissingMutationFunctionError","safeRandomUUID","createDeferred","TransactionNotPendingCommitError","TransactionNotPendingMutateError","TransactionAlreadyCompletedRollbackError","takeTransactionCommitWork","normalizeError","transactionStack","claimActiveTransaction","captureMutations"],"sources":["../../src/transactions.ts"],"sourcesContent":["import { createDeferred } from './deferred'\nimport { sameRowValue } from './utils'\nimport { safeRandomUUID } from './utils/uuid'\nimport { normalizeError } from './utils/error.js'\nimport './duplicate-instance-check'\nimport {\n  MissingMutationFunctionError,\n  TransactionAlreadyCompletedRollbackError,\n  TransactionNotPendingCommitError,\n  TransactionNotPendingMutateError,\n} from './errors'\nimport { transactionScopedScheduler } from './scheduler.js'\nimport { takeTransactionCommitWork } from './transaction-commit-work.js'\nimport { codedMessage, devBuild } from './error-message.js'\nimport type { Deferred } from './deferred'\nimport type { Collection } from './collection/index.js'\nimport type {\n  MutationFn,\n  PendingMutation,\n  TransactionConfig,\n  TransactionState,\n  TransactionWithMutations,\n} from './types'\n\nexport class TransactionScope {\n  private transactions: Array<Transaction<any>> = []\n  private transactionStack: Array<Transaction<any>> = []\n  private sequenceNumber = 0\n\n  createTransaction<T extends object = Record<string, unknown>>(\n    config: TransactionConfig<T>,\n  ): Transaction<T> {\n    const transaction = new Transaction<T>(config, this, this.sequenceNumber++)\n    this.transactions.push(transaction)\n    return transaction\n  }\n\n  getActiveTransaction(): Transaction | undefined {\n    return this.transactionStack.at(-1)\n  }\n\n  getActiveTransactionForCollection(): Transaction | undefined {\n    const activeTransaction = this.getActiveTransaction()\n    if (activeTransaction) {\n      return activeTransaction\n    }\n\n    if (this === defaultTransactionScope) {\n      return undefined\n    }\n\n    return defaultTransactionScope.claimActiveTransaction(this)\n  }\n\n  private claimActiveTransaction(\n    targetScope: TransactionScope,\n  ): Transaction | undefined {\n    const transaction = this.getActiveTransaction()\n    if (!transaction) {\n      return undefined\n    }\n\n    const owner = getTransactionScope(transaction)\n    if (owner === targetScope) {\n      return transaction\n    }\n    if (owner !== this) {\n      throw new Error(\n        devBuild() && process.env.NODE_ENV !== `production`\n          ? `A transaction created with createTransaction() cannot mutate collections from multiple DbClient instances. Use dbClient.createTransaction() for explicit client scope.`\n          : codedMessage(162),\n      )\n    }\n\n    this.removeTransaction(transaction)\n    targetScope.transactions.push(transaction)\n    targetScope.transactionStack.push(transaction)\n    transaction.sequenceNumber = targetScope.sequenceNumber++\n    transactionScopes.set(transaction, targetScope)\n    return transaction\n  }\n\n  registerTransaction(transaction: Transaction<any>): void {\n    // Clear stale work left by an aborted mutate scope before reusing the id.\n    transactionScopedScheduler.clear(transaction.id)\n    this.transactionStack.push(transaction)\n  }\n\n  unregisterTransaction(\n    transaction: Transaction<any>,\n    contextAlreadyCleared = false,\n  ): void {\n    try {\n      transactionScopedScheduler.flush(transaction.id)\n    } finally {\n      if (!contextAlreadyCleared) this.clearTransactionContext(transaction)\n    }\n  }\n\n  clearTransactionContext(transaction: Transaction<any>): void {\n    const index = this.transactionStack.lastIndexOf(transaction)\n    if (index !== -1) this.transactionStack.splice(index, 1)\n  }\n\n  removeTransaction(transaction: Transaction<any>): void {\n    const index = this.transactions.indexOf(transaction)\n    if (index !== -1) {\n      this.transactions.splice(index, 1)\n    }\n  }\n\n  /** Rolls back every conflicting candidate, then throws the first error. */\n  rollbackConflictingTransactions(\n    transaction: Transaction<any>,\n    mutationIds: Set<string>,\n  ): void {\n    const errors: Array<unknown> = []\n    for (const candidate of [...this.transactions]) {\n      if (\n        candidate !== transaction &&\n        candidate.state === `pending` &&\n        candidate.mutations.some((mutation) =>\n          mutationIds.has(mutation.globalKey),\n        )\n      ) {\n        try {\n          candidate.rollback({ isSecondaryRollback: true })\n        } catch (error) {\n          errors.push(error)\n        }\n      }\n    }\n    if (errors.length > 0) throw errors[0]\n  }\n\n  clear(): void {\n    const transactionIds = new Set([\n      ...this.transactions.map((transaction) => transaction.id),\n      ...this.transactionStack.map((transaction) => transaction.id),\n    ])\n    for (const transactionId of transactionIds) {\n      transactionScopedScheduler.clear(transactionId)\n    }\n    this.transactions = []\n    this.transactionStack = []\n  }\n}\n\nconst defaultTransactionScope = new TransactionScope()\nconst transactionScopes = new WeakMap<object, TransactionScope>()\nconst transactionAmbientScopes = new WeakMap<object, TransactionScope>()\n\nfunction getTransactionScope(transaction: object): TransactionScope {\n  const scope = transactionScopes.get(transaction)\n  if (!scope) {\n    throw new Error(\n      devBuild() && process.env.NODE_ENV !== `production`\n        ? `Transaction is not associated with a TransactionScope.`\n        : codedMessage(163),\n    )\n  }\n  return scope\n}\n\nfunction getTransactionAmbientScope(transaction: object): TransactionScope {\n  const scope = transactionAmbientScopes.get(transaction)\n  if (!scope) {\n    throw new Error(\n      devBuild() && process.env.NODE_ENV !== `production`\n        ? `Transaction is not associated with an ambient scope.`\n        : codedMessage(164),\n    )\n  }\n  return scope\n}\n\n/**\n * Merges two pending mutations for the same item within a transaction\n *\n * Merge behavior truth table:\n * - (insert, update) → insert (merge changes, keep empty original)\n * - (insert, delete) → null (cancel both mutations)\n * - (update, delete) → delete (delete dominates)\n * - (update, update) → update (replace with latest, union changes)\n * - (delete, delete) → delete (replace with latest)\n * - (insert, insert) → insert (replace with latest)\n * - (delete, insert) → insert without an authoritative row, null if restoring\n *   the authoritative row, otherwise update\n *\n * Note: (delete, update) should never occur as the collection layer prevents\n * update operations on deleted items within the same transaction.\n *\n * @param existing - The existing mutation in the transaction\n * @param incoming - The new mutation being applied\n * @returns The merged mutation, or null if both should be removed\n */\nfunction mergePendingMutations<T extends object>(\n  existing: PendingMutation<T>,\n  incoming: PendingMutation<T>,\n): PendingMutation<T> | null {\n  // Dispatch on the arriving operation without constructing a composite key.\n  switch (incoming.type) {\n    case `update`: {\n      if (existing.type === `delete`) break\n      // An insert keeps its identity and optimistic policy. An update uses\n      // the newest envelope. Both merge fields and keep the first original.\n      const inserted = existing.type === `insert`\n      return {\n        ...(inserted ? existing : incoming),\n        original: inserted ? {} : existing.original,\n        modified: incoming.modified,\n        changes: { ...existing.changes, ...incoming.changes },\n        // Merge metadata (last-write-wins)\n        metadata: incoming.metadata ?? existing.metadata,\n        syncMetadata: { ...existing.syncMetadata, ...incoming.syncMetadata },\n        // Update tracking info\n        mutationId: incoming.mutationId,\n        updatedAt: incoming.updatedAt,\n      }\n    }\n\n    case `delete`:\n      // An insert followed by a delete cancels. Otherwise the delete dominates.\n      return existing.type === `insert` ? null : incoming\n\n    case `insert`: {\n      if (existing.type === `insert`) return incoming\n      if (existing.type !== `delete`) break\n      const original = existing.collection._state.syncedData.get(existing.key)\n      if (original === undefined) return incoming\n      // -0 and 0 are distinct row values, as user writes (FID-1).\n      if (sameRowValue(original, incoming.modified)) {\n        return null\n      }\n\n      const modified = incoming.modified\n      const keys = new Set([...Object.keys(original), ...Object.keys(modified)])\n      const changes: Partial<T> = {}\n      for (const key of keys) {\n        if (\n          Object.hasOwn(original, key) !== Object.hasOwn(modified, key) ||\n          !sameRowValue(original[key as keyof T], modified[key as keyof T])\n        ) {\n          changes[key as keyof T] = modified[key as keyof T]\n        }\n      }\n\n      return {\n        ...incoming,\n        type: `update`,\n        original,\n        changes,\n        metadata: incoming.metadata ?? existing.metadata,\n        syncMetadata: { ...existing.syncMetadata, ...incoming.syncMetadata },\n      }\n    }\n  }\n\n  // Reject combinations that mutation admission does not allow.\n  const _exhaustive = `${existing.type}-${incoming.type}`\n  throw new Error(\n    devBuild() && process.env.NODE_ENV !== `production`\n      ? `Unhandled mutation combination: ${_exhaustive}`\n      : codedMessage(165, { combination: _exhaustive }),\n  )\n}\n\n/**\n * Creates a new transaction for grouping multiple collection operations\n * @param config - Transaction configuration with mutation function\n * @returns A new Transaction instance\n * @example\n * // Basic transaction usage\n * const tx = createTransaction({\n *   mutationFn: async ({ transaction }) => {\n *     // Send all mutations to API\n *     await api.saveChanges(transaction.mutations)\n *   }\n * })\n *\n * tx.mutate(() => {\n *   collection.insert({ id: \"1\", text: \"Buy milk\" })\n *   collection.update(\"2\", draft => { draft.completed = true })\n * })\n *\n * await tx.when('settled')\n *\n * @example\n * // Handle transaction errors\n * try {\n *   const tx = createTransaction({\n *     mutationFn: async () => { throw new Error(\"API failed\") }\n *   })\n *\n *   tx.mutate(() => {\n *     collection.insert({ id: \"1\", text: \"New item\" })\n *   })\n *\n *   await tx.when('settled')\n * } catch (error) {\n *   console.log('Transaction failed:', error)\n * }\n *\n * @example\n * // Manual commit control\n * const tx = createTransaction({\n *   autoCommit: false,\n *   mutationFn: async () => {\n *     // API call\n *   }\n * })\n *\n * tx.mutate(() => {\n *   collection.insert({ id: \"1\", text: \"Item\" })\n * })\n *\n * // Commit later\n * await tx.commit()\n */\nexport function createTransaction<T extends object = Record<string, unknown>>(\n  config: TransactionConfig<T>,\n): Transaction<T> {\n  return defaultTransactionScope.createTransaction(config)\n}\n\n/**\n * Gets the currently active ambient transaction, if any\n * Used internally by collection operations to join existing transactions\n * @returns The active transaction or undefined if none is active\n * @example\n * // Check if operations will join an ambient transaction\n * const ambientTx = getActiveTransaction()\n * if (ambientTx) {\n *   console.log('Operations will join transaction:', ambientTx.id)\n * }\n */\nexport function getActiveTransaction(): Transaction | undefined {\n  return defaultTransactionScope.getActiveTransaction()\n}\n\n// TransactionWithMutations is an Omit-based structural view of Transaction,\n// so the settlement cannot be a private class field.\nconst transactionSettlements = new WeakMap<object, unknown>()\n\nfunction settlementFor<T extends object>(\n  transaction: Transaction<T>,\n): Deferred<Transaction<T>> {\n  return transactionSettlements.get(transaction) as Deferred<Transaction<T>>\n}\n\nclass Transaction<T extends object = Record<string, unknown>> {\n  public id: string\n  public state: TransactionState\n  public mutationFn: MutationFn<T>\n  public mutations: Array<PendingMutation<T>>\n  /**\n   * Every Collection that has tracked this transaction. Settlement recomputes\n   * each of them, including one whose mutations merged away.\n   */\n  public readonly collections: Set<Collection<any, any, any, any, any>> =\n    new Set()\n  private captureMutations?: () => void\n  public autoCommit: boolean\n  public createdAt: Date\n  public sequenceNumber: number\n  public metadata: Record<string, unknown>\n  public error?: {\n    message: string\n    error: Error\n  }\n\n  constructor(\n    config: TransactionConfig<T>,\n    scope: TransactionScope,\n    sequenceNumber: number,\n  ) {\n    if (typeof config.mutationFn === `undefined`) {\n      throw new MissingMutationFunctionError()\n    }\n    this.id = config.id ?? safeRandomUUID()\n    this.mutationFn = config.mutationFn\n    this.state = `pending`\n    this.mutations = []\n    const settlement = createDeferred<Transaction<T>>()\n    transactionSettlements.set(this, settlement)\n    // A rejection nobody reads is not an unhandled rejection; a caller reads\n    // the outcome from `when('settled')`.\n    settlement.promise.catch(() => undefined)\n    this.autoCommit = config.autoCommit ?? true\n    this.createdAt = new Date()\n    this.sequenceNumber = sequenceNumber\n    this.metadata = config.metadata ?? {}\n    transactionScopes.set(this, scope)\n    transactionAmbientScopes.set(this, scope)\n  }\n\n  /**\n   * Wait for this transaction to complete successfully or fail.\n   *\n   * The promise resolves with this transaction on success and rejects with\n   * the original error on failure (or `undefined` for a rollback without an\n   * error). For non-empty commits, this\n   * boundary is the mutation function's completion; it does not inherently\n   * prove backend acknowledgement or read-back unless the mutation function\n   * or an adapter-registered commit work item waits for it.\n   */\n  when(_state: 'settled'): Promise<Transaction<T>> {\n    return settlementFor(this).promise\n  }\n\n  /** Complete a transaction whose work was already applied outside commit(). @internal */\n  completeWithoutCommit(): void {\n    if (this.state !== `pending`) throw new TransactionNotPendingCommitError()\n    this.setState(`completed`)\n    settlementFor(this).resolve(this)\n  }\n\n  setState(newState: TransactionState) {\n    this.state = newState\n\n    if (newState === `completed` || newState === `failed`) {\n      getTransactionScope(this).removeTransaction(this)\n    }\n  }\n\n  /**\n   * Execute collection operations within this transaction\n   * @param callback - Synchronous function containing collection operations to group together.\n   * The transaction context is active only for the synchronous duration of this callback.\n   * Async work should happen in `mutationFn`; collection operations after `await` boundaries\n   * inside this callback will not be part of this transaction. For manual transactions, call\n   * `mutate` multiple times before committing to add more synchronous operations to the same\n   * transaction. If this callback throws, its mutations are removed before the\n   * error reaches the caller; mutations from earlier successful calls remain.\n   * @returns This transaction for chaining\n   * @example\n   * // Group multiple operations\n   * const tx = createTransaction({ mutationFn: async () => {\n   *   // Send to API\n   * }})\n   *\n   * tx.mutate(() => {\n   *   collection.insert({ id: \"1\", text: \"Buy milk\" })\n   *   collection.update(\"2\", draft => { draft.completed = true })\n   *   collection.delete(\"3\")\n   * })\n   *\n   * await tx.when('settled')\n   *\n   * @example\n   * // Handle mutate errors\n   * try {\n   *   tx.mutate(() => {\n   *     collection.insert({ id: \"invalid\" }) // This might throw\n   *   })\n   * } catch (error) {\n   *   console.log('Mutation failed:', error)\n   * }\n   *\n   * @example\n   * // Manual commit control\n   * const tx = createTransaction({ autoCommit: false, mutationFn: async () => {} })\n   *\n   * tx.mutate(() => {\n   *   collection.insert({ id: \"1\", text: \"Item\" })\n   * })\n   *\n   * // Add more synchronous mutations to the same transaction\n   * tx.mutate(() => {\n   *   collection.update(\"1\", draft => { draft.text = \"Updated item\" })\n   * })\n   *\n   * // Commit later when ready\n   * await tx.commit()\n   */\n  mutate(callback: () => void): Transaction<T> {\n    if (this.state !== `pending`) {\n      throw new TransactionNotPendingMutateError()\n    }\n\n    const initialScope = getTransactionScope(this)\n    const registeredScopes = new Set([\n      initialScope,\n      getTransactionAmbientScope(this),\n    ])\n    for (const scope of registeredScopes) {\n      scope.registerTransaction(this)\n    }\n\n    let previousMutations: Array<PendingMutation<T>> | undefined\n    const captureOuter = this.captureMutations\n    this.captureMutations = () => {\n      captureOuter?.()\n      previousMutations ??= [...this.mutations]\n    }\n    let contextAlreadyCleared = false\n    try {\n      callback()\n    } catch (error) {\n      // Keep successful earlier callbacks when this one fails after changing\n      // one or more Collections. The original mutation objects are immutable\n      // snapshots; later same-key merges replace them rather than editing them.\n      const before = previousMutations ?? this.mutations\n      const touched = new Set(\n        [...before, ...this.mutations].map((mutation) => mutation.collection),\n      )\n      if (previousMutations)\n        this.mutations.splice(0, this.mutations.length, ...previousMutations)\n      // Restoration publishes outside the failed callback's transaction\n      // context. A subscriber's new write must not join this transaction.\n      registeredScopes.add(getTransactionScope(this))\n      for (const scope of registeredScopes) scope.clearTransactionContext(this)\n      contextAlreadyCleared = true\n      const restorationErrors: Array<unknown> = []\n      for (const collection of touched) {\n        try {\n          collection._state.onTransactionStateChange()\n        } catch (restorationError) {\n          restorationErrors.push(restorationError)\n        }\n      }\n      if (restorationErrors.length)\n        throw new AggregateError(\n          [error, ...restorationErrors],\n          devBuild() && process.env.NODE_ENV !== `production`\n            ? `Mutation callback and restoration failed`\n            : codedMessage(174),\n          { cause: error },\n        )\n      throw error\n    } finally {\n      this.captureMutations = captureOuter\n      registeredScopes.add(getTransactionScope(this))\n      for (const scope of registeredScopes) {\n        scope.unregisterTransaction(this, contextAlreadyCleared)\n      }\n    }\n\n    if (this.autoCommit) {\n      this.commit().catch(() => {\n        // Errors from autoCommit are handled via when('settled')\n        // This catch prevents unhandled promise rejections\n      })\n    }\n\n    return this\n  }\n\n  /**\n   * Apply new mutations to this transaction, intelligently merging with existing mutations\n   *\n   * When mutations operate on the same item (same globalKey), they are merged according to\n   * the following rules:\n   *\n   * - **insert + update** → insert (merge changes, keep empty original)\n   * - **insert + delete** → removed (mutations cancel each other out)\n   * - **update + delete** → delete (delete dominates)\n   * - **update + update** → update (union changes, keep first original)\n   * - **delete + insert** → removed if restored, otherwise update\n   * - **same type** → replace with latest\n   *\n   * This merging reduces over-the-wire churn and keeps the optimistic local view\n   * aligned with user intent.\n   *\n   * @param mutations - Array of new mutations to apply\n   */\n  applyMutations(mutations: Array<PendingMutation<any>>): void {\n    this.captureMutations?.()\n    // Merge via a globalKey-keyed map rather than a findIndex scan per\n    // mutation, which is O(n²) for bulk operations (e.g. inserting many rows\n    // in one call). Map preserves insertion order, matching the previous\n    // replace-in-place / remove / append semantics.\n    const merged = new Map<string, PendingMutation<any>>()\n    for (const mutation of this.mutations) {\n      merged.set(mutation.globalKey, mutation)\n    }\n\n    for (const newMutation of mutations) {\n      const globalKey = newMutation.globalKey\n      const existingMutation = merged.get(globalKey)\n\n      const mergeResult = existingMutation\n        ? mergePendingMutations(existingMutation, newMutation)\n        : newMutation\n      if (mergeResult === null) {\n        // Remove the mutation (e.g., delete after insert cancels both).\n        merged.delete(globalKey)\n      } else {\n        // Insert the new mutation or replace it with the merged result.\n        merged.set(globalKey, mergeResult)\n      }\n    }\n\n    // Rebuild in place to preserve the array's identity for external holders\n    this.mutations.length = 0\n    for (const mutation of merged.values()) {\n      this.mutations.push(mutation)\n    }\n  }\n\n  /**\n   * Rollback the transaction and any conflicting transactions\n   * @param config - Configuration for rollback behavior\n   * @returns This transaction for chaining\n   * @example\n   * // Manual rollback\n   * const tx = createTransaction({ mutationFn: async () => {\n   *   // Send to API\n   * }})\n   *\n   * tx.mutate(() => {\n   *   collection.insert({ id: \"1\", text: \"Buy milk\" })\n   * })\n   *\n   * // Rollback if needed\n   * if (shouldCancel) {\n   *   tx.rollback()\n   * }\n   *\n   * @example\n   * // Handle rollback cascade (automatic)\n   * const tx1 = createTransaction({ mutationFn: async () => {} })\n   * const tx2 = createTransaction({ mutationFn: async () => {} })\n   *\n   * tx1.mutate(() => collection.update(\"1\", draft => { draft.value = \"A\" }))\n   * tx2.mutate(() => collection.update(\"1\", draft => { draft.value = \"B\" })) // Same item\n   *\n   * tx1.rollback() // This will also rollback tx2 due to conflict\n   *\n   * @example\n   * // Handle rollback in error scenarios\n   * try {\n   *   await tx.when('settled')\n   * } catch (error) {\n   *   console.log('Transaction was rolled back:', error)\n   *   // Transaction automatically rolled back on mutation function failure\n   * }\n   */\n  rollback(config?: {\n    isSecondaryRollback?: boolean\n    error?: Error\n  }): Transaction<T> {\n    const isSecondaryRollback = config?.isSecondaryRollback ?? false\n    if (this.state === `completed`) {\n      throw new TransactionAlreadyCompletedRollbackError()\n    }\n    if (this.state === `failed`) return this\n\n    if (config?.error) {\n      this.error = { message: config.error.message, error: config.error }\n    }\n\n    const wasPersisting = this.state === `persisting`\n    this.setState(`failed`)\n\n    // A failing subscriber cannot leave this transaction unsettled.\n    try {\n      // See if there's any other transactions w/ mutations on the same ids\n      // and roll them back as well.\n      if (!isSecondaryRollback) {\n        const mutationIds = new Set(\n          this.mutations.map((mutation) => mutation.globalKey),\n        )\n        getTransactionScope(this).rollbackConflictingTransactions(\n          this,\n          mutationIds,\n        )\n      }\n    } finally {\n      // Reject the promise\n      settlementFor(this).reject(this.error?.error)\n      this.touchCollection(wasPersisting)\n    }\n\n    return this\n  }\n\n  /**\n   * Tell every Collection that tracked this transaction that it changed. A\n   * failure in one Collection must not leave the others showing this\n   * transaction's settled optimistic state, so each one recomputes before the\n   * first error is thrown. A settled transaction then empties its set of\n   * tracking Collections. Its mutations still name their Collection.\n   */\n  touchCollection(releasedHold = false): void {\n    const collections = new Set(this.collections)\n    for (const mutation of this.mutations) collections.add(mutation.collection)\n    const settled = this.state === `completed` || this.state === `failed`\n    if (settled) this.collections.clear()\n    const errors: Array<unknown> = []\n    for (const collection of collections) {\n      try {\n        collection._state.onTransactionStateChange()\n        if (releasedHold) collection._lifecycle.startGCTimer(true)\n\n        // Only call commitPendingTransactions if there are pending sync transactions\n        if (collection._state.pendingSyncedTransactions.length > 0) {\n          collection._state.commitPendingTransactions()\n        }\n      } catch (error) {\n        errors.push(error)\n      }\n    }\n    if (errors.length > 0) throw errors[0]\n  }\n\n  /**\n   * Commit the transaction and execute the mutation function\n   * @returns Promise that resolves to this transaction when complete\n   * @example\n   * // Manual commit (when autoCommit is false)\n   * const tx = createTransaction({\n   *   autoCommit: false,\n   *   mutationFn: async ({ transaction }) => {\n   *     await api.saveChanges(transaction.mutations)\n   *   }\n   * })\n   *\n   * tx.mutate(() => {\n   *   collection.insert({ id: \"1\", text: \"Buy milk\" })\n   * })\n   *\n   * await tx.commit() // Manually commit\n   *\n   * @example\n   * // Handle commit errors\n   * try {\n   *   const tx = createTransaction({\n   *     mutationFn: async () => { throw new Error(\"API failed\") }\n   *   })\n   *\n   *   tx.mutate(() => {\n   *     collection.insert({ id: \"1\", text: \"Item\" })\n   *   })\n   *\n   *   await tx.commit()\n   * } catch (error) {\n   *   console.log('Commit failed, transaction rolled back:', error)\n   * }\n   *\n   * @example\n   * // Check transaction state after commit\n   * await tx.commit()\n   * console.log(tx.state) // \"completed\" or \"failed\"\n   */\n  async commit(): Promise<Transaction<T>> {\n    if (this.state !== `pending`) {\n      throw new TransactionNotPendingCommitError()\n    }\n\n    this.setState(`persisting`)\n\n    // An empty transaction completes in this tick without invoking its handler.\n    // Both paths still notify Collections whose mutations merged away.\n    if (this.mutations.length > 0) {\n      // Run mutationFn\n      try {\n        // At this point we know there's at least one mutation\n        // We've already verified mutations is non-empty, so this cast is safe\n        // Use a direct type assertion instead of object spreading to preserve the original type\n        await this.mutationFn({\n          transaction: this as unknown as TransactionWithMutations<T>,\n        })\n        const commitWork = takeTransactionCommitWork(this)\n        if (commitWork) await commitWork\n      } catch (error) {\n        if ((this.state as TransactionState) !== `persisting`) return this\n\n        // Preserve the original error for rethrowing\n        const originalError = normalizeError(error)\n\n        // A mutationFn can accept local work and then fail. That work remains\n        // accepted, so its storage effect must settle before this receipt does.\n        try {\n          await takeTransactionCommitWork(this)\n        } catch {\n          // The mutationFn error remains the transaction's reported cause.\n        }\n\n        // Update transaction with error information\n        this.error = {\n          message: originalError.message,\n          error: originalError,\n        }\n\n        // Roll back. The mutation error stays the reported cause.\n        try {\n          this.rollback()\n        } catch {\n          // Settlement still ran every step.\n        }\n\n        // Re-throw the original error to preserve identity and stack\n        throw originalError\n      }\n\n      if ((this.state as TransactionState) !== `persisting`) return this\n    }\n\n    this.setState(`completed`)\n    // Publication errors cannot undo persistence or leave its receipt pending.\n    // Keep normal publication queued before callers resume from the receipt.\n    try {\n      this.touchCollection(true)\n    } finally {\n      settlementFor(this).resolve(this)\n    }\n\n    return this\n  }\n\n  /**\n   * Compare two transactions by their createdAt time and sequence number in order\n   * to sort them in the order they were created.\n   * @param other - The other transaction to compare to\n   * @returns -1 if this transaction was created before the other, 1 if it was created after, 0 if they were created at the same time\n   */\n  compareCreatedAt(other: Transaction<any>): number {\n    const createdAtComparison =\n      this.createdAt.getTime() - other.createdAt.getTime()\n    if (createdAtComparison !== 0) {\n      return createdAtComparison\n    }\n    return this.sequenceNumber - other.sequenceNumber\n  }\n}\n\nexport type { Transaction }\n"],"mappings":";;;;;;;;AAwBA,IAAa,mBAAb,MAA8B;;EACoB,KAAA,eAAA,CAAC;EACG,KAAAU,KAAA,CAAC;EAC5B,KAAA,iBAAA;;CAEzB,kBACE,QACgB;EAChB,MAAM,cAAc,IAAI,YAAe,QAAQ,MAAM,KAAK,gBAAgB;EAC1E,KAAK,aAAa,KAAK,WAAW;EAClC,OAAO;CACT;CAEA,uBAAgD;EAC9C,OAAO,KAAKA,GAAiB,GAAG,EAAE;CACpC;CAEA,oCAA6D;EAC3D,MAAM,oBAAoB,KAAK,qBAAqB;EACpD,IAAI,mBACF,OAAO;EAGT,IAAI,SAAS,yBACX;EAGF,OAAO,wBAAwBC,GAAuB,IAAI;CAC5D;CAEAA,GACE,aACyB;EACzB,MAAM,cAAc,KAAK,qBAAqB;EAC9C,IAAI,CAAC,aACH;EAGF,MAAM,QAAQ,oBAAoB,WAAW;EAC7C,IAAI,UAAU,aACZ,OAAO;EAET,IAAI,UAAU,MACZ,MAAM,IAAI,MACR,sCAAA,SAAS,KAAA,QAAA,IAAA,aAA8B,eACnC,2KACAX,sBAAAA,aAAa,GAAG,CACtB;EAGF,KAAK,kBAAkB,WAAW;EAClC,YAAY,aAAa,KAAK,WAAW;EACzC,YAAYU,GAAiB,KAAK,WAAW;EAC7C,YAAY,iBAAiB,YAAY;EACzC,kBAAkB,IAAI,aAAa,WAAW;EAC9C,OAAO;CACT;CAEA,oBAAoB,aAAqC;EAEvD,kBAAA,2BAA2B,MAAM,YAAY,EAAE;EAC/C,KAAKA,GAAiB,KAAK,WAAW;CACxC;CAEA,sBACE,aACA,wBAAwB,OAClB;EACN,IAAI;GACF,kBAAA,2BAA2B,MAAM,YAAY,EAAE;EACjD,UAAA;GACE,IAAI,CAAC,uBAAuB,KAAK,wBAA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