@tearleads/client-sdk 0.1.261 → 0.1.263

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 (39) hide show
  1. package/README.md +1 -1
  2. package/client/documents/index.d.ts +11 -0
  3. package/client/documents/index.js +7 -1
  4. package/client/documents/index.js.map +1 -1
  5. package/client/index.d.ts +1 -1
  6. package/client/index.js.map +1 -1
  7. package/index.d.ts +1 -1
  8. package/index.js.map +1 -1
  9. package/internal/sqlite-worker/crossTabConnectionMachine.js +67 -0
  10. package/internal/sqlite-worker/crossTabConnectionMachine.js.map +1 -0
  11. package/internal/sqlite-worker/crossTabLocalClient.js +76 -14
  12. package/internal/sqlite-worker/crossTabLocalClient.js.map +1 -1
  13. package/internal/sqlite-worker/crossTabProtocol.js +17 -0
  14. package/internal/sqlite-worker/crossTabProtocol.js.map +1 -1
  15. package/internal/sqlite-worker/crossTabRuntime.js +20 -18
  16. package/internal/sqlite-worker/crossTabRuntime.js.map +1 -1
  17. package/internal/sqlite-worker/runtime.d.ts +1 -1
  18. package/internal/sqlite-worker/runtime.js +1 -0
  19. package/internal/sqlite-worker/runtime.js.map +1 -1
  20. package/internal/sqlite-worker/types.d.ts +7 -0
  21. package/internal/sqlite-worker/types.js +12 -0
  22. package/internal/sqlite-worker/types.js.map +1 -1
  23. package/internal/sqlite-worker/workerCrash.d.ts +23 -0
  24. package/internal/sqlite-worker/workerCrash.js +17 -0
  25. package/internal/sqlite-worker/workerCrash.js.map +1 -1
  26. package/package.json +1 -1
  27. package/sqlite/index.d.ts +1 -1
  28. package/sqlite/index.js +1 -1
  29. package/sqlite/index.js.map +1 -1
  30. package/sqlite/worker.js +4 -4
  31. package/stores/documents/downloadRetry.d.ts +16 -0
  32. package/stores/documents/downloadRetry.js +28 -0
  33. package/stores/documents/downloadRetry.js.map +1 -0
  34. package/stores/documents/index.d.ts +1 -0
  35. package/stores/documents/index.js +1 -0
  36. package/stores/documents/index.js.map +1 -1
  37. package/workflows/container-contents/documentQueries/pendingDownloads.d.ts +23 -2
  38. package/workflows/container-contents/documentQueries/pendingDownloads.js +63 -1
  39. package/workflows/container-contents/documentQueries/pendingDownloads.js.map +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"crossTabProtocol.js","sourceRoot":"","sources":["crossTabProtocol.ts"],"names":[],"mappings":"AAwBA,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;AACrD,CAAC;AAED,SAAS,SAAS,CAAC,KAAc,EAAE,GAAW;IAC5C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACzC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;AACxD,CAAC;AAED,SAAS,SAAS,CAAC,KAAc,EAAE,GAAW;IAC5C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACzC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,IAAI,CAAC;AACxD,CAAC;AAED,MAAM,UAAU,SAAS,CAAC,OAAgB;IACxC,OAAO,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;AAClC,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,OAAgB;IAC5C,OAAO,SAAS,CAAC,OAAO,EAAE,QAAQ,CAAC,CAAC;AACtC,CAAC;AAED,MAAM,UAAU,UAAU,CAAC,QAAiB;IAC1C,OAAO,SAAS,CAAC,QAAQ,EAAE,IAAI,CAAC,CAAC;AACnC,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,EAAU,EAAE,OAAe;IACvD,OAAO;QACL,EAAE;QACF,MAAM,EAAE;YACN,EAAE,EAAE,KAAK;YACT,OAAO;SACR;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,KAAc;IAC/C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACxC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IAChD,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;QACjC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;QACrB,OAAO,CACL,OAAO,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,SAAS,CAAC,KAAK,QAAQ,CACvE,CAAC;IACJ,CAAC;IAED,OAAO,IAAI,KAAK,UAAU,CAAC;AAC7B,CAAC","sourcesContent":["import type { WorkerResponse } from \"./types\";\nimport type { WorkerCrashDetail } from \"./workerCrash\";\n\ntype CrossTabEnvelope =\n | {\n readonly type: \"request\";\n readonly clientId: string;\n readonly hasClientLock?: boolean;\n readonly request: unknown;\n }\n | {\n readonly type: \"response\";\n readonly clientId: string;\n readonly response: unknown;\n }\n // The owner's worker crashed while serving `clientId` from another tab. An\n // Error cannot cross the channel, so the receiving tab mints its own from the\n // detail (see workerCrash.ts).\n | {\n readonly type: \"error\";\n readonly clientId: string;\n readonly detail: WorkerCrashDetail;\n };\n\nfunction isObject(value: unknown): value is object {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction getString(value: unknown, key: string): string | null {\n if (!isObject(value)) {\n return null;\n }\n\n const property = Reflect.get(value, key);\n return typeof property === \"string\" ? property : null;\n}\n\nfunction getNumber(value: unknown, key: string): number | null {\n if (!isObject(value)) {\n return null;\n }\n\n const property = Reflect.get(value, key);\n return typeof property === \"number\" ? property : null;\n}\n\nexport function requestId(request: unknown): number | null {\n return getNumber(request, \"id\");\n}\n\nexport function requestMethod(request: unknown): string | null {\n return getString(request, \"method\");\n}\n\nexport function responseId(response: unknown): number | null {\n return getNumber(response, \"id\");\n}\n\nexport function errorResponse(id: number, message: string): WorkerResponse {\n return {\n id,\n result: {\n ok: false,\n message,\n },\n };\n}\n\nexport function isCrossTabEnvelope(value: unknown): value is CrossTabEnvelope {\n if (!isObject(value)) {\n return false;\n }\n\n const type = Reflect.get(value, \"type\");\n const clientId = Reflect.get(value, \"clientId\");\n if (typeof clientId !== \"string\") {\n return false;\n }\n\n if (type === \"request\") {\n return true;\n }\n\n if (type === \"error\") {\n return (\n typeof getString(Reflect.get(value, \"detail\"), \"message\") === \"string\"\n );\n }\n\n return type === \"response\";\n}\n"]}
