@powerhousedao/reactor-api 6.2.3 → 6.3.0-dev.1

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 (57) hide show
  1. package/dist/{adapter-gateway-apollo-B54G_cXT.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +12 -14
  2. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
  3. package/dist/{adapter-gateway-mercurius-rbKlwF9m.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +4 -12
  4. package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
  5. package/dist/{adapter-http-express-CWqziB1p.mjs → adapter-http-express-78KD77cI.mjs} +7 -7
  6. package/dist/adapter-http-express-78KD77cI.mjs.map +1 -0
  7. package/dist/{adapter-http-fastify-CYZQ6FFv.mjs → adapter-http-fastify-Dk7aT_xw.mjs} +7 -7
  8. package/dist/adapter-http-fastify-Dk7aT_xw.mjs.map +1 -0
  9. package/dist/base-document-models-caJpqTLw.mjs +2083 -0
  10. package/dist/base-document-models-caJpqTLw.mjs.map +1 -0
  11. package/dist/create-schema-BCArFBv9.d.mts +167 -0
  12. package/dist/create-schema-BCArFBv9.d.mts.map +1 -0
  13. package/dist/error-info-Cr6oQACe.mjs +601 -0
  14. package/dist/error-info-Cr6oQACe.mjs.map +1 -0
  15. package/dist/index.d.mts +2944 -930
  16. package/dist/index.d.mts.map +1 -1
  17. package/dist/index.mjs +7111 -2845
  18. package/dist/index.mjs.map +1 -1
  19. package/dist/package-subgraph-check-BxKx9kcQ.mjs +138 -0
  20. package/dist/package-subgraph-check-BxKx9kcQ.mjs.map +1 -0
  21. package/dist/pglite-like-CKQEL_Q0.d.mts +27 -0
  22. package/dist/pglite-like-CKQEL_Q0.d.mts.map +1 -0
  23. package/dist/pglite-node-CcX2YT-l.mjs +744 -0
  24. package/dist/pglite-node-CcX2YT-l.mjs.map +1 -0
  25. package/dist/src/graphql/subgraph-types.d.mts +43 -0
  26. package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
  27. package/dist/src/graphql/subgraph-types.mjs +14 -0
  28. package/dist/src/graphql/subgraph-types.mjs.map +1 -0
  29. package/dist/src/packages/vite-loader.d.mts +13 -2
  30. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  31. package/dist/src/packages/vite-loader.mjs +122 -69
  32. package/dist/src/packages/vite-loader.mjs.map +1 -1
  33. package/dist/src/pglite/pglite-node.d.mts +434 -0
  34. package/dist/src/pglite/pglite-node.d.mts.map +1 -0
  35. package/dist/src/pglite/pglite-node.mjs +5 -0
  36. package/dist/src/pglite/worker/entry.d.mts +2 -0
  37. package/dist/src/pglite/worker/entry.mjs +298 -0
  38. package/dist/src/pglite/worker/entry.mjs.map +1 -0
  39. package/dist/subgraph-extraction-uJ8BR0he.mjs +2020 -0
  40. package/dist/subgraph-extraction-uJ8BR0he.mjs.map +1 -0
  41. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs +10 -0
  42. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs.map +1 -0
  43. package/dist/{types-CuSz_zv6.d.mts → types-Bz_xjf8j.d.mts} +41 -7
  44. package/dist/types-Bz_xjf8j.d.mts.map +1 -0
  45. package/package.json +36 -23
  46. package/dist/adapter-gateway-apollo-B54G_cXT.mjs.map +0 -1
  47. package/dist/adapter-gateway-apollo-D2DNlPY0.mjs +0 -4
  48. package/dist/adapter-gateway-mercurius-rbKlwF9m.mjs.map +0 -1
  49. package/dist/adapter-gateway-stitching-Dzv10u8D.mjs +0 -321
  50. package/dist/adapter-gateway-stitching-Dzv10u8D.mjs.map +0 -1
  51. package/dist/adapter-http-express-CWqziB1p.mjs.map +0 -1
  52. package/dist/adapter-http-fastify-CYZQ6FFv.mjs.map +0 -1
  53. package/dist/pieces-swupjgIO.mjs +0 -790
  54. package/dist/pieces-swupjgIO.mjs.map +0 -1
  55. package/dist/types-CuSz_zv6.d.mts.map +0 -1
  56. package/dist/websocket-_SH5aBcy.mjs +0 -18
  57. package/dist/websocket-_SH5aBcy.mjs.map +0 -1
@@ -0,0 +1,2020 @@
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]="f1ee108b-9a7f-5652-b111-a79a7b101b2e")}catch(e){}}();
3
+ import { createRequire } from "node:module";
4
+ import { childLogger, compileSubgraph, createSubgraphEntryBuilders, projectSubgraphGraphQL, readSubgraphProtocol } from "document-model";
5
+ import { gql } from "graphql-tag";
6
+ import { GraphQLError, print } 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
+ /** What a caller the access gate refused is told. */
696
+ const NO_LICENCE_MESSAGE = "No licence for this app";
697
+ const DEFAULT_CREDENTIAL_CACHE_TTL_MS = 6e4;
698
+ const CREDENTIAL_CACHE_MAX_ENTRIES = 1e3;
699
+ /** The invalidator a subgraph receives: forwards to `authService`, or does
700
+ * nothing when the host runs without one. */
701
+ function createCredentialInvalidator(authService) {
702
+ return { invalidateCredential: (address, chainId, appDid) => authService?.invalidateCredential(address, chainId, appDid) ?? 0 };
703
+ }
704
+ var AuthService = class {
705
+ config;
706
+ credentialCache = /* @__PURE__ */ new Map();
707
+ invalidationListeners = /* @__PURE__ */ new Set();
708
+ constructor(config) {
709
+ this.config = config;
710
+ }
711
+ /**
712
+ * Whether this service reads the bearer at all. Defaults to `enabled`, so a
713
+ * config written before `resolveIdentity` existed behaves exactly as it did.
714
+ */
715
+ get resolvesIdentity() {
716
+ return this.config.resolveIdentity ?? this.config.enabled;
717
+ }
718
+ /**
719
+ * `ACCESS=licensed`: only admins and licence holders may use the host, so
720
+ * nothing is served to an anonymous caller, drive discovery included.
721
+ */
722
+ get refusesAnonymousCallers() {
723
+ return this.config.accessGate !== void 0;
724
+ }
725
+ /** The context an unresolved request gets: no user, and no admin list to match against. */
726
+ anonymousContext() {
727
+ return {
728
+ user: void 0,
729
+ admins: [],
730
+ auth_enabled: this.config.enabled
731
+ };
732
+ }
733
+ async authenticateRequest(request) {
734
+ if (!this.resolvesIdentity) return this.anonymousContext();
735
+ if (request.method === "OPTIONS") return {
736
+ user: void 0,
737
+ admins: this.config.admins,
738
+ auth_enabled: this.config.enabled
739
+ };
740
+ return this.verifyBearer(request.headers.get("authorization") ?? void 0);
741
+ }
742
+ /**
743
+ * Verify a Bearer token regardless of HTTP method. Use this from non-GraphQL
744
+ * middleware that must enforce authentication on every request.
745
+ */
746
+ async verifyBearer(authorization) {
747
+ if (!this.resolvesIdentity) return this.anonymousContext();
748
+ const token = authorization?.split(" ")[1];
749
+ if (!token) return {
750
+ user: void 0,
751
+ admins: this.config.admins,
752
+ auth_enabled: this.config.enabled
753
+ };
754
+ try {
755
+ const verified = await this.verifyToken(token);
756
+ if (!verified) return new Response(JSON.stringify({ error: "Verification failed" }), { status: 401 });
757
+ const user = this.extractUserFromVerification(verified);
758
+ if (!user) return new Response(JSON.stringify({ error: "Missing credentials" }), { status: 401 });
759
+ if (!this.config.skipCredentialVerification) {
760
+ if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) return new Response(JSON.stringify({ error: "Credentials no longer valid" }), { status: 401 });
761
+ }
762
+ if (!await this.admitted(user)) return new Response(JSON.stringify({ error: NO_LICENCE_MESSAGE }), {
763
+ status: 403,
764
+ headers: { "content-type": "application/json" }
765
+ });
766
+ this.config.onVerified?.(user);
767
+ return {
768
+ user,
769
+ admins: this.config.admins,
770
+ auth_enabled: this.config.enabled
771
+ };
772
+ } catch {
773
+ return new Response(JSON.stringify({ error: "Authentication failed" }), { status: 401 });
774
+ }
775
+ }
776
+ /** Throws only for a bearer that is present and unusable, as HTTP 401s it. */
777
+ async authenticateWebSocketConnection(connectionParams) {
778
+ if (!this.resolvesIdentity) return null;
779
+ const authHeader = connectionParams.authorization;
780
+ if (!authHeader) return null;
781
+ const token = authHeader.split(" ")[1];
782
+ if (!token) throw new Error("Invalid authorization format");
783
+ const verified = await this.verifyToken(token);
784
+ if (!verified) throw new Error("Token verification failed");
785
+ const user = this.extractUserFromVerification(verified);
786
+ if (!user) throw new Error("Invalid credentials");
787
+ if (!this.config.skipCredentialVerification) {
788
+ if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) throw new Error("Credentials no longer valid");
789
+ }
790
+ if (!await this.admitted(user)) throw new Error(NO_LICENCE_MESSAGE);
791
+ this.config.onVerified?.(user);
792
+ return user;
793
+ }
794
+ /** {@inheritDoc ICredentialInvalidator.invalidateCredential} */
795
+ invalidateCredential(address, chainId, appDid) {
796
+ const normalized = address.toLowerCase();
797
+ let evicted = 0;
798
+ for (const [key, entry] of this.credentialCache) if (entry.address === normalized && (chainId === void 0 || entry.chainId === chainId) && (appDid === void 0 || entry.appId === appDid)) {
799
+ this.credentialCache.delete(key);
800
+ evicted++;
801
+ }
802
+ const invalidation = { address: normalized };
803
+ if (chainId !== void 0) invalidation.chainId = chainId;
804
+ if (appDid !== void 0) invalidation.appDid = appDid;
805
+ for (const listener of this.invalidationListeners) try {
806
+ listener(invalidation);
807
+ } catch {}
808
+ return evicted;
809
+ }
810
+ /** Called after every `invalidateCredential`; returns an unsubscribe. */
811
+ onCredentialInvalidated(listener) {
812
+ this.invalidationListeners.add(listener);
813
+ return () => {
814
+ this.invalidationListeners.delete(listener);
815
+ };
816
+ }
817
+ /**
818
+ * Whether an already-authenticated principal's credential still holds, for
819
+ * re-checking long-lived connections. Goes through the same cache as
820
+ * admission, so it costs at most one verifier call per identity per TTL.
821
+ */
822
+ async isCredentialValid(user) {
823
+ return (this.config.skipCredentialVerification || await this.verifyCredentialExists(user.address, user.chainId, user.appKey)) && await this.admitted(user);
824
+ }
825
+ /** ACCESS=licensed: admins pass; everyone else needs the gate's yes (or its grace). */
826
+ async admitted(user) {
827
+ const gate = this.config.accessGate;
828
+ if (!gate) return true;
829
+ const address = user.address.toLowerCase();
830
+ if (this.config.admins.some((admin) => admin.toLowerCase() === address)) return true;
831
+ return (await gate.check(address)).allowed;
832
+ }
833
+ /**
834
+ * Verify the auth bearer token
835
+ */
836
+ async verifyToken(token) {
837
+ return await verifyAuthBearerToken(token);
838
+ }
839
+ /**
840
+ * Extract user information from verification result.
841
+ *
842
+ * The issuer is required along with the credential subject. A credential that
843
+ * verified must carry one -- resolving it is how the signature was checked --
844
+ * so this rejects a shape that cannot have come from verification rather than
845
+ * admitting a keyless principal.
846
+ */
847
+ extractUserFromVerification(verified) {
848
+ try {
849
+ const { address, chainId, networkId } = verified.verifiableCredential.credentialSubject;
850
+ const appKey = verified.issuer;
851
+ if (!address || !chainId || !networkId || !appKey) return null;
852
+ return {
853
+ address,
854
+ chainId,
855
+ networkId,
856
+ appKey
857
+ };
858
+ } catch {
859
+ return null;
860
+ }
861
+ }
862
+ /**
863
+ * Verify that the credential still exists on the Renown API.
864
+ *
865
+ * Results are cached per (address, chainId, issuer) for a short TTL so the
866
+ * blocking external round-trip is not paid on every request. Concurrent
867
+ * checks for the same key share a single in-flight request, and entries
868
+ * that resolve to false are evicted immediately so failed or revoked
869
+ * credentials are re-checked on the next request.
870
+ */
871
+ verifyCredentialExists(address, chainId, appId) {
872
+ const ttlMs = this.config.credentialVerificationCacheTtlMs ?? DEFAULT_CREDENTIAL_CACHE_TTL_MS;
873
+ if (ttlMs <= 0) return this.fetchCredentialExists(address, chainId, appId);
874
+ const key = `${address.toLowerCase()}:${chainId}:${appId}`;
875
+ const now = Date.now();
876
+ const cached = this.credentialCache.get(key);
877
+ if (cached && cached.expiresAt > now) return cached.exists;
878
+ this.pruneCredentialCache(now);
879
+ const entry = {
880
+ exists: this.fetchCredentialExists(address, chainId, appId).then((exists) => {
881
+ if (!exists && this.credentialCache.get(key) === entry) this.credentialCache.delete(key);
882
+ return exists;
883
+ }),
884
+ expiresAt: now + ttlMs,
885
+ address: address.toLowerCase(),
886
+ chainId,
887
+ appId
888
+ };
889
+ this.credentialCache.set(key, entry);
890
+ return entry.exists;
891
+ }
892
+ /**
893
+ * Enforce the cache size cap before inserting a new entry: drop expired
894
+ * entries first, then evict oldest-inserted entries (insertion order
895
+ * matches expiry order since the TTL is constant) until under the cap, so
896
+ * a flood of distinct keys cannot grow the map without bound.
897
+ */
898
+ pruneCredentialCache(now) {
899
+ if (this.credentialCache.size < CREDENTIAL_CACHE_MAX_ENTRIES) return;
900
+ for (const [key, entry] of this.credentialCache) if (entry.expiresAt <= now) this.credentialCache.delete(key);
901
+ while (this.credentialCache.size >= CREDENTIAL_CACHE_MAX_ENTRIES) {
902
+ const oldestKey = this.credentialCache.keys().next().value;
903
+ if (oldestKey === void 0) break;
904
+ this.credentialCache.delete(oldestKey);
905
+ }
906
+ }
907
+ async fetchCredentialExists(address, chainId, appId) {
908
+ if (!this.config.verifyCredential) throw new Error("AuthService: credential verification is enabled but no verifyCredential was provided");
909
+ return this.config.verifyCredential({
910
+ address,
911
+ chainId,
912
+ appId
913
+ });
914
+ }
915
+ };
916
+ //#endregion
917
+ //#region src/graphql/request-clients.ts
918
+ /** A resolver outside a mutation asked for the write client. */
919
+ var WriteClientUnavailableError = class extends Error {
920
+ operation;
921
+ field;
922
+ constructor(operation, field) {
923
+ const where = field ? `field ${field}` : "this resolver";
924
+ const running = operation === "unbound" ? "outside a mutation" : `in a ${operation}`;
925
+ super(`ctx.clients.write is only available to Mutation fields; ${where} runs ${running}. Read through ctx.clients.read.`);
926
+ this.name = "WriteClientUnavailableError";
927
+ this.operation = operation;
928
+ this.field = field;
929
+ }
930
+ static isError(error) {
931
+ return error instanceof Error && error.name === "WriteClientUnavailableError";
932
+ }
933
+ };
934
+ /** The field whose resolver is running, so a refusal can name it. */
935
+ const executingField = new AsyncLocalStorage();
936
+ const operations = /* @__PURE__ */ new WeakMap();
937
+ /**
938
+ * The clients for one operation: both halves for a mutation, the read half
939
+ * and a refusing `write` for anything else. The refusing property is not
940
+ * enumerable, so spreading or printing the clients does not trip it.
941
+ */
942
+ function createRequestClients(read, write, operation) {
943
+ let clients;
944
+ if (operation === "mutation") clients = Object.freeze({
945
+ read,
946
+ write
947
+ });
948
+ else {
949
+ const gated = { read };
950
+ Object.defineProperty(gated, "write", {
951
+ enumerable: false,
952
+ get() {
953
+ throw new WriteClientUnavailableError(operation, executingField.getStore());
954
+ }
955
+ });
956
+ clients = Object.freeze(gated);
957
+ }
958
+ operations.set(clients, operation);
959
+ return clients;
960
+ }
961
+ /**
962
+ * The read half alone, for a context nobody bound to an operation (a resolver
963
+ * called directly rather than through the GraphQL layer). `write` refuses.
964
+ */
965
+ function readOnlyClients(read) {
966
+ return createRequestClients(read, UNAVAILABLE_WRITE, "unbound");
967
+ }
968
+ /** Never reached: a non-mutation client set refuses before handing it out. */
969
+ const UNAVAILABLE_WRITE = {};
970
+ /**
971
+ * Both halves for a field that reads write-side state outside a mutation. The
972
+ * clients still report `operation`, so identifiers resolve on the read side.
973
+ */
974
+ function createWriteSideClients(read, write, operation) {
975
+ const clients = Object.freeze({
976
+ read,
977
+ write
978
+ });
979
+ operations.set(clients, operation);
980
+ return clients;
981
+ }
982
+ /**
983
+ * The operation the clients were built for, or undefined for clients that
984
+ * {@link createRequestClients} did not build (a hand-made pair in a test).
985
+ */
986
+ function operationOfClients(clients) {
987
+ return clients === void 0 ? void 0 : operations.get(clients);
988
+ }
989
+ /**
990
+ * A resolver map's own object, as opposed to a scalar or another class
991
+ * instance, which passes through. Checked by prototype rather than with
992
+ * `isScalarType`, which refuses a scalar from another copy of graphql.
993
+ */
994
+ function isPlainObject(value) {
995
+ if (value === null || typeof value !== "object") return false;
996
+ const prototype = Object.getPrototypeOf(value);
997
+ return prototype === Object.prototype || prototype === null;
998
+ }
999
+ /** Type-level resolvers that receive the context; each is `(value, ctx, info)`. */
1000
+ const TYPE_LEVEL_RESOLVERS = /* @__PURE__ */ new Set([
1001
+ "__resolveReference",
1002
+ "__resolveType",
1003
+ "__isTypeOf"
1004
+ ]);
1005
+ /**
1006
+ * Puts the client halves on the GraphQL context per operation. The host builds
1007
+ * one context per request (or per WebSocket operation) before it knows what
1008
+ * the operation is; every resolver this binder wraps receives instead a
1009
+ * context derived from that one for the operation it is running in, so a
1010
+ * mutation gets `ctx.clients.write` and a query or subscription does not.
1011
+ *
1012
+ * The derived context is memoized per request context and operation, so every
1013
+ * field of one operation sees the same object, which per-request memos key on.
1014
+ */
1015
+ var RequestClientBinder = class {
1016
+ #read;
1017
+ #write;
1018
+ #contexts = /* @__PURE__ */ new WeakMap();
1019
+ #derived = /* @__PURE__ */ new WeakSet();
1020
+ #wrapped = /* @__PURE__ */ new WeakMap();
1021
+ constructor(read, write) {
1022
+ this.#read = read;
1023
+ this.#write = write;
1024
+ }
1025
+ /** The clients for a context the host builds before the operation is known. */
1026
+ unboundClients() {
1027
+ return createRequestClients(this.#read, this.#write, "unbound");
1028
+ }
1029
+ /**
1030
+ * The context a resolver of `operation` receives for request context `base`.
1031
+ * `writeSide` hands a query field the write client too: a field declared to
1032
+ * read write-side state.
1033
+ */
1034
+ contextFor(base, operation, writeSide = false) {
1035
+ if (this.#derived.has(base)) return base;
1036
+ let byOperation = this.#contexts.get(base);
1037
+ if (!byOperation) {
1038
+ byOperation = /* @__PURE__ */ new Map();
1039
+ this.#contexts.set(base, byOperation);
1040
+ }
1041
+ const key = writeSide ? `${operation}:write-side` : operation;
1042
+ let derived = byOperation.get(key);
1043
+ if (!derived) {
1044
+ derived = {
1045
+ ...base,
1046
+ clients: writeSide ? createWriteSideClients(this.#read, this.#write, operation) : createRequestClients(this.#read, this.#write, operation)
1047
+ };
1048
+ this.#derived.add(derived);
1049
+ byOperation.set(key, derived);
1050
+ }
1051
+ return derived;
1052
+ }
1053
+ /**
1054
+ * A copy of a subgraph's resolver map whose resolvers receive the context
1055
+ * for their operation. Scalars, enums and non-function members pass through.
1056
+ * `writeSideFields` names the fields (`Type.field`) handed the write client
1057
+ * whatever their operation. The copy is memoized per map.
1058
+ */
1059
+ bindResolvers(resolvers, writeSideFields = /* @__PURE__ */ new Set()) {
1060
+ const cached = this.#wrapped.get(resolvers);
1061
+ if (cached) return cached;
1062
+ const bound = {};
1063
+ for (const [typeName, typeResolvers] of Object.entries(resolvers)) bound[typeName] = this.#bindType(typeName, typeResolvers, writeSideFields);
1064
+ this.#wrapped.set(resolvers, bound);
1065
+ return bound;
1066
+ }
1067
+ #bindType(typeName, typeResolvers, writeSideFields) {
1068
+ if (!isPlainObject(typeResolvers)) return typeResolvers;
1069
+ const bound = {};
1070
+ for (const [field, value] of Object.entries(typeResolvers)) {
1071
+ const writeSide = writeSideFields.has(`${typeName}.${field}`);
1072
+ if (typeof value === "function") bound[field] = TYPE_LEVEL_RESOLVERS.has(field) ? this.#bindTypeResolver(value) : field.startsWith("__") ? value : this.#bindFieldResolver(value, writeSide);
1073
+ else if (isPlainObject(value)) {
1074
+ const config = { ...value };
1075
+ for (const key of ["resolve", "subscribe"]) if (typeof config[key] === "function") config[key] = this.#bindFieldResolver(config[key], writeSide);
1076
+ bound[field] = config;
1077
+ } else bound[field] = value;
1078
+ }
1079
+ return bound;
1080
+ }
1081
+ #bindFieldResolver(resolver, writeSide) {
1082
+ return (parent, args, context, info) => {
1083
+ if (!info?.operation) return resolver(parent, args, context, info);
1084
+ const derived = this.contextFor(context ?? {}, info.operation.operation, writeSide);
1085
+ return executingField.run(`${info.parentType.name}.${info.fieldName}`, () => resolver(parent, args, derived, info));
1086
+ };
1087
+ }
1088
+ #bindTypeResolver(resolver) {
1089
+ return (value, context, info) => {
1090
+ if (!info?.operation) return resolver(value, context, info);
1091
+ return resolver(value, this.contextFor(context ?? {}, info.operation.operation), info);
1092
+ };
1093
+ }
1094
+ };
1095
+ //#endregion
1096
+ //#region src/graphql/base-subgraph.ts
1097
+ /**
1098
+ * Stands in for a client the subgraph was not given: any use names what to
1099
+ * use instead rather than failing on `undefined`.
1100
+ */
1101
+ function missingClient(name, hint) {
1102
+ return new Proxy({}, { get(_target, property) {
1103
+ if (property === "then" || typeof property === "symbol") return;
1104
+ throw new Error(`${name}.${String(property)}: ${hint}`);
1105
+ } });
1106
+ }
1107
+ /**
1108
+ * The subject a request reads as: its address and the app key its token
1109
+ * carries. Anonymous is an empty subject, never the host's signer.
1110
+ */
1111
+ function callerSubject(user) {
1112
+ return {
1113
+ address: user?.address,
1114
+ key: user?.appKey
1115
+ };
1116
+ }
1117
+ var BaseSubgraph = class {
1118
+ name = "example";
1119
+ path = "";
1120
+ resolvers = { Query: { hello: () => this.name } };
1121
+ typeDefs = gql`
1122
+ type Query {
1123
+ hello: String
1124
+ }
1125
+ `;
1126
+ /**
1127
+ * The read half, for setup-time use (schema building, model lookup).
1128
+ * Resolvers read through `ctx.clients.read` instead.
1129
+ */
1130
+ readClient;
1131
+ /**
1132
+ * @deprecated The facade over both halves, for subgraphs that have not
1133
+ * moved. Resolvers use `ctx.clients.read` and, in a mutation,
1134
+ * `ctx.clients.write`; setup-time code uses {@link readClient}.
1135
+ */
1136
+ reactorClient;
1137
+ /** This package's namespaced slice of the HTTP surface. */
1138
+ http;
1139
+ graphqlManager;
1140
+ relationalDb;
1141
+ syncManager;
1142
+ documentPermissionService;
1143
+ authorizationService;
1144
+ syncServingGate;
1145
+ /**
1146
+ * The readable-documents read model (`services/readable-documents.ts`):
1147
+ * the host ACL's read closure as rows an index table joins on. Absent on
1148
+ * a host that does not serve it; `readableFilter` then fails closed for
1149
+ * every caller but a listed admin.
1150
+ */
1151
+ readableDocuments;
1152
+ /**
1153
+ * The host's credential cache, for a package that revokes credentials:
1154
+ * call `this.credentials.invalidateCredential(address, chainId?, appDid?)`
1155
+ * right after the revocation is stored, so this host refuses the credential
1156
+ * on the next request and closes WebSocket connections that rely on it.
1157
+ * A no-op on a host without authentication.
1158
+ */
1159
+ credentials;
1160
+ /**
1161
+ * Per-request memo of raw identifier to canonical document id, keyed on the
1162
+ * request context object so entries are released when the request ends. Lets
1163
+ * batch resolvers resolve each distinct identifier at most once.
1164
+ */
1165
+ #canonicalIdMemo = /* @__PURE__ */ new WeakMap();
1166
+ #unboundClients;
1167
+ #attachments;
1168
+ #attachmentClientMemo = /* @__PURE__ */ new WeakMap();
1169
+ constructor(args) {
1170
+ const facadeRead = args.reactorClient?.read;
1171
+ this.readClient = args.readClient ?? (typeof facadeRead?.get === "function" ? facadeRead : args.reactorClient) ?? missingClient("BaseSubgraph.readClient", "this subgraph was constructed without a readClient.");
1172
+ 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.");
1173
+ this.#unboundClients = readOnlyClients(this.readClient);
1174
+ this.http = args.http;
1175
+ this.graphqlManager = args.graphqlManager;
1176
+ this.relationalDb = args.relationalDb;
1177
+ this.syncManager = args.syncManager;
1178
+ this.documentPermissionService = args.documentPermissionService;
1179
+ this.authorizationService = args.authorizationService;
1180
+ this.syncServingGate = args.syncServingGate;
1181
+ this.readableDocuments = args.readableDocuments;
1182
+ this.path = args.path ?? "";
1183
+ this.#attachments = args.attachments;
1184
+ this.credentials = args.credentials ?? createCredentialInvalidator(void 0);
1185
+ }
1186
+ /**
1187
+ * An attachment client bound to this request's caller, memoized per request.
1188
+ *
1189
+ * @throws Error when the host provides no attachment client to subgraphs.
1190
+ */
1191
+ attachmentsFor(ctx) {
1192
+ if (!this.#attachments) throw new Error("This host provides no attachment client to subgraphs");
1193
+ let client = this.#attachmentClientMemo.get(ctx);
1194
+ if (!client) {
1195
+ client = this.#attachments.forSubject(callerSubject(ctx.user));
1196
+ this.#attachmentClientMemo.set(ctx, client);
1197
+ }
1198
+ return client;
1199
+ }
1200
+ /**
1201
+ * The clients this request's operation may use: those the GraphQL layer put
1202
+ * on the context. A context it never saw (a resolver called directly) reads
1203
+ * through {@link readClient} and may not write.
1204
+ */
1205
+ clientsOf(ctx) {
1206
+ return ctx?.clients ?? this.#unboundClients;
1207
+ }
1208
+ async onSetup() {}
1209
+ async onDisconnect() {}
1210
+ /**
1211
+ * Resolves a caller-supplied identifier (id or slug) to its canonical
1212
+ * document id, memoized per request. Both the decision layer and the data
1213
+ * layer must agree on the subject, so this runs the lookup the data path
1214
+ * uses: `resolveIdOrSlug` on the read half for a query, `describe` on the
1215
+ * write half for a mutation. A resolution failure (not found, ambiguous, or
1216
+ * transient) surfaces as a generic Forbidden, fail-closed, so a bad
1217
+ * identifier cannot be used as a document-existence oracle.
1218
+ */
1219
+ async resolveCanonicalDocumentId(identifier, requestKey) {
1220
+ let cache = this.#canonicalIdMemo.get(requestKey);
1221
+ if (!cache) {
1222
+ cache = /* @__PURE__ */ new Map();
1223
+ this.#canonicalIdMemo.set(requestKey, cache);
1224
+ }
1225
+ const cached = cache.get(identifier);
1226
+ if (cached !== void 0) return cached;
1227
+ const clients = this.clientsOf(requestKey);
1228
+ const resolve = operationOfClients(clients) === "mutation" ? createCanonicalDocumentIdResolver({
1229
+ read: clients.read,
1230
+ write: clients.write
1231
+ }, "mutation") : createCanonicalDocumentIdResolver({ read: clients.read }, "query");
1232
+ let canonical;
1233
+ try {
1234
+ canonical = await resolve(identifier);
1235
+ } catch {
1236
+ throw new ForbiddenError();
1237
+ }
1238
+ cache.set(identifier, canonical);
1239
+ return canonical;
1240
+ }
1241
+ /**
1242
+ * Resolves the args' `documentId` to canonical form. Unconditional (unlike the
1243
+ * assertCan* helpers, no admin skip): ACL rows are keyed on the canonical id.
1244
+ */
1245
+ async withCanonicalDocumentId(args, requestKey) {
1246
+ const documentId = await this.resolveCanonicalDocumentId(args.documentId, requestKey);
1247
+ return {
1248
+ ...args,
1249
+ documentId
1250
+ };
1251
+ }
1252
+ /**
1253
+ * Resolves an identifier for a per-document check, or null when the caller has
1254
+ * policy-wide access (OPEN or supreme admin) and the check can be skipped.
1255
+ * Only DOCUMENT_PERMISSIONS keys on the document id, so other policies fail
1256
+ * closed without resolving.
1257
+ */
1258
+ async #resolveForCheck(identifier, ctx) {
1259
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return null;
1260
+ if (this.authorizationService.config.policy !== AuthorizationPolicy.DOCUMENT_PERMISSIONS) throw new ForbiddenError();
1261
+ return this.resolveCanonicalDocumentId(identifier, ctx);
1262
+ }
1263
+ /**
1264
+ * Read filter for an already-canonical document id (one sourced from the data
1265
+ * layer, such as a fetched document's id). Performs no slug resolution.
1266
+ */
1267
+ async canReadDocument(documentId, ctx) {
1268
+ return this.authorizationService.canRead(documentId, ctx.user?.address);
1269
+ }
1270
+ /** The ids or slugs in `ids` that {@link assertCanRead} admits, in order; the rest are dropped. */
1271
+ async filterReadableDocumentIds(ids, ctx) {
1272
+ const readable = [];
1273
+ for (const id of ids) {
1274
+ try {
1275
+ await this.assertCanRead(id, ctx);
1276
+ } catch (error) {
1277
+ if (error instanceof ForbiddenError) continue;
1278
+ throw error;
1279
+ }
1280
+ readable.push(id);
1281
+ }
1282
+ return readable;
1283
+ }
1284
+ /** Drops the items the host's own ACL refuses the caller. */
1285
+ async readableByHost(items, ctx) {
1286
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return [...items];
1287
+ const readable = [];
1288
+ for (const item of items) if (await this.canReadDocument(item.id, ctx)) readable.push(item);
1289
+ return readable;
1290
+ }
1291
+ /**
1292
+ * Whether the caller is in the ADMINS list. Not `isSupremeAdmin`: under
1293
+ * OPEN that admits every caller, anonymous included.
1294
+ */
1295
+ isListedAdmin(ctx) {
1296
+ const address = ctx.user?.address.toLowerCase();
1297
+ return address !== void 0 && this.authorizationService.config.admins.includes(address);
1298
+ }
1299
+ /**
1300
+ * The readable-documents filter for this request's caller, for a query
1301
+ * over an index table keyed by document (`applyReadableFilter`). Without
1302
+ * the read model only a listed admin reads anything: an index must never
1303
+ * serve more than the host would.
1304
+ */
1305
+ readableFilter(ctx) {
1306
+ if (this.readableDocuments) return this.readableDocuments.filterFor(ctx.user?.address);
1307
+ return this.isListedAdmin(ctx) ? { kind: "all" } : { kind: "none" };
1308
+ }
1309
+ /**
1310
+ * The row filter for an index query scoped to one document (its drive or
1311
+ * folder): `none` when the caller may not read the scope itself, the
1312
+ * caller's `readableFilter` otherwise. One call per resolver, then
1313
+ * `applyReadableFilter` on every query it runs.
1314
+ */
1315
+ async indexAccess(ctx, scopeDocumentId) {
1316
+ const filter = this.readableFilter(ctx);
1317
+ if (filter.kind !== "ids") return filter;
1318
+ return await isDocumentListed(this.relationalDb, filter, scopeDocumentId) ? filter : { kind: "none" };
1319
+ }
1320
+ /**
1321
+ * The principal a request decides as: the authenticated caller's address, and
1322
+ * the did:key of the app instance whose token authenticated it.
1323
+ *
1324
+ * Both, because a policy can name either. The key is what a document records
1325
+ * as its creator, so a subject built without one cannot match the creator's
1326
+ * standing permission over the auth scope -- the document's own creator would
1327
+ * be refused an operation the write path accepts, since a signed action
1328
+ * carries the same key. Anonymous callers supply neither.
1329
+ */
1330
+ viewSubject(ctx) {
1331
+ return callerSubject(ctx.user);
1332
+ }
1333
+ /** Whether a listing would serve the document to the caller; fails closed. */
1334
+ async servesDocument(documentId, ctx) {
1335
+ if (!documentId) return false;
1336
+ try {
1337
+ return await this.servesDocumentOrThrows(documentId, ctx);
1338
+ } catch {
1339
+ return false;
1340
+ }
1341
+ }
1342
+ /** {@link servesDocument}, but a reactor that cannot answer throws. */
1343
+ servesDocumentOrThrows(identifier, ctx, view) {
1344
+ return this.clientsOf(ctx).read.isServed(identifier, {
1345
+ ...view,
1346
+ subject: this.viewSubject(ctx)
1347
+ });
1348
+ }
1349
+ /**
1350
+ * Whether a listing would serve the document to the caller: the reactor read
1351
+ * gate, then the host's legacy layer, as `findDocuments` applies them. Absent
1352
+ * or withheld is `false`; a failure to decide throws.
1353
+ */
1354
+ async listsDocument(identifier, ctx, view) {
1355
+ if (!await this.servesDocumentOrThrows(identifier, ctx, view)) return false;
1356
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return true;
1357
+ return this.canReadDocument(await this.resolveCanonicalDocumentId(identifier, ctx), ctx);
1358
+ }
1359
+ /**
1360
+ * Asserts read access, resolving a slug first. Returns a handle whose
1361
+ * `fetchIdentifier` the caller reuses for the data fetch; a denial throws.
1362
+ */
1363
+ async assertCanRead(identifier, ctx) {
1364
+ const documentId = await this.#resolveForCheck(identifier, ctx);
1365
+ if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
1366
+ await this.assertCanReadCanonical(documentId, ctx);
1367
+ return AuthorizedDocumentHandle.resolved(documentId);
1368
+ }
1369
+ async assertCanWrite(identifier, ctx) {
1370
+ const documentId = await this.#resolveForCheck(identifier, ctx);
1371
+ if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
1372
+ await this.assertCanWriteCanonical(documentId, ctx);
1373
+ return AuthorizedDocumentHandle.resolved(documentId);
1374
+ }
1375
+ async assertCanExecuteOperation(identifier, operationType, ctx) {
1376
+ const documentId = await this.#resolveForCheck(identifier, ctx);
1377
+ if (documentId === null) return AuthorizedDocumentHandle.skipped(identifier);
1378
+ await this.assertCanExecuteOperationCanonical(documentId, operationType, ctx);
1379
+ return AuthorizedDocumentHandle.resolved(documentId);
1380
+ }
1381
+ /**
1382
+ * Read assertion for an already-canonical document id. No slug resolution;
1383
+ * use only with ids sourced from the data layer or already resolved.
1384
+ */
1385
+ async assertCanReadCanonical(documentId, ctx) {
1386
+ if (!await this.authorizationService.canRead(documentId, ctx.user?.address)) throw new ForbiddenError("to read this document");
1387
+ }
1388
+ async assertCanWriteCanonical(documentId, ctx) {
1389
+ if (!await this.authorizationService.canWrite(documentId, ctx.user?.address)) throw new ForbiddenError("to write to this document");
1390
+ }
1391
+ async assertCanExecuteOperationCanonical(documentId, operationType, ctx) {
1392
+ if (!await this.authorizationService.canMutate(documentId, operationType, ctx.user?.address)) throw new ForbiddenError(`to execute operation "${operationType}" on this document`);
1393
+ }
1394
+ assertCanCreate(ctx) {
1395
+ if (this.authorizationService.canCreate(ctx.user?.address)) return;
1396
+ if (ctx.user?.address) throw new ForbiddenError("to create documents");
1397
+ throw new AuthenticationRequiredError("to create documents");
1398
+ }
1399
+ };
1400
+ //#endregion
1401
+ //#region src/packages/import-resolver.ts
1402
+ /**
1403
+ * Imports a specifier that may be either a bare package specifier or a
1404
+ * filesystem path. Absolute paths are converted to file:// URLs, because the
1405
+ * ESM loader reads the drive letter in a Windows path as a URL scheme
1406
+ * (`import('D:\\...')` fails with ERR_UNSUPPORTED_ESM_URL_SCHEME).
1407
+ */
1408
+ async function importSpecifier(target) {
1409
+ return await (path.isAbsolute(target) ? import(pathToFileURL(target).href) : import(target));
1410
+ }
1411
+ /**
1412
+ * Attempts to import from suggested Node.js paths
1413
+ */
1414
+ async function tryNodeSuggestedPaths(packageName, subPath) {
1415
+ const suggestedPaths = [
1416
+ `${packageName}/dist/node/${subPath}/index.mjs`,
1417
+ `${packageName}/dist/node/${subPath}.mjs`,
1418
+ `${packageName}/dist/${subPath}/index.js`,
1419
+ `${packageName}/dist/${subPath}.js`
1420
+ ];
1421
+ for (const suggestedPath of suggestedPaths) try {
1422
+ return await importSpecifier(suggestedPath);
1423
+ } catch {}
1424
+ return null;
1425
+ }
1426
+ /**
1427
+ * Attempts to resolve package using import.meta.resolve
1428
+ */
1429
+ async function tryImportMetaResolve(packageName, subPath) {
1430
+ try {
1431
+ let packageRoot;
1432
+ if (path.isAbsolute(packageName)) packageRoot = packageName;
1433
+ else {
1434
+ const resolvedUrl = import.meta.resolve?.(`${packageName}/package.json`);
1435
+ if (!resolvedUrl) return null;
1436
+ packageRoot = path.dirname(fileURLToPath(resolvedUrl));
1437
+ }
1438
+ const pathsToTry = [
1439
+ path.join(packageRoot, "dist", "node", subPath, "index.mjs"),
1440
+ path.join(packageRoot, "dist", "node", `${subPath}.mjs`),
1441
+ path.join(packageRoot, "dist", subPath, "index.js"),
1442
+ path.join(packageRoot, "dist", `${subPath}.js`),
1443
+ path.join(packageRoot, subPath, "index.js"),
1444
+ path.join(packageRoot, `${subPath}.js`)
1445
+ ];
1446
+ for (const attemptPath of pathsToTry) try {
1447
+ return await importSpecifier(attemptPath);
1448
+ } catch {}
1449
+ } catch {}
1450
+ return null;
1451
+ }
1452
+ /**
1453
+ * Resolves symlinks in node_modules to find the real package location
1454
+ */
1455
+ async function resolveSymlinkedPaths(packageName, subPath) {
1456
+ const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
1457
+ const nodeModulesPatterns = [path.join(process.cwd(), "node_modules", packageName), path.join(process.cwd(), "node_modules", packageBaseName || packageName)];
1458
+ const workspacePatterns = [];
1459
+ for (const nodeModulesPath of nodeModulesPatterns) try {
1460
+ const fs = await import("node:fs");
1461
+ if (fs.existsSync(nodeModulesPath)) {
1462
+ const realPath = fs.realpathSync(nodeModulesPath);
1463
+ 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`));
1464
+ }
1465
+ } catch {}
1466
+ return workspacePatterns;
1467
+ }
1468
+ /**
1469
+ * Generates common workspace pattern paths
1470
+ */
1471
+ function getCommonWorkspacePaths(packageName, subPath) {
1472
+ const packageBaseName = packageName.includes("/") ? packageName.split("/").pop() : packageName;
1473
+ const commonRoots = [process.cwd(), path.dirname(process.cwd())];
1474
+ const workspacePatterns = [];
1475
+ 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`));
1476
+ return workspacePatterns;
1477
+ }
1478
+ /**
1479
+ * Attempts to import from a list of workspace patterns
1480
+ */
1481
+ async function tryWorkspacePatterns(patterns) {
1482
+ for (const workspacePath of patterns) try {
1483
+ return await importSpecifier(workspacePath);
1484
+ } catch {}
1485
+ return null;
1486
+ }
1487
+ /**
1488
+ * Attempts to resolve linked packages using various fallback strategies
1489
+ */
1490
+ async function resolveLinkedPackage(packageName, subPath) {
1491
+ let result = await tryNodeSuggestedPaths(packageName, subPath);
1492
+ if (result) return result;
1493
+ result = await tryImportMetaResolve(packageName, subPath);
1494
+ if (result) return result;
1495
+ result = await tryWorkspacePatterns(await resolveSymlinkedPaths(packageName, subPath));
1496
+ if (result) return result;
1497
+ result = await tryWorkspacePatterns(getCommonWorkspacePaths(packageName, subPath));
1498
+ if (result) return result;
1499
+ return null;
1500
+ }
1501
+ //#endregion
1502
+ //#region src/packages/util.ts
1503
+ childLogger(["reactor-api", "packages/util"]);
1504
+ const PACKAGE_MODULE_FAILED = "ERR_PACKAGE_MODULE_FAILED";
1505
+ /**
1506
+ * Tries to import document models from a package. This function cannot throw.
1507
+ */
1508
+ async function loadDocumentModels(packageName) {
1509
+ return loadDependency(packageName, "document-models");
1510
+ }
1511
+ /**
1512
+ * Tries to import subgraphs from a package. This function cannot throw.
1513
+ */
1514
+ async function loadSubgraphs(packageName) {
1515
+ return loadDependency(packageName, "subgraphs");
1516
+ }
1517
+ /** The header every failed load of a package entry logs, whatever the kind. */
1518
+ function failedLoadHeader(kind) {
1519
+ return `Failed to load ${kind} from @pkg:`;
1520
+ }
1521
+ async function loadScalars(packageName) {
1522
+ return loadDependency(packageName, "scalars");
1523
+ }
1524
+ /**
1525
+ * Tries to import processors from a package. This function cannot throw.
1526
+ */
1527
+ async function loadProcessors(packageName) {
1528
+ return loadDependency(packageName, "processors");
1529
+ }
1530
+ /**
1531
+ * Generic dependency loader - tries to import a dependency from a package. This function cannot throw.
1532
+ * Returns null if the dependency cannot be loaded.
1533
+ */
1534
+ async function loadDependency(packageName, subPath) {
1535
+ const fullPath = path.isAbsolute(packageName) ? pathToFileURL(path.join(packageName, subPath)).href : `${packageName}/${subPath}`;
1536
+ try {
1537
+ return await import(
1538
+ /* @vite-ignore */
1539
+ fullPath
1540
+ );
1541
+ } catch (e) {
1542
+ 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")) {
1543
+ const result = await resolveLinkedPackage(packageName, subPath);
1544
+ if (result) return result;
1545
+ }
1546
+ throw e;
1547
+ }
1548
+ }
1549
+ /**
1550
+ * The subgraphs a package's `powerhouse.manifest.json` declares, when the
1551
+ * manifest is reachable — which it is for a package identified by an
1552
+ * absolute path (how every local project reaches the loaders). Lets the
1553
+ * package manager warn when a manifest promises subgraphs and the loaders
1554
+ * deliver none, instead of failing silently. For a bare package name the
1555
+ * manifest would have to be resolved through the module system; until a
1556
+ * caller needs that, a bare name answers [] rather than guessing.
1557
+ */
1558
+ function manifestDeclaredSubgraphs(identifier) {
1559
+ if (!path.isAbsolute(identifier)) return [];
1560
+ try {
1561
+ const raw = readFileSync(path.join(identifier, "powerhouse.manifest.json"), "utf-8");
1562
+ const manifest = JSON.parse(raw);
1563
+ if (!Array.isArray(manifest.subgraphs)) return [];
1564
+ return manifest.subgraphs.map((subgraph) => {
1565
+ if (typeof subgraph !== "object" || subgraph === null) return;
1566
+ const { id, name } = subgraph;
1567
+ return id ?? name;
1568
+ }).filter((value) => typeof value === "string" && value.length > 0);
1569
+ } catch {
1570
+ return [];
1571
+ }
1572
+ }
1573
+ function isUpgradeManifest(value) {
1574
+ return typeof value === "object" && value !== null && "documentType" in value && "supportedVersions" in value && "upgrades" in value;
1575
+ }
1576
+ /**
1577
+ * Collects upgrade manifests from a package's document-models namespace.
1578
+ * Handles both the aggregate `upgradeManifests` array export and individual
1579
+ * manifest exports; dedupes by documentType.
1580
+ */
1581
+ function extractUpgradeManifests(namespace) {
1582
+ const manifests = /* @__PURE__ */ new Map();
1583
+ const add = (value) => {
1584
+ if (isUpgradeManifest(value)) manifests.set(value.documentType, value);
1585
+ };
1586
+ for (const value of Object.values(namespace)) if (Array.isArray(value)) value.forEach(add);
1587
+ else add(value);
1588
+ return Array.from(manifests.values());
1589
+ }
1590
+ /** Calls superseded before the timer fires settle with the run that follows. */
1591
+ function debounce(func, delay = 250) {
1592
+ let timer;
1593
+ let waiting = [];
1594
+ const run = async () => {
1595
+ timer = void 0;
1596
+ const callers = waiting;
1597
+ waiting = [];
1598
+ try {
1599
+ const value = await func();
1600
+ callers.forEach((caller) => caller.resolve(value));
1601
+ } catch (error) {
1602
+ callers.forEach((caller) => caller.reject(error));
1603
+ }
1604
+ };
1605
+ return (immediate = false) => {
1606
+ clearTimeout(timer);
1607
+ return new Promise((resolve, reject) => {
1608
+ waiting.push({
1609
+ resolve,
1610
+ reject
1611
+ });
1612
+ if (immediate) run();
1613
+ else timer = setTimeout(() => void run(), delay);
1614
+ });
1615
+ };
1616
+ }
1617
+ function isSubpath(parent, dir) {
1618
+ const relative = path.relative(parent, dir);
1619
+ return relative && !relative.startsWith("..") && !path.isAbsolute(relative);
1620
+ }
1621
+ //#endregion
1622
+ //#region src/utils/detached.ts
1623
+ /** Logs `error` as the message's last replacement and reports it. */
1624
+ function reportFailure({ logger, report }, error, message, ...args) {
1625
+ logger.error(message, ...args, error);
1626
+ try {
1627
+ report?.(error);
1628
+ } catch (reportError) {
1629
+ logger.error("Reporting a failure failed: @error", reportError);
1630
+ }
1631
+ }
1632
+ /** Runs work nobody awaits: a failure is logged and reported, never thrown. */
1633
+ async function runDetached(label, task, options) {
1634
+ try {
1635
+ await task();
1636
+ } catch (error) {
1637
+ reportFailure(options, error, "@label failed: @error", label);
1638
+ }
1639
+ }
1640
+ //#endregion
1641
+ //#region src/graphql/code-first/compile.ts
1642
+ const compilations = /* @__PURE__ */ new WeakMap();
1643
+ const builders = createSubgraphEntryBuilders();
1644
+ function compileSubgraphClass(cls) {
1645
+ let compilation = compilations.get(cls);
1646
+ if (compilation === void 0) {
1647
+ compilation = compileOnce(cls);
1648
+ compilations.set(cls, compilation);
1649
+ }
1650
+ return compilation;
1651
+ }
1652
+ function compileOnce(cls) {
1653
+ const name = cls.subgraphName;
1654
+ if (typeof name !== "string") return {
1655
+ kind: "failed",
1656
+ diagnostics: [],
1657
+ reason: `${cls.name} has no static subgraphName`
1658
+ };
1659
+ let entries;
1660
+ try {
1661
+ entries = cls.getSchema(builders);
1662
+ } catch (error) {
1663
+ const diagnostics = [getSchemaThrew(name, cls.name, error)];
1664
+ return {
1665
+ kind: "failed",
1666
+ name,
1667
+ diagnostics,
1668
+ reason: reasonOf(diagnostics)
1669
+ };
1670
+ }
1671
+ const { definition, bindings, diagnostics } = compileSubgraph({
1672
+ name,
1673
+ entries
1674
+ });
1675
+ if (definition === void 0) return {
1676
+ kind: "failed",
1677
+ name,
1678
+ diagnostics,
1679
+ reason: reasonOf(diagnostics)
1680
+ };
1681
+ return {
1682
+ kind: "compiled",
1683
+ name,
1684
+ definition,
1685
+ diagnostics,
1686
+ sdl: print(projectSubgraphGraphQL(definition)),
1687
+ bindings,
1688
+ hasSubscriptions: definition.hasSubscriptions
1689
+ };
1690
+ }
1691
+ function getSchemaThrew(name, className, error) {
1692
+ return {
1693
+ code: "PH-SG-ENTRY-INVALID",
1694
+ severity: "error",
1695
+ phase: "definition",
1696
+ definition: {
1697
+ kind: "subgraph",
1698
+ key: name
1699
+ },
1700
+ path: ["entries"],
1701
+ message: `${className}.getSchema threw: ${error instanceof Error ? error.message : String(error)}`,
1702
+ repair: "Make getSchema return the entries without throwing."
1703
+ };
1704
+ }
1705
+ function reasonOf(diagnostics) {
1706
+ return diagnostics.filter((diagnostic) => diagnostic.severity === "error").map(({ code, path, message }) => `${code}${path.length > 0 ? ` at ${path.join(".")}` : ""}: ${message}`).join("; ");
1707
+ }
1708
+ //#endregion
1709
+ //#region src/graphql/code-first/errors.ts
1710
+ /**
1711
+ * @experimental Thrown when the host refuses a code-first subgraph class or
1712
+ * instance, and by the `Subgraph` constructor of a class that cannot compile.
1713
+ */
1714
+ var CodeFirstSubgraphError = class extends Error {
1715
+ name = "CodeFirstSubgraphError";
1716
+ };
1717
+ //#endregion
1718
+ //#region src/graphql/code-first/admission.ts
1719
+ const SUPPORTED_PROTOCOL_VERSION = 1;
1720
+ /**
1721
+ * Refuses a code-first subgraph that the host must not serve, by throwing a
1722
+ * `CodeFirstSubgraphError`. `target` is the class at registration and the
1723
+ * instance after it. A schema-first class, its instances and plain objects
1724
+ * return at once.
1725
+ *
1726
+ * The protocol runs in the copy of reactor-api that defined the class, so a
1727
+ * class from another copy is described and validated by its own copy.
1728
+ */
1729
+ function codeFirstCheck(target, phase) {
1730
+ const cls = phase === "registration" ? target : target?.constructor;
1731
+ const read = readSubgraphProtocol(cls);
1732
+ if (read.kind === "schema-first") return;
1733
+ const label = cls.name;
1734
+ if (read.kind === "unsupported") {
1735
+ const spoken = read.version === SUPPORTED_PROTOCOL_VERSION ? `a malformed subgraph protocol version ${SUPPORTED_PROTOCOL_VERSION}` : `subgraph protocol version ${String(read.version)}`;
1736
+ throw new CodeFirstSubgraphError(`Refusing ${String(label)}: it speaks ${spoken}, but this host supports version ${SUPPORTED_PROTOCOL_VERSION}`);
1737
+ }
1738
+ if (phase === "registration") {
1739
+ const { name, diagnostics } = read.protocol.describe();
1740
+ const reason = name === void 0 ? `${String(label)} has no static subgraphName` : reasonOf(diagnostics);
1741
+ if (reason !== "") throw new CodeFirstSubgraphError(`Refusing ${String(label)}: ${reason}`);
1742
+ return;
1743
+ }
1744
+ const result = read.protocol.validate(target);
1745
+ if (!result.ok) throw new CodeFirstSubgraphError(`Refusing ${String(label)} after ${phase === "setup" ? "onSetup" : "construction"}: ${result.message}`);
1746
+ }
1747
+ function isCodeFirstBase(candidate) {
1748
+ const read = readSubgraphProtocol(candidate);
1749
+ return read.kind === "code-first" && read.protocol.describe().name === void 0;
1750
+ }
1751
+ //#endregion
1752
+ //#region src/graphql/utils.ts
1753
+ function isSubgraphClass(candidate) {
1754
+ if (typeof candidate !== "function") return false;
1755
+ let proto = Object.getPrototypeOf(candidate);
1756
+ while (typeof proto === "function") {
1757
+ if (proto === BaseSubgraph) return true;
1758
+ if (proto.name === "BaseSubgraph") return true;
1759
+ proto = Object.getPrototypeOf(proto);
1760
+ }
1761
+ return false;
1762
+ }
1763
+ function buildGraphqlOperations(operations, skip, first) {
1764
+ return operations.slice(skip, skip + first).map(buildGraphqlOperation);
1765
+ }
1766
+ function buildGraphqlOperation(operation) {
1767
+ const signer = operation.action.context?.signer;
1768
+ return {
1769
+ id: operation.id ?? "",
1770
+ type: operation.action.type,
1771
+ index: operation.index,
1772
+ timestampUtcMs: operation.timestampUtcMs,
1773
+ hash: operation.hash,
1774
+ skip: operation.skip,
1775
+ inputText: typeof operation.action.input === "string" ? operation.action.input : JSON.stringify(operation.action.input),
1776
+ error: operation.error,
1777
+ context: { signer: signer ? {
1778
+ user: signer.user,
1779
+ app: signer.app,
1780
+ signatures: signer.signatures.map((sig) => Array.isArray(sig) ? sig.join(", ") : sig)
1781
+ } : void 0 }
1782
+ };
1783
+ }
1784
+ function buildGraphQlDocument(doc) {
1785
+ const state = doc.state;
1786
+ const initialState = doc.initialState;
1787
+ const globalState = "global" in doc.state ? doc.state.global : {};
1788
+ return {
1789
+ id: doc.header.id,
1790
+ name: doc.header.name,
1791
+ documentType: doc.header.documentType,
1792
+ revision: doc.header.revision.global || 0,
1793
+ createdAtUtcIso: doc.header.createdAtUtcIso,
1794
+ lastModifiedAtUtcIso: doc.header.lastModifiedAtUtcIso,
1795
+ operations: [],
1796
+ stateJSON: globalState,
1797
+ state,
1798
+ initialState
1799
+ };
1800
+ }
1801
+ function buildGraphQlDriveDocument(doc) {
1802
+ return {
1803
+ ...buildGraphQlDocument(doc),
1804
+ meta: { preferredEditor: doc.header.meta?.preferredEditor },
1805
+ slug: doc.header.slug,
1806
+ state: doc.state.global,
1807
+ initialState: doc.state.global
1808
+ };
1809
+ }
1810
+ //#endregion
1811
+ //#region src/packages/document-model-detection.ts
1812
+ /**
1813
+ * The one acceptance rule for a package's `document-models` module.
1814
+ *
1815
+ * The three package loaders duck-typed this independently and disagreed on
1816
+ * one case: the http loader required `documentModel` to be non-null, while
1817
+ * the import and vite loaders accepted any object merely carrying the key,
1818
+ * so an export shaped `{ documentModel: null }` registered as a model under
1819
+ * two loaders and vanished under the third. The strict rule is the correct
1820
+ * one — a module without its documentModel cannot define a document type —
1821
+ * and this predicate is now the single rule all three share, the same way
1822
+ * extractSubgraphs unified the subgraph rule.
1823
+ */
1824
+ function isDocumentModelModule(candidate) {
1825
+ if (candidate === null || typeof candidate !== "object") return false;
1826
+ if (!("documentModel" in candidate)) return false;
1827
+ const model = candidate.documentModel;
1828
+ return model !== null && model !== void 0;
1829
+ }
1830
+ /** Collects the document-model modules among a namespace's exports. */
1831
+ function extractDocumentModels(namespace) {
1832
+ return Object.values(namespace).filter(isDocumentModelModule);
1833
+ }
1834
+ //#endregion
1835
+ //#region src/packages/pieces.ts
1836
+ /** The sub-entry every loader asks a package for its pieces through. */
1837
+ const PIECES_SUBPATH = "pieces";
1838
+ const BUILT_PIECE_LIST = packageJsonExports["./pieces"].node;
1839
+ /** Where a package keeps its piece sources, for telling unbuilt from absent. */
1840
+ const PIECE_SOURCE_LIST = join(PIECES_SUBPATH, "index.ts");
1841
+ /** The nearest enclosing package.json, which `exports` usually hides. */
1842
+ function packageRootOf(dir) {
1843
+ let current = dir;
1844
+ while (!existsSync(join(current, "package.json"))) {
1845
+ const parent = dirname(current);
1846
+ if (parent === current) return void 0;
1847
+ current = parent;
1848
+ }
1849
+ return current;
1850
+ }
1851
+ function resolvePieceList(specifier, hostDir) {
1852
+ try {
1853
+ return fileURLToPath(import.meta.resolve(specifier));
1854
+ } catch (error) {
1855
+ try {
1856
+ return createRequire(join(hostDir, "package.json")).resolve(specifier);
1857
+ } catch {
1858
+ throw error;
1859
+ }
1860
+ }
1861
+ }
1862
+ function pieceListLocation(identifier, hostDir = process.cwd()) {
1863
+ if (isAbsolute(identifier)) return {
1864
+ root: identifier,
1865
+ listPath: join(identifier, BUILT_PIECE_LIST)
1866
+ };
1867
+ const listPath = resolvePieceList(`${identifier}/${PIECES_SUBPATH}`, hostDir);
1868
+ const root = packageRootOf(dirname(listPath));
1869
+ if (!root) throw new Error(`No package.json above ${listPath}`);
1870
+ return {
1871
+ root,
1872
+ listPath
1873
+ };
1874
+ }
1875
+ function packageVersionAt(root) {
1876
+ try {
1877
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1878
+ return typeof pkg.version === "string" && pkg.version !== "" ? pkg.version : void 0;
1879
+ } catch {
1880
+ return;
1881
+ }
1882
+ }
1883
+ function locatePieces(declared, context) {
1884
+ const { root, identifier, logger, version } = context;
1885
+ const located = [];
1886
+ for (const piece of declared) {
1887
+ const where = piece.entry ?? piece.bundle;
1888
+ if (typeof where !== "string" || where === "") {
1889
+ logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
1890
+ continue;
1891
+ }
1892
+ const path = isAbsolute(where) ? where : join(root, where);
1893
+ if (!(piece.entry ? existsSync(path) : existsSync(join(path, "package.json")))) {
1894
+ logger.warn("Piece @piece of @pkg is declared but not built at @path", piece.name, identifier, path);
1895
+ continue;
1896
+ }
1897
+ located.push({
1898
+ name: piece.name,
1899
+ version,
1900
+ ...piece.entry ? { entryPath: path } : { bundleDir: path }
1901
+ });
1902
+ }
1903
+ return located;
1904
+ }
1905
+ function declaredPieces(module, identifier, logger) {
1906
+ const namespace = module ?? {};
1907
+ const declared = namespace.pieces ?? namespace.default;
1908
+ if (!Array.isArray(declared)) {
1909
+ logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", identifier);
1910
+ return;
1911
+ }
1912
+ return declared;
1913
+ }
1914
+ function piecesFromCdnList(module, baseUrl, identifier, logger, version) {
1915
+ const declared = declaredPieces(module, identifier, logger);
1916
+ if (!declared) return [];
1917
+ const located = [];
1918
+ for (const piece of declared) {
1919
+ const where = piece.entry ?? piece.bundle;
1920
+ if (typeof where !== "string" || where === "") {
1921
+ logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
1922
+ continue;
1923
+ }
1924
+ located.push({
1925
+ name: piece.name,
1926
+ version,
1927
+ entryUrl: `${baseUrl}${where.replace(/^dist\/node\/pieces\//, "")}`
1928
+ });
1929
+ }
1930
+ return located;
1931
+ }
1932
+ function piecesFromListModule(module, context) {
1933
+ const namespace = module ?? {};
1934
+ const declared = namespace.pieces ?? namespace.default;
1935
+ if (!Array.isArray(declared)) {
1936
+ context.logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", context.identifier);
1937
+ return [];
1938
+ }
1939
+ const version = packageVersionAt(context.root);
1940
+ if (!version) {
1941
+ 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);
1942
+ return [];
1943
+ }
1944
+ return locatePieces(declared, {
1945
+ ...context,
1946
+ version
1947
+ });
1948
+ }
1949
+ //#endregion
1950
+ //#region src/packages/scalar-exports.ts
1951
+ /**
1952
+ * @experimental The scalar exports of a package's `scalars` entry, as this
1953
+ * host reads them; ph-cli passes them to `buildScalarRegistry` for release
1954
+ * evidence.
1955
+ */
1956
+ function scalarExportsOf(namespace) {
1957
+ return Object.entries(namespace).flatMap(([exportName, value]) => {
1958
+ if (isScalarDefinition(value)) return [{
1959
+ exportName,
1960
+ definition: value
1961
+ }];
1962
+ const version = scalarDefinitionVersion(value);
1963
+ return version === void 0 ? [] : [{
1964
+ exportName,
1965
+ unsupportedVersion: version
1966
+ }];
1967
+ });
1968
+ }
1969
+ //#endregion
1970
+ //#region src/packages/subgraph-extraction.ts
1971
+ /**
1972
+ * The one acceptance rule for a package's `subgraphs` module.
1973
+ *
1974
+ * All three package loaders (vite, import, http) consume the same generated
1975
+ * `subgraphs/index` file, and each used to apply its own rule — the vite
1976
+ * loader required a namespace whose alias equalled the class name inside it,
1977
+ * the http loader took any function one level deep, and the import loader
1978
+ * took every nested value. An export that registered under one loader could
1979
+ * silently vanish under another (the codegen-does-not-register-subgraphs
1980
+ * report). This is now the single rule they all share:
1981
+ *
1982
+ * - an export that is itself a subgraph class is accepted (named or default
1983
+ * export of the class);
1984
+ * - any subgraph class among the values of an exported object is accepted
1985
+ * (a `export * as Alias from ...` namespace under any alias, or a
1986
+ * default-exported object of classes);
1987
+ * - everything else — constants, configs, functions and classes that do not
1988
+ * extend BaseSubgraph — is dropped.
1989
+ *
1990
+ * Codegen emits `export * as <ClassName> from "./<dir>/index.js"`
1991
+ * (makeSubgraphsIndexFile in packages/codegen), which the namespace branch
1992
+ * accepts regardless of the alias; hand-written packages may re-export a
1993
+ * class directly, which the direct branch accepts. A class reached through
1994
+ * both branches is returned once.
1995
+ *
1996
+ * A code-first base (a `Subgraph` subclass without `subgraphName`) that
1997
+ * another accepted export extends is dropped: it is shared code, not a
1998
+ * subgraph. A base nothing extends stays, and the host refuses it by name.
1999
+ */
2000
+ function extractSubgraphs(namespace) {
2001
+ const found = [];
2002
+ const add = (candidate) => {
2003
+ if (isSubgraphClass(candidate) && !found.includes(candidate)) found.push(candidate);
2004
+ };
2005
+ for (const value of valuesByName(namespace)) {
2006
+ add(value);
2007
+ if (value !== null && typeof value === "object") for (const inner of valuesByName(value)) add(inner);
2008
+ }
2009
+ return found.filter((candidate) => !isCodeFirstBase(candidate) || !found.some((other) => Object.prototype.isPrototypeOf.call(candidate, other)));
2010
+ }
2011
+ function valuesByName(record) {
2012
+ const keys = Object.keys(record);
2013
+ if (Object.prototype.toString.call(record) === "[object Module]") keys.sort();
2014
+ return keys.map((key) => record[key]);
2015
+ }
2016
+ //#endregion
2017
+ export { RefusalNotRecordedError as $, manifestDeclaredSubgraphs as A, ReadableDocumentsProjection as B, extractUpgradeManifests as C, loadProcessors as D, loadDocumentModels as E, NO_LICENCE_MESSAGE as F, createCanonicalDocumentIdResolver as G, isDocumentListed as H, createCredentialInvalidator as I, createAuthorizationService as J, AuthorizationPolicy as K, DEFAULT_ROOT_TYPES as L, callerSubject as M, RequestClientBinder as N, loadScalars as O, AuthService as P, MalformedStoredOperationError as Q, EVERYONE as R, debounce as S, isSubpath as T, readableDocumentsSubquery as U, applyReadableFilter as V, CanonicalDocumentIdResolutionError as W, AuthenticationRequiredError as X, AuthEvaluationUnsupportedError as Y, ForbiddenError as Z, CodeFirstSubgraphError as _, PIECE_SOURCE_LIST as a, runDetached as b, piecesFromCdnList as c, buildGraphQlDocument as d, buildGraphQlDriveDocument as f, codeFirstCheck as g, isSubgraphClass as h, PIECES_SUBPATH as i, BaseSubgraph as j, loadSubgraphs as k, piecesFromListModule as l, buildGraphqlOperations as m, scalarExportsOf as n, packageRootOf as o, buildGraphqlOperation as p, AuthorizedDocumentHandle as q, BUILT_PIECE_LIST as r, pieceListLocation as s, extractSubgraphs as t, extractDocumentModels as u, compileSubgraphClass as v, failedLoadHeader as w, PACKAGE_MODULE_FAILED as x, reportFailure as y, READABLE_DOCUMENTS_NAMESPACE as z };
2018
+
2019
+ //# sourceMappingURL=subgraph-extraction-uJ8BR0he.mjs.map
2020
+ //# debugId=f1ee108b-9a7f-5652-b111-a79a7b101b2e