@powerhousedao/reactor-api 6.2.3-dev.10 → 6.2.3-dev.101

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 (68) hide show
  1. package/README.md +7 -2
  2. package/dist/{adapter-gateway-apollo-CxJNBVyD.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +23 -23
  3. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
  4. package/dist/{adapter-gateway-mercurius-CZVy88Za.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +4 -12
  5. package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
  6. package/dist/{adapter-http-express-B39rPhqH.mjs → adapter-http-express-78KD77cI.mjs} +11 -11
  7. package/dist/adapter-http-express-78KD77cI.mjs.map +1 -0
  8. package/dist/{adapter-http-fastify-BwXO6rqE.mjs → adapter-http-fastify-Dk7aT_xw.mjs} +14 -13
  9. package/dist/adapter-http-fastify-Dk7aT_xw.mjs.map +1 -0
  10. package/dist/base-document-models-caJpqTLw.mjs +2083 -0
  11. package/dist/base-document-models-caJpqTLw.mjs.map +1 -0
  12. package/dist/create-schema-BCArFBv9.d.mts +167 -0
  13. package/dist/create-schema-BCArFBv9.d.mts.map +1 -0
  14. package/dist/error-info-Cr6oQACe.mjs +601 -0
  15. package/dist/error-info-Cr6oQACe.mjs.map +1 -0
  16. package/dist/index.d.mts +3180 -1021
  17. package/dist/index.d.mts.map +1 -1
  18. package/dist/index.mjs +7197 -2728
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/package-subgraph-check-BxKx9kcQ.mjs +138 -0
  21. package/dist/package-subgraph-check-BxKx9kcQ.mjs.map +1 -0
  22. package/dist/pglite-like-CKQEL_Q0.d.mts +27 -0
  23. package/dist/pglite-like-CKQEL_Q0.d.mts.map +1 -0
  24. package/dist/pglite-node-CcX2YT-l.mjs +744 -0
  25. package/dist/pglite-node-CcX2YT-l.mjs.map +1 -0
  26. package/dist/rolldown-runtime-8H4AJuhK.mjs +16 -0
  27. package/dist/run-node-handler-CQjyjOuN.mjs +52 -0
  28. package/dist/run-node-handler-CQjyjOuN.mjs.map +1 -0
  29. package/dist/src/graphql/subgraph-types.d.mts +43 -0
  30. package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
  31. package/dist/src/graphql/subgraph-types.mjs +14 -0
  32. package/dist/src/graphql/subgraph-types.mjs.map +1 -0
  33. package/dist/src/packages/https-hooks.d.mts +4 -4
  34. package/dist/src/packages/https-hooks.d.mts.map +1 -1
  35. package/dist/src/packages/https-hooks.mjs +2 -2
  36. package/dist/src/packages/https-hooks.mjs.map +1 -1
  37. package/dist/src/packages/vite-loader.d.mts +30 -9
  38. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  39. package/dist/src/packages/vite-loader.mjs +205 -85
  40. package/dist/src/packages/vite-loader.mjs.map +1 -1
  41. package/dist/src/pglite/pglite-node.d.mts +434 -0
  42. package/dist/src/pglite/pglite-node.d.mts.map +1 -0
  43. package/dist/src/pglite/pglite-node.mjs +5 -0
  44. package/dist/src/pglite/worker/entry.d.mts +2 -0
  45. package/dist/src/pglite/worker/entry.mjs +298 -0
  46. package/dist/src/pglite/worker/entry.mjs.map +1 -0
  47. package/dist/subgraph-extraction-C_hFvSaS.mjs +1884 -0
  48. package/dist/subgraph-extraction-C_hFvSaS.mjs.map +1 -0
  49. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs +10 -0
  50. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs.map +1 -0
  51. package/dist/types-Bz_xjf8j.d.mts +105 -0
  52. package/dist/types-Bz_xjf8j.d.mts.map +1 -0
  53. package/package.json +39 -26
  54. package/dist/adapter-gateway-apollo-CxJNBVyD.mjs.map +0 -1
  55. package/dist/adapter-gateway-apollo-DowrX6E_.mjs +0 -4
  56. package/dist/adapter-gateway-mercurius-CZVy88Za.mjs.map +0 -1
  57. package/dist/adapter-gateway-stitching-CaZjvRzx.mjs +0 -316
  58. package/dist/adapter-gateway-stitching-CaZjvRzx.mjs.map +0 -1
  59. package/dist/adapter-http-express-B39rPhqH.mjs.map +0 -1
  60. package/dist/adapter-http-fastify-BwXO6rqE.mjs.map +0 -1
  61. package/dist/path-normalize-BOQwY9wR.mjs +0 -23
  62. package/dist/path-normalize-BOQwY9wR.mjs.map +0 -1
  63. package/dist/types-DcYyNcHJ.d.mts +0 -48
  64. package/dist/types-DcYyNcHJ.d.mts.map +0 -1
  65. package/dist/utils-XWVecaNn.mjs +0 -653
  66. package/dist/utils-XWVecaNn.mjs.map +0 -1
  67. package/dist/websocket-DncAB9XK.mjs +0 -18
  68. package/dist/websocket-DncAB9XK.mjs.map +0 -1
@@ -0,0 +1,1884 @@
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]="1629639f-53d5-56ba-9006-abc2cb9963c0")}catch(e){}}();
3
+ import { createRequire } from "node:module";
4
+ import { childLogger } from "document-model";
5
+ import { gql } from "graphql-tag";
6
+ import { GraphQLError } from "graphql";
7
+ import { DRIVE_AUTH_ERROR_MESSAGES, DocumentChangeType, RECOVERABLE_GRAPHQL_ERROR_CODES } from "@powerhousedao/reactor";
8
+ import { PURGE_DOCUMENT } from "@powerhousedao/shared/document-model";
9
+ import { hashNamespace } from "@powerhousedao/shared/processors";
10
+ import { sql } from "kysely";
11
+ import { verifyAuthBearerToken } from "@renown/sdk";
12
+ import { AsyncLocalStorage } from "node:async_hooks";
13
+ import path, { dirname, isAbsolute, join } from "node:path";
14
+ import { existsSync, readFileSync } from "node:fs";
15
+ import { isScalarDefinition, scalarDefinitionVersion } from "document-model/scalars";
16
+ import { fileURLToPath, pathToFileURL } from "node:url";
17
+ import { packageJsonExports } from "@powerhousedao/shared/clis/constants";
18
+ //#region src/graphql/errors.ts
19
+ /** Caller (authenticated or anonymous) lacks permission for the document. */
20
+ var ForbiddenError = class extends GraphQLError {
21
+ constructor(detail = "") {
22
+ const base = DRIVE_AUTH_ERROR_MESSAGES.forbidden;
23
+ super(`${base}${detail ? ` ${detail}` : ""}`, { extensions: { code: "FORBIDDEN" } });
24
+ }
25
+ };
26
+ /** Anonymous caller on an action that requires logging in. */
27
+ var AuthenticationRequiredError = class extends GraphQLError {
28
+ constructor(detail = "") {
29
+ const base = DRIVE_AUTH_ERROR_MESSAGES.authenticationRequired;
30
+ super(`${base}${detail ? ` ${detail}` : ""}`, { extensions: { code: "UNAUTHENTICATED" } });
31
+ }
32
+ };
33
+ /**
34
+ * The reactor holds no decision model, so no authorization preflight can be
35
+ * answered.
36
+ *
37
+ * Distinct from a denial, and deliberately so: a caller that cannot get a
38
+ * prediction should render its controls as it did before it asked and let the
39
+ * submit path refuse. Reading this as a denial would disable every control on a
40
+ * switchboard running without authEnforcement. The code is what a client
41
+ * branches on, since the message is not a contract.
42
+ */
43
+ var AuthEvaluationUnsupportedError = class extends GraphQLError {
44
+ constructor() {
45
+ super("Authorization evaluation is unavailable: this reactor runs without the authEnforcement feature flag, so it holds no decision model", { extensions: { code: "AUTH_EVALUATION_UNSUPPORTED" } });
46
+ }
47
+ };
48
+ /**
49
+ * A stored operation cannot be represented in the schema, so it is reported
50
+ * rather than served.
51
+ *
52
+ * The schema declares an action's id, type, timestamp, input and scope
53
+ * non-null; an operation written before the API rejected an action without an
54
+ * id violates that. Left to the executor, the missing value nullifies the
55
+ * action, which bubbles up through the non-null chain until it nullifies the
56
+ * envelope's whole operation list, and the caller receives a partial response
57
+ * beside "Cannot return null for non-nullable field Action.id" - which says
58
+ * nothing about which operation, and which a sync client can only read as a
59
+ * permanent GraphQL rejection, stopping its poll timer for good.
60
+ *
61
+ * Thrown instead, with a code that says the failure is worth polling through:
62
+ * the document holding the operation needs repairing, but the channel serves
63
+ * every other document, and a peer that stopped polling would stop receiving
64
+ * those too. The code is what a client branches on, since the message is not a
65
+ * contract.
66
+ */
67
+ var MalformedStoredOperationError = class extends GraphQLError {
68
+ constructor(detail) {
69
+ super(`Stored operation cannot be served: ${detail}`, { extensions: { code: RECOVERABLE_GRAPHQL_ERROR_CODES.malformedStoredOperation } });
70
+ }
71
+ };
72
+ /**
73
+ * The marker refusals a poll carried were not recorded, so the poll fails.
74
+ * The code is recoverable: the client keeps polling and reports them again.
75
+ */
76
+ var RefusalNotRecordedError = class extends GraphQLError {
77
+ constructor(cause) {
78
+ super("A reported marker refusal was not recorded; report it again", {
79
+ originalError: cause instanceof Error ? cause : new Error(String(cause)),
80
+ extensions: { code: RECOVERABLE_GRAPHQL_ERROR_CODES.refusalNotRecorded }
81
+ });
82
+ }
83
+ };
84
+ //#endregion
85
+ //#region src/services/authorization.service.ts
86
+ /**
87
+ * Result of a passed per-document authorization check. `fetchIdentifier` is
88
+ * always safe for the data fetch: the canonical id when resolved, or the raw
89
+ * identifier when the check was skipped for a policy-wide caller.
90
+ */
91
+ var AuthorizedDocumentHandle = class AuthorizedDocumentHandle {
92
+ fetchIdentifier;
93
+ isResolved;
94
+ constructor(fetchIdentifier, isResolved) {
95
+ this.fetchIdentifier = fetchIdentifier;
96
+ this.isResolved = isResolved;
97
+ }
98
+ static resolved(documentId) {
99
+ return new AuthorizedDocumentHandle(documentId, true);
100
+ }
101
+ static skipped(identifier) {
102
+ return new AuthorizedDocumentHandle(identifier, false);
103
+ }
104
+ /** The verified canonical id; throws when resolution was skipped. */
105
+ canonicalId() {
106
+ if (!this.isResolved) throw new Error("Canonical document id is unavailable: the authorization check was skipped for a policy-wide caller");
107
+ return this.fetchIdentifier;
108
+ }
109
+ };
110
+ const AuthorizationPolicy = {
111
+ OPEN: "OPEN",
112
+ ADMIN_ONLY: "ADMIN_ONLY",
113
+ DOCUMENT_PERMISSIONS: "DOCUMENT_PERMISSIONS"
114
+ };
115
+ /** Shared config holder and admin-list check for the policy strategies. */
116
+ var BaseAuthorizationService = class {
117
+ config;
118
+ constructor(config) {
119
+ this.config = config;
120
+ }
121
+ isSupremeAdmin(userAddress) {
122
+ if (!userAddress) return false;
123
+ return this.config.admins.includes(userAddress.toLowerCase());
124
+ }
125
+ };
126
+ /** OPEN: authentication disabled — everyone (incl. anonymous) is allowed. */
127
+ var OpenAuthorizationService = class extends BaseAuthorizationService {
128
+ isSupremeAdmin() {
129
+ return true;
130
+ }
131
+ canCreate() {
132
+ return true;
133
+ }
134
+ canRead() {
135
+ return Promise.resolve(true);
136
+ }
137
+ canWrite() {
138
+ return Promise.resolve(true);
139
+ }
140
+ canManage() {
141
+ return Promise.resolve(true);
142
+ }
143
+ canMutate() {
144
+ return Promise.resolve(true);
145
+ }
146
+ };
147
+ /** ADMIN_ONLY: authentication on, document permissions off — only ADMINS. */
148
+ var AdminOnlyAuthorizationService = class extends BaseAuthorizationService {
149
+ canCreate(userAddress) {
150
+ return this.isSupremeAdmin(userAddress);
151
+ }
152
+ canRead(_documentId, userAddress) {
153
+ return Promise.resolve(this.isSupremeAdmin(userAddress));
154
+ }
155
+ canWrite(_documentId, userAddress) {
156
+ return Promise.resolve(this.isSupremeAdmin(userAddress));
157
+ }
158
+ canManage(_documentId, userAddress) {
159
+ return Promise.resolve(this.isSupremeAdmin(userAddress));
160
+ }
161
+ canMutate(_documentId, _operationType, userAddress) {
162
+ return Promise.resolve(this.isSupremeAdmin(userAddress));
163
+ }
164
+ };
165
+ const PERMISSION_RANK = {
166
+ READ: 1,
167
+ WRITE: 2,
168
+ ADMIN: 3
169
+ };
170
+ function satisfies(level, required) {
171
+ return level !== null && PERMISSION_RANK[level] >= PERMISSION_RANK[required];
172
+ }
173
+ /**
174
+ * DOCUMENT_PERMISSIONS: the full per-document protection + grant model.
175
+ *
176
+ * All decisions live here; DocumentPermissionService is the data-access
177
+ * layer underneath (grants, protection rows, owners).
178
+ */
179
+ var DocumentPermissionsAuthorizationService = class extends BaseAuthorizationService {
180
+ #permissions;
181
+ #getParentIds;
182
+ constructor(permissions, getParentIds, config) {
183
+ super(config);
184
+ this.#permissions = permissions;
185
+ this.#getParentIds = getParentIds;
186
+ }
187
+ canCreate(userAddress) {
188
+ return this.isSupremeAdmin(userAddress) || !!userAddress;
189
+ }
190
+ canRead(documentId, userAddress) {
191
+ return this.#canAccess(documentId, "READ", userAddress);
192
+ }
193
+ canWrite(documentId, userAddress) {
194
+ return this.#canAccess(documentId, "WRITE", userAddress);
195
+ }
196
+ canManage(documentId, userAddress) {
197
+ return this.#isDocumentAdmin(documentId, userAddress);
198
+ }
199
+ async canMutate(documentId, operationType, userAddress) {
200
+ if (this.isSupremeAdmin(userAddress)) return true;
201
+ if (operationType === PURGE_DOCUMENT) return this.#isDocumentAdmin(documentId, userAddress);
202
+ if (await this.#permissions.isOperationRestricted(documentId, operationType)) {
203
+ if (!userAddress) return false;
204
+ if (await this.#isDocumentAdmin(documentId, userAddress)) return true;
205
+ return this.#permissions.hasOperationGrant(documentId, operationType, userAddress);
206
+ }
207
+ return this.#canAccess(documentId, "WRITE", userAddress);
208
+ }
209
+ /**
210
+ * The one "administers this document" predicate: supreme admin, document
211
+ * owner, or ADMIN grant on the document itself.
212
+ */
213
+ async #isDocumentAdmin(documentId, userAddress) {
214
+ if (this.isSupremeAdmin(userAddress)) return true;
215
+ if (!userAddress) return false;
216
+ const owner = await this.#permissions.getDocumentOwner(documentId);
217
+ if (owner && owner === userAddress.toLowerCase()) return true;
218
+ return satisfies(await this.#grantLevel(documentId, userAddress), "ADMIN");
219
+ }
220
+ /**
221
+ * The one read/write decision shape: supreme admin → unprotected (self or
222
+ * ancestor) → owner → inherited grant of at least the required level.
223
+ */
224
+ async #canAccess(documentId, required, userAddress) {
225
+ if (this.isSupremeAdmin(userAddress)) return true;
226
+ if (!await this.#permissions.isProtectedWithAncestors(documentId, this.#getParentIds)) return true;
227
+ if (!userAddress) return false;
228
+ const owner = await this.#permissions.getDocumentOwner(documentId);
229
+ if (owner && owner === userAddress.toLowerCase()) return true;
230
+ return this.#hasGrantInHierarchy(documentId, userAddress, required);
231
+ }
232
+ /** Best grant the user holds on the document. */
233
+ async #grantLevel(documentId, userAddress) {
234
+ return this.#permissions.getUserPermission(documentId, userAddress);
235
+ }
236
+ /**
237
+ * Walks the parent hierarchy (with cycle protection) looking for a grant of
238
+ * at least the required level on the document or any ancestor.
239
+ */
240
+ async #hasGrantInHierarchy(documentId, userAddress, required) {
241
+ const visited = /* @__PURE__ */ new Set();
242
+ const queue = [documentId];
243
+ while (queue.length > 0) {
244
+ const current = queue.shift();
245
+ if (visited.has(current)) continue;
246
+ visited.add(current);
247
+ if (satisfies(await this.#grantLevel(current, userAddress), required)) return true;
248
+ for (const parentId of await this.#getParentIds(current)) if (!visited.has(parentId)) queue.push(parentId);
249
+ }
250
+ return false;
251
+ }
252
+ };
253
+ /**
254
+ * Selects the strategy for the configured policy. The strategy classes are
255
+ * not exported, so this guard is the only construction path.
256
+ */
257
+ function createAuthorizationService(config, documentPermissionService, getParentIds) {
258
+ if (config.policy === AuthorizationPolicy.OPEN) return new OpenAuthorizationService(config);
259
+ if (config.policy === AuthorizationPolicy.ADMIN_ONLY) return new AdminOnlyAuthorizationService(config);
260
+ if (!documentPermissionService) throw new Error("DocumentPermissionService is required for the DOCUMENT_PERMISSIONS policy");
261
+ if (!getParentIds) throw new Error("A getParentIds resolver is required for the DOCUMENT_PERMISSIONS policy");
262
+ return new DocumentPermissionsAuthorizationService(documentPermissionService, getParentIds, config);
263
+ }
264
+ //#endregion
265
+ //#region src/services/canonical-document-id.ts
266
+ /**
267
+ * Raised when a caller-supplied identifier cannot be resolved to a canonical
268
+ * document id. Carries no detail on purpose: resolution failures must not act
269
+ * as a document-existence oracle, so consumers map this to their generic
270
+ * fail-closed response.
271
+ */
272
+ var CanonicalDocumentIdResolutionError = class extends Error {
273
+ constructor() {
274
+ super("Document identifier could not be resolved");
275
+ this.name = "CanonicalDocumentIdResolutionError";
276
+ }
277
+ };
278
+ /**
279
+ * The sanctioned string-to-CanonicalDocumentId cast: both the GraphQL layer
280
+ * and server routes must resolve caller identifiers through this helper so
281
+ * decision and data layers always agree on the subject document.
282
+ *
283
+ * Queries and subscriptions resolve on the read half (`resolveIdOrSlug`, the
284
+ * lookup their data fetch makes); mutations on the write half (`describe`, the
285
+ * lookup their write makes). A bare read client (or the facade, whose
286
+ * `write` is then used) is accepted as the read half.
287
+ */
288
+ function createCanonicalDocumentIdResolver(clients, operationType = "query") {
289
+ const pair = "resolveIdOrSlug" in clients ? {
290
+ read: clients,
291
+ write: clients.write
292
+ } : clients;
293
+ if (operationType === "mutation" && !pair.write) throw new Error("A mutation resolves identifiers on the write half; none was given");
294
+ return async (identifier) => {
295
+ let resolved;
296
+ try {
297
+ resolved = operationType === "mutation" ? (await pair.write.describe(identifier)).documentId : await pair.read.resolveIdOrSlug(identifier);
298
+ } catch {
299
+ throw new CanonicalDocumentIdResolutionError();
300
+ }
301
+ return resolved;
302
+ };
303
+ }
304
+ //#endregion
305
+ //#region src/services/readable-documents.ts
306
+ /**
307
+ * The read-permission closure as a read model: `readable_documents(user_id,
308
+ * document_id)` in the processors' relational database, so an index subgraph
309
+ * decides "may the caller see this row" with one join instead of one
310
+ * authorization call per row.
311
+ *
312
+ * It is a projection of the host's own permission data, never an authority:
313
+ * the write path keeps deciding from the permission tables in the reactor
314
+ * store (`IAuthorizationService`), and nothing here is consulted for a
315
+ * write. The projection mirrors four small facts into its own namespace,
316
+ * documents, `child` edges, protection and grants, and recomputes the
317
+ * closure from them in one SQL statement whenever one of them changes:
318
+ *
319
+ * - `'*'` for a document that is unprotected along its whole ancestor chain
320
+ * (everyone may read it; `DEFAULT_PROTECTION` fills a missing row),
321
+ * - the owner of a protected document,
322
+ * - every holder of a grant on the document or any ancestor (READ is the
323
+ * floor, so any level counts).
324
+ *
325
+ * Listed admins are a bypass, never rows. Under OPEN everyone reads
326
+ * everything and under ADMIN_ONLY only admins read, so the projection keeps
327
+ * no rows for those policies; `filterFor` answers from the policy alone.
328
+ *
329
+ * Kept current by the permission service's change notifications and the
330
+ * reactor's document and relationship change events; rebuilt from the
331
+ * reactor and the permission service at start. Eventually consistent, no
332
+ * worse than the permission cache's TTL. The document's own `state.auth`
333
+ * policy (the reactor's read gate under `authEnforcement`) is not projected
334
+ * here; a subgraph that must honour it keeps the per-document reactor check.
335
+ */
336
+ const READABLE_DOCUMENTS_NAMESPACE = "ph_readable_documents";
337
+ /** The `user_id` that stands for every caller, anonymous included. */
338
+ const EVERYONE = "*";
339
+ /** Document types that root the `child` hierarchy: drives. */
340
+ const DEFAULT_ROOT_TYPES = ["powerhouse/document-drive", "powerhouse/reactor-drive"];
341
+ /**
342
+ * `select document_id from <schema>.readable_documents where user_id in
343
+ * (:user, '*')`, for a `where document_id in (...)` on an index table.
344
+ */
345
+ function readableDocumentsSubquery(filter) {
346
+ return sql`(select document_id from ${sql.table(`${filter.schema}.readable_documents`)} where user_id in (${filter.userId}, ${"*"}))`;
347
+ }
348
+ /**
349
+ * Applies a caller's filter to a query over a document-keyed index table:
350
+ * unchanged for `all`, no row for `none`, `where <column> in (readable ids)`
351
+ * for `ids`. `column` is the table's document id column, qualified when the
352
+ * query joins.
353
+ */
354
+ function applyReadableFilter(query, column, filter, options = {}) {
355
+ const pass = options.passWhen ? sql`${sql.ref(options.passWhen.column)} = ${options.passWhen.equals}` : void 0;
356
+ switch (filter.kind) {
357
+ case "all": return query;
358
+ case "none": return query.where(pass ?? sql`false`);
359
+ case "ids": {
360
+ const listed = sql`${sql.ref(column)} in ${readableDocumentsSubquery(filter)}`;
361
+ return query.where(pass ? sql`(${listed} or ${pass})` : listed);
362
+ }
363
+ }
364
+ }
365
+ /**
366
+ * Whether `filter` lists one document: the scope gate of an index query (its
367
+ * drive or folder), asked of the same rows the row filter joins on.
368
+ */
369
+ async function isDocumentListed(db, filter, documentId) {
370
+ switch (filter.kind) {
371
+ case "all": return true;
372
+ case "none": return false;
373
+ case "ids": return (await sql`select 1 as listed from ${sql.table(`${filter.schema}.readable_documents`)} where document_id = ${documentId} and user_id in (${filter.userId}, ${"*"}) limit 1`.execute(db)).rows.length > 0;
374
+ }
375
+ }
376
+ var ReadableDocumentsProjection = class {
377
+ schema;
378
+ ready;
379
+ #deps;
380
+ #maintained;
381
+ #db;
382
+ #resolveReady;
383
+ #rejectReady;
384
+ #unsubscribe;
385
+ #timer;
386
+ #chain = Promise.resolve();
387
+ #pending = false;
388
+ #stopped = false;
389
+ constructor(deps) {
390
+ this.#deps = deps;
391
+ this.schema = hashNamespace(READABLE_DOCUMENTS_NAMESPACE);
392
+ this.#maintained = deps.config.policy === AuthorizationPolicy.DOCUMENT_PERMISSIONS && deps.permissions !== void 0;
393
+ this.ready = new Promise((resolve, reject) => {
394
+ this.#resolveReady = resolve;
395
+ this.#rejectReady = reject;
396
+ });
397
+ this.ready.catch(() => void 0);
398
+ }
399
+ /** Creates the tables, rebuilds the closure, and follows changes. */
400
+ async start() {
401
+ if (!this.#maintained) {
402
+ this.#resolveReady();
403
+ return;
404
+ }
405
+ try {
406
+ const db = await this.#deps.relationalDb.createNamespace(READABLE_DOCUMENTS_NAMESPACE);
407
+ this.#db = db;
408
+ await this.#ensureTables(db);
409
+ this.#unsubscribe = this.#deps.read.subscribe({}, (event) => {
410
+ this.#onDocumentChange(event).catch((error) => {
411
+ this.#deps.logger?.warn("readable-documents: a change could not be applied: @error", error);
412
+ });
413
+ });
414
+ this.#unsubscribePermissions = this.#deps.permissions.onChange((documentId) => {
415
+ this.#onPermissionChange(documentId).catch((error) => {
416
+ this.#deps.logger?.warn("readable-documents: a permission change could not be applied: @error", error);
417
+ });
418
+ });
419
+ await this.rebuild();
420
+ this.#resolveReady();
421
+ } catch (error) {
422
+ this.#rejectReady(error);
423
+ throw error;
424
+ }
425
+ }
426
+ #unsubscribePermissions;
427
+ async stop() {
428
+ this.#stopped = true;
429
+ this.#unsubscribe?.();
430
+ this.#unsubscribePermissions?.();
431
+ if (this.#timer) clearTimeout(this.#timer);
432
+ await this.#chain;
433
+ }
434
+ filterFor(userAddress) {
435
+ const address = userAddress?.toLowerCase();
436
+ const { policy, admins } = this.#deps.config;
437
+ if (policy === AuthorizationPolicy.OPEN) return { kind: "all" };
438
+ const admin = address !== void 0 && admins.includes(address);
439
+ if (policy === AuthorizationPolicy.ADMIN_ONLY) return admin ? { kind: "all" } : { kind: "none" };
440
+ if (admin) return { kind: "all" };
441
+ if (!this.#db || !this.#isReady) return { kind: "none" };
442
+ return {
443
+ kind: "ids",
444
+ schema: this.schema,
445
+ userId: address ?? "*"
446
+ };
447
+ }
448
+ #isReady = false;
449
+ /**
450
+ * Rebuilds the mirrors from the reactor and the permission service, then
451
+ * recomputes the closure. Serialised with the incremental updates.
452
+ */
453
+ rebuild() {
454
+ return this.#enqueue(async () => {
455
+ const db = this.#db;
456
+ const pageSize = this.#deps.pageSize ?? 500;
457
+ const ids = await this.#allDocumentIds(pageSize);
458
+ const edges = await this.#allEdges(pageSize);
459
+ const snapshots = await this.#snapshotsOf(ids, pageSize);
460
+ await db.transaction().execute(async (trx) => {
461
+ await trx.deleteFrom("documents").execute();
462
+ await trx.deleteFrom("edges").execute();
463
+ await trx.deleteFrom("protection").execute();
464
+ await trx.deleteFrom("grants").execute();
465
+ for (const chunk of chunks(ids, pageSize)) await trx.insertInto("documents").values(chunk.map((document_id) => ({ document_id }))).execute();
466
+ for (const chunk of chunks(edges, pageSize)) await trx.insertInto("edges").values(chunk).execute();
467
+ const protection = [...snapshots.values()].map((s) => ({
468
+ document_id: s.documentId,
469
+ protected: s.isProtected,
470
+ owner_id: s.ownerAddress
471
+ }));
472
+ for (const chunk of chunks(protection, pageSize)) await trx.insertInto("protection").values(chunk).execute();
473
+ const grants = [...snapshots.values()].flatMap((s) => [...s.grants.keys()].map((user_id) => ({
474
+ document_id: s.documentId,
475
+ user_id
476
+ })));
477
+ for (const chunk of chunks(grants, pageSize)) await trx.insertInto("grants").values(chunk).execute();
478
+ await this.#recompute(trx);
479
+ });
480
+ this.#isReady = true;
481
+ this.#deps.logger?.info(`readable-documents: rebuilt (${ids.length} documents, ${edges.length} edges, ${snapshots.size} protected or granted)`);
482
+ });
483
+ }
484
+ async #onDocumentChange(event) {
485
+ const db = this.#db;
486
+ if (!db || this.#stopped) return;
487
+ const ids = event.documents.map((d) => d.header.id);
488
+ switch (event.type) {
489
+ case DocumentChangeType.Created: {
490
+ const snapshots = await this.#snapshotsOf(ids, ids.length || 1);
491
+ await this.#enqueue(async () => {
492
+ for (const document_id of ids) await db.insertInto("documents").values({ document_id }).onConflict((oc) => oc.column("document_id").doNothing()).execute();
493
+ await this.#applySnapshots(db, snapshots);
494
+ });
495
+ break;
496
+ }
497
+ case DocumentChangeType.Deleted:
498
+ await this.#enqueue(async () => {
499
+ for (const id of ids) {
500
+ await db.deleteFrom("documents").where("document_id", "=", id).execute();
501
+ await db.deleteFrom("edges").where((eb) => eb.or([eb("parent_id", "=", id), eb("child_id", "=", id)])).execute();
502
+ await db.deleteFrom("protection").where("document_id", "=", id).execute();
503
+ await db.deleteFrom("grants").where("document_id", "=", id).execute();
504
+ }
505
+ });
506
+ break;
507
+ case DocumentChangeType.ChildAdded:
508
+ case DocumentChangeType.ParentAdded: {
509
+ const edge = edgeOf(event);
510
+ if (!edge) return;
511
+ await this.#enqueue(async () => {
512
+ await db.insertInto("edges").values(edge).onConflict((oc) => oc.columns(["parent_id", "child_id"]).doNothing()).execute();
513
+ });
514
+ break;
515
+ }
516
+ case DocumentChangeType.ChildRemoved:
517
+ case DocumentChangeType.ParentRemoved: {
518
+ const edge = edgeOf(event);
519
+ if (!edge) return;
520
+ await this.#enqueue(async () => {
521
+ await db.deleteFrom("edges").where("parent_id", "=", edge.parent_id).where("child_id", "=", edge.child_id).execute();
522
+ });
523
+ break;
524
+ }
525
+ default: return;
526
+ }
527
+ this.#scheduleRecompute();
528
+ }
529
+ async #onPermissionChange(documentId) {
530
+ const db = this.#db;
531
+ if (!db || this.#stopped) return;
532
+ const snapshots = await this.#snapshotsOf([documentId], 1);
533
+ await this.#enqueue(async () => {
534
+ await this.#applySnapshots(db, snapshots);
535
+ });
536
+ this.#scheduleRecompute();
537
+ }
538
+ async #applySnapshots(db, snapshots) {
539
+ for (const s of snapshots.values()) {
540
+ await db.insertInto("protection").values({
541
+ document_id: s.documentId,
542
+ protected: s.isProtected,
543
+ owner_id: s.ownerAddress
544
+ }).onConflict((oc) => oc.column("document_id").doUpdateSet({
545
+ protected: s.isProtected,
546
+ owner_id: s.ownerAddress
547
+ })).execute();
548
+ await db.deleteFrom("grants").where("document_id", "=", s.documentId).execute();
549
+ const users = [...s.grants.keys()];
550
+ if (users.length > 0) await db.insertInto("grants").values(users.map((user_id) => ({
551
+ document_id: s.documentId,
552
+ user_id
553
+ }))).execute();
554
+ }
555
+ }
556
+ #scheduleRecompute() {
557
+ if (this.#stopped) return;
558
+ this.#pending = true;
559
+ if (this.#timer) return;
560
+ this.#timer = setTimeout(() => {
561
+ this.#timer = void 0;
562
+ if (!this.#pending) return;
563
+ this.#pending = false;
564
+ this.#enqueue(async () => {
565
+ const db = this.#db;
566
+ if (!db) return;
567
+ await db.transaction().execute((trx) => this.#recompute(trx));
568
+ }).catch((error) => {
569
+ this.#deps.logger?.warn("readable-documents: recompute failed: @error", error);
570
+ });
571
+ }, this.#deps.debounceMs ?? 100);
572
+ }
573
+ /** The closure, in one statement (UNION dedups, so a cycle terminates). */
574
+ async #recompute(db) {
575
+ const t = (name) => sql.table(`${this.schema}.${name}`);
576
+ const defaultProtection = this.#deps.config.defaultProtection;
577
+ await sql`delete from ${t("readable_documents")}`.execute(db);
578
+ await sql`
579
+ insert into ${t("readable_documents")} (user_id, document_id)
580
+ with recursive anc(document_id, ancestor_id) as (
581
+ select document_id, document_id from ${t("documents")}
582
+ union
583
+ select a.document_id, e.parent_id
584
+ from anc a join ${t("edges")} e on e.child_id = a.ancestor_id
585
+ ),
586
+ prot as (
587
+ select d.document_id,
588
+ coalesce(p.protected, ${defaultProtection}) as protected,
589
+ p.owner_id
590
+ from ${t("documents")} d
591
+ left join ${t("protection")} p on p.document_id = d.document_id
592
+ )
593
+ select ${"*"}, a.document_id
594
+ from anc a join prot p on p.document_id = a.ancestor_id
595
+ group by a.document_id
596
+ having bool_and(not p.protected)
597
+ union
598
+ select p.owner_id, p.document_id from prot p where p.owner_id is not null
599
+ union
600
+ select g.user_id, a.document_id
601
+ from anc a join ${t("grants")} g on g.document_id = a.ancestor_id
602
+ `.execute(db);
603
+ }
604
+ async #ensureTables(db) {
605
+ await db.schema.createTable("documents").ifNotExists().addColumn("document_id", "text", (c) => c.primaryKey()).execute();
606
+ await db.schema.createTable("edges").ifNotExists().addColumn("parent_id", "text", (c) => c.notNull()).addColumn("child_id", "text", (c) => c.notNull()).addPrimaryKeyConstraint("edges_pkey", ["parent_id", "child_id"]).execute();
607
+ await db.schema.createIndex("edges_child_idx").ifNotExists().on("edges").column("child_id").execute();
608
+ await db.schema.createTable("protection").ifNotExists().addColumn("document_id", "text", (c) => c.primaryKey()).addColumn("protected", "boolean", (c) => c.notNull()).addColumn("owner_id", "text").execute();
609
+ await db.schema.createTable("grants").ifNotExists().addColumn("document_id", "text", (c) => c.notNull()).addColumn("user_id", "text", (c) => c.notNull()).addPrimaryKeyConstraint("grants_pkey", ["document_id", "user_id"]).execute();
610
+ await db.schema.createTable("readable_documents").ifNotExists().addColumn("user_id", "text", (c) => c.notNull()).addColumn("document_id", "text", (c) => c.notNull()).addPrimaryKeyConstraint("readable_documents_pkey", ["user_id", "document_id"]).execute();
611
+ await db.schema.createIndex("readable_documents_document_idx").ifNotExists().on("readable_documents").column("document_id").execute();
612
+ }
613
+ async #allDocumentIds(pageSize) {
614
+ const ids = [];
615
+ await eachPage(() => this.#deps.read.find({}, { scopes: ["header"] }, {
616
+ cursor: "0",
617
+ limit: pageSize
618
+ }), (page) => {
619
+ for (const doc of page) ids.push(doc.header.id);
620
+ });
621
+ return ids;
622
+ }
623
+ /** `child` edges, found by walking down from every drive. */
624
+ async #allEdges(pageSize) {
625
+ const roots = [];
626
+ for (const type of this.#deps.rootTypes ?? DEFAULT_ROOT_TYPES) await eachPage(() => this.#deps.read.find({ type }, { scopes: ["header"] }, {
627
+ cursor: "0",
628
+ limit: pageSize
629
+ }), (page) => {
630
+ for (const doc of page) roots.push(doc.header.id);
631
+ });
632
+ const edges = [];
633
+ const seen = /* @__PURE__ */ new Set();
634
+ const queue = [...roots];
635
+ while (queue.length > 0) {
636
+ const parent = queue.shift();
637
+ if (seen.has(parent)) continue;
638
+ seen.add(parent);
639
+ await eachPage(() => this.#deps.read.getOutgoingRelationshipEdges(parent, "child", void 0, {
640
+ cursor: "0",
641
+ limit: pageSize
642
+ }), (page) => {
643
+ for (const edge of page) {
644
+ edges.push({
645
+ parent_id: parent,
646
+ child_id: edge.targetId
647
+ });
648
+ if (!seen.has(edge.targetId)) queue.push(edge.targetId);
649
+ }
650
+ });
651
+ }
652
+ return edges;
653
+ }
654
+ async #snapshotsOf(ids, pageSize) {
655
+ const out = /* @__PURE__ */ new Map();
656
+ const permissions = this.#deps.permissions;
657
+ for (const chunk of chunks(ids, pageSize)) {
658
+ const loaded = await permissions.loadPermissionSnapshots(chunk);
659
+ for (const [id, snapshot] of loaded) {
660
+ if (snapshot.ownerAddress === null && snapshot.grants.size === 0 && snapshot.isProtected === this.#deps.config.defaultProtection) continue;
661
+ out.set(id, snapshot);
662
+ }
663
+ }
664
+ return out;
665
+ }
666
+ #enqueue(task) {
667
+ const run = this.#chain.then(task, task);
668
+ this.#chain = run.catch(() => void 0);
669
+ return run;
670
+ }
671
+ };
672
+ function edgeOf(event) {
673
+ const parent = event.context?.parentId;
674
+ const child = event.context?.childId;
675
+ return parent && child ? {
676
+ parent_id: parent,
677
+ child_id: child
678
+ } : void 0;
679
+ }
680
+ async function eachPage(first, consume) {
681
+ let page = await first();
682
+ for (;;) {
683
+ consume(page.results);
684
+ if (page.results.length === 0 || !page.next) return;
685
+ page = await page.next();
686
+ }
687
+ }
688
+ function chunks(items, size) {
689
+ const out = [];
690
+ for (let at = 0; at < items.length; at += size) out.push(items.slice(at, at + size));
691
+ return out;
692
+ }
693
+ //#endregion
694
+ //#region src/services/auth.service.ts
695
+ const DEFAULT_CREDENTIAL_CACHE_TTL_MS = 6e4;
696
+ const CREDENTIAL_CACHE_MAX_ENTRIES = 1e3;
697
+ /** The invalidator a subgraph receives: forwards to `authService`, or does
698
+ * nothing when the host runs without one. */
699
+ function createCredentialInvalidator(authService) {
700
+ return { invalidateCredential: (address, chainId, appDid) => authService?.invalidateCredential(address, chainId, appDid) ?? 0 };
701
+ }
702
+ var AuthService = class {
703
+ config;
704
+ credentialCache = /* @__PURE__ */ new Map();
705
+ invalidationListeners = /* @__PURE__ */ new Set();
706
+ constructor(config) {
707
+ this.config = config;
708
+ }
709
+ /**
710
+ * Whether this service reads the bearer at all. Defaults to `enabled`, so a
711
+ * config written before `resolveIdentity` existed behaves exactly as it did.
712
+ */
713
+ get resolvesIdentity() {
714
+ return this.config.resolveIdentity ?? this.config.enabled;
715
+ }
716
+ /** The context an unresolved request gets: no user, and no admin list to match against. */
717
+ anonymousContext() {
718
+ return {
719
+ user: void 0,
720
+ admins: [],
721
+ auth_enabled: this.config.enabled
722
+ };
723
+ }
724
+ async authenticateRequest(request) {
725
+ if (!this.resolvesIdentity) return this.anonymousContext();
726
+ if (request.method === "OPTIONS") return {
727
+ user: void 0,
728
+ admins: this.config.admins,
729
+ auth_enabled: this.config.enabled
730
+ };
731
+ return this.verifyBearer(request.headers.get("authorization") ?? void 0);
732
+ }
733
+ /**
734
+ * Verify a Bearer token regardless of HTTP method. Use this from non-GraphQL
735
+ * middleware that must enforce authentication on every request.
736
+ */
737
+ async verifyBearer(authorization) {
738
+ if (!this.resolvesIdentity) return this.anonymousContext();
739
+ const token = authorization?.split(" ")[1];
740
+ if (!token) return {
741
+ user: void 0,
742
+ admins: this.config.admins,
743
+ auth_enabled: this.config.enabled
744
+ };
745
+ try {
746
+ const verified = await this.verifyToken(token);
747
+ if (!verified) return new Response(JSON.stringify({ error: "Verification failed" }), { status: 401 });
748
+ const user = this.extractUserFromVerification(verified);
749
+ if (!user) return new Response(JSON.stringify({ error: "Missing credentials" }), { status: 401 });
750
+ if (!this.config.skipCredentialVerification) {
751
+ if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) return new Response(JSON.stringify({ error: "Credentials no longer valid" }), { status: 401 });
752
+ }
753
+ this.config.onVerified?.(user);
754
+ return {
755
+ user,
756
+ admins: this.config.admins,
757
+ auth_enabled: this.config.enabled
758
+ };
759
+ } catch {
760
+ return new Response(JSON.stringify({ error: "Authentication failed" }), { status: 401 });
761
+ }
762
+ }
763
+ /** Throws only for a bearer that is present and unusable, as HTTP 401s it. */
764
+ async authenticateWebSocketConnection(connectionParams) {
765
+ if (!this.resolvesIdentity) return null;
766
+ const authHeader = connectionParams.authorization;
767
+ if (!authHeader) return null;
768
+ const token = authHeader.split(" ")[1];
769
+ if (!token) throw new Error("Invalid authorization format");
770
+ const verified = await this.verifyToken(token);
771
+ if (!verified) throw new Error("Token verification failed");
772
+ const user = this.extractUserFromVerification(verified);
773
+ if (!user) throw new Error("Invalid credentials");
774
+ if (!this.config.skipCredentialVerification) {
775
+ if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) throw new Error("Credentials no longer valid");
776
+ }
777
+ this.config.onVerified?.(user);
778
+ return user;
779
+ }
780
+ /** {@inheritDoc ICredentialInvalidator.invalidateCredential} */
781
+ invalidateCredential(address, chainId, appDid) {
782
+ const normalized = address.toLowerCase();
783
+ let evicted = 0;
784
+ for (const [key, entry] of this.credentialCache) if (entry.address === normalized && (chainId === void 0 || entry.chainId === chainId) && (appDid === void 0 || entry.appId === appDid)) {
785
+ this.credentialCache.delete(key);
786
+ evicted++;
787
+ }
788
+ const invalidation = { address: normalized };
789
+ if (chainId !== void 0) invalidation.chainId = chainId;
790
+ if (appDid !== void 0) invalidation.appDid = appDid;
791
+ for (const listener of this.invalidationListeners) try {
792
+ listener(invalidation);
793
+ } catch {}
794
+ return evicted;
795
+ }
796
+ /** Called after every `invalidateCredential`; returns an unsubscribe. */
797
+ onCredentialInvalidated(listener) {
798
+ this.invalidationListeners.add(listener);
799
+ return () => {
800
+ this.invalidationListeners.delete(listener);
801
+ };
802
+ }
803
+ /**
804
+ * Whether an already-authenticated principal's credential still holds, for
805
+ * re-checking long-lived connections. Goes through the same cache as
806
+ * admission, so it costs at most one verifier call per identity per TTL.
807
+ */
808
+ async isCredentialValid(user) {
809
+ if (this.config.skipCredentialVerification) return true;
810
+ return this.verifyCredentialExists(user.address, user.chainId, user.appKey);
811
+ }
812
+ /**
813
+ * Verify the auth bearer token
814
+ */
815
+ async verifyToken(token) {
816
+ return await verifyAuthBearerToken(token);
817
+ }
818
+ /**
819
+ * Extract user information from verification result.
820
+ *
821
+ * The issuer is required along with the credential subject. A credential that
822
+ * verified must carry one -- resolving it is how the signature was checked --
823
+ * so this rejects a shape that cannot have come from verification rather than
824
+ * admitting a keyless principal.
825
+ */
826
+ extractUserFromVerification(verified) {
827
+ try {
828
+ const { address, chainId, networkId } = verified.verifiableCredential.credentialSubject;
829
+ const appKey = verified.issuer;
830
+ if (!address || !chainId || !networkId || !appKey) return null;
831
+ return {
832
+ address,
833
+ chainId,
834
+ networkId,
835
+ appKey
836
+ };
837
+ } catch {
838
+ return null;
839
+ }
840
+ }
841
+ /**
842
+ * Verify that the credential still exists on the Renown API.
843
+ *
844
+ * Results are cached per (address, chainId, issuer) for a short TTL so the
845
+ * blocking external round-trip is not paid on every request. Concurrent
846
+ * checks for the same key share a single in-flight request, and entries
847
+ * that resolve to false are evicted immediately so failed or revoked
848
+ * credentials are re-checked on the next request.
849
+ */
850
+ verifyCredentialExists(address, chainId, appId) {
851
+ const ttlMs = this.config.credentialVerificationCacheTtlMs ?? DEFAULT_CREDENTIAL_CACHE_TTL_MS;
852
+ if (ttlMs <= 0) return this.fetchCredentialExists(address, chainId, appId);
853
+ const key = `${address.toLowerCase()}:${chainId}:${appId}`;
854
+ const now = Date.now();
855
+ const cached = this.credentialCache.get(key);
856
+ if (cached && cached.expiresAt > now) return cached.exists;
857
+ this.pruneCredentialCache(now);
858
+ const entry = {
859
+ exists: this.fetchCredentialExists(address, chainId, appId).then((exists) => {
860
+ if (!exists && this.credentialCache.get(key) === entry) this.credentialCache.delete(key);
861
+ return exists;
862
+ }),
863
+ expiresAt: now + ttlMs,
864
+ address: address.toLowerCase(),
865
+ chainId,
866
+ appId
867
+ };
868
+ this.credentialCache.set(key, entry);
869
+ return entry.exists;
870
+ }
871
+ /**
872
+ * Enforce the cache size cap before inserting a new entry: drop expired
873
+ * entries first, then evict oldest-inserted entries (insertion order
874
+ * matches expiry order since the TTL is constant) until under the cap, so
875
+ * a flood of distinct keys cannot grow the map without bound.
876
+ */
877
+ pruneCredentialCache(now) {
878
+ if (this.credentialCache.size < CREDENTIAL_CACHE_MAX_ENTRIES) return;
879
+ for (const [key, entry] of this.credentialCache) if (entry.expiresAt <= now) this.credentialCache.delete(key);
880
+ while (this.credentialCache.size >= CREDENTIAL_CACHE_MAX_ENTRIES) {
881
+ const oldestKey = this.credentialCache.keys().next().value;
882
+ if (oldestKey === void 0) break;
883
+ this.credentialCache.delete(oldestKey);
884
+ }
885
+ }
886
+ async fetchCredentialExists(address, chainId, appId) {
887
+ if (!this.config.verifyCredential) throw new Error("AuthService: credential verification is enabled but no verifyCredential was provided");
888
+ return this.config.verifyCredential({
889
+ address,
890
+ chainId,
891
+ appId
892
+ });
893
+ }
894
+ };
895
+ //#endregion
896
+ //#region src/graphql/request-clients.ts
897
+ /** A resolver outside a mutation asked for the write client. */
898
+ var WriteClientUnavailableError = class extends Error {
899
+ operation;
900
+ field;
901
+ constructor(operation, field) {
902
+ const where = field ? `field ${field}` : "this resolver";
903
+ const running = operation === "unbound" ? "outside a mutation" : `in a ${operation}`;
904
+ super(`ctx.clients.write is only available to Mutation fields; ${where} runs ${running}. Read through ctx.clients.read.`);
905
+ this.name = "WriteClientUnavailableError";
906
+ this.operation = operation;
907
+ this.field = field;
908
+ }
909
+ static isError(error) {
910
+ return error instanceof Error && error.name === "WriteClientUnavailableError";
911
+ }
912
+ };
913
+ /** The field whose resolver is running, so a refusal can name it. */
914
+ const executingField = new AsyncLocalStorage();
915
+ const operations = /* @__PURE__ */ new WeakMap();
916
+ /**
917
+ * The clients for one operation: both halves for a mutation, the read half
918
+ * and a refusing `write` for anything else. The refusing property is not
919
+ * enumerable, so spreading or printing the clients does not trip it.
920
+ */
921
+ function createRequestClients(read, write, operation) {
922
+ let clients;
923
+ if (operation === "mutation") clients = Object.freeze({
924
+ read,
925
+ write
926
+ });
927
+ else {
928
+ const gated = { read };
929
+ Object.defineProperty(gated, "write", {
930
+ enumerable: false,
931
+ get() {
932
+ throw new WriteClientUnavailableError(operation, executingField.getStore());
933
+ }
934
+ });
935
+ clients = Object.freeze(gated);
936
+ }
937
+ operations.set(clients, operation);
938
+ return clients;
939
+ }
940
+ /**
941
+ * The read half alone, for a context nobody bound to an operation (a resolver
942
+ * called directly rather than through the GraphQL layer). `write` refuses.
943
+ */
944
+ function readOnlyClients(read) {
945
+ return createRequestClients(read, UNAVAILABLE_WRITE, "unbound");
946
+ }
947
+ /** Never reached: a non-mutation client set refuses before handing it out. */
948
+ const UNAVAILABLE_WRITE = {};
949
+ /**
950
+ * Both halves for a field that reads write-side state outside a mutation. The
951
+ * clients still report `operation`, so identifiers resolve on the read side.
952
+ */
953
+ function createWriteSideClients(read, write, operation) {
954
+ const clients = Object.freeze({
955
+ read,
956
+ write
957
+ });
958
+ operations.set(clients, operation);
959
+ return clients;
960
+ }
961
+ /**
962
+ * The operation the clients were built for, or undefined for clients that
963
+ * {@link createRequestClients} did not build (a hand-made pair in a test).
964
+ */
965
+ function operationOfClients(clients) {
966
+ return clients === void 0 ? void 0 : operations.get(clients);
967
+ }
968
+ /**
969
+ * A resolver map's own object, as opposed to a scalar or another class
970
+ * instance, which passes through. Checked by prototype rather than with
971
+ * `isScalarType`, which refuses a scalar from another copy of graphql.
972
+ */
973
+ function isPlainObject(value) {
974
+ if (value === null || typeof value !== "object") return false;
975
+ const prototype = Object.getPrototypeOf(value);
976
+ return prototype === Object.prototype || prototype === null;
977
+ }
978
+ /** Type-level resolvers that receive the context; each is `(value, ctx, info)`. */
979
+ const TYPE_LEVEL_RESOLVERS = /* @__PURE__ */ new Set([
980
+ "__resolveReference",
981
+ "__resolveType",
982
+ "__isTypeOf"
983
+ ]);
984
+ /**
985
+ * Puts the client halves on the GraphQL context per operation. The host builds
986
+ * one context per request (or per WebSocket operation) before it knows what
987
+ * the operation is; every resolver this binder wraps receives instead a
988
+ * context derived from that one for the operation it is running in, so a
989
+ * mutation gets `ctx.clients.write` and a query or subscription does not.
990
+ *
991
+ * The derived context is memoized per request context and operation, so every
992
+ * field of one operation sees the same object, which per-request memos key on.
993
+ */
994
+ var RequestClientBinder = class {
995
+ #read;
996
+ #write;
997
+ #contexts = /* @__PURE__ */ new WeakMap();
998
+ #derived = /* @__PURE__ */ new WeakSet();
999
+ #wrapped = /* @__PURE__ */ new WeakMap();
1000
+ constructor(read, write) {
1001
+ this.#read = read;
1002
+ this.#write = write;
1003
+ }
1004
+ /** The clients for a context the host builds before the operation is known. */
1005
+ unboundClients() {
1006
+ return createRequestClients(this.#read, this.#write, "unbound");
1007
+ }
1008
+ /**
1009
+ * The context a resolver of `operation` receives for request context `base`.
1010
+ * `writeSide` hands a query field the write client too: a field declared to
1011
+ * read write-side state.
1012
+ */
1013
+ contextFor(base, operation, writeSide = false) {
1014
+ if (this.#derived.has(base)) return base;
1015
+ let byOperation = this.#contexts.get(base);
1016
+ if (!byOperation) {
1017
+ byOperation = /* @__PURE__ */ new Map();
1018
+ this.#contexts.set(base, byOperation);
1019
+ }
1020
+ const key = writeSide ? `${operation}:write-side` : operation;
1021
+ let derived = byOperation.get(key);
1022
+ if (!derived) {
1023
+ derived = {
1024
+ ...base,
1025
+ clients: writeSide ? createWriteSideClients(this.#read, this.#write, operation) : createRequestClients(this.#read, this.#write, operation)
1026
+ };
1027
+ this.#derived.add(derived);
1028
+ byOperation.set(key, derived);
1029
+ }
1030
+ return derived;
1031
+ }
1032
+ /**
1033
+ * A copy of a subgraph's resolver map whose resolvers receive the context
1034
+ * for their operation. Scalars, enums and non-function members pass through.
1035
+ * `writeSideFields` names the fields (`Type.field`) handed the write client
1036
+ * whatever their operation. The copy is memoized per map.
1037
+ */
1038
+ bindResolvers(resolvers, writeSideFields = /* @__PURE__ */ new Set()) {
1039
+ const cached = this.#wrapped.get(resolvers);
1040
+ if (cached) return cached;
1041
+ const bound = {};
1042
+ for (const [typeName, typeResolvers] of Object.entries(resolvers)) bound[typeName] = this.#bindType(typeName, typeResolvers, writeSideFields);
1043
+ this.#wrapped.set(resolvers, bound);
1044
+ return bound;
1045
+ }
1046
+ #bindType(typeName, typeResolvers, writeSideFields) {
1047
+ if (!isPlainObject(typeResolvers)) return typeResolvers;
1048
+ const bound = {};
1049
+ for (const [field, value] of Object.entries(typeResolvers)) {
1050
+ const writeSide = writeSideFields.has(`${typeName}.${field}`);
1051
+ if (typeof value === "function") bound[field] = TYPE_LEVEL_RESOLVERS.has(field) ? this.#bindTypeResolver(value) : field.startsWith("__") ? value : this.#bindFieldResolver(value, writeSide);
1052
+ else if (isPlainObject(value)) {
1053
+ const config = { ...value };
1054
+ for (const key of ["resolve", "subscribe"]) if (typeof config[key] === "function") config[key] = this.#bindFieldResolver(config[key], writeSide);
1055
+ bound[field] = config;
1056
+ } else bound[field] = value;
1057
+ }
1058
+ return bound;
1059
+ }
1060
+ #bindFieldResolver(resolver, writeSide) {
1061
+ return (parent, args, context, info) => {
1062
+ if (!info?.operation) return resolver(parent, args, context, info);
1063
+ const derived = this.contextFor(context ?? {}, info.operation.operation, writeSide);
1064
+ return executingField.run(`${info.parentType.name}.${info.fieldName}`, () => resolver(parent, args, derived, info));
1065
+ };
1066
+ }
1067
+ #bindTypeResolver(resolver) {
1068
+ return (value, context, info) => {
1069
+ if (!info?.operation) return resolver(value, context, info);
1070
+ return resolver(value, this.contextFor(context ?? {}, info.operation.operation), info);
1071
+ };
1072
+ }
1073
+ };
1074
+ //#endregion
1075
+ //#region src/graphql/base-subgraph.ts
1076
+ /**
1077
+ * Stands in for a client the subgraph was not given: any use names what to
1078
+ * use instead rather than failing on `undefined`.
1079
+ */
1080
+ function missingClient(name, hint) {
1081
+ return new Proxy({}, { get(_target, property) {
1082
+ if (property === "then" || typeof property === "symbol") return;
1083
+ throw new Error(`${name}.${String(property)}: ${hint}`);
1084
+ } });
1085
+ }
1086
+ /**
1087
+ * The subject a request reads as: its address and the app key its token
1088
+ * carries. Anonymous is an empty subject, never the host's signer.
1089
+ */
1090
+ function callerSubject(user) {
1091
+ return {
1092
+ address: user?.address,
1093
+ key: user?.appKey
1094
+ };
1095
+ }
1096
+ var BaseSubgraph = class {
1097
+ name = "example";
1098
+ path = "";
1099
+ resolvers = { Query: { hello: () => this.name } };
1100
+ typeDefs = gql`
1101
+ type Query {
1102
+ hello: String
1103
+ }
1104
+ `;
1105
+ /**
1106
+ * The read half, for setup-time use (schema building, model lookup).
1107
+ * Resolvers read through `ctx.clients.read` instead.
1108
+ */
1109
+ readClient;
1110
+ /**
1111
+ * @deprecated The facade over both halves, for subgraphs that have not
1112
+ * moved. Resolvers use `ctx.clients.read` and, in a mutation,
1113
+ * `ctx.clients.write`; setup-time code uses {@link readClient}.
1114
+ */
1115
+ reactorClient;
1116
+ /** This package's namespaced slice of the HTTP surface. */
1117
+ http;
1118
+ graphqlManager;
1119
+ relationalDb;
1120
+ syncManager;
1121
+ documentPermissionService;
1122
+ authorizationService;
1123
+ syncServingGate;
1124
+ /**
1125
+ * The readable-documents read model (`services/readable-documents.ts`):
1126
+ * the host ACL's read closure as rows an index table joins on. Absent on
1127
+ * a host that does not serve it; `readableFilter` then fails closed for
1128
+ * every caller but a listed admin.
1129
+ */
1130
+ readableDocuments;
1131
+ /**
1132
+ * The host's credential cache, for a package that revokes credentials:
1133
+ * call `this.credentials.invalidateCredential(address, chainId?, appDid?)`
1134
+ * right after the revocation is stored, so this host refuses the credential
1135
+ * on the next request and closes WebSocket connections that rely on it.
1136
+ * A no-op on a host without authentication.
1137
+ */
1138
+ credentials;
1139
+ /**
1140
+ * Per-request memo of raw identifier to canonical document id, keyed on the
1141
+ * request context object so entries are released when the request ends. Lets
1142
+ * batch resolvers resolve each distinct identifier at most once.
1143
+ */
1144
+ #canonicalIdMemo = /* @__PURE__ */ new WeakMap();
1145
+ #unboundClients;
1146
+ #attachments;
1147
+ #attachmentClientMemo = /* @__PURE__ */ new WeakMap();
1148
+ constructor(args) {
1149
+ const facadeRead = args.reactorClient?.read;
1150
+ this.readClient = args.readClient ?? (typeof facadeRead?.get === "function" ? facadeRead : args.reactorClient) ?? missingClient("BaseSubgraph.readClient", "this subgraph was constructed without a readClient.");
1151
+ this.reactorClient = args.reactorClient ?? missingClient("BaseSubgraph.reactorClient", "this host passes no reactorClient facade. Read through ctx.clients.read (or this.readClient at setup) and write through ctx.clients.write in a mutation.");
1152
+ this.#unboundClients = readOnlyClients(this.readClient);
1153
+ this.http = args.http;
1154
+ this.graphqlManager = args.graphqlManager;
1155
+ this.relationalDb = args.relationalDb;
1156
+ this.syncManager = args.syncManager;
1157
+ this.documentPermissionService = args.documentPermissionService;
1158
+ this.authorizationService = args.authorizationService;
1159
+ this.syncServingGate = args.syncServingGate;
1160
+ this.readableDocuments = args.readableDocuments;
1161
+ this.path = args.path ?? "";
1162
+ this.#attachments = args.attachments;
1163
+ this.credentials = args.credentials ?? createCredentialInvalidator(void 0);
1164
+ }
1165
+ /**
1166
+ * An attachment client bound to this request's caller, memoized per request.
1167
+ *
1168
+ * @throws Error when the host provides no attachment client to subgraphs.
1169
+ */
1170
+ attachmentsFor(ctx) {
1171
+ if (!this.#attachments) throw new Error("This host provides no attachment client to subgraphs");
1172
+ let client = this.#attachmentClientMemo.get(ctx);
1173
+ if (!client) {
1174
+ client = this.#attachments.forSubject(callerSubject(ctx.user));
1175
+ this.#attachmentClientMemo.set(ctx, client);
1176
+ }
1177
+ return client;
1178
+ }
1179
+ /**
1180
+ * The clients this request's operation may use: those the GraphQL layer put
1181
+ * on the context. A context it never saw (a resolver called directly) reads
1182
+ * through {@link readClient} and may not write.
1183
+ */
1184
+ clientsOf(ctx) {
1185
+ return ctx?.clients ?? this.#unboundClients;
1186
+ }
1187
+ async onSetup() {}
1188
+ async onDisconnect() {}
1189
+ /**
1190
+ * Resolves a caller-supplied identifier (id or slug) to its canonical
1191
+ * document id, memoized per request. Both the decision layer and the data
1192
+ * layer must agree on the subject, so this runs the lookup the data path
1193
+ * uses: `resolveIdOrSlug` on the read half for a query, `describe` on the
1194
+ * write half for a mutation. A resolution failure (not found, ambiguous, or
1195
+ * transient) surfaces as a generic Forbidden, fail-closed, so a bad
1196
+ * identifier cannot be used as a document-existence oracle.
1197
+ */
1198
+ async resolveCanonicalDocumentId(identifier, requestKey) {
1199
+ let cache = this.#canonicalIdMemo.get(requestKey);
1200
+ if (!cache) {
1201
+ cache = /* @__PURE__ */ new Map();
1202
+ this.#canonicalIdMemo.set(requestKey, cache);
1203
+ }
1204
+ const cached = cache.get(identifier);
1205
+ if (cached !== void 0) return cached;
1206
+ const clients = this.clientsOf(requestKey);
1207
+ const resolve = operationOfClients(clients) === "mutation" ? createCanonicalDocumentIdResolver({
1208
+ read: clients.read,
1209
+ write: clients.write
1210
+ }, "mutation") : createCanonicalDocumentIdResolver({ read: clients.read }, "query");
1211
+ let canonical;
1212
+ try {
1213
+ canonical = await resolve(identifier);
1214
+ } catch {
1215
+ throw new ForbiddenError();
1216
+ }
1217
+ cache.set(identifier, canonical);
1218
+ return canonical;
1219
+ }
1220
+ /**
1221
+ * Resolves the args' `documentId` to canonical form. Unconditional (unlike the
1222
+ * assertCan* helpers, no admin skip): ACL rows are keyed on the canonical id.
1223
+ */
1224
+ async withCanonicalDocumentId(args, requestKey) {
1225
+ const documentId = await this.resolveCanonicalDocumentId(args.documentId, requestKey);
1226
+ return {
1227
+ ...args,
1228
+ documentId
1229
+ };
1230
+ }
1231
+ /**
1232
+ * Resolves an identifier for a per-document check, or null when the caller has
1233
+ * policy-wide access (OPEN or supreme admin) and the check can be skipped.
1234
+ * Only DOCUMENT_PERMISSIONS keys on the document id, so other policies fail
1235
+ * closed without resolving.
1236
+ */
1237
+ async #resolveForCheck(identifier, ctx) {
1238
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return null;
1239
+ if (this.authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
1240
+ return this.resolveCanonicalDocumentId(identifier, ctx);
1241
+ }
1242
+ /**
1243
+ * Read filter for an already-canonical document id (one sourced from the data
1244
+ * layer, such as a fetched document's id). Performs no slug resolution.
1245
+ */
1246
+ async canReadDocument(documentId, ctx) {
1247
+ return this.authorizationService.canRead(documentId, ctx.user?.address);
1248
+ }
1249
+ /** The ids or slugs in `ids` that {@link assertCanRead} admits, in order; the rest are dropped. */
1250
+ async filterReadableDocumentIds(ids, ctx) {
1251
+ const readable = [];
1252
+ for (const id of ids) {
1253
+ try {
1254
+ await this.assertCanRead(id, ctx);
1255
+ } catch (error) {
1256
+ if (error instanceof ForbiddenError) continue;
1257
+ throw error;
1258
+ }
1259
+ readable.push(id);
1260
+ }
1261
+ return readable;
1262
+ }
1263
+ /** Drops the items the host's own ACL refuses the caller. */
1264
+ async readableByHost(items, ctx) {
1265
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return [...items];
1266
+ const readable = [];
1267
+ for (const item of items) if (await this.canReadDocument(item.id, ctx)) readable.push(item);
1268
+ return readable;
1269
+ }
1270
+ /**
1271
+ * Whether the caller is in the ADMINS list. Not `isSupremeAdmin`: under
1272
+ * OPEN that admits every caller, anonymous included.
1273
+ */
1274
+ isListedAdmin(ctx) {
1275
+ const address = ctx.user?.address.toLowerCase();
1276
+ return address !== void 0 && this.authorizationService.config.admins.includes(address);
1277
+ }
1278
+ /**
1279
+ * The readable-documents filter for this request's caller, for a query
1280
+ * over an index table keyed by document (`applyReadableFilter`). Without
1281
+ * the read model only a listed admin reads anything: an index must never
1282
+ * serve more than the host would.
1283
+ */
1284
+ readableFilter(ctx) {
1285
+ if (this.readableDocuments) return this.readableDocuments.filterFor(ctx.user?.address);
1286
+ return this.isListedAdmin(ctx) ? { kind: "all" } : { kind: "none" };
1287
+ }
1288
+ /**
1289
+ * The row filter for an index query scoped to one document (its drive or
1290
+ * folder): `none` when the caller may not read the scope itself, the
1291
+ * caller's `readableFilter` otherwise. One call per resolver, then
1292
+ * `applyReadableFilter` on every query it runs.
1293
+ */
1294
+ async indexAccess(ctx, scopeDocumentId) {
1295
+ const filter = this.readableFilter(ctx);
1296
+ if (filter.kind !== "ids") return filter;
1297
+ return await isDocumentListed(this.relationalDb, filter, scopeDocumentId) ? filter : { kind: "none" };
1298
+ }
1299
+ /**
1300
+ * The principal a request decides as: the authenticated caller's address, and
1301
+ * the did:key of the app instance whose token authenticated it.
1302
+ *
1303
+ * Both, because a policy can name either. The key is what a document records
1304
+ * as its creator, so a subject built without one cannot match the creator's
1305
+ * standing permission over the auth scope -- the document's own creator would
1306
+ * be refused an operation the write path accepts, since a signed action
1307
+ * carries the same key. Anonymous callers supply neither.
1308
+ */
1309
+ viewSubject(ctx) {
1310
+ return callerSubject(ctx.user);
1311
+ }
1312
+ /** Whether a listing would serve the document to the caller; fails closed. */
1313
+ async servesDocument(documentId, ctx) {
1314
+ if (!documentId) return false;
1315
+ try {
1316
+ return await this.servesDocumentOrThrows(documentId, ctx);
1317
+ } catch {
1318
+ return false;
1319
+ }
1320
+ }
1321
+ /** {@link servesDocument}, but a reactor that cannot answer throws. */
1322
+ servesDocumentOrThrows(identifier, ctx, view) {
1323
+ return this.clientsOf(ctx).read.isServed(identifier, {
1324
+ ...view,
1325
+ subject: this.viewSubject(ctx)
1326
+ });
1327
+ }
1328
+ /**
1329
+ * Whether a listing would serve the document to the caller: the reactor read
1330
+ * gate, then the host's legacy layer, as `findDocuments` applies them. Absent
1331
+ * or withheld is `false`; a failure to decide throws.
1332
+ */
1333
+ async listsDocument(identifier, ctx, view) {
1334
+ if (!await this.servesDocumentOrThrows(identifier, ctx, view)) return false;
1335
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return true;
1336
+ return this.canReadDocument(await this.resolveCanonicalDocumentId(identifier, ctx), ctx);
1337
+ }
1338
+ /**
1339
+ * Asserts read access, resolving a slug first. Returns a handle whose
1340
+ * `fetchIdentifier` the caller reuses for the data fetch; a denial throws.
1341
+ */
1342
+ async assertCanRead(identifier, ctx) {
1343
+ const documentId = await this.#resolveForCheck(identifier, ctx);
1344
+ if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
1345
+ await this.assertCanReadCanonical(documentId, ctx);
1346
+ return AuthorizedDocumentHandle.resolved(documentId);
1347
+ }
1348
+ async assertCanWrite(identifier, ctx) {
1349
+ const documentId = await this.#resolveForCheck(identifier, ctx);
1350
+ if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
1351
+ await this.assertCanWriteCanonical(documentId, ctx);
1352
+ return AuthorizedDocumentHandle.resolved(documentId);
1353
+ }
1354
+ async assertCanExecuteOperation(identifier, operationType, ctx) {
1355
+ const documentId = await this.#resolveForCheck(identifier, ctx);
1356
+ if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
1357
+ await this.assertCanExecuteOperationCanonical(documentId, operationType, ctx);
1358
+ return AuthorizedDocumentHandle.resolved(documentId);
1359
+ }
1360
+ /**
1361
+ * Read assertion for an already-canonical document id. No slug resolution;
1362
+ * use only with ids sourced from the data layer or already resolved.
1363
+ */
1364
+ async assertCanReadCanonical(documentId, ctx) {
1365
+ if (!await this.authorizationService.canRead(documentId, ctx.user?.address)) throw new ForbiddenError("to read this document");
1366
+ }
1367
+ async assertCanWriteCanonical(documentId, ctx) {
1368
+ if (!await this.authorizationService.canWrite(documentId, ctx.user?.address)) throw new ForbiddenError("to write to this document");
1369
+ }
1370
+ async assertCanExecuteOperationCanonical(documentId, operationType, ctx) {
1371
+ if (!await this.authorizationService.canMutate(documentId, operationType, ctx.user?.address)) throw new ForbiddenError(`to execute operation "${operationType}" on this document`);
1372
+ }
1373
+ assertCanCreate(ctx) {
1374
+ if (this.authorizationService.canCreate(ctx.user?.address)) return;
1375
+ if (ctx.user?.address) throw new ForbiddenError("to create documents");
1376
+ throw new AuthenticationRequiredError("to create documents");
1377
+ }
1378
+ };
1379
+ //#endregion
1380
+ //#region src/packages/import-resolver.ts
1381
+ /**
1382
+ * Imports a specifier that may be either a bare package specifier or a
1383
+ * filesystem path. Absolute paths are converted to file:// URLs, because the
1384
+ * ESM loader reads the drive letter in a Windows path as a URL scheme
1385
+ * (`import('D:\\...')` fails with ERR_UNSUPPORTED_ESM_URL_SCHEME).
1386
+ */
1387
+ async function importSpecifier(target) {
1388
+ return await (path.isAbsolute(target) ? import(pathToFileURL(target).href) : import(target));
1389
+ }
1390
+ /**
1391
+ * Attempts to import from suggested Node.js paths
1392
+ */
1393
+ async function tryNodeSuggestedPaths(packageName, subPath) {
1394
+ const suggestedPaths = [
1395
+ `${packageName}/dist/node/${subPath}/index.mjs`,
1396
+ `${packageName}/dist/node/${subPath}.mjs`,
1397
+ `${packageName}/dist/${subPath}/index.js`,
1398
+ `${packageName}/dist/${subPath}.js`
1399
+ ];
1400
+ for (const suggestedPath of suggestedPaths) try {
1401
+ return await importSpecifier(suggestedPath);
1402
+ } catch {}
1403
+ return null;
1404
+ }
1405
+ /**
1406
+ * Attempts to resolve package using import.meta.resolve
1407
+ */
1408
+ async function tryImportMetaResolve(packageName, subPath) {
1409
+ try {
1410
+ let packageRoot;
1411
+ if (path.isAbsolute(packageName)) packageRoot = packageName;
1412
+ else {
1413
+ const resolvedUrl = import.meta.resolve?.(`${packageName}/package.json`);
1414
+ if (!resolvedUrl) return null;
1415
+ packageRoot = path.dirname(fileURLToPath(resolvedUrl));
1416
+ }
1417
+ const pathsToTry = [
1418
+ path.join(packageRoot, "dist", "node", subPath, "index.mjs"),
1419
+ path.join(packageRoot, "dist", "node", `${subPath}.mjs`),
1420
+ path.join(packageRoot, "dist", subPath, "index.js"),
1421
+ path.join(packageRoot, "dist", `${subPath}.js`),
1422
+ path.join(packageRoot, subPath, "index.js"),
1423
+ path.join(packageRoot, `${subPath}.js`)
1424
+ ];
1425
+ for (const attemptPath of pathsToTry) try {
1426
+ return await importSpecifier(attemptPath);
1427
+ } catch {}
1428
+ } catch {}
1429
+ return null;
1430
+ }
1431
+ /**
1432
+ * Resolves symlinks in node_modules to find the real package location
1433
+ */
1434
+ async function resolveSymlinkedPaths(packageName, subPath) {
1435
+ const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
1436
+ const nodeModulesPatterns = [path.join(process.cwd(), "node_modules", packageName), path.join(process.cwd(), "node_modules", packageBaseName || packageName)];
1437
+ const workspacePatterns = [];
1438
+ for (const nodeModulesPath of nodeModulesPatterns) try {
1439
+ const fs = await import("node:fs");
1440
+ if (fs.existsSync(nodeModulesPath)) {
1441
+ const realPath = fs.realpathSync(nodeModulesPath);
1442
+ workspacePatterns.push(path.join(realPath, "dist", "node", subPath, "index.mjs"), path.join(realPath, "dist", "node", `${subPath}.mjs`), path.join(realPath, "dist", subPath, "index.js"), path.join(realPath, "dist", `${subPath}.js`), path.join(realPath, subPath, "index.js"), path.join(realPath, `${subPath}.js`));
1443
+ }
1444
+ } catch {}
1445
+ return workspacePatterns;
1446
+ }
1447
+ /**
1448
+ * Generates common workspace pattern paths
1449
+ */
1450
+ function getCommonWorkspacePaths(packageName, subPath) {
1451
+ const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
1452
+ const commonRoots = [process.cwd(), path.dirname(process.cwd())];
1453
+ const workspacePatterns = [];
1454
+ for (const root of commonRoots) workspacePatterns.push(path.join(root, "packages", packageBaseName || packageName, "dist", "node", subPath, "index.mjs"), path.join(root, "packages", packageBaseName || packageName, "dist", "node", `${subPath}.mjs`), path.join(root, "packages", packageBaseName || packageName, "dist", subPath, "index.js"), path.join(root, "packages", packageBaseName || packageName, "dist", `${subPath}.js`));
1455
+ return workspacePatterns;
1456
+ }
1457
+ /**
1458
+ * Attempts to import from a list of workspace patterns
1459
+ */
1460
+ async function tryWorkspacePatterns(patterns) {
1461
+ for (const workspacePath of patterns) try {
1462
+ return await importSpecifier(workspacePath);
1463
+ } catch {}
1464
+ return null;
1465
+ }
1466
+ /**
1467
+ * Attempts to resolve linked packages using various fallback strategies
1468
+ */
1469
+ async function resolveLinkedPackage(packageName, subPath) {
1470
+ let result = await tryNodeSuggestedPaths(packageName, subPath);
1471
+ if (result) return result;
1472
+ result = await tryImportMetaResolve(packageName, subPath);
1473
+ if (result) return result;
1474
+ result = await tryWorkspacePatterns(await resolveSymlinkedPaths(packageName, subPath));
1475
+ if (result) return result;
1476
+ result = await tryWorkspacePatterns(getCommonWorkspacePaths(packageName, subPath));
1477
+ if (result) return result;
1478
+ return null;
1479
+ }
1480
+ //#endregion
1481
+ //#region src/packages/util.ts
1482
+ childLogger(["reactor-api", "packages/util"]);
1483
+ const PACKAGE_MODULE_FAILED = "ERR_PACKAGE_MODULE_FAILED";
1484
+ /**
1485
+ * Tries to import document models from a package. This function cannot throw.
1486
+ */
1487
+ async function loadDocumentModels(packageName) {
1488
+ return loadDependency(packageName, "document-models");
1489
+ }
1490
+ /**
1491
+ * Tries to import subgraphs from a package. This function cannot throw.
1492
+ */
1493
+ async function loadSubgraphs(packageName) {
1494
+ return loadDependency(packageName, "subgraphs");
1495
+ }
1496
+ /** The header every failed load of a package entry logs, whatever the kind. */
1497
+ function failedLoadHeader(kind) {
1498
+ return `Failed to load ${kind} from @pkg:`;
1499
+ }
1500
+ async function loadScalars(packageName) {
1501
+ return loadDependency(packageName, "scalars");
1502
+ }
1503
+ /**
1504
+ * Tries to import processors from a package. This function cannot throw.
1505
+ */
1506
+ async function loadProcessors(packageName) {
1507
+ return loadDependency(packageName, "processors");
1508
+ }
1509
+ /**
1510
+ * Generic dependency loader - tries to import a dependency from a package. This function cannot throw.
1511
+ * Returns null if the dependency cannot be loaded.
1512
+ */
1513
+ async function loadDependency(packageName, subPath) {
1514
+ const fullPath = path.isAbsolute(packageName) ? pathToFileURL(path.join(packageName, subPath)).href : `${packageName}/${subPath}`;
1515
+ try {
1516
+ return await import(
1517
+ /* @vite-ignore */
1518
+ fullPath
1519
+ );
1520
+ } catch (e) {
1521
+ if (e instanceof Error && "code" in e && (e.code === "ERR_MODULE_NOT_FOUND" || e.code === "ERR_UNSUPPORTED_DIR_IMPORT" || e.code === "ERR_UNSUPPORTED_ESM_URL_SCHEME")) {
1522
+ const result = await resolveLinkedPackage(packageName, subPath);
1523
+ if (result) return result;
1524
+ }
1525
+ throw e;
1526
+ }
1527
+ }
1528
+ /**
1529
+ * The subgraphs a package's `powerhouse.manifest.json` declares, when the
1530
+ * manifest is reachable — which it is for a package identified by an
1531
+ * absolute path (how every local project reaches the loaders). Lets the
1532
+ * package manager warn when a manifest promises subgraphs and the loaders
1533
+ * deliver none, instead of failing silently. For a bare package name the
1534
+ * manifest would have to be resolved through the module system; until a
1535
+ * caller needs that, a bare name answers [] rather than guessing.
1536
+ */
1537
+ function manifestDeclaredSubgraphs(identifier) {
1538
+ if (!path.isAbsolute(identifier)) return [];
1539
+ try {
1540
+ const raw = readFileSync(path.join(identifier, "powerhouse.manifest.json"), "utf-8");
1541
+ const manifest = JSON.parse(raw);
1542
+ if (!Array.isArray(manifest.subgraphs)) return [];
1543
+ return manifest.subgraphs.map((subgraph) => {
1544
+ if (typeof subgraph !== "object" || subgraph === null) return;
1545
+ const { id, name } = subgraph;
1546
+ return id ?? name;
1547
+ }).filter((value) => typeof value === "string" && value.length > 0);
1548
+ } catch {
1549
+ return [];
1550
+ }
1551
+ }
1552
+ function isUpgradeManifest(value) {
1553
+ return typeof value === "object" && value !== null && "documentType" in value && "supportedVersions" in value && "upgrades" in value;
1554
+ }
1555
+ /**
1556
+ * Collects upgrade manifests from a package's document-models namespace.
1557
+ * Handles both the aggregate `upgradeManifests` array export and individual
1558
+ * manifest exports; dedupes by documentType.
1559
+ */
1560
+ function extractUpgradeManifests(namespace) {
1561
+ const manifests = /* @__PURE__ */ new Map();
1562
+ const add = (value) => {
1563
+ if (isUpgradeManifest(value)) manifests.set(value.documentType, value);
1564
+ };
1565
+ for (const value of Object.values(namespace)) if (Array.isArray(value)) value.forEach(add);
1566
+ else add(value);
1567
+ return Array.from(manifests.values());
1568
+ }
1569
+ /** Calls superseded before the timer fires settle with the run that follows. */
1570
+ function debounce(func, delay = 250) {
1571
+ let timer;
1572
+ let waiting = [];
1573
+ const run = async () => {
1574
+ timer = void 0;
1575
+ const callers = waiting;
1576
+ waiting = [];
1577
+ try {
1578
+ const value = await func();
1579
+ callers.forEach((caller) => caller.resolve(value));
1580
+ } catch (error) {
1581
+ callers.forEach((caller) => caller.reject(error));
1582
+ }
1583
+ };
1584
+ return (immediate = false) => {
1585
+ clearTimeout(timer);
1586
+ return new Promise((resolve, reject) => {
1587
+ waiting.push({
1588
+ resolve,
1589
+ reject
1590
+ });
1591
+ if (immediate) run();
1592
+ else timer = setTimeout(() => void run(), delay);
1593
+ });
1594
+ };
1595
+ }
1596
+ function isSubpath(parent, dir) {
1597
+ const relative = path.relative(parent, dir);
1598
+ return relative && !relative.startsWith("..") && !path.isAbsolute(relative);
1599
+ }
1600
+ //#endregion
1601
+ //#region src/utils/detached.ts
1602
+ /** Logs `error` as the message's last replacement and reports it. */
1603
+ function reportFailure({ logger, report }, error, message, ...args) {
1604
+ logger.error(message, ...args, error);
1605
+ try {
1606
+ report?.(error);
1607
+ } catch (reportError) {
1608
+ logger.error("Reporting a failure failed: @error", reportError);
1609
+ }
1610
+ }
1611
+ /** Runs work nobody awaits: a failure is logged and reported, never thrown. */
1612
+ async function runDetached(label, task, options) {
1613
+ try {
1614
+ await task();
1615
+ } catch (error) {
1616
+ reportFailure(options, error, "@label failed: @error", label);
1617
+ }
1618
+ }
1619
+ //#endregion
1620
+ //#region src/graphql/utils.ts
1621
+ function isSubgraphClass(candidate) {
1622
+ if (typeof candidate !== "function") return false;
1623
+ let proto = Object.getPrototypeOf(candidate);
1624
+ while (typeof proto === "function") {
1625
+ if (proto === BaseSubgraph) return true;
1626
+ if (proto.name === "BaseSubgraph") return true;
1627
+ proto = Object.getPrototypeOf(proto);
1628
+ }
1629
+ return false;
1630
+ }
1631
+ function buildGraphqlOperations(operations, skip, first) {
1632
+ return operations.slice(skip, skip + first).map(buildGraphqlOperation);
1633
+ }
1634
+ function buildGraphqlOperation(operation) {
1635
+ const signer = operation.action.context?.signer;
1636
+ return {
1637
+ id: operation.id ?? "",
1638
+ type: operation.action.type,
1639
+ index: operation.index,
1640
+ timestampUtcMs: operation.timestampUtcMs,
1641
+ hash: operation.hash,
1642
+ skip: operation.skip,
1643
+ inputText: typeof operation.action.input === "string" ? operation.action.input : JSON.stringify(operation.action.input),
1644
+ error: operation.error,
1645
+ context: { signer: signer ? {
1646
+ user: signer.user,
1647
+ app: signer.app,
1648
+ signatures: signer.signatures.map((sig) => Array.isArray(sig) ? sig.join(", ") : sig)
1649
+ } : void 0 }
1650
+ };
1651
+ }
1652
+ function buildGraphQlDocument(doc) {
1653
+ const state = doc.state;
1654
+ const initialState = doc.initialState;
1655
+ const globalState = "global" in doc.state ? doc.state.global : {};
1656
+ return {
1657
+ id: doc.header.id,
1658
+ name: doc.header.name,
1659
+ documentType: doc.header.documentType,
1660
+ revision: doc.header.revision.global || 0,
1661
+ createdAtUtcIso: doc.header.createdAtUtcIso,
1662
+ lastModifiedAtUtcIso: doc.header.lastModifiedAtUtcIso,
1663
+ operations: [],
1664
+ stateJSON: globalState,
1665
+ state,
1666
+ initialState
1667
+ };
1668
+ }
1669
+ function buildGraphQlDriveDocument(doc) {
1670
+ return {
1671
+ ...buildGraphQlDocument(doc),
1672
+ meta: { preferredEditor: doc.header.meta?.preferredEditor },
1673
+ slug: doc.header.slug,
1674
+ state: doc.state.global,
1675
+ initialState: doc.state.global
1676
+ };
1677
+ }
1678
+ //#endregion
1679
+ //#region src/packages/document-model-detection.ts
1680
+ /**
1681
+ * The one acceptance rule for a package's `document-models` module.
1682
+ *
1683
+ * The three package loaders duck-typed this independently and disagreed on
1684
+ * one case: the http loader required `documentModel` to be non-null, while
1685
+ * the import and vite loaders accepted any object merely carrying the key,
1686
+ * so an export shaped `{ documentModel: null }` registered as a model under
1687
+ * two loaders and vanished under the third. The strict rule is the correct
1688
+ * one — a module without its documentModel cannot define a document type —
1689
+ * and this predicate is now the single rule all three share, the same way
1690
+ * extractSubgraphs unified the subgraph rule.
1691
+ */
1692
+ function isDocumentModelModule(candidate) {
1693
+ if (candidate === null || typeof candidate !== "object") return false;
1694
+ if (!("documentModel" in candidate)) return false;
1695
+ const model = candidate.documentModel;
1696
+ return model !== null && model !== void 0;
1697
+ }
1698
+ /** Collects the document-model modules among a namespace's exports. */
1699
+ function extractDocumentModels(namespace) {
1700
+ return Object.values(namespace).filter(isDocumentModelModule);
1701
+ }
1702
+ //#endregion
1703
+ //#region src/packages/pieces.ts
1704
+ /** The sub-entry every loader asks a package for its pieces through. */
1705
+ const PIECES_SUBPATH = "pieces";
1706
+ const BUILT_PIECE_LIST = packageJsonExports["./pieces"].node;
1707
+ /** Where a package keeps its piece sources, for telling unbuilt from absent. */
1708
+ const PIECE_SOURCE_LIST = join(PIECES_SUBPATH, "index.ts");
1709
+ /** The nearest enclosing package.json, which `exports` usually hides. */
1710
+ function packageRootOf(dir) {
1711
+ let current = dir;
1712
+ while (!existsSync(join(current, "package.json"))) {
1713
+ const parent = dirname(current);
1714
+ if (parent === current) return void 0;
1715
+ current = parent;
1716
+ }
1717
+ return current;
1718
+ }
1719
+ function resolvePieceList(specifier, hostDir) {
1720
+ try {
1721
+ return fileURLToPath(import.meta.resolve(specifier));
1722
+ } catch (error) {
1723
+ try {
1724
+ return createRequire(join(hostDir, "package.json")).resolve(specifier);
1725
+ } catch {
1726
+ throw error;
1727
+ }
1728
+ }
1729
+ }
1730
+ function pieceListLocation(identifier, hostDir = process.cwd()) {
1731
+ if (isAbsolute(identifier)) return {
1732
+ root: identifier,
1733
+ listPath: join(identifier, BUILT_PIECE_LIST)
1734
+ };
1735
+ const listPath = resolvePieceList(`${identifier}/${PIECES_SUBPATH}`, hostDir);
1736
+ const root = packageRootOf(dirname(listPath));
1737
+ if (!root) throw new Error(`No package.json above ${listPath}`);
1738
+ return {
1739
+ root,
1740
+ listPath
1741
+ };
1742
+ }
1743
+ function packageVersionAt(root) {
1744
+ try {
1745
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1746
+ return typeof pkg.version === "string" && pkg.version !== "" ? pkg.version : void 0;
1747
+ } catch {
1748
+ return;
1749
+ }
1750
+ }
1751
+ function locatePieces(declared, context) {
1752
+ const { root, identifier, logger, version } = context;
1753
+ const located = [];
1754
+ for (const piece of declared) {
1755
+ const where = piece.entry ?? piece.bundle;
1756
+ if (typeof where !== "string" || where === "") {
1757
+ logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
1758
+ continue;
1759
+ }
1760
+ const path = isAbsolute(where) ? where : join(root, where);
1761
+ if (!(piece.entry ? existsSync(path) : existsSync(join(path, "package.json")))) {
1762
+ logger.warn("Piece @piece of @pkg is declared but not built at @path", piece.name, identifier, path);
1763
+ continue;
1764
+ }
1765
+ located.push({
1766
+ name: piece.name,
1767
+ version,
1768
+ ...piece.entry ? { entryPath: path } : { bundleDir: path }
1769
+ });
1770
+ }
1771
+ return located;
1772
+ }
1773
+ function declaredPieces(module, identifier, logger) {
1774
+ const namespace = module ?? {};
1775
+ const declared = namespace.pieces ?? namespace.default;
1776
+ if (!Array.isArray(declared)) {
1777
+ logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", identifier);
1778
+ return;
1779
+ }
1780
+ return declared;
1781
+ }
1782
+ function piecesFromCdnList(module, baseUrl, identifier, logger, version) {
1783
+ const declared = declaredPieces(module, identifier, logger);
1784
+ if (!declared) return [];
1785
+ const located = [];
1786
+ for (const piece of declared) {
1787
+ const where = piece.entry ?? piece.bundle;
1788
+ if (typeof where !== "string" || where === "") {
1789
+ logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
1790
+ continue;
1791
+ }
1792
+ located.push({
1793
+ name: piece.name,
1794
+ version,
1795
+ entryUrl: `${baseUrl}${where.replace(/^dist\/node\/pieces\//, "")}`
1796
+ });
1797
+ }
1798
+ return located;
1799
+ }
1800
+ function piecesFromListModule(module, context) {
1801
+ const namespace = module ?? {};
1802
+ const declared = namespace.pieces ?? namespace.default;
1803
+ if (!Array.isArray(declared)) {
1804
+ context.logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", context.identifier);
1805
+ return [];
1806
+ }
1807
+ const version = packageVersionAt(context.root);
1808
+ if (!version) {
1809
+ context.logger.warn("@pkg has no version in @root/package.json, and a piece takes its package's version; its pieces contribute none", context.identifier, context.root);
1810
+ return [];
1811
+ }
1812
+ return locatePieces(declared, {
1813
+ ...context,
1814
+ version
1815
+ });
1816
+ }
1817
+ //#endregion
1818
+ //#region src/packages/scalar-exports.ts
1819
+ /**
1820
+ * @experimental The scalar exports of a package's `scalars` entry, as this
1821
+ * host reads them; ph-cli passes them to `buildScalarRegistry` for release
1822
+ * evidence.
1823
+ */
1824
+ function scalarExportsOf(namespace) {
1825
+ return Object.entries(namespace).flatMap(([exportName, value]) => {
1826
+ if (isScalarDefinition(value)) return [{
1827
+ exportName,
1828
+ definition: value
1829
+ }];
1830
+ const version = scalarDefinitionVersion(value);
1831
+ return version === void 0 ? [] : [{
1832
+ exportName,
1833
+ unsupportedVersion: version
1834
+ }];
1835
+ });
1836
+ }
1837
+ //#endregion
1838
+ //#region src/packages/subgraph-extraction.ts
1839
+ /**
1840
+ * The one acceptance rule for a package's `subgraphs` module.
1841
+ *
1842
+ * All three package loaders (vite, import, http) consume the same generated
1843
+ * `subgraphs/index` file, and each used to apply its own rule — the vite
1844
+ * loader required a namespace whose alias equalled the class name inside it,
1845
+ * the http loader took any function one level deep, and the import loader
1846
+ * took every nested value. An export that registered under one loader could
1847
+ * silently vanish under another (the codegen-does-not-register-subgraphs
1848
+ * report). This is now the single rule they all share:
1849
+ *
1850
+ * - an export that is itself a subgraph class is accepted (named or default
1851
+ * export of the class);
1852
+ * - any subgraph class among the values of an exported object is accepted
1853
+ * (a `export * as Alias from ...` namespace under any alias, or a
1854
+ * default-exported object of classes);
1855
+ * - everything else — constants, configs, functions and classes that do not
1856
+ * extend BaseSubgraph — is dropped.
1857
+ *
1858
+ * Codegen emits `export * as <ClassName> from "./<dir>/index.js"`
1859
+ * (makeSubgraphsIndexFile in packages/codegen), which the namespace branch
1860
+ * accepts regardless of the alias; hand-written packages may re-export a
1861
+ * class directly, which the direct branch accepts. A class reached through
1862
+ * both branches is returned once.
1863
+ */
1864
+ function extractSubgraphs(namespace) {
1865
+ const found = [];
1866
+ const add = (candidate) => {
1867
+ if (isSubgraphClass(candidate) && !found.includes(candidate)) found.push(candidate);
1868
+ };
1869
+ for (const value of valuesByName(namespace)) {
1870
+ add(value);
1871
+ if (value !== null && typeof value === "object") for (const inner of valuesByName(value)) add(inner);
1872
+ }
1873
+ return found;
1874
+ }
1875
+ function valuesByName(record) {
1876
+ const keys = Object.keys(record);
1877
+ if (Object.prototype.toString.call(record) === "[object Module]") keys.sort();
1878
+ return keys.map((key) => record[key]);
1879
+ }
1880
+ //#endregion
1881
+ export { RequestClientBinder as A, CanonicalDocumentIdResolutionError as B, loadDocumentModels as C, manifestDeclaredSubgraphs as D, loadSubgraphs as E, READABLE_DOCUMENTS_NAMESPACE as F, AuthEvaluationUnsupportedError as G, AuthorizationPolicy as H, ReadableDocumentsProjection as I, MalformedStoredOperationError as J, AuthenticationRequiredError as K, applyReadableFilter as L, createCredentialInvalidator as M, DEFAULT_ROOT_TYPES as N, BaseSubgraph as O, EVERYONE as P, isDocumentListed as R, isSubpath as S, loadScalars as T, AuthorizedDocumentHandle as U, createCanonicalDocumentIdResolver as V, createAuthorizationService as W, RefusalNotRecordedError as Y, runDetached as _, PIECE_SOURCE_LIST as a, extractUpgradeManifests as b, piecesFromCdnList as c, buildGraphQlDocument as d, buildGraphQlDriveDocument as f, reportFailure as g, isSubgraphClass as h, PIECES_SUBPATH as i, AuthService as j, callerSubject as k, piecesFromListModule as l, buildGraphqlOperations as m, scalarExportsOf as n, packageRootOf as o, buildGraphqlOperation as p, ForbiddenError as q, BUILT_PIECE_LIST as r, pieceListLocation as s, extractSubgraphs as t, extractDocumentModels as u, PACKAGE_MODULE_FAILED as v, loadProcessors as w, failedLoadHeader as x, debounce as y, readableDocumentsSubquery as z };
1882
+
1883
+ //# sourceMappingURL=subgraph-extraction-C_hFvSaS.mjs.map
1884
+ //# debugId=1629639f-53d5-56ba-9006-abc2cb9963c0