@bastani/atomic 0.10.11-alpha.3 → 0.10.11-alpha.4
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.
- package/CHANGELOG.md +51 -0
- package/dist/_shared/dist-KOELCESV.js +2 -2
- package/dist/_shared/fork-row-index-UAUAQRD5.js +2 -2
- package/dist/_shared/lib-4PES5P4V.js +2 -2
- package/dist/_shared/mode-interactive-sdk-7KXUFI2F.js +4 -4
- package/dist/_shared/mode-rpc-sdk-IOPGDYR4.js +4 -4
- package/dist/_shared/mode-shared-2QJSCUM6.js +4 -4
- package/dist/_shared/p1a-prewarm-XIU57JHF.js +3 -3
- package/dist/_shared/p1b-elig-TVB5CBLL.js +22 -6
- package/dist/_shared/p1b-elig-TVB5CBLL.js.map +1 -1
- package/dist/_shared/p2-shell-main-B2WIALFD.js +6 -3
- package/dist/_shared/p2-shell-main-B2WIALFD.js.map +1 -1
- package/dist/_shared/runtime-O4KCSG4C.js +2 -2
- package/dist/_shared/sdk-B5LEWGGI.js +899 -515
- package/dist/_shared/sdk-B5LEWGGI.js.map +1 -1
- package/dist/_shared/session-data-AHTU7IS6.js +2 -2
- package/dist/_shared/session-manager-list-2BLEEZVG.js +1 -1
- package/dist/_shared/{startup-0-0-EZUKEP4Q.js → startup-0-0-XJJDOIEC.js} +6 -12
- package/dist/_shared/{startup-0-0-EZUKEP4Q.js.map → startup-0-0-XJJDOIEC.js.map} +1 -1
- package/dist/_shared/{startup-0-1-RTOHJFDJ.js → startup-0-1-M6OWAYHH.js} +354 -103
- package/dist/_shared/startup-0-1-M6OWAYHH.js.map +1 -0
- package/dist/_shared/startup-0-2-5QHPCEON.js +18 -9
- package/dist/_shared/startup-0-2-5QHPCEON.js.map +1 -1
- package/dist/_shared/startup-0-3-4ZYBYQNM.js +4 -4
- package/dist/_shared/startup-0-4-ZMJV547D.js +4 -4
- package/dist/_shared/startup-0-5-YDW47QX6.js +4 -4
- package/dist/_shared/startup-10-0-TDQNBDDL.js +4 -4
- package/dist/_shared/startup-12-0-55AAXBJZ.js +1 -1
- package/dist/_shared/startup-14-0-MLX36RBG.js +2 -2
- package/dist/_shared/startup-15-0-YUKGAC63.js +2 -2
- package/dist/_shared/startup-15-1-4S7FLMNG.js +4 -4
- package/dist/_shared/startup-8-0-34CBHPZH.js +2114 -235
- package/dist/_shared/startup-8-0-34CBHPZH.js.map +1 -1
- package/dist/_shared/startup-8-1-LZFXSD3Z.js +12 -12
- package/dist/_shared/storage-command-7MGXLJGZ.js +6 -6
- package/dist/_shared/storage-command-7MGXLJGZ.js.map +1 -1
- package/dist/_shared/storage-status-K7PX2RXA.js +2 -2
- package/dist/_shared/task-unsaved-answer-VJ2KTB4V.js +2 -2
- package/dist/_shared/team-DOQKICG2.js +1 -1
- package/dist/_shared/tree-outline-MUEPK5B7.js +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +19 -0
- package/dist/builtin/intercom/broker/broker.bundle.mjs +1020 -108
- package/dist/builtin/intercom/broker/client.ts +8 -0
- package/dist/builtin/intercom/broker/database-wake-up-bus.ts +91 -14
- package/dist/builtin/intercom/broker/multinode-router.ts +102 -17
- package/dist/builtin/intercom/broker/multinode-state-store.ts +41 -2
- package/dist/builtin/intercom/broker/send-order-gate.ts +5 -2
- package/dist/builtin/intercom/broker/sql-add-column.ts +22 -1
- package/dist/builtin/intercom/broker/sql-lease-store.ts +304 -48
- package/dist/builtin/intercom/broker/sql-outbox-store.ts +541 -50
- package/dist/builtin/intercom/broker/sql-restoring-reservation-store.ts +239 -8
- package/dist/builtin/intercom/broker/sql-retention.ts +11 -2
- package/dist/builtin/intercom/broker/sql-schema.ts +42 -8
- package/dist/builtin/intercom/index.bundle.mjs +13 -2
- package/dist/builtin/intercom/package.json +1 -1
- package/dist/builtin/mcp/index.bundle.mjs +1 -1
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +6 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/subagents/skills/skill-creator/eval-viewer/generate_review.py +8 -1
- package/dist/builtin/subagents/src/extension/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/index.bundle.mjs +1 -1
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/cli/args.js +2 -2
- package/dist/cli/auth-cli.code.js +2 -2
- package/dist/cli/auth-cli.impl.js +3 -3
- package/dist/cli/auth-cli.js +3 -3
- package/dist/cli/blueprint-command.code.js +1 -1
- package/dist/cli/blueprint-command.impl.js +3 -3
- package/dist/cli/blueprint-command.js +3 -3
- package/dist/cli/intercom-command.code.js +2 -2
- package/dist/cli/intercom-command.impl.js +3 -3
- package/dist/cli/intercom-command.js +3 -3
- package/dist/cli/list-models.code.js +2 -2
- package/dist/cli/list-models.impl.js +3 -3
- package/dist/cli/list-models.js +3 -3
- package/dist/cli/session-picker.code.js +1 -1
- package/dist/cli/session-picker.impl.js +3 -3
- package/dist/cli/session-picker.js +3 -3
- package/dist/cli/startup-ui.code.js +1 -1
- package/dist/cli/startup-ui.impl.js +3 -3
- package/dist/cli/startup-ui.js +3 -3
- package/dist/cli/storage-command.impl.js +3 -3
- package/dist/cli/storage-command.js +3 -3
- package/dist/cli/storage-search-session.code.js +1 -1
- package/dist/cli/storage-search-session.impl.js +3 -3
- package/dist/cli/storage-search-session.js +3 -3
- package/dist/cli/team-command.code.js +1 -1
- package/dist/cli/team-command.impl.js +3 -3
- package/dist/cli/team-command.js +3 -3
- package/dist/cli.js +2 -2
- package/dist/core/debug.impl.js +3 -3
- package/dist/core/debug.js +3 -3
- package/dist/core/export-html/card-projection.impl.js +3 -3
- package/dist/core/export-html/card-projection.js +3 -3
- package/dist/core/export-html/index.code.js +4 -4
- package/dist/core/export-html/index.code.js.map +1 -1
- package/dist/core/export-html/index.impl.js +3 -3
- package/dist/core/export-html/index.js +3 -3
- package/dist/core/export-html/json-spans.impl.js +3 -3
- package/dist/core/export-html/json-spans.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.impl.js +3 -3
- package/dist/core/export-html/oversized-render-inputs.js +3 -3
- package/dist/core/export-html/tool-renderer.impl.js +3 -3
- package/dist/core/export-html/tool-renderer.js +3 -3
- package/dist/core/extensions/jiti-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-loader.js +3 -3
- package/dist/core/extensions/jiti-static-loader.impl.js +3 -3
- package/dist/core/extensions/jiti-static-loader.js +3 -3
- package/dist/core/extensions/loader-host-modules.code.js +1 -1
- package/dist/core/extensions/loader-host-modules.impl.js +3 -3
- package/dist/core/extensions/loader-host-modules.js +3 -3
- package/dist/core/extensions/loader-virtual-modules.js +1 -1
- package/dist/core/extensions/runner-context.js +1 -1
- package/dist/core/intercom-broker-control-host.impl.js +3 -3
- package/dist/core/intercom-broker-control-host.js +3 -3
- package/dist/core/intercom-broker-control.code.js +3 -3
- package/dist/core/intercom-broker-control.impl.js +3 -3
- package/dist/core/intercom-broker-control.js +3 -3
- package/dist/core/package-manager-storage-adapters.impl.js +3 -3
- package/dist/core/package-manager-storage-adapters.js +3 -3
- package/dist/core/process-start-token.d.ts +5 -4
- package/dist/core/sdk.code.js +2 -2
- package/dist/core/sdk.impl.js +3 -3
- package/dist/core/sdk.js +3 -3
- package/dist/core/session-manager-core.js +4 -4
- package/dist/core/session-manager-list.impl.js +3 -3
- package/dist/core/session-manager-list.js +3 -3
- package/dist/core/session-manager.code.js +1 -1
- package/dist/core/session-manager.impl.js +3 -3
- package/dist/core/session-manager.js +3 -3
- package/dist/core/session-storage.impl.js +3 -3
- package/dist/core/session-storage.js +3 -3
- package/dist/core/storage/database.d.ts +6 -0
- package/dist/core/storage/database.js.map +1 -1
- package/dist/core/storage/fenced-paths.d.ts +7 -6
- package/dist/core/storage/fenced-paths.js +7 -6
- package/dist/core/storage/fenced-paths.js.map +1 -1
- package/dist/core/storage/index.js +2 -2
- package/dist/core/storage/node-sqlite-thread.js +209 -19
- package/dist/core/storage/node-sqlite-thread.js.map +1 -1
- package/dist/core/storage/node-sqlite.js +435 -71
- package/dist/core/storage/node-sqlite.js.map +1 -1
- package/dist/core/storage/offline-snapshot-file.impl.js +3 -3
- package/dist/core/storage/offline-snapshot-file.js +3 -3
- package/dist/core/storage/provider.js +2 -2
- package/dist/core/storage/schema-catalog.d.ts +69 -7
- package/dist/core/storage/schema-catalog.js +352 -61
- package/dist/core/storage/schema-catalog.js.map +1 -1
- package/dist/core/storage/selection.js +2 -2
- package/dist/core/storage/session/branch-fork-source.code.js +2 -2
- package/dist/core/storage/session/branch-fork-source.impl.js +3 -3
- package/dist/core/storage/session/branch-fork-source.js +3 -3
- package/dist/core/storage/session/card-view.impl.js +3 -3
- package/dist/core/storage/session/card-view.js +3 -3
- package/dist/core/storage/session/child-reader.code.js +3 -3
- package/dist/core/storage/session/child-reader.impl.js +3 -3
- package/dist/core/storage/session/child-reader.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.impl.js +3 -3
- package/dist/core/storage/session/chunked-resume-projection.js +3 -3
- package/dist/core/storage/session/expanded-child-details.code.js +2 -2
- package/dist/core/storage/session/expanded-child-details.impl.js +3 -3
- package/dist/core/storage/session/expanded-child-details.js +3 -3
- package/dist/core/storage/session/fork-detach.d.ts +11 -1
- package/dist/core/storage/session/fork-row-bytes.impl.js +3 -3
- package/dist/core/storage/session/fork-row-bytes.js +3 -3
- package/dist/core/storage/session/fork-row-index.impl.js +3 -3
- package/dist/core/storage/session/fork-row-index.js +3 -3
- package/dist/core/storage/session/fork-staging.code.js +1 -1
- package/dist/core/storage/session/fork-staging.impl.js +3 -3
- package/dist/core/storage/session/fork-staging.js +3 -3
- package/dist/core/storage/session/fork-sweep.js +31 -7
- package/dist/core/storage/session/fork-sweep.js.map +1 -1
- package/dist/core/storage/session/fork-window.code.js +3 -3
- package/dist/core/storage/session/fork-window.impl.js +3 -3
- package/dist/core/storage/session/fork-window.js +3 -3
- package/dist/core/storage/session/history-pages.impl.js +3 -3
- package/dist/core/storage/session/history-pages.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.impl.js +3 -3
- package/dist/core/storage/session/jsonl-entry-projection.js +3 -3
- package/dist/core/storage/session/jsonl-session-lock.d.ts +100 -0
- package/dist/core/storage/session/jsonl-session-store.d.ts +41 -23
- package/dist/core/storage/session/jsonl-session-store.impl.js +3 -3
- package/dist/core/storage/session/jsonl-session-store.js +3 -3
- package/dist/core/storage/session/memory-session-store.impl.js +3 -3
- package/dist/core/storage/session/memory-session-store.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.code.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.impl.js +3 -3
- package/dist/core/storage/session/pinned-branch-resume.js +3 -3
- package/dist/core/storage/session/released-history-files.code.js +8 -8
- package/dist/core/storage/session/released-history-files.code.js.map +1 -1
- package/dist/core/storage/session/released-history-files.impl.js +3 -3
- package/dist/core/storage/session/released-history-files.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.impl.js +3 -3
- package/dist/core/storage/session/resident-fork-rows.js +3 -3
- package/dist/core/storage/session/session-resume.impl.js +3 -3
- package/dist/core/storage/session/session-resume.js +3 -3
- package/dist/core/storage/session/session-search-index.d.ts +9 -1
- package/dist/core/storage/session/snapshot-cut.impl.js +3 -3
- package/dist/core/storage/session/snapshot-cut.js +3 -3
- package/dist/core/storage/session/snapshot-history.code.js +3 -3
- package/dist/core/storage/session/snapshot-history.impl.js +3 -3
- package/dist/core/storage/session/snapshot-history.js +3 -3
- package/dist/core/storage/session/sql-session-store.d.ts +51 -7
- package/dist/core/storage/session/sql-session-store.impl.js +3 -3
- package/dist/core/storage/session/sql-session-store.js +3 -3
- package/dist/core/storage/session/tree-outline.impl.js +3 -3
- package/dist/core/storage/session/tree-outline.js +3 -3
- package/dist/core/storage/session/tree-presentation.impl.js +3 -3
- package/dist/core/storage/session/tree-presentation.js +3 -3
- package/dist/core/storage/sqlite-facade.d.ts +6 -0
- package/dist/core/storage/sqlite-facade.js +309 -33
- package/dist/core/storage/sqlite-facade.js.map +1 -1
- package/dist/core/storage/sqlite-open-batch.js +10 -0
- package/dist/core/storage/sqlite-open-batch.js.map +1 -0
- package/dist/core/storage/storage-status.impl.js +3 -3
- package/dist/core/storage/storage-status.js +3 -3
- package/dist/core/storage/team.impl.js +3 -3
- package/dist/core/storage/team.js +3 -3
- package/dist/core/structured-output/index.impl.js +3 -3
- package/dist/core/structured-output/index.js +3 -3
- package/dist/core/tasks/task-completion-entry.impl.js +3 -3
- package/dist/core/tasks/task-completion-entry.js +3 -3
- package/dist/core/tasks/task-file-history.code.js +3 -3
- package/dist/core/tasks/task-file-history.impl.js +3 -3
- package/dist/core/tasks/task-file-history.js +3 -3
- package/dist/core/tasks/task-reference-archive.code.js +3 -3
- package/dist/core/tasks/task-reference-archive.js +3 -3
- package/dist/core/tasks/task-reference-identity.js +3 -3
- package/dist/core/tasks/task-reference-stream.impl.js +3 -3
- package/dist/core/tasks/task-reference-stream.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.impl.js +3 -3
- package/dist/core/tasks/task-unsaved-answer.js +3 -3
- package/dist/core/tasks/task-view-source.impl.js +3 -3
- package/dist/core/tasks/task-view-source.js +3 -3
- package/dist/core/tools/read-url.code.js +2 -2
- package/dist/core/tools/read-url.impl.js +3 -3
- package/dist/core/tools/read-url.js +3 -3
- package/dist/core/worktree-snapshot/blob-store.d.ts +5 -3
- package/dist/core/worktree-snapshot/blob-store.js +151 -21
- package/dist/core/worktree-snapshot/blob-store.js.map +1 -1
- package/dist/core/worktree-snapshot/errors.code.js +2 -2
- package/dist/core/worktree-snapshot/errors.impl.js +3 -3
- package/dist/core/worktree-snapshot/errors.js +3 -3
- package/dist/core/worktree-snapshot/fork-snapshot-index.js +158 -41
- package/dist/core/worktree-snapshot/fork-snapshot-index.js.map +1 -1
- package/dist/core/worktree-snapshot/session-index-reset.impl.js +3 -3
- package/dist/core/worktree-snapshot/session-index-reset.js +3 -3
- package/dist/extensions/codemode/execute.code.js +1 -1
- package/dist/extensions/codemode/execute.impl.js +3 -3
- package/dist/extensions/codemode/execute.js +3 -3
- package/dist/extensions/codemode/renderer.code.js +1 -1
- package/dist/extensions/codemode/renderer.impl.js +3 -3
- package/dist/extensions/codemode/renderer.js +3 -3
- package/dist/extensions/mcp/cli.code.js +1 -1
- package/dist/extensions/mcp/cli.impl.js +3 -3
- package/dist/extensions/mcp/cli.js +3 -3
- package/dist/extensions/mcp/cli.lazy.code.js +2 -2
- package/dist/extensions/mcp/cli.lazy.impl.js +3 -3
- package/dist/extensions/mcp/cli.lazy.js +3 -3
- package/dist/extensions/mcp/runtime.impl.js +3 -3
- package/dist/extensions/mcp/runtime.js +3 -3
- package/dist/index.js +2 -2
- package/dist/main-first-time-setup.code.js +1 -1
- package/dist/main-first-time-setup.impl.js +3 -3
- package/dist/main-first-time-setup.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.code.js +2 -2
- package/dist/modes/interactive/components/stored-tree-view.impl.js +3 -3
- package/dist/modes/interactive/components/stored-tree-view.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.impl.js +3 -3
- package/dist/modes/interactive/components/user-message-selector-archive.js +3 -3
- package/dist/package-manager-cli.code.js +4 -4
- package/dist/package-manager-cli.impl.js +3 -3
- package/dist/package-manager-cli.js +3 -3
- package/dist/rpc-entry.js +1 -1
- package/dist/startup-files.json +1 -1
- package/dist/startup-stages/3.js +1 -1
- package/dist/startup-stages/5.js +1 -1
- package/dist/utils/startup-database-spare.code.js +2 -2
- package/dist/utils/startup-database-spare.impl.js +3 -3
- package/dist/utils/startup-database-spare.js +3 -3
- package/dist/utils/tools-manager.code.js +1 -1
- package/dist/utils/tools-manager.impl.js +3 -3
- package/dist/utils/tools-manager.js +3 -3
- package/docs/changelog.mdx +49 -0
- package/docs/storage/jsonl.md +3 -3
- package/package.json +8 -8
- package/dist/_shared/startup-0-1-RTOHJFDJ.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"node-sqlite-thread.js","sourceRoot":"","sources":["../../../src/core/storage/node-sqlite-thread.ts"],"names":[],"mappings":"AAA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C,iHAAiH;QACjH,6EAA6E;QAC7E,KAAK,KAAK,CAAC,KAAK,CAAC;QACjB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;QACnB,MAAM,OAAO,GAAG,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC3C,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;QACpB,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpD,CAAC;IAEO,KAAK,CAAC,IAAI;QACjB,IAAI,CAAC,GAAG,CAAC,IAAI,0BAA0B,CAAC,0BAA0B,CAAC,CAAC,CAAC;QACrE,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAC/B,CAAC;IAED,wFAAwF;IACxF,MAAM,CAAC,QAAoB;QAC1B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACpC,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,KAAK,CAAC,qBAAqB,CACjC,IAAuB,EACvB,QAAyE,EACzE,eAA8B;QAE9B,MAAM,EAAE,8BAA8B,EAAE,GAAG,MAAM,MAAM,CAAC,uCAAuC,CAAC,CAAC;QACjG,IAAI,eAAe,EAAE,IAAI,8BAA8B,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAChF,gBAAgB,CAAC,UAAU,EAAE,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { startupNodeOptions } from \"@bastani/atomic-codemode/node-options\";\nimport { EVAL_WORKER_BUILTIN } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteStatement, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { SequencedStatement, SqliteSequence } from \"./statement-sequence.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\n${EVAL_WORKER_BUILTIN}\nconst { parentPort, workerData } = builtin(\"node:worker_threads\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = builtin(\"node:sqlite\");\nlet database;\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nconst prepared = new Map();\n\nfunction statement(sql) {\n\tconst cached = prepared.get(sql);\n\tif (cached !== undefined) {\n\t\tprepared.delete(sql);\n\t\tprepared.set(sql, cached);\n\t\treturn cached;\n\t}\n\tconst made = database.prepare(sql);\n\tmade.setReadBigInts(true);\n\tprepared.set(sql, made);\n\tif (prepared.size > workerData.statementCacheSize) prepared.delete(prepared.keys().next().value);\n\treturn made;\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\treturn database.location();\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...request.params).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...request.params);\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...request.params)),\n\t// A read transaction's start: BEGIN, then its leading reads, in one request. A BEGIN that fails fails the request and\n\t// leaves no transaction. The reads answer up to the first that fails, which, with the ones after it, the caller then\n\t// sends on its own in the same transaction, so it fails or answers there as it always would.\n\tread: (request) => {\n\t\tdatabase.exec(\"BEGIN\");\n\t\tconst answers = [];\n\t\tfor (const { sql, params } of request.statements) {\n\t\t\ttry {\n\t\t\t\tanswers.push(table(statement(sql).all(...params)));\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn answers;\n\t},\n\t// A read transaction's end, which its caller does not wait for: COMMIT, or ROLLBACK where COMMIT fails, so the\n\t// connection is never left inside it.\n\tendRead: () => {\n\t\ttry {\n\t\t\tdatabase.exec(\"COMMIT\");\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\t} catch {}\n\t\t\tthrow error;\n\t\t}\n\t},\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering.\n\tbegin: (request) => {\n\t\t// The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a\n\t\t// statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.\n\t\tif (request.lockState !== undefined) {\n\t\t\tconst state = new Int32Array(request.lockState);\n\t\t\tfor (;;) {\n\t\t\t\tconst found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);\n\t\t\t\tif (found === 0) break;\n\t\t\t\t// Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.\n\t\t\t\tif (found !== 1)\n\t\t\t\t\tthrow Object.assign(new Error(\"database is locked\"), { code: \"ERR_SQLITE_ERROR\", errcode: 5, errstr: \"database is locked\" });\n\t\t\t\tAtomics.wait(state, 0, 1, 50);\n\t\t\t}\n\t\t\tAtomics.notify(state, 0);\n\t\t\tlockState = { state, held: request.lockTag * 4 + 3 };\n\t\t}\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t},\n\t// \\`repeat\\`, then each statement, in one request: the statements the caller would send one at a time, in the same\n\t// order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.\n\tsequence: (request) => {\n\t\tconst abort = request.abort === undefined ? undefined : new Int32Array(request.abort);\n\t\tconst aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;\n\t\tlet repeated = 0;\n\t\tif (request.repeat !== undefined) {\n\t\t\tconst { statement: repeat, times, minChanges } = request.repeat;\n\t\t\twhile (repeated < times) {\n\t\t\t\tif (aborted()) return { aborted: true };\n\t\t\t\tconst before = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tstatement(repeat.sql).run(...repeat.params);\n\t\t\t\tconst after = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tif (after - before < minChanges) break;\n\t\t\t\trepeated++;\n\t\t\t}\n\t\t}\n\t\tfor (const { sql, params, script } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tif (script === true) database.exec(sql);\n\t\t\telse statement(sql).run(...params);\n\t\t}\n\t\treturn { repeated };\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tprepared.clear();\n\t\tdatabase?.close();\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\n// The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given\n// back (and the waiting threads woken) once none is, before the request that ended it is answered.\nlet lockState;\n\nfunction settleLock() {\n\tif (lockState === undefined) return;\n\tconst { state, held } = lockState;\n\tlet open = false;\n\ttry {\n\t\topen = database?.isTransaction === true;\n\t} catch {}\n\tif (open) {\n\t\tif (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);\n\t\treturn;\n\t}\n\tlockState = undefined;\n\tif (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)\n\t\tAtomics.notify(state, 0);\n}\n\nfunction handle(request) {\n\ttry {\n\t\treturn handlers[request.kind](request);\n\t} finally {\n\t\tsettleLock();\n\t}\n}\n\nparentPort.on(\"message\", (request) => {\n\ttry {\n\t\tparentPort.postMessage({ id: request.id, value: handle(request) });\n\t} catch (error) {\n\t\tparentPort.postMessage({ id: request.id, failure: failure(error) });\n\t}\n});\n`;\n\n/**\n * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its\n * signal aborts: the thread reads it before each run of `repeat` and before each statement.\n */\nexport interface SequenceRequest {\n\treadonly kind: \"sequence\";\n\treadonly repeat?: SqliteSequence[\"repeat\"];\n\treadonly statements: readonly SequencedStatement[];\n\treadonly abort?: SharedArrayBuffer;\n}\n\n/**\n * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it\n * stopped because the caller's signal aborted.\n */\nexport type SequenceAnswer = { readonly repeated: number } | { readonly aborted: true };\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| { readonly kind: \"begin\"; readonly lockState?: SharedArrayBuffer; readonly lockTag?: number }\n\t| { readonly kind: \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" }\n\t| ReadTransactionRequest\n\t| SequenceRequest;\n\n/**\n * A read-only transaction's start with its leading reads, and its end, which only a connection on a thread of its own\n * is sent: see the thread's `read` and `endRead`.\n */\nexport type ReadTransactionRequest =\n\t| { readonly kind: \"read\"; readonly statements: readonly SqliteStatement[] }\n\t| { readonly kind: \"endRead\" };\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue =\n\t| RowTable\n\t| readonly RowTable[]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `read` the rows of each leading read up to\n * the first that failed, `run` the changes, `sequence` a `SequenceAnswer`, `open` the location, `dataVersion` and `now`\n * a number, `jsonbExtract` a boolean, the others undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| SqliteRow[][]\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** Options that make every worker thread run code of the user's: a preload or a module loader. */\nconst WORKER_CODE_OPTIONS = new Set([\"--require\", \"-r\", \"--import\", \"--loader\", \"--experimental-loader\"]);\n\n/** The thread `startSpare` started for the next open, until an open takes it or `releaseSpare` ends it. */\nlet spare: ThreadConnection | undefined;\n\n/** How many prepared statements a connection keeps for reuse, least recently used first out. */\nexport const STATEMENT_CACHE_SIZE = 256;\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: the caller's preloads would run again for every connection, and its\n\t\t// `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: { nowSql: `SELECT ${sqliteDialect.nowMs} AS now`, statementCacheSize: STATEMENT_CACHE_SIZE },\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined && started.ended === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await ThreadConnection.openOn(started, path, options);\n\t\t\t} catch (error) {\n\t\t\t\t// The spare thread was lost before it answered: open on a thread of its own, as without one.\n\t\t\t\tif (error !== started.ended) throw error;\n\t\t\t}\n\t\t}\n\t\treturn ThreadConnection.openOn(new ThreadConnection(), path, options);\n\t}\n\n\t/**\n\t * Starts one connection thread now, for the next open to take, so that the thread's startup overlaps whatever the\n\t * process does until then (an interactive session loads its modules meanwhile). Idle, the thread keeps nothing\n\t * alive. Nothing starts when the process runs a preload or a module loader, which every worker thread runs again,\n\t * or runs under the permission model; a thread that cannot start leaves every open as it is without one.\n\t */\n\tstatic startSpare(): void {\n\t\tif (spare !== undefined || process.permission !== undefined) return;\n\t\tif (startupNodeOptions().some((option) => WORKER_CODE_OPTIONS.has(option.name))) return;\n\t\ttry {\n\t\t\tconst started = new ThreadConnection();\n\t\t\tstarted.worker.unref();\n\t\t\tspare = started;\n\t\t} catch {\n\t\t\t// Opens start their own threads.\n\t\t}\n\t}\n\n\t/** Ends the spare thread if no open has taken it. */\n\tstatic releaseSpare(): void {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined) void started.stop();\n\t}\n\n\tprivate static async openOn(\n\t\tconnection: ThreadConnection,\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\tif (request.kind === \"read\") return answer.then((value) => (value as readonly RowTable[]).map(rowsOf));\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n\n\t/** Calls `listener` once the connection's thread has exited, whether closed or lost. */\n\tonExit(listener: () => void): void {\n\t\tthis.worker.once(\"exit\", listener);\n\t}\n\n\t/**\n\t * Starts a spare worker for a non-interactive or storage-overridden CLI\n\t * invocation only when the real CLI/storage resolvers select a SQLite store.\n\t */\n\tstatic async startSpareIfSqlNeeded(\n\t\targs: readonly string[],\n\t\tterminal: { readonly stdinIsTTY: boolean; readonly stdoutIsTTY: boolean },\n\t\tstillBeforeMain: () => boolean,\n\t): Promise<void> {\n\t\tconst { shouldStartSpareDatabaseThread } = await import(\"../../utils/startup-database-spare.ts\");\n\t\tif (stillBeforeMain() && shouldStartSpareDatabaseThread(args, false, terminal)) {\n\t\t\tThreadConnection.startSpare();\n\t\t}\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"node-sq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AAM,CAAC,KAAK,EAAE,CAAC;QACpB,KAAK,MAAM,MAAM,IAAI,OAAO;YAAE,MAAM,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;IACpD,CAAC;IAEO,KAAK,CAAC,IAAI;QACjB,IAAI,CAAC,GAAG,CAAC,IAAI,0BAA0B,CAAC,0BAA0B,CAAC,CAAC,CAAC;QACrE,MAAM,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAC;IAC/B,CAAC;IAED,wFAAwF;IACxF,MAAM,CAAC,QAAoB;QAC1B,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IACpC,CAAC;IAED;;;OAGG;IACH,MAAM,CAAC,KAAK,CAAC,qBAAqB,CACjC,IAAuB,EACvB,QAAyE,EACzE,eAA8B;QAE9B,MAAM,EAAE,8BAA8B,EAAE,GAAG,MAAM,MAAM,CAAC,uCAAuC,CAAC,CAAC;QACjG,IAAI,eAAe,EAAE,IAAI,8BAA8B,CAAC,IAAI,EAAE,KAAK,EAAE,QAAQ,CAAC,EAAE,CAAC;YAChF,gBAAgB,CAAC,UAAU,EAAE,CAAC;QAC/B,CAAC;IACF,CAAC;CACD","sourcesContent":["import { Worker } from \"node:worker_threads\";\nimport { startupNodeOptions } from \"@bastani/atomic-codemode/node-options\";\nimport { EVAL_WORKER_BUILTIN } from \"../../utils/worker-threads.js\";\nimport type { SqliteRow, SqliteStatement, SqliteValue } from \"./database.js\";\nimport { sqliteDialect } from \"./dialect.js\";\nimport type { SequencedStatement, SqliteSequence } from \"./statement-sequence.js\";\n\n/**\n * A node:sqlite connection that runs on a worker thread of its own (#5376). The thread owns the `DatabaseSync`; the\n * calling thread sends it one request at a time and receives each answer as a message, so no statement, lock wait or\n * synced commit runs on the caller's event loop. SQLite's busy handler waits on the connection's own thread, so a\n * statement waiting for a lock that another connection of the same process holds never stops that connection from\n * finishing.\n */\nconst CONNECTION_SOURCE = `\n${EVAL_WORKER_BUILTIN}\nconst { parentPort, workerData } = builtin(\"node:worker_threads\");\nconst fs = builtin(\"node:fs\");\nprocess.emitWarning = () => {};\nconst { DatabaseSync } = builtin(\"node:sqlite\");\nconst { statSync } = fs;\nlet database;\nlet walPath;\nlet lastWalSize = -1n;\nlet lastWalMtimeNs = -1n;\nconst WAL_SIZE_LIMIT_BYTES = BigInt(workerData.walSizeLimit);\nconst CHECKPOINT_AFTER = new Set([\"exec\", \"run\", \"get\", \"all\", \"begin\", \"sequence\"]);\nlet holderFd;\nlet holderActive = false;\nlet writersDir;\nlet lastFreed = false;\nlet lastHasWaiters;\nlet pendingHolderError;\nconst HOLDER_FREE = \"free \" + \"0\".repeat(15) + \"\\\\n\";\n\nfunction hasWriters(dir) {\n\tif (!fs.existsSync(dir)) return false;\n\ttry {\n\t\treturn fs.readdirSync(dir).length > 0;\n\t} catch (error) {\n\t\treturn error?.code !== \"ENOENT\";\n\t}\n}\n\nfunction writeHolder(record) {\n\tif (holderFd === undefined) return;\n\ttry {\n\t\tfs.writeSync(holderFd, record, 0, \"utf8\");\n\t} catch (error) {\n\t\tholderFd = undefined;\n\t\tpendingHolderError ??= failure(error);\n\t}\n}\n\nfunction holderLine(prefix) {\n\treturn prefix + \" \" + String(Date.now()).padStart(15, \"0\") + \"\\\\n\";\n}\n\nconst STANDARD_ERRORS = [Error, TypeError, RangeError, SyntaxError, ReferenceError, EvalError, URIError];\n// Bun stamps every error with where it was thrown; the caller's copy gets its own.\nconst LOCATION_FIELDS = new Set([\"stack\", \"message\", \"line\", \"column\", \"originalLine\", \"originalColumn\", \"sourceURL\"]);\n\n// An object's own fields that hold plain values, with their enumerability.\nfunction fieldsOf(object, skip) {\n\tconst fields = [];\n\tfor (const key of Object.getOwnPropertyNames(object)) {\n\t\tif (skip.has(key)) continue;\n\t\tconst descriptor = Object.getOwnPropertyDescriptor(object, key);\n\t\tconst value = descriptor?.value;\n\t\tif (value === null || (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\" && typeof value !== \"bigint\")) continue;\n\t\tfields.push([key, value, descriptor.enumerable === true]);\n\t}\n\treturn fields;\n}\n\n// A thrown error as it crosses to the caller: the standard constructor it descends from, its message, and its own\n// fields with their enumerability. A runtime's error class of its own between the error and that constructor (Bun's\n// node:sqlite errors have one holding name, code and toString) is described by its fields and whether it has a\n// toString of its own, and how it shows.\nfunction failure(error) {\n\tif (!(error instanceof Error)) return { constructor: \"Error\", message: String(error), fields: [] };\n\tlet standard = Object.getPrototypeOf(error);\n\tlet between;\n\twhile (standard !== null && !STANDARD_ERRORS.some((each) => each.prototype === standard)) {\n\t\tif (between === undefined) {\n\t\t\tconst toString = Object.getOwnPropertyDescriptor(standard, \"toString\");\n\t\t\tbetween = {\n\t\t\t\tfields: fieldsOf(standard, new Set([\"constructor\", \"message\"])),\n\t\t\t\t...(typeof toString?.value === \"function\" ? { toString: { enumerable: toString.enumerable === true } } : {}),\n\t\t\t};\n\t\t}\n\t\tstandard = Object.getPrototypeOf(standard);\n\t}\n\treturn {\n\t\tconstructor: standard === null ? \"Error\" : standard.constructor.name,\n\t\tmessage: String(error.message),\n\t\tfields: fieldsOf(error, LOCATION_FIELDS),\n\t\t...(between === undefined ? {} : { between }),\n\t};\n}\n\nconst prepared = new Map();\n\nfunction statement(sql) {\n\tconst cached = prepared.get(sql);\n\tif (cached !== undefined) {\n\t\tprepared.delete(sql);\n\t\tprepared.set(sql, cached);\n\t\treturn cached;\n\t}\n\tconst made = database.prepare(sql);\n\tmade.setReadBigInts(true);\n\tprepared.set(sql, made);\n\tif (prepared.size > workerData.statementCacheSize) prepared.delete(prepared.keys().next().value);\n\treturn made;\n}\n\nfunction value(each) {\n\tif (typeof each === \"bigint\") return each >= -BigInt(Number.MAX_SAFE_INTEGER) && each <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(each) : each;\n\t// A copy of its own: a view of a larger buffer would send the whole buffer.\n\treturn each instanceof Uint8Array ? new Uint8Array(each) : each;\n}\n\n// Rows cross as their column names and one array of values each, in the order the driver gives a row's fields.\nfunction table(rows) {\n\tif (rows.length === 0) return { columns: [], values: [] };\n\tconst columns = Object.keys(rows[0]);\n\treturn { columns, values: rows.map((row) => columns.map((column) => value(row[column]))) };\n}\n\nconst handlers = {\n\topen: (request) => {\n\t\tdatabase = new DatabaseSync(request.path, { readOnly: request.readOnly });\n\t\tconst location = database.location();\n\t\tif (!request.readOnly && typeof location === \"string\" && location.length > 0) {\n\t\t\twalPath = location + \"-wal\";\n\t\t\tlastWalSize = -1n;\n\t\t\tlastWalMtimeNs = -1n;\n\t\t\tdatabase.exec(\n\t\t\t\t\"PRAGMA wal_autocheckpoint=\" +\n\t\t\t\t\tworkerData.walAutoCheckpoint +\n\t\t\t\t\t\"; PRAGMA journal_size_limit=\" +\n\t\t\t\t\tworkerData.walSizeLimit,\n\t\t\t);\n\t\t}\n\t\treturn location;\n\t},\n\texec: (request) => {\n\t\tdatabase.exec(request.sql);\n\t},\n\trun: (request) => ({ changes: Number(statement(request.sql).run(...request.params).changes) }),\n\tget: (request) => {\n\t\tconst row = statement(request.sql).get(...request.params);\n\t\treturn row === undefined ? undefined : table([row]);\n\t},\n\tall: (request) => table(statement(request.sql).all(...request.params)),\n\t// A read transaction's start: BEGIN, then its leading reads, in one request. A BEGIN that fails fails the request and\n\t// leaves no transaction. The reads answer up to the first that fails, which, with the ones after it, the caller then\n\t// sends on its own in the same transaction, so it fails or answers there as it always would.\n\tread: (request) => {\n\t\tdatabase.exec(\"BEGIN\");\n\t\tconst answers = [];\n\t\tfor (const { sql, params } of request.statements) {\n\t\t\ttry {\n\t\t\t\tanswers.push(table(statement(sql).all(...params)));\n\t\t\t} catch {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\treturn answers;\n\t},\n\t// A read transaction's end, which its caller does not wait for: COMMIT, or ROLLBACK where COMMIT fails, so the\n\t// connection is never left inside it.\n\tendRead: () => {\n\t\ttry {\n\t\t\tdatabase.exec(\"COMMIT\");\n\t\t} catch (error) {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"ROLLBACK\");\n\t\t\t} catch {}\n\t\t\tthrow error;\n\t\t}\n\t},\n\t// One non-blocking BEGIN IMMEDIATE, the connection's busy timeout restored before answering, then the transaction's\n\t// leading statements, if any, in the same request. When writersDir and checkQueue are given, checks the\n\t// writers' queue directory first and returns { contended: true } without taking the lock if entries are present\n\t// (or the directory cannot be listed). When holderFd is given, writes the connection's holder record in place\n\t// around taking and releasing the lock.\n\tbegin: (request) => {\n\t\tif (request.writersDir !== undefined) writersDir = request.writersDir;\n\t\tif (\"holderFd\" in request) holderFd = request.holderFd;\n\t\tif (request.checkQueue === true && writersDir !== undefined && hasWriters(writersDir)) {\n\t\t\treturn { contended: true };\n\t\t}\n\t\twriteHolder(holderLine(\"want\"));\n\t\t// The file's lock word (see FREE in node-sqlite-file-gate.ts): taken before BEGIN, after waiting here for a\n\t\t// statement the calling thread runs meanwhile; settleLock gives it back once the transaction ended.\n\t\tif (request.lockState !== undefined) {\n\t\t\tconst state = new Int32Array(request.lockState);\n\t\t\tfor (;;) {\n\t\t\t\tconst found = Atomics.compareExchange(state, 0, 0, request.lockTag * 4 + 2);\n\t\t\t\tif (found === 0) break;\n\t\t\t\t// Anything but a statement of the calling thread (1) is another holder: a lock taken, as BEGIN would find.\n\t\t\t\tif (found !== 1)\n\t\t\t\t\tthrow Object.assign(new Error(\"database is locked\"), { code: \"ERR_SQLITE_ERROR\", errcode: 5, errstr: \"database is locked\" });\n\t\t\t\tAtomics.wait(state, 0, 1, 50);\n\t\t\t}\n\t\t\tAtomics.notify(state, 0);\n\t\t\tlockState = { state, held: request.lockTag * 4 + 3 };\n\t\t}\n\t\tconst configured = Number(database.prepare(\"PRAGMA busy_timeout\").get()?.timeout ?? 0);\n\t\tdatabase.exec(\"PRAGMA busy_timeout=0\");\n\t\tlet began = false;\n\t\ttry {\n\t\t\tdatabase.exec(\"BEGIN IMMEDIATE\");\n\t\t\tbegan = true;\n\t\t\tholderActive = true;\n\t\t} finally {\n\t\t\ttry {\n\t\t\t\tdatabase.exec(\"PRAGMA busy_timeout=\" + configured);\n\t\t\t} catch (restoreFailure) {\n\t\t\t\tif (began) database.exec(\"ROLLBACK\");\n\t\t\t\tthrow restoreFailure;\n\t\t\t}\n\t\t}\n\t\tconst result = request.statements === undefined ? undefined : lead(request.statements);\n\t\tif (inTransaction()) writeHolder(holderLine(\"held\"));\n\t\treturn result;\n\t},\n\tlead: (request) => lead(request.statements),\n\t// \\`repeat\\`, then each statement, in one request: the statements the caller would send one at a time, in the same\n\t// order, each prepared when it is reached. The caller's abort flag is read where the caller would check its signal.\n\tsequence: (request) => {\n\t\tconst abort = request.abort === undefined ? undefined : new Int32Array(request.abort);\n\t\tconst aborted = () => abort !== undefined && Atomics.load(abort, 0) !== 0;\n\t\tlet repeated = 0;\n\t\tif (request.repeat !== undefined) {\n\t\t\tconst { statement: repeat, times, minChanges } = request.repeat;\n\t\t\twhile (repeated < times) {\n\t\t\t\tif (aborted()) return { aborted: true };\n\t\t\t\tconst before = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tstatement(repeat.sql).run(...repeat.params);\n\t\t\t\tconst after = Number(statement(\"SELECT total_changes() AS changes\").get().changes);\n\t\t\t\tif (after - before < minChanges) break;\n\t\t\t\trepeated++;\n\t\t\t}\n\t\t}\n\t\tfor (const { sql, params, script } of request.statements) {\n\t\t\tif (aborted()) return { aborted: true };\n\t\t\tif (script === true) database.exec(sql);\n\t\t\telse statement(sql).run(...params);\n\t\t}\n\t\treturn { repeated };\n\t},\n\tdataVersion: () => Number(database.prepare(\"PRAGMA data_version\").get()?.data_version ?? 0),\n\tnow: () => Number(database.prepare(workerData.nowSql).get().now),\n\tjsonbExtract: () => {\n\t\ttry {\n\t\t\tstatement(\"SELECT jsonb_extract('[]', '$')\");\n\t\t\treturn true;\n\t\t} catch (error) {\n\t\t\tif (error instanceof Error && error.message === \"no such function: jsonb_extract\") return false;\n\t\t\tthrow error;\n\t\t}\n\t},\n\tclose: () => {\n\t\tprepared.clear();\n\t\twalPath = undefined;\n\t\tdatabase?.close();\n\t\tdatabase = undefined;\n\t\tglobalThis.Bun?.gc?.(true);\n\t},\n};\n\n// A write transaction's leading statements, run in order once BEGIN IMMEDIATE took the lock: each answers with its rows\n// and the rows it changed, as all and run would, up to the first that fails; nothing after it runs. The answer says\n// whether the transaction is still open after that failure: SQLite rolls back only the statement for most failures, and\n// the whole transaction for a few (a full disk, an I/O error). A script answers nothing.\nfunction lead(statements) {\n\tconst answers = [];\n\tfor (const { sql, params, script } of statements) {\n\t\ttry {\n\t\t\tif (script === true) {\n\t\t\t\tdatabase.exec(sql);\n\t\t\t\tanswers.push({ columns: [], values: [], changes: 0 });\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst rows = table(statement(sql).all(...params));\n\t\t\tanswers.push({ ...rows, changes: Number(statement(\"SELECT changes() AS changes\").get().changes) });\n\t\t} catch (error) {\n\t\t\treturn { answers, failure: failure(error), open: database.isTransaction === true };\n\t\t}\n\t}\n\treturn { answers };\n}\n\n// The file's lock word while this connection takes or holds the lock: held while a transaction is open on it, given\n// back (and the waiting threads woken) once none is, before the request that ended it is answered.\nlet lockState;\n\nfunction inTransaction() {\n\ttry {\n\t\treturn database?.isTransaction === true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\nfunction settleLock() {\n\tconst open = inTransaction();\n\tif (lockState !== undefined) {\n\t\tconst { state, held } = lockState;\n\t\tif (open) {\n\t\t\tif (Atomics.compareExchange(state, 0, held - 1, held) === held - 1) Atomics.notify(state, 0);\n\t\t} else {\n\t\t\tlockState = undefined;\n\t\t\tif (Atomics.compareExchange(state, 0, held, 0) === held || Atomics.compareExchange(state, 0, held - 1, 0) === held - 1)\n\t\t\t\tAtomics.notify(state, 0);\n\t\t}\n\t}\n\tif (holderActive && !open) {\n\t\tholderActive = false;\n\t\twriteHolder(HOLDER_FREE);\n\t\tlastFreed = true;\n\t\tlastHasWaiters = writersDir !== undefined && fs.existsSync(writersDir);\n\t}\n}\n\nfunction handle(request) {\n\ttry {\n\t\treturn handlers[request.kind](request);\n\t} finally {\n\t\tsettleLock();\n\t}\n}\n\nfunction maybeCheckpoint(kind) {\n\tif (walPath === undefined || database === undefined || !CHECKPOINT_AFTER.has(kind)) return;\n\ttry {\n\t\tif (database.isTransaction !== false) return;\n\t\tconst stat = statSync(walPath, { bigint: true, throwIfNoEntry: false });\n\t\tif (stat === undefined) {\n\t\t\tlastWalSize = -1n;\n\t\t\tlastWalMtimeNs = -1n;\n\t\t\treturn;\n\t\t}\n\t\tif (stat.size <= WAL_SIZE_LIMIT_BYTES) {\n\t\t\tlastWalSize = stat.size;\n\t\t\tlastWalMtimeNs = stat.mtimeNs;\n\t\t\treturn;\n\t\t}\n\t\tif (stat.size === lastWalSize && stat.mtimeNs === lastWalMtimeNs) return;\n\t\tlastWalSize = stat.size;\n\t\tlastWalMtimeNs = stat.mtimeNs;\n\t\tdatabase.exec(\"PRAGMA wal_checkpoint(PASSIVE)\");\n\t} catch {}\n}\n\nparentPort.on(\"message\", (request) => {\n\tlet answered = false;\n\tlastFreed = false;\n\tlastHasWaiters = undefined;\n\tpendingHolderError = undefined;\n\ttry {\n\t\tconst value = handle(request);\n\t\tconst reply = { id: request.id, value, tx: inTransaction() };\n\t\tif (lastFreed) reply.freed = true;\n\t\tif (lastHasWaiters !== undefined) reply.hasWaiters = lastHasWaiters;\n\t\tif (pendingHolderError !== undefined) reply.holderError = pendingHolderError;\n\t\tparentPort.postMessage(reply);\n\t\tanswered = true;\n\t} catch (error) {\n\t\tconst reply = { id: request.id, failure: failure(error), tx: inTransaction() };\n\t\tif (lastFreed) reply.freed = true;\n\t\tif (lastHasWaiters !== undefined) reply.hasWaiters = lastHasWaiters;\n\t\tif (pendingHolderError !== undefined) reply.holderError = pendingHolderError;\n\t\tparentPort.postMessage(reply);\n\t}\n\tif (answered) maybeCheckpoint(request.kind);\n});\n`;\n\n/**\n * Statements sent as one request (see `SqliteSequence`). `abort` holds one `Int32` the caller sets to non-zero when its\n * signal aborts: the thread reads it before each run of `repeat` and before each statement.\n */\nexport interface SequenceRequest {\n\treadonly kind: \"sequence\";\n\treadonly repeat?: SqliteSequence[\"repeat\"];\n\treadonly statements: readonly SequencedStatement[];\n\treadonly abort?: SharedArrayBuffer;\n}\n\n/**\n * What a sequence request is answered with: how many runs of `repeat` changed `minChanges` rows or more, or that it\n * stopped because the caller's signal aborted.\n */\nexport type SequenceAnswer = { readonly repeated: number } | { readonly aborted: true };\n\n/** What a connection's thread is asked to do; each request is answered once, in the order it was sent. */\nexport type ConnectionRequest =\n\t| { readonly kind: \"open\"; readonly path: string; readonly readOnly: boolean }\n\t| { readonly kind: \"exec\"; readonly sql: string }\n\t| { readonly kind: \"run\" | \"get\" | \"all\"; readonly sql: string; readonly params: readonly SqliteValue[] }\n\t| BeginRequest\n\t| LeadRequest\n\t| { readonly kind: \"dataVersion\" | \"now\" | \"jsonbExtract\" | \"close\" }\n\t| ReadTransactionRequest\n\t| SequenceRequest;\n\n/**\n * One non-blocking `BEGIN IMMEDIATE`, then, once it took the lock, `statements`, the transaction's leading statements, in\n * the same request (#6560): see the thread's `begin` and `lead`. `lockState` and `lockTag` are the file's lock word and\n * this connection's tag in it (see `node-sqlite-file-gate.ts`).\n */\nexport interface BeginRequest {\n\treadonly kind: \"begin\";\n\treadonly lockState?: SharedArrayBuffer;\n\treadonly lockTag?: number;\n\treadonly statements?: readonly SequencedStatement[];\n\t/** Open descriptor of this connection's write-lock holder record, written synchronously on the connection thread. */\n\treadonly holderFd?: number;\n\t/** Path of the cross-process writers'-queue directory, checked on the connection thread. */\n\treadonly writersDir?: string;\n\t/** When true, return `{ contended: true }` without taking the lock if `writersDir` has entries or cannot be listed. */\n\treadonly checkQueue?: boolean;\n}\n\n/** Returned by a `begin` request with `checkQueue: true` when the writers' queue directory is non-empty or unreadable. */\nexport interface BeginContendedAnswer {\n\treadonly contended: true;\n}\n\n/**\n * Statements run in one request inside an open transaction, such as a group-commit member's `SAVEPOINT` with its\n * leading statements (#6706): see the thread's `lead`.\n */\nexport interface LeadRequest {\n\treadonly kind: \"lead\";\n\treadonly statements: readonly SequencedStatement[];\n}\n\n/**\n * What a `begin` request with statements is answered with: each statement's rows and the rows it changed, in order, up\n * to the first that failed, that one's failure, and whether the transaction was still open after it; nothing after it\n * ran.\n */\nexport interface LeadAnswer {\n\treadonly answers: readonly { readonly rows: SqliteRow[]; readonly changes: number }[];\n\treadonly failure?: Error;\n\treadonly open?: boolean;\n}\n\n/**\n * A read-only transaction's start with its leading reads, and its end, which only a connection on a thread of its own\n * is sent: see the thread's `read` and `endRead`.\n */\nexport type ReadTransactionRequest =\n\t| { readonly kind: \"read\"; readonly statements: readonly SqliteStatement[] }\n\t| { readonly kind: \"endRead\" };\n\n/** Rows as they cross from a connection's thread: the column names, then each row's values in their order. */\ninterface RowTable {\n\treadonly columns: readonly string[];\n\treadonly values: readonly (readonly SqliteValue[])[];\n}\n\n/** A `LeadAnswer` as it crosses, before rows and the failure are rebuilt. */\ninterface LeadTable {\n\treadonly answers: readonly (RowTable & { readonly changes: number })[];\n\treadonly failure?: ConnectionFailure;\n\treadonly open?: boolean;\n}\n\n/** What a request's answer carries as it crosses, before rows are rebuilt. */\ntype ConnectionValue =\n\t| RowTable\n\t| readonly RowTable[]\n\t| LeadTable\n\t| BeginContendedAnswer\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/**\n * What a request is answered with: `get` a row or undefined, `all` rows, `read` the rows of each leading read up to\n * the first that failed, `run` the changes, `sequence` a `SequenceAnswer`, `open` the location, `dataVersion` and `now`\n * a number, `jsonbExtract` a boolean, the others undefined.\n */\nexport type ConnectionAnswer =\n\t| SqliteRow\n\t| SqliteRow[]\n\t| SqliteRow[][]\n\t| LeadAnswer\n\t| BeginContendedAnswer\n\t| { readonly changes: number }\n\t| SequenceAnswer\n\t| string\n\t| number\n\t| boolean\n\t| null\n\t| undefined;\n\n/** An own field that holds a plain value: its key, value and enumerability. */\ntype ConnectionField = readonly [string, string | number | boolean | bigint, boolean];\n\n/** A failure as it crosses from a connection's thread; see `failure` in the thread's source. */\ninterface ConnectionFailure {\n\treadonly constructor: string;\n\treadonly message: string;\n\treadonly fields: readonly ConnectionField[];\n\treadonly between?: {\n\t\treadonly fields: readonly ConnectionField[];\n\t\treadonly toString?: { readonly enumerable: boolean };\n\t};\n}\n\ninterface ConnectionReply {\n\treadonly id: number;\n\treadonly value?: ConnectionValue;\n\treadonly failure?: ConnectionFailure;\n\treadonly tx?: boolean;\n\treadonly freed?: boolean;\n\treadonly hasWaiters?: boolean;\n\treadonly holderError?: ConnectionFailure;\n}\n\nconst STANDARD_ERRORS: Readonly<Record<string, ErrorConstructor>> = {\n\tError,\n\tTypeError,\n\tRangeError,\n\tSyntaxError,\n\tReferenceError,\n\tEvalError,\n\tURIError,\n};\n\n/** One prototype per runtime error class seen, by what it holds: see `connectionError`. */\nconst betweenPrototypes = new Map<string, object>();\n\n/** How a runtime's error class of its own shows an error, as Bun's do: `TypeError [ERR_INVALID_ARG_VALUE]: …`. */\nfunction showWithCode(this: Error & { readonly code?: unknown }): string {\n\treturn `${this.name} [${String(this.code)}]: ${this.message}`;\n}\n\nfunction betweenPrototype(base: ErrorConstructor, between: NonNullable<ConnectionFailure[\"between\"]>): object {\n\tconst key = JSON.stringify([\n\t\tbase.name,\n\t\tbetween.fields.map(([field, value, enumerable]) => [field, String(value), enumerable]),\n\t\tbetween.toString,\n\t]);\n\tlet prototype = betweenPrototypes.get(key);\n\tif (prototype === undefined) {\n\t\tconst created: object = Object.create(base.prototype);\n\t\tfor (const [field, value, enumerable] of between.fields)\n\t\t\tObject.defineProperty(created, field, { value, enumerable, writable: true, configurable: true });\n\t\tif (between.toString !== undefined)\n\t\t\tObject.defineProperty(created, \"toString\", {\n\t\t\t\tvalue: showWithCode,\n\t\t\t\tenumerable: between.toString.enumerable,\n\t\t\t\twritable: true,\n\t\t\t\tconfigurable: true,\n\t\t\t});\n\t\tbetweenPrototypes.set(key, created);\n\t\tprototype = created;\n\t}\n\treturn prototype;\n}\n\n/**\n * The driver's error, rebuilt on the calling thread as the driver threw it: an instance of the same standard error\n * class with the same message, and the same own fields (`code`, `errcode`, `errstr` for SQLite's errors) with the same\n * enumerability. A runtime's own error class between them is stood in for by a prototype that holds the same fields and\n * shows the error the same way.\n */\nfunction connectionError(failure: ConnectionFailure): Error {\n\tconst base = STANDARD_ERRORS[failure.constructor] ?? Error;\n\tconst error = new base(failure.message);\n\tif (failure.between !== undefined) Object.setPrototypeOf(error, betweenPrototype(base, failure.between));\n\tfor (const [key, value, enumerable] of failure.fields)\n\t\tObject.defineProperty(error, key, { value, enumerable, writable: true, configurable: true });\n\treturn error;\n}\n\n/** The rows of `table`, each a plain object built the way the calling-thread connection builds them. */\nfunction rowsOf(table: RowTable): SqliteRow[] {\n\tconst { columns, values } = table;\n\treturn values.map((row) => Object.fromEntries(columns.map((column, index) => [column, row[index] as SqliteValue])));\n}\n\ninterface Waiter {\n\treadonly resolve: (value: ConnectionValue) => void;\n\treadonly reject: (error: unknown) => void;\n}\n\n/** Thrown for a request to a connection whose thread is gone: closed, or lost to an error or an exit. */\nexport class ConnectionThreadEndedError extends Error {\n\tconstructor(message: string) {\n\t\tsuper(message);\n\t\tthis.name = \"ConnectionThreadEndedError\";\n\t}\n}\n\n/** Options that make every worker thread run code of the user's: a preload or a module loader. */\nconst WORKER_CODE_OPTIONS = new Set([\"--require\", \"-r\", \"--import\", \"--loader\", \"--experimental-loader\"]);\n\n/** The thread `startSpare` started for the next open, until an open takes it or `releaseSpare` ends it. */\nlet spare: ThreadConnection | undefined;\n\n/** How many prepared statements a connection keeps for reuse, least recently used first out. */\nexport const STATEMENT_CACHE_SIZE = 256;\n\n/** Safety-net automatic WAL checkpoint threshold in pages on writable file connections. */\nconst WAL_AUTO_CHECKPOINT = 10_000;\n/** Target write-ahead log size limit in bytes (4 MiB) for journal truncation and post-response checkpoints. */\nconst WAL_SIZE_LIMIT = 4 * 1024 * 1024;\n\n/** A node:sqlite connection running on its own worker thread. */\nexport class ThreadConnection {\n\tprivate readonly worker: Worker;\n\tprivate readonly waiting = new Map<number, Waiter>();\n\tprivate nextId = 1;\n\tprivate _inTransaction?: boolean;\n\tprivate _lastFreed = false;\n\tprivate _lastHasWaiters?: boolean;\n\tprivate _holderError?: Error;\n\tprivate ended?: Error;\n\tprivate closing?: Promise<undefined>;\n\n\t/** Whether SQLite had an open transaction after the thread's last answer; undefined for older connection threads. */\n\tget inTransaction(): boolean | undefined {\n\t\treturn this._inTransaction;\n\t}\n\n\t/** Consumes any connection-thread holder-record write failure reported since the last check. */\n\ttakeHolderError(): Error | undefined {\n\t\tconst error = this._holderError;\n\t\tthis._holderError = undefined;\n\t\treturn error;\n\t}\n\n\t/**\n\t * Consumes the release metadata reported by the connection thread when the transaction ended: whether the thread\n\t * already wrote the `\"free\"` holder record, and whether the writers'-queue directory existed.\n\t */\n\ttakeReleaseState(): { readonly freed: boolean; readonly hasWaiters: boolean | undefined } {\n\t\tconst state = { freed: this._lastFreed, hasWaiters: this._lastHasWaiters };\n\t\tthis._lastFreed = false;\n\t\tthis._lastHasWaiters = undefined;\n\t\treturn state;\n\t}\n\n\tprivate constructor() {\n\t\t// None of the process's own flags: the caller's preloads would run again for every connection, and its\n\t\t// `--input-type=module` would make this source a module. Whether node:sqlite is available was settled by the\n\t\t// open before it started the thread.\n\t\tthis.worker = new Worker(CONNECTION_SOURCE, {\n\t\t\teval: true,\n\t\t\texecArgv: [],\n\t\t\tworkerData: {\n\t\t\t\tnowSql: `SELECT ${sqliteDialect.nowMs} AS now`,\n\t\t\t\tstatementCacheSize: STATEMENT_CACHE_SIZE,\n\t\t\t\twalAutoCheckpoint: WAL_AUTO_CHECKPOINT,\n\t\t\t\twalSizeLimit: WAL_SIZE_LIMIT,\n\t\t\t},\n\t\t});\n\t\tthis.worker.on(\"message\", (reply: ConnectionReply) => this.receive(reply));\n\t\tthis.worker.on(\"error\", (error: Error) => this.end(error));\n\t\tthis.worker.on(\"exit\", (code: number) =>\n\t\t\tthis.end(new ConnectionThreadEndedError(`SQLite connection thread exited with code ${code}`)),\n\t\t);\n\t}\n\n\t/**\n\t * Opens `openAs` (or `path`) on a thread of its own and resolves with the location SQLite reports for it. A failure\n\t * to start the thread or to open the database rejects with its cause; the thread is gone then.\n\t */\n\tstatic async open(\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined && started.ended === undefined) {\n\t\t\ttry {\n\t\t\t\treturn await ThreadConnection.openOn(started, path, options);\n\t\t\t} catch (error) {\n\t\t\t\t// The spare thread was lost before it answered: open on a thread of its own, as without one.\n\t\t\t\tif (error !== started.ended) throw error;\n\t\t\t}\n\t\t}\n\t\treturn ThreadConnection.openOn(new ThreadConnection(), path, options);\n\t}\n\n\t/**\n\t * Starts one connection thread now, for the next open to take, so that the thread's startup overlaps whatever the\n\t * process does until then (an interactive session loads its modules meanwhile). Idle, the thread keeps nothing\n\t * alive. Nothing starts when the process runs a preload or a module loader, which every worker thread runs again,\n\t * or runs under the permission model; a thread that cannot start leaves every open as it is without one.\n\t */\n\tstatic startSpare(): void {\n\t\tif (spare !== undefined || process.permission !== undefined) return;\n\t\tif (startupNodeOptions().some((option) => WORKER_CODE_OPTIONS.has(option.name))) return;\n\t\ttry {\n\t\t\tconst started = new ThreadConnection();\n\t\t\tstarted.worker.unref();\n\t\t\tspare = started;\n\t\t} catch {\n\t\t\t// Opens start their own threads.\n\t\t}\n\t}\n\n\t/** Ends the spare thread if no open has taken it. */\n\tstatic releaseSpare(): void {\n\t\tconst started = spare;\n\t\tspare = undefined;\n\t\tif (started !== undefined) void started.stop();\n\t}\n\n\tprivate static async openOn(\n\t\tconnection: ThreadConnection,\n\t\tpath: string,\n\t\toptions: { readonly readOnly: boolean; readonly openAs?: string },\n\t): Promise<{ readonly connection: ThreadConnection; readonly location: string | null }> {\n\t\ttry {\n\t\t\tconst location = await connection.request({\n\t\t\t\tkind: \"open\",\n\t\t\t\tpath: options.openAs ?? path,\n\t\t\t\treadOnly: options.readOnly,\n\t\t\t});\n\t\t\treturn { connection, location: typeof location === \"string\" ? location : null };\n\t\t} catch (error) {\n\t\t\tawait connection.stop();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/**\n\t * Sends one request; resolves with the thread's answer or rejects with the driver's error, rebuilt. While a request\n\t * waits for its answer the thread keeps the process alive; an idle connection does not, as a connection on the\n\t * calling thread would not.\n\t */\n\trequest(request: ConnectionRequest): Promise<ConnectionAnswer> {\n\t\tif (request.kind === \"close\") return this.close();\n\t\tconst answer = this.send(request);\n\t\tif (request.kind === \"get\")\n\t\t\treturn answer.then((value) => (value === undefined ? undefined : rowsOf(value as RowTable)[0]));\n\t\tif (request.kind === \"all\") return answer.then((value) => rowsOf(value as RowTable));\n\t\tif (request.kind === \"read\") return answer.then((value) => (value as readonly RowTable[]).map(rowsOf));\n\t\tif (request.kind === \"lead\" || (request.kind === \"begin\" && request.statements !== undefined))\n\t\t\treturn answer.then((value): LeadAnswer | BeginContendedAnswer | undefined => {\n\t\t\t\tif (value === undefined) return undefined;\n\t\t\t\tif (typeof value === \"object\" && value !== null && \"contended\" in value)\n\t\t\t\t\treturn value as BeginContendedAnswer;\n\t\t\t\tconst { answers, failure, open } = value as LeadTable;\n\t\t\t\treturn {\n\t\t\t\t\tanswers: answers.map((each) => ({ rows: rowsOf(each), changes: each.changes })),\n\t\t\t\t\t...(failure === undefined ? {} : { failure: connectionError(failure), open: open === true }),\n\t\t\t\t};\n\t\t\t});\n\t\treturn answer as Promise<ConnectionAnswer>;\n\t}\n\n\tprivate send(request: ConnectionRequest): Promise<ConnectionValue> {\n\t\treturn new Promise<ConnectionValue>((resolve, reject) => {\n\t\t\tif (this.ended !== undefined) {\n\t\t\t\treject(this.ended);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst id = this.nextId++;\n\t\t\ttry {\n\t\t\t\tthis.worker.postMessage({ id, ...request });\n\t\t\t} catch (error) {\n\t\t\t\t// A value the thread cannot receive.\n\t\t\t\treject(error);\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthis.waiting.set(id, { resolve, reject });\n\t\t\tif (this.waiting.size === 1) this.worker.ref();\n\t\t});\n\t}\n\n\t/**\n\t * Closes the database on its thread, then ends the thread: a `close` request. Requests sent after it are rejected. A\n\t * thread already lost has nothing to close.\n\t */\n\tprivate close(): Promise<undefined> {\n\t\tthis.closing ??= (async () => {\n\t\t\ttry {\n\t\t\t\tif (this.ended === undefined) await this.send({ kind: \"close\" });\n\t\t\t} finally {\n\t\t\t\tawait this.stop();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t})();\n\t\treturn this.closing;\n\t}\n\n\tprivate receive(reply: ConnectionReply): void {\n\t\tif (typeof reply.tx === \"boolean\") this._inTransaction = reply.tx;\n\t\tif (reply.freed === true) {\n\t\t\tthis._lastFreed = true;\n\t\t\tthis._lastHasWaiters = reply.hasWaiters;\n\t\t}\n\t\tif (reply.holderError !== undefined) this._holderError ??= connectionError(reply.holderError);\n\t\tconst waiter = this.waiting.get(reply.id);\n\t\tif (waiter === undefined) return;\n\t\tthis.waiting.delete(reply.id);\n\t\tif (this.waiting.size === 0) this.worker.unref();\n\t\tif (reply.failure === undefined) waiter.resolve(reply.value);\n\t\telse waiter.reject(connectionError(reply.failure));\n\t}\n\n\t/** Rejects every request still waiting, oldest first, and every later one. Ending again does nothing. */\n\tprivate end(cause: Error): void {\n\t\tif (this.ended !== undefined) return;\n\t\t// Kept for as long as the connection is: an error's stack, until formatted, keeps the functions of the frames it\n\t\t// names, and so whatever they hold, such as a session that closed its store.\n\t\tvoid cause.stack;\n\t\tthis.ended = cause;\n\t\tconst waiting = [...this.waiting.values()];\n\t\tthis.waiting.clear();\n\t\tthis.worker.unref();\n\t\tfor (const waiter of waiting) waiter.reject(cause);\n\t}\n\n\tprivate async stop(): Promise<void> {\n\t\tthis.end(new ConnectionThreadEndedError(\"SQLite connection closed\"));\n\t\tawait this.worker.terminate();\n\t}\n\n\t/** Calls `listener` once the connection's thread has exited, whether closed or lost. */\n\tonExit(listener: () => void): void {\n\t\tthis.worker.once(\"exit\", listener);\n\t}\n\n\t/**\n\t * Starts a spare worker for a non-interactive or storage-overridden CLI\n\t * invocation only when the real CLI/storage resolvers select a SQLite store.\n\t */\n\tstatic async startSpareIfSqlNeeded(\n\t\targs: readonly string[],\n\t\tterminal: { readonly stdinIsTTY: boolean; readonly stdoutIsTTY: boolean },\n\t\tstillBeforeMain: () => boolean,\n\t): Promise<void> {\n\t\tconst { shouldStartSpareDatabaseThread } = await import(\"../../utils/startup-database-spare.ts\");\n\t\tif (stillBeforeMain() && shouldStartSpareDatabaseThread(args, false, terminal)) {\n\t\t\tThreadConnection.startSpare();\n\t\t}\n\t}\n}\n"]}
|