@powerhousedao/switchboard 6.2.3-dev.89 → 6.2.3-dev.90

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 (67) hide show
  1. package/.tsbuild/test/boot-desktop-auth.test.d.ts +2 -0
  2. package/.tsbuild/test/boot-desktop-auth.test.d.ts.map +1 -0
  3. package/.tsbuild/test/delegated-publish.test.d.ts +2 -0
  4. package/.tsbuild/test/delegated-publish.test.d.ts.map +1 -0
  5. package/.tsbuild/tsconfig.tsbuildinfo +1 -1
  6. package/CHANGELOG.md +35 -0
  7. package/dist/boot.d.mts +2 -2
  8. package/dist/boot.mjs +2 -2
  9. package/dist/config/from-env.d.mts +1 -1
  10. package/dist/config/from-env.mjs +3 -3
  11. package/dist/config/schema.d.mts +1 -1
  12. package/dist/config/schema.mjs +3 -3
  13. package/dist/{from-env-DuUwngOC.mjs → from-env-DJ4iQ3QZ.mjs} +5 -5
  14. package/dist/from-env-DJ4iQ3QZ.mjs.map +1 -0
  15. package/dist/index.mjs +3 -3
  16. package/dist/{plugin-host-C0bSz1Oe.d.mts → plugin-host-BHEUSn9G.d.mts} +2 -2
  17. package/dist/{plugin-host-C0bSz1Oe.d.mts.map → plugin-host-BHEUSn9G.d.mts.map} +1 -1
  18. package/dist/plugins/ai.d.mts +1 -1
  19. package/dist/plugins/ai.d.mts.map +1 -1
  20. package/dist/plugins/ai.mjs +68 -20
  21. package/dist/plugins/ai.mjs.map +1 -1
  22. package/dist/plugins/attachments.d.mts +1 -1
  23. package/dist/plugins/attachments.mjs +3 -3
  24. package/dist/plugins/mcp.d.mts +1 -1
  25. package/dist/plugins/privacy.d.mts +1 -1
  26. package/dist/plugins/workflows.d.mts +3 -3
  27. package/dist/plugins/workflows.mjs +3 -3
  28. package/dist/{schema-XEZrdmag.mjs → schema-1yj85yQD.mjs} +15 -5
  29. package/dist/schema-1yj85yQD.mjs.map +1 -0
  30. package/dist/{schema-DhempFjb.d.mts → schema-ugrJupVH.d.mts} +5 -1
  31. package/dist/schema-ugrJupVH.d.mts.map +1 -0
  32. package/dist/{server-BJk9-9n4.mjs → server-CgDvrUqE.mjs} +129 -30
  33. package/dist/server-CgDvrUqE.mjs.map +1 -0
  34. package/dist/server.d.mts +8 -306
  35. package/dist/server.d.mts.map +1 -1
  36. package/dist/server.mjs +4 -4
  37. package/dist/types-DzO3_320.d.mts +308 -0
  38. package/dist/types-DzO3_320.d.mts.map +1 -0
  39. package/dist/utils-Cm0TE6dP.mjs +148 -0
  40. package/dist/utils-Cm0TE6dP.mjs.map +1 -0
  41. package/dist/utils.d.mts +21 -3
  42. package/dist/utils.d.mts.map +1 -1
  43. package/dist/utils.mjs +4 -4
  44. package/dist/{worker-pool-BWHBLBJd.mjs → worker-pool-gyxJnCxA.mjs} +4 -4
  45. package/dist/worker-pool-gyxJnCxA.mjs.map +1 -0
  46. package/dist/workflow-runtime-CF5pc8mt.d.mts.map +1 -1
  47. package/dist/{workflows-krankcQT.mjs → workflows-C9BQlyT0.mjs} +31 -7
  48. package/dist/workflows-C9BQlyT0.mjs.map +1 -0
  49. package/package.json +29 -19
  50. package/test/ai-gateway.test.ts +58 -1
  51. package/test/boot-desktop-auth.test.ts +278 -0
  52. package/test/boot-preconditions.test.ts +13 -0
  53. package/test/config-merge.test.ts +11 -0
  54. package/test/default-drive-protocol-versions.test.ts +1 -24
  55. package/test/default-drive-slug.test.ts +170 -2
  56. package/test/delegated-publish.test.ts +435 -0
  57. package/test/fatal-shutdown.test.ts +40 -0
  58. package/test/pglite-store.test.ts +179 -2
  59. package/test/workflow-runtime.test.ts +119 -0
  60. package/dist/from-env-DuUwngOC.mjs.map +0 -1
  61. package/dist/schema-DhempFjb.d.mts.map +0 -1
  62. package/dist/schema-XEZrdmag.mjs.map +0 -1
  63. package/dist/server-BJk9-9n4.mjs.map +0 -1
  64. package/dist/utils-C6AIF38Z.mjs +0 -133
  65. package/dist/utils-C6AIF38Z.mjs.map +0 -1
  66. package/dist/worker-pool-BWHBLBJd.mjs.map +0 -1
  67. package/dist/workflows-krankcQT.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-DzO3_320.d.mts","names":[],"sources":["../src/privacy.mts","../src/types.ts"],"mappings":";;;;;;;;;;;KAyBY;;EAEV;;EAEA;;EAEA,SAAS;;EAET;EACA;EACA;EACA;;;;;;;;;;KCXU;;KAKA,wBAAwB;EAClC,eAAe;;KAGL;EACV;EACA;EACA;;KAGU;;EAEV;;;;;EAKA;;EAGA;;;;;;;KAQU;;;;;;;;;;;;;;;;;;;;;EAqBV,UAAU;;;;;;;;EAQV;;;;;;;EAOA;;;;;EAKA,aAAa;;;;;;;EAOb;EACA;;;;;;;EAOA;;;;;;EAMA;EACA;EACA;EACA,QAAQ;EACR;EACA;EACA;IAEM;IACA;;;;;;;EASN,WAAW;;EAEX;;;EAGA;;;;;;EAMA,oBAAoB;;;EAGpB;;;;EAIA;;;EAGA;IACE;;;;;;;IAOA;MACE;MACA;QAAW;QAAkB;;MAC7B;QAAU;QAAkB;QAAqB;;;;;EAIrD,UAAU;EACV,kBAAkB;EAClB;EACA;;;;;;EAMA;EACA,SAAS;;;;;;;;;;EAUT;;;;;;;;;;EAUA;;;;;;;;;EASA;IACE;IACA;IACA;;;;;;;;;;;EAWF;IACE;IACA;;;;;;;;;EASF,6BAA6B;;;KAInB;EACV,SAAS;;EAET,UAAU;;EAEV,oBAAoB;;EAEpB,eAAe;;EAEf;;EAEA;;EAEA,aAAa;;EAEb,gBAAgB;;KAGN;EACV;EACA,SAAS;;;;EAIT,mBAAmB;;EAEnB,+BAA+B;;;EAG/B,mBAAmB;;EAEnB;;EAEA,iBAAiB;;EAEjB;IAAY,SAAS;;;EAErB;;EAEA;;EAEA,WAAW;;EAEX,QAAQ;;;;;EAKR;;;;;;;;EAQA,gBAAgB"}
