@powerhousedao/reactor-api 6.2.3-dev.73 → 6.2.3-dev.75

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 (28) hide show
  1. package/dist/{base-document-models-D3aAUB7E.mjs → base-document-models-BGt__Ctn.mjs} +47 -3
  2. package/dist/{base-document-models-D3aAUB7E.mjs.map → base-document-models-BGt__Ctn.mjs.map} +1 -1
  3. package/dist/error-info-CCQcLAcW.mjs +424 -0
  4. package/dist/error-info-CCQcLAcW.mjs.map +1 -0
  5. package/dist/index.d.mts +54 -9
  6. package/dist/index.d.mts.map +1 -1
  7. package/dist/index.mjs +155 -13
  8. package/dist/index.mjs.map +1 -1
  9. package/dist/{package-subgraph-check-C0hGBt4N.mjs → package-subgraph-check-C5S8yvBI.mjs} +4 -4
  10. package/dist/{package-subgraph-check-C0hGBt4N.mjs.map → package-subgraph-check-C5S8yvBI.mjs.map} +1 -1
  11. package/dist/pglite-like-CKQEL_Q0.d.mts +27 -0
  12. package/dist/pglite-like-CKQEL_Q0.d.mts.map +1 -0
  13. package/dist/pglite-node-BOFT_yUj.mjs +702 -0
  14. package/dist/pglite-node-BOFT_yUj.mjs.map +1 -0
  15. package/dist/src/graphql/subgraph-types.mjs +1 -1
  16. package/dist/src/packages/vite-loader.d.mts +7 -0
  17. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  18. package/dist/src/packages/vite-loader.mjs +21 -4
  19. package/dist/src/packages/vite-loader.mjs.map +1 -1
  20. package/dist/src/pglite/pglite-node.d.mts +227 -2
  21. package/dist/src/pglite/pglite-node.d.mts.map +1 -1
  22. package/dist/src/pglite/pglite-node.mjs +5 -4
  23. package/dist/src/pglite/worker/entry.d.mts +2 -0
  24. package/dist/src/pglite/worker/entry.mjs +251 -0
  25. package/dist/src/pglite/worker/entry.mjs.map +1 -0
  26. package/package.json +13 -13
  27. package/dist/pglite-node-C-UQXrjU.mjs +0 -576
  28. package/dist/pglite-node-C-UQXrjU.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pglite-node-BOFT_yUj.mjs","sources":["../src/pglite/snapshot-reader.ts","../src/pglite/convert-snapshot-dir.ts","../src/pglite/preflight.ts","../src/pglite/worker/errors.ts","../src/pglite/worker/protocol.ts","../src/pglite/worker/threaded-pglite.ts"],"sourcesContent":["import { promises as fs } from \"node:fs\";\nimport type { FileHandle } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { syncTree, type SyncTreeHostFs } from \"./sync-tree.js\";\n\n// v1: magic, u32 version, u32 count; then u8 type, u32 mode, path, u32 len, data.\nexport const SNAPSHOT_FILE_NAME = \"snapshot.bin\";\nconst MAGIC = new Uint8Array([0x50, 0x47, 0x4c, 0x41]);\nconst FORMAT_VERSION = 1;\nconst HEADER_SIZE = 12;\nconst ENTRY_PREFIX_SIZE = 9;\nconst SKIPPED_ENTRIES = new Set([\"postmaster.pid\"]);\n// Node rejects a single read above 2^31-1 bytes.\nconst DEFAULT_IO_CHUNK_SIZE = 64 * 1024 * 1024;\n\nexport interface ExtractSnapshotOptions {\n chunkSize?: number;\n /** Default true: one fsync pass over the tree after the last write. */\n sync?: boolean;\n hostFs?: SyncTreeHostFs;\n}\n\nexport interface ExtractedSnapshot {\n pgVersionMajor: number;\n /** `global/pg_control` bytes; absent only in synthetic trees. */\n pgControl?: Buffer;\n /** Entries written to disk; skipped entries are not counted. */\n entries: number;\n /** Size of the snapshot file. */\n bytes: number;\n}\n\n/** Unpacks a snapshot into the existing `outDir`. */\nexport async function extractSnapshot(\n snapshotPath: string,\n outDir: string,\n options: ExtractSnapshotOptions = {},\n): Promise<ExtractedSnapshot> {\n const fh = await fs.open(snapshotPath, \"r\");\n try {\n const { size } = await fh.stat();\n return await extractFromHandle(fh, size, outDir, options);\n } finally {\n await fh.close();\n }\n}\n\nasync function extractFromHandle(\n fh: FileHandle,\n fileSize: number,\n outDir: string,\n options: ExtractSnapshotOptions,\n): Promise<ExtractedSnapshot> {\n const root = path.resolve(outDir);\n const chunkSize = Math.min(\n options.chunkSize ?? DEFAULT_IO_CHUNK_SIZE,\n Math.max(1, fileSize),\n );\n const reader = new ChunkedReader(fh, chunkSize);\n\n const header = await reader.take(HEADER_SIZE);\n for (let i = 0; i < MAGIC.length; i++) {\n if (header[i] !== MAGIC[i]) {\n throw new Error(\"snapshot.bin: invalid snapshot magic\");\n }\n }\n const version = header.readUInt32LE(4);\n if (version !== FORMAT_VERSION) {\n throw new Error(`snapshot.bin: unsupported snapshot version ${version}`);\n }\n const count = header.readUInt32LE(8);\n\n const decoder = new TextDecoder();\n let pgVersionText: string | undefined;\n let pgControl: Buffer | undefined;\n let written = 0;\n\n for (let i = 0; i < count; i++) {\n const prefix = await reader.take(ENTRY_PREFIX_SIZE);\n const type = prefix.readUInt8(0);\n const mode = prefix.readUInt32LE(1) & 0o7777;\n const pathLen = prefix.readUInt32LE(5);\n const relPath = decoder.decode(await reader.take(pathLen));\n const dataLen = (await reader.take(4)).readUInt32LE(0);\n const data = await reader.take(dataLen);\n\n const full = resolveInside(root, relPath);\n if (SKIPPED_ENTRIES.has(relPath)) continue;\n\n if (type === 0) {\n await fs.mkdir(full, { recursive: true });\n await fs.chmod(full, dirMode(mode));\n } else if (type === 1) {\n await fs.mkdir(path.dirname(full), { recursive: true });\n await fs.writeFile(full, data);\n await fs.chmod(full, mode);\n if (relPath === \"PG_VERSION\") pgVersionText = data.toString(\"utf8\");\n if (relPath === \"global/pg_control\") pgControl = data;\n } else {\n throw new Error(`snapshot.bin: unknown entry type ${type}`);\n }\n written++;\n }\n\n if (pgVersionText === undefined) {\n throw new Error(\"snapshot.bin: no PG_VERSION entry\");\n }\n const pgVersionMajor = Number.parseInt(pgVersionText.trim(), 10);\n if (!Number.isInteger(pgVersionMajor) || pgVersionMajor <= 0) {\n throw new Error(\n `snapshot.bin: unreadable PG_VERSION ${JSON.stringify(pgVersionText)}`,\n );\n }\n\n if (options.sync ?? true) syncTree(root, options.hostFs);\n\n return { pgVersionMajor, pgControl, entries: written, bytes: fileSize };\n}\n\nfunction resolveInside(root: string, relPath: string): string {\n const full = path.resolve(root, relPath);\n if (full !== root && !full.startsWith(root + path.sep)) {\n throw new Error(`snapshot.bin: entry escapes the data dir: ${relPath}`);\n }\n return full;\n}\n\n/** NTFS has no execute bit; a Windows snapshot can carry untraversable dirs. */\nexport function dirMode(mode: number): number {\n return (mode & 0o7777) | 0o111;\n}\n\nclass ChunkedReader {\n private readonly buf: Buffer;\n private start = 0;\n private end = 0;\n private position = 0;\n\n constructor(\n private readonly fh: Pick<FileHandle, \"read\">,\n chunkSize: number,\n ) {\n this.buf = Buffer.allocUnsafe(Math.max(1, chunkSize));\n }\n\n async take(n: number): Promise<Buffer> {\n const out = Buffer.allocUnsafe(n);\n let filled = 0;\n while (filled < n) {\n if (this.start === this.end) {\n if (n - filled >= this.buf.byteLength) {\n filled += await this.readInto(out, filled, n - filled);\n continue;\n }\n this.start = 0;\n this.end = await this.readInto(this.buf, 0, this.buf.byteLength);\n }\n const k = Math.min(this.end - this.start, n - filled);\n this.buf.copy(out, filled, this.start, this.start + k);\n this.start += k;\n filled += k;\n }\n return out;\n }\n\n private async readInto(\n target: Buffer,\n offset: number,\n length: number,\n ): Promise<number> {\n const { bytesRead } = await this.fh.read(\n target,\n offset,\n Math.min(length, this.buf.byteLength),\n this.position,\n );\n if (bytesRead <= 0) {\n throw new Error(\"snapshot.bin: truncated snapshot\");\n }\n this.position += bytesRead;\n return bytesRead;\n }\n}\n","import type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { extractSnapshot, SNAPSHOT_FILE_NAME } from \"./snapshot-reader.js\";\nimport { syncDirectory, syncTree, type SyncTreeHostFs } from \"./sync-tree.js\";\n\nexport interface VerifyHandle {\n query<T>(sql: string): Promise<{ rows: T[] }>;\n close(): Promise<void>;\n}\n\nexport type ConversionStep =\n | \"extract\"\n | \"verify\"\n | \"renameOld\"\n | \"renameNew\"\n | \"removeOld\";\n\nexport interface ConversionDeps {\n /** Opens `dataDir` with the stock NodeFS of the PGlite module for `major`. */\n openForVerify: (major: number, dataDir: string) => Promise<VerifyHandle>;\n logger: ILogger;\n /** Test hook: throw after a named step to simulate a crash there. */\n afterStep?: (step: ConversionStep) => void | Promise<void>;\n hostFs?: SyncTreeHostFs;\n}\n\n// Backoff doubles per retry; five keeps a scanner-held file to ~3 s.\nconst RM_OPTIONS = {\n recursive: true,\n force: true,\n maxRetries: 5,\n retryDelay: 100,\n} as const;\n\ninterface Siblings {\n dir: string;\n converting: string;\n old: string;\n snapshot: string;\n}\n\nfunction siblingsOf(dir: string): Siblings {\n const resolved = path.resolve(dir);\n return {\n dir: resolved,\n converting: `${resolved}.converting`,\n old: `${resolved}.old`,\n snapshot: path.join(resolved, SNAPSHOT_FILE_NAME),\n };\n}\n\n/** Settles the debris of an interrupted conversion; runs before it at boot. */\nexport async function recoverConversion(\n dir: string,\n deps: ConversionDeps,\n): Promise<void> {\n const s = siblingsOf(dir);\n const [dirExists, convertingExists, oldExists] = await Promise.all([\n exists(s.dir),\n exists(s.converting),\n exists(s.old),\n ]);\n\n if (!dirExists) {\n if (convertingExists) {\n // Died between the two renames: finish the swap.\n await fs.rename(s.converting, s.dir);\n if (oldExists) await fs.rm(s.old, RM_OPTIONS);\n deps.logger.warn(\n `PGlite conversion of ${s.dir} was interrupted after the swap started; completed it`,\n );\n return;\n }\n if (oldExists) {\n throw new Error(\n `PGlite data dir ${s.dir} is missing but ${s.old} exists; refusing to initialize beside it. Inspect and rename or remove ${s.old}.`,\n );\n }\n return;\n }\n\n const snapshotExists = await exists(s.snapshot);\n if (snapshotExists) {\n // The snapshot is authoritative; anything beside it is debris.\n if (convertingExists) await fs.rm(s.converting, RM_OPTIONS);\n if (oldExists) await fs.rm(s.old, RM_OPTIONS);\n return;\n }\n\n // dir is a converted PGDATA; anything beside it is superseded.\n if (oldExists) await fs.rm(s.old, RM_OPTIONS);\n if (convertingExists) {\n deps.logger.warn(\n `Removing stray ${s.converting}; ${s.dir} holds no snapshot and is authoritative`,\n );\n await fs.rm(s.converting, RM_OPTIONS);\n }\n}\n\n/** Extracts into `.converting`, verifies by opening it, swaps through `.old`. */\nexport async function convertSnapshotDir(\n dir: string,\n deps: ConversionDeps,\n): Promise<\"converted\" | \"none\"> {\n const s = siblingsOf(dir);\n if (!(await exists(s.snapshot))) return \"none\";\n\n const startedAt = performance.now();\n await fs.rm(s.converting, RM_OPTIONS);\n await fs.mkdir(s.converting, { mode: 0o700 });\n\n let snapshotBytes: number;\n let entries: number;\n try {\n ({ bytes: snapshotBytes, entries } = await extractAndVerify(s, deps));\n } catch (err) {\n await fs.rm(s.converting, RM_OPTIONS);\n throw err;\n }\n\n // Parent synced after each rename: a power loss lands on one recovery row.\n const parent = path.dirname(s.dir);\n await fs.rename(s.dir, s.old);\n syncDirectory(parent, deps.hostFs);\n await deps.afterStep?.(\"renameOld\");\n await fs.rename(s.converting, s.dir);\n syncDirectory(parent, deps.hostFs);\n await deps.afterStep?.(\"renameNew\");\n try {\n await fs.rm(s.old, RM_OPTIONS);\n } catch (err) {\n // The converted dir is in place; recoverConversion removes .old next boot.\n deps.logger.warn(\n `Could not remove ${s.old} after conversion; it is removed at the next boot: ${String(err)}`,\n );\n }\n await deps.afterStep?.(\"removeOld\");\n\n const convertedBytes = await treeBytes(s.dir);\n const durationMs = Math.round(performance.now() - startedAt);\n deps.logger.info(\n `Converted PGlite snapshot at ${s.dir}: snapshot ${snapshotBytes} bytes -> ${convertedBytes} bytes on disk, ${entries} entries, ${durationMs} ms`,\n );\n return \"converted\";\n}\n\nasync function extractAndVerify(\n s: Siblings,\n deps: ConversionDeps,\n): Promise<{ bytes: number; entries: number }> {\n const extracted = await extractSnapshot(s.snapshot, s.converting, {\n sync: false,\n });\n await deps.afterStep?.(\"extract\");\n\n if (!extracted.pgControl) {\n throw new Error(`${s.snapshot} has no global/pg_control entry`);\n }\n const expectedIdentifier = extracted.pgControl.readBigUInt64LE(0).toString();\n const handle = await deps.openForVerify(\n extracted.pgVersionMajor,\n s.converting,\n );\n try {\n await verifyOpenStore(handle, expectedIdentifier);\n } finally {\n // Must close before the renames; Windows refuses to rename an open dir.\n await handle.close();\n }\n await fs.rm(path.join(s.converting, \"postmaster.pid\"), { force: true });\n if (await exists(path.join(s.converting, SNAPSHOT_FILE_NAME))) {\n throw new Error(\n `Extracted PGlite data dir ${s.converting} contains ${SNAPSHOT_FILE_NAME}`,\n );\n }\n // One pass covers the extraction and the verify open's own writes.\n syncTree(s.converting, deps.hostFs);\n await deps.afterStep?.(\"verify\");\n return { bytes: extracted.bytes, entries: extracted.entries };\n}\n\nasync function verifyOpenStore(\n handle: VerifyHandle,\n expectedIdentifier: string,\n): Promise<void> {\n // numeric parses to a float above 2^53; compare as text.\n const ident = await handle.query<{ system_identifier: string }>(\n \"SELECT system_identifier::text AS system_identifier FROM pg_control_system()\",\n );\n const actual = ident.rows[0]?.system_identifier;\n if (actual !== expectedIdentifier) {\n throw new Error(\n `PGlite system identifier mismatch after extraction: pg_control says ${expectedIdentifier}, server says ${String(actual)}`,\n );\n }\n const tables = await handle.query<{ qualified: string }>(\n \"SELECT format('%I.%I', schemaname, tablename) AS qualified FROM pg_tables WHERE schemaname NOT IN ('pg_catalog', 'information_schema') ORDER BY 1\",\n );\n for (const { qualified } of tables.rows) {\n await handle.query(`SELECT count(*) FROM ${qualified}`);\n }\n}\n\nasync function exists(p: string): Promise<boolean> {\n try {\n await fs.lstat(p);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function treeBytes(dir: string): Promise<number> {\n let total = 0;\n const entries = await fs.readdir(dir, { withFileTypes: true });\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n total += await treeBytes(full);\n } else if (entry.isFile()) {\n total += (await fs.stat(full)).size;\n }\n }\n return total;\n}\n","import { PGlite } from \"@electric-sql/pglite\";\nimport { NodeFS } from \"@electric-sql/pglite/nodefs\";\nimport type { ILogger } from \"document-model\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport {\n convertSnapshotDir,\n recoverConversion,\n type ConversionDeps,\n type VerifyHandle,\n} from \"./convert-snapshot-dir.js\";\n\n/** PG major of the pinned @electric-sql/pglite; it exports none, so the test checks initdb. */\nexport const CURRENT_PGLITE_MAJOR = 17;\n\n/** `openForVerify` over the loaded PGlite module only. */\nexport async function openCurrentPgliteForVerify(\n major: number,\n dataDir: string,\n): Promise<VerifyHandle> {\n if (major !== CURRENT_PGLITE_MAJOR) {\n throw new Error(\n `PGlite snapshot at ${dataDir} is PG${major}; this process only opens PG${CURRENT_PGLITE_MAJOR} data dirs`,\n );\n }\n const pg = new PGlite({ fs: new NodeFS(dataDir) });\n await pg.waitReady;\n return pg;\n}\n\n/** Converts a snapshot store and clears the files a previous run leaves behind. */\nexport async function preparePgliteDataDir(\n dir: string,\n deps: ConversionDeps,\n): Promise<void> {\n await recoverConversion(dir, deps);\n await convertSnapshotDir(dir, deps);\n await removeStalePgliteFiles(dir, deps.logger);\n}\n\n/** PGlite leaves `postmaster.pid` after every close and `pg_wal/xlogtemp.*` after some. */\nexport async function removeStalePgliteFiles(\n dir: string,\n logger: Pick<ILogger, \"debug\">,\n): Promise<void> {\n const lockfile = path.join(dir, \"postmaster.pid\");\n let hadLockfile = true;\n try {\n await fs.unlink(lockfile);\n } catch {\n hadLockfile = false;\n }\n if (hadLockfile) logger.debug(`Removed PGlite lockfile ${lockfile}`);\n\n const walDir = path.join(dir, \"pg_wal\");\n let names: string[];\n try {\n names = await fs.readdir(walDir);\n } catch {\n return;\n }\n for (const name of names) {\n if (!name.startsWith(\"xlogtemp.\")) continue;\n await fs.rm(path.join(walDir, name), { force: true });\n logger.debug(`Removed PGlite temp WAL file ${path.join(walDir, name)}`);\n }\n}\n","/** Base class for failures of the worker itself, as opposed to SQL errors. */\nexport class PGliteWorkerError extends Error {\n constructor(\n readonly label: string,\n message: string,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n this.name = \"PGliteWorkerError\";\n }\n}\n\n/** The worker could not open its store; every call on the stand-in fails with this. */\nexport class PGliteWorkerInitError extends PGliteWorkerError {\n constructor(label: string, options?: { cause?: unknown }) {\n super(\n label,\n `PGlite worker for ${label} failed to open its store`,\n options,\n );\n this.name = \"PGliteWorkerInitError\";\n }\n}\n\n/** The worker thread exited (crash, terminate, out of memory) before answering. */\nexport class PGliteWorkerExitedError extends PGliteWorkerError {\n constructor(\n label: string,\n readonly exitCode: number,\n options?: { cause?: unknown },\n ) {\n super(\n label,\n `PGlite worker for ${label} exited with code ${exitCode}`,\n options,\n );\n this.name = \"PGliteWorkerExitedError\";\n }\n}\n\n/** A call was made after `close()` started. */\nexport class PGliteWorkerClosedError extends PGliteWorkerError {\n constructor(label: string) {\n super(label, `PGlite worker for ${label} is closed`);\n this.name = \"PGliteWorkerClosedError\";\n }\n}\n","/**\n * Wire protocol between a {@link ThreadedPGlite} stand-in on the main thread\n * and the worker thread that owns one PGlite store.\n *\n * Every payload is structured-cloned, so it holds data only: functions such as\n * row parsers are named by preset and built inside the worker.\n */\n\n/** Module specifiers the worker imports PGlite and its NodeFS from. */\nexport type PGliteModuleSpec = {\n /** Specifier or file URL of the PGlite package entry, e.g. `@electric-sql/pglite`. */\n pglite: string;\n /** Specifier or file URL of the matching NodeFS entry, e.g. `@electric-sql/pglite/nodefs`. */\n nodefs: string;\n};\n\nexport const CURRENT_PGLITE_MODULE: PGliteModuleSpec = {\n pglite: \"@electric-sql/pglite\",\n nodefs: \"@electric-sql/pglite/nodefs\",\n};\n\n/** Row parser sets the worker knows how to build. */\nexport type PGliteParserPreset = \"none\" | \"utc-timestamps\";\n\n/** DurableNodeFs settings; see `DurableNodeFsOptions`. */\nexport type PGliteWorkerDurableFsOptions = {\n fsync: boolean;\n /** Undefined keeps the DurableNodeFs default (5 min); 0 disables. */\n maintenanceIntervalMs?: number;\n /** Undefined keeps the DurableNodeFs default (256 MB); 0 disables. */\n vacuumFullAboveBytes?: number;\n /** Undefined keeps the DurableNodeFs default (60 s); 0 runs VACUUM FULL on the first pass. */\n vacuumFullQuietMs?: number;\n /** Undefined keeps the DurableNodeFs default (30 min); 0 waits for the quiet window only. */\n vacuumFullMaxDeferMs?: number;\n};\n\n/** What the worker opens. */\nexport type PGliteWorkerStoreOptions = {\n /** Names the store in logs and errors, e.g. `read-storage`. */\n label: string;\n /** PGlite data dir; null opens an in-memory store. */\n dataDir: string | null;\n module: PGliteModuleSpec;\n /** DurableNodeFs over `dataDir`; null uses the module's stock NodeFS. Ignored in memory. */\n durableFs: PGliteWorkerDurableFsOptions | null;\n parsers: PGliteParserPreset;\n};\n\n/** The structured-clonable subset of PGlite's `QueryOptions`. */\nexport type WorkerQueryOptions = {\n rowMode?: \"object\" | \"array\";\n paramTypes?: number[];\n};\n\nexport type PGliteErrorInfo = {\n name: string;\n message: string;\n stack?: string;\n cause?: PGliteErrorInfo;\n /** Postgres error fields, copied when present. */\n fields: Record<string, string>;\n};\n\nexport type WorkerResults = {\n rows: unknown[];\n affectedRows?: number;\n fields: { name: string; dataTypeID: number }[];\n};\n\nexport type InitRequest = {\n type: \"init\";\n id: number;\n store: PGliteWorkerStoreOptions;\n};\n\nexport type QueryRequest = {\n type: \"query\";\n id: number;\n /** The reservation this statement runs under, or null for the request queue. */\n admission: number | null;\n sql: string;\n params: unknown[];\n options: WorkerQueryOptions;\n};\n\nexport type ExecRequest = {\n type: \"exec\";\n id: number;\n admission: number | null;\n sql: string;\n options: WorkerQueryOptions;\n};\n\nexport type CloseRequest = {\n type: \"close\";\n id: number;\n};\n\n/**\n * Asks for the connection: answered with `admitted` once everything queued\n * ahead (requests and maintenance passes) has finished. Until the matching\n * `release`, the worker runs only statements tagged with this reservation.\n */\nexport type ReserveRequest = {\n type: \"reserve\";\n id: number;\n};\n\n/** Ends a reservation; the request queue resumes. Not answered. */\nexport type ReleaseRequest = {\n type: \"release\";\n id: number;\n};\n\nexport type HostMessage =\n | InitRequest\n | QueryRequest\n | ExecRequest\n | CloseRequest\n | ReserveRequest\n | ReleaseRequest;\n\nexport type AdmittedMessage = {\n type: \"admitted\";\n id: number;\n inTransaction: boolean;\n};\n\nexport type ReadyMessage = {\n type: \"ready\";\n id: number;\n inTransaction: boolean;\n};\n\nexport type QueryResultMessage = {\n type: \"query-result\";\n id: number;\n result: WorkerResults;\n inTransaction: boolean;\n};\n\nexport type ExecResultMessage = {\n type: \"exec-result\";\n id: number;\n results: WorkerResults[];\n inTransaction: boolean;\n};\n\nexport type ClosedMessage = {\n type: \"closed\";\n id: number;\n};\n\nexport type ErrorMessage = {\n type: \"error\";\n id: number;\n error: PGliteErrorInfo;\n inTransaction: boolean;\n};\n\n/** The wasm runtime aborted (a Postgres PANIC); the store is dead. */\nexport type AbortMessage = {\n type: \"abort\";\n reason: string;\n};\n\nexport type LogLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport type LogMessage = {\n type: \"log\";\n level: LogLevel;\n message: string;\n error?: PGliteErrorInfo;\n};\n\nexport type WorkerMessage =\n | AdmittedMessage\n | ReadyMessage\n | QueryResultMessage\n | ExecResultMessage\n | ClosedMessage\n | ErrorMessage\n | AbortMessage\n | LogMessage;\n","import type { QueryOptions, Results } from \"@electric-sql/pglite\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { existsSync } from \"node:fs\";\nimport { createRequire } from \"node:module\";\nimport { Worker, type ResourceLimits } from \"node:worker_threads\";\nimport type { PGliteLike } from \"../pglite-like.js\";\nimport { fromPGliteErrorInfo } from \"./error-info.js\";\nimport {\n PGliteWorkerClosedError,\n PGliteWorkerExitedError,\n PGliteWorkerInitError,\n} from \"./errors.js\";\nimport type {\n HostMessage,\n LogMessage,\n PGliteWorkerStoreOptions,\n WorkerMessage,\n WorkerQueryOptions,\n WorkerResults,\n} from \"./protocol.js\";\n\nexport const DEFAULT_PGLITE_WORKER_MEMORY_MB = 1024;\nexport const DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS = 60_000;\n\nexport type ThreadedPGliteOptions = {\n store: PGliteWorkerStoreOptions;\n /** Caps the worker's JS heap; defaults to {@link resolvePgliteWorkerMemoryMb}. WebAssembly memory is outside it. */\n memoryLimitMb?: number;\n /** The worker script; defaults to the built entry next to this module. Tests pass a tsx bootstrap. */\n workerScript?: string | URL;\n /** Bound on PGlite's own close (its shutdown checkpoint) before the thread is terminated. */\n closeGraceMs?: number;\n logger?: ILogger;\n};\n\n/** Called once, when the worker reports that the wasm runtime aborted. */\nexport type PGliteAbortListener = (reason: string) => void;\n\n/** Called once, when the worker thread is gone; `error` is null after a clean close. */\nexport type PGliteExitListener = (error: Error | null) => void;\n\ntype PendingKind = \"init\" | \"query\" | \"exec\" | \"close\" | \"reserve\";\n\ntype Pending = {\n kind: PendingKind;\n resolve: (value: unknown) => void;\n reject: (error: Error) => void;\n};\n\ntype Phase = \"starting\" | \"ready\" | \"closing\" | \"closed\";\n\n/** `PH_PGLITE_WORKER_MEMORY_MB`, else {@link DEFAULT_PGLITE_WORKER_MEMORY_MB}. */\nexport function resolvePgliteWorkerMemoryMb(\n env: Record<string, string | undefined>,\n): number {\n const raw = env.PH_PGLITE_WORKER_MEMORY_MB;\n if (raw === undefined || raw.trim() === \"\") {\n return DEFAULT_PGLITE_WORKER_MEMORY_MB;\n }\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed <= 0) {\n throw new Error(\n `PH_PGLITE_WORKER_MEMORY_MB must be a positive integer (got: ${raw})`,\n );\n }\n return parsed;\n}\n\n/**\n * Main-thread stand-in for a PGlite instance whose store lives in a worker\n * thread. It has the surface knex-pglite, kysely-pglite-dialect and\n * `HardenedPGliteDialect` use: `waitReady`, `query`, `exec`, a synchronous\n * `isInTransaction()`, `closed` and `close()`.\n *\n * Construction is synchronous and starts the worker; calls made before the\n * worker is ready are queued behind its open. The worker runs requests one at\n * a time in arrival order, and every answer carries the transaction status.\n * The instance is a plain extensible object, since knex stores its own\n * bookkeeping on the connection.\n */\nexport class ThreadedPGlite implements PGliteLike {\n readonly label: string;\n /** Settles once the worker has opened the store; rejects with {@link PGliteWorkerInitError}. */\n readonly waitReady: Promise<void>;\n\n private readonly worker: Worker;\n private readonly logger: ILogger;\n private readonly closeGraceMs: number;\n private readonly pending = new Map<number, Pending>();\n /** The reservation an `admit` run is executing under, carried through its async calls. */\n private readonly admission = new AsyncLocalStorage<number>();\n private readonly abortListeners = new Set<PGliteAbortListener>();\n private readonly exitListeners = new Set<PGliteExitListener>();\n private nextId = 1;\n private phase: Phase = \"starting\";\n private inTransaction = false;\n private terminalError: Error | null = null;\n private workerError: Error | null = null;\n private abortReason: string | null = null;\n private closePromise: Promise<void> | null = null;\n\n constructor(options: ThreadedPGliteOptions) {\n this.label = options.store.label;\n this.logger =\n options.logger ??\n childLogger([\"reactor-api\", \"pglite-worker\", this.label]);\n this.closeGraceMs =\n options.closeGraceMs ?? DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS;\n const memoryLimitMb =\n options.memoryLimitMb ?? resolvePgliteWorkerMemoryMb(process.env);\n\n const workerScript = options.workerScript ?? pgliteWorkerEntryPath;\n if (workerScript === null) {\n throw new Error(\n \"No PGlite worker script is available: build @powerhousedao/reactor-api or pass workerScript\",\n );\n }\n this.worker = new Worker(workerScript, {\n name: `pglite:${this.label}`,\n resourceLimits: { maxOldGenerationSizeMb: memoryLimitMb },\n });\n this.worker.on(\"message\", (msg: WorkerMessage) => this.handleMessage(msg));\n this.worker.on(\"error\", (err: Error) => this.handleWorkerError(err));\n this.worker.on(\"exit\", (code: number) => this.handleExit(code));\n\n this.waitReady = this.request<void>(\"init\", (id) => ({\n type: \"init\",\n id,\n store: options.store,\n })).then(\n () => {\n if (this.phase === \"starting\") {\n this.phase = \"ready\";\n }\n },\n (error: unknown) => {\n const initError =\n error instanceof PGliteWorkerInitError\n ? error\n : new PGliteWorkerInitError(this.label, { cause: error });\n this.fail(initError);\n throw initError;\n },\n );\n this.waitReady.catch(() => undefined);\n }\n\n /** True once the store is open and until close starts. */\n get ready(): boolean {\n return this.phase === \"ready\";\n }\n\n /** True once close has started or the worker is gone. */\n get closed(): boolean {\n return this.phase === \"closing\" || this.phase === \"closed\";\n }\n\n /** The reason the worker reported for a wasm abort, or null. */\n get aborted(): string | null {\n return this.abortReason;\n }\n\n /** The limits the worker thread runs under (empty once it has exited). */\n get resourceLimits(): ResourceLimits {\n return this.worker.resourceLimits ?? {};\n }\n\n /** The worker's thread id, for diagnostics. */\n get threadId(): number {\n return this.worker.threadId;\n }\n\n async query<T = Record<string, unknown>>(\n sql: string,\n params?: unknown[],\n options?: QueryOptions,\n ): Promise<Results<T>> {\n const wireOptions = toWireOptions(options);\n const result = await this.request<WorkerResults>(\"query\", (id) => ({\n type: \"query\",\n id,\n admission: this.currentAdmission(),\n sql,\n params: params ?? [],\n options: wireOptions,\n }));\n return toResults<T>(result);\n }\n\n async exec(sql: string, options?: QueryOptions): Promise<Results[]> {\n const wireOptions = toWireOptions(options);\n const results = await this.request<WorkerResults[]>(\"exec\", (id) => ({\n type: \"exec\",\n id,\n admission: this.currentAdmission(),\n sql,\n options: wireOptions,\n }));\n return results.map((result) => toResults(result));\n }\n\n /**\n * `HardenedPGliteDialect`'s admission hook: `run` starts only once the worker\n * can run its statements at once, with nothing queued ahead and no\n * maintenance pass in progress, so the dialect's statement deadline (which\n * starts inside `run`) never counts time spent waiting behind other work.\n * Statements `run` issues bypass the queue until it settles; everything\n * else waits behind them.\n */\n async admit<T>(run: () => Promise<T>): Promise<T> {\n let reservation = 0;\n await this.request<void>(\"reserve\", (id) => {\n reservation = id;\n return { type: \"reserve\", id };\n });\n try {\n return await this.admission.run(reservation, run);\n } finally {\n this.release(reservation);\n }\n }\n\n /** The status after the most recently answered request, as PGlite reported it. */\n isInTransaction(): boolean {\n return this.inTransaction;\n }\n\n /** Closes PGlite inside the worker (its shutdown checkpoint), then terminates the thread. */\n close(): Promise<void> {\n if (this.closePromise !== null) {\n return this.closePromise;\n }\n if (this.phase === \"closed\") {\n return Promise.resolve();\n }\n this.closePromise = this.closeWorker();\n return this.closePromise;\n }\n\n /** Stops the thread at once, without PGlite's close; pending calls reject. */\n async terminate(): Promise<void> {\n if (this.phase === \"closed\") {\n return;\n }\n await this.worker.terminate();\n }\n\n onAbort(listener: PGliteAbortListener): () => void {\n this.abortListeners.add(listener);\n return () => {\n this.abortListeners.delete(listener);\n };\n }\n\n onExit(listener: PGliteExitListener): () => void {\n this.exitListeners.add(listener);\n return () => {\n this.exitListeners.delete(listener);\n };\n }\n\n private async closeWorker(): Promise<void> {\n if (this.terminalError !== null) {\n this.phase = \"closing\";\n await this.worker.terminate();\n return;\n }\n const closing = this.request<void>(\"close\", (id) => ({\n type: \"close\",\n id,\n }));\n this.phase = \"closing\";\n let timer: ReturnType<typeof setTimeout> | undefined;\n const grace = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), this.closeGraceMs);\n });\n let outcome: \"closed\" | \"timeout\" = \"closed\";\n let closeError: Error | null = null;\n try {\n outcome = await Promise.race([\n closing.then(() => \"closed\" as const),\n grace,\n ]);\n } catch (error) {\n closeError = error instanceof Error ? error : new Error(String(error));\n } finally {\n clearTimeout(timer);\n }\n if (outcome === \"timeout\") {\n this.logger.warn(\n `PGlite worker for ${this.label} did not close within ${this.closeGraceMs}ms; terminating`,\n );\n }\n await this.worker.terminate();\n if (closeError !== null) {\n throw closeError;\n }\n }\n\n private currentAdmission(): number | null {\n return this.admission.getStore() ?? null;\n }\n\n private release(reservation: number): void {\n if (this.phase === \"closed\") {\n return;\n }\n const message: HostMessage = { type: \"release\", id: reservation };\n this.worker.postMessage(message);\n }\n\n private request<T>(\n kind: PendingKind,\n build: (id: number) => HostMessage,\n ): Promise<T> {\n if (this.terminalError !== null) {\n return Promise.reject(this.terminalError);\n }\n if (kind !== \"init\" && this.closed) {\n return Promise.reject(new PGliteWorkerClosedError(this.label));\n }\n const id = this.nextId++;\n const promise = new Promise<T>((resolve, reject) => {\n this.pending.set(id, {\n kind,\n resolve: resolve as (value: unknown) => void,\n reject,\n });\n });\n this.worker.postMessage(build(id));\n return promise;\n }\n\n private handleMessage(msg: WorkerMessage): void {\n switch (msg.type) {\n case \"admitted\":\n this.settle(msg.id, msg.inTransaction, undefined);\n return;\n case \"ready\":\n this.settle(msg.id, msg.inTransaction, undefined);\n return;\n case \"query-result\":\n this.settle(msg.id, msg.inTransaction, msg.result);\n return;\n case \"exec-result\":\n this.settle(msg.id, msg.inTransaction, msg.results);\n return;\n case \"closed\":\n this.settle(msg.id, false, undefined);\n return;\n case \"error\":\n this.settleError(\n msg.id,\n msg.inTransaction,\n fromPGliteErrorInfo(msg.error),\n );\n return;\n case \"abort\":\n this.handleAbort(msg.reason);\n return;\n case \"log\":\n this.handleLog(msg);\n return;\n default: {\n const exhaustive: never = msg;\n void exhaustive;\n }\n }\n }\n\n private settle(id: number, inTransaction: boolean, value: unknown): void {\n this.inTransaction = inTransaction;\n const entry = this.pending.get(id);\n if (entry === undefined) {\n return;\n }\n this.pending.delete(id);\n entry.resolve(value);\n }\n\n private settleError(id: number, inTransaction: boolean, error: Error): void {\n this.inTransaction = inTransaction;\n const entry = this.pending.get(id);\n if (entry === undefined) {\n return;\n }\n this.pending.delete(id);\n entry.reject(error);\n }\n\n private handleAbort(reason: string): void {\n if (this.abortReason !== null) {\n return;\n }\n this.abortReason = reason;\n this.logger.error(\n `PGlite worker for ${this.label} aborted: @reason`,\n reason,\n );\n for (const listener of [...this.abortListeners]) {\n try {\n listener(reason);\n } catch (error) {\n this.logger.error(\"PGlite abort listener threw: @error\", error);\n }\n }\n }\n\n private handleLog(msg: LogMessage): void {\n const message = `[${this.label}] ${msg.message}`;\n const args =\n msg.error === undefined ? [] : [fromPGliteErrorInfo(msg.error)];\n const template = args.length > 0 ? `${message}: @error` : message;\n switch (msg.level) {\n case \"debug\":\n this.logger.debug(template, ...args);\n return;\n case \"info\":\n this.logger.info(template, ...args);\n return;\n case \"warn\":\n this.logger.warn(template, ...args);\n return;\n case \"error\":\n this.logger.error(template, ...args);\n return;\n default: {\n const exhaustive: never = msg.level;\n void exhaustive;\n }\n }\n }\n\n private handleWorkerError(err: Error): void {\n this.workerError = err;\n this.logger.error(`PGlite worker for ${this.label} failed: @error`, err);\n }\n\n private handleExit(code: number): void {\n const graceful = this.phase === \"closing\" && this.terminalError === null;\n this.phase = \"closed\";\n this.inTransaction = false;\n const error = graceful\n ? null\n : (this.terminalError ??\n new PGliteWorkerExitedError(this.label, code, {\n cause: this.workerError ?? undefined,\n }));\n if (error !== null && this.terminalError === null) {\n this.terminalError = error;\n }\n this.rejectPending(error ?? new PGliteWorkerClosedError(this.label));\n for (const listener of [...this.exitListeners]) {\n try {\n listener(error);\n } catch (listenerError) {\n this.logger.error(\"PGlite exit listener threw: @error\", listenerError);\n }\n }\n this.exitListeners.clear();\n this.abortListeners.clear();\n }\n\n /** Records a fatal error and stops the thread; the exit rejects what is pending. */\n private fail(error: Error): void {\n if (this.terminalError === null) {\n this.terminalError = error;\n }\n this.rejectPending(error);\n void this.worker.terminate();\n }\n\n private rejectPending(error: Error): void {\n const entries = [...this.pending.values()];\n this.pending.clear();\n for (const entry of entries) {\n entry.reject(error);\n }\n }\n}\n\nfunction toWireOptions(options: QueryOptions | undefined): WorkerQueryOptions {\n if (options === undefined) {\n return {};\n }\n if (\n options.parsers !== undefined ||\n options.serializers !== undefined ||\n options.blob !== undefined ||\n options.onNotice !== undefined\n ) {\n throw new Error(\n \"ThreadedPGlite does not support parsers, serializers, blob or onNotice per query; configure parsers on the worker\",\n );\n }\n const wire: WorkerQueryOptions = {};\n if (options.rowMode !== undefined) {\n wire.rowMode = options.rowMode;\n }\n if (options.paramTypes !== undefined) {\n wire.paramTypes = options.paramTypes;\n }\n return wire;\n}\n\nfunction toResults<T>(result: WorkerResults): Results<T> {\n const out: Results<T> = {\n rows: result.rows as T[],\n fields: result.fields,\n };\n if (result.affectedRows !== undefined) {\n out.affectedRows = result.affectedRows;\n }\n return out;\n}\n\n/**\n * The worker script: the built entry (chunking may place this module in\n * `dist/` or `dist/src/pglite/`), or, when this module runs from its\n * TypeScript source, a bootstrap that loads the entry through tsx. Null when\n * neither is available.\n */\nfunction resolvePgliteWorkerEntryPath(): string | null {\n if (/\\.m?ts$/.test(new URL(import.meta.url).pathname)) {\n return resolveSourceBootstrap();\n }\n const candidates = [\n \"./src/pglite/worker/entry.mjs\",\n \"./worker/entry.mjs\",\n \"./entry.mjs\",\n ].map((relative) => fileUrlToPath(new URL(relative, import.meta.url)));\n return candidates.find((candidate) => existsSync(candidate)) ?? null;\n}\n\nfunction resolveSourceBootstrap(): string | null {\n const bootstrap = fileUrlToPath(\n new URL(\"./source-bootstrap.mjs\", import.meta.url),\n );\n if (!existsSync(bootstrap)) {\n return null;\n }\n try {\n createRequire(import.meta.url).resolve(\"tsx/esm/api\");\n } catch {\n return null;\n }\n return bootstrap;\n}\n\nfunction fileUrlToPath(url: URL): string {\n if (url.protocol !== \"file:\") {\n return url.href;\n }\n let pathname = decodeURIComponent(url.pathname);\n if (/^\\/[A-Za-z]:[/\\\\]/.test(pathname)) {\n pathname = pathname.slice(1);\n }\n return pathname;\n}\n\n/** Absolute path of the worker script for `new Worker(...)`; null when none can run here. */\nexport const pgliteWorkerEntryPath = resolvePgliteWorkerEntryPath();\n"],"names":["fs","fs","fs"],"mappings":";;;;;;;;;;;;AAMA,MAAa,qBAAqB;AAClC,MAAM,QAAQ,IAAI,WAAW;CAAC;CAAM;CAAM;CAAM;AAAI,CAAC;AACrD,MAAM,iBAAiB;AACvB,MAAM,cAAc;AACpB,MAAM,oBAAoB;AAC1B,MAAM,kCAAkB,IAAI,IAAI,CAAC,gBAAgB,CAAC;AAElD,MAAM,wBAAwB;;AAoB9B,eAAsB,gBACpB,cACA,QACA,UAAkC,CAAC,GACP;CAC5B,MAAM,KAAK,MAAMA,SAAG,KAAK,cAAc,GAAG;CAC1C,IAAI;EACF,MAAM,EAAE,SAAS,MAAM,GAAG,KAAK;EAC/B,OAAO,MAAM,kBAAkB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AAc,IAAI,IAAI,UAAU,YAAY,GAAG,CAAC,CACpD,CAAC,CAAC,MAAM,cAAc,WAAW,SAAS,CAAC,KAAK;AAClE;AAEA,SAAS,yBAAwC;CAC/C,MAAM,YAAY,cAChB,IAAI,IAAI,0BAA0B,YAAY,GAAG,CACnD;CACA,IAAI,CAAC,WAAW,SAAS,GACvB,OAAO;CAET,IAAI;EACF,cAAc,YAAY,GAAG,CAAC,CAAC,QAAQ,aAAa;CACtD,QAAQ;EACN,OAAO;CACT;CACA,OAAO;AACT;AAEA,SAAS,cAAc,KAAkB;CACvC,IAAI,IAAI,aAAa,SACnB,OAAO,IAAI;CAEb,IAAI,WAAW,mBAAmB,IAAI,QAAQ;CAC9C,IAAI,oBAAoB,KAAK,QAAQ,GACnC,WAAW,SAAS,MAAM,CAAC;CAE7B,OAAO;AACT;;AAGA,MAAa,wBAAwB,6BAA6B","debug_id":"f6b44ee1-02f4-57d0-aeea-150475095c5a"}
