@tearleads/client-sdk 0.1.251 → 0.1.252

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (141) hide show
  1. package/Tearleads.d.ts +0 -2
  2. package/Tearleads.js +14 -25
  3. package/Tearleads.js.map +1 -1
  4. package/client/organizations/organizationReadModelPresentation.js +7 -4
  5. package/client/organizations/organizationReadModelPresentation.js.map +1 -1
  6. package/client/organizations/organizationReadModels.js +6 -5
  7. package/client/organizations/organizationReadModels.js.map +1 -1
  8. package/client/organizations/organizationWorkflowRuntime.js +1 -1
  9. package/client/organizations/organizationWorkflowRuntime.js.map +1 -1
  10. package/client/runtime/principalMutationApi.d.ts +4 -0
  11. package/client/runtime/principalMutationApi.js +9 -5
  12. package/client/runtime/principalMutationApi.js.map +1 -1
  13. package/client/runtime/runtimeIdentityResolution.js +23 -0
  14. package/client/runtime/runtimeIdentityResolution.js.map +1 -1
  15. package/client/runtime/runtimeSubscription.js +68 -0
  16. package/client/runtime/runtimeSubscription.js.map +1 -0
  17. package/client/runtime/workflowRuntime.d.ts +1 -1
  18. package/client/runtime/workflowRuntime.js +20 -77
  19. package/client/runtime/workflowRuntime.js.map +1 -1
  20. package/client/session/authenticationMachine.js +47 -0
  21. package/client/session/authenticationMachine.js.map +1 -0
  22. package/client/session/index.js +75 -93
  23. package/client/session/index.js.map +1 -1
  24. package/client/session/sessionBlobStore.js +39 -0
  25. package/client/session/sessionBlobStore.js.map +1 -0
  26. package/client/session/sessionContext.js +11 -0
  27. package/client/session/sessionContext.js.map +1 -1
  28. package/client/session/sessionIdentityTrust.d.ts +2 -1
  29. package/client/session/sessionIdentityTrust.js +8 -4
  30. package/client/session/sessionIdentityTrust.js.map +1 -1
  31. package/client/session/sessionLifetime.js +87 -0
  32. package/client/session/sessionLifetime.js.map +1 -0
  33. package/client/session/sessionLogin.js +114 -0
  34. package/client/session/sessionLogin.js.map +1 -0
  35. package/client/session/sessionOrganizationCreation.js +3 -2
  36. package/client/session/sessionOrganizationCreation.js.map +1 -1
  37. package/client/session/sessionPurgeRecovery.js +11 -3
  38. package/client/session/sessionPurgeRecovery.js.map +1 -1
  39. package/client/session/sessionTypes.d.ts +6 -2
  40. package/client/session/sessionTypes.js.map +1 -1
  41. package/data/blobs/blobContracts.d.ts +4 -3
  42. package/data/blobs/blobContracts.js.map +1 -1
  43. package/data/blobs/createBlobStore.js +1 -8
  44. package/data/blobs/createBlobStore.js.map +1 -1
  45. package/data/blobs/encryptedBlobStore.js +17 -12
  46. package/data/blobs/encryptedBlobStore.js.map +1 -1
  47. package/data/blobs/memoryBlobStore.js +8 -5
  48. package/data/blobs/memoryBlobStore.js.map +1 -1
  49. package/data/blobs/opfsBlobFile.js +36 -0
  50. package/data/blobs/opfsBlobFile.js.map +1 -0
  51. package/data/blobs/opfsBlobStore.d.ts +1 -1
  52. package/data/blobs/opfsBlobStore.js +91 -21
  53. package/data/blobs/opfsBlobStore.js.map +1 -1
  54. package/data/principals/principalPolicyCoordinator.js +8 -17
  55. package/data/principals/principalPolicyCoordinator.js.map +1 -1
  56. package/data/shared/domainScope.d.ts +2 -0
  57. package/data/shared/domainScope.js +2 -1
  58. package/data/shared/domainScope.js.map +1 -1
  59. package/data/shared/keyedQueue.js +15 -0
  60. package/data/shared/keyedQueue.js.map +1 -0
  61. package/data/sqlite/migrations/migrateLocalSchema.js +2 -3
  62. package/data/sqlite/migrations/migrateLocalSchema.js.map +1 -1
  63. package/data/sqlite/sqlExec.d.ts +6 -0
  64. package/data/sqlite/sqlExec.js +64 -13
  65. package/data/sqlite/sqlExec.js.map +1 -1
  66. package/data/sqlite/sqlitePersistenceRuntime.js +2 -3
  67. package/data/sqlite/sqlitePersistenceRuntime.js.map +1 -1
  68. package/data/trustedUserIdentity/service.js +2 -1
  69. package/data/trustedUserIdentity/service.js.map +1 -1
  70. package/data/trustedUserIdentity/types.d.ts +1 -1
  71. package/data/trustedUserIdentity/types.js.map +1 -1
  72. package/internal/api-client/ApiClient.d.ts +4 -1
  73. package/internal/api-client/apiRequestRuntime.d.ts +6 -3
  74. package/internal/api-client/apiRequestRuntime.js +86 -101
  75. package/internal/api-client/apiRequestRuntime.js.map +1 -1
  76. package/internal/api-client/binaryRequestOperationTransport.js +2 -1
  77. package/internal/api-client/binaryRequestOperationTransport.js.map +1 -1
  78. package/internal/api-client/binaryResponseOperationTransport.js +6 -2
  79. package/internal/api-client/binaryResponseOperationTransport.js.map +1 -1
  80. package/internal/api-client/client/blobs.d.ts +1 -0
  81. package/internal/api-client/client/blobs.js +12 -3
  82. package/internal/api-client/client/blobs.js.map +1 -1
  83. package/internal/api-client/client/laneListingRequest.js +4 -0
  84. package/internal/api-client/client/laneListingRequest.js.map +1 -1
  85. package/internal/api-client/client/session.d.ts +5 -1
  86. package/internal/api-client/client/session.js +12 -4
  87. package/internal/api-client/client/session.js.map +1 -1
  88. package/internal/api-client/client/writerProjections.js +12 -13
  89. package/internal/api-client/client/writerProjections.js.map +1 -1
  90. package/internal/api-client/operationResponse.d.ts +1 -1
  91. package/internal/api-client/operationResponse.js +10 -23
  92. package/internal/api-client/operationResponse.js.map +1 -1
  93. package/internal/api-client/operationTransport.js +2 -1
  94. package/internal/api-client/operationTransport.js.map +1 -1
  95. package/internal/api-client/principalHistoryRequest.js +25 -20
  96. package/internal/api-client/principalHistoryRequest.js.map +1 -1
  97. package/internal/api-client/principalHistoryRequestContext.js +30 -6
  98. package/internal/api-client/principalHistoryRequestContext.js.map +1 -1
  99. package/internal/api-client/principalPolicyPages.d.ts +4 -1
  100. package/internal/api-client/principalPolicyPages.js +4 -2
  101. package/internal/api-client/principalPolicyPages.js.map +1 -1
  102. package/internal/api-client/projectionPolicyHistoryPages.d.ts +4 -1
  103. package/internal/api-client/projectionPolicyHistoryPages.js +4 -2
  104. package/internal/api-client/projectionPolicyHistoryPages.js.map +1 -1
  105. package/internal/api-client/routes/blobs/blobDownloadBody.js +65 -0
  106. package/internal/api-client/routes/blobs/blobDownloadBody.js.map +1 -0
  107. package/internal/api-client/routes/blobs/get.js +9 -67
  108. package/internal/api-client/routes/blobs/get.js.map +1 -1
  109. package/internal/api-client/routes/blobs/multipartUpload.js +1 -1
  110. package/internal/api-client/routes/blobs/multipartUpload.js.map +1 -1
  111. package/internal/api-client/sessionRefresh.js +1 -1
  112. package/internal/api-client/sessionRefresh.js.map +1 -1
  113. package/internal/api-client/sessionRenewal.d.ts +31 -0
  114. package/internal/api-client/sessionRenewal.js +91 -6
  115. package/internal/api-client/sessionRenewal.js.map +1 -1
  116. package/internal/api-client/sessionRequestInit.js +22 -0
  117. package/internal/api-client/sessionRequestInit.js.map +1 -0
  118. package/internal/api-client/sessionResponse.js +39 -0
  119. package/internal/api-client/sessionResponse.js.map +1 -0
  120. package/internal/api-client/types.d.ts +1 -0
  121. package/internal/api-client/types.js.map +1 -1
  122. package/internal/api-client/webSocketTickets.d.ts +1 -0
  123. package/internal/api-client/webSocketTickets.js +4 -0
  124. package/internal/api-client/webSocketTickets.js.map +1 -1
  125. package/internal/sqlite-worker/client.d.ts +1 -1
  126. package/internal/sqlite-worker/client.js +6 -1
  127. package/internal/sqlite-worker/client.js.map +1 -1
  128. package/internal/sqlite-worker/purgeOpfsDatabase.d.ts +1 -1
  129. package/internal/sqlite-worker/purgeOpfsDatabase.js +3 -2
  130. package/internal/sqlite-worker/purgeOpfsDatabase.js.map +1 -1
  131. package/internal/sqlite-worker/types.d.ts +4 -0
  132. package/internal/sqlite-worker/types.js.map +1 -1
  133. package/package.json +1 -1
  134. package/sqlite/worker.js +1 -1
  135. package/workflows/documents/attachments/blobMutationLock.d.ts +1 -1
  136. package/workflows/documents/attachments/blobMutationLock.js +2 -2
  137. package/workflows/documents/attachments/blobMutationLock.js.map +1 -1
  138. package/workflows/organizations/readModel/readModelProjection.js +2 -0
  139. package/workflows/organizations/readModel/readModelProjection.js.map +1 -1
  140. package/workflows/registration/registerIdentity.js +2 -0
  141. package/workflows/registration/registerIdentity.js.map +1 -1