@@ -0,0 +1,148 @@
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]="aa01e979-2da2-5a91-8bd6-514c16afd3b2")}catch(e){}}();
3
+ import { REACTOR_DRIVE_DOCUMENT_TYPE, reactorDriveCreateState } from "@powerhousedao/reactor-drive";
4
+ import { driveCreateState, driveDocumentType } from "@powerhousedao/shared/document-drive";
5
+ //#region src/utils.mts
6
+ const isDriveDocumentType = (documentType) => documentType === driveDocumentType || documentType === REACTOR_DRIVE_DOCUMENT_TYPE;
7
+ /**
8
+ * Only a legacy drive can take a chosen id; without one the client's creation
9
+ * default applies.
10
+ */
11
+ function newDrive(client, documentType, initialState, id) {
12
+ return client.newDocument(documentType, {
13
+ initialState,
14
+ ...id ? {
15
+ signaturePolicy: "legacy",
16
+ id
17
+ } : {}
18
+ });
19
+ }
20
+ /** The document a slug names, unless someone deleted it and kept the slug. */
21
+ async function liveHolder(client, id) {
22
+ let document;
23
+ try {
24
+ document = await client.get(id);
25
+ } catch (error) {
26
+ if (error instanceof Error && (error.name === "DocumentDeletedError" || error.name === "DocumentNotFoundError")) return "deleted";
27
+ throw error;
28
+ }
29
+ return document.state.document?.isDeleted ? "deleted" : document;
30
+ }
31
+ /** The document that already holds `slug`; null when two do (an id and a slug). */
32
+ async function slugHolder(client, slug) {
33
+ let id;
34
+ try {
35
+ id = await client.resolveIdOrSlug(slug);
36
+ } catch (error) {
37
+ return error instanceof Error && error.name === "DocumentNotFoundError" ? void 0 : null;
38
+ }
39
+ const holder = await liveHolder(client, id);
40
+ return holder === "deleted" && id === slug ? void 0 : holder;
41
+ }
42
+ async function existingDrive(client, id) {
43
+ try {
44
+ const document = await client.get(id);
45
+ return document.state.document?.isDeleted ? void 0 : document;
46
+ } catch {
47
+ return;
48
+ }
49
+ }
50
+ const driveState = (drive, documentType) => {
51
+ if (documentType === REACTOR_DRIVE_DOCUMENT_TYPE) {
52
+ const { global, local } = reactorDriveCreateState();
53
+ return {
54
+ global: {
55
+ ...global,
56
+ name: drive.global.name,
57
+ icon: drive.global.icon ?? global.icon
58
+ },
59
+ local: {
60
+ ...local,
61
+ availableOffline: drive.local?.availableOffline ?? local.availableOffline,
62
+ sharingType: drive.local?.sharingType ?? local.sharingType
63
+ }
64
+ };
65
+ }
66
+ const { global } = driveCreateState();
67
+ return {
68
+ global: {
69
+ ...global,
70
+ name: drive.global.name,
71
+ icon: drive.global.icon ?? global.icon
72
+ },
73
+ local: {
74
+ availableOffline: drive.local?.availableOffline ?? false,
75
+ sharingType: drive.local?.sharingType ?? "public",
76
+ listeners: drive.local?.listeners ?? [],
77
+ triggers: drive.local?.triggers ?? []
78
+ }
79
+ };
80
+ };
81
+ /**
82
+ * Makes sure the drive `drive.slug` names exists, and returns the URL it is
83
+ * served at, or undefined when it could not be made (logged, so the server
84
+ * still starts).
85
+ *
86
+ * The slug is the drive's name, and the only thing an existing drive is found
87
+ * by: everything else is what a missing drive is created with, so a drive of
88
+ * another type or id under that slug is left as it is. `drive.id` is found too,
89
+ * for a drive declared by an id it already has. Without one the reactor
90
+ * generates the id, so nothing here may rely on it equalling the slug.
91
+ *
92
+ * A deleted drive frees its slug, so the next call makes a new empty drive and
93
+ * the slug names that one from then on. Its id stays taken, so a declared id
94
+ * that a deleted drive holds gives way to a generated one. A delete with
95
+ * `keepSlug` is someone deciding the drive is gone: the slug stays on it and
96
+ * nothing is created.
97
+ */
98
+ async function ensureDrive(client, drive, serverPort, logger = console) {
99
+ if (!drive.slug && !drive.id) throw new Error("A drive needs a slug");
100
+ const documentType = drive.documentType ?? driveDocumentType;
101
+ if (drive.slug) {
102
+ const holder = await slugHolder(client, drive.slug);
103
+ if (holder === "deleted") {
104
+ logger.error(`The default drive "${drive.slug}" was not created: it was deleted, and its slug kept.`);
105
+ return;
106
+ }
107
+ if (holder?.header && isDriveDocumentType(holder.header.documentType)) return `http://localhost:${serverPort}/d/${holder.header.id}`;
108
+ if (holder !== void 0) {
109
+ const owner = holder ? `${holder.header.documentType} document ${holder.header.id}` : "two documents";
110
+ logger.error(`The default drive "${drive.slug}" was not created: the slug belongs to ${owner}.`);
111
+ return;
112
+ }
113
+ }
114
+ if (drive.id && await existingDrive(client, drive.id)) return `http://localhost:${serverPort}/d/${drive.id}`;
115
+ const document = await newDrive(client, documentType, driveState(drive, documentType), drive.id);
116
+ if (drive.slug) document.header.slug = drive.slug;
117
+ if (drive.global.name) document.header.name = drive.global.name;
118
+ if (drive.preferredEditor) document.header.meta = { preferredEditor: drive.preferredEditor };
119
+ try {
120
+ await (await client.write.create(document)).readable;
121
+ } catch (e) {
122
+ if (!(e instanceof Error ? e.message : String(e)).includes("already exists")) throw e;
123
+ if (drive.slug && drive.id && !await existingDrive(client, drive.id)) return ensureDrive(client, {
124
+ ...drive,
125
+ id: void 0
126
+ }, serverPort, logger);
127
+ }
128
+ return `http://localhost:${serverPort}/d/${drive.id || drive.slug}`;
129
+ }
130
+ /** @deprecated Use {@link ensureDrive}. */
131
+ function addDefaultDrive(client, drive, serverPort, logger = console) {
132
+ return ensureDrive(client, {
133
+ ...drive,
134
+ documentType: driveDocumentType
135
+ }, serverPort, logger);
136
+ }
137
+ /** @deprecated Use {@link ensureDrive} with `documentType`. */
138
+ function addDefaultReactorDrive(client, drive, serverPort, logger = console) {
139
+ return ensureDrive(client, {
140
+ ...drive,
141
+ documentType: REACTOR_DRIVE_DOCUMENT_TYPE
142
+ }, serverPort, logger);
143
+ }
144
+ //#endregion
145
+ export { addDefaultReactorDrive as n, ensureDrive as r, addDefaultDrive as t };
146
+
147
+ //# sourceMappingURL=utils-Cm0TE6dP.mjs.map
148
+ //# debugId=aa01e979-2da2-5a91-8bd6-514c16afd3b2
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils-Cm0TE6dP.mjs","sources":["../src/utils.mts"],"sourcesContent":["import type { IReactorClient } from \"@powerhousedao/reactor\";\nimport {\n REACTOR_DRIVE_DOCUMENT_TYPE,\n reactorDriveCreateState,\n} from \"@powerhousedao/reactor-drive\";\nimport {\n driveCreateState,\n driveDocumentType,\n} from \"@powerhousedao/shared/document-drive\";\nimport type { DriveInput } from \"@powerhousedao/shared/document-drive\";\nimport type {\n PHBaseState,\n PHDocument,\n} from \"@powerhousedao/shared/document-model\";\nimport type {\n SwitchboardDriveDocumentType,\n SwitchboardDriveInput,\n} from \"./types.js\";\n\nconst isDriveDocumentType = (documentType: string): boolean =>\n documentType === driveDocumentType ||\n documentType === REACTOR_DRIVE_DOCUMENT_TYPE;\n\n/**\n * Only a legacy drive can take a chosen id; without one the client's creation\n * default applies.\n */\nfunction newDrive<TDocument extends PHDocument>(\n client: IReactorClient,\n documentType: string,\n initialState: Partial<PHBaseState>,\n id: string | undefined,\n): Promise<TDocument> {\n return client.newDocument<TDocument>(documentType, {\n initialState,\n ...(id ? { signaturePolicy: \"legacy\" as const, id } : {}),\n });\n}\n\ntype DefaultDriveLogger = { error: (message: string) => void };\n\n/** The document a slug names, unless someone deleted it and kept the slug. */\nasync function liveHolder(\n client: IReactorClient,\n id: string,\n): Promise<PHDocument | \"deleted\"> {\n let document: PHDocument;\n try {\n document = await client.get(id);\n } catch (error) {\n // A slug resolved to it, so it exists: which error depends on the host.\n const gone =\n error instanceof Error &&\n (error.name === \"DocumentDeletedError\" ||\n error.name === \"DocumentNotFoundError\");\n if (gone) return \"deleted\";\n throw error;\n }\n return document.state.document?.isDeleted ? \"deleted\" : document;\n}\n\n/** The document that already holds `slug`; null when two do (an id and a slug). */\nasync function slugHolder(\n client: IReactorClient,\n slug: string,\n): Promise<PHDocument | \"deleted\" | null | undefined> {\n let id: string;\n try {\n id = await client.resolveIdOrSlug(slug);\n } catch (error) {\n const notFound =\n error instanceof Error && error.name === \"DocumentNotFoundError\";\n return notFound ? undefined : null;\n }\n const holder = await liveHolder(client, id);\n // The slug matched a deleted document's id, which leaves the slug free.\n return holder === \"deleted\" && id === slug ? undefined : holder;\n}\n\nasync function existingDrive(\n client: IReactorClient,\n id: string,\n): Promise<PHDocument | undefined> {\n try {\n const document = await client.get(id);\n return document.state.document?.isDeleted ? undefined : document;\n } catch {\n return undefined;\n }\n}\n\nconst driveState = (\n drive: SwitchboardDriveInput,\n documentType: SwitchboardDriveDocumentType,\n): Partial<PHBaseState> => {\n if (documentType === REACTOR_DRIVE_DOCUMENT_TYPE) {\n const { global, local } = reactorDriveCreateState();\n return {\n global: {\n ...global,\n name: drive.global.name,\n icon: drive.global.icon ?? global.icon,\n },\n local: {\n ...local,\n availableOffline:\n drive.local?.availableOffline ?? local.availableOffline,\n sharingType: drive.local?.sharingType ?? local.sharingType,\n },\n } as Partial<PHBaseState>;\n }\n const { global } = driveCreateState();\n return {\n global: {\n ...global,\n name: drive.global.name,\n icon: drive.global.icon ?? global.icon,\n },\n local: {\n availableOffline: drive.local?.availableOffline ?? false,\n sharingType: drive.local?.sharingType ?? \"public\",\n listeners: drive.local?.listeners ?? [],\n triggers: drive.local?.triggers ?? [],\n },\n } as Partial<PHBaseState>;\n};\n\n/**\n * Makes sure the drive `drive.slug` names exists, and returns the URL it is\n * served at, or undefined when it could not be made (logged, so the server\n * still starts).\n *\n * The slug is the drive's name, and the only thing an existing drive is found\n * by: everything else is what a missing drive is created with, so a drive of\n * another type or id under that slug is left as it is. `drive.id` is found too,\n * for a drive declared by an id it already has. Without one the reactor\n * generates the id, so nothing here may rely on it equalling the slug.\n *\n * A deleted drive frees its slug, so the next call makes a new empty drive and\n * the slug names that one from then on. Its id stays taken, so a declared id\n * that a deleted drive holds gives way to a generated one. A delete with\n * `keepSlug` is someone deciding the drive is gone: the slug stays on it and\n * nothing is created.\n */\nexport async function ensureDrive(\n client: IReactorClient,\n drive: SwitchboardDriveInput,\n serverPort: number,\n logger: DefaultDriveLogger = console,\n): Promise<string | undefined> {\n if (!drive.slug && !drive.id) {\n throw new Error(\"A drive needs a slug\");\n }\n const documentType = drive.documentType ?? driveDocumentType;\n\n if (drive.slug) {\n const holder = await slugHolder(client, drive.slug);\n if (holder === \"deleted\") {\n logger.error(\n `The default drive \"${drive.slug}\" was not created: it was deleted, and its slug kept.`,\n );\n return undefined;\n }\n if (holder?.header && isDriveDocumentType(holder.header.documentType)) {\n return `http://localhost:${serverPort}/d/${holder.header.id}`;\n }\n if (holder !== undefined) {\n const owner = holder\n ? `${holder.header.documentType} document ${holder.header.id}`\n : \"two documents\";\n logger.error(\n `The default drive \"${drive.slug}\" was not created: the slug belongs to ${owner}.`,\n );\n return undefined;\n }\n }\n if (drive.id && (await existingDrive(client, drive.id))) {\n return `http://localhost:${serverPort}/d/${drive.id}`;\n }\n\n const document = await newDrive(\n client,\n documentType,\n driveState(drive, documentType),\n drive.id,\n );\n if (drive.slug) {\n document.header.slug = drive.slug;\n }\n if (drive.global.name) {\n document.header.name = drive.global.name;\n }\n if (drive.preferredEditor) {\n document.header.meta = { preferredEditor: drive.preferredEditor };\n }\n\n try {\n await (\n await client.write.create(document)\n ).readable;\n } catch (e) {\n const errorMessage = e instanceof Error ? e.message : String(e);\n if (!errorMessage.includes(\"already exists\")) {\n throw e;\n }\n if (drive.slug && drive.id && !(await existingDrive(client, drive.id))) {\n return ensureDrive(\n client,\n { ...drive, id: undefined },\n serverPort,\n logger,\n );\n }\n }\n\n return `http://localhost:${serverPort}/d/${drive.id || drive.slug}`;\n}\n\n/** @deprecated Use {@link ensureDrive}. */\nexport function addDefaultDrive(\n client: IReactorClient,\n drive: DriveInput,\n serverPort: number,\n logger: DefaultDriveLogger = console,\n): Promise<string | undefined> {\n return ensureDrive(\n client,\n { ...drive, documentType: driveDocumentType },\n serverPort,\n logger,\n );\n}\n\n/** @deprecated Use {@link ensureDrive} with `documentType`. */\nexport function addDefaultReactorDrive(\n client: IReactorClient,\n drive: DriveInput,\n serverPort: number,\n logger: DefaultDriveLogger = console,\n): Promise<string | undefined> {\n return ensureDrive(\n client,\n { ...drive, documentType: REACTOR_DRIVE_DOCUMENT_TYPE },\n serverPort,\n logger,\n );\n}\n\nexport { isPostgresUrl } from \"./postgres-url.mjs\";\n"],"names":[],"mappings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AAO,MAAM,OAAO,QAAQ,EAAA,CAClC;CACJ,SAAS,GAAG;EAEV,IAAI,EADiB,aAAa,QAAQ,EAAE,UAAU,OAAO,CAAC,EAAA,CAC5C,SAAS,gBAAgB,GACzC,MAAM;EAER,IAAI,MAAM,QAAQ,MAAM,MAAM,CAAE,MAAM,cAAc,QAAQ,MAAM,EAAE,GAClE,OAAO,YACL,QACA;GAAE,GAAG;GAAO,IAAI,KAAA;EAAU,GAC1B,YACA,MACF;CAEJ;CAEA,OAAO,oBAAoB,WAAW,KAAK,MAAM,MAAM,MAAM;AAC/D;;AAGA,SAAgB,gBACd,QACA,OACA,YACA,SAA6B,SACA;CAC7B,OAAO,YACL,QACA;EAAE,GAAG;EAAO,cAAc;CAAkB,GAC5C,YACA,MACF;AACF;;AAGA,SAAgB,uBACd,QACA,OACA,YACA,SAA6B,SACA;CAC7B,OAAO,YACL,QACA;EAAE,GAAG;EAAO,cAAc;CAA4B,GACtD,YACA,MACF;AACF","debug_id":"aa01e979-2da2-5a91-8bd6-514c16afd3b2"}
package/dist/utils.d.mts CHANGED
@@ -1,3 +1,4 @@
1
+ import { o as SwitchboardDriveInput } from "./types-DzO3_320.mjs";
1
2
  import { IReactorClient } from "@powerhousedao/reactor";