@@ -4,7 +4,7 @@ import { t as DOCUMENT_MODEL_SCHEMA_OWNER } from "../../subgraph-schema-owner-BE
4
4
  //#region src/graphql/subgraph-types.ts
5
5
  /** Loaded on call: the check pulls in the base models and core schemas. */
6
6
  async function findPackageSubgraphConflicts(subgraphs, documentModels) {
7
- const { checkPackageSubgraphs } = await import("../../package-subgraph-check-C0hGBt4N.mjs");
7
+ const { checkPackageSubgraphs } = await import("../../package-subgraph-check-C5S8yvBI.mjs");
8
8
  return checkPackageSubgraphs(subgraphs, documentModels);
9
9
  }
10
10
  //#endregion
@@ -35,6 +35,13 @@ export declare class VitePackageLoader implements ISubscribablePackageLoader {
35
35
  onProcessorsChange(identifier: string, handler: (processors: ProcessorFactoryBuilder | null) => void, options?: ISubscriptionOptions): () => void;
36
36
  onPiecesChange(identifier: string, handler: (pieces: PackagePieceEntry[]) => void, options?: ISubscriptionOptions): () => void;
37
37
  }
38
+ /**
39
+ * The project's build output, but for the built piece list `onPiecesChange`
40
+ * watches: its own `dist/` and a Tauri shell's Rust `target/`. On Windows
41
+ * every watched file costs a synchronous `fs.watch` at startup, over a
42
+ * minute for a built project with a built desktop shell.
43
+ */
44
+ export declare function ignoreBuildOutputButPieces(root: string): (file: string) => boolean;
38
45
  export declare function startViteServer(root: string, logger?: Logger): Promise<ViteDevServer>;