1
+ {"version":3,"file":"crossTabProtocol.js","sourceRoot":"","sources":["crossTabProtocol.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,oCAAoC,GAErC,MAAM,SAAS,CAAC;AAwBjB,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,CAAC;AACrD,CAAC;AAED,SAAS,SAAS,CAAC,KAAc,EAAE,GAAW;IAC5C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,GAAG,CAAC,CAAC;IACzC,OAAO,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC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E,CAAC;QAC5B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,OAAO,EAAE,EAAE,EAAE,OAAO,EAAE,SAAS,CAAC,MAAM,EAAE,SAAS,CAAC,EAAE,CAAC;AACvD,CAAC;AAED,MAAM,UAAU,aAAa,CAAC,EAAU,EAAE,OAAe;IACvD,OAAO;QACL,EAAE;QACF,MAAM,EAAE;YACN,EAAE,EAAE,KAAK;YACT,OAAO;SACR;KACF,CAAC;AACJ,CAAC;AAED,MAAM,UAAU,kBAAkB,CAAC,KAAc;IAC/C,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;QACrB,OAAO,KAAK,CAAC;IACf,CAAC;IAED,MAAM,IAAI,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAC;IACxC,MAAM,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,UAAU,CAAC,CAAC;IAChD,IAAI,OAAO,QAAQ,KAAK,QAAQ,EAAE,CAAC;QACjC,OAAO,KAAK,CAAC;IACf,CAAC;IAED,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;QACvB,OAAO,IAAI,CAAC;IACd,CAAC;IAED,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;QACrB,OAAO,CACL,OAAO,SAAS,CAAC,OAAO,CAAC,GAAG,CAAC,KAAK,EAAE,QAAQ,CAAC,EAAE,SAAS,CAAC,KAAK,QAAQ,CACvE,CAAC;IACJ,CAAC;IAED,OAAO,IAAI,KAAK,UAAU,CAAC;AAC7B,CAAC","sourcesContent":["import {\n WORKER_DATABASE_DELETED_MESSAGE_TYPE,\n type WorkerResponse,\n} from \"./types\";\nimport type { WorkerCrashDetail } from \"./workerCrash\";\n\ntype CrossTabEnvelope =\n | {\n readonly type: \"request\";\n readonly clientId: string;\n readonly hasClientLock?: boolean;\n readonly request: unknown;\n }\n | {\n readonly type: \"response\";\n readonly clientId: string;\n readonly response: unknown;\n }\n // The owner's worker crashed while serving `clientId` from another tab. An\n // Error cannot cross the channel, so the receiving tab mints its own from the\n // detail (see workerCrash.ts).\n | {\n readonly type: \"error\";\n readonly clientId: string;\n readonly detail: WorkerCrashDetail;\n };\n\nfunction isObject(value: unknown): value is object {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction getString(value: unknown, key: string): string | null {\n if (!isObject(value)) {\n return null;\n }\n\n const property = Reflect.get(value, key);\n return typeof property === \"string\" ? property : null;\n}\n\nfunction getNumber(value: unknown, key: string): number | null {\n if (!isObject(value)) {\n return null;\n }\n\n const property = Reflect.get(value, key);\n return typeof property === \"number\" ? property : null;\n}\n\nexport function requestId(request: unknown): number | null {\n return getNumber(request, \"id\");\n}\n\nexport function requestMethod(request: unknown): string | null {\n return getString(request, \"method\");\n}\n\nexport function responseId(response: unknown): number | null {\n return getNumber(response, \"id\");\n}\n\n// The worker's unprompted notice that another connection deleted the database.\nexport function isDatabaseDeletedNotice(message: unknown): boolean {\n return getString(message, \"type\") === WORKER_DATABASE_DELETED_MESSAGE_TYPE;\n}\n\n// The outcome a worker response reports, or null for anything that is not one.\nexport function responseOutcome(\n response: unknown,\n): { readonly ok: boolean; readonly message: string | null } | null {\n if (!isObject(response)) {\n return null;\n }\n\n const result = Reflect.get(response, \"result\");\n const ok = isObject(result) ? Reflect.get(result, \"ok\") : undefined;\n if (typeof ok !== \"boolean\") {\n return null;\n }\n\n return { ok, message: getString(result, \"message\") };\n}\n\nexport function errorResponse(id: number, message: string): WorkerResponse {\n return {\n id,\n result: {\n ok: false,\n message,\n },\n };\n}\n\nexport function isCrossTabEnvelope(value: unknown): value is CrossTabEnvelope {\n if (!isObject(value)) {\n return false;\n }\n\n const type = Reflect.get(value, \"type\");\n const clientId = Reflect.get(value, \"clientId\");\n if (typeof clientId !== \"string\") {\n return false;\n }\n\n if (type === \"request\") {\n return true;\n }\n\n if (type === \"error\") {\n return (\n typeof getString(Reflect.get(value, \"detail\"), \"message\") === \"string\"\n );\n }\n\n return type === \"response\";\n}\n"]}
@@ -1,16 +1,12 @@
1
- import { createLocalClient, dispatchCrashToLocalClient, dispatchResponseToLocalClient, failPendingRemoteRequests, releaseLocalClient, } from "./crossTabLocalClient.js";
1
+ import { admitLocalClientRequest, assertLocalClientConnected, createLocalClient, dispatchCrashToLocalClient, dispatchResponseToLocalClient, isOpenLocalClient, releaseLocalClient, releaseLocalClientFromPreviousOwner, } from "./crossTabLocalClient.js";
2
2
  import { canUseCrossTabPrimitives, lockManager, } from "./crossTabLocks.js";
3
3
  import { CrossTabOwner } from "./crossTabOwner.js";
4
4
  import { isOwnerLockHeld, pollForOwner } from "./crossTabOwnership.js";
5
- import { errorResponse, isCrossTabEnvelope, requestId, requestMethod, } from "./crossTabProtocol.js";
5
+ import { errorResponse, isCrossTabEnvelope, requestId, } from "./crossTabProtocol.js";
6
6
  import { DatabaseWorkerCrashError } from "./workerCrash.js";
7
7
  const CROSS_TAB_CHANNEL_NAME = "tearleads-sqlite-worker";
8
8
  const CROSS_TAB_OWNER_LOCK_NAME = "tearleads-sqlite-worker-owner";
9
9
  const CROSS_TAB_REQUEST_TIMEOUT_MS = 10_000;
10
- function isTeardownRequest(request) {
11
- const method = requestMethod(request);
12
- return method === "close" || method === "delete";
13
- }
14
10
  class CrossTabCoordinator {
15
11
  workerUrl;
16
12
  workerConstructor;
@@ -99,8 +95,11 @@ class CrossTabCoordinator {
99
95
  * only ever risks a missed heal, never wrongly stranding a real remote tab.
100
96
  */
101
97
  forceStopOwnerFor(clientId) {
98
+ // A lost client's database died with an earlier owner; the current owner
99
+ // may never have served it, so its silence is no reason to stop it.
100
+ const lost = this.localClientsById.get(clientId)?.connection.status === "lost";
102
101
  this.unregisterLocalClient(clientId);
103
- if (this.hasOpenLocalClients()) {
102
+ if (lost || this.hasOpenLocalClients()) {
104
103
  return;
105
104
  }
106
105
  const owner = this.owner;
@@ -115,8 +114,8 @@ class CrossTabCoordinator {
115
114
  const id = requestId(request);
116
115
  try {
117
116
  const localClient = this.localClientsById.get(clientId);
118
- if (localClient && isTeardownRequest(request)) {
119
- localClient.closing = true;
117
+ if (localClient) {
118
+ admitLocalClientRequest(localClient, request);
120
119
  }
121
120
  const hasClientLock = await this.waitForLocalClientLock(clientId);
122
121
  if (!this.localClientsById.has(clientId)) {
@@ -130,6 +129,10 @@ class CrossTabCoordinator {
130
129
  if (!this.localClientsById.has(clientId)) {
131
130
  return;
132
131
  }
132
+ // A client can be lost while it waits, when this tab is promoted.
133
+ if (localClient) {
134
+ assertLocalClientConnected(localClient);
135
+ }
133
136
  if (this.owner) {
134
137
  this.owner.route(clientId, request, { hasClientLock });
135
138
  return;
@@ -268,9 +271,8 @@ class CrossTabCoordinator {
268
271
  });
269
272
  this.owner = owner;
270
273
  this.ownerError = null;
271
- // Requests posted to the previous owner are orphaned; fail them with a
272
- // retryable error instead of waiting out the timeout.
273
- this.failPendingRemoteRequests();
274
+ // The previous owner is gone, with every database it had open.
275
+ this.releaseClientsFromPreviousOwner();
274
276
  this.settleOwnership(generation);
275
277
  await ownerReleased;
276
278
  releasedNormally = true;
@@ -282,7 +284,7 @@ class CrossTabCoordinator {
282
284
  this.owner = null;
283
285
  this.ownerError =
284
286
  error instanceof Error ? error : new Error(String(error));
285
- this.failPendingRemoteRequests();
287
+ this.releaseClientsFromPreviousOwner();
286
288
  this.settleOwnership(generation);
287
289
  throw error;
288
290
  }
@@ -308,7 +310,7 @@ class CrossTabCoordinator {
308
310
  }
309
311
  hasOpenLocalClients() {
310
312
  for (const localClient of this.localClientsById.values()) {
311
- if (!localClient.closing) {
313
+ if (isOpenLocalClient(localClient)) {
312
314
  return true;
313
315
  }
314
316
  }
@@ -363,11 +365,11 @@ class CrossTabCoordinator {
363
365
  const locks = lockManager();
364
366
  return locks ? isOwnerLockHeld(locks, CROSS_TAB_OWNER_LOCK_NAME) : false;
365
367
  }
366
- // Called when this tab is promoted to owner: the owner its clients had posted
367
- // their remote requests to is gone, so fail them fast rather than time out.
368
- failPendingRemoteRequests() {
368
+ // Called when this tab takes the owner lock: the owner its clients had been
369
+ // routing to is gone (see releaseLocalClientFromPreviousOwner).
370
+ releaseClientsFromPreviousOwner() {
369
371
  for (const localClient of this.localClientsById.values()) {
370
- failPendingRemoteRequests(localClient);
372
+ releaseLocalClientFromPreviousOwner(localClient);
371
373
  }
372
374
  }
373
375
  }
@@ -1 +1 @@
1
- {"version":3,"file":"crossTabRuntime.js","sourceRoot":"","sources":["crossTabRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EACL,iBAAiB,EACjB,0BAA0B,EAC1B,6BAA6B,EAC7B,yBAAyB,EAEzB,kBAAkB,GACnB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,EACL,wBAAwB,EAExB,WAAW,GACZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,aAAa,EAAgC,MAAM,iBAAiB,CAAC;AAC9E,OAAO,EAAE,eAAe,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACpE,OAAO,EACL,aAAa,EACb,kBAAkB,EAClB,SAAS,EACT,aAAa,GACd,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,wBAAwB,EAAE,MAAM,eAAe,CAAC;AAEzD,MAAM,sBAAsB,GAAG,yBAAyB,CAAC;AACzD,MAAM,yBAAyB,GAAG,+BAA+B,CAAC;AAClE,MAAM,4BAA4B,GAAG,MAAM,CAAC;AAc5C,SAAS,iBAAiB,CAAC,OAAgB;IACzC,MAAM,MAAM,GAAG,aAAa,CAAC,OAAO,CAAC,CAAC;IACtC,OAAO,MAAM,KAAK,OAAO,IAAI,MAAM,KAAK,QAAQ,CAAC;AACnD,CAAC;AAED,MAAM,mBAAmB;IAkBJ;IACA;IAlBF,OAAO,GAAG,IAAI,gBAAgB,CAAC,sBAAsB,CAAC,CAAC;IAChE,gBAAgB,GAAG,KAAK,CAAC;IAChB,gBAAgB,GAAG,IAAI,GAAG,EAAuB,CAAC;IAC3D,KAAK,GAAyB,IAAI,CAAC;IAC3C,0EAA0E;IAC1E,0DAA0D;IACl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,CAAC;IAC9B,IAAI,WAAW,GAAG,uBAAuB,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;IACnD,IAAI,CAAC,WAAW,EAAE,CAAC;QACjB,WAAW,GAAG,IAAI,mBAAmB,CAAC,SAAS,EAAE,iBAAiB,CAAC,CAAC;QACpE,uBAAuB,CAAC,GAAG,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC;IAChD,CAAC;IAED,OAAO,WAAW,CAAC,YAAY,EAAE,CAAC;AACpC,CAAC","sourcesContent":["import type { WorkerLike } from \"./client\";\nimport {\n createLocalClient,\n dispatchCrashToLocalClient,\n dispatchResponseToLocalClient,\n failPendingRemoteRequests,\n type LocalClient,\n releaseLocalClient,\n} from \"./crossTabLocalClient\";\nimport {\n canUseCrossTabPrimitives,\n type LockManagerLike,\n lockManager,\n} from \"./crossTabLocks\";\nimport { CrossTabOwner, type ModuleWorkerConstructor } from \"./crossTabOwner\";\nimport { isOwnerLockHeld, pollForOwner } from \"./crossTabOwnership\";\nimport {\n errorResponse,\n isCrossTabEnvelope,\n requestId,\n requestMethod,\n} from \"./crossTabProtocol\";\nimport { DatabaseWorkerCrashError } from \"./workerCrash\";\n\nconst CROSS_TAB_CHANNEL_NAME = \"tearleads-sqlite-worker\";\nconst CROSS_TAB_OWNER_LOCK_NAME = \"tearleads-sqlite-worker-owner\";\nconst CROSS_TAB_REQUEST_TIMEOUT_MS = 10_000;\n\ninterface CrossTabDatabaseWorker extends WorkerLike {\n close(): void;\n /**\n * Abrupt teardown for a runtime that could not close gracefully — its worker\n * went silent, so the `close` round-trip never came back to stop the owner via\n * {@link CrossTabOwner.stop}. Unregisters this client and, when safe, force-stops\n * the owner so the next boot re-contends and builds a fresh owner instead of\n * routing into the dead one. See {@link CrossTabCoordinator.forceStopOwnerFor}.\n */\n forceStopOwner(): void;\n}\n\nfunction isTeardownRequest(request: unknown): boolean {\n const method = requestMethod(request);\n return method === \"close\" || method === \"delete\";\n}\n\nclass CrossTabCoordinator {\n private readonly channel = new BroadcastChannel(CROSS_TAB_CHANNEL_NAME);\n private hasCreatedClient = false;\n private readonly localClientsById = new Map<string, LocalClient>();\n private owner: CrossTabOwner | null = null;\n // Set if this tab won ownership but its owner worker failed to construct.\n // Cleared if a later bid succeeds in installing an owner.\n private ownerError: Error | null = null;\n // Resolves when ownership is settled for the current owner generation (this tab\n // won and installed/failed to construct an owner, or it observed another tab\n // already owns), so routing never posts remotely while no owner exists.\n private ownershipBidActive = false;\n private ownershipGeneration = 0;\n private ownershipSettled: Promise<void> = Promise.resolve();\n private retryOwnershipAfterBid = false;\n private settleOwnershipGate: () => void = () => {};\n\n constructor(\n private readonly workerUrl: string | URL,\n private readonly workerConstructor: ModuleWorkerConstructor,\n ) {\n this.resetOwnershipGate();\n this.channel.addEventListener(\"message\", (event) => {\n this.handleChannelMessage(event);\n });\n // Start the first ownership bid; later clients can restart it after teardown.\n this.contendForOwnership();\n }\n\n createWorker(): CrossTabDatabaseWorker {\n const clientId = crypto.randomUUID();\n const events = new EventTarget();\n if (this.ownerError && this.hasCreatedClient) {\n this.ownerError = null;\n this.retryOwnershipAfterBid = this.ownershipBidActive;\n this.resetOwnershipGate();\n }\n this.localClientsById.set(clientId, createLocalClient(clientId, events));\n this.hasCreatedClient = true;\n this.contendForOwnership();\n\n return {\n postMessage: (message) => {\n this.route(clientId, message);\n },\n addEventListener(type, listener) {\n events.addEventListener(type, listener);\n },\n removeEventListener(type, listener) {\n events.removeEventListener(type, listener);\n },\n close: () => {\n this.unregisterLocalClient(clientId);\n },\n forceStopOwner: () => {\n this.forceStopOwnerFor(clientId);\n },\n };\n }\n\n /**\n * Tear down a possibly-wedged owner on abrupt runtime teardown.\n *\n * `this.owner` is normally cleared only when the dedicated worker answers a\n * `close`/`delete` (→ {@link CrossTabOwner.stop} via `handleWorkerResponse`). A\n * worker hung inside OPFS never answers, so that path never runs and the plain\n * client `close()` (just {@link unregisterLocalClient}) leaves `this.owner`\n * pinned to the dead worker — every later boot then routes its `init` straight\n * into it over the untimed local path and hangs. Because the coordinator is a\n * per-URL module singleton, that pins EVERY database, not just the one that\n * wedged.\n *\n * So on abrupt teardown, after unregistering the client, stop the owner —\n * `stop()` terminates the worker, releases the owner lock, and (via the release\n * callback) nulls `this.owner` + resets the gate, so the next `createWorker()`\n * re-contends and constructs a fresh owner. Gated to stay multi-tab-safe: only\n * when this tab has no other open local client AND the owner serves no other\n * (remote) client, so it can never strand a sibling tab still routing here.\n *\n * The remote-client half of the gate reads the owner's `activeClientIds`, which\n * is coarse: a wedged local client that was force-torn-down without a close\n * response leaves a *stale* id there (only a close-response or the liveness sweep\n * removes it). So if TWO local clients on one coordinator were wedged and torn\n * down in the same tick, the second would see the first's stale id and decline to\n * stop — leaving the wedge unhealed. That cannot happen here: the app drives a\n * single runtime at a time (`useManagedSQLiteRuntime` holds one runtimeRef and\n * defers each spawn on the prior release), so a coordinator never has two live\n * local clients. The gate therefore errs, at worst, toward NOT stopping — which\n * only ever risks a missed heal, never wrongly stranding a real remote tab.\n */\n private forceStopOwnerFor(clientId: string): void {\n this.unregisterLocalClient(clientId);\n if (this.hasOpenLocalClients()) {\n return;\n }\n\n const owner = this.owner;\n if (owner && !owner.hasActiveClientsExcept(clientId)) {\n owner.stop();\n }\n }\n\n private route(clientId: string, request: unknown): void {\n void this.routeAsync(clientId, request);\n }\n\n private async routeAsync(clientId: string, request: unknown): Promise<void> {\n const id = requestId(request);\n try {\n const localClient = this.localClientsById.get(clientId);\n if (localClient && isTeardownRequest(request)) {\n localClient.closing = true;\n }\n\n const hasClientLock = await this.waitForLocalClientLock(clientId);\n if (!this.localClientsById.has(clientId)) {\n return;\n }\n\n // Wait for ownership so this request is not posted into the void.\n if (!this.owner && !this.ownerError) {\n this.contendForOwnership();\n }\n await this.ownershipSettled;\n if (!this.localClientsById.has(clientId)) {\n return;\n }\n\n if (this.owner) {\n this.owner.route(clientId, request, { hasClientLock });\n return;\n }\n\n // This tab won ownership earlier but its owner worker failed to construct.\n // If another tab has since become a healthy owner, fall back to it; only\n // surface the construction error when no owner exists anywhere, so a single\n // tab whose worker cannot start fails fast instead of hanging on the timeout.\n if (this.ownerError && !(await this.anotherTabOwns())) {\n throw this.ownerError;\n }\n\n this.postRemoteRequest(clientId, request, hasClientLock);\n } catch (error: unknown) {\n if (id !== null) {\n this.dispatchLocalResponse(\n clientId,\n errorResponse(\n id,\n error instanceof Error\n ? error.message\n : \"Failed to route database request.\",\n ),\n );\n }\n }\n }\n\n private async waitForLocalClientLock(clientId: string): Promise<boolean> {\n const localClient = this.localClientsById.get(clientId);\n if (!localClient) {\n return false;\n }\n\n return localClient.liveness.ready;\n }\n\n private postRemoteRequest(\n clientId: string,\n request: unknown,\n hasClientLock: boolean,\n ): void {\n const id = requestId(request);\n if (id !== null) {\n const localClient = this.localClientsById.get(clientId);\n localClient?.pendingRemoteRequestIds.add(id);\n const timeoutId = setTimeout(() => {\n localClient?.timeoutsByRequestId.delete(id);\n localClient?.pendingRemoteRequestIds.delete(id);\n this.dispatchLocalResponse(\n clientId,\n errorResponse(id, \"Timed out waiting for the database owner tab.\"),\n );\n }, CROSS_TAB_REQUEST_TIMEOUT_MS);\n localClient?.timeoutsByRequestId.set(id, timeoutId);\n }\n\n this.channel.postMessage({\n type: \"request\",\n clientId,\n hasClientLock,\n request,\n });\n }\n\n private dispatchLocalResponse(clientId: string, response: unknown): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n dispatchResponseToLocalClient(localClient, response);\n }\n }\n\n private dispatchLocalError(\n clientId: string,\n error: DatabaseWorkerCrashError,\n ): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n dispatchCrashToLocalClient(localClient, error);\n }\n }\n\n // A crashed owner worker is the same failure class as one that never\n // constructed: record it so routing fails fast instead of rebuilding the\n // crashed worker on the next bid (`contendForOwnership` and the post-release\n // retry both stop on `ownerError`), and fail every local client — including\n // one whose first request has not been routed yet, which is exactly where a\n // script-load failure lands. The next `createWorker()` (a fresh runtime boot)\n // clears the error and re-contends.\n private handleOwnerCrash(error: DatabaseWorkerCrashError): void {\n this.ownerError = error;\n for (const localClient of this.localClientsById.values()) {\n dispatchCrashToLocalClient(localClient, error);\n }\n }\n\n private unregisterLocalClient(clientId: string): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n releaseLocalClient(localClient);\n }\n\n this.localClientsById.delete(clientId);\n }\n\n private handleChannelMessage(event: MessageEvent): void {\n const envelope = event.data;\n if (!isCrossTabEnvelope(envelope)) {\n return;\n }\n\n if (envelope.type === \"request\") {\n this.owner?.route(envelope.clientId, envelope.request, {\n hasClientLock: envelope.hasClientLock === true,\n });\n return;\n }\n\n if (envelope.type === \"error\") {\n this.dispatchLocalError(\n envelope.clientId,\n new DatabaseWorkerCrashError(envelope.detail),\n );\n return;\n }\n\n this.dispatchLocalResponse(envelope.clientId, envelope.response);\n }\n\n /**\n * Hold one blocking owner-lock bid. The current holder owns until it releases;\n * queued bidders are promoted when the holder disappears.\n */\n private contendForOwnership(): void {\n if (this.owner || this.ownershipBidActive || this.ownerError) {\n return;\n }\n\n const locks = lockManager();\n if (!locks) {\n // No Web Locks: unblock routing and rely on the request timeout.\n this.settleOwnership();\n return;\n }\n\n this.ownershipBidActive = true;\n const generation = this.ownershipGeneration;\n // A non-owner tab's blocking bid stays queued (never enters its callback)\n // until the current owner dies, so it cannot settle the routing gate on its\n // own. Settle it from here as soon as ownership is known either way.\n this.observeExistingOwner(locks, generation);\n\n let releasedNormally = false;\n\n void locks\n .request(CROSS_TAB_OWNER_LOCK_NAME, null, async () => {\n let releaseOwner: (() => void) | null = null;\n const ownerReleased = new Promise<void>((resolve) => {\n releaseOwner = resolve;\n });\n try {\n const owner = new CrossTabOwner(\n this.workerUrl,\n this.workerConstructor,\n this.channel,\n (clientId, response) =>\n this.dispatchLocalResponse(clientId, response),\n (error) => this.handleOwnerCrash(error),\n () => {\n if (this.owner === owner) {\n this.owner = null;\n // After a crash the gate stays settled: routing fails fast on\n // the recorded error instead of waiting for a bid that must\n // not run until a fresh client asks for one.\n if (!this.ownerError) {\n this.resetOwnershipGate();\n }\n }\n releaseOwner?.();\n },\n );\n this.owner = owner;\n this.ownerError = null;\n // Requests posted to the previous owner are orphaned; fail them with a\n // retryable error instead of waiting out the timeout.\n this.failPendingRemoteRequests();\n this.settleOwnership(generation);\n await ownerReleased;\n releasedNormally = true;\n } catch (error) {\n // This tab won ownership but could not stand up the owner worker. Record\n // the failure so its own clients see the error instead of hanging, then\n // rethrow to release the lock so another tab can try to own.\n this.owner = null;\n this.ownerError =\n error instanceof Error ? error : new Error(String(error));\n this.failPendingRemoteRequests();\n this.settleOwnership(generation);\n throw error;\n }\n })\n .catch(() => {\n // The bid itself failed (e.g. the lock manager rejected). Unblock routing\n // so requests fall back to the remote path instead of hanging forever.\n this.settleOwnership(generation);\n })\n .finally(() => {\n this.ownershipBidActive = false;\n const shouldRetryOwnership =\n releasedNormally || this.retryOwnershipAfterBid;\n this.retryOwnershipAfterBid = false;\n if (!shouldRetryOwnership) {\n return;\n }\n\n queueMicrotask(() => {\n if (this.hasOpenLocalClients() && !this.owner && !this.ownerError) {\n this.contendForOwnership();\n }\n });\n });\n }\n\n private hasOpenLocalClients(): boolean {\n for (const localClient of this.localClientsById.values()) {\n if (!localClient.closing) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Settle the initial routing gate on a tab that did NOT win ownership. Runs\n * concurrently with the blocking bid above; whichever resolves first settles the\n * gate (the bid settles it on the tab that becomes owner, this settles it on\n * every other tab). See {@link pollForOwner} for why this polls.\n *\n * Falls back to settling immediately when the lock manager cannot be queried, so\n * routing is never blocked indefinitely.\n */\n private observeExistingOwner(\n locks: LockManagerLike,\n generation: number,\n ): void {\n if (!locks.query) {\n // No query support: cannot observe another tab's owner without contending\n // for the lock (which would steal it). Settle so routing proceeds remotely.\n this.settleOwnership(generation);\n return;\n }\n\n void pollForOwner({\n locks,\n lockName: CROSS_TAB_OWNER_LOCK_NAME,\n hasOwner: () => this.owner !== null,\n settle: () => this.settleOwnership(generation),\n });\n }\n\n private resetOwnershipGate(): void {\n this.ownershipGeneration += 1;\n this.ownershipSettled = new Promise((resolve) => {\n this.settleOwnershipGate = resolve;\n });\n }\n\n private settleOwnership(generation = this.ownershipGeneration): void {\n if (generation !== this.ownershipGeneration) {\n return;\n }\n\n this.settleOwnershipGate();\n }\n\n /**\n * Whether some other tab currently holds the owner lock. Used by routing to\n * decide, when this tab's own owner failed to construct, between surfacing that\n * error (no owner anywhere) and falling back to a healthy remote owner. Returns\n * false when the lock cannot be queried, so routing posts remotely and lets the\n * request/timeout path decide rather than throwing a possibly-stale error.\n */\n private async anotherTabOwns(): Promise<boolean> {\n if (this.owner) {\n return false;\n }\n\n const locks = lockManager();\n return locks ? isOwnerLockHeld(locks, CROSS_TAB_OWNER_LOCK_NAME) : false;\n }\n\n // Called when this tab is promoted to owner: the owner its clients had posted\n // their remote requests to is gone, so fail them fast rather than time out.\n private failPendingRemoteRequests(): void {\n for (const localClient of this.localClientsById.values()) {\n failPendingRemoteRequests(localClient);\n }\n }\n}\n\nconst coordinatorsByWorkerUrl = new Map<string, CrossTabCoordinator>();\n\nexport function createCrossTabDatabaseWorker(\n workerUrl: string | URL,\n workerConstructor: ModuleWorkerConstructor,\n): CrossTabDatabaseWorker | null {\n if (!canUseCrossTabPrimitives()) {\n return null;\n }\n\n const key = String(workerUrl);\n let coordinator = coordinatorsByWorkerUrl.get(key);\n if (!coordinator) {\n coordinator = new CrossTabCoordinator(workerUrl, workerConstructor);\n coordinatorsByWorkerUrl.set(key, coordinator);\n }\n\n return coordinator.createWorker();\n}\n"]}
1
+ {"version":3,"file":"crossTabRuntime.js","sourceRoot":"","sources":["crossTabRuntime.ts"],"names":[],"mappings":"AACA,OAAO,EACL,uBAAuB,EACvB,0BAA0B,EAC1B,iBAAiB,EACjB,0BAA0B,EAC1B,6BAA6B,EAC7B,iBAAiB,EAEjB,kBAAkB,EAClB,mCAAmC,GACpC,MAAM,uBAAuB,CAAC;AAC/B,OAAO,E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assertLocalClientConnected,\n createLocalClient,\n dispatchCrashToLocalClient,\n dispatchResponseToLocalClient,\n isOpenLocalClient,\n type LocalClient,\n releaseLocalClient,\n releaseLocalClientFromPreviousOwner,\n} from \"./crossTabLocalClient\";\nimport {\n canUseCrossTabPrimitives,\n type LockManagerLike,\n lockManager,\n} from \"./crossTabLocks\";\nimport { CrossTabOwner, type ModuleWorkerConstructor } from \"./crossTabOwner\";\nimport { isOwnerLockHeld, pollForOwner } from \"./crossTabOwnership\";\nimport {\n errorResponse,\n isCrossTabEnvelope,\n requestId,\n} from \"./crossTabProtocol\";\nimport { DatabaseWorkerCrashError } from \"./workerCrash\";\n\nconst CROSS_TAB_CHANNEL_NAME = \"tearleads-sqlite-worker\";\nconst CROSS_TAB_OWNER_LOCK_NAME = \"tearleads-sqlite-worker-owner\";\nconst CROSS_TAB_REQUEST_TIMEOUT_MS = 10_000;\n\ninterface CrossTabDatabaseWorker extends WorkerLike {\n close(): void;\n /**\n * Abrupt teardown for a runtime that could not close gracefully — its worker\n * went silent, so the `close` round-trip never came back to stop the owner via\n * {@link CrossTabOwner.stop}. Unregisters this client and, when safe, force-stops\n * the owner so the next boot re-contends and builds a fresh owner instead of\n * routing into the dead one. See {@link CrossTabCoordinator.forceStopOwnerFor}.\n */\n forceStopOwner(): void;\n}\n\nclass CrossTabCoordinator {\n private readonly channel = new BroadcastChannel(CROSS_TAB_CHANNEL_NAME);\n private hasCreatedClient = false;\n private readonly localClientsById = new Map<string, LocalClient>();\n private owner: CrossTabOwner | null = null;\n // Set if this tab won ownership but its owner worker failed to construct.\n // Cleared if a later bid succeeds in installing an owner.\n private ownerError: Error | null = null;\n // Resolves when ownership is settled for the current owner generation (this tab\n // won and installed/failed to construct an owner, or it observed another tab\n // already owns), so routing never posts remotely while no owner exists.\n private ownershipBidActive = false;\n private ownershipGeneration = 0;\n private ownershipSettled: Promise<void> = Promise.resolve();\n private retryOwnershipAfterBid = false;\n private settleOwnershipGate: () => void = () => {};\n\n constructor(\n private readonly workerUrl: string | URL,\n private readonly workerConstructor: ModuleWorkerConstructor,\n ) {\n this.resetOwnershipGate();\n this.channel.addEventListener(\"message\", (event) => {\n this.handleChannelMessage(event);\n });\n // Start the first ownership bid; later clients can restart it after teardown.\n this.contendForOwnership();\n }\n\n createWorker(): CrossTabDatabaseWorker {\n const clientId = crypto.randomUUID();\n const events = new EventTarget();\n if (this.ownerError && this.hasCreatedClient) {\n this.ownerError = null;\n this.retryOwnershipAfterBid = this.ownershipBidActive;\n this.resetOwnershipGate();\n }\n this.localClientsById.set(clientId, createLocalClient(clientId, events));\n this.hasCreatedClient = true;\n this.contendForOwnership();\n\n return {\n postMessage: (message) => {\n this.route(clientId, message);\n },\n addEventListener(type, listener) {\n events.addEventListener(type, listener);\n },\n removeEventListener(type, listener) {\n events.removeEventListener(type, listener);\n },\n close: () => {\n this.unregisterLocalClient(clientId);\n },\n forceStopOwner: () => {\n this.forceStopOwnerFor(clientId);\n },\n };\n }\n\n /**\n * Tear down a possibly-wedged owner on abrupt runtime teardown.\n *\n * `this.owner` is normally cleared only when the dedicated worker answers a\n * `close`/`delete` (→ {@link CrossTabOwner.stop} via `handleWorkerResponse`). A\n * worker hung inside OPFS never answers, so that path never runs and the plain\n * client `close()` (just {@link unregisterLocalClient}) leaves `this.owner`\n * pinned to the dead worker — every later boot then routes its `init` straight\n * into it over the untimed local path and hangs. Because the coordinator is a\n * per-URL module singleton, that pins EVERY database, not just the one that\n * wedged.\n *\n * So on abrupt teardown, after unregistering the client, stop the owner —\n * `stop()` terminates the worker, releases the owner lock, and (via the release\n * callback) nulls `this.owner` + resets the gate, so the next `createWorker()`\n * re-contends and constructs a fresh owner. Gated to stay multi-tab-safe: only\n * when this tab has no other open local client AND the owner serves no other\n * (remote) client, so it can never strand a sibling tab still routing here.\n *\n * The remote-client half of the gate reads the owner's `activeClientIds`, which\n * is coarse: a wedged local client that was force-torn-down without a close\n * response leaves a *stale* id there (only a close-response or the liveness sweep\n * removes it). So if TWO local clients on one coordinator were wedged and torn\n * down in the same tick, the second would see the first's stale id and decline to\n * stop — leaving the wedge unhealed. That cannot happen here: the app drives a\n * single runtime at a time (`useManagedSQLiteRuntime` holds one runtimeRef and\n * defers each spawn on the prior release), so a coordinator never has two live\n * local clients. The gate therefore errs, at worst, toward NOT stopping — which\n * only ever risks a missed heal, never wrongly stranding a real remote tab.\n */\n private forceStopOwnerFor(clientId: string): void {\n // A lost client's database died with an earlier owner; the current owner\n // may never have served it, so its silence is no reason to stop it.\n const lost =\n this.localClientsById.get(clientId)?.connection.status === \"lost\";\n this.unregisterLocalClient(clientId);\n if (lost || this.hasOpenLocalClients()) {\n return;\n }\n\n const owner = this.owner;\n if (owner && !owner.hasActiveClientsExcept(clientId)) {\n owner.stop();\n }\n }\n\n private route(clientId: string, request: unknown): void {\n void this.routeAsync(clientId, request);\n }\n\n private async routeAsync(clientId: string, request: unknown): Promise<void> {\n const id = requestId(request);\n try {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n admitLocalClientRequest(localClient, request);\n }\n\n const hasClientLock = await this.waitForLocalClientLock(clientId);\n if (!this.localClientsById.has(clientId)) {\n return;\n }\n\n // Wait for ownership so this request is not posted into the void.\n if (!this.owner && !this.ownerError) {\n this.contendForOwnership();\n }\n await this.ownershipSettled;\n if (!this.localClientsById.has(clientId)) {\n return;\n }\n\n // A client can be lost while it waits, when this tab is promoted.\n if (localClient) {\n assertLocalClientConnected(localClient);\n }\n\n if (this.owner) {\n this.owner.route(clientId, request, { hasClientLock });\n return;\n }\n\n // This tab won ownership earlier but its owner worker failed to construct.\n // If another tab has since become a healthy owner, fall back to it; only\n // surface the construction error when no owner exists anywhere, so a single\n // tab whose worker cannot start fails fast instead of hanging on the timeout.\n if (this.ownerError && !(await this.anotherTabOwns())) {\n throw this.ownerError;\n }\n\n this.postRemoteRequest(clientId, request, hasClientLock);\n } catch (error: unknown) {\n if (id !== null) {\n this.dispatchLocalResponse(\n clientId,\n errorResponse(\n id,\n error instanceof Error\n ? error.message\n : \"Failed to route database request.\",\n ),\n );\n }\n }\n }\n\n private async waitForLocalClientLock(clientId: string): Promise<boolean> {\n const localClient = this.localClientsById.get(clientId);\n if (!localClient) {\n return false;\n }\n\n return localClient.liveness.ready;\n }\n\n private postRemoteRequest(\n clientId: string,\n request: unknown,\n hasClientLock: boolean,\n ): void {\n const id = requestId(request);\n if (id !== null) {\n const localClient = this.localClientsById.get(clientId);\n localClient?.pendingRemoteRequestIds.add(id);\n const timeoutId = setTimeout(() => {\n localClient?.timeoutsByRequestId.delete(id);\n localClient?.pendingRemoteRequestIds.delete(id);\n this.dispatchLocalResponse(\n clientId,\n errorResponse(id, \"Timed out waiting for the database owner tab.\"),\n );\n }, CROSS_TAB_REQUEST_TIMEOUT_MS);\n localClient?.timeoutsByRequestId.set(id, timeoutId);\n }\n\n this.channel.postMessage({\n type: \"request\",\n clientId,\n hasClientLock,\n request,\n });\n }\n\n private dispatchLocalResponse(clientId: string, response: unknown): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n dispatchResponseToLocalClient(localClient, response);\n }\n }\n\n private dispatchLocalError(\n clientId: string,\n error: DatabaseWorkerCrashError,\n ): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n dispatchCrashToLocalClient(localClient, error);\n }\n }\n\n // A crashed owner worker is the same failure class as one that never\n // constructed: record it so routing fails fast instead of rebuilding the\n // crashed worker on the next bid (`contendForOwnership` and the post-release\n // retry both stop on `ownerError`), and fail every local client — including\n // one whose first request has not been routed yet, which is exactly where a\n // script-load failure lands. The next `createWorker()` (a fresh runtime boot)\n // clears the error and re-contends.\n private handleOwnerCrash(error: DatabaseWorkerCrashError): void {\n this.ownerError = error;\n for (const localClient of this.localClientsById.values()) {\n dispatchCrashToLocalClient(localClient, error);\n }\n }\n\n private unregisterLocalClient(clientId: string): void {\n const localClient = this.localClientsById.get(clientId);\n if (localClient) {\n releaseLocalClient(localClient);\n }\n\n this.localClientsById.delete(clientId);\n }\n\n private handleChannelMessage(event: MessageEvent): void {\n const envelope = event.data;\n if (!isCrossTabEnvelope(envelope)) {\n return;\n }\n\n if (envelope.type === \"request\") {\n this.owner?.route(envelope.clientId, envelope.request, {\n hasClientLock: envelope.hasClientLock === true,\n });\n return;\n }\n\n if (envelope.type === \"error\") {\n this.dispatchLocalError(\n envelope.clientId,\n new DatabaseWorkerCrashError(envelope.detail),\n );\n return;\n }\n\n this.dispatchLocalResponse(envelope.clientId, envelope.response);\n }\n\n /**\n * Hold one blocking owner-lock bid. The current holder owns until it releases;\n * queued bidders are promoted when the holder disappears.\n */\n private contendForOwnership(): void {\n if (this.owner || this.ownershipBidActive || this.ownerError) {\n return;\n }\n\n const locks = lockManager();\n if (!locks) {\n // No Web Locks: unblock routing and rely on the request timeout.\n this.settleOwnership();\n return;\n }\n\n this.ownershipBidActive = true;\n const generation = this.ownershipGeneration;\n // A non-owner tab's blocking bid stays queued (never enters its callback)\n // until the current owner dies, so it cannot settle the routing gate on its\n // own. Settle it from here as soon as ownership is known either way.\n this.observeExistingOwner(locks, generation);\n\n let releasedNormally = false;\n\n void locks\n .request(CROSS_TAB_OWNER_LOCK_NAME, null, async () => {\n let releaseOwner: (() => void) | null = null;\n const ownerReleased = new Promise<void>((resolve) => {\n releaseOwner = resolve;\n });\n try {\n const owner = new CrossTabOwner(\n this.workerUrl,\n this.workerConstructor,\n this.channel,\n (clientId, response) =>\n this.dispatchLocalResponse(clientId, response),\n (error) => this.handleOwnerCrash(error),\n () => {\n if (this.owner === owner) {\n this.owner = null;\n // After a crash the gate stays settled: routing fails fast on\n // the recorded error instead of waiting for a bid that must\n // not run until a fresh client asks for one.\n if (!this.ownerError) {\n this.resetOwnershipGate();\n }\n }\n releaseOwner?.();\n },\n );\n this.owner = owner;\n this.ownerError = null;\n // The previous owner is gone, with every database it had open.\n this.releaseClientsFromPreviousOwner();\n this.settleOwnership(generation);\n await ownerReleased;\n releasedNormally = true;\n } catch (error) {\n // This tab won ownership but could not stand up the owner worker. Record\n // the failure so its own clients see the error instead of hanging, then\n // rethrow to release the lock so another tab can try to own.\n this.owner = null;\n this.ownerError =\n error instanceof Error ? error : new Error(String(error));\n this.releaseClientsFromPreviousOwner();\n this.settleOwnership(generation);\n throw error;\n }\n })\n .catch(() => {\n // The bid itself failed (e.g. the lock manager rejected). Unblock routing\n // so requests fall back to the remote path instead of hanging forever.\n this.settleOwnership(generation);\n })\n .finally(() => {\n this.ownershipBidActive = false;\n const shouldRetryOwnership =\n releasedNormally || this.retryOwnershipAfterBid;\n this.retryOwnershipAfterBid = false;\n if (!shouldRetryOwnership) {\n return;\n }\n\n queueMicrotask(() => {\n if (this.hasOpenLocalClients() && !this.owner && !this.ownerError) {\n this.contendForOwnership();\n }\n });\n });\n }\n\n private hasOpenLocalClients(): boolean {\n for (const localClient of this.localClientsById.values()) {\n if (isOpenLocalClient(localClient)) {\n return true;\n }\n }\n\n return false;\n }\n\n /**\n * Settle the initial routing gate on a tab that did NOT win ownership. Runs\n * concurrently with the blocking bid above; whichever resolves first settles the\n * gate (the bid settles it on the tab that becomes owner, this settles it on\n * every other tab). See {@link pollForOwner} for why this polls.\n *\n * Falls back to settling immediately when the lock manager cannot be queried, so\n * routing is never blocked indefinitely.\n */\n private observeExistingOwner(\n locks: LockManagerLike,\n generation: number,\n ): void {\n if (!locks.query) {\n // No query support: cannot observe another tab's owner without contending\n // for the lock (which would steal it). Settle so routing proceeds remotely.\n this.settleOwnership(generation);\n return;\n }\n\n void pollForOwner({\n locks,\n lockName: CROSS_TAB_OWNER_LOCK_NAME,\n hasOwner: () => this.owner !== null,\n settle: () => this.settleOwnership(generation),\n });\n }\n\n private resetOwnershipGate(): void {\n this.ownershipGeneration += 1;\n this.ownershipSettled = new Promise((resolve) => {\n this.settleOwnershipGate = resolve;\n });\n }\n\n private settleOwnership(generation = this.ownershipGeneration): void {\n if (generation !== this.ownershipGeneration) {\n return;\n }\n\n this.settleOwnershipGate();\n }\n\n /**\n * Whether some other tab currently holds the owner lock. Used by routing to\n * decide, when this tab's own owner failed to construct, between surfacing that\n * error (no owner anywhere) and falling back to a healthy remote owner. Returns\n * false when the lock cannot be queried, so routing posts remotely and lets the\n * request/timeout path decide rather than throwing a possibly-stale error.\n */\n private async anotherTabOwns(): Promise<boolean> {\n if (this.owner) {\n return false;\n }\n\n const locks = lockManager();\n return locks ? isOwnerLockHeld(locks, CROSS_TAB_OWNER_LOCK_NAME) : false;\n }\n\n // Called when this tab takes the owner lock: the owner its clients had been\n // routing to is gone (see releaseLocalClientFromPreviousOwner).\n private releaseClientsFromPreviousOwner(): void {\n for (const localClient of this.localClientsById.values()) {\n releaseLocalClientFromPreviousOwner(localClient);\n }\n }\n}\n\nconst coordinatorsByWorkerUrl = new Map<string, CrossTabCoordinator>();\n\nexport function createCrossTabDatabaseWorker(\n workerUrl: string | URL,\n workerConstructor: ModuleWorkerConstructor,\n): CrossTabDatabaseWorker | null {\n if (!canUseCrossTabPrimitives()) {\n return null;\n }\n\n const key = String(workerUrl);\n let coordinator = coordinatorsByWorkerUrl.get(key);\n if (!coordinator) {\n coordinator = new CrossTabCoordinator(workerUrl, workerConstructor);\n coordinatorsByWorkerUrl.set(key, coordinator);\n }\n\n return coordinator.createWorker();\n}\n"]}
@@ -1,5 +1,6 @@
1
1
  import { type DatabaseWorkerClient, type WorkerLike } from "./client.js";
2
2
  import { type DatabaseRuntimeMessageChannelConstructor } from "./renewedClientTransport.js";
3
+ export { DatabaseConnectionLostError, isDatabaseConnectionLostError, } from "./workerCrash.js";
3
4
  interface TerminableWorkerLike extends WorkerLike {
4
5
  terminate(): void;
5
6
  }
@@ -93,4 +94,3 @@ export interface CreateModuleDatabaseRuntimeOptions {
93
94
  export declare function createDatabaseRuntime(worker: TerminableWorkerLike, messageChannelConstructor?: DatabaseRuntimeMessageChannelConstructor | null): DatabaseRuntime;
94
95
  export declare function createSharedDatabaseRuntime(worker: CloseableWorkerLike): DatabaseRuntime;
95
96
  export declare function createModuleDatabaseRuntime(options?: CreateModuleDatabaseRuntimeOptions): DatabaseRuntime;
96
- export {};
@@ -3,6 +3,7 @@ import { createDatabaseWorkerClient, } from "./client.js";
3
3
  import { createCrossTabDatabaseWorker } from "./crossTabRuntime.js";
4
4
  import { availableMessageChannelConstructor, closeMessagePort, createRenewedDatabaseClient, disconnectMessagePort, } from "./renewedClientTransport.js";
5
5
  import { workerCrashErrorFromEvent } from "./workerCrash.js";
6
+ export { DatabaseConnectionLostError, isDatabaseConnectionLostError, } from "./workerCrash.js";
6
7
  const DEFAULT_DATABASE_WORKER_URL = "/worker.js";
7
8
  const DEFAULT_SHARED_DATABASE_WORKER_NAME = "tearleads-sqlite-worker";
8
9
  function subscribeWorkerError(worker) {
@@ -1 +1 @@
1
- {"version":3,"file":"runtime.js","sourceRoot":"","sources":["runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,0BAA0B,GAG3B,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EACL,kCAAkC,EAClC,gBAAgB,EAChB,2BAA2B,EAG3B,qBAAqB,GACtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAE1D,MAAM,2BAA2B,GAAG,YAAY,CAAC;AACjD,MAAM,mCAAmC,GAAG,yBAAyB,CAAC;AA+EtE,SAAS,oBAAoB,CAC3B,MAAkB;IAElB,OAAO,CAAC,QAAQ,EAAE,EAAE;QAClB,MAAM,WAAW,GAAG,CAAC,KAAY,EAAE,EAAE;YACnC,QAAQ,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC7C,CAAC,CAAC;QACF,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QAC9C,OAAO,GAAG,EAAE;YACV,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QACnD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AED,IACE,OAAO,OAAO,CAAC,iBAAiB,KAAK,WAAW;QAChD,OAAO,MAAM,KAAK,WAAW,EAC7B,CAAC;QACD,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,qBAAqB,CAC1B,kBAAkB,CAChB,OAAO,CAAC,SAAS,IAAI,2BAA2B,EAChD,OAAO,CAAC,iBAAiB,CAC1B,EACD,kCAAkC,CAAC,OAAO,CAAC,yBAAyB,CAAC,CACtE,CAAC;AACJ,CAAC","sourcesContent":["import { evictCachedDatabasePages } from \"./cachedPageEviction\";\nimport {\n createDatabaseWorkerClient,\n type DatabaseWorkerClient,\n type WorkerLike,\n} from \"./client\";\nimport { createCrossTabDatabaseWorker } from \"./crossTabRuntime\";\nimport {\n availableMessageChannelConstructor,\n closeMessagePort,\n createRenewedDatabaseClient,\n type DatabaseRuntimeMessageChannelConstructor,\n type DatabaseRuntimeMessagePort,\n disconnectMessagePort,\n} from \"./renewedClientTransport\";\nimport { workerCrashErrorFromEvent } from \"./workerCrash\";\n\nconst DEFAULT_DATABASE_WORKER_URL = \"/worker.js\";\nconst DEFAULT_SHARED_DATABASE_WORKER_NAME = \"tearleads-sqlite-worker\";\n\ninterface TerminableWorkerLike extends WorkerLike {\n terminate(): void;\n}\n\ninterface CloseableWorkerLike extends WorkerLike {\n close(): void;\n /**\n * Cross-tab worker only: force-stop a possibly-wedged owner (its worker went\n * silent and never answered the graceful `close`) so the next boot builds a\n * fresh owner. Absent on a real SharedWorker port, where the browser reclaims\n * the port/owner itself; called optionally.\n */\n forceStopOwner?(): void;\n}\n\nexport interface ModuleWorkerLike extends TerminableWorkerLike {}\n\nexport interface ModuleWorkerConstructor {\n new (scriptURL: string | URL, options?: WorkerOptions): ModuleWorkerLike;\n}\n\nexport interface ModuleSharedWorkerLike {\n readonly port: CloseableWorkerLike & { start?: () => void };\n addEventListener?: WorkerLike[\"addEventListener\"];\n removeEventListener?: WorkerLike[\"removeEventListener\"];\n}\n\nexport interface ModuleSharedWorkerConstructor {\n new (\n scriptURL: string | URL,\n options?: {\n name?: string;\n type?: \"classic\" | \"module\";\n },\n ): ModuleSharedWorkerLike;\n}\n\nexport interface DatabaseRuntime {\n id: string;\n client: DatabaseWorkerClient;\n destroy(): void;\n /**\n * Permanently destroy the persisted database: ask the worker to wipe its OPFS\n * files (not merely release the handles, as {@link destroy} does), then\n * terminate the worker. Resolves once teardown completes. Used to forget local\n * data on logout. Best-effort: a wipe failure still terminates the worker.\n */\n deleteData(): Promise<void>;\n /**\n * Synchronous, abrupt teardown for page-unload handlers (`pagehide`), where\n * there is no time for destroy()'s async graceful close. Terminating the worker\n * thread releases its OPFS access handles promptly, so the next page's worker\n * can acquire them instead of racing a leaked handle from the discarded page.\n */\n terminateNow(): void;\n /**\n * Replace this runtime's main-thread client (and its `id`) with a fresh one on\n * the SAME worker, without tearing the worker down. Used when the worker is\n * reused for a different database (see the app's `reuseDatabaseWorker` path):\n * the SDK keys per-connection caches — schema/projection ensures, mutation\n * queues, persistence runtimes — off the client object, so a new database MUST\n * see a fresh client or it inherits the previous database's \"schema already\n * ensured\" state and then queries/writes missing tables. Only the dedicated\n * runtime implements this; the cross-tab runtime omits it (it is never reused).\n */\n renewClient?(): void;\n /**\n * Observe the worker crashing (an `error` event: a failed script load or an\n * uncaught exception outside request handling). The client has already\n * rejected every in-flight request with the same failure; this is the host's\n * signal to report it and retire the runtime, because errors thrown inside a\n * Worker never reach the page's own error handlers. Returns an unsubscribe.\n * Runtimes hosts construct themselves may omit it.\n */\n subscribeWorkerError?(listener: (error: Error) => void): () => void;\n}\n\nfunction subscribeWorkerError(\n worker: WorkerLike,\n): NonNullable<DatabaseRuntime[\"subscribeWorkerError\"]> {\n return (listener) => {\n const handleError = (event: Event) => {\n listener(workerCrashErrorFromEvent(event));\n };\n worker.addEventListener(\"error\", handleError);\n return () => {\n worker.removeEventListener(\"error\", handleError);\n };\n };\n}\n\nexport interface CreateModuleDatabaseRuntimeOptions {\n /**\n * Dedicated Worker fallback. Supplying this keeps the historical dedicated\n * worker path, which is useful for tests and non-browser hosts.\n */\n workerConstructor?: ModuleWorkerConstructor;\n /**\n * SharedWorker constructor for browser hosts that can share one SQLite owner\n * across tabs. Pass `null` to force the dedicated Worker fallback.\n */\n sharedWorkerConstructor?: ModuleSharedWorkerConstructor | null;\n sharedWorkerName?: string;\n /**\n * Overrides the channel used to give a renewed client fresh worker-side\n * connection state. Pass `null` in hosts without transferable message ports;\n * the returned runtime then omits its optional renewal capability.\n */\n messageChannelConstructor?: DatabaseRuntimeMessageChannelConstructor | null;\n workerUrl?: string | URL;\n}\n\nfunction createModuleWorker(\n workerUrl: string | URL,\n workerConstructor: ModuleWorkerConstructor = globalThis.Worker,\n): ModuleWorkerLike {\n return new workerConstructor(workerUrl, { type: \"module\" });\n}\n\nfunction portFromModuleSharedWorker(\n sharedWorker: ModuleSharedWorkerLike,\n): CloseableWorkerLike {\n sharedWorker.port.start?.();\n\n return {\n postMessage(message) {\n sharedWorker.port.postMessage(message);\n },\n addEventListener(type, listener) {\n if (type === \"error\" && sharedWorker.addEventListener) {\n sharedWorker.addEventListener(type, listener);\n return;\n }\n\n sharedWorker.port.addEventListener(type, listener);\n },\n removeEventListener(type, listener) {\n if (type === \"error\" && sharedWorker.removeEventListener) {\n sharedWorker.removeEventListener(type, listener);\n return;\n }\n\n sharedWorker.port.removeEventListener(type, listener);\n },\n close() {\n sharedWorker.port.close();\n },\n };\n}\n\nfunction createModuleSharedWorkerPort(\n workerUrl: string | URL,\n sharedWorkerConstructor: ModuleSharedWorkerConstructor,\n sharedWorkerName: string,\n): CloseableWorkerLike {\n return portFromModuleSharedWorker(\n new sharedWorkerConstructor(workerUrl, {\n name: sharedWorkerName,\n type: \"module\",\n }),\n );\n}\n\nfunction createExplicitSharedWorkerPort(\n options: CreateModuleDatabaseRuntimeOptions,\n): CloseableWorkerLike | null {\n if (options.workerConstructor || !options.sharedWorkerConstructor) {\n return null;\n }\n\n return createModuleSharedWorkerPort(\n options.workerUrl ?? DEFAULT_DATABASE_WORKER_URL,\n options.sharedWorkerConstructor,\n options.sharedWorkerName ?? DEFAULT_SHARED_DATABASE_WORKER_NAME,\n );\n}\n\n// Upper bound on how long destroy() waits for the worker's graceful close\n// (db close + SAHPool handle release) before terminating anyway. Releasing the\n// OPFS handles is near-instant; this only guards against a wedged worker so\n// teardown can never hang. If it elapses we terminate regardless — the browser\n// then releases the handles asynchronously and the next boot's contention retry\n// covers the gap.\nconst GRACEFUL_CLOSE_TIMEOUT_MS = 1_000;\n\nexport function createDatabaseRuntime(\n worker: TerminableWorkerLike,\n messageChannelConstructor = availableMessageChannelConstructor(),\n): DatabaseRuntime {\n // Client/id stay mutable for same-worker renewal; one request-id sequence spans\n // generations so a late old response cannot match a replacement request.\n const requestIdSequence = { current: 1 };\n let client = createDatabaseWorkerClient(worker, requestIdSequence);\n let activeClientPort: DatabaseRuntimeMessagePort | null = null;\n let id: string = crypto.randomUUID();\n let torndown = false;\n\n // Terminate exactly once, tearing down the client first so its pending-request\n // map is cleared and listeners removed.\n const terminate = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n client.destroy();\n closeMessagePort(activeClientPort);\n activeClientPort = null;\n worker.terminate();\n };\n\n const runtime: DatabaseRuntime = {\n get id() {\n return id;\n },\n get client() {\n return client;\n },\n destroy() {\n if (torndown) {\n return;\n }\n // Ask the worker to release the database and its OPFS access handles\n // *before* we terminate it. terminate() alone releases handles only\n // asynchronously, which is what makes a reloaded page's SAHPool install\n // race and fail; closing first hands the handles off cleanly.\n //\n // destroy() stays synchronous (React effect cleanups can't await), so this\n // is fire-and-forget: terminate once the worker confirms the close, or\n // once the timeout elapses if it never does. `terminate` is idempotent, so\n // the race between the two is harmless.\n const timeoutId = setTimeout(terminate, GRACEFUL_CLOSE_TIMEOUT_MS);\n client.close().then(\n () => {\n clearTimeout(timeoutId);\n terminate();\n },\n () => {\n // The worker may already be gone or never responded; terminate anyway.\n clearTimeout(timeoutId);\n terminate();\n },\n );\n },\n async deleteData() {\n if (torndown) {\n return;\n }\n // Ask the worker to wipe its OPFS files before terminating. Unlike\n // destroy()'s fire-and-forget close, callers await this so they know the\n // data is gone before re-provisioning a fresh database. The wipe is\n // best-effort inside the worker; terminate regardless once it settles or\n // the timeout elapses so teardown can never hang on a wedged worker.\n await new Promise<void>((resolve) => {\n const timeoutId = setTimeout(() => {\n terminate();\n resolve();\n }, GRACEFUL_CLOSE_TIMEOUT_MS);\n const finish = () => {\n clearTimeout(timeoutId);\n terminate();\n resolve();\n };\n client.delete().then(finish, finish);\n });\n },\n terminateNow() {\n terminate();\n },\n subscribeWorkerError: subscribeWorkerError(worker),\n };\n\n if (messageChannelConstructor) {\n runtime.renewClient = () => {\n if (torndown) {\n return;\n }\n\n let renewed: ReturnType<typeof createRenewedDatabaseClient>;\n try {\n renewed = createRenewedDatabaseClient({\n messageChannelConstructor,\n requestIdSequence,\n worker,\n });\n } catch (error) {\n // MessageChannel existence does not guarantee this Worker accepts a\n // transferred port. Retire the capability so the app's next retry uses\n // its safe teardown/new-runtime fallback instead of looping this failure.\n delete runtime.renewClient;\n throw error;\n }\n\n const previousClient = client;\n const previousPort = activeClientPort;\n client = renewed.client;\n activeClientPort = renewed.port;\n id = renewed.id;\n\n // Only retire the previous generation after the worker accepted the new\n // port. A failed transfer therefore leaves the old client fully usable.\n previousClient.destroy();\n disconnectMessagePort(previousPort);\n };\n }\n\n return runtime;\n}\n\nfunction postCloseWithoutWaiting(worker: WorkerLike): void {\n try {\n worker.postMessage({ id: 0, method: \"close\", params: undefined });\n } catch {\n // The page is unloading or the closeable port is already gone. The browser\n // will release page-owned ports/workers when the document is discarded.\n }\n}\n\nexport function createSharedDatabaseRuntime(\n worker: CloseableWorkerLike,\n): DatabaseRuntime {\n const client = createDatabaseWorkerClient(worker);\n let torndown = false;\n\n const close = () => {\n if (torndown) {\n return;\n }\n\n torndown = true;\n client.destroy();\n worker.close();\n };\n\n // Abrupt teardown: the graceful `close`/`delete` never came back (the worker is\n // wedged) or there was no time to wait for it, so the owner was never stopped\n // via its close-response. Also force-stop a possibly-wedged owner so the next\n // boot re-contends and builds a fresh owner instead of routing into the dead\n // one. Idempotent and no-ops when the owner already stopped itself (healthy\n // close) or this tab is not the owner.\n const forceClose = () => {\n if (torndown) {\n return;\n }\n\n torndown = true;\n client.destroy();\n worker.forceStopOwner?.();\n worker.close();\n };\n\n return {\n id: crypto.randomUUID(),\n client,\n destroy() {\n if (torndown) {\n return;\n }\n\n // The worker acked the graceful close within the budget → it already stopped\n // the owner itself, so a plain close() suffices. If it did NOT ack (timeout\n // or rejection), it may be wedged → force-stop the owner.\n const timeoutId = setTimeout(forceClose, GRACEFUL_CLOSE_TIMEOUT_MS);\n client.close().then(\n () => {\n clearTimeout(timeoutId);\n close();\n },\n () => {\n clearTimeout(timeoutId);\n forceClose();\n },\n );\n },\n async deleteData() {\n if (torndown) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n const timeoutId = setTimeout(() => {\n forceClose();\n resolve();\n }, GRACEFUL_CLOSE_TIMEOUT_MS);\n const finish = () => {\n clearTimeout(timeoutId);\n close();\n resolve();\n };\n const fail = () => {\n clearTimeout(timeoutId);\n forceClose();\n resolve();\n };\n client.delete().then(finish, fail);\n });\n },\n terminateNow() {\n if (torndown) {\n return;\n }\n\n postCloseWithoutWaiting(worker);\n forceClose();\n },\n subscribeWorkerError: subscribeWorkerError(worker),\n };\n}\n\nexport function createModuleDatabaseRuntime(\n options: CreateModuleDatabaseRuntimeOptions = {},\n): DatabaseRuntime {\n evictCachedDatabasePages();\n if (\n !options.workerConstructor &&\n options.sharedWorkerConstructor === undefined &&\n typeof Worker !== \"undefined\"\n ) {\n const crossTabWorker = createCrossTabDatabaseWorker(\n options.workerUrl ?? DEFAULT_DATABASE_WORKER_URL,\n globalThis.Worker,\n );\n if (crossTabWorker) {\n return createSharedDatabaseRuntime(crossTabWorker);\n }\n }\n\n const sharedWorkerPort = createExplicitSharedWorkerPort(options);\n if (sharedWorkerPort) {\n return createSharedDatabaseRuntime(sharedWorkerPort);\n }\n\n if (\n typeof options.workerConstructor === \"undefined\" &&\n typeof Worker === \"undefined\"\n ) {\n throw new Error(\"Worker must be defined.\");\n }\n\n return createDatabaseRuntime(\n createModuleWorker(\n options.workerUrl ?? DEFAULT_DATABASE_WORKER_URL,\n options.workerConstructor,\n ),\n availableMessageChannelConstructor(options.messageChannelConstructor),\n );\n}\n"]}
1
+ {"version":3,"file":"runtime.js","sourceRoot":"","sources":["runtime.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,wBAAwB,EAAE,MAAM,sBAAsB,CAAC;AAChE,OAAO,EACL,0BAA0B,GAG3B,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,4BAA4B,EAAE,MAAM,mBAAmB,CAAC;AACjE,OAAO,EACL,kCAAkC,EAClC,gBAAgB,EAChB,2BAA2B,EAG3B,qBAAqB,GACtB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,yBAAyB,EAAE,MAAM,eAAe,CAAC;AAE1D,OAAO,EACL,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,eAAe,CAAC;AAEvB,MAAM,2BAA2B,GAAG,YAAY,CAAC;AACjD,MAAM,mCAAmC,GAAG,yBAAyB,CAAC;AA+EtE,SAAS,oBAAoB,CAC3B,MAAkB;IAElB,OAAO,CAAC,QAAQ,EAAE,EAAE;QAClB,MAAM,WAAW,GAAG,CAAC,KAAY,EAAE,EAAE;YACnC,QAAQ,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC,CAAC;QAC7C,CAAC,CAAC;QACF,MAAM,CAAC,gBAAgB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QAC9C,OAAO,GAAG,EAAE;YACV,MAAM,CAAC,mBAAmB,CAAC,OAAO,EAAE,WAAW,CAAC,CAAC;QACnD,CAAC,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAuBD,SAAS,kBAAkB,CACzB,SAAuB,EACvB,oBAA6C,UAAU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AM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IAED,OAAO,qBAAqB,CAC1B,kBAAkB,CAChB,OAAO,CAAC,SAAS,IAAI,2BAA2B,EAChD,OAAO,CAAC,iBAAiB,CAC1B,EACD,kCAAkC,CAAC,OAAO,CAAC,yBAAyB,CAAC,CACtE,CAAC;AACJ,CAAC","sourcesContent":["import { evictCachedDatabasePages } from \"./cachedPageEviction\";\nimport {\n createDatabaseWorkerClient,\n type DatabaseWorkerClient,\n type WorkerLike,\n} from \"./client\";\nimport { createCrossTabDatabaseWorker } from \"./crossTabRuntime\";\nimport {\n availableMessageChannelConstructor,\n closeMessagePort,\n createRenewedDatabaseClient,\n type DatabaseRuntimeMessageChannelConstructor,\n type DatabaseRuntimeMessagePort,\n disconnectMessagePort,\n} from \"./renewedClientTransport\";\nimport { workerCrashErrorFromEvent } from \"./workerCrash\";\n\nexport {\n DatabaseConnectionLostError,\n isDatabaseConnectionLostError,\n} from \"./workerCrash\";\n\nconst DEFAULT_DATABASE_WORKER_URL = \"/worker.js\";\nconst DEFAULT_SHARED_DATABASE_WORKER_NAME = \"tearleads-sqlite-worker\";\n\ninterface TerminableWorkerLike extends WorkerLike {\n terminate(): void;\n}\n\ninterface CloseableWorkerLike extends WorkerLike {\n close(): void;\n /**\n * Cross-tab worker only: force-stop a possibly-wedged owner (its worker went\n * silent and never answered the graceful `close`) so the next boot builds a\n * fresh owner. Absent on a real SharedWorker port, where the browser reclaims\n * the port/owner itself; called optionally.\n */\n forceStopOwner?(): void;\n}\n\nexport interface ModuleWorkerLike extends TerminableWorkerLike {}\n\nexport interface ModuleWorkerConstructor {\n new (scriptURL: string | URL, options?: WorkerOptions): ModuleWorkerLike;\n}\n\nexport interface ModuleSharedWorkerLike {\n readonly port: CloseableWorkerLike & { start?: () => void };\n addEventListener?: WorkerLike[\"addEventListener\"];\n removeEventListener?: WorkerLike[\"removeEventListener\"];\n}\n\nexport interface ModuleSharedWorkerConstructor {\n new (\n scriptURL: string | URL,\n options?: {\n name?: string;\n type?: \"classic\" | \"module\";\n },\n ): ModuleSharedWorkerLike;\n}\n\nexport interface DatabaseRuntime {\n id: string;\n client: DatabaseWorkerClient;\n destroy(): void;\n /**\n * Permanently destroy the persisted database: ask the worker to wipe its OPFS\n * files (not merely release the handles, as {@link destroy} does), then\n * terminate the worker. Resolves once teardown completes. Used to forget local\n * data on logout. Best-effort: a wipe failure still terminates the worker.\n */\n deleteData(): Promise<void>;\n /**\n * Synchronous, abrupt teardown for page-unload handlers (`pagehide`), where\n * there is no time for destroy()'s async graceful close. Terminating the worker\n * thread releases its OPFS access handles promptly, so the next page's worker\n * can acquire them instead of racing a leaked handle from the discarded page.\n */\n terminateNow(): void;\n /**\n * Replace this runtime's main-thread client (and its `id`) with a fresh one on\n * the SAME worker, without tearing the worker down. Used when the worker is\n * reused for a different database (see the app's `reuseDatabaseWorker` path):\n * the SDK keys per-connection caches — schema/projection ensures, mutation\n * queues, persistence runtimes — off the client object, so a new database MUST\n * see a fresh client or it inherits the previous database's \"schema already\n * ensured\" state and then queries/writes missing tables. Only the dedicated\n * runtime implements this; the cross-tab runtime omits it (it is never reused).\n */\n renewClient?(): void;\n /**\n * Observe the worker crashing (an `error` event: a failed script load or an\n * uncaught exception outside request handling). The client has already\n * rejected every in-flight request with the same failure; this is the host's\n * signal to report it and retire the runtime, because errors thrown inside a\n * Worker never reach the page's own error handlers. Returns an unsubscribe.\n * Runtimes hosts construct themselves may omit it.\n */\n subscribeWorkerError?(listener: (error: Error) => void): () => void;\n}\n\nfunction subscribeWorkerError(\n worker: WorkerLike,\n): NonNullable<DatabaseRuntime[\"subscribeWorkerError\"]> {\n return (listener) => {\n const handleError = (event: Event) => {\n listener(workerCrashErrorFromEvent(event));\n };\n worker.addEventListener(\"error\", handleError);\n return () => {\n worker.removeEventListener(\"error\", handleError);\n };\n };\n}\n\nexport interface CreateModuleDatabaseRuntimeOptions {\n /**\n * Dedicated Worker fallback. Supplying this keeps the historical dedicated\n * worker path, which is useful for tests and non-browser hosts.\n */\n workerConstructor?: ModuleWorkerConstructor;\n /**\n * SharedWorker constructor for browser hosts that can share one SQLite owner\n * across tabs. Pass `null` to force the dedicated Worker fallback.\n */\n sharedWorkerConstructor?: ModuleSharedWorkerConstructor | null;\n sharedWorkerName?: string;\n /**\n * Overrides the channel used to give a renewed client fresh worker-side\n * connection state. Pass `null` in hosts without transferable message ports;\n * the returned runtime then omits its optional renewal capability.\n */\n messageChannelConstructor?: DatabaseRuntimeMessageChannelConstructor | null;\n workerUrl?: string | URL;\n}\n\nfunction createModuleWorker(\n workerUrl: string | URL,\n workerConstructor: ModuleWorkerConstructor = globalThis.Worker,\n): ModuleWorkerLike {\n return new workerConstructor(workerUrl, { type: \"module\" });\n}\n\nfunction portFromModuleSharedWorker(\n sharedWorker: ModuleSharedWorkerLike,\n): CloseableWorkerLike {\n sharedWorker.port.start?.();\n\n return {\n postMessage(message) {\n sharedWorker.port.postMessage(message);\n },\n addEventListener(type, listener) {\n if (type === \"error\" && sharedWorker.addEventListener) {\n sharedWorker.addEventListener(type, listener);\n return;\n }\n\n sharedWorker.port.addEventListener(type, listener);\n },\n removeEventListener(type, listener) {\n if (type === \"error\" && sharedWorker.removeEventListener) {\n sharedWorker.removeEventListener(type, listener);\n return;\n }\n\n sharedWorker.port.removeEventListener(type, listener);\n },\n close() {\n sharedWorker.port.close();\n },\n };\n}\n\nfunction createModuleSharedWorkerPort(\n workerUrl: string | URL,\n sharedWorkerConstructor: ModuleSharedWorkerConstructor,\n sharedWorkerName: string,\n): CloseableWorkerLike {\n return portFromModuleSharedWorker(\n new sharedWorkerConstructor(workerUrl, {\n name: sharedWorkerName,\n type: \"module\",\n }),\n );\n}\n\nfunction createExplicitSharedWorkerPort(\n options: CreateModuleDatabaseRuntimeOptions,\n): CloseableWorkerLike | null {\n if (options.workerConstructor || !options.sharedWorkerConstructor) {\n return null;\n }\n\n return createModuleSharedWorkerPort(\n options.workerUrl ?? DEFAULT_DATABASE_WORKER_URL,\n options.sharedWorkerConstructor,\n options.sharedWorkerName ?? DEFAULT_SHARED_DATABASE_WORKER_NAME,\n );\n}\n\n// Upper bound on how long destroy() waits for the worker's graceful close\n// (db close + SAHPool handle release) before terminating anyway. Releasing the\n// OPFS handles is near-instant; this only guards against a wedged worker so\n// teardown can never hang. If it elapses we terminate regardless — the browser\n// then releases the handles asynchronously and the next boot's contention retry\n// covers the gap.\nconst GRACEFUL_CLOSE_TIMEOUT_MS = 1_000;\n\nexport function createDatabaseRuntime(\n worker: TerminableWorkerLike,\n messageChannelConstructor = availableMessageChannelConstructor(),\n): DatabaseRuntime {\n // Client/id stay mutable for same-worker renewal; one request-id sequence spans\n // generations so a late old response cannot match a replacement request.\n const requestIdSequence = { current: 1 };\n let client = createDatabaseWorkerClient(worker, requestIdSequence);\n let activeClientPort: DatabaseRuntimeMessagePort | null = null;\n let id: string = crypto.randomUUID();\n let torndown = false;\n\n // Terminate exactly once, tearing down the client first so its pending-request\n // map is cleared and listeners removed.\n const terminate = () => {\n if (torndown) {\n return;\n }\n torndown = true;\n client.destroy();\n closeMessagePort(activeClientPort);\n activeClientPort = null;\n worker.terminate();\n };\n\n const runtime: DatabaseRuntime = {\n get id() {\n return id;\n },\n get client() {\n return client;\n },\n destroy() {\n if (torndown) {\n return;\n }\n // Ask the worker to release the database and its OPFS access handles\n // *before* we terminate it. terminate() alone releases handles only\n // asynchronously, which is what makes a reloaded page's SAHPool install\n // race and fail; closing first hands the handles off cleanly.\n //\n // destroy() stays synchronous (React effect cleanups can't await), so this\n // is fire-and-forget: terminate once the worker confirms the close, or\n // once the timeout elapses if it never does. `terminate` is idempotent, so\n // the race between the two is harmless.\n const timeoutId = setTimeout(terminate, GRACEFUL_CLOSE_TIMEOUT_MS);\n client.close().then(\n () => {\n clearTimeout(timeoutId);\n terminate();\n },\n () => {\n // The worker may already be gone or never responded; terminate anyway.\n clearTimeout(timeoutId);\n terminate();\n },\n );\n },\n async deleteData() {\n if (torndown) {\n return;\n }\n // Ask the worker to wipe its OPFS files before terminating. Unlike\n // destroy()'s fire-and-forget close, callers await this so they know the\n // data is gone before re-provisioning a fresh database. The wipe is\n // best-effort inside the worker; terminate regardless once it settles or\n // the timeout elapses so teardown can never hang on a wedged worker.\n await new Promise<void>((resolve) => {\n const timeoutId = setTimeout(() => {\n terminate();\n resolve();\n }, GRACEFUL_CLOSE_TIMEOUT_MS);\n const finish = () => {\n clearTimeout(timeoutId);\n terminate();\n resolve();\n };\n client.delete().then(finish, finish);\n });\n },\n terminateNow() {\n terminate();\n },\n subscribeWorkerError: subscribeWorkerError(worker),\n };\n\n if (messageChannelConstructor) {\n runtime.renewClient = () => {\n if (torndown) {\n return;\n }\n\n let renewed: ReturnType<typeof createRenewedDatabaseClient>;\n try {\n renewed = createRenewedDatabaseClient({\n messageChannelConstructor,\n requestIdSequence,\n worker,\n });\n } catch (error) {\n // MessageChannel existence does not guarantee this Worker accepts a\n // transferred port. Retire the capability so the app's next retry uses\n // its safe teardown/new-runtime fallback instead of looping this failure.\n delete runtime.renewClient;\n throw error;\n }\n\n const previousClient = client;\n const previousPort = activeClientPort;\n client = renewed.client;\n activeClientPort = renewed.port;\n id = renewed.id;\n\n // Only retire the previous generation after the worker accepted the new\n // port. A failed transfer therefore leaves the old client fully usable.\n previousClient.destroy();\n disconnectMessagePort(previousPort);\n };\n }\n\n return runtime;\n}\n\nfunction postCloseWithoutWaiting(worker: WorkerLike): void {\n try {\n worker.postMessage({ id: 0, method: \"close\", params: undefined });\n } catch {\n // The page is unloading or the closeable port is already gone. The browser\n // will release page-owned ports/workers when the document is discarded.\n }\n}\n\nexport function createSharedDatabaseRuntime(\n worker: CloseableWorkerLike,\n): DatabaseRuntime {\n const client = createDatabaseWorkerClient(worker);\n let torndown = false;\n\n const close = () => {\n if (torndown) {\n return;\n }\n\n torndown = true;\n client.destroy();\n worker.close();\n };\n\n // Abrupt teardown: the graceful `close`/`delete` never came back (the worker is\n // wedged) or there was no time to wait for it, so the owner was never stopped\n // via its close-response. Also force-stop a possibly-wedged owner so the next\n // boot re-contends and builds a fresh owner instead of routing into the dead\n // one. Idempotent and no-ops when the owner already stopped itself (healthy\n // close) or this tab is not the owner.\n const forceClose = () => {\n if (torndown) {\n return;\n }\n\n torndown = true;\n client.destroy();\n worker.forceStopOwner?.();\n worker.close();\n };\n\n return {\n id: crypto.randomUUID(),\n client,\n destroy() {\n if (torndown) {\n return;\n }\n\n // The worker acked the graceful close within the budget → it already stopped\n // the owner itself, so a plain close() suffices. If it did NOT ack (timeout\n // or rejection), it may be wedged → force-stop the owner.\n const timeoutId = setTimeout(forceClose, GRACEFUL_CLOSE_TIMEOUT_MS);\n client.close().then(\n () => {\n clearTimeout(timeoutId);\n close();\n },\n () => {\n clearTimeout(timeoutId);\n forceClose();\n },\n );\n },\n async deleteData() {\n if (torndown) {\n return;\n }\n\n await new Promise<void>((resolve) => {\n const timeoutId = setTimeout(() => {\n forceClose();\n resolve();\n }, GRACEFUL_CLOSE_TIMEOUT_MS);\n const finish = () => {\n clearTimeout(timeoutId);\n close();\n resolve();\n };\n const fail = () => {\n clearTimeout(timeoutId);\n forceClose();\n resolve();\n };\n client.delete().then(finish, fail);\n });\n },\n terminateNow() {\n if (torndown) {\n return;\n }\n\n postCloseWithoutWaiting(worker);\n forceClose();\n },\n subscribeWorkerError: subscribeWorkerError(worker),\n };\n}\n\nexport function createModuleDatabaseRuntime(\n options: CreateModuleDatabaseRuntimeOptions = {},\n): DatabaseRuntime {\n evictCachedDatabasePages();\n if (\n !options.workerConstructor &&\n options.sharedWorkerConstructor === undefined &&\n typeof Worker !== \"undefined\"\n ) {\n const crossTabWorker = createCrossTabDatabaseWorker(\n options.workerUrl ?? DEFAULT_DATABASE_WORKER_URL,\n globalThis.Worker,\n );\n if (crossTabWorker) {\n return createSharedDatabaseRuntime(crossTabWorker);\n }\n }\n\n const sharedWorkerPort = createExplicitSharedWorkerPort(options);\n if (sharedWorkerPort) {\n return createSharedDatabaseRuntime(sharedWorkerPort);\n }\n\n if (\n typeof options.workerConstructor === \"undefined\" &&\n typeof Worker === \"undefined\"\n ) {\n throw new Error(\"Worker must be defined.\");\n }\n\n return createDatabaseRuntime(\n createModuleWorker(\n options.workerUrl ?? DEFAULT_DATABASE_WORKER_URL,\n options.workerConstructor,\n ),\n availableMessageChannelConstructor(options.messageChannelConstructor),\n );\n}\n"]}
@@ -93,6 +93,13 @@ export interface WorkerRequestMap {
93
93
  export declare const WORKER_CONNECT_PORT_MESSAGE_TYPE = "tearleads:sqlite-connect-port";
94
94
  export declare const WORKER_DISCONNECT_PORT_MESSAGE_TYPE = "tearleads:sqlite-disconnect-port";
95
95
  export declare const WORKER_PORT_DISCONNECTED_MESSAGE_TYPE = "tearleads:sqlite-port-disconnected";
96
+ export declare const DATABASE_NOT_INITIALIZED_MESSAGE = "Database has not been initialized.";
97
+ export declare const DATABASE_DELETED_MESSAGE = "Database was deleted by another connection.";
98
+ export declare const WORKER_DATABASE_DELETED_MESSAGE_TYPE = "tearleads:sqlite-database-deleted";
99
+ /** Posts an unprompted notice back to the connection's client. */
100
+ export type DatabaseWorkerNotify = (message: {
101
+ readonly type: string;
102
+ }) => void;
96
103
  export type WorkerMethod = keyof WorkerRequestMap;
97
104
  export type WorkerRequest<K extends WorkerMethod = WorkerMethod> = K extends WorkerMethod ? {
98
105
  id: number;
@@ -1,4 +1,16 @@
1
1
  export const WORKER_CONNECT_PORT_MESSAGE_TYPE = "tearleads:sqlite-connect-port";
2
2
  export const WORKER_DISCONNECT_PORT_MESSAGE_TYPE = "tearleads:sqlite-disconnect-port";
3
3
  export const WORKER_PORT_DISCONNECTED_MESSAGE_TYPE = "tearleads:sqlite-port-disconnected";
4
+ // The worker's answer to a statement on a connection with no open database.
5
+ // The cross-tab coordinator matches it to notice a client whose database was
6
+ // lost, so the worker and the coordinator share this one string.
7
+ export const DATABASE_NOT_INITIALIZED_MESSAGE = "Database has not been initialized.";
8
+ // The worker's answer to a statement on a connection whose database another
9
+ // connection deleted. A deliberate delete (logout, destroying an identity) is
10
+ // not a loss to recover from, so it must not read as a never-opened database.
11
+ export const DATABASE_DELETED_MESSAGE = "Database was deleted by another connection.";
12
+ // Posted unprompted on each other connection to a database the moment one
13
+ // connection deletes it, so a client learns of the delete before its owner tab
14
+ // can go away, even when it sends nothing in between.
15
+ export const WORKER_DATABASE_DELETED_MESSAGE_TYPE = "tearleads:sqlite-database-deleted";
4
16
  //# sourceMappingURL=types.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AA0HA,MAAM,CAAC,MAAM,gCAAgC,GAAG,+BAA+B,CAAC;AAChF,MAAM,CAAC,MAAM,mCAAmC,GAC9C,kCAAkC,CAAC;AACrC,MAAM,CAAC,MAAM,qCAAqC,GAChD,oCAAoC,CAAC","sourcesContent":["export type CipherName =\n | \"sqlcipher\"\n | \"chacha20\"\n | \"aes128cbc\"\n | \"aes256cbc\"\n | \"ascon128\";\n\n/**\n * Where the database file lives.\n *\n * - `\"memory\"`: transient in-memory database (the historical default). Wiped on\n * every reload / worker restart.\n * - `\"opfs-sahpool\"`: persistent database backed by the OPFS SyncAccessHandle\n * Pool VFS. Survives reloads (including hard / shift+reload) because the bytes\n * live in the Origin Private File System, not in the worker heap or the HTTP\n * cache. Requires neither `SharedArrayBuffer` nor COOP/COEP headers.\n *\n * When `\"opfs-sahpool\"` is requested but OPFS is unavailable (or the VFS fails\n * to install), `initDatabase` throws rather than silently degrading to memory —\n * persistence is opt-in and a missing backend is treated as a hard error.\n */\nexport type DatabasePersistenceMode = \"memory\" | \"opfs-sahpool\";\n\nexport interface DatabaseWorkerInitOptions {\n dbName: string;\n cipher: CipherName;\n key: string;\n /**\n * Storage backend for the database. Defaults to `\"memory\"` to preserve the\n * historical behavior for callers that do not opt into persistence.\n */\n persistence?: DatabasePersistenceMode;\n}\n\nexport type SqliteBindValue = string | number | null;\nexport type SqliteBind =\n | Record<string, SqliteBindValue>\n | ReadonlyArray<SqliteBindValue>;\nexport type SqliteRowMode = \"object\" | \"array\";\nexport type SqliteObjectRow = Record<string, SqliteBindValue>;\nexport type SqliteArrayRow = SqliteBindValue[];\nexport type SqliteRow = SqliteObjectRow | SqliteArrayRow;\n\nexport interface DatabaseWorkerExecOptions {\n sql: string;\n bind?: SqliteBind;\n rowMode?: SqliteRowMode;\n}\n\nexport interface DatabaseWorkerExecResult {\n ok: true;\n rows: SqliteRow[];\n}\n\nexport interface DatabaseWorkerReady {\n ok: true;\n}\n\nexport interface DatabaseWorkerClosed {\n ok: true;\n}\n\nexport interface DatabaseWorkerDeleted {\n ok: true;\n}\n\nexport interface DatabaseWorkerStorageWiped {\n ok: true;\n}\n\nexport interface DatabaseWorkerPingResult {\n ok: true;\n message: \"pong\";\n}\n\nexport interface DatabaseWorkerError {\n ok: false;\n message: string;\n}\n\nexport type DatabaseWorkerResult<T> = T | DatabaseWorkerError;\n\nexport interface WorkerRequestMap {\n ping: {\n params: undefined;\n result: DatabaseWorkerPingResult;\n };\n init: {\n params: DatabaseWorkerInitOptions;\n result: DatabaseWorkerReady;\n };\n exec: {\n params: DatabaseWorkerExecOptions;\n result: DatabaseWorkerExecResult;\n };\n // Graceful shutdown: close the db and release the persistent VFS's OPFS access\n // handles before the worker is terminated, so the next worker (reload / other\n // tab) can acquire them without losing the SAHPool lock-contention race.\n close: {\n params: undefined;\n result: DatabaseWorkerClosed;\n };\n // Drain previously accepted database work before the host authorizes a wipe.\n prepareDelete: {\n params: undefined;\n result: DatabaseWorkerReady;\n };\n // Destructive shutdown: close the db and WIPE the persistent VFS's OPFS files\n // (not merely release the handles). Used to forget local data on logout.\n delete: {\n params: undefined;\n result: DatabaseWorkerDeleted;\n };\n // Device reset: remove everything in this origin's OPFS from the worker, for\n // shells whose main thread has no OPFS (WKWebView). Rejected once this worker\n // has opened persistent storage, whose access handles it would still hold.\n wipeStorage: {\n params: undefined;\n result: DatabaseWorkerStorageWiped;\n };\n}\n\nexport const WORKER_CONNECT_PORT_MESSAGE_TYPE = \"tearleads:sqlite-connect-port\";\nexport const WORKER_DISCONNECT_PORT_MESSAGE_TYPE =\n \"tearleads:sqlite-disconnect-port\";\nexport const WORKER_PORT_DISCONNECTED_MESSAGE_TYPE =\n \"tearleads:sqlite-port-disconnected\";\n\nexport type WorkerMethod = keyof WorkerRequestMap;\n\nexport type WorkerRequest<K extends WorkerMethod = WorkerMethod> =\n K extends WorkerMethod\n ? {\n id: number;\n method: K;\n params: WorkerRequestMap[K][\"params\"];\n }\n : never;\n\nexport type WorkerResponse<K extends WorkerMethod = WorkerMethod> =\n K extends WorkerMethod\n ? {\n id: number;\n result: DatabaseWorkerResult<WorkerRequestMap[K][\"result\"]>;\n }\n : never;\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["types.ts"],"names":[],"mappings":"AA0HA,MAAM,CAAC,MAAM,gCAAgC,GAAG,+BAA+B,CAAC;AAChF,MAAM,CAAC,MAAM,mCAAmC,GAC9C,kCAAkC,CAAC;AACrC,MAAM,CAAC,MAAM,qCAAqC,GAChD,oCAAoC,CAAC;AAEvC,4EAA4E;AAC5E,6EAA6E;AAC7E,iEAAiE;AACjE,MAAM,CAAC,MAAM,gCAAgC,GAC3C,oCAAoC,CAAC;AAEvC,4EAA4E;AAC5E,8EAA8E;AAC9E,8EAA8E;AAC9E,MAAM,CAAC,MAAM,wBAAwB,GACnC,6CAA6C,CAAC;AAEhD,0EAA0E;AAC1E,+EAA+E;AAC/E,sDAAsD;AACtD,MAAM,CAAC,MAAM,oCAAoC,GAC/C,mCAAmC,CAAC","sourcesContent":["export type CipherName =\n | \"sqlcipher\"\n | \"chacha20\"\n | \"aes128cbc\"\n | \"aes256cbc\"\n | \"ascon128\";\n\n/**\n * Where the database file lives.\n *\n * - `\"memory\"`: transient in-memory database (the historical default). Wiped on\n * every reload / worker restart.\n * - `\"opfs-sahpool\"`: persistent database backed by the OPFS SyncAccessHandle\n * Pool VFS. Survives reloads (including hard / shift+reload) because the bytes\n * live in the Origin Private File System, not in the worker heap or the HTTP\n * cache. Requires neither `SharedArrayBuffer` nor COOP/COEP headers.\n *\n * When `\"opfs-sahpool\"` is requested but OPFS is unavailable (or the VFS fails\n * to install), `initDatabase` throws rather than silently degrading to memory —\n * persistence is opt-in and a missing backend is treated as a hard error.\n */\nexport type DatabasePersistenceMode = \"memory\" | \"opfs-sahpool\";\n\nexport interface DatabaseWorkerInitOptions {\n dbName: string;\n cipher: CipherName;\n key: string;\n /**\n * Storage backend for the database. Defaults to `\"memory\"` to preserve the\n * historical behavior for callers that do not opt into persistence.\n */\n persistence?: DatabasePersistenceMode;\n}\n\nexport type SqliteBindValue = string | number | null;\nexport type SqliteBind =\n | Record<string, SqliteBindValue>\n | ReadonlyArray<SqliteBindValue>;\nexport type SqliteRowMode = \"object\" | \"array\";\nexport type SqliteObjectRow = Record<string, SqliteBindValue>;\nexport type SqliteArrayRow = SqliteBindValue[];\nexport type SqliteRow = SqliteObjectRow | SqliteArrayRow;\n\nexport interface DatabaseWorkerExecOptions {\n sql: string;\n bind?: SqliteBind;\n rowMode?: SqliteRowMode;\n}\n\nexport interface DatabaseWorkerExecResult {\n ok: true;\n rows: SqliteRow[];\n}\n\nexport interface DatabaseWorkerReady {\n ok: true;\n}\n\nexport interface DatabaseWorkerClosed {\n ok: true;\n}\n\nexport interface DatabaseWorkerDeleted {\n ok: true;\n}\n\nexport interface DatabaseWorkerStorageWiped {\n ok: true;\n}\n\nexport interface DatabaseWorkerPingResult {\n ok: true;\n message: \"pong\";\n}\n\nexport interface DatabaseWorkerError {\n ok: false;\n message: string;\n}\n\nexport type DatabaseWorkerResult<T> = T | DatabaseWorkerError;\n\nexport interface WorkerRequestMap {\n ping: {\n params: undefined;\n result: DatabaseWorkerPingResult;\n };\n init: {\n params: DatabaseWorkerInitOptions;\n result: DatabaseWorkerReady;\n };\n exec: {\n params: DatabaseWorkerExecOptions;\n result: DatabaseWorkerExecResult;\n };\n // Graceful shutdown: close the db and release the persistent VFS's OPFS access\n // handles before the worker is terminated, so the next worker (reload / other\n // tab) can acquire them without losing the SAHPool lock-contention race.\n close: {\n params: undefined;\n result: DatabaseWorkerClosed;\n };\n // Drain previously accepted database work before the host authorizes a wipe.\n prepareDelete: {\n params: undefined;\n result: DatabaseWorkerReady;\n };\n // Destructive shutdown: close the db and WIPE the persistent VFS's OPFS files\n // (not merely release the handles). Used to forget local data on logout.\n delete: {\n params: undefined;\n result: DatabaseWorkerDeleted;\n };\n // Device reset: remove everything in this origin's OPFS from the worker, for\n // shells whose main thread has no OPFS (WKWebView). Rejected once this worker\n // has opened persistent storage, whose access handles it would still hold.\n wipeStorage: {\n params: undefined;\n result: DatabaseWorkerStorageWiped;\n };\n}\n\nexport const WORKER_CONNECT_PORT_MESSAGE_TYPE = \"tearleads:sqlite-connect-port\";\nexport const WORKER_DISCONNECT_PORT_MESSAGE_TYPE =\n \"tearleads:sqlite-disconnect-port\";\nexport const WORKER_PORT_DISCONNECTED_MESSAGE_TYPE =\n \"tearleads:sqlite-port-disconnected\";\n\n// The worker's answer to a statement on a connection with no open database.\n// The cross-tab coordinator matches it to notice a client whose database was\n// lost, so the worker and the coordinator share this one string.\nexport const DATABASE_NOT_INITIALIZED_MESSAGE =\n \"Database has not been initialized.\";\n\n// The worker's answer to a statement on a connection whose database another\n// connection deleted. A deliberate delete (logout, destroying an identity) is\n// not a loss to recover from, so it must not read as a never-opened database.\nexport const DATABASE_DELETED_MESSAGE =\n \"Database was deleted by another connection.\";\n\n// Posted unprompted on each other connection to a database the moment one\n// connection deletes it, so a client learns of the delete before its owner tab\n// can go away, even when it sends nothing in between.\nexport const WORKER_DATABASE_DELETED_MESSAGE_TYPE =\n \"tearleads:sqlite-database-deleted\";\n\n/** Posts an unprompted notice back to the connection's client. */\nexport type DatabaseWorkerNotify = (message: { readonly type: string }) => void;\n\nexport type WorkerMethod = keyof WorkerRequestMap;\n\nexport type WorkerRequest<K extends WorkerMethod = WorkerMethod> =\n K extends WorkerMethod\n ? {\n id: number;\n method: K;\n params: WorkerRequestMap[K][\"params\"];\n }\n : never;\n\nexport type WorkerResponse<K extends WorkerMethod = WorkerMethod> =\n K extends WorkerMethod\n ? {\n id: number;\n result: DatabaseWorkerResult<WorkerRequestMap[K][\"result\"]>;\n }\n : never;\n"]}
@@ -0,0 +1,23 @@
1
+ export interface WorkerCrashDetail {
2
+ readonly message: string;
3
+ readonly filename?: string;
4
+ readonly lineno?: number;
5
+ readonly colno?: number;
6
+ }
7
+ export declare class DatabaseWorkerCrashError extends Error {
8
+ readonly detail: WorkerCrashDetail;
9
+ constructor(detail: WorkerCrashDetail);
10
+ }
11
+ /**
12
+ * A client's open database went away with the owner tab whose worker held it.
13
+ * Hosts handle it as a crash (retire the runtime, open a new one) but it is the
14
+ * expected result of closing or reloading a tab, not a defect: report it below
15
+ * error level. The inherited message prefix keeps "the database went away"
16
+ * classifiers matching it.
17
+ */
18
+ export declare class DatabaseConnectionLostError extends DatabaseWorkerCrashError {
19
+ constructor();
20
+ }
21
+ export declare function isDatabaseConnectionLostError(error: unknown): error is DatabaseConnectionLostError;
22
+ export declare function describeWorkerErrorEvent(event: Event): WorkerCrashDetail;
23
+ export declare function workerCrashErrorFromEvent(event: Event): Error;
@@ -17,6 +17,23 @@ export class DatabaseWorkerCrashError extends Error {
17
17
  this.detail = detail;
18
18
  }
19
19
  }
20
+ const CONNECTION_LOST_DETAIL = "The database connection was lost when the tab that owned it closed. Open the database again.";
21
+ /**
22
+ * A client's open database went away with the owner tab whose worker held it.
23
+ * Hosts handle it as a crash (retire the runtime, open a new one) but it is the
24
+ * expected result of closing or reloading a tab, not a defect: report it below
25
+ * error level. The inherited message prefix keeps "the database went away"
26
+ * classifiers matching it.
27
+ */
28
+ export class DatabaseConnectionLostError extends DatabaseWorkerCrashError {
29
+ constructor() {
30
+ super({ message: CONNECTION_LOST_DETAIL });
31
+ this.name = "DatabaseConnectionLostError";
32
+ }
33
+ }
34
+ export function isDatabaseConnectionLostError(error) {
35
+ return error instanceof DatabaseConnectionLostError;
36
+ }
20
37
  export function describeWorkerErrorEvent(event) {
21
38
  if (!(event instanceof ErrorEvent)) {
22
39
  return { message: "" };
@@ -1 +1 @@
1
- {"version":3,"file":"workerCrash.js","sourceRoot":"","sources":["workerCrash.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAC3B,EAAE;AACF,yEAAyE;AACzE,4EAA4E;AAC5E,iFAAiF;AACjF,iFAAiF;AACjF,4EAA4E;AAC5E,+EAA+E;AAE/E,MAAM,oBAAoB,GAAG,yBAAyB,CAAC;AASvD,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IACxC,MAAM,CAAoB;IAEnC,YAAY,MAAyB;QACnC,KAAK,CACH,MAAM,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC;YACvB,CAAC,CAAC,GAAG,oBAAoB,IAAI,MAAM,CAAC,OAAO,EAAE;YAC7C,CAAC,CAAC,oBAAoB,CACzB,CAAC;QACF,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;QACvC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;IACvB,CAAC;CACF;AAED,MAAM,UAAU,wBAAwB,CAAC,KAAY;IACnD,IAAI,CAAC,CAAC,KAAK,YAAY,UAAU,CAAC,EAAE,CAAC;QACnC,OAAO,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC;IACzB,CAAC;IAED,OAAO;QACL,OAAO,EAAE,KAAK,CAAC,OAAO;QACtB,QAAQ,EAAE,KAAK,CAAC,QAAQ;QACxB,MAAM,EAAE,KAAK,CAAC,MAAM;QACpB,KAAK,EAAE,KAAK,CAAC,KAAK;KACnB,CAAC;AACJ,CAAC;AAED,yEAAyE;AACzE,+EAA+E;AAC/E,yEAAyE;AACzE,MAAM,UAAU,yBAAyB,CAAC,KAAY;IACpD,IAAI,KAAK,YAAY,UAAU,IAAI,KAAK,CAAC,KAAK,YAAY,KAAK,EAAE,CAAC;QAChE,OAAO,KAAK,CAAC,KAAK,CAAC;IACrB,CAAC;IAED,OAAO,IAAI,wBAAwB,CAAC,wBAAwB,CAAC,KAAK,CAAC,CAAC,CAAC;AACvE,CAAC","sourcesContent":["// Runs on the main thread.\n//\n// An uncaught exception inside the SQLite worker reaches its owner as an\n// `ErrorEvent` whose `error` is null across the agent boundary, so the only\n// `Error` that can carry a stack is one minted here. This module is bundled into\n// the application chunk, never into the worker script, so the resulting frame is\n// one the diagnostics allowlist admits — and a single, stable location that\n// tells \"the database worker crashed\" apart from every other database failure.\n\nconst WORKER_CRASH_MESSAGE = \"Database worker failed.\";\n\nexport interface WorkerCrashDetail {\n readonly message: string;\n readonly filename?: string;\n readonly lineno?: number;\n readonly colno?: number;\n}\n\nexport class DatabaseWorkerCrashError extends Error {\n readonly detail: WorkerCrashDetail;\n\n constructor(detail: WorkerCrashDetail) {\n super(\n detail.message.length > 0\n ? `${WORKER_CRASH_MESSAGE} ${detail.message}`\n : WORKER_CRASH_MESSAGE,\n );\n this.name = \"DatabaseWorkerCrashError\";\n this.detail = detail;\n }\n}\n\nexport function describeWorkerErrorEvent(event: Event): WorkerCrashDetail {\n if (!(event instanceof ErrorEvent)) {\n return { message: \"\" };\n }\n\n return {\n message: event.message,\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n };\n}\n\n// Reuses an `Error` the event already carries: the cross-tab coordinator\n// dispatches synthetic events that hold the instance minted at the catch site,\n// so every listener sees the same stack instead of one rooted in itself.\nexport function workerCrashErrorFromEvent(event: Event): Error {\n if (event instanceof ErrorEvent && event.error instanceof Error) {\n return event.error;\n }\n\n return new DatabaseWorkerCrashError(describeWorkerErrorEvent(event));\n}\n"]}
1
+ {"version":3,"file":"workerCrash.js","sourceRoot":"","sources":["workerCrash.ts"],"names":[],"mappings":"AAAA,2BAA2B;AAC3B,EAAE;AACF,yEAAyE;AACzE,4EAA4E;AAC5E,iFAAiF;AACjF,iFAAiF;AACjF,4EAA4E;AAC5E,+EAA+E;AAE/E,MAAM,oBAAoB,GAAG,yBAAyB,CAAC;AASvD,MAAM,OAAO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,CAAC,KAAK,CAAC,CAAC,CAAC;AACvE,CAAC","sourcesContent":["// Runs on the main thread.\n//\n// An uncaught exception inside the SQLite worker reaches its owner as an\n// `ErrorEvent` whose `error` is null across the agent boundary, so the only\n// `Error` that can carry a stack is one minted here. This module is bundled into\n// the application chunk, never into the worker script, so the resulting frame is\n// one the diagnostics allowlist admits — and a single, stable location that\n// tells \"the database worker crashed\" apart from every other database failure.\n\nconst WORKER_CRASH_MESSAGE = \"Database worker failed.\";\n\nexport interface WorkerCrashDetail {\n readonly message: string;\n readonly filename?: string;\n readonly lineno?: number;\n readonly colno?: number;\n}\n\nexport class DatabaseWorkerCrashError extends Error {\n readonly detail: WorkerCrashDetail;\n\n constructor(detail: WorkerCrashDetail) {\n super(\n detail.message.length > 0\n ? `${WORKER_CRASH_MESSAGE} ${detail.message}`\n : WORKER_CRASH_MESSAGE,\n );\n this.name = \"DatabaseWorkerCrashError\";\n this.detail = detail;\n }\n}\n\nconst CONNECTION_LOST_DETAIL =\n \"The database connection was lost when the tab that owned it closed. Open the database again.\";\n\n/**\n * A client's open database went away with the owner tab whose worker held it.\n * Hosts handle it as a crash (retire the runtime, open a new one) but it is the\n * expected result of closing or reloading a tab, not a defect: report it below\n * error level. The inherited message prefix keeps \"the database went away\"\n * classifiers matching it.\n */\nexport class DatabaseConnectionLostError extends DatabaseWorkerCrashError {\n constructor() {\n super({ message: CONNECTION_LOST_DETAIL });\n this.name = \"DatabaseConnectionLostError\";\n }\n}\n\nexport function isDatabaseConnectionLostError(\n error: unknown,\n): error is DatabaseConnectionLostError {\n return error instanceof DatabaseConnectionLostError;\n}\n\nexport function describeWorkerErrorEvent(event: Event): WorkerCrashDetail {\n if (!(event instanceof ErrorEvent)) {\n return { message: \"\" };\n }\n\n return {\n message: event.message,\n filename: event.filename,\n lineno: event.lineno,\n colno: event.colno,\n };\n}\n\n// Reuses an `Error` the event already carries: the cross-tab coordinator\n// dispatches synthetic events that hold the instance minted at the catch site,\n// so every listener sees the same stack instead of one rooted in itself.\nexport function workerCrashErrorFromEvent(event: Event): Error {\n if (event instanceof ErrorEvent && event.error instanceof Error) {\n return event.error;\n }\n\n return new DatabaseWorkerCrashError(describeWorkerErrorEvent(event));\n}\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tearleads/client-sdk",
3
- "version": "0.1.261",
3
+ "version": "0.1.263",
4
4
  "description": "React-free Tearleads client runtime: local SQLite persistence, keys, sync, encrypted blobs, and domain workflows.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
package/sqlite/index.d.ts CHANGED
@@ -8,7 +8,7 @@ export type SQLiteModuleWorkerLike = ModuleWorkerLike;
8
8
  export interface SQLiteRuntimeWorker extends WorkerLike {
9
9
  terminate(): void;
10
10
  }
11
- export { createModuleDatabaseRuntime as createSQLiteRuntime } from "../internal/sqlite-worker/runtime.js";
11
+ export { createModuleDatabaseRuntime as createSQLiteRuntime, DatabaseConnectionLostError, isDatabaseConnectionLostError, } from "../internal/sqlite-worker/runtime.js";
12
12
  export declare function createSQLiteRuntimeFromWorker(worker: SQLiteRuntimeWorker): SQLiteRuntime;
13
13
  export { purgeOpfsSqliteDatabase } from "../internal/sqlite-worker/purgeOpfsDatabase.js";
14
14
  export type { DatabasePersistenceMode } from "../internal/sqlite-worker/types.js";
package/sqlite/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { createDatabaseRuntime, } from "../internal/sqlite-worker/runtime.js";
2
- export { createModuleDatabaseRuntime as createSQLiteRuntime } from "../internal/sqlite-worker/runtime.js";
2
+ export { createModuleDatabaseRuntime as createSQLiteRuntime, DatabaseConnectionLostError, isDatabaseConnectionLostError, } from "../internal/sqlite-worker/runtime.js";
3
3
  export function createSQLiteRuntimeFromWorker(worker) {
4
4
  return createDatabaseRuntime(worker);
5
5
  }
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EAEL,qBAAqB,GAItB,MAAM,kCAAkC,CAAC;AAW1C,OAAO,EAAE,2BAA2B,IAAI,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAEtG,MAAM,UAAU,6BAA6B,CAC3C,MAA2B;IAE3B,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC;AAED,OAAO,EAAE,uBAAuB,EAAE,MAAM,8CAA8C,CAAC;AAEvF,OAAO,EAEL,eAAe,GAChB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAIL,iCAAiC,IAAI,2BAA2B,GACjE,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,iCAAiC,EACjC,aAAa,EACb,oBAAoB,EAGpB,yBAAyB,EACzB,eAAe,EACf,6BAA6B,EAC7B,kBAAkB,EAClB,yBAAyB,EACzB,wBAAwB,EAOxB,kBAAkB,EAClB,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,yBAAyB,EAEzB,wBAAwB,EACxB,+BAA+B,GAEhC,MAAM,mCAAmC,CAAC","sourcesContent":["import type {\n DatabaseWorkerClient,\n WorkerLike,\n} from \"@tearleads/sqlite-worker/client\";\nimport {\n type CreateModuleDatabaseRuntimeOptions,\n createDatabaseRuntime,\n type DatabaseRuntime,\n type ModuleWorkerConstructor,\n type ModuleWorkerLike,\n} from \"@tearleads/sqlite-worker/runtime\";\n\nexport type SQLiteWorkerClient = DatabaseWorkerClient;\nexport type CreateSQLiteRuntimeOptions = CreateModuleDatabaseRuntimeOptions;\nexport type SQLiteRuntime = DatabaseRuntime;\nexport type SQLiteModuleWorkerConstructor = ModuleWorkerConstructor;\nexport type SQLiteModuleWorkerLike = ModuleWorkerLike;\nexport interface SQLiteRuntimeWorker extends WorkerLike {\n terminate(): void;\n}\n\nexport { createModuleDatabaseRuntime as createSQLiteRuntime } from \"@tearleads/sqlite-worker/runtime\";\n\nexport function createSQLiteRuntimeFromWorker(\n worker: SQLiteRuntimeWorker,\n): SQLiteRuntime {\n return createDatabaseRuntime(worker);\n}\n\nexport { purgeOpfsSqliteDatabase } from \"@tearleads/sqlite-worker/purge-opfs-database\";\nexport type { DatabasePersistenceMode } from \"@tearleads/sqlite-worker/types\";\nexport {\n type WipeOpfsStorageResult,\n wipeOpfsStorage,\n} from \"@tearleads/sqlite-worker/wipe-opfs-storage\";\nexport { clientSQLiteSchema } from \"../data/sqlite/schema\";\nexport {\n type ClientSQLiteDatabase as SQLiteDatabase,\n type ClientSQLitePersistenceRuntime as SQLitePersistenceRuntime,\n type ClientSQLiteTransactionScope as SQLiteTransaction,\n getClientSQLitePersistenceRuntime as getSQLitePersistenceRuntime,\n} from \"../data/sqlite/sqlitePersistenceRuntime\";\nexport {\n assertRestorableLocalSchemaLedger,\n createExecSql,\n defineSqlTableSchema,\n type ExecSql,\n type ExecSqlClientLike,\n ensureLocalSchemaMigrated,\n ensureSqlTables,\n LOCAL_SCHEMA_MIGRATIONS_TABLE,\n migrateLocalSchema,\n resetConnectionSchemaMemo,\n runSerializedSqlMutation,\n type SqlArrayRow,\n type SqlBind,\n type SqlRow,\n type SqlRowMode,\n type SqlRowValue,\n type SqlTableSchema,\n unavailableExecSql,\n withLocalSchemaMigrationLock,\n} from \"../data/sqlite/sqlSchema\";\nexport {\n EPHEMERAL_STORAGE_POLICY,\n isPersistentStorageSupported,\n PERSISTENT_STORAGE_POLICY,\n type RequestPersistentStorageResult,\n requestPersistentStorage,\n resolveStoragePersistencePolicy,\n type StoragePersistencePolicy,\n} from \"../data/sqlite/storagePersistence\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAIA,OAAO,EAEL,qBAAqB,GAItB,MAAM,kCAAkC,CAAC;AAW1C,OAAO,EACL,2BAA2B,IAAI,mBAAmB,EAClD,2BAA2B,EAC3B,6BAA6B,GAC9B,MAAM,kCAAkC,CAAC;AAE1C,MAAM,UAAU,6BAA6B,CAC3C,MAA2B;IAE3B,OAAO,qBAAqB,CAAC,MAAM,CAAC,CAAC;AACvC,CAAC;AAED,OAAO,EAAE,uBAAuB,EAAE,MAAM,8CAA8C,CAAC;AAEvF,OAAO,EAEL,eAAe,GAChB,MAAM,4CAA4C,CAAC;AACpD,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAC3D,OAAO,EAIL,iCAAiC,IAAI,2BAA2B,GACjE,MAAM,yCAAyC,CAAC;AACjD,OAAO,EACL,iCAAiC,EACjC,aAAa,EACb,oBAAoB,EAGpB,yBAAyB,EACzB,eAAe,EACf,6BAA6B,EAC7B,kBAAkB,EAClB,yBAAyB,EACzB,wBAAwB,EAOxB,kBAAkB,EAClB,4BAA4B,GAC7B,MAAM,0BAA0B,CAAC;AAClC,OAAO,EACL,wBAAwB,EACxB,4BAA4B,EAC5B,yBAAyB,EAEzB,wBAAwB,EACxB,+BAA+B,GAEhC,MAAM,mCAAmC,CAAC","sourcesContent":["import type {\n DatabaseWorkerClient,\n WorkerLike,\n} from \"@tearleads/sqlite-worker/client\";\nimport {\n type CreateModuleDatabaseRuntimeOptions,\n createDatabaseRuntime,\n type DatabaseRuntime,\n type ModuleWorkerConstructor,\n type ModuleWorkerLike,\n} from \"@tearleads/sqlite-worker/runtime\";\n\nexport type SQLiteWorkerClient = DatabaseWorkerClient;\nexport type CreateSQLiteRuntimeOptions = CreateModuleDatabaseRuntimeOptions;\nexport type SQLiteRuntime = DatabaseRuntime;\nexport type SQLiteModuleWorkerConstructor = ModuleWorkerConstructor;\nexport type SQLiteModuleWorkerLike = ModuleWorkerLike;\nexport interface SQLiteRuntimeWorker extends WorkerLike {\n terminate(): void;\n}\n\nexport {\n createModuleDatabaseRuntime as createSQLiteRuntime,\n DatabaseConnectionLostError,\n isDatabaseConnectionLostError,\n} from \"@tearleads/sqlite-worker/runtime\";\n\nexport function createSQLiteRuntimeFromWorker(\n worker: SQLiteRuntimeWorker,\n): SQLiteRuntime {\n return createDatabaseRuntime(worker);\n}\n\nexport { purgeOpfsSqliteDatabase } from \"@tearleads/sqlite-worker/purge-opfs-database\";\nexport type { DatabasePersistenceMode } from \"@tearleads/sqlite-worker/types\";\nexport {\n type WipeOpfsStorageResult,\n wipeOpfsStorage,\n} from \"@tearleads/sqlite-worker/wipe-opfs-storage\";\nexport { clientSQLiteSchema } from \"../data/sqlite/schema\";\nexport {\n type ClientSQLiteDatabase as SQLiteDatabase,\n type ClientSQLitePersistenceRuntime as SQLitePersistenceRuntime,\n type ClientSQLiteTransactionScope as SQLiteTransaction,\n getClientSQLitePersistenceRuntime as getSQLitePersistenceRuntime,\n} from \"../data/sqlite/sqlitePersistenceRuntime\";\nexport {\n assertRestorableLocalSchemaLedger,\n createExecSql,\n defineSqlTableSchema,\n type ExecSql,\n type ExecSqlClientLike,\n ensureLocalSchemaMigrated,\n ensureSqlTables,\n LOCAL_SCHEMA_MIGRATIONS_TABLE,\n migrateLocalSchema,\n resetConnectionSchemaMemo,\n runSerializedSqlMutation,\n type SqlArrayRow,\n type SqlBind,\n type SqlRow,\n type SqlRowMode,\n type SqlRowValue,\n type SqlTableSchema,\n unavailableExecSql,\n withLocalSchemaMigrationLock,\n} from \"../data/sqlite/sqlSchema\";\nexport {\n EPHEMERAL_STORAGE_POLICY,\n isPersistentStorageSupported,\n PERSISTENT_STORAGE_POLICY,\n type RequestPersistentStorageResult,\n requestPersistentStorage,\n resolveStoragePersistencePolicy,\n type StoragePersistencePolicy,\n} from \"../data/sqlite/storagePersistence\";\n"]}