2
3
  import { DriveInput } from "@powerhousedao/shared/document-drive";
3
4
  //#region src/postgres-url.d.mts
@@ -7,10 +8,27 @@ export declare function isPostgresUrl(url: string): boolean;
7
8
  type DefaultDriveLogger = {
8
9
  error: (message: string) => void;
9
10
  };
10
- /** Creates a configured drive unless one with its id or slug exists; the
11
- * URL it is served at, or undefined when another document holds the slug. */
11
+ /**
12
+ * Makes sure the drive `drive.slug` names exists, and returns the URL it is
13
+ * served at, or undefined when it could not be made (logged, so the server
14
+ * still starts).
15
+ *
16
+ * The slug is the drive's name, and the only thing an existing drive is found
17
+ * by: everything else is what a missing drive is created with, so a drive of
18
+ * another type or id under that slug is left as it is. `drive.id` is found too,
19
+ * for a drive declared by an id it already has. Without one the reactor
20
+ * generates the id, so nothing here may rely on it equalling the slug.
21
+ *
22
+ * A deleted drive frees its slug, so the next call makes a new empty drive and
23
+ * the slug names that one from then on. Its id stays taken, so a declared id
24
+ * that a deleted drive holds gives way to a generated one. A delete with
25
+ * `keepSlug` is someone deciding the drive is gone: the slug stays on it and
26
+ * nothing is created.
27
+ */
28
+ export declare function ensureDrive(client: IReactorClient, drive: SwitchboardDriveInput, serverPort: number, logger?: DefaultDriveLogger): Promise<string | undefined>;
29
+ /** @deprecated Use {@link ensureDrive}. */
12
30
  export declare function addDefaultDrive(client: IReactorClient, drive: DriveInput, serverPort: number, logger?: DefaultDriveLogger): Promise<string | undefined>;