39
46
  //#endregion
40
47
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"vite-loader.d.mts","names":[],"sources":["../../../src/packages/vite-loader.mts"],"mappings":";;;;;;wBAqCgB,iBAAiB,QAAQ,SAAS,kBAAW;iBA2B5C;;;EAGf;EACA,cAAc;;qBAQH,6BAA6B;;mBACvB;mBAEA;mBAEA;WAIR;SAEF,MAAM,MAAM,eAAe,UAAU,2BAAwB;EAIpE,YAAY,MAAM,eAAe,UAAS;UA+DlC;UAIA;UAIA;UAIA;UAMA;UASA;EAcF,mBAAmB,qBAAqB,QAAQ;EAehD,qBACJ,qBACC,QAAQ;EAoBL,cAAc,qBAAqB,QAAQ;EAiB3C,eACJ,qBACC,QAAQ;EAkBL,WAAW,qBAAqB,QAAQ;EAmE9C,uBACE,oBACA,UAAU,gBAAgB,gCAC1B,UAAU;EAYZ,kBACE,oBACA,UAAU,WAAW,0BACrB,UAAU;EAYZ,mBACE,oBACA,UAAU,YAAY,yCACtB,UAAU;EAYZ,eACE,oBACA,UAAU,QAAQ,8BAClB,UAAU;;wBAmBQ,gBAAgB,cAAc,SAAS,SAAM,QAAA"}
1
+ {"version":3,"file":"vite-loader.d.mts","names":[],"sources":["../../../src/packages/vite-loader.mts"],"mappings":";;;;;;wBAqCgB,iBAAiB,QAAQ,SAAS,kBAAW;iBA2B5C;;;EAGf;EACA,cAAc;;qBAQH,6BAA6B;;mBACvB;mBAEA;mBAEA;WAIR;SAEF,MAAM,MAAM,eAAe,UAAU,2BAAwB;EAIpE,YAAY,MAAM,eAAe,UAAS;UA+DlC;UAIA;UAIA;UAIA;UAMA;UASA;EAcF,mBAAmB,qBAAqB,QAAQ;EAehD,qBACJ,qBACC,QAAQ;EAoBL,cAAc,qBAAqB,QAAQ;EAiB3C,eACJ,qBACC,QAAQ;EAkBL,WAAW,qBAAqB,QAAQ;EAmE9C,uBACE,oBACA,UAAU,gBAAgB,gCAC1B,UAAU;EAYZ,kBACE,oBACA,UAAU,WAAW,0BACrB,UAAU;EAYZ,mBACE,oBACA,UAAU,YAAY,yCACtB,UAAU;EAYZ,eACE,oBACA,UAAU,QAAQ,8BAClB,UAAU;;;;;;;;wBA2BE,2BAA2B,gBAAY;wBAqBjC,gBAAgB,cAAc,SAAS,SAAM,QAAA"}
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="87a12b3c-60f9-5bc0-9f40-3a611bc92434")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="90f792c4-97fb-52c4-91c3-8f6a5b0d178b")}catch(e){}}();
3
3
  import { _ as PACKAGE_MODULE_FAILED, a as packageRootOf, b as isSubpath, c as piecesFromListModule, g as runDetached, l as extractDocumentModels, n as BUILT_PIECE_LIST, o as pieceListLocation, r as PIECES_SUBPATH, t as extractSubgraphs, v as debounce, y as extractUpgradeManifests } from "../../subgraph-extraction-cSpPp3Hq.mjs";