@@ -1 +1 @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AED;;;;GAIG;AACH,MAAM,UAAU,iCAAiC,CAC/C,IAAsD;IAEtD,MAAM,KAAK,GAAG,qBAAqB,CACjC,mBAAmB,CAAC;QAClB,aAAa,EAAE,IAAI;QACnB,MAAM,EAAE,sBAAsB,CAAC,IAAI,CAAC;QACpC,UAAU,EAAE,qBAAqB;KAClC,CAAC,CACH,CAAC;IACF,IAAI,KAAK;QAAE,MAAM,KAAK,CAAC;AACzB,CAAC","sourcesContent":["import {\n type ExecSql,\n hasCompletedConnectionOnce,\n markCompletedConnectionOnce,\n runSerializedSqlMutation,\n} from \"../sqlExec\";\nimport {\n assertLocalSchemaMigrations,\n type LocalSchemaMigration,\n type LocalSchemaMigrationContext,\n type LocalSchemaStep,\n localSchemaMigrations,\n} from \"./localSchemaMigrations\";\nimport {\n classifyLocalSchema,\n type LocalSchemaState,\n localSchemaStateError,\n parseLocalSchemaLedger,\n} from \"./localSchemaState\";\n\n/** The ledger table; a local backup carries it like any other table. */\nexport const LOCAL_SCHEMA_MIGRATIONS_TABLE = \"local_schema_migrations\";\n\nconst LEDGER_DDL = `CREATE TABLE IF NOT EXISTS \"${LOCAL_SCHEMA_MIGRATIONS_TABLE}\" (\"version\" INTEGER PRIMARY KEY NOT NULL, \"name\" TEXT NOT NULL, \"applied_at\" INTEGER NOT NULL)`;\nconst SAVEPOINT = \"local_schema_migration\";\nconst ENSURE_KEY = \"local-schema-migrations\";\n\ntype VerifyLocalSchema = (execSql: ExecSql) => Promise<void>;\n\ninterface MigrateLocalSchemaOptions {\n readonly migrations?: ReadonlyArray<LocalSchemaMigration>;\n readonly now?: () => number;\n /**\n * Runs after the steps, before they commit: a throw undoes every step and\n * ledger row, so a refused database is left exactly as it was found.\n */\n readonly verify?: VerifyLocalSchema;\n /** The caller already holds {@link withLocalSchemaMigrationLock}. */\n readonly crossTabLockHeld?: boolean;\n}\n\n// Whether the ledger exists and whether any other user table does: a\n// database with neither is fresh, one with only the latter predates the\n// ledger. A database that already has the ledger costs one more read.\nasync function readLocalSchema(execSql: ExecSql): Promise<{\n readonly ledger: LocalSchemaStep[] | null;\n readonly hasUserTables: boolean;\n}> {\n const [catalog] = await execSql(\n `SELECT\n coalesce(sum(lower(name) = ?), 0) AS ledger_tables,\n coalesce(sum(lower(name) <> ?), 0) AS user_tables\n FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`,\n [LOCAL_SCHEMA_MIGRATIONS_TABLE, LOCAL_SCHEMA_MIGRATIONS_TABLE],\n );\n const { ledger_tables: ledgerTables, user_tables: userTables } =\n catalog ?? {};\n const rows =\n Number(ledgerTables) > 0\n ? await execSql(\n `SELECT version, name FROM \"${LOCAL_SCHEMA_MIGRATIONS_TABLE}\"`,\n )\n : [];\n return {\n hasUserTables: Number(userTables) > 0,\n ledger: parseLocalSchemaLedger(rows),\n };\n}\n\n// Inlined rather than bound, so one worker message carries the ledger DDL and\n// its rows: versions are integers and step names are checked snake_case.\nfunction recordStepsSql(\n steps: ReadonlyArray<LocalSchemaStep>,\n appliedAt: number,\n): string[] {\n if (steps.length === 0) return [];\n const values = steps.map(({ name, version }) => {\n if (!/^[a-z0-9_]+$/.test(name) || !Number.isSafeInteger(version)) {\n throw new Error(`Local schema step ${version} cannot be recorded`);\n }\n return `(${version}, '${name}', ${Math.trunc(appliedAt)})`;\n });\n return [\n `INSERT INTO \"${LOCAL_SCHEMA_MIGRATIONS_TABLE}\" (version, name, applied_at) VALUES ${values.join(\", \")}`,\n ];\n}\n\nfunction migrationContext(execSql: ExecSql): LocalSchemaMigrationContext {\n return {\n hasTable: async (name) =>\n (\n await execSql(\n \"SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?\",\n [name],\n )\n ).length > 0,\n };\n}\n\n// Runs the pending steps in a savepoint: a throw from a step or from `verify`\n// rolls back every step and ledger row of this run.\nasync function applyPendingSteps(\n execSql: ExecSql,\n state: Extract<LocalSchemaState, { status: \"legacy\" | \"behind\" }>,\n now: () => number,\n verify: VerifyLocalSchema,\n): Promise<void> {\n const baseline = state.status === \"legacy\" ? state.record : [];\n try {\n // Inside the try: a conflicting baseline row (another connection recorded\n // it first) must still roll back and release this savepoint.\n await execSql(\n [\n `SAVEPOINT ${SAVEPOINT}`,\n LEDGER_DDL,\n ...recordStepsSql(baseline, now()),\n ].join(\";\\n\"),\n );\n const context = migrationContext(execSql);\n for (const migration of state.pending) {\n await migration.up(execSql, context);\n await execSql(recordStepsSql([migration], now()).join(\"\"));\n }\n await verify(execSql);\n await execSql(`RELEASE SAVEPOINT ${SAVEPOINT}`);\n } catch (error) {\n await execSql(`ROLLBACK TO SAVEPOINT ${SAVEPOINT}`).catch(() => undefined);\n await execSql(`RELEASE SAVEPOINT ${SAVEPOINT}`).catch(() => undefined);\n throw error;\n }\n}\n\nasync function applyLocalSchemaState(\n execSql: ExecSql,\n state: LocalSchemaState,\n now: () => number,\n verify: VerifyLocalSchema,\n): Promise<void> {\n if (state.status === \"fresh\") {\n // No user tables yet, so there is nothing to roll back and `verify` has\n // no table to refuse: the ledger and its rows travel in one message.\n await execSql(\n [LEDGER_DDL, ...recordStepsSql(state.record, now())].join(\";\\n\"),\n );\n await verify(execSql);\n return;\n }\n if (state.status === \"legacy\" || state.status === \"behind\") {\n await applyPendingSteps(execSql, state, now, verify);\n }\n}\n\nconst CROSS_TAB_MIGRATION_LOCK = \"tearleads-local-schema-migration\";\n\nfunction webLocks(): LockManager | null {\n if (typeof navigator !== \"object\" || navigator === null) return null;\n const { locks } = navigator;\n return typeof locks?.request === \"function\" ? locks : null;\n}\n\n/**\n * Holds the cross-tab migration lock while `run` executes. Browser tabs share\n * one worker handle but not their mutation queues, so a tab could read another\n * tab's uncommitted ledger as current and write rows that tab's rollback then\n * deletes; every migration check waits on this Web Lock. A caller that\n * rewrites the schema in its own transaction (a backup restore) holds it from\n * BEGIN through COMMIT and passes `crossTabLockHeld` to the migration it runs\n * inside. Take the connection's mutation lock first. Hosts without Web Locks\n * have no second tab on the handle.\n */\nexport function withLocalSchemaMigrationLock<T>(\n run: () => Promise<T>,\n): Promise<T> {\n const locks = webLocks();\n return locks ? locks.request(CROSS_TAB_MIGRATION_LOCK, run) : run();\n}\n\nfunction runUnderHeldLock<T>(run: () => Promise<T>): Promise<T> {\n return run();\n}\n\n/**\n * Brings the local database to this build's schema version. Pending steps,\n * their ledger rows, and `verify` commit together or not at all; a database\n * written by a newer build, or with a foreign history, is refused before any\n * change. Another connection that migrates first wins: a run that fails\n * because the ledger is already complete accepts it.\n */\nexport async function migrateLocalSchema(\n execSql: ExecSql,\n options: MigrateLocalSchemaOptions = {},\n): Promise<LocalSchemaState> {\n const migrations = options.migrations ?? localSchemaMigrations;\n const now = options.now ?? Date.now;\n const verify = options.verify ?? (async () => {});\n assertLocalSchemaMigrations(migrations);\n const withLock = options.crossTabLockHeld\n ? runUnderHeldLock\n : withLocalSchemaMigrationLock;\n // The connection's mutation lock first, then the Web Lock: a table ensure\n // already holds the former when it migrates, so the reverse order could\n // deadlock against a direct call on the same connection.\n return runSerializedSqlMutation(execSql, (lockedExecSql) =>\n withLock(async () => {\n const read = async () =>\n classifyLocalSchema({\n ...(await readLocalSchema(lockedExecSql)),\n migrations,\n });\n const state = await read();\n const error = localSchemaStateError(state);\n if (error) throw error;\n if (state.status === \"current\") {\n await verify(lockedExecSql);\n return state;\n }\n try {\n await applyLocalSchemaState(lockedExecSql, state, now, verify);\n return state;\n } catch (applyError) {\n const settled = await read().catch(() => null);\n if (settled?.status !== \"current\") throw applyError;\n await verify(lockedExecSql);\n return settled;\n }\n }),\n );\n}\n\n/**\n * Runs {@link migrateLocalSchema} once per connection, then `verify` on every\n * call. Every table ensure calls it first, so no feature reads or creates a\n * table before the database reaches this build's version, and an ensure that\n * refuses the migrated shape leaves no ledger or step behind.\n * `resetConnectionSchemaMemo` (a backup restore) makes the next ensure\n * migrate again.\n */\nexport async function ensureLocalSchemaMigrated(\n execSql: ExecSql,\n verify: VerifyLocalSchema = async () => {},\n): Promise<void> {\n if (hasCompletedConnectionOnce(execSql, ENSURE_KEY)) {\n await verify(execSql);\n return;\n }\n await migrateLocalSchema(execSql, { verify });\n markCompletedConnectionOnce(execSql, ENSURE_KEY);\n}\n\n/**\n * Refuses ledger rows (a backup's copy of the ledger table) that this build\n * could not open: a newer version or a foreign history. No rows means the\n * backup predates the ledger and restores at the baseline.\n */\nexport function assertRestorableLocalSchemaLedger(\n rows: ReadonlyArray<Readonly<Record<string, unknown>>>,\n): void {\n const error = localSchemaStateError(\n classifyLocalSchema({\n hasUserTables: true,\n ledger: parseLocalSchemaLedger(rows),\n migrations: localSchemaMigrations,\n }),\n );\n if (error) throw error;\n}\n"]}
1
+ {"version":3,"file":"migrateLocalSchema.js","sourceRoot":"","sources":["migrateLocalSchema.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,0BAA0B,EAC1B,2BAA2B,EAC3B,oBAAoB,EACpB,wBAAwB,GACzB,MAAM,YAAY,CAAC;AACpB,OAAO,EACL,2BAA2B,EAI3B,qBAAqB,GACtB,MAAM,yBAAyB,CAAC;AACjC,OAAO,EACL,mBAAmB,EAEnB,qBAAqB,EACrB,sBAAsB,GACvB,MAAM,oBAAoB,CAAC;AAE5B,wEAAwE;AACxE,MAAM,CAAC,MAAM,6BAA6B,GAAG,yBAAyB,CAAC;AAEvE,MAAM,UAAU,GAAG,+BAA+B,6BAA6B,iGAAiG,CAAC;AACjL,MAAM,SAAS,GAAG,wBAAwB,CAAC;AAC3C,MAAM,UAAU,GAAG,yBAAyB,CAAC;AAgB7C,qEAAqE;AACrE,wEAAwE;AACxE,sEAAsE;AACtE,KAAK,UAAU,eAAe,CAAC,OAAgB;IAI7C,MAAM,CAAC,OAAO,CAAC,GAAG,MAAM,OAAO,CAC7B;;;0EAGsE,EACtE,CAAC,6BAA6B,EAAE,6BAA6B,CAAC,CAC/D,CAAC;IACF,MAAM,EAAE,aAAa,EAAE,YAAY,EAAE,WAAW,EAAE,UAAU,EAAE,GAC5D,OAAO,IAAI,EAAE,CAAC;IAChB,MAAM,IAA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AA4B,KAAK,IAAI,EAAE,GAAE,CAAC;IAE1C,IAAI,0BAA0B,CAAC,OAAO,EAAE,UAAU,CAAC,EAAE,CAAC;QACpD,MAAM,MAAM,CAAC,OAAO,CAAC,CAAC;QACtB,OAAO;IACT,CAAC;IACD,MAAM,kBAAkB,CAAC,OAAO,EAAE,EAAE,MAAM,EAAE,CAAC,CAAC;IAC9C,2BAA2B,CAAC,OAAO,EAAE,UAAU,CAAC,CAAC;AACnD,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,iCAAiC,CAC/C,IAAsD;IAEtD,MAAM,KAAK,GAAG,qBAAqB,CACjC,mBAAmB,CAAC;QAClB,aAAa,EAAE,IAAI;QACnB,MAAM,EAAE,sBAAsB,CAAC,IAAI,CAAC;QACpC,UAAU,EAAE,qBAAqB;KAClC,CAAC,CACH,CAAC;IACF,IAAI,KAAK;QAAE,MAAM,KAAK,CAAC;AACzB,CAAC","sourcesContent":["import {\n type ExecSql,\n hasCompletedConnectionOnce,\n markCompletedConnectionOnce,\n rollbackSqlSavepoint,\n runSerializedSqlMutation,\n} from \"../sqlExec\";\nimport {\n assertLocalSchemaMigrations,\n type LocalSchemaMigration,\n type LocalSchemaMigrationContext,\n type LocalSchemaStep,\n localSchemaMigrations,\n} from \"./localSchemaMigrations\";\nimport {\n classifyLocalSchema,\n type LocalSchemaState,\n localSchemaStateError,\n parseLocalSchemaLedger,\n} from \"./localSchemaState\";\n\n/** The ledger table; a local backup carries it like any other table. */\nexport const LOCAL_SCHEMA_MIGRATIONS_TABLE = \"local_schema_migrations\";\n\nconst LEDGER_DDL = `CREATE TABLE IF NOT EXISTS \"${LOCAL_SCHEMA_MIGRATIONS_TABLE}\" (\"version\" INTEGER PRIMARY KEY NOT NULL, \"name\" TEXT NOT NULL, \"applied_at\" INTEGER NOT NULL)`;\nconst SAVEPOINT = \"local_schema_migration\";\nconst ENSURE_KEY = \"local-schema-migrations\";\n\ntype VerifyLocalSchema = (execSql: ExecSql) => Promise<void>;\n\ninterface MigrateLocalSchemaOptions {\n readonly migrations?: ReadonlyArray<LocalSchemaMigration>;\n readonly now?: () => number;\n /**\n * Runs after the steps, before they commit: a throw undoes every step and\n * ledger row, so a refused database is left exactly as it was found.\n */\n readonly verify?: VerifyLocalSchema;\n /** The caller already holds {@link withLocalSchemaMigrationLock}. */\n readonly crossTabLockHeld?: boolean;\n}\n\n// Whether the ledger exists and whether any other user table does: a\n// database with neither is fresh, one with only the latter predates the\n// ledger. A database that already has the ledger costs one more read.\nasync function readLocalSchema(execSql: ExecSql): Promise<{\n readonly ledger: LocalSchemaStep[] | null;\n readonly hasUserTables: boolean;\n}> {\n const [catalog] = await execSql(\n `SELECT\n coalesce(sum(lower(name) = ?), 0) AS ledger_tables,\n coalesce(sum(lower(name) <> ?), 0) AS user_tables\n FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`,\n [LOCAL_SCHEMA_MIGRATIONS_TABLE, LOCAL_SCHEMA_MIGRATIONS_TABLE],\n );\n const { ledger_tables: ledgerTables, user_tables: userTables } =\n catalog ?? {};\n const rows =\n Number(ledgerTables) > 0\n ? await execSql(\n `SELECT version, name FROM \"${LOCAL_SCHEMA_MIGRATIONS_TABLE}\"`,\n )\n : [];\n return {\n hasUserTables: Number(userTables) > 0,\n ledger: parseLocalSchemaLedger(rows),\n };\n}\n\n// Inlined rather than bound, so one worker message carries the ledger DDL and\n// its rows: versions are integers and step names are checked snake_case.\nfunction recordStepsSql(\n steps: ReadonlyArray<LocalSchemaStep>,\n appliedAt: number,\n): string[] {\n if (steps.length === 0) return [];\n const values = steps.map(({ name, version }) => {\n if (!/^[a-z0-9_]+$/.test(name) || !Number.isSafeInteger(version)) {\n throw new Error(`Local schema step ${version} cannot be recorded`);\n }\n return `(${version}, '${name}', ${Math.trunc(appliedAt)})`;\n });\n return [\n `INSERT INTO \"${LOCAL_SCHEMA_MIGRATIONS_TABLE}\" (version, name, applied_at) VALUES ${values.join(\", \")}`,\n ];\n}\n\nfunction migrationContext(execSql: ExecSql): LocalSchemaMigrationContext {\n return {\n hasTable: async (name) =>\n (\n await execSql(\n \"SELECT 1 AS present FROM sqlite_master WHERE type = 'table' AND name = ?\",\n [name],\n )\n ).length > 0,\n };\n}\n\n// Runs the pending steps in a savepoint: a throw from a step or from `verify`\n// rolls back every step and ledger row of this run.\nasync function applyPendingSteps(\n execSql: ExecSql,\n state: Extract<LocalSchemaState, { status: \"legacy\" | \"behind\" }>,\n now: () => number,\n verify: VerifyLocalSchema,\n): Promise<void> {\n const baseline = state.status === \"legacy\" ? state.record : [];\n try {\n // Inside the try: a conflicting baseline row (another connection recorded\n // it first) must still roll back and release this savepoint.\n await execSql(\n [\n `SAVEPOINT ${SAVEPOINT}`,\n LEDGER_DDL,\n ...recordStepsSql(baseline, now()),\n ].join(\";\\n\"),\n );\n const context = migrationContext(execSql);\n for (const migration of state.pending) {\n await migration.up(execSql, context);\n await execSql(recordStepsSql([migration], now()).join(\"\"));\n }\n await verify(execSql);\n await execSql(`RELEASE SAVEPOINT ${SAVEPOINT}`);\n } catch (error) {\n await rollbackSqlSavepoint(execSql, SAVEPOINT).catch(() => undefined);\n throw error;\n }\n}\n\nasync function applyLocalSchemaState(\n execSql: ExecSql,\n state: LocalSchemaState,\n now: () => number,\n verify: VerifyLocalSchema,\n): Promise<void> {\n if (state.status === \"fresh\") {\n // No user tables yet, so there is nothing to roll back and `verify` has\n // no table to refuse: the ledger and its rows travel in one message.\n await execSql(\n [LEDGER_DDL, ...recordStepsSql(state.record, now())].join(\";\\n\"),\n );\n await verify(execSql);\n return;\n }\n if (state.status === \"legacy\" || state.status === \"behind\") {\n await applyPendingSteps(execSql, state, now, verify);\n }\n}\n\nconst CROSS_TAB_MIGRATION_LOCK = \"tearleads-local-schema-migration\";\n\nfunction webLocks(): LockManager | null {\n if (typeof navigator !== \"object\" || navigator === null) return null;\n const { locks } = navigator;\n return typeof locks?.request === \"function\" ? locks : null;\n}\n\n/**\n * Holds the cross-tab migration lock while `run` executes. Browser tabs share\n * one worker handle but not their mutation queues, so a tab could read another\n * tab's uncommitted ledger as current and write rows that tab's rollback then\n * deletes; every migration check waits on this Web Lock. A caller that\n * rewrites the schema in its own transaction (a backup restore) holds it from\n * BEGIN through COMMIT and passes `crossTabLockHeld` to the migration it runs\n * inside. Take the connection's mutation lock first. Hosts without Web Locks\n * have no second tab on the handle.\n */\nexport function withLocalSchemaMigrationLock<T>(\n run: () => Promise<T>,\n): Promise<T> {\n const locks = webLocks();\n return locks ? locks.request(CROSS_TAB_MIGRATION_LOCK, run) : run();\n}\n\nfunction runUnderHeldLock<T>(run: () => Promise<T>): Promise<T> {\n return run();\n}\n\n/**\n * Brings the local database to this build's schema version. Pending steps,\n * their ledger rows, and `verify` commit together or not at all; a database\n * written by a newer build, or with a foreign history, is refused before any\n * change. Another connection that migrates first wins: a run that fails\n * because the ledger is already complete accepts it.\n */\nexport async function migrateLocalSchema(\n execSql: ExecSql,\n options: MigrateLocalSchemaOptions = {},\n): Promise<LocalSchemaState> {\n const migrations = options.migrations ?? localSchemaMigrations;\n const now = options.now ?? Date.now;\n const verify = options.verify ?? (async () => {});\n assertLocalSchemaMigrations(migrations);\n const withLock = options.crossTabLockHeld\n ? runUnderHeldLock\n : withLocalSchemaMigrationLock;\n // The connection's mutation lock first, then the Web Lock: a table ensure\n // already holds the former when it migrates, so the reverse order could\n // deadlock against a direct call on the same connection.\n return runSerializedSqlMutation(execSql, (lockedExecSql) =>\n withLock(async () => {\n const read = async () =>\n classifyLocalSchema({\n ...(await readLocalSchema(lockedExecSql)),\n migrations,\n });\n const state = await read();\n const error = localSchemaStateError(state);\n if (error) throw error;\n if (state.status === \"current\") {\n await verify(lockedExecSql);\n return state;\n }\n try {\n await applyLocalSchemaState(lockedExecSql, state, now, verify);\n return state;\n } catch (applyError) {\n const settled = await read().catch(() => null);\n if (settled?.status !== \"current\") throw applyError;\n await verify(lockedExecSql);\n return settled;\n }\n }),\n );\n}\n\n/**\n * Runs {@link migrateLocalSchema} once per connection, then `verify` on every\n * call. Every table ensure calls it first, so no feature reads or creates a\n * table before the database reaches this build's version, and an ensure that\n * refuses the migrated shape leaves no ledger or step behind.\n * `resetConnectionSchemaMemo` (a backup restore) makes the next ensure\n * migrate again.\n */\nexport async function ensureLocalSchemaMigrated(\n execSql: ExecSql,\n verify: VerifyLocalSchema = async () => {},\n): Promise<void> {\n if (hasCompletedConnectionOnce(execSql, ENSURE_KEY)) {\n await verify(execSql);\n return;\n }\n await migrateLocalSchema(execSql, { verify });\n markCompletedConnectionOnce(execSql, ENSURE_KEY);\n}\n\n/**\n * Refuses ledger rows (a backup's copy of the ledger table) that this build\n * could not open: a newer version or a foreign history. No rows means the\n * backup predates the ledger and restores at the baseline.\n */\nexport function assertRestorableLocalSchemaLedger(\n rows: ReadonlyArray<Readonly<Record<string, unknown>>>,\n): void {\n const error = localSchemaStateError(\n classifyLocalSchema({\n hasUserTables: true,\n ledger: parseLocalSchemaLedger(rows),\n migrations: localSchemaMigrations,\n }),\n );\n if (error) throw error;\n}\n"]}
@@ -25,6 +25,9 @@ export interface ExecSqlClientLike {
25
25
  }
26
26
  export declare const unavailableExecSql: ExecSql;
27
27
  export declare function resolveCanonicalExecSql(execSql: ExecSql): ExecSql;
28
+ export declare function createScopedExecSql(execSql: ExecSql, assertCurrent: () => void): ExecSql;
29
+ /** Identity only: coordination spanning sign-ins must share one physical lock. */
30
+ export declare function sqlConnectionIdentity(execSql: ExecSql): object;
28
31
  export declare function hasCompletedConnectionOnce(execSql: ExecSql, key: string): boolean;
29
32
  export declare function markCompletedConnectionOnce(execSql: ExecSql, key: string): void;
30
33
  /**
@@ -48,4 +51,7 @@ export declare function runOncePerConnection(execSql: ExecSql, key: string, run:
48
51
  */
49
52
  export declare function resetConnectionSchemaMemo(execSql: ExecSql): void;
50
53
  export declare function createExecSql(client: ExecSqlClientLike): ExecSql;
54
+ /** Unwind an open savepoint even after its owning sign-in expired. Only
55
+ * release it after rollback succeeded: a standalone RELEASE would commit. */
56
+ export declare function rollbackSqlSavepoint(locked: ExecSql, name: "local_schema_migration" | `runtime_transaction_sp_${number}`): Promise<void>;
51
57
  export declare function runSerializedSqlMutation<T>(execSql: ExecSql, operation: (execSql: ExecSql) => Promise<T> | T): Promise<T>;
@@ -18,6 +18,38 @@ const serializedSqlExecCanonicals = new WeakMap();
18
18
  export function resolveCanonicalExecSql(execSql) {
19
19
  return serializedSqlExecCanonicals.get(execSql) ?? execSql;
20
20
  }
21
+ // A sign-in may retire while a transaction waits on the connection. Its
22
+ // executor remains a distinct owner for session caches, but uses the same
23
+ // physical writer queue and schema memo as every sign-in on that database.
24
+ const scopedExecutors = new WeakMap();
25
+ export function createScopedExecSql(execSql, assertCurrent) {
26
+ // A new sign-in can immediately read from the same physical connection.
27
+ // Wait for any previous owner to commit or roll back first.
28
+ let previous = sqlMutationQueue.get(execSql);
29
+ const scoped = defineExecSql(async (sql, bind, options) => {
30
+ if (previous) {
31
+ await previous;
32
+ previous = undefined;
33
+ }
34
+ assertCurrent();
35
+ const rows = await execSql(sql, bind, options);
36
+ // Preserve the acknowledgement for an accepted transaction boundary. Its
37
+ // caller must know it opened a transaction in order to roll it back.
38
+ if (!/^\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\b/i.test(sql))
39
+ assertCurrent();
40
+ return rows;
41
+ });
42
+ scopedExecutors.set(scoped, { connection: execSql, assertCurrent });
43
+ return scoped;
44
+ }
45
+ function connectionOf(execSql) {
46
+ const canonical = resolveCanonicalExecSql(execSql);
47
+ return scopedExecutors.get(canonical)?.connection ?? canonical;
48
+ }
49
+ /** Identity only: coordination spanning sign-ins must share one physical lock. */
50
+ export function sqlConnectionIdentity(execSql) {
51
+ return connectionOf(execSql);
52
+ }
21
53
  // Completed once-per-connection keys (schema ensures).
22
54
  // Only COMPLETED runs are recorded — never in-flight promises — so two lock
23
55
  // contexts racing the same key both run the (idempotent) work instead of one
@@ -30,12 +62,10 @@ const completedConnectionOnceKeys = new WeakMap();
30
62
  // enclosing scope, whose rollback would undo them too.
31
63
  const transactionSchemaMemoScopes = new WeakMap();
32
64
  export function hasCompletedConnectionOnce(execSql, key) {
33
- return (completedConnectionOnceKeys
34
- .get(resolveCanonicalExecSql(execSql))
35
- ?.has(key) ?? false);
65
+ return (completedConnectionOnceKeys.get(connectionOf(execSql))?.has(key) ?? false);
36
66
  }
37
67
  export function markCompletedConnectionOnce(execSql, key) {
38
- const canonical = resolveCanonicalExecSql(execSql);
68
+ const canonical = connectionOf(execSql);
39
69
  const keys = completedConnectionOnceKeys.get(canonical) ?? new Set();
40
70
  if (keys.has(key))
41
71
  return;
@@ -49,7 +79,7 @@ export function markCompletedConnectionOnce(execSql, key) {
49
79
  * with exactly one `closeTransactionSchemaMemoScope`.
50
80
  */
51
81
  export function openTransactionSchemaMemoScope(execSql) {
52
- const canonical = resolveCanonicalExecSql(execSql);
82
+ const canonical = connectionOf(execSql);
53
83
  const scopes = transactionSchemaMemoScopes.get(canonical) ?? [];
54
84
  scopes.push(new Set());
55
85
  transactionSchemaMemoScopes.set(canonical, scopes);
@@ -60,7 +90,7 @@ export function openTransactionSchemaMemoScope(execSql) {
60
90
  * rollback undid; a commit keeps them, handing them to the enclosing scope.
61
91
  */
62
92
  export function closeTransactionSchemaMemoScope(execSql, committed) {
63
- const canonical = resolveCanonicalExecSql(execSql);
93
+ const canonical = connectionOf(execSql);
64
94
  const scopes = transactionSchemaMemoScopes.get(canonical);
65
95
  const scopeKeys = scopes?.pop();
66
96
  if (!scopes || !scopeKeys) {
@@ -96,7 +126,7 @@ export async function runOncePerConnection(execSql, key, run) {
96
126
  * re-runs its schema ensures.
97
127
  */
98
128
  export function resetConnectionSchemaMemo(execSql) {
99
- completedConnectionOnceKeys.delete(resolveCanonicalExecSql(execSql));
129
+ completedConnectionOnceKeys.delete(connectionOf(execSql));
100
130
  }
101
131
  function defineExecSql(run) {
102
132
  async function execSql(sql, bind, options) {
@@ -127,11 +157,28 @@ function createSerializedSqlExec(execSql) {
127
157
  if (isSerializedSqlExec(execSql)) {
128
158
  return execSql;
129
159
  }
130
- const serializedExecSql = defineExecSql(execSql);
160
+ const scope = scopedExecutors.get(execSql);
161
+ const serializedExecSql = defineExecSql((sql, bind, options) => {
162
+ if (!isSerializedSqlExec(serializedExecSql))
163
+ throw new Error("SQLite mutation lock has been released");
164
+ // Drizzle rolls back the outer transaction on its locked handle.
165
+ if (scope && sql.trim().toUpperCase() === "ROLLBACK")
166
+ return scope.connection(sql, bind, options);
167
+ return execSql(sql, bind, options);
168
+ });
131
169
  serializedSqlExecs.add(serializedExecSql);
132
170
  serializedSqlExecCanonicals.set(serializedExecSql, resolveCanonicalExecSql(execSql));
133
171
  return serializedExecSql;
134
172
  }
173
+ /** Unwind an open savepoint even after its owning sign-in expired. Only
174
+ * release it after rollback succeeded: a standalone RELEASE would commit. */
175
+ export async function rollbackSqlSavepoint(locked, name) {
176
+ if (!isSerializedSqlExec(locked))
177
+ throw new Error("Savepoint requires the mutation lock");
178
+ const connection = connectionOf(locked);
179
+ await connection(`ROLLBACK TO SAVEPOINT ${name}`);
180
+ await connection(`RELEASE SAVEPOINT ${name}`);
181
+ }
135
182
  // SQLite transactions are scoped to the shared connection, so we must hold a
136
183
  // connection-level lock across multi-statement mutations to prevent interleaving.
137
184
  // Nested callers must keep passing the provided locked executor. Re-entering
@@ -144,14 +191,15 @@ export async function runSerializedSqlMutation(execSql, operation) {
144
191
  return operation(execSql);
145
192
  }
146
193
  const queuedAtMs = readUserTimingClock();
147
- const previous = sqlMutationQueue.get(execSql);
194
+ const connection = connectionOf(execSql);
195
+ const previous = sqlMutationQueue.get(connection);
148
196
  let releaseCurrent = () => { };
149
197
  const current = new Promise((resolve) => {
150
198
  releaseCurrent = resolve;
151
199
  });
152
200
  const waitForPrevious = (previous ?? Promise.resolve()).catch(() => undefined);
153
201
  const queuedCurrent = waitForPrevious.then(() => current);
154
- sqlMutationQueue.set(execSql, queuedCurrent);
202
+ sqlMutationQueue.set(connection, queuedCurrent);
155
203
  await waitForPrevious;
156
204
  const acquiredAtMs = readUserTimingClock();
157
205
  if (previous) {
@@ -162,17 +210,20 @@ export async function runSerializedSqlMutation(execSql, operation) {
162
210
  track: "SQLite mutation queue",
163
211
  });
164
212
  }
213
+ const locked = createSerializedSqlExec(execSql);
165
214
  let failed = true;
166
215
  try {
167
- const result = await operation(createSerializedSqlExec(execSql));
216
+ scopedExecutors.get(execSql)?.assertCurrent();
217
+ const result = await operation(locked);
168
218
  failed = false;
169
219
  return result;
170
220
  }
171
221
  finally {
222
+ serializedSqlExecs.delete(locked);
172
223
  const releasedAtMs = readUserTimingClock();
173
224
  releaseCurrent();
174
- if (sqlMutationQueue.get(execSql) === queuedCurrent) {
175
- sqlMutationQueue.delete(execSql);
225
+ if (sqlMutationQueue.get(connection) === queuedCurrent) {
226
+ sqlMutationQueue.delete(connection);
176
227
  }
177
228
  recordUserTimingEntry({
178
229
  endMs: releasedAtMs,
@@ -1 +1 @@
1
- {"version":3,"file":"sqlExec.js","sourceRoot":"","sources":["sqlExec.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAkC9B,MAAM,CAAC,MAAM,kBAAkB,GAAY,KAAK,IAAI,EAAE;IACpD,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;AACrD,CAAC,CAAC;AAEF,8EAA8E;AAC9E,gFAAgF;AAChF,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAA0B,CAAC;AAE/D,6EAA6E;AAC7E,wEAAwE;AACxE,MAAM,kBAAkB,GAAG,IAAI,OAAO,EAAW,CAAC;AAElD,wEAAwE;AACxE,uDAAuD;AACvD,MAAM,cAAc,GAAG,IAAI,OAAO,EAA8B,CAAC;AAEjE,8EAA8E;AAC9E,6EAA6E;AAC7E,0BAA0B;AAC1B,MAAM,2BAA2B,GAAG,IAAI,OAAO,EAAoB,CAAC;AAEpE,MAAM,UAAU,uBAAuB,CAAC,OAA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AE,CAAC;IAC3C,IAAI,QAAQ,EAAE,CAAC;QACb,qBAAqB,CAAC;YACpB,KAAK,EAAE,YAAY;YACnB,IAAI,EAAE,sBAAsB;YAC5B,OAAO,EAAE,UAAU;YACnB,KAAK,EAAE,uBAAuB;SAC/B,CAAC,CAAC;IACL,CAAC;IAED,IAAI,MAAM,GAAG,IAAI,CAAC;IAClB,IAAI,CAAC;QACH,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,uBAAuB,CAAC,OAAO,CAAC,CAAC,CAAC;QACjE,MAAM,GAAG,KAAK,CAAC;QACf,OAAO,MAAM,CAAC;IAChB,CAAC;YAAS,CAAC;QACT,MAAM,YAAY,GAAG,mBAAmB,EAAE,CAAC;QAC3C,cAAc,EAAE,CAAC;QACjB,IAAI,gBAAgB,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,aAAa,EAAE,CAAC;YACpD,gBAAgB,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;QACnC,CAAC;QACD,qBAAqB,CAAC;YACpB,KAAK,EAAE,YAAY;YACnB,MAAM;YACN,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,YAAY;YACrB,KAAK,EAAE,kBAAkB;SAC1B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import {\n readUserTimingClock,\n recordUserTimingEntry,\n} from \"../shared/userTiming\";\n\nexport type SqlRowValue = string | number | null;\nexport type SqlRow = Record<string, SqlRowValue>;\nexport type SqlArrayRow = SqlRowValue[];\nexport type SqlBind = Record<string, SqlRowValue> | ReadonlyArray<SqlRowValue>;\nexport type SqlRowMode = \"object\" | \"array\";\n\nexport interface ExecSql {\n (\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: \"object\" },\n ): Promise<SqlRow[]>;\n (\n sql: string,\n bind: SqlBind | undefined,\n options: { rowMode: \"array\" },\n ): Promise<SqlArrayRow[]>;\n (\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: SqlRowMode },\n ): Promise<Array<SqlRow | SqlArrayRow>>;\n}\n\nexport interface ExecSqlClientLike {\n exec(options: {\n sql: string;\n bind?: SqlBind;\n rowMode?: SqlRowMode;\n }): Promise<{ rows: Array<SqlRow | SqlArrayRow> }>;\n}\n\nexport const unavailableExecSql: ExecSql = async () => {\n throw new Error(\"Database client is unavailable.\");\n};\n\n// Tracks the active serialized mutation chain for each canonical SQL executor\n// so callers sharing one connection cannot interleave transactional statements.\nconst sqlMutationQueue = new WeakMap<ExecSql, Promise<void>>();\n\n// Marks executors that already run inside the shared mutation lock so nested\n// callers can reuse the current lock instead of queueing a second time.\nconst serializedSqlExecs = new WeakSet<ExecSql>();\n\n// Reuses one ExecSql adapter per client so all wrappers around the same\n// connection share the same serialized mutation queue.\nconst clientExecSqls = new WeakMap<ExecSqlClientLike, ExecSql>();\n\n// Maps each locked executor back to the canonical executor whose lock it runs\n// under, so per-connection caches key on one stable identity no matter which\n// wrapper a caller holds.\nconst serializedSqlExecCanonicals = new WeakMap<ExecSql, ExecSql>();\n\nexport function resolveCanonicalExecSql(execSql: ExecSql): ExecSql {\n return serializedSqlExecCanonicals.get(execSql) ?? execSql;\n}\n\n// Completed once-per-connection keys (schema ensures).\n// Only COMPLETED runs are recorded — never in-flight promises — so two lock\n// contexts racing the same key both run the (idempotent) work instead of one\n// awaiting a promise that can only settle after the lock the other context is\n// already holding.\nconst completedConnectionOnceKeys = new WeakMap<ExecSql, Set<string>>();\n\n// Keys first completed inside each open transaction scope on a connection,\n// innermost scope last. A rolled-back scope undid that schema work, so it\n// forgets exactly its own keys; a committed savepoint hands its keys to the\n// enclosing scope, whose rollback would undo them too.\nconst transactionSchemaMemoScopes = new WeakMap<ExecSql, Set<string>[]>();\n\nexport function hasCompletedConnectionOnce(\n execSql: ExecSql,\n key: string,\n): boolean {\n return (\n completedConnectionOnceKeys\n .get(resolveCanonicalExecSql(execSql))\n ?.has(key) ?? false\n );\n}\n\nexport function markCompletedConnectionOnce(\n execSql: ExecSql,\n key: string,\n): void {\n const canonical = resolveCanonicalExecSql(execSql);\n const keys = completedConnectionOnceKeys.get(canonical) ?? new Set<string>();\n if (keys.has(key)) return;\n keys.add(key);\n completedConnectionOnceKeys.set(canonical, keys);\n transactionSchemaMemoScopes.get(canonical)?.at(-1)?.add(key);\n}\n\n/**\n * Start recording the once-per-connection keys completed inside a transaction\n * scope (a transaction or one of its savepoints). Every open must be paired\n * with exactly one `closeTransactionSchemaMemoScope`.\n */\nexport function openTransactionSchemaMemoScope(execSql: ExecSql): void {\n const canonical = resolveCanonicalExecSql(execSql);\n const scopes = transactionSchemaMemoScopes.get(canonical) ?? [];\n scopes.push(new Set<string>());\n transactionSchemaMemoScopes.set(canonical, scopes);\n}\n\n/**\n * Close the innermost transaction scope. A rollback forgets only the keys\n * completed inside it, so the next query re-ensures exactly the schema the\n * rollback undid; a commit keeps them, handing them to the enclosing scope.\n */\nexport function closeTransactionSchemaMemoScope(\n execSql: ExecSql,\n committed: boolean,\n): void {\n const canonical = resolveCanonicalExecSql(execSql);\n const scopes = transactionSchemaMemoScopes.get(canonical);\n const scopeKeys = scopes?.pop();\n if (!scopes || !scopeKeys) {\n throw new Error(\"No open transaction schema memo scope to close\");\n }\n if (scopes.length === 0) transactionSchemaMemoScopes.delete(canonical);\n if (committed) {\n const parent = scopes.at(-1);\n for (const key of scopeKeys) parent?.add(key);\n return;\n }\n const completed = completedConnectionOnceKeys.get(canonical);\n for (const key of scopeKeys) completed?.delete(key);\n}\n\n// Completion is recorded as soon as `run` resolves. Inside a runtime\n// transaction the key joins the open schema memo scope, so a later ROLLBACK\n// forgets it; an explicit transaction outside the runtime must instead call\n// `resetConnectionSchemaMemo` after rolling back.\nexport async function runOncePerConnection(\n execSql: ExecSql,\n key: string,\n run: () => Promise<void>,\n): Promise<void> {\n if (hasCompletedConnectionOnce(execSql, key)) {\n return;\n }\n await run();\n markCompletedConnectionOnce(execSql, key);\n}\n\n/**\n * Forget every completed once-per-connection key for this connection. Required\n * after an operation that rebuilds the schema out from under the runtime (the\n * local backup restore drops and recreates all user tables) so the next query\n * re-runs its schema ensures.\n */\nexport function resetConnectionSchemaMemo(execSql: ExecSql): void {\n completedConnectionOnceKeys.delete(resolveCanonicalExecSql(execSql));\n}\n\nfunction defineExecSql(\n run: (\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: SqlRowMode },\n ) => Promise<Array<SqlRow | SqlArrayRow>>,\n): ExecSql {\n function execSql(\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: \"object\" },\n ): Promise<SqlRow[]>;\n function execSql(\n sql: string,\n bind: SqlBind | undefined,\n options: { rowMode: \"array\" },\n ): Promise<SqlArrayRow[]>;\n function execSql(\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: SqlRowMode },\n ): Promise<Array<SqlRow | SqlArrayRow>>;\n async function execSql(\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: SqlRowMode },\n ): Promise<Array<SqlRow | SqlArrayRow>> {\n return run(sql, bind, options);\n }\n\n return execSql;\n}\n\nexport function createExecSql(client: ExecSqlClientLike): ExecSql {\n const existingExecSql = clientExecSqls.get(client);\n if (existingExecSql) {\n return existingExecSql;\n }\n\n const execSql = defineExecSql(async (sql, bind, options) => {\n const result = await client.exec({\n sql,\n ...(bind !== undefined ? { bind } : {}),\n ...(options?.rowMode ? { rowMode: options.rowMode } : {}),\n });\n return result.rows;\n });\n\n clientExecSqls.set(client, execSql);\n return execSql;\n}\n\nfunction isSerializedSqlExec(execSql: ExecSql): boolean {\n return serializedSqlExecs.has(execSql);\n}\n\nfunction createSerializedSqlExec(execSql: ExecSql): ExecSql {\n if (isSerializedSqlExec(execSql)) {\n return execSql;\n }\n\n const serializedExecSql = defineExecSql(execSql);\n serializedSqlExecs.add(serializedExecSql);\n serializedSqlExecCanonicals.set(\n serializedExecSql,\n resolveCanonicalExecSql(execSql),\n );\n return serializedExecSql;\n}\n\n// SQLite transactions are scoped to the shared connection, so we must hold a\n// connection-level lock across multi-statement mutations to prevent interleaving.\n// Nested callers must keep passing the provided locked executor. Re-entering\n// with the original canonical executor will wait on the current mutation and\n// deadlock.\n// Each outermost mutation is drawn on DevTools tracks: time spent queued\n// behind another mutation, then time holding the lock.\nexport async function runSerializedSqlMutation<T>(\n execSql: ExecSql,\n operation: (execSql: ExecSql) => Promise<T> | T,\n): Promise<T> {\n if (isSerializedSqlExec(execSql)) {\n return operation(execSql);\n }\n\n const queuedAtMs = readUserTimingClock();\n const previous = sqlMutationQueue.get(execSql);\n let releaseCurrent = () => {};\n const current = new Promise<void>((resolve) => {\n releaseCurrent = resolve;\n });\n const waitForPrevious = (previous ?? Promise.resolve()).catch(\n () => undefined,\n );\n const queuedCurrent = waitForPrevious.then(() => current);\n\n sqlMutationQueue.set(execSql, queuedCurrent);\n await waitForPrevious;\n const acquiredAtMs = readUserTimingClock();\n if (previous) {\n recordUserTimingEntry({\n endMs: acquiredAtMs,\n name: \"SQLite mutation wait\",\n startMs: queuedAtMs,\n track: \"SQLite mutation queue\",\n });\n }\n\n let failed = true;\n try {\n const result = await operation(createSerializedSqlExec(execSql));\n failed = false;\n return result;\n } finally {\n const releasedAtMs = readUserTimingClock();\n releaseCurrent();\n if (sqlMutationQueue.get(execSql) === queuedCurrent) {\n sqlMutationQueue.delete(execSql);\n }\n recordUserTimingEntry({\n endMs: releasedAtMs,\n failed,\n name: \"SQLite mutation\",\n startMs: acquiredAtMs,\n track: \"SQLite mutations\",\n });\n }\n}\n"]}
1
+ {"version":3,"file":"sqlExec.js","sourceRoot":"","sources":["sqlExec.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,qBAAqB,GACtB,MAAM,sBAAsB,CAAC;AAkC9B,MAAM,CAAC,MAAM,kBAAkB,GAAY,KAAK,IAAI,EAAE;IACpD,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;AACrD,CAAC,CAAC;AAEF,8EAA8E;AAC9E,gFAAgF;AAChF,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAA0B,CAAC;AAE/D,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AAM,GAAG,uBAAuB,CAAC,OAAO,CAAC,CAAC;IAChD,IAAI,MAAM,GAAG,IAAI,CAAC;IAClB,IAAI,CAAC;QACH,eAAe,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,aAAa,EAAE,CAAC;QAC9C,MAAM,MAAM,GAAG,MAAM,SAAS,CAAC,MAAM,CAAC,CAAC;QACvC,MAAM,GAAG,KAAK,CAAC;QACf,OAAO,MAAM,CAAC;IAChB,CAAC;YAAS,CAAC;QACT,kBAAkB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;QAClC,MAAM,YAAY,GAAG,mBAAmB,EAAE,CAAC;QAC3C,cAAc,EAAE,CAAC;QACjB,IAAI,gBAAgB,CAAC,GAAG,CAAC,UAAU,CAAC,KAAK,aAAa,EAAE,CAAC;YACvD,gBAAgB,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;QACtC,CAAC;QACD,qBAAqB,CAAC;YACpB,KAAK,EAAE,YAAY;YACnB,MAAM;YACN,IAAI,EAAE,iBAAiB;YACvB,OAAO,EAAE,YAAY;YACrB,KAAK,EAAE,kBAAkB;SAC1B,CAAC,CAAC;IACL,CAAC;AACH,CAAC","sourcesContent":["import {\n readUserTimingClock,\n recordUserTimingEntry,\n} from \"../shared/userTiming\";\n\nexport type SqlRowValue = string | number | null;\nexport type SqlRow = Record<string, SqlRowValue>;\nexport type SqlArrayRow = SqlRowValue[];\nexport type SqlBind = Record<string, SqlRowValue> | ReadonlyArray<SqlRowValue>;\nexport type SqlRowMode = \"object\" | \"array\";\n\nexport interface ExecSql {\n (\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: \"object\" },\n ): Promise<SqlRow[]>;\n (\n sql: string,\n bind: SqlBind | undefined,\n options: { rowMode: \"array\" },\n ): Promise<SqlArrayRow[]>;\n (\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: SqlRowMode },\n ): Promise<Array<SqlRow | SqlArrayRow>>;\n}\n\nexport interface ExecSqlClientLike {\n exec(options: {\n sql: string;\n bind?: SqlBind;\n rowMode?: SqlRowMode;\n }): Promise<{ rows: Array<SqlRow | SqlArrayRow> }>;\n}\n\nexport const unavailableExecSql: ExecSql = async () => {\n throw new Error(\"Database client is unavailable.\");\n};\n\n// Tracks the active serialized mutation chain for each canonical SQL executor\n// so callers sharing one connection cannot interleave transactional statements.\nconst sqlMutationQueue = new WeakMap<ExecSql, Promise<void>>();\n\n// Marks executors that already run inside the shared mutation lock so nested\n// callers can reuse the current lock instead of queueing a second time.\nconst serializedSqlExecs = new WeakSet<ExecSql>();\n\n// Reuses one ExecSql adapter per client so all wrappers around the same\n// connection share the same serialized mutation queue.\nconst clientExecSqls = new WeakMap<ExecSqlClientLike, ExecSql>();\n\n// Maps each locked executor back to the canonical executor whose lock it runs\n// under, so per-connection caches key on one stable identity no matter which\n// wrapper a caller holds.\nconst serializedSqlExecCanonicals = new WeakMap<ExecSql, ExecSql>();\n\nexport function resolveCanonicalExecSql(execSql: ExecSql): ExecSql {\n return serializedSqlExecCanonicals.get(execSql) ?? execSql;\n}\n\n// A sign-in may retire while a transaction waits on the connection. Its\n// executor remains a distinct owner for session caches, but uses the same\n// physical writer queue and schema memo as every sign-in on that database.\nconst scopedExecutors = new WeakMap<\n ExecSql,\n { connection: ExecSql; assertCurrent: () => void }\n>();\n\nexport function createScopedExecSql(\n execSql: ExecSql,\n assertCurrent: () => void,\n): ExecSql {\n // A new sign-in can immediately read from the same physical connection.\n // Wait for any previous owner to commit or roll back first.\n let previous = sqlMutationQueue.get(execSql);\n const scoped = defineExecSql(async (sql, bind, options) => {\n if (previous) {\n await previous;\n previous = undefined;\n }\n assertCurrent();\n const rows = await execSql(sql, bind, options);\n // Preserve the acknowledgement for an accepted transaction boundary. Its\n // caller must know it opened a transaction in order to roll it back.\n if (!/^\\s*(?:BEGIN|COMMIT|END|ROLLBACK|SAVEPOINT|RELEASE)\\b/i.test(sql))\n assertCurrent();\n return rows;\n });\n scopedExecutors.set(scoped, { connection: execSql, assertCurrent });\n return scoped;\n}\n\nfunction connectionOf(execSql: ExecSql): ExecSql {\n const canonical = resolveCanonicalExecSql(execSql);\n return scopedExecutors.get(canonical)?.connection ?? canonical;\n}\n\n/** Identity only: coordination spanning sign-ins must share one physical lock. */\nexport function sqlConnectionIdentity(execSql: ExecSql): object {\n return connectionOf(execSql);\n}\n\n// Completed once-per-connection keys (schema ensures).\n// Only COMPLETED runs are recorded — never in-flight promises — so two lock\n// contexts racing the same key both run the (idempotent) work instead of one\n// awaiting a promise that can only settle after the lock the other context is\n// already holding.\nconst completedConnectionOnceKeys = new WeakMap<ExecSql, Set<string>>();\n\n// Keys first completed inside each open transaction scope on a connection,\n// innermost scope last. A rolled-back scope undid that schema work, so it\n// forgets exactly its own keys; a committed savepoint hands its keys to the\n// enclosing scope, whose rollback would undo them too.\nconst transactionSchemaMemoScopes = new WeakMap<ExecSql, Set<string>[]>();\n\nexport function hasCompletedConnectionOnce(\n execSql: ExecSql,\n key: string,\n): boolean {\n return (\n completedConnectionOnceKeys.get(connectionOf(execSql))?.has(key) ?? false\n );\n}\n\nexport function markCompletedConnectionOnce(\n execSql: ExecSql,\n key: string,\n): void {\n const canonical = connectionOf(execSql);\n const keys = completedConnectionOnceKeys.get(canonical) ?? new Set<string>();\n if (keys.has(key)) return;\n keys.add(key);\n completedConnectionOnceKeys.set(canonical, keys);\n transactionSchemaMemoScopes.get(canonical)?.at(-1)?.add(key);\n}\n\n/**\n * Start recording the once-per-connection keys completed inside a transaction\n * scope (a transaction or one of its savepoints). Every open must be paired\n * with exactly one `closeTransactionSchemaMemoScope`.\n */\nexport function openTransactionSchemaMemoScope(execSql: ExecSql): void {\n const canonical = connectionOf(execSql);\n const scopes = transactionSchemaMemoScopes.get(canonical) ?? [];\n scopes.push(new Set<string>());\n transactionSchemaMemoScopes.set(canonical, scopes);\n}\n\n/**\n * Close the innermost transaction scope. A rollback forgets only the keys\n * completed inside it, so the next query re-ensures exactly the schema the\n * rollback undid; a commit keeps them, handing them to the enclosing scope.\n */\nexport function closeTransactionSchemaMemoScope(\n execSql: ExecSql,\n committed: boolean,\n): void {\n const canonical = connectionOf(execSql);\n const scopes = transactionSchemaMemoScopes.get(canonical);\n const scopeKeys = scopes?.pop();\n if (!scopes || !scopeKeys) {\n throw new Error(\"No open transaction schema memo scope to close\");\n }\n if (scopes.length === 0) transactionSchemaMemoScopes.delete(canonical);\n if (committed) {\n const parent = scopes.at(-1);\n for (const key of scopeKeys) parent?.add(key);\n return;\n }\n const completed = completedConnectionOnceKeys.get(canonical);\n for (const key of scopeKeys) completed?.delete(key);\n}\n\n// Completion is recorded as soon as `run` resolves. Inside a runtime\n// transaction the key joins the open schema memo scope, so a later ROLLBACK\n// forgets it; an explicit transaction outside the runtime must instead call\n// `resetConnectionSchemaMemo` after rolling back.\nexport async function runOncePerConnection(\n execSql: ExecSql,\n key: string,\n run: () => Promise<void>,\n): Promise<void> {\n if (hasCompletedConnectionOnce(execSql, key)) {\n return;\n }\n await run();\n markCompletedConnectionOnce(execSql, key);\n}\n\n/**\n * Forget every completed once-per-connection key for this connection. Required\n * after an operation that rebuilds the schema out from under the runtime (the\n * local backup restore drops and recreates all user tables) so the next query\n * re-runs its schema ensures.\n */\nexport function resetConnectionSchemaMemo(execSql: ExecSql): void {\n completedConnectionOnceKeys.delete(connectionOf(execSql));\n}\n\nfunction defineExecSql(\n run: (\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: SqlRowMode },\n ) => Promise<Array<SqlRow | SqlArrayRow>>,\n): ExecSql {\n function execSql(\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: \"object\" },\n ): Promise<SqlRow[]>;\n function execSql(\n sql: string,\n bind: SqlBind | undefined,\n options: { rowMode: \"array\" },\n ): Promise<SqlArrayRow[]>;\n function execSql(\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: SqlRowMode },\n ): Promise<Array<SqlRow | SqlArrayRow>>;\n async function execSql(\n sql: string,\n bind?: SqlBind,\n options?: { rowMode?: SqlRowMode },\n ): Promise<Array<SqlRow | SqlArrayRow>> {\n return run(sql, bind, options);\n }\n\n return execSql;\n}\n\nexport function createExecSql(client: ExecSqlClientLike): ExecSql {\n const existingExecSql = clientExecSqls.get(client);\n if (existingExecSql) {\n return existingExecSql;\n }\n\n const execSql = defineExecSql(async (sql, bind, options) => {\n const result = await client.exec({\n sql,\n ...(bind !== undefined ? { bind } : {}),\n ...(options?.rowMode ? { rowMode: options.rowMode } : {}),\n });\n return result.rows;\n });\n\n clientExecSqls.set(client, execSql);\n return execSql;\n}\n\nfunction isSerializedSqlExec(execSql: ExecSql): boolean {\n return serializedSqlExecs.has(execSql);\n}\n\nfunction createSerializedSqlExec(execSql: ExecSql): ExecSql {\n if (isSerializedSqlExec(execSql)) {\n return execSql;\n }\n\n const scope = scopedExecutors.get(execSql);\n const serializedExecSql = defineExecSql((sql, bind, options) => {\n if (!isSerializedSqlExec(serializedExecSql))\n throw new Error(\"SQLite mutation lock has been released\");\n // Drizzle rolls back the outer transaction on its locked handle.\n if (scope && sql.trim().toUpperCase() === \"ROLLBACK\")\n return scope.connection(sql, bind, options);\n return execSql(sql, bind, options);\n });\n serializedSqlExecs.add(serializedExecSql);\n serializedSqlExecCanonicals.set(\n serializedExecSql,\n resolveCanonicalExecSql(execSql),\n );\n return serializedExecSql;\n}\n\n/** Unwind an open savepoint even after its owning sign-in expired. Only\n * release it after rollback succeeded: a standalone RELEASE would commit. */\nexport async function rollbackSqlSavepoint(\n locked: ExecSql,\n name: \"local_schema_migration\" | `runtime_transaction_sp_${number}`,\n): Promise<void> {\n if (!isSerializedSqlExec(locked))\n throw new Error(\"Savepoint requires the mutation lock\");\n const connection = connectionOf(locked);\n await connection(`ROLLBACK TO SAVEPOINT ${name}`);\n await connection(`RELEASE SAVEPOINT ${name}`);\n}\n\n// SQLite transactions are scoped to the shared connection, so we must hold a\n// connection-level lock across multi-statement mutations to prevent interleaving.\n// Nested callers must keep passing the provided locked executor. Re-entering\n// with the original canonical executor will wait on the current mutation and\n// deadlock.\n// Each outermost mutation is drawn on DevTools tracks: time spent queued\n// behind another mutation, then time holding the lock.\nexport async function runSerializedSqlMutation<T>(\n execSql: ExecSql,\n operation: (execSql: ExecSql) => Promise<T> | T,\n): Promise<T> {\n if (isSerializedSqlExec(execSql)) {\n return operation(execSql);\n }\n\n const queuedAtMs = readUserTimingClock();\n const connection = connectionOf(execSql);\n const previous = sqlMutationQueue.get(connection);\n let releaseCurrent = () => {};\n const current = new Promise<void>((resolve) => {\n releaseCurrent = resolve;\n });\n const waitForPrevious = (previous ?? Promise.resolve()).catch(\n () => undefined,\n );\n const queuedCurrent = waitForPrevious.then(() => current);\n\n sqlMutationQueue.set(connection, queuedCurrent);\n await waitForPrevious;\n const acquiredAtMs = readUserTimingClock();\n if (previous) {\n recordUserTimingEntry({\n endMs: acquiredAtMs,\n name: \"SQLite mutation wait\",\n startMs: queuedAtMs,\n track: \"SQLite mutation queue\",\n });\n }\n\n const locked = createSerializedSqlExec(execSql);\n let failed = true;\n try {\n scopedExecutors.get(execSql)?.assertCurrent();\n const result = await operation(locked);\n failed = false;\n return result;\n } finally {\n serializedSqlExecs.delete(locked);\n const releasedAtMs = readUserTimingClock();\n releaseCurrent();\n if (sqlMutationQueue.get(connection) === queuedCurrent) {\n sqlMutationQueue.delete(connection);\n }\n recordUserTimingEntry({\n endMs: releasedAtMs,\n failed,\n name: \"SQLite mutation\",\n startMs: acquiredAtMs,\n track: \"SQLite mutations\",\n });\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  import { drizzle } from "drizzle-orm/sqlite-proxy";
2
2
  import { clientSQLiteSchema } from "./schema/index.js";
3
- import { closeTransactionSchemaMemoScope, openTransactionSchemaMemoScope, } from "./sqlExec.js";
3
+ import { closeTransactionSchemaMemoScope, openTransactionSchemaMemoScope, rollbackSqlSavepoint, } from "./sqlExec.js";
4
4
  import { assertClientSQLiteCommitAllowed, beginClientSQLiteCommitGuards, captureClientSQLiteCommitGuards, clearClientSQLiteCommitGuards, rethrowClientSQLiteCommitGuardFailure, } from "./sqliteCommitGuards.js";
5
5
  import { createExecSql, resolveCanonicalExecSql, runSerializedSqlMutation, } from "./sqlSchema.js";
6
6
  const runtimeByExecSql = new WeakMap();
@@ -97,8 +97,7 @@ async function runNestedSavepointScope(canonical, lockedExecSql, operation) {
97
97
  return result;
98
98
  }
99
99
  catch (error) {
100
- await lockedExecSql(`ROLLBACK TO SAVEPOINT ${savepoint}`).then(discardNestedGuards, () => undefined);
101
- await lockedExecSql(`RELEASE SAVEPOINT ${savepoint}`).catch(() => undefined);
100
+ await rollbackSqlSavepoint(lockedExecSql, savepoint).then(discardNestedGuards, () => undefined);
102
101
  throw error;
103
102
  }
104
103
  finally {
@@ -1 +1 @@
1
- {"version":3,"file":"sqlitePersistenceRuntime.js","sourceRoot":"","sources":["sqlitePersistenceRuntime.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAC9C,OAAO,EACL,+BAA+B,EAC/B,8BAA8B,GAC/B,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,+BAA+B,EAC/B,6BAA6B,EAC7B,+BAA+B,EAC/B,6BAA6B,EAC7B,qCAAqC,GACtC,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACL,aAAa,EAGb,uBAAuB,EACvB,wBAAwB,GAGzB,MAAM,aAAa,CAAC;AAqDrB,MAAM,gBAAgB,GAAG,IAAI,OAAO,EAA2C,CAAC;AAEhF,SAAS,yBAAyB,CAChC,MAAiD;IAEjD,IAAI,MAAM,EAAE,QAAQ,KAAK,WAAW;QAAE,OAAO,iBAAiB,CAAC;IAC/D,IAAI,MAAM,EAAE,QAAQ,KAAK,WAAW;QAAE,OAAO,iBAAiB,CAAC;IAC/D,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,6EAA6E;AAC7E,6EAA6E;AAC7E,yEAAyE;AACzE,0EAA0E;AAC1E,0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UAAU,iCAAiC,CAC/C,OAAgB;IAEhB,OAAO,gBAAgB,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC3E,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,MAAyB;IAEzB,IAAI,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1C,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;QAChC,eAAe,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,iCAAiC,CAAC,OAAO,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import type {\n RemoteCallback,\n SqliteRemoteDatabase,\n} from \"drizzle-orm/sqlite-proxy\";\nimport { drizzle } from \"drizzle-orm/sqlite-proxy\";\nimport { clientSQLiteSchema } from \"./schema\";\nimport {\n closeTransactionSchemaMemoScope,\n openTransactionSchemaMemoScope,\n} from \"./sqlExec\";\nimport {\n assertClientSQLiteCommitAllowed,\n beginClientSQLiteCommitGuards,\n captureClientSQLiteCommitGuards,\n clearClientSQLiteCommitGuards,\n rethrowClientSQLiteCommitGuardFailure,\n} from \"./sqliteCommitGuards\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n resolveCanonicalExecSql,\n runSerializedSqlMutation,\n type SqlArrayRow,\n type SqlRowValue,\n} from \"./sqlSchema\";\n\nexport type ClientSQLiteSchema = typeof clientSQLiteSchema;\nexport type ClientSQLiteDatabase = SqliteRemoteDatabase<ClientSQLiteSchema>;\nexport type ClientSQLiteTransactionConfig = NonNullable<\n Parameters<ClientSQLiteDatabase[\"transaction\"]>[1]\n>;\n/**\n * The handle a runtime transaction callback receives: the transaction's\n * query interface WITHOUT `rollback` (throw instead — every scope maps an\n * exception to its own rollback) and WITHOUT `transaction` (nest by calling\n * `runtime.transaction` again, which scopes to a savepoint). Narrowing the\n * contract here is what lets a nested scope share the connection-backed\n * database handle safely.\n */\nexport type ClientSQLiteTransactionScope = Pick<\n ClientSQLiteDatabase,\n | \"all\"\n | \"delete\"\n | \"get\"\n | \"insert\"\n | \"query\"\n | \"run\"\n | \"select\"\n | \"selectDistinct\"\n | \"update\"\n | \"values\"\n>;\n\nexport interface ClientSQLitePersistenceRuntime {\n db: ClientSQLiteDatabase;\n execSql: ExecSql;\n runMutation<T>(\n operation: (db: ClientSQLiteDatabase) => Promise<T> | T,\n ): Promise<T>;\n transaction<T>(\n operation: (tx: ClientSQLiteTransactionScope) => Promise<T>,\n config?: ClientSQLiteTransactionConfig,\n ): Promise<T>;\n /**\n * A transaction whose commit is gated on a SYNCHRONOUS guard: the guard\n * runs and — when it passes — the COMMIT is dispatched in the same\n * synchronous slice, so no JavaScript (an identity replacement included)\n * can interleave between the decision and the commit dispatch. Resolves\n * with `committed: false` (all writes rolled back) when the guard refuses.\n */\n guardedTransaction<T>(\n operation: (tx: ClientSQLiteTransactionScope) => Promise<T>,\n canCommit: () => boolean,\n config?: ClientSQLiteTransactionConfig,\n ): Promise<{ committed: boolean; result: T | null }>;\n}\n\nconst runtimeByExecSql = new WeakMap<ExecSql, ClientSQLitePersistenceRuntime>();\n\nfunction transactionBeginStatement(\n config: ClientSQLiteTransactionConfig | undefined,\n): \"BEGIN\" | \"BEGIN EXCLUSIVE\" | \"BEGIN IMMEDIATE\" {\n if (config?.behavior === \"immediate\") return \"BEGIN IMMEDIATE\";\n if (config?.behavior === \"exclusive\") return \"BEGIN EXCLUSIVE\";\n return \"BEGIN\";\n}\n\n// One transaction depth per underlying connection (canonical executor), so a\n// runtime.transaction call made while another transaction is already open on\n// the same connection degrades to a SAVEPOINT scope instead of issuing a\n// second BEGIN. Callers inside a serialized mutation get separate runtime\n// instances per locked executor, so the depth cannot live on the runtime.\nconst transactionDepthByCanonicalExecSql = new WeakMap<ExecSql, number>();\n// Sibling nested scopes on one connection must not interleave: SQLite\n// savepoints form a stack, so releasing an earlier savepoint would also\n// release a later sibling started concurrently. Scopes serialize per\n// NESTING DEPTH — siblings share a depth and queue behind each other, while\n// a descendant runs one level deeper and must NOT wait on its own enclosing\n// scope (that wait can never resolve).\nconst nestedScopeChainsByCanonicalExecSql = new WeakMap<\n ExecSql,\n Map<number, Promise<unknown>>\n>();\nconst execSqlByClient = new WeakMap<ExecSqlClientLike, ExecSql>();\n\nfunction toSqlRowValue(value: unknown): SqlRowValue {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === \"string\" || typeof value === \"number\") {\n return value;\n }\n\n if (typeof value === \"boolean\") {\n return value ? 1 : 0;\n }\n\n throw new Error(`Unsupported SQLite bind value: ${String(value)}`);\n}\n\nfunction createRemoteCallback(getExecSql: () => ExecSql): RemoteCallback {\n type RemoteResult = Awaited<ReturnType<RemoteCallback>>;\n\n function getRemoteResult(rows: readonly SqlArrayRow[]): RemoteResult {\n const row = rows[0];\n if (row !== undefined) {\n return { rows: row } satisfies RemoteResult;\n }\n\n // Drizzle's RemoteCallback type requires rows, but sqlite-proxy's get()\n // mapper treats an undefined rows value as \"no row found\".\n return Object.defineProperty({ rows: [] } satisfies RemoteResult, \"rows\", {\n enumerable: true,\n value: undefined,\n });\n }\n\n return async (sql, params, method) => {\n const execSql = getExecSql();\n if (sql.trim().toLowerCase() === \"commit\")\n assertClientSQLiteCommitAllowed(execSql);\n const rows = await execSql(sql, params.map(toSqlRowValue), {\n rowMode: \"array\",\n });\n\n if (method === \"get\") {\n return getRemoteResult(rows);\n }\n\n return { rows } satisfies RemoteResult;\n };\n}\n\nfunction createClientSQLiteDatabase(\n getExecSql: () => ExecSql,\n): ClientSQLiteDatabase {\n return drizzle(createRemoteCallback(getExecSql), {\n schema: clientSQLiteSchema,\n });\n}\n\n// Serialize nested savepoint scopes per connection AND depth: a sibling\n// (same depth) queues behind the previous sibling so their savepoints\n// strictly nest instead of interleaving on the shared stack, while a\n// descendant (called from inside an executing scope, so one level deeper)\n// starts on its own depth's chain and never waits on its unresolved parent.\nasync function runNestedSavepointScope<T>(\n canonical: ExecSql,\n lockedExecSql: ExecSql,\n operation: () => Promise<T>,\n): Promise<T> {\n const depthAtEntry = transactionDepthByCanonicalExecSql.get(canonical) ?? 0;\n const chains =\n nestedScopeChainsByCanonicalExecSql.get(canonical) ??\n new Map<number, Promise<unknown>>();\n nestedScopeChainsByCanonicalExecSql.set(canonical, chains);\n const previous = chains.get(depthAtEntry) ?? Promise.resolve();\n let tracked: Promise<unknown> = Promise.resolve();\n const scope = previous\n .catch(() => undefined)\n .then(async () => {\n const depth = transactionDepthByCanonicalExecSql.get(canonical) ?? 0;\n transactionDepthByCanonicalExecSql.set(canonical, depth + 1);\n const savepoint = `runtime_transaction_sp_${depth}`;\n const discardNestedGuards = captureClientSQLiteCommitGuards(canonical);\n openTransactionSchemaMemoScope(canonical);\n let released = false;\n try {\n await lockedExecSql(`SAVEPOINT ${savepoint}`);\n const result = await operation();\n await lockedExecSql(`RELEASE SAVEPOINT ${savepoint}`);\n released = true;\n return result;\n } catch (error: unknown) {\n await lockedExecSql(`ROLLBACK TO SAVEPOINT ${savepoint}`).then(\n discardNestedGuards,\n () => undefined,\n );\n await lockedExecSql(`RELEASE SAVEPOINT ${savepoint}`).catch(\n () => undefined,\n );\n throw error;\n } finally {\n // The savepoint's rollback undid only the schema it first ensured.\n closeTransactionSchemaMemoScope(canonical, released);\n transactionDepthByCanonicalExecSql.set(canonical, depth);\n if (chains.get(depthAtEntry) === tracked) {\n chains.delete(depthAtEntry);\n }\n }\n });\n tracked = scope.catch(() => undefined);\n chains.set(depthAtEntry, tracked);\n return scope;\n}\n\nfunction createRuntimeForExecSql(\n execSql: ExecSql,\n): ClientSQLitePersistenceRuntime {\n let activeExecSql = execSql;\n const db = createClientSQLiteDatabase(() => activeExecSql);\n\n async function withActiveExecSql<T>(\n nextExecSql: ExecSql,\n operation: () => Promise<T> | T,\n ): Promise<T> {\n const previousExecSql = activeExecSql;\n activeExecSql = nextExecSql;\n\n try {\n return await operation();\n } finally {\n activeExecSql = previousExecSql;\n }\n }\n\n const runtime: ClientSQLitePersistenceRuntime = {\n db,\n execSql,\n runMutation(operation) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n withActiveExecSql(lockedExecSql, () => operation(db)),\n );\n },\n transaction(operation, config) {\n // A caller already inside an open transaction on this connection MUST\n // reach us through the transaction's locked executor (the runtime that\n // executor resolves to detects the open transaction below and joins it\n // as a savepoint scope). Re-entering through the canonical executor\n // queues here for full isolation — the contract every persistence\n // helper follows by passing its received locked executor down.\n const canonical = resolveCanonicalExecSql(execSql);\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n withActiveExecSql(lockedExecSql, async () => {\n if ((transactionDepthByCanonicalExecSql.get(canonical) ?? 0) > 0) {\n return runNestedSavepointScope(canonical, lockedExecSql, () =>\n operation(db),\n );\n }\n\n transactionDepthByCanonicalExecSql.set(canonical, 1);\n beginClientSQLiteCommitGuards(canonical);\n openTransactionSchemaMemoScope(canonical);\n let committed = false;\n try {\n const result = await db.transaction(operation, config);\n committed = true;\n return result;\n } catch (error: unknown) {\n rethrowClientSQLiteCommitGuardFailure(canonical);\n throw error;\n } finally {\n // A rollback forgets the ensures it undid (see sqlExec).\n closeTransactionSchemaMemoScope(canonical, committed);\n clearClientSQLiteCommitGuards(canonical);\n transactionDepthByCanonicalExecSql.delete(canonical);\n }\n }),\n );\n },\n guardedTransaction(operation, canCommit, config) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n withActiveExecSql(lockedExecSql, async () => {\n const canonical = resolveCanonicalExecSql(execSql);\n if ((transactionDepthByCanonicalExecSql.get(canonical) ?? 0) > 0) {\n throw new Error(\n \"guardedTransaction cannot nest inside an open transaction\",\n );\n }\n\n transactionDepthByCanonicalExecSql.set(canonical, 1);\n beginClientSQLiteCommitGuards(canonical);\n openTransactionSchemaMemoScope(canonical);\n let committed = false;\n try {\n await lockedExecSql(transactionBeginStatement(config));\n const result = await operation(db);\n if (!canCommit()) {\n await lockedExecSql(\"ROLLBACK\");\n return { committed: false, result: null };\n }\n // The guard passed in THIS synchronous slice and the COMMIT is\n // dispatched in the same slice: no JavaScript can run between\n // the two, so the decision cannot go stale before dispatch. (A\n // host tearing the connection down concurrently is resolved by\n // SQLite's own commit atomicity, not by anything client-side.)\n assertClientSQLiteCommitAllowed(lockedExecSql);\n const commit = lockedExecSql(\"COMMIT\");\n await commit;\n committed = true;\n return { committed: true, result };\n } catch (error: unknown) {\n await lockedExecSql(\"ROLLBACK\").catch(() => undefined);\n rethrowClientSQLiteCommitGuardFailure(canonical);\n throw error;\n } finally {\n closeTransactionSchemaMemoScope(canonical, committed);\n clearClientSQLiteCommitGuards(canonical);\n transactionDepthByCanonicalExecSql.delete(canonical);\n }\n }),\n );\n },\n };\n\n runtimeByExecSql.set(execSql, runtime);\n return runtime;\n}\n\nexport function getClientSQLitePersistenceRuntime(\n execSql: ExecSql,\n): ClientSQLitePersistenceRuntime {\n return runtimeByExecSql.get(execSql) ?? createRuntimeForExecSql(execSql);\n}\n\nexport function createClientSQLitePersistenceRuntime(\n client: ExecSqlClientLike,\n): ClientSQLitePersistenceRuntime {\n let execSql = execSqlByClient.get(client);\n if (!execSql) {\n execSql = createExecSql(client);\n execSqlByClient.set(client, execSql);\n }\n\n return getClientSQLitePersistenceRuntime(execSql);\n}\n"]}
1
+ {"version":3,"file":"sqlitePersistenceRuntime.js","sourceRoot":"","sources":["sqlitePersistenceRuntime.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,OAAO,EAAE,MAAM,0BAA0B,CAAC;AACnD,OAAO,EAAE,kBAAkB,EAAE,MAAM,UAAU,CAAC;AAC9C,OAAO,EACL,+BAA+B,EAC/B,8BAA8B,EAC9B,oBAAoB,GACrB,MAAM,WAAW,CAAC;AACnB,OAAO,EACL,+BAA+B,EAC/B,6BAA6B,EAC7B,+BAA+B,EAC/B,6BAA6B,EAC7B,qCAAqC,GACtC,MAAM,sBAAsB,CAAC;AAC9B,OAAO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AC,SAAS,EAAE,SAAS,CAAC,CAAC;oBACtD,6BAA6B,CAAC,SAAS,CAAC,CAAC;oBACzC,kCAAkC,CAAC,MAAM,CAAC,SAAS,CAAC,CAAC;gBACvD,CAAC;YACH,CAAC,CAAC,CACH,CAAC;QACJ,CAAC;KACF,CAAC;IAEF,gBAAgB,CAAC,GAAG,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACvC,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,MAAM,UAAU,iCAAiC,CAC/C,OAAgB;IAEhB,OAAO,gBAAgB,CAAC,GAAG,CAAC,OAAO,CAAC,IAAI,uBAAuB,CAAC,OAAO,CAAC,CAAC;AAC3E,CAAC;AAED,MAAM,UAAU,oCAAoC,CAClD,MAAyB;IAEzB,IAAI,OAAO,GAAG,eAAe,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1C,IAAI,CAAC,OAAO,EAAE,CAAC;QACb,OAAO,GAAG,aAAa,CAAC,MAAM,CAAC,CAAC;QAChC,eAAe,CAAC,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IACvC,CAAC;IAED,OAAO,iCAAiC,CAAC,OAAO,CAAC,CAAC;AACpD,CAAC","sourcesContent":["import type {\n RemoteCallback,\n SqliteRemoteDatabase,\n} from \"drizzle-orm/sqlite-proxy\";\nimport { drizzle } from \"drizzle-orm/sqlite-proxy\";\nimport { clientSQLiteSchema } from \"./schema\";\nimport {\n closeTransactionSchemaMemoScope,\n openTransactionSchemaMemoScope,\n rollbackSqlSavepoint,\n} from \"./sqlExec\";\nimport {\n assertClientSQLiteCommitAllowed,\n beginClientSQLiteCommitGuards,\n captureClientSQLiteCommitGuards,\n clearClientSQLiteCommitGuards,\n rethrowClientSQLiteCommitGuardFailure,\n} from \"./sqliteCommitGuards\";\nimport {\n createExecSql,\n type ExecSql,\n type ExecSqlClientLike,\n resolveCanonicalExecSql,\n runSerializedSqlMutation,\n type SqlArrayRow,\n type SqlRowValue,\n} from \"./sqlSchema\";\n\nexport type ClientSQLiteSchema = typeof clientSQLiteSchema;\nexport type ClientSQLiteDatabase = SqliteRemoteDatabase<ClientSQLiteSchema>;\nexport type ClientSQLiteTransactionConfig = NonNullable<\n Parameters<ClientSQLiteDatabase[\"transaction\"]>[1]\n>;\n/**\n * The handle a runtime transaction callback receives: the transaction's\n * query interface WITHOUT `rollback` (throw instead — every scope maps an\n * exception to its own rollback) and WITHOUT `transaction` (nest by calling\n * `runtime.transaction` again, which scopes to a savepoint). Narrowing the\n * contract here is what lets a nested scope share the connection-backed\n * database handle safely.\n */\nexport type ClientSQLiteTransactionScope = Pick<\n ClientSQLiteDatabase,\n | \"all\"\n | \"delete\"\n | \"get\"\n | \"insert\"\n | \"query\"\n | \"run\"\n | \"select\"\n | \"selectDistinct\"\n | \"update\"\n | \"values\"\n>;\n\nexport interface ClientSQLitePersistenceRuntime {\n db: ClientSQLiteDatabase;\n execSql: ExecSql;\n runMutation<T>(\n operation: (db: ClientSQLiteDatabase) => Promise<T> | T,\n ): Promise<T>;\n transaction<T>(\n operation: (tx: ClientSQLiteTransactionScope) => Promise<T>,\n config?: ClientSQLiteTransactionConfig,\n ): Promise<T>;\n /**\n * A transaction whose commit is gated on a SYNCHRONOUS guard: the guard\n * runs and — when it passes — the COMMIT is dispatched in the same\n * synchronous slice, so no JavaScript (an identity replacement included)\n * can interleave between the decision and the commit dispatch. Resolves\n * with `committed: false` (all writes rolled back) when the guard refuses.\n */\n guardedTransaction<T>(\n operation: (tx: ClientSQLiteTransactionScope) => Promise<T>,\n canCommit: () => boolean,\n config?: ClientSQLiteTransactionConfig,\n ): Promise<{ committed: boolean; result: T | null }>;\n}\n\nconst runtimeByExecSql = new WeakMap<ExecSql, ClientSQLitePersistenceRuntime>();\n\nfunction transactionBeginStatement(\n config: ClientSQLiteTransactionConfig | undefined,\n): \"BEGIN\" | \"BEGIN EXCLUSIVE\" | \"BEGIN IMMEDIATE\" {\n if (config?.behavior === \"immediate\") return \"BEGIN IMMEDIATE\";\n if (config?.behavior === \"exclusive\") return \"BEGIN EXCLUSIVE\";\n return \"BEGIN\";\n}\n\n// One transaction depth per underlying connection (canonical executor), so a\n// runtime.transaction call made while another transaction is already open on\n// the same connection degrades to a SAVEPOINT scope instead of issuing a\n// second BEGIN. Callers inside a serialized mutation get separate runtime\n// instances per locked executor, so the depth cannot live on the runtime.\nconst transactionDepthByCanonicalExecSql = new WeakMap<ExecSql, number>();\n// Sibling nested scopes on one connection must not interleave: SQLite\n// savepoints form a stack, so releasing an earlier savepoint would also\n// release a later sibling started concurrently. Scopes serialize per\n// NESTING DEPTH — siblings share a depth and queue behind each other, while\n// a descendant runs one level deeper and must NOT wait on its own enclosing\n// scope (that wait can never resolve).\nconst nestedScopeChainsByCanonicalExecSql = new WeakMap<\n ExecSql,\n Map<number, Promise<unknown>>\n>();\nconst execSqlByClient = new WeakMap<ExecSqlClientLike, ExecSql>();\n\nfunction toSqlRowValue(value: unknown): SqlRowValue {\n if (value === null || value === undefined) {\n return null;\n }\n\n if (typeof value === \"string\" || typeof value === \"number\") {\n return value;\n }\n\n if (typeof value === \"boolean\") {\n return value ? 1 : 0;\n }\n\n throw new Error(`Unsupported SQLite bind value: ${String(value)}`);\n}\n\nfunction createRemoteCallback(getExecSql: () => ExecSql): RemoteCallback {\n type RemoteResult = Awaited<ReturnType<RemoteCallback>>;\n\n function getRemoteResult(rows: readonly SqlArrayRow[]): RemoteResult {\n const row = rows[0];\n if (row !== undefined) {\n return { rows: row } satisfies RemoteResult;\n }\n\n // Drizzle's RemoteCallback type requires rows, but sqlite-proxy's get()\n // mapper treats an undefined rows value as \"no row found\".\n return Object.defineProperty({ rows: [] } satisfies RemoteResult, \"rows\", {\n enumerable: true,\n value: undefined,\n });\n }\n\n return async (sql, params, method) => {\n const execSql = getExecSql();\n if (sql.trim().toLowerCase() === \"commit\")\n assertClientSQLiteCommitAllowed(execSql);\n const rows = await execSql(sql, params.map(toSqlRowValue), {\n rowMode: \"array\",\n });\n\n if (method === \"get\") {\n return getRemoteResult(rows);\n }\n\n return { rows } satisfies RemoteResult;\n };\n}\n\nfunction createClientSQLiteDatabase(\n getExecSql: () => ExecSql,\n): ClientSQLiteDatabase {\n return drizzle(createRemoteCallback(getExecSql), {\n schema: clientSQLiteSchema,\n });\n}\n\n// Serialize nested savepoint scopes per connection AND depth: a sibling\n// (same depth) queues behind the previous sibling so their savepoints\n// strictly nest instead of interleaving on the shared stack, while a\n// descendant (called from inside an executing scope, so one level deeper)\n// starts on its own depth's chain and never waits on its unresolved parent.\nasync function runNestedSavepointScope<T>(\n canonical: ExecSql,\n lockedExecSql: ExecSql,\n operation: () => Promise<T>,\n): Promise<T> {\n const depthAtEntry = transactionDepthByCanonicalExecSql.get(canonical) ?? 0;\n const chains =\n nestedScopeChainsByCanonicalExecSql.get(canonical) ??\n new Map<number, Promise<unknown>>();\n nestedScopeChainsByCanonicalExecSql.set(canonical, chains);\n const previous = chains.get(depthAtEntry) ?? Promise.resolve();\n let tracked: Promise<unknown> = Promise.resolve();\n const scope = previous\n .catch(() => undefined)\n .then(async () => {\n const depth = transactionDepthByCanonicalExecSql.get(canonical) ?? 0;\n transactionDepthByCanonicalExecSql.set(canonical, depth + 1);\n const savepoint = `runtime_transaction_sp_${depth}` as const;\n const discardNestedGuards = captureClientSQLiteCommitGuards(canonical);\n openTransactionSchemaMemoScope(canonical);\n let released = false;\n try {\n await lockedExecSql(`SAVEPOINT ${savepoint}`);\n const result = await operation();\n await lockedExecSql(`RELEASE SAVEPOINT ${savepoint}`);\n released = true;\n return result;\n } catch (error: unknown) {\n await rollbackSqlSavepoint(lockedExecSql, savepoint).then(\n discardNestedGuards,\n () => undefined,\n );\n throw error;\n } finally {\n // The savepoint's rollback undid only the schema it first ensured.\n closeTransactionSchemaMemoScope(canonical, released);\n transactionDepthByCanonicalExecSql.set(canonical, depth);\n if (chains.get(depthAtEntry) === tracked) {\n chains.delete(depthAtEntry);\n }\n }\n });\n tracked = scope.catch(() => undefined);\n chains.set(depthAtEntry, tracked);\n return scope;\n}\n\nfunction createRuntimeForExecSql(\n execSql: ExecSql,\n): ClientSQLitePersistenceRuntime {\n let activeExecSql = execSql;\n const db = createClientSQLiteDatabase(() => activeExecSql);\n\n async function withActiveExecSql<T>(\n nextExecSql: ExecSql,\n operation: () => Promise<T> | T,\n ): Promise<T> {\n const previousExecSql = activeExecSql;\n activeExecSql = nextExecSql;\n\n try {\n return await operation();\n } finally {\n activeExecSql = previousExecSql;\n }\n }\n\n const runtime: ClientSQLitePersistenceRuntime = {\n db,\n execSql,\n runMutation(operation) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n withActiveExecSql(lockedExecSql, () => operation(db)),\n );\n },\n transaction(operation, config) {\n // A caller already inside an open transaction on this connection MUST\n // reach us through the transaction's locked executor (the runtime that\n // executor resolves to detects the open transaction below and joins it\n // as a savepoint scope). Re-entering through the canonical executor\n // queues here for full isolation — the contract every persistence\n // helper follows by passing its received locked executor down.\n const canonical = resolveCanonicalExecSql(execSql);\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n withActiveExecSql(lockedExecSql, async () => {\n if ((transactionDepthByCanonicalExecSql.get(canonical) ?? 0) > 0) {\n return runNestedSavepointScope(canonical, lockedExecSql, () =>\n operation(db),\n );\n }\n\n transactionDepthByCanonicalExecSql.set(canonical, 1);\n beginClientSQLiteCommitGuards(canonical);\n openTransactionSchemaMemoScope(canonical);\n let committed = false;\n try {\n const result = await db.transaction(operation, config);\n committed = true;\n return result;\n } catch (error: unknown) {\n rethrowClientSQLiteCommitGuardFailure(canonical);\n throw error;\n } finally {\n // A rollback forgets the ensures it undid (see sqlExec).\n closeTransactionSchemaMemoScope(canonical, committed);\n clearClientSQLiteCommitGuards(canonical);\n transactionDepthByCanonicalExecSql.delete(canonical);\n }\n }),\n );\n },\n guardedTransaction(operation, canCommit, config) {\n return runSerializedSqlMutation(execSql, async (lockedExecSql) =>\n withActiveExecSql(lockedExecSql, async () => {\n const canonical = resolveCanonicalExecSql(execSql);\n if ((transactionDepthByCanonicalExecSql.get(canonical) ?? 0) > 0) {\n throw new Error(\n \"guardedTransaction cannot nest inside an open transaction\",\n );\n }\n\n transactionDepthByCanonicalExecSql.set(canonical, 1);\n beginClientSQLiteCommitGuards(canonical);\n openTransactionSchemaMemoScope(canonical);\n let committed = false;\n try {\n await lockedExecSql(transactionBeginStatement(config));\n const result = await operation(db);\n if (!canCommit()) {\n await lockedExecSql(\"ROLLBACK\");\n return { committed: false, result: null };\n }\n // The guard passed in THIS synchronous slice and the COMMIT is\n // dispatched in the same slice: no JavaScript can run between\n // the two, so the decision cannot go stale before dispatch. (A\n // host tearing the connection down concurrently is resolved by\n // SQLite's own commit atomicity, not by anything client-side.)\n assertClientSQLiteCommitAllowed(lockedExecSql);\n const commit = lockedExecSql(\"COMMIT\");\n await commit;\n committed = true;\n return { committed: true, result };\n } catch (error: unknown) {\n await lockedExecSql(\"ROLLBACK\").catch(() => undefined);\n rethrowClientSQLiteCommitGuardFailure(canonical);\n throw error;\n } finally {\n closeTransactionSchemaMemoScope(canonical, committed);\n clearClientSQLiteCommitGuards(canonical);\n transactionDepthByCanonicalExecSql.delete(canonical);\n }\n }),\n );\n },\n };\n\n runtimeByExecSql.set(execSql, runtime);\n return runtime;\n}\n\nexport function getClientSQLitePersistenceRuntime(\n execSql: ExecSql,\n): ClientSQLitePersistenceRuntime {\n return runtimeByExecSql.get(execSql) ?? createRuntimeForExecSql(execSql);\n}\n\nexport function createClientSQLitePersistenceRuntime(\n client: ExecSqlClientLike,\n): ClientSQLitePersistenceRuntime {\n let execSql = execSqlByClient.get(client);\n if (!execSql) {\n execSql = createExecSql(client);\n execSqlByClient.set(client, execSql);\n }\n\n return getClientSQLitePersistenceRuntime(execSql);\n}\n"]}
@@ -234,7 +234,7 @@ export function createTrustedUserIdentityService(input) {
234
234
  },
235
235
  verifyLink: (link) => verifyIdentityLink(dependencies, link),
236
236
  boundUserId: (signingKeyFingerprint) => boundUserId(dependencies, signingKeyFingerprint),
237
- async pinLocal(userId, candidate) {
237
+ async pinLocal(userId, candidate, assertCurrent) {
238
238
  assertTrustedUserIdentityUserId(userId);
239
239
  const { execSql, identityTrustDomain } = requireTrustStore(dependencies);
240
240
  const identity = await validateLocalUserIdentity({
@@ -247,6 +247,7 @@ export function createTrustedUserIdentityService(input) {
247
247
  execSql,
248
248
  identity,
249
249
  provenance: "self",
250
+ assertCurrent,
250
251
  });
251
252
  },
252
253
  resolve: withPinnedIdentityResolution(dependencies, async (userId) => {
@@ -1 +1 @@
1
- {"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,uBAAuB,EAAE,MAAM,mBAAmB,CAAC;AAC5D,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AACpD,OAAO,EACL,kCAAkC,EAClC,mCAAmC,GAEpC,MAAM,qDAAqD,CAAC;AAC7D,OAAO,EAAE,gCAAgC,EAAE,MAAM,0DAA0D,CAAC;AAC5G,OAAO,EAAE,qCAAqC,EAAE,MAAM,2DAA2D,CAAC;AAClH,OAAO,EAAE,wBAAwB,EAAE,MAAM,4CAA4C,CAAC;AAEtF,OAAO,EAAE,2BAA2B,EAAE,MAAM,aAAa,CAAC;AAC1D,OAAO,EACL,yBAAyB,EACzB,kBAAkB,EAClB,iBAAiB,GAClB,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,OAAO,EAAE,sBAAsB,EAAE,MAAM,kBAAkB,CAAC;AACnE,OAAO,EAAE,4BAA4B,EAAE,MAAM,oBAAoB,CAAC;AAClE,OAAO,EAAE,yBAAyB,EAAE,MAAM,yBAAyB,CAAC;AACpE,OAAO,EACL,wBAAwB,EACxB,yCAAyC,EACzC,oCAAoC,EACpC,mCAAmC,GAKpC,MAAM,SAAS,CAAC;AACjB,OAAO,EACL,+BAA+B,EAC/B,yBAAyB,EACzB,0BAA0B,GAC3B,MAAM,cAAc,CAAC;AAEtB,SAAS,kBAAkB,CACzB,YAAoD;IAE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,aAAa,EAAE,CAAC;gBAChB,OAAO,MAAM,WAAW,CAAC;oBACvB,aAAa;oBACb,YAAY;oBACZ,OAAO;oBACP,QAAQ,EAAE,SAAS,CAAC,QAAQ;oBAC5B,UAAU,EAAE,SAAS,CAAC,MAAM;iBAC7B,CAAC,CAAC;YACL,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,YAAY,CAAC,YAAY,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;gBAC7C,MAAM,KAAK,CAAC;YACd,CAAC;QACH,CAAC,EACD;YACE,aAAa,EAAE,CAAC,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAC7C,mBAAmB,CAAC,YAAY,EAAE,MAAM,EAAE,mBAAmB,CAAC;YAChE,WAAW,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,CAClD,sBAAsB,CAAC;gBACrB,aAAa;gBACb,OAAO;gBACP,WAAW,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE;gBAC/D,UAAU;gBACV,UAAU,EAAE,UAAU;aACvB,CAAC;SACL,EACD,OAAO,CACR;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport { DatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** The user this trust store already binds to a signing key, if any. */\nasync function boundUserId(\n dependencies: TrustedUserIdentityServiceDependencies,\n signingKeyFingerprint: string,\n): Promise<string | null> {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return new TrustedUserIdentityPinRepository(\n execSql,\n ).loadTrustedUserIdForSigningKey({\n identityTrustDomain,\n signingKeyFingerprint,\n });\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n boundUserId: (signingKeyFingerprint) =>\n boundUserId(dependencies, signingKeyFingerprint),\n async pinLocal(userId, candidate) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
1
+ {"version":3,"file":"service.js","sourceRoot":"","sources":["service.ts"],"names":[],"m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EAAE,CAAC,MAAM,EAAE,mBAAmB,EAAE,EAAE,CAC7C,mBAAmB,CAAC,YAAY,EAAE,MAAM,EAAE,mBAAmB,CAAC;YAChE,WAAW,EAAE,CAAC,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,EAAE,CAClD,sBAAsB,CAAC;gBACrB,aAAa;gBACb,OAAO;gBACP,WAAW,EAAE,CAAC,YAAY,CAAC,GAAG,EAAE,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC,WAAW,EAAE;gBAC/D,UAAU;gBACV,UAAU,EAAE,UAAU;aACvB,CAAC;SACL,EACD,OAAO,CACR;KACF,CAAC;AACJ,CAAC","sourcesContent":["import { KeyingVerificationError } from \"@tearleads/crypto\";\nimport { bytesToBase64 } from \"@tearleads/encoding\";\nimport {\n TrustedUserIdentityPinCorruptError,\n TrustedUserIdentityPinMismatchError,\n type TrustedUserIdentityPinProvenance,\n} from \"../persistence/identity/trustedUserIdentityPinModel\";\nimport { TrustedUserIdentityPinRepository } from \"../persistence/identity/trustedUserIdentityPinRepository\";\nimport { TrustedUserIdentityPinContentionError } from \"../persistence/identity/trustedUserIdentityPinTransaction\";\nimport { DatabaseUnavailableError } from \"../sqlite/availability/databaseUnavailable\";\nimport type { ExecSql } from \"../sqlite/sqlSchema\";\nimport { UnverifiedUserIdentityError } from \"./admission\";\nimport {\n assertIdentityLinkMatches,\n createIdentityLink,\n parseIdentityLink,\n} from \"./identityLink\";\nimport { loadPin, loadPinnedUserIdentity } from \"./pinnedIdentity\";\nimport { withPinnedIdentityResolution } from \"./pinnedResolution\";\nimport { withStagedIdentityHandoff } from \"./stagedIdentityHandoff\";\nimport {\n brandTrustedUserIdentity,\n TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n type TrustedUserIdentity,\n type TrustedUserIdentityService,\n type TrustedUserIdentityServiceDependencies,\n type ValidatedUserIdentityCandidate,\n} from \"./types\";\nimport {\n assertTrustedUserIdentityUserId,\n validateLocalUserIdentity,\n validateRemoteUserIdentity,\n} from \"./validation\";\n\nfunction requireTrustDomain(\n dependencies: TrustedUserIdentityServiceDependencies,\n): string {\n // A missing trust domain is a static misconfiguration and must stay loud.\n if (!dependencies.identityTrustDomain) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Trusted user identity resolution requires a stable API trust domain\",\n );\n }\n return dependencies.identityTrustDomain;\n}\n\nfunction requireTrustStore(\n dependencies: TrustedUserIdentityServiceDependencies,\n) {\n const identityTrustDomain = requireTrustDomain(dependencies);\n // An absent trust store is not: getExecSql() returns null exactly while the\n // database is not ready, which happens routinely when the runtime is swapped\n // under in-flight sync work. Callers that tolerate a vanishing database\n // discriminate on the error type, so this must not share the code above.\n const execSql = dependencies.getExecSql();\n if (!execSql) {\n throw new DatabaseUnavailableError(\n \"Trusted user identity resolution requires a ready SQLite trust store\",\n );\n }\n return { execSql, identityTrustDomain };\n}\n\nfunction durablePin(\n identity: ValidatedUserIdentityCandidate,\n provenance: TrustedUserIdentityPinProvenance,\n firstSeenAt: string,\n) {\n return {\n encapsulationKeyFingerprint: identity.encapsulationKeyFingerprint,\n encapsulationPublicKey: bytesToBase64(identity.encapsulationPublicKey),\n encapsulationSuite: TRUSTED_USER_IDENTITY_ENCAPSULATION_SUITE,\n firstSeenAt,\n provenance,\n formatVersion: TRUSTED_USER_IDENTITY_FORMAT_VERSION,\n identityTrustDomain: identity.identityTrustDomain,\n signingKeyFingerprint: identity.signingKeyFingerprint,\n signingPublicKey: bytesToBase64(identity.signingPublicKey),\n signingSuite: TRUSTED_USER_IDENTITY_SIGNING_SUITE,\n userId: identity.userId,\n };\n}\n\n/** Compare-or-insert every identity in one transaction: all pin, or none. */\nasync function compareWithDurablePins(input: {\n readonly assertCurrent?: (() => void) | undefined;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly firstSeenAt: string;\n readonly identities: readonly ValidatedUserIdentityCandidate[];\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<void> {\n const userIds = input.identities.map((identity) => identity.userId);\n try {\n await new TrustedUserIdentityPinRepository(\n input.execSql,\n ).compareOrInsertTrustedUserIdentityPins({\n assertCurrent: input.assertCurrent,\n pins: input.identities.map((identity) =>\n durablePin(identity, input.provenance, input.firstSeenAt),\n ),\n });\n } catch (error) {\n if (error instanceof TrustedUserIdentityPinMismatchError) {\n throw new KeyingVerificationError(\n \"equivocation\",\n error.existing.userId !== error.candidate.userId\n ? `Signing key for ${error.candidate.userId} is already bound to ${error.existing.userId}`\n : `Trusted user identity changed for ${error.candidate.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinCorruptError) {\n throw new KeyingVerificationError(\n \"invalid_shape\",\n `Trusted user identity pin is corrupt for ${error.userId}`,\n );\n }\n if (error instanceof TrustedUserIdentityPinContentionError) {\n // Lock contention says nothing about the identity; the caller retries\n // once the trust store is free, so this must not be recordable evidence.\n throw new DatabaseUnavailableError(\n `Trusted user identity pin store is busy for ${userIds.join(\", \")}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * The candidate for `userId` and where it came from: this device's own keys\n * (`self`) or the identity endpoint (`observed`). Provenance follows the\n * source, never the account that happens to be active once a lookup returns.\n */\nasync function resolveCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<{\n readonly identity: ValidatedUserIdentityCandidate;\n readonly source: \"self\" | \"observed\";\n} | null> {\n const localUserId = dependencies.getLocalUserId();\n if (userId === localUserId) {\n const localIdentity = dependencies.getLocalIdentity(userId);\n if (!localIdentity) {\n throw new KeyingVerificationError(\n \"missing_dependency\",\n \"Authoritative local identity keys are unavailable\",\n );\n }\n return {\n identity: await validateLocalUserIdentity({\n candidate: localIdentity,\n identityTrustDomain,\n userId,\n }),\n source: \"self\",\n };\n }\n\n const identity = await loadRemoteCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n return identity ? { identity, source: \"observed\" } : null;\n}\n\nasync function loadRemoteCandidate(\n dependencies: TrustedUserIdentityServiceDependencies,\n userId: string,\n identityTrustDomain: string,\n): Promise<ValidatedUserIdentityCandidate | null> {\n const remoteIdentity = await dependencies.remoteSource.load(userId);\n return remoteIdentity\n ? validateRemoteUserIdentity({\n candidate: remoteIdentity,\n identityTrustDomain,\n requestedUserId: userId,\n })\n : null;\n}\n\n/** The trust store and account a lookup started under must still be active. */\nfunction assertResolutionScope(\n dependencies: TrustedUserIdentityServiceDependencies,\n scope: { readonly execSql: ExecSql; readonly localUserId: string | null },\n message: string,\n): void {\n if (\n dependencies.getExecSql() !== scope.execSql ||\n dependencies.getLocalUserId() !== scope.localUserId\n ) {\n throw new DatabaseUnavailableError(message);\n }\n}\n\nasync function pinIdentity(input: {\n /** Checked inside the pin's write transaction, before it commits. */\n readonly assertCurrent?: (() => void) | undefined;\n readonly dependencies: TrustedUserIdentityServiceDependencies;\n readonly execSql: NonNullable<\n ReturnType<TrustedUserIdentityServiceDependencies[\"getExecSql\"]>\n >;\n readonly identity: ValidatedUserIdentityCandidate;\n readonly provenance: TrustedUserIdentityPinProvenance;\n}): Promise<TrustedUserIdentity> {\n await compareWithDurablePins({\n assertCurrent: input.assertCurrent,\n execSql: input.execSql,\n firstSeenAt: (input.dependencies.now?.() ?? new Date()).toISOString(),\n identities: [input.identity],\n provenance: input.provenance,\n });\n return brandTrustedUserIdentity(input.identity);\n}\n\n/** The user this trust store already binds to a signing key, if any. */\nasync function boundUserId(\n dependencies: TrustedUserIdentityServiceDependencies,\n signingKeyFingerprint: string,\n): Promise<string | null> {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return new TrustedUserIdentityPinRepository(\n execSql,\n ).loadTrustedUserIdForSigningKey({\n identityTrustDomain,\n signingKeyFingerprint,\n });\n}\n\n/** Compares an independently received link before pinning it as `link`. */\nasync function verifyIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n link: string,\n): Promise<TrustedUserIdentity> {\n const expectation = parseIdentityLink(link);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (expectation.identityTrustDomain !== identityTrustDomain) {\n throw new Error(\n \"This identity link belongs to a different Tearleads service.\",\n );\n }\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n expectation.userId,\n identityTrustDomain,\n );\n if (!candidate)\n throw new Error(\"The identity in this link is unavailable.\");\n await assertIdentityLinkMatches(expectation, candidate.identity);\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed. Open the identity link again.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source === \"self\" ? \"self\" : \"link\",\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(expectation.userId);\n throw error;\n }\n}\n\nfunction admissionScopeChanged(): DatabaseUnavailableError {\n return new DatabaseUnavailableError(\n \"The active database changed while admitting this user. Try again.\",\n );\n}\n\n/** Reads that admit a user: only `self` and `link` pins qualify. */\nfunction verifiedPinReaders(\n dependencies: TrustedUserIdentityServiceDependencies,\n): Pick<\n TrustedUserIdentityService,\n \"loadAdmissionPin\" | \"resolveVerified\" | \"requireVerified\"\n> {\n const resolveVerified = async (userId: string) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin && pin.provenance !== \"observed\" ? pin.identity : null;\n };\n // The pin in the trust store of the database the admission captured.\n const loadAdmittingPin = async (\n userId: string,\n admittingExecSql: ExecSql | null,\n ) => {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n if (execSql !== admittingExecSql) throw admissionScopeChanged();\n const pin = await loadPin({ execSql, identityTrustDomain, userId });\n if (dependencies.getExecSql() !== execSql) throw admissionScopeChanged();\n return pin;\n };\n return {\n resolveVerified,\n async requireVerified(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n if (!pin || pin.provenance === \"observed\") {\n throw new UnverifiedUserIdentityError(userId);\n }\n return pin.identity;\n },\n async loadAdmissionPin(userId, admittingExecSql) {\n const pin = await loadAdmittingPin(userId, admittingExecSql);\n return pin\n ? { identity: pin.identity, verified: pin.provenance !== \"observed\" }\n : null;\n },\n };\n}\n\n/** This user's own link, derived exclusively from this device's local keys. */\nasync function createLocalIdentityLink(\n dependencies: TrustedUserIdentityServiceDependencies,\n appUrl: string,\n): Promise<string> {\n const identityTrustDomain = requireTrustDomain(dependencies);\n const userId = dependencies.getLocalUserId();\n const candidate = userId ? dependencies.getLocalIdentity(userId) : null;\n if (!userId || !candidate) {\n throw new Error(\"Sign in before sharing your identity link.\");\n }\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return createIdentityLink(identity, appUrl);\n}\n\nexport function createTrustedUserIdentityService(\n input: TrustedUserIdentityServiceDependencies,\n): TrustedUserIdentityService {\n const { dependencies, handoff } = withStagedIdentityHandoff(input);\n const verifiedReaders = verifiedPinReaders(dependencies);\n return {\n async resolvePinned(userId) {\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n return loadPinnedUserIdentity({ execSql, identityTrustDomain, userId });\n },\n ...verifiedReaders,\n createLink: (appUrl) => createLocalIdentityLink(dependencies, appUrl),\n async createLinkFor(userId, appUrl) {\n if (\n userId === dependencies.getLocalUserId() &&\n dependencies.getLocalIdentity(userId)\n ) {\n return createLocalIdentityLink(dependencies, appUrl);\n }\n // Only a `link` or `self` pin: re-sharing an observed (TOFU) key as a\n // link would let its recipient pin an unverified key as `link`.\n const identity = await verifiedReaders.resolveVerified(userId);\n return identity ? createIdentityLink(identity, appUrl) : null;\n },\n verifyLink: (link) => verifyIdentityLink(dependencies, link),\n boundUserId: (signingKeyFingerprint) =>\n boundUserId(dependencies, signingKeyFingerprint),\n async pinLocal(userId, candidate, assertCurrent) {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } = requireTrustStore(dependencies);\n const identity = await validateLocalUserIdentity({\n candidate,\n identityTrustDomain,\n userId,\n });\n return pinIdentity({\n dependencies,\n execSql,\n identity,\n provenance: \"self\",\n assertCurrent,\n });\n },\n resolve: withPinnedIdentityResolution(\n dependencies,\n async (userId) => {\n assertTrustedUserIdentityUserId(userId);\n const { execSql, identityTrustDomain } =\n requireTrustStore(dependencies);\n const localUserId = dependencies.getLocalUserId();\n try {\n const candidate = await resolveCandidate(\n dependencies,\n userId,\n identityTrustDomain,\n );\n if (!candidate) {\n return null;\n }\n const assertCurrent = () =>\n assertResolutionScope(\n dependencies,\n { execSql, localUserId },\n \"The active identity changed while resolving this user.\",\n );\n assertCurrent();\n return await pinIdentity({\n assertCurrent,\n dependencies,\n execSql,\n identity: candidate.identity,\n provenance: candidate.source,\n });\n } catch (error) {\n dependencies.remoteSource.invalidate(userId);\n throw error;\n }\n },\n {\n loadCandidate: (userId, identityTrustDomain) =>\n loadRemoteCandidate(dependencies, userId, identityTrustDomain),\n pinObserved: (execSql, identities, assertCurrent) =>\n compareWithDurablePins({\n assertCurrent,\n execSql,\n firstSeenAt: (dependencies.now?.() ?? new Date()).toISOString(),\n identities,\n provenance: \"observed\",\n }),\n },\n handoff,\n ),\n };\n}\n"]}
@@ -83,7 +83,7 @@ export interface TrustedUserIdentityService {
83
83
  loadAdmissionPin(userId: string, admittingExecSql: ExecSql | null): Promise<TrustedUserIdentityAdmissionPin | null>;
84
84
  /** The user this device's trust store already binds a signing key to. */
85
85
  boundUserId(signingKeyFingerprint: string): Promise<string | null>;
86
- pinLocal(userId: string, candidate: LocalUserIdentityCandidate): Promise<TrustedUserIdentity>;
86
+ pinLocal(userId: string, candidate: LocalUserIdentityCandidate, assertCurrent?: () => void): Promise<TrustedUserIdentity>;
87
87
  /** Pins on first sight as `observed`; for users signed state references. */
88
88
  resolve: TrustedUserIdentityResolver;
89
89
  }