13
- /** addDefaultDrive for a reactor drive. */
31
+ /** @deprecated Use {@link ensureDrive} with `documentType`. */
14
32
  export declare function addDefaultReactorDrive(client: IReactorClient, drive: DriveInput, serverPort: number, logger?: DefaultDriveLogger): Promise<string | undefined>;
15
33
  //#endregion
16
34
  export {};
@@ -1 +1 @@
1
- {"version":3,"file":"utils.d.mts","names":[],"sources":["../src/postgres-url.mts","../src/utils.mts"],"mappings":";;;wBAAgB,cAAc;;;KCgCzB;EAAuB,QAAQ;;;;wBAiEd,gBACpB,QAAQ,gBACR,OAAO,YACP,oBACA,SAAQ,qBACP;;wBAgFmB,uBACpB,QAAQ,gBACR,OAAO,YACP,oBACA,SAAQ,qBACP"}
1
+ {"version":3,"file":"utils.d.mts","names":[],"sources":["../src/postgres-url.mts","../src/utils.mts"],"mappings":";;;;wBAAgB,cAAc;;;KCuCzB;EAAuB,QAAQ;;;;;;;;;;;;;;;;;;;wBAyGd,YACpB,QAAQ,gBACR,OAAO,uBACP,oBACA,SAAQ,qBACP;;wBAsEa,gBACd,QAAQ,gBACR,OAAO,YACP,oBACA,SAAQ,qBACP;;wBAUa,uBACd,QAAQ,gBACR,OAAO,YACP,oBACA,SAAQ,qBACP"}
package/dist/utils.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { t as isPostgresUrl } from "./postgres-url-DTDhBjXX.mjs";
2
- import { n as addDefaultReactorDrive, t as addDefaultDrive } from "./utils-C6AIF38Z.mjs";
3
- export { addDefaultDrive, addDefaultReactorDrive, isPostgresUrl };
4
- !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]="96977d3b-9f18-561f-abd9-e7616eab631d")}catch(e){}}();
5
- //# debugId=96977d3b-9f18-561f-abd9-e7616eab631d
2
+ import { n as addDefaultReactorDrive, r as ensureDrive, t as addDefaultDrive } from "./utils-Cm0TE6dP.mjs";
3
+ export { addDefaultDrive, addDefaultReactorDrive, ensureDrive, isPostgresUrl };
4
+ !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]="88a1492b-20ef-5063-8ee1-40e31754cbd9")}catch(e){}}();
5
+ //# debugId=88a1492b-20ef-5063-8ee1-40e31754cbd9
@@ -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]="eca2a0ad-1b80-50e5-a2e3-272987fbba5e")}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]="0abc3b7a-f473-50e3-9984-427c6dfd9263")}catch(e){}}();
3
3
  import { t as isPostgresUrl } from "./postgres-url-DTDhBjXX.mjs";
4
4
  import { existsSync, realpathSync } from "node:fs";
5
5
  import path from "node:path";
@@ -20,7 +20,7 @@ function reactorDbUrlOf(dbPath, env) {
20
20
  return dbPath ?? env.PH_REACTOR_DATABASE_URL ?? env.PH_SWITCHBOARD_DATABASE_URL;
21
21
  }
22
22
  function workerTrustPolicyIssue(facts) {
23
- if (facts.workers > 0 && facts.authEnforcement && facts.renownSource === "self") return "The executor worker pool (REACTOR_WORKERS) cannot verify signers when REACTOR_AUTH_ENFORCEMENT is on and Renown credentials are read from this switchboard (\"self\" via auth.renown.source or RENOWN_SOURCE): pooled workers have no trust policy and would refuse every signed write. Set RENOWN_SOURCE=remote, or disable the worker pool (REACTOR_WORKERS=0).";
23
+ if (facts.workers > 0 && facts.authEnforcement && facts.renownSource !== "remote") return "The executor worker pool (REACTOR_WORKERS) cannot verify signers when REACTOR_AUTH_ENFORCEMENT is on and Renown credentials are read from this switchboard (\"self\" or \"kept\" via auth.renown.source or RENOWN_SOURCE): pooled workers have no trust policy and would refuse every signed write. Set RENOWN_SOURCE=remote, or disable the worker pool (REACTOR_WORKERS=0).";
24
24
  }
25
25
  /** In the order the server checks them; empty when the pool is off. */