4
4
  import { childLogger } from "document-model";
5
5
  import path from "node:path";
@@ -191,6 +191,23 @@ var VitePackageLoader = class VitePackageLoader {
191
191
  return this.#watch(`Reloading the pieces of ${identifier}`, (changedPath) => watched.some((dir) => isSubpath(dir, changedPath)), () => this.loadPieces(identifier), handler, options);
192
192
  }
193
193
  };
194
+ const toSlashes = (file) => file.replaceAll("\\", "/");
195
+ /**
196
+ * The project's build output, but for the built piece list `onPiecesChange`
197
+ * watches: its own `dist/` and a Tauri shell's Rust `target/`. On Windows
198
+ * every watched file costs a synchronous `fs.watch` at startup, over a
199
+ * minute for a built project with a built desktop shell.
200
+ */
201
+ function ignoreBuildOutputButPieces(root) {
202
+ const dist = `${toSlashes(path.resolve(root, "dist"))}/`;
203
+ const pieces = toSlashes(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));
204
+ return (file) => {
205
+ const at = toSlashes(path.resolve(root, file));
206
+ if (at.includes("/tauri-shell/target/") || at.includes("/src-tauri/target/")) return true;
207
+ if (!at.startsWith(dist)) return false;
208
+ return !(at === pieces || at.startsWith(`${pieces}/`) || pieces.startsWith(`${at}/`));
209
+ };
210
+ }
194
211
  async function startViteServer(root, logger) {
195
212
  const packageJson = await readPackage({ cwd: root });
196
213
  return await createServer({
@@ -200,7 +217,7 @@ async function startViteServer(root, logger) {
200
217
  server: {
201
218
  middlewareMode: true,
202
219
  hmr: false,
203
- watch: { ignored: ["**/.ph/**"] }
220
+ watch: { ignored: ["**/.ph/**", ignoreBuildOutputButPieces(root)] }
204
221
  },
205
222
  appType: "custom",
206
223
  cacheDir: path.join(root, "node_modules", ".vite-reactor"),
@@ -223,7 +240,7 @@ async function startViteServer(root, logger) {
223
240
  });
224
241
  }
225
242
  //#endregion
226
- export { VitePackageLoader, createViteLogger, startViteServer };
243
+ export { VitePackageLoader, createViteLogger, ignoreBuildOutputButPieces, startViteServer };
227
244
 
228
245
  //# sourceMappingURL=vite-loader.mjs.map
229
- //# debugId=87a12b3c-60f9-5bc0-9f40-3a611bc92434
246
+ //# debugId=90f792c4-97fb-52c4-91c3-8f6a5b0d178b
@@ -1 +1 @@
1
- {"version":3,"file":"vite-loader.mjs","sources":["../../../src/packages/vite-loader.mts"],"sourcesContent":["import { viteCommonjs } from \"@originjs/vite-plugin-commonjs\";\nimport type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { readPackage } from \"read-pkg\";\nimport type { Logger, PluginOption, ViteDevServer } from \"vite\";\nimport { createLogger, createServer } from \"vite\";\nimport { extractDocumentModels } from \"./document-model-detection.js\";\nimport { extractSubgraphs } from \"./subgraph-extraction.js\";\nimport {\n BUILT_PIECE_LIST,\n PIECES_SUBPATH,\n packageRootOf,\n pieceListLocation,\n piecesFromListModule,\n} from \"./pieces.js\";\nimport type {\n ISubscribablePackageLoader,\n ISubscriptionOptions,\n PackagePieceEntry,\n} from \"./types.js\";\nimport {\n PACKAGE_MODULE_FAILED,\n debounce,\n extractUpgradeManifests,\n isSubpath,\n} from \"./util.js\";\nimport { runDetached, type ReportError } from \"../utils/detached.js\";\n\nexport function createViteLogger(logger: ILogger, prefix = \"\") {\n const customLogger = createLogger(\"info\", {\n prefix,\n });\n // Wrapped rather than assigned: the logger methods are bound to their own\n // instance, and re-homing them onto Vite's logger object made every Vite\n // log line throw.\n //\n // Vite's text goes through as a replacement, never as the format string: it\n // is somebody else's prose, not a template. `ILogger` substitutes `@token`,\n // and Vite log lines are full of npm scopes, so `pre-transforming\n // @powerhousedao/design-system` came out as `pre-transforming\n // null/design-system`. Substituting into `@line` instead emits it verbatim.\n //\n // Vite's second argument is dropped for the same reason. It is `LogOptions`\n // -- `{ clear, timestamp }` -- and forwarding it made it the replacement for\n // whatever `@token` the line happened to contain, or got appended as JSON.\n // Only `error` keeps it, where it carries the error itself.\n customLogger.info = (msg) => logger.info(\"@line\", msg);\n customLogger.warn = (msg) => logger.warn(\"@line\", msg);\n customLogger.error = (msg, options) =>\n options?.error\n ? logger.error(\"@line\", msg, options.error)\n : logger.error(\"@line\", msg);\n return customLogger;\n}\n\nexport interface VitePackageLoaderOptions {\n /** Modules, as paths or file URLs, whose dependencies a package the project\n * does not install may resolve from. This loader's own module always is. */\n resolveFrom?: string[];\n reportError?: ReportError;\n}\n\ninterface LoadedModule {\n id: string;\n namespace: Record<string, unknown>;\n}\n\nexport class VitePackageLoader implements ISubscribablePackageLoader {\n private readonly logger = childLogger([\"reactor-api\", \"vite-loader\"]);\n\n private readonly vite: ViteDevServer;\n\n private readonly importers: string[];\n\n readonly #reportError?: ReportError;\n\n readonly name = \"VitePackageLoader\";\n\n static build(vite: ViteDevServer, options?: VitePackageLoaderOptions) {\n return new VitePackageLoader(vite, options);\n }\n\n constructor(vite: ViteDevServer, options: VitePackageLoaderOptions = {}) {\n this.vite = vite;\n this.importers = [...(options.resolveFrom ?? []), import.meta.url].map(\n (from) => (from.startsWith(\"file:\") ? fileURLToPath(from) : from),\n );\n this.#reportError = options.reportError;\n }\n\n // The project first, then the host's own dependencies. A bare name or a path\n // Vite cannot resolve is a package without that module, not an error.\n async #resolve(identifier: string, subpath: string) {\n const aliased = path.isAbsolute(identifier)\n ? undefined\n : this.aliasedRoot(identifier);\n const specifier = path.posix.join(aliased ?? identifier, subpath);\n const bare = !aliased && !path.isAbsolute(identifier);\n const importers = bare ? [undefined, ...this.importers] : [undefined];\n const container = this.vite.environments.ssr.pluginContainer;\n for (const importer of importers) {\n try {\n const resolved = await container.resolveId(specifier, importer);\n if (resolved && !resolved.external) return resolved.id;\n } catch (e) {\n this.logger.debug(\"Could not resolve @specifier: @error\", specifier, e);\n }\n }\n return undefined;\n }\n\n // Resolved before it is loaded, so only a module that exists and fails is\n // reported and thrown; one a package does not have is a debug-level miss.\n async #load(\n identifier: string,\n subpath: string,\n ): Promise<LoadedModule | undefined> {\n const id = await this.#resolve(identifier, subpath);\n if (id === undefined) {\n this.logger.debug(\"No @subpath module in @pkg\", subpath, identifier);\n return undefined;\n }\n try {\n const namespace = (await this.vite.ssrLoadModule(id)) as Record<\n string,\n unknown\n >;\n return { id, namespace };\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n this.logger.error(\n \"Failed to load @subpath of @pkg from @id: @error\",\n subpath,\n identifier,\n id,\n message,\n );\n // Tagged: vite's own code can read as a package without the module.\n throw Object.assign(\n new Error(`Failed to load ${id}: ${message}`, { cause: e }),\n { code: PACKAGE_MODULE_FAILED },\n );\n }\n }\n\n private getDocumentModelsPath(identifier: string): string {\n return path.posix.join(identifier, \"./document-models\");\n }\n\n private getSubgraphsPath(identifier: string): string {\n return path.posix.join(identifier, \"./subgraphs\");\n }\n\n private getProcessorsPath(identifier: string): string {\n return path.posix.join(identifier, \"./processors\");\n }\n\n private getPiecesPath(identifier: string): string {\n return path.posix.join(identifier, `./${PIECES_SUBPATH}`);\n }\n\n // The dev server aliases the local project by its own package name, so a\n // package that is this project is rooted at the source tree vite serves.\n private aliasedRoot(identifier: string): string | undefined {\n const alias = this.vite.config.resolve.alias;\n const entries = Array.isArray(alias) ? alias : [];\n const hit = entries.find((entry) => entry.find === identifier);\n return typeof hit?.replacement === \"string\" ? hit.replacement : undefined;\n }\n\n // What a declared piece path is relative to. Not the module vite loaded: a\n // list read from source still points at the built output beside it.\n private pieceRoot(identifier: string, listId?: string): string | undefined {\n if (!path.isAbsolute(identifier)) {\n const aliased = this.aliasedRoot(identifier);\n if (aliased) return aliased;\n // A built list resolved from wherever the package is installed.\n if (listId) return packageRootOf(path.dirname(listId));\n }\n try {\n return pieceListLocation(identifier).root;\n } catch {\n return undefined;\n }\n }\n\n async loadDocumentModels(identifier: string): Promise<DocumentModelModule[]> {\n this.logger.debug(\n \"Loading document models from\",\n this.getDocumentModelsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"document-models\");\n if (!loaded) return [];\n\n const documentModels = extractDocumentModels(loaded.namespace);\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`,\n );\n return documentModels;\n }\n\n async loadUpgradeManifests(\n identifier: string,\n ): Promise<UpgradeManifest<readonly number[]>[]> {\n // Projects generated before the aggregate index re-exported the\n // manifests only expose them at document-models/upgrade-manifests.\n for (const subpath of [\n \"document-models\",\n \"document-models/upgrade-manifests\",\n ]) {\n const loaded = await this.#load(identifier, subpath);\n if (!loaded) continue;\n const manifests = extractUpgradeManifests(loaded.namespace);\n if (manifests.length > 0) {\n this.logger.verbose(\n ` ➜ Loaded ${manifests.length} Upgrade Manifests from: ${identifier}`,\n );\n return manifests;\n }\n }\n return [];\n }\n\n async loadSubgraphs(identifier: string): Promise<SubgraphClass[]> {\n this.logger.verbose(\n \"Loading subgraphs from\",\n this.getSubgraphsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"subgraphs\");\n if (!loaded) return [];\n\n const subgraphs = extractSubgraphs(loaded.namespace);\n\n this.logger.debug(\n ` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`,\n );\n\n return subgraphs;\n }\n\n async loadProcessors(\n identifier: string,\n ): Promise<ProcessorFactoryBuilder | null> {\n this.logger.verbose(\n \"Loading processors from\",\n this.getProcessorsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"processors\");\n const factory = loaded?.namespace.processorFactory;\n if (typeof factory === \"function\") {\n this.logger.verbose(` ➜ Loaded Processor Factory from: ${identifier}`);\n return factory as ProcessorFactoryBuilder;\n }\n\n this.logger.verbose(` ➜ No Processor Factory found for: ${identifier}`);\n return null;\n }\n\n // The list only, never a piece: in dev it is usually the TypeScript source,\n // and what it names is still the built bundle a worker will load.\n async loadPieces(identifier: string): Promise<PackagePieceEntry[]> {\n this.logger.verbose(\"Loading pieces from\", this.getPiecesPath(identifier));\n const loaded = await this.#load(identifier, PIECES_SUBPATH);\n if (!loaded) return [];\n\n const root = this.pieceRoot(identifier, loaded.id);\n if (root === undefined) {\n this.logger.debug(` ➜ No package root found for: ${identifier}`);\n return [];\n }\n\n const pieces = piecesFromListModule(loaded.namespace, {\n root,\n identifier,\n logger: this.logger,\n });\n this.logger.debug(\n ` ➜ Loaded ${pieces.length} Pieces from: ${identifier}`,\n );\n return pieces;\n }\n\n // One detached reload per burst of file events. \"add\" and \"unlink\" too, or a\n // removed entry never reports empty and its registrations leak. Once\n // unsubscribed, no pending or running reload reaches `handler`, and a\n // failed load leaves the last good set.\n #watch<T>(\n label: string,\n matches: (changedPath: string) => unknown,\n load: () => Promise<T>,\n handler: (value: T) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n let subscribed = true;\n const reloadOnce = debounce(\n () =>\n runDetached(\n label,\n async () => {\n if (!subscribed) return;\n let value: T;\n try {\n value = await load();\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === PACKAGE_MODULE_FAILED) {\n return;\n }\n throw e;\n }\n if (subscribed) handler(value);\n },\n { logger: this.logger, report: this.#reportError },\n ),\n options?.debounce ?? 100,\n );\n const listener = (changedPath: string) => {\n if (matches(changedPath)) void reloadOnce();\n };\n const events = [\"change\", \"add\", \"unlink\"] as const;\n for (const event of events) this.vite.watcher.on(event, listener);\n\n return () => {\n subscribed = false;\n for (const event of events) this.vite.watcher.off(event, listener);\n };\n }\n\n onDocumentModelsChange(\n identifier: string,\n handler: (documentModels: DocumentModelModule[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const documentModelsPath = this.getDocumentModelsPath(identifier);\n return this.#watch(\n `Reloading the document models of ${identifier}`,\n (changedPath) => isSubpath(documentModelsPath, changedPath),\n () => this.loadDocumentModels(identifier),\n handler,\n options,\n );\n }\n\n onSubgraphsChange(\n identifier: string,\n handler: (subgraphs: SubgraphClass[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const subgraphsPath = this.getSubgraphsPath(identifier);\n return this.#watch(\n `Reloading the subgraphs of ${identifier}`,\n (changedPath) => isSubpath(subgraphsPath, changedPath),\n () => this.loadSubgraphs(identifier),\n handler,\n options,\n );\n }\n\n onProcessorsChange(\n identifier: string,\n handler: (processors: ProcessorFactoryBuilder | null) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const processorsPath = this.getProcessorsPath(identifier);\n return this.#watch(\n `Reloading the processors of ${identifier}`,\n (changedPath) => isSubpath(processorsPath, changedPath),\n () => this.loadProcessors(identifier),\n handler,\n options,\n );\n }\n\n onPiecesChange(\n identifier: string,\n handler: (pieces: PackagePieceEntry[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n // Both the source list and the build output: the list says which pieces a\n // package ships, and only the build decides whether one is there to run.\n const watched = [this.getPiecesPath(identifier)];\n const root = this.pieceRoot(identifier);\n if (root !== undefined) {\n watched.push(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));\n }\n return this.#watch(\n `Reloading the pieces of ${identifier}`,\n (changedPath) => watched.some((dir) => isSubpath(dir, changedPath)),\n () => this.loadPieces(identifier),\n handler,\n options,\n );\n }\n}\n\nexport async function startViteServer(root: string, logger?: Logger) {\n const packageJson = await readPackage({ cwd: root });\n\n const vite = await createServer({\n root,\n configFile: false,\n logger,\n server: {\n middlewareMode: true,\n // It loads modules, never serves a page: no HMR port to collide on.\n hmr: false,\n watch: { ignored: [\"**/.ph/**\"] },\n },\n appType: \"custom\",\n // Its own cache, and no client deps to optimize: Studio's cache is the\n // project's node_modules/.vite, which it would otherwise rewrite.\n cacheDir: path.join(root, \"node_modules\", \".vite-reactor\"),\n optimizeDeps: { noDiscovery: true, include: [], entries: [] },\n build: {\n rollupOptions: {\n input: [],\n },\n },\n resolve: {\n tsconfigPaths: true,\n alias: {\n [packageJson.name]: root,\n },\n },\n plugins: [\n // cast: the plugin ships types built against an older vite, and the\n // mismatched Plugin type crashes tsc 6 during assignability checking\n viteCommonjs() as PluginOption,\n {\n name: \"suppress-hmr\",\n handleHotUpdate() {\n return []; // return empty array to suppress server refresh\n },\n },\n ],\n });\n\n return vite;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAqCA,SAAgB,iBAAiB,QAAiB,SAAS,IAAI;CAC7D,MAAM,eAAe,aAAa,QAAQ,EACxC,OACF,CAAC;CAeD,aAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,GAAG;CACrD,aAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,GAAG;CACrD,aAAa,SAAS,KAAK,YACzB,SAAS,QACL,OAAO,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A,mBACE,YACA,SACA,SACY;EACZ,MAAM,iBAAiB,KAAK,kBAAkB,UAAU;EACxD,OAAO,KAAK,OACV,+BAA+B,eAC9B,gBAAgB,UAAU,gBAAgB,WAAW,SAChD,KAAK,eAAe,UAAU,GACpC,SACA,OACF;CACF;CAEA,eACE,YACA,SACA,SACY;EAGZ,MAAM,UAAU,CAAC,KAAK,cAAc,UAAU,CAAC;EAC/C,MAAM,OAAO,KAAK,UAAU,UAAU;EACtC,IAAI,SAAS,KAAA,GACX,QAAQ,KAAK,KAAK,QAAQ,KAAK,QAAQ,MAAM,gBAAgB,CAAC,CAAC;EAEjE,OAAO,KAAK,OACV,2BAA2B,eAC1B,gBAAgB,QAAQ,MAAM,QAAQ,UAAU,KAAK,WAAW,CAAC,SAC5D,KAAK,WAAW,UAAU,GAChC,SACA,OACF;CACF;AACF;AAEA,eAAsB,gBAAgB,MAAc,QAAiB;CACnE,MAAM,cAAc,MAAM,YAAY,EAAE,KAAK,KAAK,CAAC;CAyCnD,OAAO,MAvCY,aAAa;EAC9B;EACA,YAAY;EACZ;EACA,QAAQ;GACN,gBAAgB;GAEhB,KAAK;GACL,OAAO,EAAE,SAAS,CAAC,WAAW,EAAE;EAClC;EACA,SAAS;EAGT,UAAU,KAAK,KAAK,MAAM,gBAAgB,eAAe;EACzD,cAAc;GAAE,aAAa;GAAM,SAAS,CAAC;GAAG,SAAS,CAAC;EAAE;EAC5D,OAAO,EACL,eAAe,EACb,OAAO,CAAC,EACV,EACF;EACA,SAAS;GACP,eAAe;GACf,OAAO,GACJ,YAAY,OAAO,KACtB;EACF;EACA,SAAS,CAGP,aAAa,GACb;GACE,MAAM;GACN,kBAAkB;IAChB,OAAO,CAAC;GACV;EACF,CACF;CACF,CAAC;AAGH","debug_id":"87a12b3c-60f9-5bc0-9f40-3a611bc92434"}
1
+ {"version":3,"file":"vite-loader.mjs","sources":["../../../src/packages/vite-loader.mts"],"sourcesContent":["import { viteCommonjs } from \"@originjs/vite-plugin-commonjs\";\nimport type {\n ProcessorFactoryBuilder,\n SubgraphClass,\n} from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelModule,\n UpgradeManifest,\n} from \"@powerhousedao/shared/document-model\";\nimport { childLogger, type ILogger } from \"document-model\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { readPackage } from \"read-pkg\";\nimport type { Logger, PluginOption, ViteDevServer } from \"vite\";\nimport { createLogger, createServer } from \"vite\";\nimport { extractDocumentModels } from \"./document-model-detection.js\";\nimport { extractSubgraphs } from \"./subgraph-extraction.js\";\nimport {\n BUILT_PIECE_LIST,\n PIECES_SUBPATH,\n packageRootOf,\n pieceListLocation,\n piecesFromListModule,\n} from \"./pieces.js\";\nimport type {\n ISubscribablePackageLoader,\n ISubscriptionOptions,\n PackagePieceEntry,\n} from \"./types.js\";\nimport {\n PACKAGE_MODULE_FAILED,\n debounce,\n extractUpgradeManifests,\n isSubpath,\n} from \"./util.js\";\nimport { runDetached, type ReportError } from \"../utils/detached.js\";\n\nexport function createViteLogger(logger: ILogger, prefix = \"\") {\n const customLogger = createLogger(\"info\", {\n prefix,\n });\n // Wrapped rather than assigned: the logger methods are bound to their own\n // instance, and re-homing them onto Vite's logger object made every Vite\n // log line throw.\n //\n // Vite's text goes through as a replacement, never as the format string: it\n // is somebody else's prose, not a template. `ILogger` substitutes `@token`,\n // and Vite log lines are full of npm scopes, so `pre-transforming\n // @powerhousedao/design-system` came out as `pre-transforming\n // null/design-system`. Substituting into `@line` instead emits it verbatim.\n //\n // Vite's second argument is dropped for the same reason. It is `LogOptions`\n // -- `{ clear, timestamp }` -- and forwarding it made it the replacement for\n // whatever `@token` the line happened to contain, or got appended as JSON.\n // Only `error` keeps it, where it carries the error itself.\n customLogger.info = (msg) => logger.info(\"@line\", msg);\n customLogger.warn = (msg) => logger.warn(\"@line\", msg);\n customLogger.error = (msg, options) =>\n options?.error\n ? logger.error(\"@line\", msg, options.error)\n : logger.error(\"@line\", msg);\n return customLogger;\n}\n\nexport interface VitePackageLoaderOptions {\n /** Modules, as paths or file URLs, whose dependencies a package the project\n * does not install may resolve from. This loader's own module always is. */\n resolveFrom?: string[];\n reportError?: ReportError;\n}\n\ninterface LoadedModule {\n id: string;\n namespace: Record<string, unknown>;\n}\n\nexport class VitePackageLoader implements ISubscribablePackageLoader {\n private readonly logger = childLogger([\"reactor-api\", \"vite-loader\"]);\n\n private readonly vite: ViteDevServer;\n\n private readonly importers: string[];\n\n readonly #reportError?: ReportError;\n\n readonly name = \"VitePackageLoader\";\n\n static build(vite: ViteDevServer, options?: VitePackageLoaderOptions) {\n return new VitePackageLoader(vite, options);\n }\n\n constructor(vite: ViteDevServer, options: VitePackageLoaderOptions = {}) {\n this.vite = vite;\n this.importers = [...(options.resolveFrom ?? []), import.meta.url].map(\n (from) => (from.startsWith(\"file:\") ? fileURLToPath(from) : from),\n );\n this.#reportError = options.reportError;\n }\n\n // The project first, then the host's own dependencies. A bare name or a path\n // Vite cannot resolve is a package without that module, not an error.\n async #resolve(identifier: string, subpath: string) {\n const aliased = path.isAbsolute(identifier)\n ? undefined\n : this.aliasedRoot(identifier);\n const specifier = path.posix.join(aliased ?? identifier, subpath);\n const bare = !aliased && !path.isAbsolute(identifier);\n const importers = bare ? [undefined, ...this.importers] : [undefined];\n const container = this.vite.environments.ssr.pluginContainer;\n for (const importer of importers) {\n try {\n const resolved = await container.resolveId(specifier, importer);\n if (resolved && !resolved.external) return resolved.id;\n } catch (e) {\n this.logger.debug(\"Could not resolve @specifier: @error\", specifier, e);\n }\n }\n return undefined;\n }\n\n // Resolved before it is loaded, so only a module that exists and fails is\n // reported and thrown; one a package does not have is a debug-level miss.\n async #load(\n identifier: string,\n subpath: string,\n ): Promise<LoadedModule | undefined> {\n const id = await this.#resolve(identifier, subpath);\n if (id === undefined) {\n this.logger.debug(\"No @subpath module in @pkg\", subpath, identifier);\n return undefined;\n }\n try {\n const namespace = (await this.vite.ssrLoadModule(id)) as Record<\n string,\n unknown\n >;\n return { id, namespace };\n } catch (e) {\n const message = e instanceof Error ? e.message : String(e);\n this.logger.error(\n \"Failed to load @subpath of @pkg from @id: @error\",\n subpath,\n identifier,\n id,\n message,\n );\n // Tagged: vite's own code can read as a package without the module.\n throw Object.assign(\n new Error(`Failed to load ${id}: ${message}`, { cause: e }),\n { code: PACKAGE_MODULE_FAILED },\n );\n }\n }\n\n private getDocumentModelsPath(identifier: string): string {\n return path.posix.join(identifier, \"./document-models\");\n }\n\n private getSubgraphsPath(identifier: string): string {\n return path.posix.join(identifier, \"./subgraphs\");\n }\n\n private getProcessorsPath(identifier: string): string {\n return path.posix.join(identifier, \"./processors\");\n }\n\n private getPiecesPath(identifier: string): string {\n return path.posix.join(identifier, `./${PIECES_SUBPATH}`);\n }\n\n // The dev server aliases the local project by its own package name, so a\n // package that is this project is rooted at the source tree vite serves.\n private aliasedRoot(identifier: string): string | undefined {\n const alias = this.vite.config.resolve.alias;\n const entries = Array.isArray(alias) ? alias : [];\n const hit = entries.find((entry) => entry.find === identifier);\n return typeof hit?.replacement === \"string\" ? hit.replacement : undefined;\n }\n\n // What a declared piece path is relative to. Not the module vite loaded: a\n // list read from source still points at the built output beside it.\n private pieceRoot(identifier: string, listId?: string): string | undefined {\n if (!path.isAbsolute(identifier)) {\n const aliased = this.aliasedRoot(identifier);\n if (aliased) return aliased;\n // A built list resolved from wherever the package is installed.\n if (listId) return packageRootOf(path.dirname(listId));\n }\n try {\n return pieceListLocation(identifier).root;\n } catch {\n return undefined;\n }\n }\n\n async loadDocumentModels(identifier: string): Promise<DocumentModelModule[]> {\n this.logger.debug(\n \"Loading document models from\",\n this.getDocumentModelsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"document-models\");\n if (!loaded) return [];\n\n const documentModels = extractDocumentModels(loaded.namespace);\n this.logger.verbose(\n ` ➜ Loaded ${documentModels.length} Document Models from: ${identifier}`,\n );\n return documentModels;\n }\n\n async loadUpgradeManifests(\n identifier: string,\n ): Promise<UpgradeManifest<readonly number[]>[]> {\n // Projects generated before the aggregate index re-exported the\n // manifests only expose them at document-models/upgrade-manifests.\n for (const subpath of [\n \"document-models\",\n \"document-models/upgrade-manifests\",\n ]) {\n const loaded = await this.#load(identifier, subpath);\n if (!loaded) continue;\n const manifests = extractUpgradeManifests(loaded.namespace);\n if (manifests.length > 0) {\n this.logger.verbose(\n ` ➜ Loaded ${manifests.length} Upgrade Manifests from: ${identifier}`,\n );\n return manifests;\n }\n }\n return [];\n }\n\n async loadSubgraphs(identifier: string): Promise<SubgraphClass[]> {\n this.logger.verbose(\n \"Loading subgraphs from\",\n this.getSubgraphsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"subgraphs\");\n if (!loaded) return [];\n\n const subgraphs = extractSubgraphs(loaded.namespace);\n\n this.logger.debug(\n ` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`,\n );\n\n return subgraphs;\n }\n\n async loadProcessors(\n identifier: string,\n ): Promise<ProcessorFactoryBuilder | null> {\n this.logger.verbose(\n \"Loading processors from\",\n this.getProcessorsPath(identifier),\n );\n const loaded = await this.#load(identifier, \"processors\");\n const factory = loaded?.namespace.processorFactory;\n if (typeof factory === \"function\") {\n this.logger.verbose(` ➜ Loaded Processor Factory from: ${identifier}`);\n return factory as ProcessorFactoryBuilder;\n }\n\n this.logger.verbose(` ➜ No Processor Factory found for: ${identifier}`);\n return null;\n }\n\n // The list only, never a piece: in dev it is usually the TypeScript source,\n // and what it names is still the built bundle a worker will load.\n async loadPieces(identifier: string): Promise<PackagePieceEntry[]> {\n this.logger.verbose(\"Loading pieces from\", this.getPiecesPath(identifier));\n const loaded = await this.#load(identifier, PIECES_SUBPATH);\n if (!loaded) return [];\n\n const root = this.pieceRoot(identifier, loaded.id);\n if (root === undefined) {\n this.logger.debug(` ➜ No package root found for: ${identifier}`);\n return [];\n }\n\n const pieces = piecesFromListModule(loaded.namespace, {\n root,\n identifier,\n logger: this.logger,\n });\n this.logger.debug(\n ` ➜ Loaded ${pieces.length} Pieces from: ${identifier}`,\n );\n return pieces;\n }\n\n // One detached reload per burst of file events. \"add\" and \"unlink\" too, or a\n // removed entry never reports empty and its registrations leak. Once\n // unsubscribed, no pending or running reload reaches `handler`, and a\n // failed load leaves the last good set.\n #watch<T>(\n label: string,\n matches: (changedPath: string) => unknown,\n load: () => Promise<T>,\n handler: (value: T) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n let subscribed = true;\n const reloadOnce = debounce(\n () =>\n runDetached(\n label,\n async () => {\n if (!subscribed) return;\n let value: T;\n try {\n value = await load();\n } catch (e) {\n if ((e as NodeJS.ErrnoException).code === PACKAGE_MODULE_FAILED) {\n return;\n }\n throw e;\n }\n if (subscribed) handler(value);\n },\n { logger: this.logger, report: this.#reportError },\n ),\n options?.debounce ?? 100,\n );\n const listener = (changedPath: string) => {\n if (matches(changedPath)) void reloadOnce();\n };\n const events = [\"change\", \"add\", \"unlink\"] as const;\n for (const event of events) this.vite.watcher.on(event, listener);\n\n return () => {\n subscribed = false;\n for (const event of events) this.vite.watcher.off(event, listener);\n };\n }\n\n onDocumentModelsChange(\n identifier: string,\n handler: (documentModels: DocumentModelModule[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const documentModelsPath = this.getDocumentModelsPath(identifier);\n return this.#watch(\n `Reloading the document models of ${identifier}`,\n (changedPath) => isSubpath(documentModelsPath, changedPath),\n () => this.loadDocumentModels(identifier),\n handler,\n options,\n );\n }\n\n onSubgraphsChange(\n identifier: string,\n handler: (subgraphs: SubgraphClass[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const subgraphsPath = this.getSubgraphsPath(identifier);\n return this.#watch(\n `Reloading the subgraphs of ${identifier}`,\n (changedPath) => isSubpath(subgraphsPath, changedPath),\n () => this.loadSubgraphs(identifier),\n handler,\n options,\n );\n }\n\n onProcessorsChange(\n identifier: string,\n handler: (processors: ProcessorFactoryBuilder | null) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n const processorsPath = this.getProcessorsPath(identifier);\n return this.#watch(\n `Reloading the processors of ${identifier}`,\n (changedPath) => isSubpath(processorsPath, changedPath),\n () => this.loadProcessors(identifier),\n handler,\n options,\n );\n }\n\n onPiecesChange(\n identifier: string,\n handler: (pieces: PackagePieceEntry[]) => void,\n options?: ISubscriptionOptions,\n ): () => void {\n // Both the source list and the build output: the list says which pieces a\n // package ships, and only the build decides whether one is there to run.\n const watched = [this.getPiecesPath(identifier)];\n const root = this.pieceRoot(identifier);\n if (root !== undefined) {\n watched.push(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));\n }\n return this.#watch(\n `Reloading the pieces of ${identifier}`,\n (changedPath) => watched.some((dir) => isSubpath(dir, changedPath)),\n () => this.loadPieces(identifier),\n handler,\n options,\n );\n }\n}\n\nconst toSlashes = (file: string) => file.replaceAll(\"\\\\\", \"/\");\n\n/**\n * The project's build output, but for the built piece list `onPiecesChange`\n * watches: its own `dist/` and a Tauri shell's Rust `target/`. On Windows\n * every watched file costs a synchronous `fs.watch` at startup, over a\n * minute for a built project with a built desktop shell.\n */\nexport function ignoreBuildOutputButPieces(root: string) {\n const dist = `${toSlashes(path.resolve(root, \"dist\"))}/`;\n const pieces = toSlashes(path.dirname(path.resolve(root, BUILT_PIECE_LIST)));\n return (file: string) => {\n const at = toSlashes(path.resolve(root, file));\n if (\n at.includes(\"/tauri-shell/target/\") ||\n at.includes(\"/src-tauri/target/\")\n ) {\n return true;\n }\n if (!at.startsWith(dist)) return false;\n // The piece list's folder, what is in it, and the folders leading to it stay watched.\n return !(\n at === pieces ||\n at.startsWith(`${pieces}/`) ||\n pieces.startsWith(`${at}/`)\n );\n };\n}\n\nexport async function startViteServer(root: string, logger?: Logger) {\n const packageJson = await readPackage({ cwd: root });\n\n const vite = await createServer({\n root,\n configFile: false,\n logger,\n server: {\n middlewareMode: true,\n // It loads modules, never serves a page: no HMR port to collide on.\n hmr: false,\n watch: { ignored: [\"**/.ph/**\", ignoreBuildOutputButPieces(root)] },\n },\n appType: \"custom\",\n // Its own cache, and no client deps to optimize: Studio's cache is the\n // project's node_modules/.vite, which it would otherwise rewrite.\n cacheDir: path.join(root, \"node_modules\", \".vite-reactor\"),\n optimizeDeps: { noDiscovery: true, include: [], entries: [] },\n build: {\n rollupOptions: {\n input: [],\n },\n },\n resolve: {\n tsconfigPaths: true,\n alias: {\n [packageJson.name]: root,\n },\n },\n plugins: [\n // cast: the plugin ships types built against an older vite, and the\n // mismatched Plugin type crashes tsc 6 during assignability checking\n viteCommonjs() as PluginOption,\n {\n name: \"suppress-hmr\",\n handleHotUpdate() {\n return []; // return empty array to suppress server refresh\n },\n },\n ],\n });\n\n return vite;\n}\n"],"names":[],"mappings":";;;;;;;;;;AAqCA,SAAgB,iBAAiB,QAAiB,SAAS,IAAI;CAC7D,MAAM,eAAe,aAAa,QAAQ,EACxC,OACF,CAAC;CAeD,aAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,GAAG;CACrD,aAAa,QAAQ,QAAQ,OAAO,KAAK,SAAS,GAAG;CACrD,aAAa,SAAS,KAAK,YACzB,SAAS,QACL,OAAO,MAAM,SAAS,KAAK,QAAQ,KAAK,IACxC,OAAO,MAAM,SAAS,GAAG;CAC/B,OAAO;AACT;AAcA,IAAa,oBAAb,MAAa,kBAAwD;CACnE,SAA0B,YAAY,CAAC,eAAe,aAAa,CAAC;CAEpE;CAEA;CAEA;CAEA,OAAgB;CAEhB,OAAO,MAAM,MAAqB,SAAoC;EACpE,OAAO,IAAI,kBAAkB,MAAM,OAAO;CAC5C;CAEA,YAAY,MAAqB,UAAoC,CAAC,GAAG;EACvE,KAAK,OAAO;EACZ,KAAK,YAAY,CAAC,GAAI,QAAQ,eAAe,CAAC,GAAI,YAAY,GAAG,CAAC,CAAC,KAChE,SAAU,KAAK,WAAW,OAAO,IAAI,cAAc,IAAI,IAAI,IAC9D;EACA,KAAK,eAAe,QAAQ;CAC9B;CAIA,MAAM,SAAS,YAAoB,SAAiB;EAClD,MAAM,UAAU,KAAK,WAAW,UAAU,IACtC,KAAA,IACA,KAA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7D,SAAgB,2BAA2B,MAAc;CACvD,MAAM,OAAO,GAAG,UAAU,KAAK,QAAQ,MAAM,MAAM,CAAC,EAAE;CACtD,MAAM,SAAS,UAAU,KAAK,QAAQ,KAAK,QAAQ,MAAM,gBAAgB,CAAC,CAAC;CAC3E,QAAQ,SAAiB;EACvB,MAAM,KAAK,UAAU,KAAK,QAAQ,MAAM,IAAI,CAAC;EAC7C,IACE,GAAG,SAAS,sBAAsB,KAClC,GAAG,SAAS,oBAAoB,GAEhC,OAAO;EAET,IAAI,CAAC,GAAG,WAAW,IAAI,GAAG,OAAO;EAEjC,OAAO,EACL,OAAO,UACP,GAAG,WAAW,GAAG,OAAO,EAAE,KAC1B,OAAO,WAAW,GAAG,GAAG,EAAE;CAE9B;AACF;AAEA,eAAsB,gBAAgB,MAAc,QAAiB;CACnE,MAAM,cAAc,MAAM,YAAY,EAAE,KAAK,KAAK,CAAC;CAyCnD,OAAO,MAvCY,aAAa;EAC9B;EACA,YAAY;EACZ;EACA,QAAQ;GACN,gBAAgB;GAEhB,KAAK;GACL,OAAO,EAAE,SAAS,CAAC,aAAa,2BAA2B,IAAI,CAAC,EAAE;EACpE;EACA,SAAS;EAGT,UAAU,KAAK,KAAK,MAAM,gBAAgB,eAAe;EACzD,cAAc;GAAE,aAAa;GAAM,SAAS,CAAC;GAAG,SAAS,CAAC;EAAE;EAC5D,OAAO,EACL,eAAe,EACb,OAAO,CAAC,EACV,EACF;EACA,SAAS;GACP,eAAe;GACf,OAAO,GACJ,YAAY,OAAO,KACtB;EACF;EACA,SAAS,CAGP,aAAa,GACb;GACE,MAAM;GACN,kBAAkB;IAChB,OAAO,CAAC;GACV;EACF,CACF;CACF,CAAC;AAGH","debug_id":"90f792c4-97fb-52c4-91c3-8f6a5b0d178b"}
@@ -1,25 +1,55 @@
1
+ import { n as PGLITE_UTC_PARSERS, t as PGliteLike } from "../../pglite-like-CKQEL_Q0.mjs";
1
2
  import { ILogger } from "document-model";
2
3
  import nodeFs from "node:fs";
3
- import { PGlite } from "@electric-sql/pglite";
4
+ import { PGlite, QueryOptions, Results } from "@electric-sql/pglite";
4
5
  import { NodeFS } from "@electric-sql/pglite/nodefs";
6
+ import { ResourceLimits } from "node:worker_threads";
5
7
  //#region src/pglite/maintenance.d.ts
6
8
  export declare const DEFAULT_MAINTENANCE_INTERVAL_MS: number;
7
9
  export declare const DEFAULT_VACUUM_FULL_ABOVE_BYTES: number;
10
+ export declare const DEFAULT_VACUUM_FULL_QUIET_MS: number;
8
11
  type MaintenanceOutcome = "vacuum" | "vacuum-full" | "idle" | "not-ready" | "in-transaction" | "failed";
9
12
  interface MaintenanceLogger {
10
13
  warn(message: string): void;
11
14
  }
15
+ /** Runs a maintenance pass in the owner's turn; see {@link MaintenanceOptions.gate}. */
16
+ type MaintenanceGate = <T>(task: () => Promise<T>) => Promise<T>;
12
17
  interface MaintenanceOptions {
13
18
  /** VACUUM + CHECKPOINT cadence; PGlite has no autovacuum. Default 5 min; 0 disables. */
14
19
  intervalMs?: number;
15
20
  /** First pass runs VACUUM FULL when `base/` exceeds this at open. Default 256 MB; 0 disables. */
16
21
  vacuumFullAboveBytes?: number;
22
+ /**
23
+ * VACUUM FULL holds the store for minutes on a large dir, so it waits for a
24
+ * store with no synced statement (no write, no catch-up) for this long,
25
+ * counted from open; until then a pass runs plain VACUUM and keeps the
26
+ * VACUUM FULL pending. Default 60 s; 0 runs it on the first pass.
27
+ */
28
+ vacuumFullQuietMs?: number;
29
+ /**
30
+ * The longest a pending VACUUM FULL waits for that quiet window, counted
31
+ * from open; past it the next pass runs VACUUM FULL anyway. Default 30 min;
32
+ * 0 waits for the quiet window however long it takes.
33
+ */
34
+ vacuumFullMaxDeferMs?: number;
35
+ /**
36
+ * Queues each pass with the store's other work, e.g. behind a worker's
37
+ * pending requests, so a pass never starts ahead of a statement already
38
+ * admitted. A pass still waiting here when the store closes is skipped.
39
+ */
40
+ gate?: MaintenanceGate;
17
41
  logger?: MaintenanceLogger;
42
+ /** Clock for the quiet window; tests pass their own. */
43
+ now?: () => number;
18
44
  }
19
45
  export declare class PgliteMaintenance {
20
46
  private readonly intervalMs;
21
47
  private readonly vacuumFullAboveBytes;
48
+ private readonly vacuumFullQuietMs;
49
+ private readonly vacuumFullMaxDeferMs;
50
+ private readonly gate?;
22
51
  private readonly logger?;
52
+ private readonly now;
23
53
  private pg?;
24
54
  private label;
25
55
  private closing;
@@ -27,13 +57,20 @@ export declare class PgliteMaintenance {
27
57
  private vacuumFullPending;
28
58
  private timer?;
29
59
  private inFlight?;
60
+ private active;
61
+ private deferralLogged;
62
+ private lastSyncAt;
63
+ private openedAt;
30
64
  constructor(options?: MaintenanceOptions);
31
65
  get scheduled(): boolean;
32
66
  get running(): boolean;
33
67
  start(pg: PGlite, label: string, baseBytes: number): void;
34
68
  noteSync(): void;
69
+ /** Waits for a pass that has started; one still queued at the gate is left to skip itself. */
35
70
  stop(): Promise<void>;
36
71
  run(): Promise<MaintenanceOutcome>;
72
+ private runNow;
73
+ private pass;
37
74
  private schedule;
38
75
  private cancel;
39
76
  }
@@ -47,6 +84,14 @@ interface DurableNodeFsOptions {
47
84
  maintenanceIntervalMs?: number;
48
85
  /** `base/` size at open; default 256 MB; 0 disables. */
49
86
  vacuumFullAboveBytes?: number;
87
+ /** See `MaintenanceOptions.vacuumFullQuietMs`; default 60 s. */
88
+ vacuumFullQuietMs?: number;
89
+ /** See `MaintenanceOptions.vacuumFullMaxDeferMs`; default 30 min. */
90
+ vacuumFullMaxDeferMs?: number;
91
+ /** See `MaintenanceOptions.gate`. */
92
+ maintenanceGate?: MaintenanceGate;
93
+ /** Clock for the maintenance quiet window; tests pass their own. */
94
+ now?: () => number;
50
95
  logger?: {
51
96
  warn(message: string): void;
52
97
  };
@@ -125,6 +170,186 @@ export declare function preparePgliteDataDir(dir: string, deps: ConversionDeps):
125
170
  /** PGlite leaves `postmaster.pid` after every close and `pg_wal/xlogtemp.*` after some. */
126
171
  export declare function removeStalePgliteFiles(dir: string, logger: Pick<ILogger, "debug">): Promise<void>;
127
172
  //#endregion
128
- export type { ConversionDeps, ConversionStep, DurableNodeFs, DurableNodeFsOptions, ExtractSnapshotOptions, ExtractedSnapshot, MaintenanceLogger, MaintenanceOptions, MaintenanceOutcome, NodeFsClass, SyncTreeHostFs, SyncTreeResult, VerifyHandle };
173
+ //#region src/pglite/worker/protocol.d.ts
174
+ /**
175
+ * Wire protocol between a {@link ThreadedPGlite} stand-in on the main thread
176
+ * and the worker thread that owns one PGlite store.
177
+ *
178
+ * Every payload is structured-cloned, so it holds data only: functions such as
179
+ * row parsers are named by preset and built inside the worker.
180
+ */
181
+ /** Module specifiers the worker imports PGlite and its NodeFS from. */
182
+ type PGliteModuleSpec = {
183
+ /** Specifier or file URL of the PGlite package entry, e.g. `@electric-sql/pglite`. */
184
+ pglite: string;
185
+ /** Specifier or file URL of the matching NodeFS entry, e.g. `@electric-sql/pglite/nodefs`. */
186
+ nodefs: string;
187
+ };
188
+ export declare const CURRENT_PGLITE_MODULE: PGliteModuleSpec;
189
+ /** Row parser sets the worker knows how to build. */
190
+ type PGliteParserPreset = "none" | "utc-timestamps";
191
+ /** DurableNodeFs settings; see `DurableNodeFsOptions`. */
192
+ type PGliteWorkerDurableFsOptions = {
193
+ fsync: boolean;
194
+ /** Undefined keeps the DurableNodeFs default (5 min); 0 disables. */
195
+ maintenanceIntervalMs?: number;
196
+ /** Undefined keeps the DurableNodeFs default (256 MB); 0 disables. */
197
+ vacuumFullAboveBytes?: number;
198
+ /** Undefined keeps the DurableNodeFs default (60 s); 0 runs VACUUM FULL on the first pass. */
199
+ vacuumFullQuietMs?: number;
200
+ /** Undefined keeps the DurableNodeFs default (30 min); 0 waits for the quiet window only. */
201
+ vacuumFullMaxDeferMs?: number;
202
+ };
203
+ /** What the worker opens. */
204
+ type PGliteWorkerStoreOptions = {
205
+ /** Names the store in logs and errors, e.g. `read-storage`. */
206
+ label: string;
207
+ /** PGlite data dir; null opens an in-memory store. */
208
+ dataDir: string | null;
209
+ module: PGliteModuleSpec;
210
+ /** DurableNodeFs over `dataDir`; null uses the module's stock NodeFS. Ignored in memory. */
211
+ durableFs: PGliteWorkerDurableFsOptions | null;
212
+ parsers: PGliteParserPreset;
213
+ };
214
+ type PGliteErrorInfo = {
215
+ name: string;
216
+ message: string;
217
+ stack?: string;
218
+ cause?: PGliteErrorInfo;
219
+ /** Postgres error fields, copied when present. */
220
+ fields: Record<string, string>;
221
+ };
222
+ //#endregion
223
+ //#region src/pglite/worker/error-info.d.ts
224
+ /** Flattens an error and its cause chain into a structured-clonable shape. */
225
+ export declare function toPGliteErrorInfo(err: unknown, depth?: number): PGliteErrorInfo;
226
+ /** Rebuilds an `Error` carrying the original name, stack, Postgres fields and cause chain. */
227
+ export declare function fromPGliteErrorInfo(info: PGliteErrorInfo): Error;
228
+ //#endregion
229
+ //#region src/pglite/worker/errors.d.ts
230
+ /** Base class for failures of the worker itself, as opposed to SQL errors. */
231
+ export declare class PGliteWorkerError extends Error {
232
+ readonly label: string;
233
+ constructor(label: string, message: string, options?: {
234
+ cause?: unknown;
235
+ });
236
+ }
237
+ /** The worker could not open its store; every call on the stand-in fails with this. */
238
+ export declare class PGliteWorkerInitError extends PGliteWorkerError {
239
+ constructor(label: string, options?: {
240
+ cause?: unknown;
241
+ });
242
+ }
243
+ /** The worker thread exited (crash, terminate, out of memory) before answering. */
244
+ export declare class PGliteWorkerExitedError extends PGliteWorkerError {
245
+ readonly exitCode: number;
246
+ constructor(label: string, exitCode: number, options?: {
247
+ cause?: unknown;
248
+ });
249
+ }
250
+ /** A call was made after `close()` started. */
251
+ export declare class PGliteWorkerClosedError extends PGliteWorkerError {
252
+ constructor(label: string);
253
+ }
254
+ //#endregion
255
+ //#region src/pglite/worker/threaded-pglite.d.ts
256
+ export declare const DEFAULT_PGLITE_WORKER_MEMORY_MB = 1024;
257
+ export declare const DEFAULT_PGLITE_WORKER_CLOSE_GRACE_MS = 60000;
258
+ type ThreadedPGliteOptions = {
259
+ store: PGliteWorkerStoreOptions;
260
+ /** Caps the worker's JS heap; defaults to {@link resolvePgliteWorkerMemoryMb}. WebAssembly memory is outside it. */
261
+ memoryLimitMb?: number;
262
+ /** The worker script; defaults to the built entry next to this module. Tests pass a tsx bootstrap. */
263
+ workerScript?: string | URL;
264
+ /** Bound on PGlite's own close (its shutdown checkpoint) before the thread is terminated. */
265
+ closeGraceMs?: number;
266
+ logger?: ILogger;
267
+ };
268
+ /** Called once, when the worker reports that the wasm runtime aborted. */
269
+ type PGliteAbortListener = (reason: string) => void;
270
+ /** Called once, when the worker thread is gone; `error` is null after a clean close. */
271
+ type PGliteExitListener = (error: Error | null) => void;
272
+ /** `PH_PGLITE_WORKER_MEMORY_MB`, else {@link DEFAULT_PGLITE_WORKER_MEMORY_MB}. */
273
+ export declare function resolvePgliteWorkerMemoryMb(env: Record<string, string | undefined>): number;
274
+ /**
275
+ * Main-thread stand-in for a PGlite instance whose store lives in a worker
276
+ * thread. It has the surface knex-pglite, kysely-pglite-dialect and
277
+ * `HardenedPGliteDialect` use: `waitReady`, `query`, `exec`, a synchronous
278
+ * `isInTransaction()`, `closed` and `close()`.
279
+ *
280
+ * Construction is synchronous and starts the worker; calls made before the
281
+ * worker is ready are queued behind its open. The worker runs requests one at
282
+ * a time in arrival order, and every answer carries the transaction status.
283
+ * The instance is a plain extensible object, since knex stores its own
284
+ * bookkeeping on the connection.
285
+ */
286
+ export declare class ThreadedPGlite implements PGliteLike {
287
+ readonly label: string;
288
+ /** Settles once the worker has opened the store; rejects with {@link PGliteWorkerInitError}. */
289
+ readonly waitReady: Promise<void>;
290
+ private readonly worker;
291
+ private readonly logger;
292
+ private readonly closeGraceMs;
293
+ private readonly pending;
294
+ /** The reservation an `admit` run is executing under, carried through its async calls. */
295
+ private readonly admission;
296
+ private readonly abortListeners;
297
+ private readonly exitListeners;
298
+ private nextId;
299
+ private phase;
300
+ private inTransaction;
301
+ private terminalError;
302
+ private workerError;
303
+ private abortReason;
304
+ private closePromise;
305
+ constructor(options: ThreadedPGliteOptions);
306
+ /** True once the store is open and until close starts. */
307
+ get ready(): boolean;
308
+ /** True once close has started or the worker is gone. */
309
+ get closed(): boolean;
310
+ /** The reason the worker reported for a wasm abort, or null. */
311
+ get aborted(): string | null;
312
+ /** The limits the worker thread runs under (empty once it has exited). */
313
+ get resourceLimits(): ResourceLimits;
314
+ /** The worker's thread id, for diagnostics. */
315
+ get threadId(): number;
316
+ query<T = Record<string, unknown>>(sql: string, params?: unknown[], options?: QueryOptions): Promise<Results<T>>;
317
+ exec(sql: string, options?: QueryOptions): Promise<Results[]>;
318
+ /**
319
+ * `HardenedPGliteDialect`'s admission hook: `run` starts only once the worker
320
+ * can run its statements at once, with nothing queued ahead and no
321
+ * maintenance pass in progress, so the dialect's statement deadline (which
322
+ * starts inside `run`) never counts time spent waiting behind other work.
323
+ * Statements `run` issues bypass the queue until it settles; everything
324
+ * else waits behind them.
325
+ */
326
+ admit<T>(run: () => Promise<T>): Promise<T>;
327
+ /** The status after the most recently answered request, as PGlite reported it. */
328
+ isInTransaction(): boolean;
329
+ /** Closes PGlite inside the worker (its shutdown checkpoint), then terminates the thread. */
330
+ close(): Promise<void>;
331
+ /** Stops the thread at once, without PGlite's close; pending calls reject. */
332
+ terminate(): Promise<void>;
333
+ onAbort(listener: PGliteAbortListener): () => void;
334
+ onExit(listener: PGliteExitListener): () => void;
335
+ private closeWorker;
336
+ private currentAdmission;
337
+ private release;
338
+ private request;
339
+ private handleMessage;
340
+ private settle;
341
+ private settleError;
342
+ private handleAbort;
343
+ private handleLog;
344
+ private handleWorkerError;
345
+ private handleExit;
346
+ /** Records a fatal error and stops the thread; the exit rejects what is pending. */
347
+ private fail;
348
+ private rejectPending;
349
+ }
350
+ /** Absolute path of the worker script for `new Worker(...)`; null when none can run here. */
351
+ export declare const pgliteWorkerEntryPath: string | null;
352
+ //#endregion
353
+ export { type ConversionDeps, type ConversionStep, type DurableNodeFs, type DurableNodeFsOptions, type ExtractSnapshotOptions, type ExtractedSnapshot, type MaintenanceGate, type MaintenanceLogger, type MaintenanceOptions, type MaintenanceOutcome, type NodeFsClass, PGLITE_UTC_PARSERS, type PGliteAbortListener, type PGliteErrorInfo, type PGliteExitListener, type PGliteLike, type PGliteModuleSpec, type PGliteParserPreset, type PGliteWorkerDurableFsOptions, type PGliteWorkerStoreOptions, type SyncTreeHostFs, type SyncTreeResult, type ThreadedPGliteOptions, type VerifyHandle };
129
354
  export {};
130
355
  //# sourceMappingURL=pglite-node.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"pglite-node.d.mts","names":[],"sources":["../../../src/pglite/maintenance.ts","../../../src/pglite/durable-node-fs.ts","../../../src/pglite/sync-tree.ts","../../../src/pglite/snapshot-reader.ts","../../../src/pglite/convert-snapshot-dir.ts","../../../src/pglite/preflight.ts"],"mappings":";;;;;qBAIa;qBACA;KAGD;UAQK;EACf,KAAK;;UAGU;;EAEf;;EAEA;EACA,SAAS;;qBAGE;mBACM;mBACA;mBACA;UAET;UACA;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,UAAS;MAYjB;MAIA;EAIJ,MAAM,IAAI,QAAQ,eAAe;EAQjC;EAIM,QAAQ;EAMR,OAAO,QAAQ;UA+Cb;UAoBA;;;;KC1IE,qBAAqB;UAKhB;;EAEf;;EAEA;;EAEA;EACA;IAAW,KAAK;;;EAEhB,WAAW;EACX,SAAS,YAAY;;KAGX,gBAAgB,aAAa;WAC9B,aAAa;;wBAGR,mBACd,KAAK;;wBA4ES,oBACd,MAAM,aACN,iBACA,UAAS,uBACR;;;UC5Gc;EACf,UAAU;;UAGK;EACf;EACA;;;wBAIc,SACd,cACA,SAAQ,iBACP;;wBA+Ba,cACd,aACA,SAAQ;;;qBC3CG;UASI;EACf;;EAEA;EACA,SAAS;;UAGM;EACf;;EAEA,YAAY;;EAEZ;;EAEA;;;wBAIoB,gBACpB,sBACA,gBACA,UAAS,yBACR,QAAQ;;;UC/BM;EACf,MAAM,GAAG,cAAc;IAAU,MAAM;;EACvC,SAAS;;KAGC;UAOK;;EAEf,gBAAgB,eAAe,oBAAoB,QAAQ;EAC3D,QAAQ;;EAER,aAAa,MAAM,0BAA0B;EAC7C,SAAS;;;wBA6BW,kBACpB,aACA,MAAM,iBACL;;wBA6CmB,mBACpB,aACA,MAAM,iBACL;;;;qBC3FU;;wBAGS,2BACpB,eACA,kBACC,QAAQ;;wBAYW,qBACpB,aACA,MAAM,iBACL;;wBAOmB,uBACpB,aACA,QAAQ,KAAK,oBACZ"}
1
+ {"version":3,"file":"pglite-node.d.mts","names":[],"sources":["../../../src/pglite/maintenance.ts","../../../src/pglite/durable-node-fs.ts","../../../src/pglite/sync-tree.ts","../../../src/pglite/snapshot-reader.ts","../../../src/pglite/convert-snapshot-dir.ts","../../../src/pglite/preflight.ts","../../../src/pglite/worker/protocol.ts","../../../src/pglite/worker/error-info.ts","../../../src/pglite/worker/errors.ts","../../../src/pglite/worker/threaded-pglite.ts"],"mappings":";;;;;;;qBAIa;qBACA;qBACA;KAKD;UAQK;EACf,KAAK;;;KAIK,mBAAmB,GAAG,YAAY,QAAQ,OAAO,QAAQ;UAEpD;;EAEf;;EAEA;;;;;;;EAOA;;;;;;EAMA;;;;;;EAMA,OAAO;EACP,SAAS;;EAET;;qBAGW;mBACM;mBACA;mBACA;mBACA;mBACA;mBACA;mBACA;UAET;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;UACA;EAER,YAAY,UAAS;MAsBjB;MAIA;EAIJ,MAAM,IAAI,QAAQ,eAAe;EAUjC;;EAMM,QAAQ;EAMR,OAAO,QAAQ;UAKP;UASA;UA2DN;UAoBA;;;;KCjNE,qBAAqB;UAKhB;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA,kBAAkB;;EAElB;EACA;IAAW,KAAK;;;EAEhB,WAAW;EACX,SAAS,YAAY;;KAGX,gBAAgB,aAAa;WAC9B,aAAa;;wBAGR,mBACd,KAAK;;wBA4ES,oBACd,MAAM,aACN,iBACA,UAAS,uBACR;;;UCx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