@powerhousedao/reactor-api 6.2.3-dev.77 → 6.2.3-dev.78

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.
@@ -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]="ba1434c3-ef59-57f0-ae3b-f32e4a59c605")}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]="873a19a3-7cc0-5306-af99-b21f44afb4d2")}catch(e){}}();
3
3
  import path from "node:path";
4
4
  import nodeFs, { promises } from "node:fs";
5
5
  import { protocol } from "@electric-sql/pglite";
@@ -11,6 +11,16 @@ const PGLITE_UTC_PARSERS = { 1114: (value) => /* @__PURE__ */ new Date(`${value.
11
11
  const DEFAULT_MAINTENANCE_INTERVAL_MS = 3e5;
12
12
  const DEFAULT_VACUUM_FULL_ABOVE_BYTES = 268435456;
13
13
  const DEFAULT_VACUUM_FULL_QUIET_MS = 6e4;
14
+ /**
15
+ * How long a pending VACUUM FULL waits for a quiet store before it runs
16
+ * anyway: by default it never does (0), because a forced rewrite of a large
17
+ * store under load holds the only connection for minutes, every caller times
18
+ * out, and the dir needs about twice its size in free space meanwhile.
19
+ * `PH_PGLITE_VACUUM_FULL=forced` restores a deadline.
20
+ */
21
+ const DEFAULT_VACUUM_FULL_MAX_DEFER_MS = 0;
22
+ /** The deadline `PH_PGLITE_VACUUM_FULL=forced` sets. */
23
+ const FORCED_VACUUM_FULL_MAX_DEFER_MS = 18e5;
14
24
  const MAINTENANCE_RETRY_MS = 1e3;
15
25
  var PgliteMaintenance = class {
16
26
  intervalMs;
@@ -35,7 +45,7 @@ var PgliteMaintenance = class {
35
45
  this.intervalMs = Math.max(0, options.intervalMs ?? 3e5);
36
46
  this.vacuumFullAboveBytes = Math.max(0, options.vacuumFullAboveBytes ?? 268435456);
37
47
  this.vacuumFullQuietMs = Math.max(0, options.vacuumFullQuietMs ?? 6e4);
38
- this.vacuumFullMaxDeferMs = Math.max(0, options.vacuumFullMaxDeferMs ?? 18e5);
48
+ this.vacuumFullMaxDeferMs = Math.max(0, options.vacuumFullMaxDeferMs ?? 0);
39
49
  this.gate = options.gate;
40
50
  this.logger = options.logger;
41
51
  this.now = options.now ?? Date.now;
@@ -88,6 +98,9 @@ var PgliteMaintenance = class {
88
98
  this.logger?.warn(`DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; VACUUM FULL waits until the store has had no writes for ${this.vacuumFullQuietMs} ms${this.vacuumFullMaxDeferMs > 0 ? `, or at most ${this.vacuumFullMaxDeferMs} ms from open` : ""}`);
89
99
  }
90
100
  if (!full && this.syncsSinceMaintenance === 0) return "idle";
101
+ const baseDir = path.join(this.label, "base");
102
+ const bytesBefore = full ? await dirBytes(baseDir) : 0;
103
+ const startedAt = this.now();
91
104
  let outcome;
92
105
  try {
93
106
  outcome = await pg._runExclusiveQuery(async () => {
@@ -107,7 +120,13 @@ var PgliteMaintenance = class {
107
120
  }
108
121
  if (outcome !== "vacuum" && outcome !== "vacuum-full") return outcome;
109
122
  this.syncsSinceMaintenance = 0;
110
- if (full) this.vacuumFullPending = false;
123
+ if (full) {
124
+ this.vacuumFullPending = false;
125
+ const bytesAfter = await dirBytes(baseDir);
126
+ const message = `DurableNodeFs: ${this.label}/base VACUUM FULL finished in ${this.now() - startedAt} ms; ${bytesBefore} -> ${bytesAfter} bytes`;
127
+ if (this.logger?.info) this.logger.info(message);
128
+ else this.logger?.warn(message);
129
+ }
111
130
  return outcome;
112
131
  }
113
132
  schedule(delayMs) {
@@ -210,6 +229,49 @@ const EIO = 29;
210
229
  function resolvePgliteFsync(env) {
211
230
  return env.PH_PGLITE_FSYNC !== "0";
212
231
  }
232
+ const VACUUM_FULL_MODES = [
233
+ "off",
234
+ "quiet",
235
+ "forced"
236
+ ];
237
+ /**
238
+ * Reads the VACUUM FULL knobs. `PH_PGLITE_VACUUM_FULL` is `off` (the
239
+ * default: never), `quiet` (only after the quiet window, however long that
240
+ * takes) or `forced` (a deadline of 30 min from open, after which it runs
241
+ * under load). Off is the default because a full rewrite of a large store
242
+ * needs about twice its size in free disk and holds the only connection for
243
+ * minutes, and on a store that is live data rather than bloat it reclaims
244
+ * nothing; a quiet window of a minute arrives naturally between jobs, so
245
+ * `quiet` is an opt-in for stores known to be small or bloated.
246
+ * `PH_PGLITE_VACUUM_FULL_ABOVE_MB` sets the size that makes a store
247
+ * eligible; `PH_PGLITE_VACUUM_FULL_QUIET_MS` and
248
+ * `PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS` override the mode's timings. A value
249
+ * that is not a non-negative number is left to the default; an unknown mode
250
+ * throws, since silently running a rewrite is what this guards against.
251
+ */
252
+ function resolvePgliteMaintenance(env) {
253
+ const rawMode = env.PH_PGLITE_VACUUM_FULL?.trim().toLowerCase() || "off";
254
+ if (!isVacuumFullMode(rawMode)) throw new Error(`Invalid PH_PGLITE_VACUUM_FULL: ${String(env.PH_PGLITE_VACUUM_FULL)}. Expected "off", "quiet" or "forced".`);
255
+ const mode = rawMode;
256
+ const settings = {};
257
+ if (mode === "off") settings.vacuumFullAboveBytes = 0;
258
+ if (mode === "forced") settings.vacuumFullMaxDeferMs = FORCED_VACUUM_FULL_MAX_DEFER_MS;
259
+ const aboveMb = nonNegative(env.PH_PGLITE_VACUUM_FULL_ABOVE_MB);
260
+ if (aboveMb !== void 0 && mode !== "off") settings.vacuumFullAboveBytes = aboveMb * 1024 * 1024;
261
+ const quiet = nonNegative(env.PH_PGLITE_VACUUM_FULL_QUIET_MS);
262
+ if (quiet !== void 0) settings.vacuumFullQuietMs = quiet;
263
+ const maxDefer = nonNegative(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);
264
+ if (maxDefer !== void 0) settings.vacuumFullMaxDeferMs = maxDefer;
265
+ return settings;
266
+ }
267
+ function isVacuumFullMode(value) {
268
+ return VACUUM_FULL_MODES.includes(value);
269
+ }
270
+ function nonNegative(value) {
271
+ if (value === void 0 || value.trim() === "") return void 0;
272
+ const parsed = Number(value);
273
+ return Number.isFinite(parsed) && parsed >= 0 ? parsed : void 0;
274
+ }
213
275
  function isReadOnly(stream) {
214
276
  return stream.flags !== void 0 && (stream.flags & 3) === 0;
215
277
  }
@@ -418,7 +480,7 @@ function describe(value) {
418
480
  }
419
481
  }
420
482
  //#endregion
421
- export { syncDirectory as a, DEFAULT_VACUUM_FULL_ABOVE_BYTES as c, PGLITE_UTC_PARSERS as d, resolvePgliteFsync as i, DEFAULT_VACUUM_FULL_QUIET_MS as l, toPGliteErrorInfo as n, syncTree as o, createDurableNodeFs as r, DEFAULT_MAINTENANCE_INTERVAL_MS as s, fromPGliteErrorInfo as t, PgliteMaintenance as u };
483
+ export { resolvePgliteMaintenance as a, DEFAULT_MAINTENANCE_INTERVAL_MS as c, DEFAULT_VACUUM_FULL_QUIET_MS as d, FORCED_VACUUM_FULL_MAX_DEFER_MS as f, resolvePgliteFsync as i, DEFAULT_VACUUM_FULL_ABOVE_BYTES as l, PGLITE_UTC_PARSERS as m, toPGliteErrorInfo as n, syncDirectory as o, PgliteMaintenance as p, createDurableNodeFs as r, syncTree as s, fromPGliteErrorInfo as t, DEFAULT_VACUUM_FULL_MAX_DEFER_MS as u };
422
484
 
423
- //# sourceMappingURL=error-info-CCQcLAcW.mjs.map
424
- //# debugId=ba1434c3-ef59-57f0-ae3b-f32e4a59c605
485
+ //# sourceMappingURL=error-info-BaEL50f5.mjs.map
486
+ //# debugId=873a19a3-7cc0-5306-af99-b21f44afb4d2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"error-info-BaEL50f5.mjs","sources":["../src/pglite/parsers.ts","../src/pglite/maintenance.ts","../src/pglite/sync-tree.ts","../src/pglite/durable-node-fs.ts","../src/pglite/worker/error-info.ts"],"sourcesContent":["// PGlite parses `timestamp` (no tz) columns as local time; read-model columns\n// store UTC, so parse them as UTC or values shift by the host's TZ offset.\nexport const PGLITE_UTC_PARSERS = {\n // 1114 = timestamp without time zone\n 1114: (value: string) => new Date(`${value.replace(\" \", \"T\")}Z`),\n} as const;\n","import { protocol, type PGlite } from \"@electric-sql/pglite\";\nimport { promises as fs } from \"node:fs\";\nimport path from \"node:path\";\n\nexport const DEFAULT_MAINTENANCE_INTERVAL_MS = 5 * 60 * 1000;\nexport const DEFAULT_VACUUM_FULL_ABOVE_BYTES = 256 * 1024 * 1024;\nexport const DEFAULT_VACUUM_FULL_QUIET_MS = 60 * 1000;\n/**\n * How long a pending VACUUM FULL waits for a quiet store before it runs\n * anyway: by default it never does (0), because a forced rewrite of a large\n * store under load holds the only connection for minutes, every caller times\n * out, and the dir needs about twice its size in free space meanwhile.\n * `PH_PGLITE_VACUUM_FULL=forced` restores a deadline.\n */\nexport const DEFAULT_VACUUM_FULL_MAX_DEFER_MS = 0;\n/** The deadline `PH_PGLITE_VACUUM_FULL=forced` sets. */\nexport const FORCED_VACUUM_FULL_MAX_DEFER_MS = 30 * 60_000;\nconst MAINTENANCE_RETRY_MS = 1000;\n\nexport type MaintenanceOutcome =\n | \"vacuum\"\n | \"vacuum-full\"\n | \"idle\"\n | \"not-ready\"\n | \"in-transaction\"\n | \"failed\";\n\nexport interface MaintenanceLogger {\n warn(message: string): void;\n /** A finished VACUUM FULL is reported here; `warn` when absent. */\n info?(message: string): void;\n}\n\n/** Runs a maintenance pass in the owner's turn; see {@link MaintenanceOptions.gate}. */\nexport type MaintenanceGate = <T>(task: () => Promise<T>) => Promise<T>;\n\nexport interface MaintenanceOptions {\n /** VACUUM + CHECKPOINT cadence; PGlite has no autovacuum. Default 5 min; 0 disables. */\n intervalMs?: number;\n /** First pass runs VACUUM FULL when `base/` exceeds this at open. Default 256 MB; 0 disables. */\n vacuumFullAboveBytes?: number;\n /**\n * VACUUM FULL holds the store for minutes on a large dir, so it waits for a\n * store with no synced statement (no write, no catch-up) for this long,\n * counted from open; until then a pass runs plain VACUUM and keeps the\n * VACUUM FULL pending. Default 60 s; 0 runs it on the first pass.\n */\n vacuumFullQuietMs?: number;\n /**\n * The longest a pending VACUUM FULL waits for that quiet window, counted\n * from open; past it the next pass runs VACUUM FULL anyway. Default 0,\n * which waits for the quiet window however long it takes.\n */\n vacuumFullMaxDeferMs?: number;\n /**\n * Queues each pass with the store's other work, e.g. behind a worker's\n * pending requests, so a pass never starts ahead of a statement already\n * admitted. A pass still waiting here when the store closes is skipped.\n */\n gate?: MaintenanceGate;\n logger?: MaintenanceLogger;\n /** Clock for the quiet window; tests pass their own. */\n now?: () => number;\n}\n\nexport class PgliteMaintenance {\n private readonly intervalMs: number;\n private readonly vacuumFullAboveBytes: number;\n private readonly vacuumFullQuietMs: number;\n private readonly vacuumFullMaxDeferMs: number;\n private readonly gate?: MaintenanceGate;\n private readonly logger?: MaintenanceLogger;\n private readonly now: () => number;\n\n private pg?: PGlite;\n private label = \"\";\n private closing = false;\n private syncsSinceMaintenance = 0;\n private vacuumFullPending = false;\n private timer?: ReturnType<typeof setTimeout>;\n private inFlight?: Promise<MaintenanceOutcome>;\n private active = false;\n private deferralLogged = false;\n private lastSyncAt = 0;\n private openedAt = 0;\n\n constructor(options: MaintenanceOptions = {}) {\n this.intervalMs = Math.max(\n 0,\n options.intervalMs ?? DEFAULT_MAINTENANCE_INTERVAL_MS,\n );\n this.vacuumFullAboveBytes = Math.max(\n 0,\n options.vacuumFullAboveBytes ?? DEFAULT_VACUUM_FULL_ABOVE_BYTES,\n );\n this.vacuumFullQuietMs = Math.max(\n 0,\n options.vacuumFullQuietMs ?? DEFAULT_VACUUM_FULL_QUIET_MS,\n );\n this.vacuumFullMaxDeferMs = Math.max(\n 0,\n options.vacuumFullMaxDeferMs ?? DEFAULT_VACUUM_FULL_MAX_DEFER_MS,\n );\n this.gate = options.gate;\n this.logger = options.logger;\n this.now = options.now ?? Date.now;\n }\n\n get scheduled(): boolean {\n return this.timer !== undefined;\n }\n\n get running(): boolean {\n return this.inFlight !== undefined;\n }\n\n start(pg: PGlite, label: string, baseBytes: number): void {\n this.pg = pg;\n this.label = label;\n this.vacuumFullPending =\n this.vacuumFullAboveBytes > 0 && baseBytes > this.vacuumFullAboveBytes;\n this.lastSyncAt = this.now();\n this.openedAt = this.lastSyncAt;\n this.schedule(this.intervalMs);\n }\n\n noteSync(): void {\n this.syncsSinceMaintenance++;\n this.lastSyncAt = this.now();\n }\n\n /** Waits for a pass that has started; one still queued at the gate is left to skip itself. */\n async stop(): Promise<void> {\n this.closing = true;\n this.cancel();\n if (this.active) await this.inFlight;\n }\n\n async run(): Promise<MaintenanceOutcome> {\n if (this.gate) return this.gate(() => this.runNow());\n return this.runNow();\n }\n\n private async runNow(): Promise<MaintenanceOutcome> {\n this.active = true;\n try {\n return await this.pass();\n } finally {\n this.active = false;\n }\n }\n\n private async pass(): Promise<MaintenanceOutcome> {\n const pg = this.pg;\n if (this.closing || !pg?.ready) return \"not-ready\";\n // pg.close() does not take the query mutex; recheck before each statement.\n const isReady = (): boolean => pg.ready && !this.closing;\n const now = this.now();\n const overdue =\n this.vacuumFullMaxDeferMs > 0 &&\n now - this.openedAt >= this.vacuumFullMaxDeferMs;\n const full =\n this.vacuumFullPending &&\n (now - this.lastSyncAt >= this.vacuumFullQuietMs || overdue);\n if (this.vacuumFullPending && !full && !this.deferralLogged) {\n this.deferralLogged = true;\n this.logger?.warn(\n `DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; VACUUM FULL waits until the store has had no writes for ${this.vacuumFullQuietMs} ms${this.vacuumFullMaxDeferMs > 0 ? `, or at most ${this.vacuumFullMaxDeferMs} ms from open` : \"\"}`,\n );\n }\n if (!full && this.syncsSinceMaintenance === 0) {\n return \"idle\";\n }\n const baseDir = path.join(this.label, \"base\");\n const bytesBefore = full ? await dirBytes(baseDir) : 0;\n const startedAt = this.now();\n let outcome: MaintenanceOutcome;\n try {\n outcome = await pg._runExclusiveQuery(async () => {\n // isInTransaction() misses START TRANSACTION; ReadyForQuery status does not.\n if (!isReady()) return \"not-ready\";\n const { messages } = await pg.execProtocol(\n protocol.serialize.query(\"\"),\n { syncToFs: false },\n );\n if (transactionStatus(messages) !== \"I\") return \"in-transaction\";\n if (full) {\n this.logger?.warn(\n `DurableNodeFs: ${this.label}/base exceeds ${this.vacuumFullAboveBytes} bytes; running VACUUM FULL`,\n );\n }\n for (const statement of [\n full ? \"VACUUM FULL\" : \"VACUUM\",\n \"CHECKPOINT\",\n ]) {\n if (!isReady()) return \"not-ready\";\n await pg.execProtocol(protocol.serialize.query(statement), {\n syncToFs: false,\n });\n }\n return full ? \"vacuum-full\" : \"vacuum\";\n });\n } catch (err) {\n this.logger?.warn(\n `DurableNodeFs maintenance failed: ${errorMessage(err)}`,\n );\n return \"failed\";\n }\n if (outcome !== \"vacuum\" && outcome !== \"vacuum-full\") return outcome;\n this.syncsSinceMaintenance = 0;\n if (full) {\n this.vacuumFullPending = false;\n const bytesAfter = await dirBytes(baseDir);\n const message = `DurableNodeFs: ${this.label}/base VACUUM FULL finished in ${this.now() - startedAt} ms; ${bytesBefore} -> ${bytesAfter} bytes`;\n if (this.logger?.info) this.logger.info(message);\n else this.logger?.warn(message);\n }\n return outcome;\n }\n\n private schedule(delayMs: number): void {\n if (this.intervalMs === 0 || this.closing) return;\n this.timer = setTimeout(() => {\n this.timer = undefined;\n this.inFlight = this.run()\n .then((outcome) => {\n this.schedule(\n outcome === \"in-transaction\"\n ? Math.min(MAINTENANCE_RETRY_MS, this.intervalMs)\n : this.intervalMs,\n );\n return outcome;\n })\n .finally(() => {\n this.inFlight = undefined;\n });\n }, delayMs);\n this.timer.unref();\n }\n\n private cancel(): void {\n if (!this.timer) return;\n clearTimeout(this.timer);\n this.timer = undefined;\n }\n}\n\n/** Total size of the regular files under `dir`; 0 when `dir` is missing. */\nexport async function dirBytes(dir: string): Promise<number> {\n let entries;\n try {\n entries = await fs.readdir(dir, { withFileTypes: true });\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return 0;\n throw err;\n }\n let total = 0;\n for (const entry of entries) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n total += await dirBytes(full);\n } else if (entry.isFile()) {\n total += (await fs.stat(full)).size;\n }\n }\n return total;\n}\n\nfunction transactionStatus(messages: readonly { name: string }[]): unknown {\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i];\n if (m.name === \"readyForQuery\") return (m as { status?: unknown }).status;\n }\n return undefined;\n}\n\nfunction errorMessage(err: unknown): string {\n return err instanceof Error ? err.message : String(err);\n}\n","import nodeFs from \"node:fs\";\nimport path from \"node:path\";\n\nexport interface SyncTreeHostFs {\n fsyncSync(fd: number): void;\n}\n\nexport interface SyncTreeResult {\n files: number;\n dirs: number;\n}\n\n/** One pass over a finished tree; interleaving fsync with writes costs seconds. */\nexport function syncTree(\n root: string,\n hostFs: SyncTreeHostFs = nodeFs,\n): SyncTreeResult {\n const result: SyncTreeResult = { files: 0, dirs: 0 };\n const pending = [path.resolve(root)];\n while (pending.length > 0) {\n const dir = pending.pop()!;\n for (const entry of nodeFs.readdirSync(dir, { withFileTypes: true })) {\n const full = path.join(dir, entry.name);\n if (entry.isDirectory()) {\n pending.push(full);\n } else if (entry.isFile()) {\n syncFile(full, hostFs);\n result.files++;\n }\n }\n syncDirectory(dir, hostFs);\n result.dirs++;\n }\n return result;\n}\n\n// Windows refuses FlushFileBuffers on a read-only handle (EPERM).\nfunction syncFile(file: string, hostFs: SyncTreeHostFs): void {\n const fd = nodeFs.openSync(file, \"r+\");\n try {\n hostFs.fsyncSync(fd);\n } finally {\n nodeFs.closeSync(fd);\n }\n}\n\n/** fsyncs a directory's entries; false where the platform refuses (Windows). */\nexport function syncDirectory(\n dir: string,\n hostFs: SyncTreeHostFs = nodeFs,\n): boolean {\n let fd: number;\n try {\n fd = nodeFs.openSync(dir, \"r\");\n } catch {\n return false;\n }\n try {\n hostFs.fsyncSync(fd);\n return true;\n } catch {\n return false;\n } finally {\n nodeFs.closeSync(fd);\n }\n}\n","import type { PGlite } from \"@electric-sql/pglite\";\nimport { ERRNO_CODES } from \"@electric-sql/pglite/basefs\";\nimport type { NodeFS } from \"@electric-sql/pglite/nodefs\";\nimport nodeFs from \"node:fs\";\nimport path from \"node:path\";\nimport {\n dirBytes,\n FORCED_VACUUM_FULL_MAX_DEFER_MS,\n PgliteMaintenance,\n type MaintenanceGate,\n} from \"./maintenance.js\";\nimport { syncTree } from \"./sync-tree.js\";\n\nexport type NodeFsClass = typeof NodeFS;\n\n// Emscripten/WASI errno; the basefs ERRNO_CODES export lacks it.\nconst EIO = 29;\n\nexport interface DurableNodeFsOptions {\n /** Default true; `PH_PGLITE_FSYNC=0` turns it off (power-loss durability off). */\n fsync?: boolean;\n /** Default 5 min; 0 disables. */\n maintenanceIntervalMs?: number;\n /** `base/` size at open; default 256 MB; 0 disables. */\n vacuumFullAboveBytes?: number;\n /** See `MaintenanceOptions.vacuumFullQuietMs`; default 60 s. */\n vacuumFullQuietMs?: number;\n /** See `MaintenanceOptions.vacuumFullMaxDeferMs`; default 0 (quiet window only). */\n vacuumFullMaxDeferMs?: number;\n /** See `MaintenanceOptions.gate`. */\n maintenanceGate?: MaintenanceGate;\n /** Clock for the maintenance quiet window; tests pass their own. */\n now?: () => number;\n logger?: { warn(message: string): void; info?(message: string): void };\n /** Emscripten abort (a Postgres PANIC, e.g. ENOSPC on WAL). */\n onAbort?: (what: unknown) => void;\n hostFs?: Pick<typeof nodeFs, \"fsyncSync\" | \"fdatasyncSync\">;\n}\n\nexport type DurableNodeFs = InstanceType<NodeFsClass> & {\n readonly maintenance: PgliteMaintenance;\n};\n\nexport function resolvePgliteFsync(\n env: Record<string, string | undefined>,\n): boolean {\n return env.PH_PGLITE_FSYNC !== \"0\";\n}\n\n/** `PH_PGLITE_VACUUM_FULL`: when an oversized store's one-time VACUUM FULL may run. */\nexport type PgliteVacuumFullMode = \"off\" | \"quiet\" | \"forced\";\n\nconst VACUUM_FULL_MODES: readonly PgliteVacuumFullMode[] = [\n \"off\",\n \"quiet\",\n \"forced\",\n];\n\n/** The VACUUM FULL settings an environment selects; see {@link resolvePgliteMaintenance}. */\nexport type PgliteMaintenanceSettings = Pick<\n DurableNodeFsOptions,\n \"vacuumFullAboveBytes\" | \"vacuumFullQuietMs\" | \"vacuumFullMaxDeferMs\"\n>;\n\n/**\n * Reads the VACUUM FULL knobs. `PH_PGLITE_VACUUM_FULL` is `off` (the\n * default: never), `quiet` (only after the quiet window, however long that\n * takes) or `forced` (a deadline of 30 min from open, after which it runs\n * under load). Off is the default because a full rewrite of a large store\n * needs about twice its size in free disk and holds the only connection for\n * minutes, and on a store that is live data rather than bloat it reclaims\n * nothing; a quiet window of a minute arrives naturally between jobs, so\n * `quiet` is an opt-in for stores known to be small or bloated.\n * `PH_PGLITE_VACUUM_FULL_ABOVE_MB` sets the size that makes a store\n * eligible; `PH_PGLITE_VACUUM_FULL_QUIET_MS` and\n * `PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS` override the mode's timings. A value\n * that is not a non-negative number is left to the default; an unknown mode\n * throws, since silently running a rewrite is what this guards against.\n */\nexport function resolvePgliteMaintenance(\n env: Record<string, string | undefined>,\n): PgliteMaintenanceSettings {\n const rawMode = env.PH_PGLITE_VACUUM_FULL?.trim().toLowerCase() || \"off\";\n if (!isVacuumFullMode(rawMode)) {\n throw new Error(\n `Invalid PH_PGLITE_VACUUM_FULL: ${String(env.PH_PGLITE_VACUUM_FULL)}. Expected \"off\", \"quiet\" or \"forced\".`,\n );\n }\n const mode: PgliteVacuumFullMode = rawMode;\n const settings: PgliteMaintenanceSettings = {};\n if (mode === \"off\") settings.vacuumFullAboveBytes = 0;\n if (mode === \"forced\") {\n settings.vacuumFullMaxDeferMs = FORCED_VACUUM_FULL_MAX_DEFER_MS;\n }\n const aboveMb = nonNegative(env.PH_PGLITE_VACUUM_FULL_ABOVE_MB);\n if (aboveMb !== undefined && mode !== \"off\") {\n settings.vacuumFullAboveBytes = aboveMb * 1024 * 1024;\n }\n const quiet = nonNegative(env.PH_PGLITE_VACUUM_FULL_QUIET_MS);\n if (quiet !== undefined) settings.vacuumFullQuietMs = quiet;\n const maxDefer = nonNegative(env.PH_PGLITE_VACUUM_FULL_MAX_DEFER_MS);\n if (maxDefer !== undefined) settings.vacuumFullMaxDeferMs = maxDefer;\n return settings;\n}\n\nfunction isVacuumFullMode(value: string): value is PgliteVacuumFullMode {\n return (VACUUM_FULL_MODES as readonly string[]).includes(value);\n}\n\nfunction nonNegative(value: string | undefined): number | undefined {\n if (value === undefined || value.trim() === \"\") return undefined;\n const parsed = Number(value);\n return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\ninterface NodeFsStream {\n nfd?: number;\n /** Emscripten open flags; NODEFS opens the host fd with the same access mode. */\n flags?: number;\n}\n\n// Only PGlite's pg_flush_data (fsync on pre_sync_fname's O_RDONLY fd) syncs a\n// read-only fd: the result is discarded and an O_RDWR fsync of the same file\n// follows. Skipped, as Windows refuses FlushFileBuffers without write access.\nfunction isReadOnly(stream: NodeFsStream): boolean {\n return stream.flags !== undefined && (stream.flags & 3) === 0;\n}\n\ninterface EmscriptenFs {\n filesystems: { NODEFS: { stream_ops: Record<string, unknown> } };\n getStreamChecked(fd: number): NodeFsStream;\n quit(): void;\n}\n\ninterface EmscriptenMod {\n FS: EmscriptenFs;\n [wasmExport: string]: unknown;\n}\n\n// PGlite re-enters wasm from its own error handler after a query fails; on an\n// aborted runtime that spins forever, so every entry point is cut off first.\nconst WASM_ENTRY_POINTS = [\n \"_interactive_one\",\n \"_interactive_write\",\n \"_pgl_backend\",\n \"_pgl_initdb\",\n \"_pgl_shutdown\",\n];\n\nfunction poisonAfterAbort(mod: EmscriptenMod | undefined, what: unknown): void {\n if (!mod) return;\n const message = `PGlite aborted: ${String(what) || \"wasm runtime abort\"}`;\n for (const name of WASM_ENTRY_POINTS) {\n if (typeof mod[name] !== \"function\") continue;\n mod[name] = () => {\n throw new Error(message);\n };\n }\n // pg.close() rejects before closeFs(), so release the host fds here.\n try {\n mod.FS.quit();\n } catch {\n // already quit by an earlier abort\n }\n}\n\ntype SyscallImport = ((fd: number) => number) & { sig?: string };\n\ninterface WasmImports {\n env: Record<string, unknown> & { __syscall_fdatasync?: SyscallImport };\n}\n\ntype InstantiateWasm = (\n imports: WasmImports,\n done: (instance: WebAssembly.Instance, module: WebAssembly.Module) => void,\n) => unknown;\n\ninterface EmscriptenOpts {\n preRun?: ((mod: EmscriptenMod) => void)[];\n instantiateWasm?: InstantiateWasm;\n onAbort?: (what: unknown) => void;\n}\n\ntype InitOpts = Parameters<InstanceType<NodeFsClass>[\"init\"]>[1];\n\n/** Built over the passed-in class so PG16 dirs on `pglite-legacy-02` get the same behaviour. */\nexport function createDurableNodeFs(\n Base: NodeFsClass,\n dataDir: string,\n options: DurableNodeFsOptions = {},\n): DurableNodeFs {\n const fsync = options.fsync ?? true;\n const hostFs = options.hostFs ?? nodeFs;\n const logger = options.logger;\n const onAbort = options.onAbort;\n const resolvedDir = path.resolve(dataDir);\n const maintenance = new PgliteMaintenance({\n intervalMs: options.maintenanceIntervalMs,\n vacuumFullAboveBytes: options.vacuumFullAboveBytes,\n vacuumFullQuietMs: options.vacuumFullQuietMs,\n vacuumFullMaxDeferMs: options.vacuumFullMaxDeferMs,\n gate: options.maintenanceGate,\n now: options.now,\n logger,\n });\n\n class Durable extends Base {\n readonly maintenance = maintenance;\n private mod?: EmscriptenMod;\n // Off from initialSyncFs of a fresh dir until PGlite's first syncToFs.\n private hostSyncs = fsync;\n private freshInit = false;\n\n async init(\n pg: PGlite,\n opts: InitOpts,\n ): Promise<{ emscriptenOpts: InitOpts }> {\n const { emscriptenOpts: base } = await super.init(pg, opts);\n const baseOpts = base as EmscriptenOpts;\n const inner = baseOpts.instantiateWasm;\n if (fsync && !inner) {\n throw new Error(\"PGlite did not supply instantiateWasm\");\n }\n const emscriptenOpts: EmscriptenOpts = {\n ...baseOpts,\n onAbort: (what) => {\n poisonAfterAbort(this.mod, what);\n void maintenance.stop();\n onAbort?.(what);\n },\n preRun: [\n ...(baseOpts.preRun ?? []),\n (mod) => {\n this.mod = mod;\n if (!fsync) return;\n mod.FS.filesystems.NODEFS.stream_ops.fsync = (\n stream: NodeFsStream,\n ) => this.fsyncStream(stream);\n },\n ],\n instantiateWasm:\n fsync && inner\n ? (imports, done) => {\n const original = imports.env.__syscall_fdatasync;\n const replacement: SyscallImport = (fd) => this.fdatasync(fd);\n replacement.sig = original?.sig;\n imports.env.__syscall_fdatasync = replacement;\n return inner(imports, done);\n }\n : inner,\n };\n return { emscriptenOpts: emscriptenOpts as InitOpts };\n }\n\n async initialSyncFs(): Promise<void> {\n await super.initialSyncFs();\n // No PG_VERSION: initdb runs next; PGlite calls syncToFs once before ready.\n this.freshInit =\n fsync && !nodeFs.existsSync(path.join(resolvedDir, \"PG_VERSION\"));\n if (this.freshInit) this.hostSyncs = false;\n const baseBytes = await dirBytes(path.join(resolvedDir, \"base\"));\n maintenance.start(this.pg!, resolvedDir, baseBytes);\n }\n\n async syncToFs(relaxedDurability?: boolean): Promise<void> {\n maintenance.noteSync();\n await super.syncToFs(relaxedDurability);\n if (!this.freshInit) return;\n this.freshInit = false;\n this.hostSyncs = true;\n syncTree(resolvedDir, hostFs);\n }\n\n async closeFs(): Promise<void> {\n try {\n await maintenance.stop();\n } finally {\n await super.closeFs();\n }\n }\n\n // WASI fd_sync convention: 0 or a positive errno.\n private fsyncStream(stream: NodeFsStream): number {\n if (!this.hostSyncs) return 0;\n // Directory streams carry no host fd; only regular files do.\n if (typeof stream.nfd !== \"number\" || isReadOnly(stream)) return 0;\n try {\n hostFs.fsyncSync(stream.nfd);\n } catch (err) {\n logger?.warn(`DurableNodeFs fsync failed: ${String(err)}`);\n return EIO;\n }\n return 0;\n }\n\n // Linux syscall convention: 0 or a negative errno.\n private fdatasync(fd: number): number {\n if (!this.hostSyncs) return 0;\n let stream: NodeFsStream;\n try {\n stream = this.mod!.FS.getStreamChecked(fd);\n } catch {\n return -ERRNO_CODES.EBADF;\n }\n if (typeof stream.nfd !== \"number\" || isReadOnly(stream)) return 0;\n try {\n hostFs.fdatasyncSync(stream.nfd);\n } catch (err) {\n logger?.warn(`DurableNodeFs fdatasync failed: ${String(err)}`);\n return -EIO;\n }\n return 0;\n }\n }\n\n return new Durable(dataDir) as DurableNodeFs;\n}\n","import type { PGliteErrorInfo } from \"./protocol.js\";\n\nconst MAX_STACK_LENGTH = 8 * 1024;\nconst MAX_CAUSE_DEPTH = 8;\n\n/** The string fields of PGlite's `DatabaseError`, plus the query PGlite attaches. */\nexport const PG_ERROR_FIELDS = [\n \"code\",\n \"severity\",\n \"detail\",\n \"hint\",\n \"position\",\n \"internalPosition\",\n \"internalQuery\",\n \"where\",\n \"schema\",\n \"table\",\n \"column\",\n \"dataType\",\n \"constraint\",\n \"file\",\n \"line\",\n \"routine\",\n \"query\",\n] as const;\n\n/** Flattens an error and its cause chain into a structured-clonable shape. */\nexport function toPGliteErrorInfo(err: unknown, depth = 0): PGliteErrorInfo {\n if (depth > MAX_CAUSE_DEPTH) {\n return { name: \"Error\", message: \"cause chain truncated\", fields: {} };\n }\n if (!(err instanceof Error)) {\n return { name: \"Error\", message: describe(err), fields: {} };\n }\n const info: PGliteErrorInfo = {\n name: err.name || \"Error\",\n message: err.message,\n fields: pgFieldsOf(err),\n };\n if (typeof err.stack === \"string\") {\n info.stack = err.stack.slice(0, MAX_STACK_LENGTH);\n }\n if (err.cause !== undefined) {\n info.cause = toPGliteErrorInfo(err.cause, depth + 1);\n }\n return info;\n}\n\n/** Rebuilds an `Error` carrying the original name, stack, Postgres fields and cause chain. */\nexport function fromPGliteErrorInfo(info: PGliteErrorInfo): Error {\n const err = new Error(info.message);\n define(err, \"name\", info.name);\n if (info.stack !== undefined) {\n err.stack = info.stack;\n }\n for (const [key, value] of Object.entries(info.fields)) {\n define(err, key, value);\n }\n if (info.cause !== undefined) {\n define(err, \"cause\", fromPGliteErrorInfo(info.cause));\n }\n return err;\n}\n\nfunction pgFieldsOf(err: Error): Record<string, string> {\n const fields: Record<string, string> = {};\n const record = err as unknown as Record<string, unknown>;\n for (const key of PG_ERROR_FIELDS) {\n const value = record[key];\n if (typeof value === \"string\") {\n fields[key] = value;\n }\n }\n return fields;\n}\n\nfunction define(err: Error, key: string, value: unknown): void {\n Object.defineProperty(err, key, {\n value,\n configurable: true,\n writable: true,\n enumerable: key !== \"name\" && key !== \"cause\",\n });\n}\n\nfunction describe(value: unknown): string {\n if (typeof value === \"string\") {\n return value;\n }\n if (value && typeof value === \"object\") {\n const message = (value as { message?: unknown }).message;\n if (typeof message === \"string\") {\n return message;\n }\n }\n if (value === undefined || typeof value === \"function\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return \"[unserializable]\";\n }\n}\n"],"names":["fs"],"mappings":";;;;;;;AAEA,MAAa,qBAAqB,EAEhC,OAAO,0BAAkB,IAAI,KAAK,GAAG,MAAM,QAAQ,KAAK,GAAG,EAAE,EAAE,EACjE;;;ACDA,MAAa,kCAAkC;AAC/C,MAAa,kCAAkC;AAC/C,MAAa,+BAA+B;;;;;;;;AAQ5C,MAAa,mCAAmC;;AAEhD,MAAa,kCAAkC;AAC/C,MAAM,uBAAuB;AAgD7B,IAAa,oBAAb,MAA+B;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA,QAAgB;CAChB,UAAkB;CAClB,wBAAgC;CAChC,oBAA4B;CAC5B;CACA;CACA,SAAiB;CACjB,iBAAyB;CACzB,aAAqB;CACrB,WAAmB;CAEnB,YAAY,UAA8B,CAAC,GAAG;EAC5C,KAAK,aAAa,KAAK,IACrB,GACA,QAAQ,cAAA,GACV;EACA,KAAK,uBAAuB,KAAK,IAC/B,GACA,QAAQ,wBAA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,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,IAAI,SAAS,OAAO,UAAU,UAAU;EACtC,MAAM,UAAW,MAAgC;EACjD,IAAI,OAAO,YAAY,UACrB,OAAO;CAEX;CACA,IAAI,UAAU,KAAA,KAAa,OAAO,UAAU,YAC1C,OAAO,OAAO,KAAK;CAErB,IAAI;EACF,OAAO,KAAK,UAAU,KAAK;CAC7B,QAAQ;EACN,OAAO;CACT;AACF","debug_id":"873a19a3-7cc0-5306-af99-b21f44afb4d2"}
package/dist/index.d.mts CHANGED
@@ -4,7 +4,7 @@ import { C as hasOperationSchemas, E as typeDefinitionNames, S as getGeneratedDo
4
4
  import { IAnalyticsStore } from "@powerhousedao/analytics-engine-core";
5
5
  import { AnalyticsModel } from "@powerhousedao/analytics-engine-graphql";
6
6
  import { DocumentNode, GraphQLError, GraphQLResolveInfo, GraphQLScalarType, GraphQLScalarTypeConfig, GraphQLSchema } from "graphql";
7
- import { AttachmentRef, CatchUpLoadSample, DocumentModelSource as DocumentModelSource$1, ICatchUpLoadSource, IDocumentModelLoader, IDocumentModelRegistry, IDriveClient, IInspectableAttachmentStore, IInspector, IInspectorAdmin, IInspectorStorageHealthProvider, INSPECTOR_OPS, IReactorClient, IReactorFactsSink, IReactorProcessorHostModuleBase, IReactorReadClient, IReactorWriteClient, IRelationalDb, ISyncInspector, ISyncManager, InProcessReactorClientModule, InProcessReactorModule, InspectorDocumentReader, InspectorReadOpKey, PagedResults, ParsedDriveUrl, ProcessorFactoryBuilder as ProcessorFactoryBuilder$1, Remote, SYNC_INSPECTION_OPS, SearchFilter, SyncInspectionReadOpKey, SyncScopeGate, ViewFilter, driveIdFromUrl, parseDriveUrl } from "@powerhousedao/reactor";
7
+ import { AttachmentRef, CatchUpLoadSample, DocumentModelSource as DocumentModelSource$1, ICatchUpLoadSource, IDocumentModelLoader, IDocumentModelRegistry, IDriveClient, IDriveNodeSource, IInspectableAttachmentStore, IInspector, IInspectorAdmin, IInspectorStorageHealthProvider, INSPECTOR_OPS, IReactorClient, IReactorFactsSink, IReactorProcessorHostModuleBase, IReactorReadClient, IReactorWriteClient, IRelationalDb, ISyncInspector, ISyncManager, InProcessReactorClientModule, InProcessReactorModule, InspectorDocumentReader, InspectorReadOpKey, PagedResults, ParsedDriveUrl, ProcessorFactoryBuilder as ProcessorFactoryBuilder$1, Remote, SYNC_INSPECTION_OPS, SearchFilter, SyncInspectionReadOpKey, SyncScopeGate, ViewFilter, driveIdFromUrl, parseDriveUrl } from "@powerhousedao/reactor";
8
8
  import { AuthSubject, DocumentModelModule, Operation, PHDocument, UpgradeManifest } from "@powerhousedao/shared/document-model";
9
9
  import { ILogger } from "document-model";
10
10
  import { GraphQLResolverMap } from "@apollo/subgraph";
@@ -736,11 +736,13 @@ export declare class MemoryWebhookStore implements IWebhookStore {
736
736
  //#region src/http/webhook-service.d.ts
737
737
  /** The flat, token-addressed path family. */
738
738
  export declare const WEBHOOK_SEGMENT = "webhooks";
739
+ /** An origin, or a read of one only known once the server listens. */
740
+ type PublicOrigin = string | (() => string);
739
741
  interface WebhookServiceOptions {
740
742
  store: IWebhookStore;
741
743
  basePath?: string;
742
744
  /** Public origin to advertise, e.g. https://switchboard.example. */
743
- publicUrl?: string;
745
+ publicUrl?: PublicOrigin;
744
746
  }
745
747
  /** One host route for `/webhooks/:token`, dispatching by token. The flat path leaks
746
748
  * neither package nor document; the namespace lives in the token record, which is also what stops one package's token reaching another's handler. */
@@ -777,7 +779,7 @@ interface HttpRouteServiceOptions {
777
779
  /** Absent when auth is disabled host-wide; every route then sees an anonymous actor. */
778
780
  authService?: AuthService;
779
781
  /** The host's public origin; empty when unknowable, the only case where advertised URLs degrade to paths. */
780
- publicUrl?: string;
782
+ publicUrl?: PublicOrigin;
781
783
  /** Whether to believe the `X-Forwarded-*` headers that name the request's public origin.
782
784
  * Off by default: they are client-written, so with no proxy in front a caller could choose the origin a route advertises. */
783
785
  trustProxy?: boolean;
@@ -1766,6 +1768,11 @@ export type GraphQLManagerOptions = {
1766
1768
  authorizationService: IAuthorizationService;
1767
1769
  /** Resolvers dispatch to it for reactor-drive parents. */
1768
1770
  reactorDriveClient?: IDriveClient;
1771
+ /**
1772
+ * Type-neutral drive node reads behind the reactor subgraph's `driveNodes`,
1773
+ * `driveNode` and `driveDescendants`. Without it those fields refuse.
1774
+ */
1775
+ driveNodes?: IDriveNodeSource;
1769
1776
  syncServingGate?: SyncScopeGate;
1770
1777
  httpRoutes?: HttpRouteService;
1771
1778
  attachments?: IAttachmentClientProvider;
@@ -1820,6 +1827,8 @@ export declare class GraphQLManager {
1820
1827
  * it for reactor-drive parents.
1821
1828
  */
1822
1829
  readonly reactorDriveClient?: IDriveClient;
1830
+ /** See {@link GraphQLManagerOptions.driveNodes}. */
1831
+ readonly driveNodes?: IDriveNodeSource;
1823
1832
  private readonly authorizationService;
1824
1833
  private readonly path;
1825
1834
  private readonly httpServer;
@@ -2015,6 +2024,8 @@ export type ReadinessGate = {
2015
2024
  };
2016
2025
  export type API = {
2017
2026
  httpAdapter: IHttpAdapter;
2027
+ /** The port the HTTP server bound; the ephemeral one when 0 was requested. */
2028
+ port: number;
2018
2029
  /** The listening server, for host-side observers such as request load. */
2019
2030
  httpServer: http.Server;
2020
2031
  /** Hands each package a namespaced slice of the HTTP surface. */
@@ -2336,6 +2347,7 @@ export type MakeEmpty<T extends {
2336
2347
  [key: string]: unknown;
2337
2348
  }, K extends keyof T> = { [_ in K]?: never; };
2338
2349
  export type Incremental<T> = T | { [P in keyof T]?: P extends " $fragmentName" | "__typename" ? T[P] : never; };
2350
+ export type Omit<T, K extends keyof T> = Pick<T, Exclude<keyof T, K>>;
2339
2351
  export type RequireFields<T, K extends keyof T> = Omit<T, K> & { [P in K]-?: NonNullable<T[P]>; };
2340
2352
  /** All built-in and custom scalars, mapped to their actual values */
2341
2353
  export type Scalars = {
@@ -2580,6 +2592,29 @@ export type DocumentWithChildren = {
2580
2592
  readonly childIds: ReadonlyArray<Scalars["String"]["output"]>;
2581
2593
  readonly document: PhDocument;
2582
2594
  };
2595
+ export type DriveFileNode = {
2596
+ readonly documentType: Scalars["String"]["output"];
2597
+ readonly driveId: Scalars["ID"]["output"];
2598
+ readonly id: Scalars["ID"]["output"];
2599
+ readonly name: Scalars["String"]["output"];
2600
+ readonly parentFolder?: Maybe<Scalars["ID"]["output"]>;
2601
+ };
2602
+ export type DriveFolderNode = {
2603
+ readonly driveId: Scalars["ID"]["output"];
2604
+ readonly id: Scalars["ID"]["output"];
2605
+ readonly name: Scalars["String"]["output"];
2606
+ readonly parentFolder?: Maybe<Scalars["ID"]["output"]>;
2607
+ };
2608
+ export type DriveNode = DriveFileNode | DriveFolderNode;
2609
+ export declare enum DriveNodeKind {
2610
+ File = "FILE",
2611
+ Folder = "FOLDER"
2612
+ }
2613
+ export type DriveNodePage = {
2614
+ readonly hasMore: Scalars["Boolean"]["output"];
2615
+ readonly nextCursor?: Maybe<Scalars["String"]["output"]>;
2616
+ readonly results: ReadonlyArray<DriveNode>;
2617
+ };
2583
2618
  /**
2584
2619
  * One mutation job of a batch, mirroring the reactor's `ExecutionJobPlan`
2585
2620
  * (packages/reactor/src/core/types.ts). The batch runs its jobs in dependency
@@ -2913,6 +2948,9 @@ export type Query = {
2913
2948
  readonly documentOutgoingRelationshipEdges: DocumentRelationshipResultPage;
2914
2949
  readonly documentOutgoingRelationships: PhDocumentResultPage;
2915
2950
  readonly documentServed: Scalars["Boolean"]["output"];
2951
+ readonly driveDescendants: ReadonlyArray<DriveNode>;
2952
+ readonly driveNode?: Maybe<DriveNode>;
2953
+ readonly driveNodes: DriveNodePage;
2916
2954
  /**
2917
2955
  * Predicts whether the calling subject would be admitted to execute each of a
2918
2956
  * set of candidate operations, without submitting any of them. A UI asks this to
@@ -3011,6 +3049,20 @@ export type QueryDocumentServedArgs = {
3011
3049
  idOrSlug: Scalars["String"]["input"];
3012
3050
  view?: InputMaybe<ViewFilterInput>;
3013
3051
  };
3052
+ export type QueryDriveDescendantsArgs = {
3053
+ driveId: Scalars["ID"]["input"];
3054
+ root: Scalars["ID"]["input"];
3055
+ };
3056
+ export type QueryDriveNodeArgs = {
3057
+ driveId: Scalars["ID"]["input"];
3058
+ id: Scalars["ID"]["input"];
3059
+ };
3060
+ export type QueryDriveNodesArgs = {
3061
+ driveId: Scalars["ID"]["input"];
3062
+ kind?: InputMaybe<DriveNodeKind>;
3063
+ paging?: InputMaybe<PagingInput>;
3064
+ parentFolder?: InputMaybe<Scalars["ID"]["input"]>;
3065
+ };
3014
3066
  export type QueryEvaluateActionsArgs = {
3015
3067
  branch?: InputMaybe<Scalars["String"]["input"]>;
3016
3068
  candidates: ReadonlyArray<ActionCandidateInput>;
@@ -3535,6 +3587,80 @@ export type GetCreateDefaultsQuery = {
3535
3587
  readonly protocolVersions: NonNullable<unknown>;
3536
3588
  };
3537
3589
  };
3590
+ type DriveNodeFields_DriveFileNode_Fragment = {
3591
+ readonly id: string;
3592
+ readonly driveId: string;
3593
+ readonly name: string;
3594
+ readonly parentFolder?: string | null | undefined;
3595
+ readonly documentType: string;
3596
+ };
3597
+ type DriveNodeFields_DriveFolderNode_Fragment = {
3598
+ readonly id: string;
3599
+ readonly driveId: string;
3600
+ readonly name: string;
3601
+ readonly parentFolder?: string | null | undefined;
3602
+ };
3603
+ export type DriveNodeFieldsFragment = DriveNodeFields_DriveFileNode_Fragment | DriveNodeFields_DriveFolderNode_Fragment;
3604
+ export type GetDriveNodesQueryVariables = Exact<{
3605
+ driveId: Scalars["ID"]["input"];
3606
+ parentFolder?: InputMaybe<Scalars["ID"]["input"]>;
3607
+ paging?: InputMaybe<PagingInput>;
3608
+ kind?: InputMaybe<DriveNodeKind>;
3609
+ }>;
3610
+ export type GetDriveNodesQuery = {
3611
+ readonly driveNodes: {
3612
+ readonly nextCursor?: string | null | undefined;
3613
+ readonly hasMore: boolean;
3614
+ readonly results: ReadonlyArray<{
3615
+ readonly id: string;
3616
+ readonly driveId: string;
3617
+ readonly name: string;
3618
+ readonly parentFolder?: string | null | undefined;
3619
+ readonly documentType: string;
3620
+ } | {
3621
+ readonly id: string;
3622
+ readonly driveId: string;
3623
+ readonly name: string;
3624
+ readonly parentFolder?: string | null | undefined;
3625
+ }>;
3626
+ };
3627
+ };
3628
+ export type GetDriveNodeQueryVariables = Exact<{
3629
+ driveId: Scalars["ID"]["input"];
3630
+ id: Scalars["ID"]["input"];
3631
+ }>;
3632
+ export type GetDriveNodeQuery = {
3633
+ readonly driveNode?: {
3634
+ readonly id: string;
3635
+ readonly driveId: string;
3636
+ readonly name: string;
3637
+ readonly parentFolder?: string | null | undefined;
3638
+ readonly documentType: string;
3639
+ } | {
3640
+ readonly id: string;
3641
+ readonly driveId: string;
3642
+ readonly name: string;
3643
+ readonly parentFolder?: string | null | undefined;
3644
+ } | null | undefined;
3645
+ };
3646
+ export type GetDriveDescendantsQueryVariables = Exact<{
3647
+ driveId: Scalars["ID"]["input"];
3648
+ root: Scalars["ID"]["input"];
3649
+ }>;
3650
+ export type GetDriveDescendantsQuery = {
3651
+ readonly driveDescendants: ReadonlyArray<{
3652
+ readonly id: string;
3653
+ readonly driveId: string;
3654
+ readonly name: string;
3655
+ readonly parentFolder?: string | null | undefined;
3656
+ readonly documentType: string;
3657
+ } | {
3658
+ readonly id: string;
3659
+ readonly driveId: string;
3660
+ readonly name: string;
3661
+ readonly parentFolder?: string | null | undefined;
3662
+ }>;
3663
+ };
3538
3664
  export type EvaluateActionsQueryVariables = Exact<{
3539
3665
  documentIdentifier: Scalars["String"]["input"];
3540
3666
  branch?: InputMaybe<Scalars["String"]["input"]>;
@@ -4002,6 +4128,10 @@ export type TypeResolveFn<TTypes, TParent = Record<PropertyKey, never>, TContext
4002
4128
  export type IsTypeOfResolverFn<T = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>> = (obj: T, context: TContext, info: GraphQLResolveInfo) => boolean | Promise<boolean>;
4003
4129
  export type NextResolverFn<T> = () => Promise<T>;
4004
4130
  export type DirectiveResolverFn<TResult = Record<PropertyKey, never>, TParent = Record<PropertyKey, never>, TContext = Record<PropertyKey, never>, TArgs = Record<PropertyKey, never>> = (next: NextResolverFn<TResult>, parent: TParent, args: TArgs, context: TContext, info: GraphQLResolveInfo) => TResult | Promise<TResult>;
4131
+ /** Mapping of union types */
4132
+ export type ResolversUnionTypes<_RefType extends Record<string, unknown>> = ResolversObject<{
4133
+ DriveNode: DriveFileNode | DriveFolderNode;
4134
+ }>;
4005
4135
  /** Mapping between all available schema types and the resolvers types */
4006
4136
  export type ResolversTypes = ResolversObject<{
4007
4137
  Action: ResolverTypeWrapper<Action>;
@@ -4033,7 +4163,15 @@ export type ResolversTypes = ResolversObject<{
4033
4163
  DocumentRelationship: ResolverTypeWrapper<DocumentRelationship>;
4034
4164
  DocumentRelationshipResultPage: ResolverTypeWrapper<DocumentRelationshipResultPage>;
4035
4165
  DocumentWithChildren: ResolverTypeWrapper<DocumentWithChildren>;
4166
+ DriveFileNode: ResolverTypeWrapper<DriveFileNode>;
4167
+ DriveFolderNode: ResolverTypeWrapper<DriveFolderNode>;
4168
+ DriveNode: ResolverTypeWrapper<ResolversUnionTypes<ResolversTypes>["DriveNode"]>;
4169
+ DriveNodeKind: DriveNodeKind;
4170
+ DriveNodePage: ResolverTypeWrapper<Omit<DriveNodePage, "results"> & {
4171
+ results: ReadonlyArray<ResolversTypes["DriveNode"]>;
4172
+ }>;
4036
4173
  ExecutionJobInput: ExecutionJobInput;
4174
+ ID: ResolverTypeWrapper<Scalars["ID"]["output"]>;
4037
4175
  Int: ResolverTypeWrapper<Scalars["Int"]["output"]>;
4038
4176
  JSONObject: ResolverTypeWrapper<Scalars["JSONObject"]["output"]>;
4039
4177
  JobBatchMeta: ResolverTypeWrapper<JobBatchMeta>;
@@ -4110,7 +4248,14 @@ export type ResolversParentTypes = ResolversObject<{
4110
4248
  DocumentRelationship: DocumentRelationship;
4111
4249
  DocumentRelationshipResultPage: DocumentRelationshipResultPage;
4112
4250
  DocumentWithChildren: DocumentWithChildren;
4251
+ DriveFileNode: DriveFileNode;
4252
+ DriveFolderNode: DriveFolderNode;
4253
+ DriveNode: ResolversUnionTypes<ResolversParentTypes>["DriveNode"];
4254
+ DriveNodePage: Omit<DriveNodePage, "results"> & {
4255
+ results: ReadonlyArray<ResolversParentTypes["DriveNode"]>;
4256
+ };
4113
4257
  ExecutionJobInput: ExecutionJobInput;
4258
+ ID: Scalars["ID"]["output"];
4114
4259
  Int: Scalars["Int"]["output"];
4115
4260
  JSONObject: Scalars["JSONObject"]["output"];
4116
4261
  JobBatchMeta: JobBatchMeta;
@@ -4255,6 +4400,29 @@ export type DocumentWithChildrenResolvers<ContextType = Context, ParentType exte
4255
4400
  childIds?: Resolver<ReadonlyArray<ResolversTypes["String"]>, ParentType, ContextType>;
4256
4401
  document?: Resolver<ResolversTypes["PHDocument"], ParentType, ContextType>;
4257
4402
  }>;
4403
+ export type DriveFileNodeResolvers<ContextType = Context, ParentType extends ResolversParentTypes["DriveFileNode"] = ResolversParentTypes["DriveFileNode"]> = ResolversObject<{
4404
+ documentType?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
4405
+ driveId?: Resolver<ResolversTypes["ID"], ParentType, ContextType>;
4406
+ id?: Resolver<ResolversTypes["ID"], ParentType, ContextType>;
4407
+ name?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
4408
+ parentFolder?: Resolver<Maybe<ResolversTypes["ID"]>, ParentType, ContextType>;
4409
+ __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
4410
+ }>;
4411
+ export type DriveFolderNodeResolvers<ContextType = Context, ParentType extends ResolversParentTypes["DriveFolderNode"] = ResolversParentTypes["DriveFolderNode"]> = ResolversObject<{
4412
+ driveId?: Resolver<ResolversTypes["ID"], ParentType, ContextType>;
4413
+ id?: Resolver<ResolversTypes["ID"], ParentType, ContextType>;
4414
+ name?: Resolver<ResolversTypes["String"], ParentType, ContextType>;
4415
+ parentFolder?: Resolver<Maybe<ResolversTypes["ID"]>, ParentType, ContextType>;
4416
+ __isTypeOf?: IsTypeOfResolverFn<ParentType, ContextType>;
4417
+ }>;
4418
+ export type DriveNodeResolvers<ContextType = Context, ParentType extends ResolversParentTypes["DriveNode"] = ResolversParentTypes["DriveNode"]> = ResolversObject<{
4419
+ __resolveType: TypeResolveFn<"DriveFileNode" | "DriveFolderNode", ParentType, ContextType>;
4420
+ }>;
4421
+ export type DriveNodePageResolvers<ContextType = Context, ParentType extends ResolversParentTypes["DriveNodePage"] = ResolversParentTypes["DriveNodePage"]> = ResolversObject<{
4422
+ hasMore?: Resolver<ResolversTypes["Boolean"], ParentType, ContextType>;
4423
+ nextCursor?: Resolver<Maybe<ResolversTypes["String"]>, ParentType, ContextType>;
4424
+ results?: Resolver<ReadonlyArray<ResolversTypes["DriveNode"]>, ParentType, ContextType>;
4425
+ }>;
4258
4426
  export interface JsonObjectScalarConfig extends GraphQLScalarTypeConfig<ResolversTypes["JSONObject"], any> {
4259
4427
  name: "JSONObject";
4260
4428
  }
@@ -4368,6 +4536,9 @@ export type QueryResolvers<ContextType = Context, ParentType extends ResolversPa
4368
4536
  documentOutgoingRelationshipEdges?: Resolver<ResolversTypes["DocumentRelationshipResultPage"], ParentType, ContextType, Partial<QueryDocumentOutgoingRelationshipEdgesArgs>>;
4369
4537
  documentOutgoingRelationships?: Resolver<ResolversTypes["PHDocumentResultPage"], ParentType, ContextType, RequireFields<QueryDocumentOutgoingRelationshipsArgs, "relationshipType">>;
4370
4538
  documentServed?: Resolver<ResolversTypes["Boolean"], ParentType, ContextType, RequireFields<QueryDocumentServedArgs, "idOrSlug">>;
4539
+ driveDescendants?: Resolver<ReadonlyArray<ResolversTypes["DriveNode"]>, ParentType, ContextType, RequireFields<QueryDriveDescendantsArgs, "driveId" | "root">>;
4540
+ driveNode?: Resolver<Maybe<ResolversTypes["DriveNode"]>, ParentType, ContextType, RequireFields<QueryDriveNodeArgs, "driveId" | "id">>;
4541
+ driveNodes?: Resolver<ResolversTypes["DriveNodePage"], ParentType, ContextType, RequireFields<QueryDriveNodesArgs, "driveId">>;
4371
4542
  evaluateActions?: Resolver<ResolversTypes["ActionEvaluations"], ParentType, ContextType, RequireFields<QueryEvaluateActionsArgs, "candidates">>;
4372
4543
  findDocuments?: Resolver<ResolversTypes["PHDocumentResultPage"], ParentType, ContextType, Partial<QueryFindDocumentsArgs>>;
4373
4544
  jobStatus?: Resolver<Maybe<ResolversTypes["JobInfo"]>, ParentType, ContextType, RequireFields<QueryJobStatusArgs, "jobId">>;
@@ -4463,6 +4634,10 @@ export type Resolvers<ContextType = Context> = ResolversObject<{
4463
4634
  DocumentRelationship?: DocumentRelationshipResolvers<ContextType>;
4464
4635
  DocumentRelationshipResultPage?: DocumentRelationshipResultPageResolvers<ContextType>;
4465
4636
  DocumentWithChildren?: DocumentWithChildrenResolvers<ContextType>;
4637
+ DriveFileNode?: DriveFileNodeResolvers<ContextType>;
4638
+ DriveFolderNode?: DriveFolderNodeResolvers<ContextType>;
4639
+ DriveNode?: DriveNodeResolvers<ContextType>;
4640
+ DriveNodePage?: DriveNodePageResolvers<ContextType>;
4466
4641
  JSONObject?: GraphQLScalarType;
4467
4642
  JobBatchMeta?: JobBatchMetaResolvers<ContextType>;
4468
4643
  JobChangeEvent?: JobChangeEventResolvers<ContextType>;
@@ -4497,6 +4672,7 @@ export declare const isDefinedNonNullAny: (v: any) => v is definedNonNullAny;
4497
4672
  export declare const definedNonNullAnySchema: z$1.ZodAny & z$1.ZodType<definedNonNullAny, any, z$1.core.$ZodTypeInternals<definedNonNullAny, any>>;
4498
4673
  export declare const AuthDecisionSchema: z$1.ZodEnum<typeof AuthDecision>;
4499
4674
  export declare const DocumentChangeTypeSchema: z$1.ZodEnum<typeof DocumentChangeType>;
4675
+ export declare const DriveNodeKindSchema: z$1.ZodEnum<typeof DriveNodeKind>;
4500
4676
  export declare const PropagationModeSchema: z$1.ZodEnum<typeof PropagationMode>;
4501
4677
  export declare const SyncEnvelopeTypeSchema: z$1.ZodEnum<typeof SyncEnvelopeType>;
4502
4678
  export declare function ActionCandidateInputSchema(): z$1.ZodObject<Properties<ActionCandidateInput>>;
@@ -4525,6 +4701,7 @@ export declare function ViewFilterInputSchema(): z$1.ZodObject<Properties<ViewFi
4525
4701
  export declare const PhDocumentFieldsFragmentDoc: DocumentNode;
4526
4702
  export declare const DocumentRelationshipFieldsFragmentDoc: DocumentNode;
4527
4703
  export declare const JobInfoFieldsFragmentDoc: DocumentNode;
4704
+ export declare const DriveNodeFieldsFragmentDoc: DocumentNode;
4528
4705
  export declare const GetDocumentModelsDocument: DocumentNode;
4529
4706
  export declare const GetDocumentDocument: DocumentNode;
4530
4707
  export declare const GetDocumentWithOperationsDocument: DocumentNode;
@@ -4537,6 +4714,9 @@ export declare const GetDocumentOperationsDocument: DocumentNode;
4537
4714
  export declare const GetJobStatusDocument: DocumentNode;
4538
4715
  export declare const GetDocumentServedDocument: DocumentNode;
4539
4716
  export declare const GetCreateDefaultsDocument: DocumentNode;
4717
+ export declare const GetDriveNodesDocument: DocumentNode;
4718
+ export declare const GetDriveNodeDocument: DocumentNode;
4719
+ export declare const GetDriveDescendantsDocument: DocumentNode;
4540
4720
  export declare const EvaluateActionsDocument: DocumentNode;
4541
4721
  export declare const CreateDocumentDocument: DocumentNode;
4542
4722
  export declare const CreateEmptyDocumentDocument: DocumentNode;
@@ -4570,6 +4750,9 @@ export declare function getSdk<C>(requester: Requester<C>): {
4570
4750
  GetJobStatus(variables: GetJobStatusQueryVariables, options?: C): Promise<GetJobStatusQuery>;
4571
4751
  GetDocumentServed(variables: GetDocumentServedQueryVariables, options?: C): Promise<GetDocumentServedQuery>;
4572
4752
  GetCreateDefaults(variables?: GetCreateDefaultsQueryVariables, options?: C): Promise<GetCreateDefaultsQuery>;
4753
+ GetDriveNodes(variables: GetDriveNodesQueryVariables, options?: C): Promise<GetDriveNodesQuery>;
4754
+ GetDriveNode(variables: GetDriveNodeQueryVariables, options?: C): Promise<GetDriveNodeQuery>;
4755
+ GetDriveDescendants(variables: GetDriveDescendantsQueryVariables, options?: C): Promise<GetDriveDescendantsQuery>;
4573
4756
  EvaluateActions(variables: EvaluateActionsQueryVariables, options?: C): Promise<EvaluateActionsQuery>;
4574
4757
  CreateDocument(variables: CreateDocumentMutationVariables, options?: C): Promise<CreateDocumentMutation>;
4575
4758
  CreateEmptyDocument(variables: CreateEmptyDocumentMutationVariables, options?: C): Promise<CreateEmptyDocumentMutation>;
@@ -4654,6 +4837,20 @@ export declare function createReactorGraphQLClient(url: string, fetchImpl?: Fetc
4654
4837
  GetCreateDefaults(variables?: Exact<{
4655
4838
  parentIdOrSlug?: InputMaybe<Scalars["String"]["input"]>;
4656
4839
  }> | undefined, options?: {} | undefined): Promise<GetCreateDefaultsQuery>;
4840
+ GetDriveNodes(variables: Exact<{
4841
+ driveId: Scalars["ID"]["input"];
4842
+ parentFolder?: InputMaybe<Scalars["ID"]["input"]>;
4843
+ paging?: InputMaybe<PagingInput>;
4844
+ kind?: InputMaybe<DriveNodeKind>;
4845
+ }>, options?: {} | undefined): Promise<GetDriveNodesQuery>;
4846
+ GetDriveNode(variables: Exact<{
4847
+ driveId: Scalars["ID"]["input"];
4848
+ id: Scalars["ID"]["input"];
4849
+ }>, options?: {} | undefined): Promise<GetDriveNodeQuery>;
4850
+ GetDriveDescendants(variables: Exact<{
4851
+ driveId: Scalars["ID"]["input"];
4852
+ root: Scalars["ID"]["input"];
4853
+ }>, options?: {} | undefined): Promise<GetDriveDescendantsQuery>;
4657
4854
  EvaluateActions(variables: Exact<{
4658
4855
  documentIdentifier: Scalars["String"]["input"];
4659
4856
  branch?: InputMaybe<Scalars["String"]["input"]>;
@@ -5151,6 +5348,8 @@ export declare function getExplorerPrefix(basePath: string): string;
5151
5348
  export interface ClientInitializerResult {
5152
5349
  module: InProcessReactorClientModule;
5153
5350
  reactorDriveClient?: IDriveClient;
5351
+ /** Type-neutral drive node reads for the reactor subgraph's node queries. */
5352
+ driveNodes?: IDriveNodeSource;
5154
5353
  attachmentReferenceProjection?: AttachmentReferenceProjectionCapability;
5155
5354
  /**
5156
5355
  * The reactor store, bound to the schema its migrations ran in, where the
@@ -5212,6 +5411,6 @@ export declare class PrivacyPermissionAdapter {
5212
5411
  erasePermissions(documentId: string): Promise<Record<string, number>>;
5213
5412
  }
5214
5413
  //#endregion
5215
- export { type AttachmentReadGate, type AuthorizationConfig, type AuthorizerResult, type CanonicalDocumentId, DocumentModelSchema, DocumentModelSchemaCache, DocumentModelSchemaOptions, DocumentModelSource, GeneratedDocumentModelTypes, type HttpRouteServiceOptions, type IAuthorizationService, type IDocumentScopeGate, type IEventLoopDelaySource, type IHttpScope, type IPackageLoader, type IPackageLoaderOptions, type IPackagePieceSource, type IReactorInspectionSource, type IWebhookEndpoints, type IWebhookScope, type IWebhookStore, type InspectionCallerGate, type InspectionReadField, type InspectionThrottleConfig, type NodeRouteSpec, PGLITE_UTC_PARSERS, type PackagePiece, type PackagePieceEntry, type PackagesSubgraphArgs, type ParsedDriveUrl, type ReactorInspectionOptions, ReportError, type RequestClients, type RequestLoadRecorderOptions, ReservedTypeNames, ResolvedDocumentModelSchema, type RouteActor, type RouteAuth, type RouteAuthorizer, type RouteBody, type RouteContext, type RouteHandler, type RouteMethod, type RouteOptions, type RouteSpec, type RouteTransport, type RouteUser, RunDetachedOptions, type ScopedRouteHandle, SubgraphSchemaOptions, SubgraphTypeCollisionError, type WebhookEndpointInfo, type WebhookEndpointRow, type WebhookField, type WebhookHashAlgorithm, type WebhookPolicy, type WebhookReply, type WebhookRequest, type WebhookScheme, type WebhookSignatureEncoding, type WebhookSpec, type WebhookVerification, assembleSubgraphTypeDefs, buildDocumentModelSchema, buildSubgraphSchemaModule, createMergedSchema, createSchema, documentModelSubgraphTypes, driveIdFromUrl, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getGeneratedDocumentModelTypes, hasOperationSchemas, parseDriveUrl, reportFailure, reservedTypeNames, reservedTypeNamesTaken, runDetached, typeDefinitionNames };
5414
+ export { type AttachmentReadGate, type AuthorizationConfig, type AuthorizerResult, type CanonicalDocumentId, DocumentModelSchema, DocumentModelSchemaCache, DocumentModelSchemaOptions, DocumentModelSource, GeneratedDocumentModelTypes, type HttpRouteServiceOptions, type IAuthorizationService, type IDocumentScopeGate, type IEventLoopDelaySource, type IHttpScope, type IPackageLoader, type IPackageLoaderOptions, type IPackagePieceSource, type IReactorInspectionSource, type IWebhookEndpoints, type IWebhookScope, type IWebhookStore, type InspectionCallerGate, type InspectionReadField, type InspectionThrottleConfig, type NodeRouteSpec, PGLITE_UTC_PARSERS, type PackagePiece, type PackagePieceEntry, type PackagesSubgraphArgs, type ParsedDriveUrl, type PublicOrigin, type ReactorInspectionOptions, ReportError, type RequestClients, type RequestLoadRecorderOptions, ReservedTypeNames, ResolvedDocumentModelSchema, type RouteActor, type RouteAuth, type RouteAuthorizer, type RouteBody, type RouteContext, type RouteHandler, type RouteMethod, type RouteOptions, type RouteSpec, type RouteTransport, type RouteUser, RunDetachedOptions, type ScopedRouteHandle, SubgraphSchemaOptions, SubgraphTypeCollisionError, type WebhookEndpointInfo, type WebhookEndpointRow, type WebhookField, type WebhookHashAlgorithm, type WebhookPolicy, type WebhookReply, type WebhookRequest, type WebhookScheme, type WebhookSignatureEncoding, type WebhookSpec, type WebhookVerification, assembleSubgraphTypeDefs, buildDocumentModelSchema, buildSubgraphSchemaModule, createMergedSchema, createSchema, documentModelSubgraphTypes, driveIdFromUrl, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getGeneratedDocumentModelTypes, hasOperationSchemas, parseDriveUrl, reportFailure, reservedTypeNames, reservedTypeNamesTaken, runDetached, typeDefinitionNames };
5216
5415
  export {};
5217
5416
  //# sourceMappingURL=index.d.mts.map