26
26
  function workerPoolIssues(facts) {
@@ -300,5 +300,5 @@ function parseWorkerCount(raw) {
300
300
  //#endregion
301
301
  export { resolveWorkerModelSources as a, parseOnOff as c, reactorDbUrlOf as d, switchboardBootIssues as f, parseNonNegativeInt as h, resolveHostPoolSize as i, resolveProjectionWorkerOptions as l, workerTrustPolicyIssue as m, keepImportableSources as n, resolveWorkerPoolOptions as o, workerPoolIssues as p, parseWorkerCount as r, assertProjectionWorkerSupported as s, buildWorkerDbConfig as t, projectionWorkerIssues as u };
302
302
 
303
- //# sourceMappingURL=worker-pool-BWHBLBJd.mjs.map
304
- //# debugId=eca2a0ad-1b80-50e5-a2e3-272987fbba5e
303
+ //# sourceMappingURL=worker-pool-gyxJnCxA.mjs.map
304
+ //# debugId=0abc3b7a-f473-50e3-9984-427c6dfd9263
@@ -0,0 +1 @@
1
+ {"version":3,"file":"worker-pool-gyxJnCxA.mjs","sources":["../src/env.mts","../src/boot-preconditions.mts","../src/projection-worker.mts","../src/worker-pool.mts"],"sourcesContent":["export function parseNonNegativeInt(\n raw: string | undefined,\n name: string,\n): number | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n const value = Number.parseInt(raw, 10);\n if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) {\n throw new Error(`${name} must be a non-negative integer, got \"${raw}\"`);\n }\n return value;\n}\n","import { isPostgresUrl } from \"./postgres-url.mjs\";\n\n/** What the server refuses to boot with; it throws the first, `ph host check` reports all. */\nexport interface SwitchboardBootFacts {\n dev: boolean;\n /** Executor pool size; 0 when the pool is off. */\n workers: number;\n projectionWorker: boolean;\n reactorDbUrl: string | undefined;\n authEnforcement: boolean;\n renownSource: \"self\" | \"remote\" | \"kept\";\n}\n\n/** The reactor database the server boots with: its `dbPath` option, then the env. */\nexport function reactorDbUrlOf(\n dbPath: string | undefined,\n env: Readonly<Record<string, string | undefined>>,\n): string | undefined {\n return (\n dbPath ?? env.PH_REACTOR_DATABASE_URL ?? env.PH_SWITCHBOARD_DATABASE_URL\n );\n}\n\nexport function workerTrustPolicyIssue(\n facts: Pick<\n SwitchboardBootFacts,\n \"workers\" | \"authEnforcement\" | \"renownSource\"\n >,\n): string | undefined {\n if (\n facts.workers > 0 &&\n facts.authEnforcement &&\n facts.renownSource !== \"remote\"\n ) {\n return (\n \"The executor worker pool (REACTOR_WORKERS) cannot verify signers when \" +\n \"REACTOR_AUTH_ENFORCEMENT is on and Renown credentials are read from \" +\n 'this switchboard (\"self\" or \"kept\" via auth.renown.source or RENOWN_SOURCE): ' +\n \"pooled workers have no trust policy and would refuse every signed \" +\n \"write. Set RENOWN_SOURCE=remote, or disable the worker pool \" +\n \"(REACTOR_WORKERS=0).\"\n );\n }\n return undefined;\n}\n\n/** In the order the server checks them; empty when the pool is off. */\nexport function workerPoolIssues(facts: SwitchboardBootFacts): string[] {\n if (facts.workers <= 0) return [];\n const issues: string[] = [];\n if (facts.dev) {\n issues.push(\n \"The executor worker pool (REACTOR_WORKERS) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary\",\n );\n }\n const trust = workerTrustPolicyIssue(facts);\n if (trust) issues.push(trust);\n if (!facts.reactorDbUrl || !isPostgresUrl(facts.reactorDbUrl)) {\n issues.push(\n \"The executor worker pool (REACTOR_WORKERS) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.\",\n );\n }\n return issues;\n}\n\n/** The projection worker's preconditions, assuming it is enabled. */\nexport function projectionWorkerIssues(\n facts: Pick<SwitchboardBootFacts, \"dev\" | \"reactorDbUrl\">,\n): string[] {\n const issues: string[] = [];\n if (facts.dev) {\n issues.push(\n \"The projection worker (REACTOR_PROJECTION_WORKER) is not supported in dev mode: Vite-loaded document models cannot cross a worker-thread boundary\",\n );\n }\n if (!facts.reactorDbUrl || !isPostgresUrl(facts.reactorDbUrl)) {\n issues.push(\n \"The projection worker (REACTOR_PROJECTION_WORKER) requires a Postgres reactor database — set PH_REACTOR_DATABASE_URL or PH_SWITCHBOARD_DATABASE_URL. PGlite cannot be shared across worker threads.\",\n );\n }\n return issues;\n}\n\nexport function switchboardBootIssues(facts: SwitchboardBootFacts): string[] {\n return [\n ...workerPoolIssues(facts),\n ...(facts.projectionWorker ? projectionWorkerIssues(facts) : []),\n ];\n}\n","import { projectionWorkerIssues } from \"./boot-preconditions.mjs\";\nimport { parseNonNegativeInt } from \"./env.mjs\";\n\nexport type SwitchboardProjectionWorkerOptions = {\n dbPoolSize: number;\n};\n\nexport type SwitchboardProjectionWorkerInput = {\n enabled?: boolean;\n dbPoolSize?: number;\n};\n\n// Run 11 of the bench sweep saw chain.depth ~6.5 at one shard, so 8 covers the\n// working set; behind a 25-slot transaction pooler a larger pool is not spendable.\nconst DEFAULT_DB_POOL_SIZE_PROJECTION = 8;\n\nconst ON_TOKENS = [\"1\", \"true\", \"on\", \"yes\"];\nconst OFF_TOKENS = [\"0\", \"false\", \"off\", \"no\"];\n\n/**\n * Enabled by REACTOR_PROJECTION_WORKER (1/true/on/yes, case-insensitive) or\n * `input.enabled`, which wins when defined; null when off (the default).\n */\nexport function resolveProjectionWorkerOptions(\n input: SwitchboardProjectionWorkerInput | undefined,\n env: NodeJS.ProcessEnv,\n): SwitchboardProjectionWorkerOptions | null {\n const enabled =\n input?.enabled ?? parseOnOff(env.REACTOR_PROJECTION_WORKER) ?? false;\n if (!enabled) {\n return null;\n }\n const dbPoolSize =\n input?.dbPoolSize ??\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_PROJECTION,\n \"REACTOR_DB_POOL_SIZE_PROJECTION\",\n ) ??\n DEFAULT_DB_POOL_SIZE_PROJECTION;\n if (dbPoolSize < 1) {\n throw new Error(\n \"REACTOR_DB_POOL_SIZE_PROJECTION must be at least 1; the projection worker cannot run without a pool\",\n );\n }\n return { dbPoolSize };\n}\n\n/** Same preconditions as the executor worker pool; message shape mirrors server.mts. */\nexport function assertProjectionWorkerSupported(args: {\n dev: boolean;\n reactorDbUrl: string | undefined;\n}): void {\n const issue = projectionWorkerIssues(args).at(0);\n if (issue) throw new Error(issue);\n}\n\nexport function parseOnOff(raw: string | undefined): boolean | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n const token = raw.trim().toLowerCase();\n if (ON_TOKENS.includes(token)) {\n return true;\n }\n if (OFF_TOKENS.includes(token)) {\n return false;\n }\n throw new Error(\n `REACTOR_PROJECTION_WORKER must be one of 1, true, on, yes, 0, false, off, no, got \"${raw}\"`,\n );\n}\n","import type { DbConfig, FileModelSource } from \"@powerhousedao/reactor\";\nimport type { ILogger } from \"document-model\";\nimport { existsSync, realpathSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\nimport { parseNonNegativeInt } from \"./env.mjs\";\n\nexport type WorkerCountInput = number | \"auto\";\n\nexport type SwitchboardWorkerPoolOptions = {\n numWorkers: number;\n /** Whether numWorkers was given explicitly or sized from the core count. */\n mode: \"explicit\" | \"auto\";\n dbPoolSizePerWorker: number;\n acquireTimeoutMs: number;\n};\n\nexport type SwitchboardWorkerPoolInput = {\n numWorkers?: WorkerCountInput;\n dbPoolSizePerWorker?: number;\n acquireTimeoutMs?: number;\n};\n\nconst DEFAULT_DB_POOL_SIZE_PER_WORKER = 2;\nconst DEFAULT_ACQUIRE_TIMEOUT_MS = 5000;\n\n// Host reactor pool. pg-pool's own default is 10, below the bench harness's\n// floor of 16 (bench/host/src/main.ts, REACTOR_DB_POOL_SIZE_HOST). Run 8 of\n// the sweep found throughput flat from 16 to 96 but per-op index p50\n// collapsing 262ms -> 43ms, so this buys latency, not throughput — and only\n// up to whatever the connection budget in front of Postgres allows.\nconst DEFAULT_DB_POOL_SIZE_HOST = 16;\n\n// Auto-sizing: reserve cores for the host event loop (queue, read models,\n// HTTP) and cap at the top of the bench sweep envelope, which also bounds\n// the worker Postgres-connection budget.\nconst AUTO_RESERVED_CORES = 2;\nconst AUTO_WORKER_CAP = 8;\n\n/** Worker count for \"auto\": always at least 1 — auto sizes the pool, it does not turn worker mode off. */\nexport function autoWorkerCount(availableCores: number): number {\n return Math.max(\n 1,\n Math.min(AUTO_WORKER_CAP, availableCores - AUTO_RESERVED_CORES),\n );\n}\n\n/**\n * Effective worker-pool config from programmatic options (which win) and the\n * REACTOR_* env vars; null when disabled (numWorkers 0, the default).\n * `\"auto\"` sizes the pool from the machine's available cores.\n */\nexport function resolveWorkerPoolOptions(\n input: SwitchboardWorkerPoolInput | undefined,\n env: NodeJS.ProcessEnv,\n availableCores: number = os.availableParallelism(),\n): SwitchboardWorkerPoolOptions | null {\n const requested =\n input?.numWorkers ?? parseWorkerCount(env.REACTOR_WORKERS) ?? 0;\n const mode = requested === \"auto\" ? \"auto\" : \"explicit\";\n const numWorkers =\n requested === \"auto\" ? autoWorkerCount(availableCores) : requested;\n if (!Number.isInteger(numWorkers) || numWorkers < 0) {\n throw new Error(\n `workerPool.numWorkers must be \"auto\" or a non-negative integer, got ${numWorkers}`,\n );\n }\n if (numWorkers === 0) {\n return null;\n }\n return {\n numWorkers,\n mode,\n dbPoolSizePerWorker:\n input?.dbPoolSizePerWorker ??\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_WORKER,\n \"REACTOR_DB_POOL_SIZE_WORKER\",\n ) ??\n DEFAULT_DB_POOL_SIZE_PER_WORKER,\n acquireTimeoutMs:\n input?.acquireTimeoutMs ??\n parseNonNegativeInt(\n env.REACTOR_DB_ACQUIRE_TIMEOUT_MS,\n \"REACTOR_DB_ACQUIRE_TIMEOUT_MS\",\n ) ??\n DEFAULT_ACQUIRE_TIMEOUT_MS,\n };\n}\n\n/**\n * Size of the reactor's own (host) Postgres pool. Unlike the worker pool there\n * is no \"disabled\" state — the host pool is the only Postgres pool in the\n * server path, backing both reactor storage and the read models that reach it\n * via `withSchema` — so 0 is rejected rather than read as \"off\".\n *\n * The acquire timeout is deliberately not configurable here: the host pool\n * waits indefinitely today, and making it finite converts saturation from a\n * latency problem into a thrown error on the read-model path. That is a\n * behavior change worth making separately, once the retry semantics of a\n * rejected `pool.connect()` inside the read-model coordinator are settled.\n */\nexport function resolveHostPoolSize(env: NodeJS.ProcessEnv): number {\n const poolSize =\n parseNonNegativeInt(\n env.REACTOR_DB_POOL_SIZE_HOST,\n \"REACTOR_DB_POOL_SIZE_HOST\",\n ) ?? DEFAULT_DB_POOL_SIZE_HOST;\n if (poolSize < 1) {\n throw new Error(\n \"REACTOR_DB_POOL_SIZE_HOST must be at least 1; the host pool cannot be disabled\",\n );\n }\n return poolSize;\n}\n\n/**\n * DbConfig for each worker's own pool, parsed from a postgres:// URL.\n * Explicit host, database, and user are required — no pg-side defaults.\n */\nexport function buildWorkerDbConfig(\n postgresUrl: string,\n options: Pick<\n SwitchboardWorkerPoolOptions,\n \"dbPoolSizePerWorker\" | \"acquireTimeoutMs\"\n >,\n): DbConfig {\n let parsed: URL;\n try {\n parsed = new URL(postgresUrl);\n } catch {\n throw new Error(\n `Worker pool requires a valid postgres:// URL for the reactor database, got \"${postgresUrl}\"`,\n );\n }\n const database = decodeURIComponent(parsed.pathname.replace(/^\\//, \"\"));\n if (!parsed.hostname || !database) {\n throw new Error(\n `Worker pool requires a postgres URL with a host and database name, got \"${postgresUrl}\"`,\n );\n }\n if (!parsed.username) {\n throw new Error(\n `Worker pool requires explicit credentials in the postgres URL (workers open their own connections), got \"${postgresUrl}\"`,\n );\n }\n const sslmode = parsed.searchParams.get(\"sslmode\");\n const ssl =\n parsed.searchParams.get(\"ssl\") === \"true\" ||\n (sslmode !== null && sslmode !== \"disable\");\n return {\n host: parsed.hostname,\n port: parsed.port ? Number(parsed.port) : 5432,\n database,\n user: decodeURIComponent(parsed.username),\n password: decodeURIComponent(parsed.password),\n ssl,\n applicationName: \"switchboard-worker\",\n poolSize: options.dbPoolSizePerWorker,\n connectionTimeoutMillis: options.acquireTimeoutMs,\n };\n}\n\n/** Specifiers of the base models switchboard always registers. */\nconst BASE_MODEL_SPECIFIERS = [\n \"document-model\",\n \"@powerhousedao/shared/document-drive\",\n \"@powerhousedao/reactor-drive\",\n \"@powerhousedao/reactor-group/document-models\",\n];\n\n// As the reactor builder tells a module from the rest of a source's exports.\nfunction isModelModule(value: unknown): boolean {\n const candidate = value as {\n reducer?: unknown;\n documentModel?: { global?: { id?: unknown } };\n } | null;\n return (\n typeof candidate?.reducer === \"function\" &&\n typeof candidate.documentModel?.global?.id === \"string\"\n );\n}\n\n// Drops sources that fail to import or export no model. For workflow pieces\n// only: a missing model means \"unavailable to pieces\", not a failed boot.\nexport async function keepImportableSources(\n sources: FileModelSource[],\n logger: ILogger,\n): Promise<FileModelSource[]> {\n const kept: FileModelSource[] = [];\n for (const source of sources) {\n try {\n const exports = (await import(\n pathToFileURL(source.filePath).href\n )) as Record<string, unknown>;\n if (Object.values(exports).some(isModelModule)) kept.push(source);\n } catch (error) {\n logger.warn(\n `Worker model sources: \"${source.filePath}\" does not import, so workflow pieces will not see its models: ${String(error)}`,\n );\n }\n }\n return kept;\n}\n\n/**\n * Resolves base models and configured package identifiers to `{ filePath }`\n * sources for the reactor builder. Resolution to absolute paths happens here\n * because workers (and the builder) resolve bare specifiers from the reactor\n * package's own dependency context, which cannot see switchboard or project\n * packages. Unresolvable identifiers are skipped with a warning; the builder\n * fails the boot if a registered model ends up without an importable source.\n */\nexport async function resolveWorkerModelSources(\n packages: string[],\n logger: ILogger,\n options: {\n /** Cached file for a package not installed locally, e.g. from a registry. */\n resolveRemote?: (identifier: string) => Promise<string | null>;\n } = {},\n): Promise<FileModelSource[]> {\n const sources: FileModelSource[] = [];\n for (const identifier of [...BASE_MODEL_SPECIFIERS, ...packages]) {\n const filePath =\n (await resolveModelModuleFile(identifier)) ??\n (await resolveRemoteSafely(identifier, options.resolveRemote, logger));\n if (!filePath) {\n logger.warn(\n `Worker model sources: no importable document-models entry for \"${identifier}\", skipping`,\n );\n continue;\n }\n sources.push({ filePath });\n }\n return sources;\n}\n\nasync function resolveRemoteSafely(\n identifier: string,\n resolveRemote: ((identifier: string) => Promise<string | null>) | undefined,\n logger: ILogger,\n): Promise<string | null> {\n if (!resolveRemote) return null;\n try {\n return await resolveRemote(identifier);\n } catch (error) {\n logger.warn(\n `Worker model sources: could not cache \"${identifier}\" from the registry: ${String(error)}`,\n );\n return null;\n }\n}\n\n/**\n * Absolute file path of a source's models barrel. Mirrors reactor-api's\n * import-resolver: import.meta.resolve, then the project's node_modules via\n * the package.json exports map / dist layout.\n */\nasync function resolveModelModuleFile(source: string): Promise<string | null> {\n if (isFsPath(source)) {\n return resolveFromPackageDir(source, \"./document-models\");\n }\n\n const specifier = BASE_MODEL_SPECIFIERS.includes(source)\n ? source\n : `${source}/document-models`;\n\n try {\n const resolved = import.meta.resolve(specifier);\n if (resolved.startsWith(\"file:\")) {\n return fileURLToPath(resolved);\n }\n } catch {\n // fall through to node_modules resolution from the project dir\n }\n\n const { packageName, subpath } = splitSpecifier(specifier);\n const packageDir = path.join(process.cwd(), \"node_modules\", packageName);\n if (!existsSync(packageDir)) {\n return null;\n }\n let realDir: string;\n try {\n realDir = realpathSync(packageDir);\n } catch {\n return null;\n }\n return resolveFromPackageDir(realDir, subpath);\n}\n\nfunction splitSpecifier(specifier: string): {\n packageName: string;\n subpath: string;\n} {\n const parts = specifier.split(\"/\");\n const packageSegments = specifier.startsWith(\"@\") ? 2 : 1;\n const packageName = parts.slice(0, packageSegments).join(\"/\");\n const rest = parts.slice(packageSegments).join(\"/\");\n return { packageName, subpath: rest ? `./${rest}` : \".\" };\n}\n\n/** Exports-map lookup (import condition), then conventional dist paths. */\nasync function resolveFromPackageDir(\n packageDir: string,\n subpath: string,\n): Promise<string | null> {\n const fromManifest = await resolveViaManifest(packageDir, subpath);\n if (fromManifest) {\n return fromManifest;\n }\n const candidates =\n subpath === \".\"\n ? [path.join(packageDir, \"dist\", \"index.js\")]\n : [\n path.join(packageDir, \"dist\", subpath.slice(2), \"index.js\"),\n path.join(packageDir, \"dist\", `${subpath.slice(2)}.js`),\n path.join(packageDir, subpath.slice(2), \"index.js\"),\n ];\n for (const candidate of candidates) {\n if (existsSync(candidate)) {\n return candidate;\n }\n }\n return null;\n}\n\nasync function resolveViaManifest(\n packageDir: string,\n subpath: string,\n): Promise<string | null> {\n let raw: string;\n try {\n raw = await readFile(path.join(packageDir, \"package.json\"), \"utf8\");\n } catch {\n return null;\n }\n let manifest: { exports?: unknown; main?: unknown };\n try {\n manifest = JSON.parse(raw) as { exports?: unknown; main?: unknown };\n } catch {\n return null;\n }\n\n let entry: unknown;\n const exportsField = manifest.exports;\n if (\n exportsField !== null &&\n typeof exportsField === \"object\" &&\n !Array.isArray(exportsField)\n ) {\n const map = exportsField as Record<string, unknown>;\n const hasSubpathKeys = Object.keys(map).some((key) => key.startsWith(\".\"));\n entry = hasSubpathKeys ? map[subpath] : subpath === \".\" ? map : undefined;\n } else if (typeof exportsField === \"string\" && subpath === \".\") {\n entry = exportsField;\n }\n\n let target = pickImportTarget(entry);\n if (!target && subpath === \".\" && typeof manifest.main === \"string\") {\n target = manifest.main;\n }\n if (!target) {\n return null;\n }\n const resolved = path.join(packageDir, target);\n return existsSync(resolved) ? resolved : null;\n}\n\nfunction pickImportTarget(entry: unknown): string | null {\n if (typeof entry === \"string\") {\n return entry;\n }\n if (typeof entry !== \"object\" || entry === null) {\n return null;\n }\n const conditions = entry as Record<string, unknown>;\n for (const condition of [\"import\", \"node\", \"default\"]) {\n const value = conditions[condition];\n if (typeof value === \"string\") {\n return value;\n }\n }\n return null;\n}\n\nfunction isFsPath(identifier: string): boolean {\n return (\n path.isAbsolute(identifier) ||\n identifier.startsWith(\"./\") ||\n identifier.startsWith(\"../\")\n );\n}\n\nexport function parseWorkerCount(\n raw: string | undefined,\n): WorkerCountInput | undefined {\n if (raw === undefined || raw.trim() === \"\") {\n return undefined;\n }\n if (raw.trim().toLowerCase() === \"auto\") {\n return \"auto\";\n }\n const value = Number.parseInt(raw, 10);\n if (!Number.isInteger(value) || value < 0 || String(value) !== raw.trim()) {\n throw new Error(\n `REACTOR_WORKERS must be \"auto\" or a non-negative integer, got \"${raw}\"`,\n );\n }\n return value;\n}\n"],"names":[],"mappings":";;;;;;;;;AAAA,SAAgB,oBACd,KACA,MACoB;CACpB,IAAI,QAAQ,KAAA,KAAa,IAAI,KAAK,MAAM,IACtC;CAEF,MAAM,QAAQ,OAAO,SAAS,KAAK,EAAE;CACrC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,OAAO,KAAK,MAAM,IAAI,KAAK,GACtE,MAAM,IAAI,MAAM,GAAG,KAAK,wCAAwC,IAAI,EAAE;CAExE,OAAO;AACT;;;;ACEA,SAAgB,eACd,QACA,KACoB;CACpB,OACE,UAAU,IAAI,2BAA2B,IAAI;AAEjD;AAEA,SAAgB,uBACd,OAIoB;CACpB,IACE,MAAM,UAA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OAAO,UAAU,YAAY,UAAU,MACzC,OAAO;CAET,MAAM,aAAa;CACnB,KAAK,MAAM,aAAa;EAAC;EAAU;EAAQ;CAAS,GAAG;EACrD,MAAM,QAAQ,WAAW;EACzB,IAAI,OAAO,UAAU,UACnB,OAAO;CAEX;CACA,OAAO;AACT;AAEA,SAAS,SAAS,YAA6B;CAC7C,OACE,KAAK,WAAW,UAAU,KAC1B,WAAW,WAAW,IAAI,KAC1B,WAAW,WAAW,KAAK;AAE/B;AAEA,SAAgB,iBACd,KAC8B;CAC9B,IAAI,QAAQ,KAAA,KAAa,IAAI,KAAK,MAAM,IACtC;CAEF,IAAI,IAAI,KAAK,CAAC,CAAC,YAAY,MAAM,QAC/B,OAAO;CAET,MAAM,QAAQ,OAAO,SAAS,KAAK,EAAE;CACrC,IAAI,CAAC,OAAO,UAAU,KAAK,KAAK,QAAQ,KAAK,OAAO,KAAK,MAAM,IAAI,KAAK,GACtE,MAAM,IAAI,MACR,kEAAkE,IAAI,EACxE;CAEF,OAAO;AACT","debug_id":"0abc3b7a-f473-50e3-9984-427c6dfd9263"}
@@ -1 +1 @@
1
- {"version":3,"file":"workflow-runtime-CF5pc8mt.d.mts","names":[],"sources":["../src/workflow-runtime.mts"],"mappings":";;;;;;;;;KAsEY;EACN;;EAEA;EACA;;KAgQD,yBAAyB,eAAe;UAE5B;EACf,UAAU;;;WAGD,UAAU;;;EAGnB;;EAEA,SAAS;EACT,SAAS;EACT,QAAQ"}
1
+ {"version":3,"file":"workflow-runtime-CF5pc8mt.d.mts","names":[],"sources":["../src/workflow-runtime.mts"],"mappings":";;;;;;;;;KAsEY;EACN;;EAEA;EACA;;KAiQD,yBAAyB,eAAe;UAE5B;EACf,UAAU;;;WAGD,UAAU;;;EAGnB;;EAEA,SAAS;EACT,SAAS;EACT,QAAQ"}
@@ -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]="9e2323f5-5df7-5067-8ab5-48736bf1f120")}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]="304dba06-3911-5948-9cf8-15b64e59b7b1")}catch(e){}}();
3
3
  import { REACTOR_SCHEMA, supportsLiveReadModelRegistration } from "@powerhousedao/reactor";
4
4
  import { AuthorizationPolicy, BaseSubgraph, ForbiddenError, callerSubject, createCanonicalDocumentIdResolver } from "@powerhousedao/reactor-api";
5
5
  import { hostname } from "node:os";
@@ -10,6 +10,19 @@ import { GraphQLError, Kind } from "graphql";
10
10
  import { gql } from "graphql-tag";
11
11
  //#region src/fatal-shutdown.mts
12
12
  const FORCED_EXIT_MS = 15e3;
13
+ /**
14
+ * Starts the shutdown that SIGTERM's listeners run. Windows has no signals:
15
+ * `kill` there ends the process at once, stores open, so the listeners are
16
+ * called directly. False when nothing is listening.
17
+ */
18
+ function raiseSigterm(proc = process) {
19
+ if (proc.platform === "win32") return proc.emit("SIGTERM", "SIGTERM");
20
+ return proc.kill(proc.pid, "SIGTERM");
21
+ }
22
+ /** A write to a stdout or stderr that nobody reads any more. */
23
+ function isClosedPipe(err) {
24
+ return err?.code === "EPIPE";
25
+ }
13
26
  const fatalHandlers = /* @__PURE__ */ new WeakMap();
14
27
  /**
15
28
  * Sends an uncaught exception or unhandled rejection through the SIGTERM
@@ -42,6 +55,7 @@ function installFatalErrorShutdown(logger, proc = process) {
42
55
  } catch {}
43
56
  };
44
57
  const onFatal = (kind, err) => {
58
+ if (shuttingDown && isClosedPipe(err)) return;
45
59
  logFatal(`${kind}: @error`, err);
46
60
  if (shuttingDown) return;
47
61
  shuttingDown = true;
@@ -50,7 +64,7 @@ function installFatalErrorShutdown(logger, proc = process) {
50
64
  logFatal("Shutdown after fatal error timed out; exiting");
51
65
  realExit(1);
52
66
  }, FORCED_EXIT_MS).unref();
53
- proc.kill(proc.pid, "SIGTERM");
67
+ if (!raiseSigterm(proc)) realExit(1);
54
68
  };
55
69
  fatalHandlers.set(proc, onFatal);
56
70
  proc.on("uncaughtException", (err) => onFatal("Uncaught exception", err));
@@ -1592,8 +1606,13 @@ function reactorAccessOf(clientModule) {
1592
1606
  * the host's too: the request's caller is the host's signed-in address. A
1593
1607
  * host with no signed-in identity reads anonymously, which the
1594
1608
  * authenticated-caller floor refuses as it would an anonymous HTTP request.
1609
+ *
1610
+ * A caller the policy gives no rows is refused here. The index would answer it
1611
+ * with nothing, which a piece cannot tell from "nothing exists", and an upsert
1612
+ * would then create a duplicate of everything: a granter who left ADMINS must
1613
+ * stop a run, not double its documents.
1595
1614
  */
1596
- function indexQueryFor(manager, clientModule) {
1615
+ function indexQueryFor(manager, clientModule, authorization) {
1597
1616
  const signer = clientModule?.signer;
1598
1617
  const host = signer?.user;
1599
1618
  const hostKey = signer?.app?.key ?? "";
@@ -1611,6 +1630,10 @@ function indexQueryFor(manager, clientModule) {
1611
1630
  networkId,
1612
1631
  appKey: hostKey
1613
1632
  } : void 0;
1633
+ if (authorization?.config.policy === AuthorizationPolicy.ADMIN_ONLY && !authorization.isSupremeAdmin(user?.address)) return {
1634
+ data: null,
1635
+ errors: [{ message: user ? `Forbidden: ${user.address} is not an admin of this host, so it reads no index` : "Forbidden: this run has no person behind it, so it reads no index" }]
1636
+ };
1614
1637
  const result = await manager.executeSubgraph(request.subgraph, {
1615
1638
  query: request.query,
1616
1639
  variables: request.variables,
@@ -1707,6 +1730,7 @@ async function composeWorkflowRuntime(deps) {
1707
1730
  logger: deps.logger,
1708
1731
  ...deps.storageId ? { storageId: deps.storageId } : {},
1709
1732
  selfFence: deps.exclusiveJournal !== true,
1733
+ exclusive: deps.exclusiveJournal === true,
1710
1734
  onLost: (lost) => {
1711
1735
  loss.lost = true;
1712
1736
  if (lost.reason === "taken") loss.heldBy = lost.heldBy;
@@ -1745,7 +1769,7 @@ async function composeClaimed(engine, deps, lease, loss) {
1745
1769
  ...deps.clientModule?.reactorModule ? { authEnforcement: access.authEnforcement } : {},
1746
1770
  hostPrincipal: hostPrincipalOf(access),
1747
1771
  hostIdentity: hostIdentityOf(access),
1748
- ...deps.indexQueries ? { queryIndex: indexQueryFor(deps.indexQueries, deps.clientModule) } : {},
1772
+ ...deps.indexQueries ? { queryIndex: indexQueryFor(deps.indexQueries, deps.clientModule, deps.authorizationService) } : {},
1749
1773
  ...models ? {
1750
1774
  modelManifest: () => models.modelManifest(),
1751
1775
  modelEntries: (documentType) => models.modelEntries(documentType)
@@ -1913,7 +1937,7 @@ function createWorkflowsPlugin(rawConfig = {}) {
1913
1937
  /** The default-config instance: the built-in composition's entry. */
1914
1938
  const workflowsPlugin = createWorkflowsPlugin({});
1915
1939
  //#endregion
1916
- export { workflowsPlugin as a, WORKFLOW_TELEMETRY_SCOPE as c, isWorkflowSingletonConflict as d, modelManifestSource as f, triggerFatalShutdown as g, installFatalErrorShutdown as h, workflowsDriveDeclaration as i, assertWorkflowPackageLoadable as l, workflowSingletonLossHandler as m, WORKFLOW_STUDIO_EDITOR_ID as n, workflowsPluginConfigSchema as o, retryWorkflowSingleton as p, createWorkflowsPlugin as r, WORKFLOW_PACKAGE_NAME as s, DEFAULT_WORKFLOWS_DRIVE as t, composeWorkflowRuntime as u };
1940
+ export { triggerFatalShutdown as _, workflowsPlugin as a, WORKFLOW_TELEMETRY_SCOPE as c, isWorkflowSingletonConflict as d, modelManifestSource as f, raiseSigterm as g, installFatalErrorShutdown as h, workflowsDriveDeclaration as i, assertWorkflowPackageLoadable as l, workflowSingletonLossHandler as m, WORKFLOW_STUDIO_EDITOR_ID as n, workflowsPluginConfigSchema as o, retryWorkflowSingleton as p, createWorkflowsPlugin as r, WORKFLOW_PACKAGE_NAME as s, DEFAULT_WORKFLOWS_DRIVE as t, composeWorkflowRuntime as u };
1917
1941
 
1918
- //# sourceMappingURL=workflows-krankcQT.mjs.map
1919
- //# debugId=9e2323f5-5df7-5067-8ab5-48736bf1f120
1942
+ //# sourceMappingURL=workflows-C9BQlyT0.mjs.map
1943
+ //# debugId=304dba06-3911-5948-9cf8-15b64e59b7b1