@powerhousedao/reactor-api 6.2.3-dev.7 → 6.2.3-dev.71

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 (60) hide show
  1. package/README.md +7 -2
  2. package/dist/{adapter-gateway-apollo-CxJNBVyD.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +23 -23
  3. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
  4. package/dist/{adapter-gateway-mercurius-CZVy88Za.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +4 -12
  5. package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
  6. package/dist/{adapter-http-express-B39rPhqH.mjs → adapter-http-express-P0t-mdMV.mjs} +10 -10
  7. package/dist/adapter-http-express-P0t-mdMV.mjs.map +1 -0
  8. package/dist/{adapter-http-fastify-BwXO6rqE.mjs → adapter-http-fastify-D0OP5q9K.mjs} +13 -12
  9. package/dist/adapter-http-fastify-D0OP5q9K.mjs.map +1 -0
  10. package/dist/base-document-models-uUQKgXcf.mjs +1415 -0
  11. package/dist/base-document-models-uUQKgXcf.mjs.map +1 -0
  12. package/dist/create-schema-BUk-IQCT.d.mts +144 -0
  13. package/dist/create-schema-BUk-IQCT.d.mts.map +1 -0
  14. package/dist/index.d.mts +2029 -739
  15. package/dist/index.d.mts.map +1 -1
  16. package/dist/index.mjs +4558 -1715
  17. package/dist/index.mjs.map +1 -1
  18. package/dist/package-subgraph-check-CsTPajAN.mjs +137 -0
  19. package/dist/package-subgraph-check-CsTPajAN.mjs.map +1 -0
  20. package/dist/pglite-node-C-UQXrjU.mjs +576 -0
  21. package/dist/pglite-node-C-UQXrjU.mjs.map +1 -0
  22. package/dist/rolldown-runtime-8H4AJuhK.mjs +16 -0
  23. package/dist/run-node-handler-CQjyjOuN.mjs +52 -0
  24. package/dist/run-node-handler-CQjyjOuN.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/https-hooks.d.mts +4 -4
  30. package/dist/src/packages/https-hooks.d.mts.map +1 -1
  31. package/dist/src/packages/https-hooks.mjs +2 -2
  32. package/dist/src/packages/https-hooks.mjs.map +1 -1
  33. package/dist/src/packages/vite-loader.d.mts +21 -10
  34. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  35. package/dist/src/packages/vite-loader.mjs +134 -82
  36. package/dist/src/packages/vite-loader.mjs.map +1 -1
  37. package/dist/src/pglite/pglite-node.d.mts +130 -0
  38. package/dist/src/pglite/pglite-node.d.mts.map +1 -0
  39. package/dist/src/pglite/pglite-node.mjs +4 -0
  40. package/dist/{utils-XWVecaNn.mjs → subgraph-extraction-cSpPp3Hq.mjs} +541 -17
  41. package/dist/subgraph-extraction-cSpPp3Hq.mjs.map +1 -0
  42. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs +10 -0
  43. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs.map +1 -0
  44. package/dist/types-CCI5IDgT.d.mts +82 -0
  45. package/dist/types-CCI5IDgT.d.mts.map +1 -0
  46. package/package.json +30 -20
  47. package/dist/adapter-gateway-apollo-CxJNBVyD.mjs.map +0 -1
  48. package/dist/adapter-gateway-apollo-DowrX6E_.mjs +0 -4
  49. package/dist/adapter-gateway-mercurius-CZVy88Za.mjs.map +0 -1
  50. package/dist/adapter-gateway-stitching-CaZjvRzx.mjs +0 -316
  51. package/dist/adapter-gateway-stitching-CaZjvRzx.mjs.map +0 -1
  52. package/dist/adapter-http-express-B39rPhqH.mjs.map +0 -1
  53. package/dist/adapter-http-fastify-BwXO6rqE.mjs.map +0 -1
  54. package/dist/path-normalize-BOQwY9wR.mjs +0 -23
  55. package/dist/path-normalize-BOQwY9wR.mjs.map +0 -1
  56. package/dist/types-DcYyNcHJ.d.mts +0 -48
  57. package/dist/types-DcYyNcHJ.d.mts.map +0 -1
  58. package/dist/utils-XWVecaNn.mjs.map +0 -1
  59. package/dist/websocket-DncAB9XK.mjs +0 -18
  60. package/dist/websocket-DncAB9XK.mjs.map +0 -1
@@ -1,11 +1,16 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="df700b05-17ec-5ac9-b31f-f6f9cfcfa5f5")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e49cb480-7b71-5bff-8aad-d8fe772df5e1")}catch(e){}}();
3
+ import { createRequire } from "node:module";
3
4
  import { gql } from "graphql-tag";
4
5
  import { GraphQLError } from "graphql";
5
6
  import { DRIVE_AUTH_ERROR_MESSAGES, RECOVERABLE_GRAPHQL_ERROR_CODES } from "@powerhousedao/reactor";
7
+ import { PURGE_DOCUMENT } from "@powerhousedao/shared/document-model";
8
+ import { verifyAuthBearerToken } from "@renown/sdk";
6
9
  import { childLogger } from "document-model";
7
- import path from "node:path";
10
+ import path, { dirname, isAbsolute, join } from "node:path";
11
+ import { existsSync, readFileSync } from "node:fs";
8
12
  import { fileURLToPath, pathToFileURL } from "node:url";
13
+ import { packageJsonExports } from "@powerhousedao/shared/clis/constants";
9
14
  //#region src/graphql/errors.ts
10
15
  /** Caller (authenticated or anonymous) lacks permission for the document. */
11
16
  var ForbiddenError = class extends GraphQLError {
@@ -60,6 +65,18 @@ var MalformedStoredOperationError = class extends GraphQLError {
60
65
  super(`Stored operation cannot be served: ${detail}`, { extensions: { code: RECOVERABLE_GRAPHQL_ERROR_CODES.malformedStoredOperation } });
61
66
  }
62
67
  };
68
+ /**
69
+ * The marker refusals a poll carried were not recorded, so the poll fails.
70
+ * The code is recoverable: the client keeps polling and reports them again.
71
+ */
72
+ var RefusalNotRecordedError = class extends GraphQLError {
73
+ constructor(cause) {
74
+ super("A reported marker refusal was not recorded; report it again", {
75
+ originalError: cause instanceof Error ? cause : new Error(String(cause)),
76
+ extensions: { code: RECOVERABLE_GRAPHQL_ERROR_CODES.refusalNotRecorded }
77
+ });
78
+ }
79
+ };
63
80
  //#endregion
64
81
  //#region src/services/authorization.service.ts
65
82
  /**
@@ -68,6 +85,8 @@ var MalformedStoredOperationError = class extends GraphQLError {
68
85
  * identifier when the check was skipped for a policy-wide caller.
69
86
  */
70
87
  var AuthorizedDocumentHandle = class AuthorizedDocumentHandle {
88
+ fetchIdentifier;
89
+ isResolved;
71
90
  constructor(fetchIdentifier, isResolved) {
72
91
  this.fetchIdentifier = fetchIdentifier;
73
92
  this.isResolved = isResolved;
@@ -91,6 +110,7 @@ const AuthorizationPolicy = {
91
110
  };
92
111
  /** Shared config holder and admin-list check for the policy strategies. */
93
112
  var BaseAuthorizationService = class {
113
+ config;
94
114
  constructor(config) {
95
115
  this.config = config;
96
116
  }
@@ -174,6 +194,7 @@ var DocumentPermissionsAuthorizationService = class extends BaseAuthorizationSer
174
194
  }
175
195
  async canMutate(documentId, operationType, userAddress) {
176
196
  if (this.isSupremeAdmin(userAddress)) return true;
197
+ if (operationType === PURGE_DOCUMENT) return this.#isDocumentAdmin(documentId, userAddress);
177
198
  if (await this.#permissions.isOperationRestricted(documentId, operationType)) {
178
199
  if (!userAddress) return false;
179
200
  if (await this.#isDocumentAdmin(documentId, userAddress)) return true;
@@ -267,7 +288,217 @@ function createCanonicalDocumentIdResolver(client) {
267
288
  };
268
289
  }
269
290
  //#endregion
291
+ //#region src/services/auth.service.ts
292
+ const DEFAULT_CREDENTIAL_CACHE_TTL_MS = 6e4;
293
+ const CREDENTIAL_CACHE_MAX_ENTRIES = 1e3;
294
+ /** The invalidator a subgraph receives: forwards to `authService`, or does
295
+ * nothing when the host runs without one. */
296
+ function createCredentialInvalidator(authService) {
297
+ return { invalidateCredential: (address, chainId, appDid) => authService?.invalidateCredential(address, chainId, appDid) ?? 0 };
298
+ }
299
+ var AuthService = class {
300
+ config;
301
+ credentialCache = /* @__PURE__ */ new Map();
302
+ invalidationListeners = /* @__PURE__ */ new Set();
303
+ constructor(config) {
304
+ this.config = config;
305
+ }
306
+ /**
307
+ * Whether this service reads the bearer at all. Defaults to `enabled`, so a
308
+ * config written before `resolveIdentity` existed behaves exactly as it did.
309
+ */
310
+ get resolvesIdentity() {
311
+ return this.config.resolveIdentity ?? this.config.enabled;
312
+ }
313
+ /** The context an unresolved request gets: no user, and no admin list to match against. */
314
+ anonymousContext() {
315
+ return {
316
+ user: void 0,
317
+ admins: [],
318
+ auth_enabled: this.config.enabled
319
+ };
320
+ }
321
+ async authenticateRequest(request) {
322
+ if (!this.resolvesIdentity) return this.anonymousContext();
323
+ if (request.method === "OPTIONS") return {
324
+ user: void 0,
325
+ admins: this.config.admins,
326
+ auth_enabled: this.config.enabled
327
+ };
328
+ return this.verifyBearer(request.headers.get("authorization") ?? void 0);
329
+ }
330
+ /**
331
+ * Verify a Bearer token regardless of HTTP method. Use this from non-GraphQL
332
+ * middleware that must enforce authentication on every request.
333
+ */
334
+ async verifyBearer(authorization) {
335
+ if (!this.resolvesIdentity) return this.anonymousContext();
336
+ const token = authorization?.split(" ")[1];
337
+ if (!token) return {
338
+ user: void 0,
339
+ admins: this.config.admins,
340
+ auth_enabled: this.config.enabled
341
+ };
342
+ try {
343
+ const verified = await this.verifyToken(token);
344
+ if (!verified) return new Response(JSON.stringify({ error: "Verification failed" }), { status: 401 });
345
+ const user = this.extractUserFromVerification(verified);
346
+ if (!user) return new Response(JSON.stringify({ error: "Missing credentials" }), { status: 401 });
347
+ if (!this.config.skipCredentialVerification) {
348
+ if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) return new Response(JSON.stringify({ error: "Credentials no longer valid" }), { status: 401 });
349
+ }
350
+ return {
351
+ user,
352
+ admins: this.config.admins,
353
+ auth_enabled: this.config.enabled
354
+ };
355
+ } catch {
356
+ return new Response(JSON.stringify({ error: "Authentication failed" }), { status: 401 });
357
+ }
358
+ }
359
+ /** Throws only for a bearer that is present and unusable, as HTTP 401s it. */
360
+ async authenticateWebSocketConnection(connectionParams) {
361
+ if (!this.resolvesIdentity) return null;
362
+ const authHeader = connectionParams.authorization;
363
+ if (!authHeader) return null;
364
+ const token = authHeader.split(" ")[1];
365
+ if (!token) throw new Error("Invalid authorization format");
366
+ const verified = await this.verifyToken(token);
367
+ if (!verified) throw new Error("Token verification failed");
368
+ const user = this.extractUserFromVerification(verified);
369
+ if (!user) throw new Error("Invalid credentials");
370
+ if (!this.config.skipCredentialVerification) {
371
+ if (!await this.verifyCredentialExists(user.address, user.chainId, verified.issuer)) throw new Error("Credentials no longer valid");
372
+ }
373
+ return user;
374
+ }
375
+ /** {@inheritDoc ICredentialInvalidator.invalidateCredential} */
376
+ invalidateCredential(address, chainId, appDid) {
377
+ const normalized = address.toLowerCase();
378
+ let evicted = 0;
379
+ for (const [key, entry] of this.credentialCache) if (entry.address === normalized && (chainId === void 0 || entry.chainId === chainId) && (appDid === void 0 || entry.appId === appDid)) {
380
+ this.credentialCache.delete(key);
381
+ evicted++;
382
+ }
383
+ const invalidation = { address: normalized };
384
+ if (chainId !== void 0) invalidation.chainId = chainId;
385
+ if (appDid !== void 0) invalidation.appDid = appDid;
386
+ for (const listener of this.invalidationListeners) try {
387
+ listener(invalidation);
388
+ } catch {}
389
+ return evicted;
390
+ }
391
+ /** Called after every `invalidateCredential`; returns an unsubscribe. */
392
+ onCredentialInvalidated(listener) {
393
+ this.invalidationListeners.add(listener);
394
+ return () => {
395
+ this.invalidationListeners.delete(listener);
396
+ };
397
+ }
398
+ /**
399
+ * Whether an already-authenticated principal's credential still holds, for
400
+ * re-checking long-lived connections. Goes through the same cache as
401
+ * admission, so it costs at most one verifier call per identity per TTL.
402
+ */
403
+ async isCredentialValid(user) {
404
+ if (this.config.skipCredentialVerification) return true;
405
+ return this.verifyCredentialExists(user.address, user.chainId, user.appKey);
406
+ }
407
+ /**
408
+ * Verify the auth bearer token
409
+ */
410
+ async verifyToken(token) {
411
+ return await verifyAuthBearerToken(token);
412
+ }
413
+ /**
414
+ * Extract user information from verification result.
415
+ *
416
+ * The issuer is required along with the credential subject. A credential that
417
+ * verified must carry one -- resolving it is how the signature was checked --
418
+ * so this rejects a shape that cannot have come from verification rather than
419
+ * admitting a keyless principal.
420
+ */
421
+ extractUserFromVerification(verified) {
422
+ try {
423
+ const { address, chainId, networkId } = verified.verifiableCredential.credentialSubject;
424
+ const appKey = verified.issuer;
425
+ if (!address || !chainId || !networkId || !appKey) return null;
426
+ return {
427
+ address,
428
+ chainId,
429
+ networkId,
430
+ appKey
431
+ };
432
+ } catch {
433
+ return null;
434
+ }
435
+ }
436
+ /**
437
+ * Verify that the credential still exists on the Renown API.
438
+ *
439
+ * Results are cached per (address, chainId, issuer) for a short TTL so the
440
+ * blocking external round-trip is not paid on every request. Concurrent
441
+ * checks for the same key share a single in-flight request, and entries
442
+ * that resolve to false are evicted immediately so failed or revoked
443
+ * credentials are re-checked on the next request.
444
+ */
445
+ verifyCredentialExists(address, chainId, appId) {
446
+ const ttlMs = this.config.credentialVerificationCacheTtlMs ?? DEFAULT_CREDENTIAL_CACHE_TTL_MS;
447
+ if (ttlMs <= 0) return this.fetchCredentialExists(address, chainId, appId);
448
+ const key = `${address.toLowerCase()}:${chainId}:${appId}`;
449
+ const now = Date.now();
450
+ const cached = this.credentialCache.get(key);
451
+ if (cached && cached.expiresAt > now) return cached.exists;
452
+ this.pruneCredentialCache(now);
453
+ const entry = {
454
+ exists: this.fetchCredentialExists(address, chainId, appId).then((exists) => {
455
+ if (!exists && this.credentialCache.get(key) === entry) this.credentialCache.delete(key);
456
+ return exists;
457
+ }),
458
+ expiresAt: now + ttlMs,
459
+ address: address.toLowerCase(),
460
+ chainId,
461
+ appId
462
+ };
463
+ this.credentialCache.set(key, entry);
464
+ return entry.exists;
465
+ }
466
+ /**
467
+ * Enforce the cache size cap before inserting a new entry: drop expired
468
+ * entries first, then evict oldest-inserted entries (insertion order
469
+ * matches expiry order since the TTL is constant) until under the cap, so
470
+ * a flood of distinct keys cannot grow the map without bound.
471
+ */
472
+ pruneCredentialCache(now) {
473
+ if (this.credentialCache.size < CREDENTIAL_CACHE_MAX_ENTRIES) return;
474
+ for (const [key, entry] of this.credentialCache) if (entry.expiresAt <= now) this.credentialCache.delete(key);
475
+ while (this.credentialCache.size >= CREDENTIAL_CACHE_MAX_ENTRIES) {
476
+ const oldestKey = this.credentialCache.keys().next().value;
477
+ if (oldestKey === void 0) break;
478
+ this.credentialCache.delete(oldestKey);
479
+ }
480
+ }
481
+ async fetchCredentialExists(address, chainId, appId) {
482
+ if (!this.config.verifyCredential) throw new Error("AuthService: credential verification is enabled but no verifyCredential was provided");
483
+ return this.config.verifyCredential({
484
+ address,
485
+ chainId,
486
+ appId
487
+ });
488
+ }
489
+ };
490
+ //#endregion
270
491
  //#region src/graphql/base-subgraph.ts
492
+ /**
493
+ * The subject a request reads as: its address and the app key its token
494
+ * carries. Anonymous is an empty subject, never the host's signer.
495
+ */
496
+ function callerSubject(user) {
497
+ return {
498
+ address: user?.address,
499
+ key: user?.appKey
500
+ };
501
+ }
271
502
  var BaseSubgraph = class {
272
503
  name = "example";
273
504
  path = "";
@@ -287,12 +518,22 @@ var BaseSubgraph = class {
287
518
  authorizationService;
288
519
  syncServingGate;
289
520
  /**
521
+ * The host's credential cache, for a package that revokes credentials:
522
+ * call `this.credentials.invalidateCredential(address, chainId?, appDid?)`
523
+ * right after the revocation is stored, so this host refuses the credential
524
+ * on the next request and closes WebSocket connections that rely on it.
525
+ * A no-op on a host without authentication.
526
+ */
527
+ credentials;
528
+ /**
290
529
  * Per-request memo of raw identifier to canonical document id, keyed on the
291
530
  * request context object so entries are released when the request ends. Lets
292
531
  * batch resolvers resolve each distinct identifier at most once.
293
532
  */
294
533
  #canonicalIdMemo = /* @__PURE__ */ new WeakMap();
295
534
  #resolveCanonical;
535
+ #attachments;
536
+ #attachmentClientMemo = /* @__PURE__ */ new WeakMap();
296
537
  constructor(args) {
297
538
  this.#resolveCanonical = createCanonicalDocumentIdResolver(args.reactorClient);
298
539
  this.http = args.http;
@@ -304,6 +545,22 @@ var BaseSubgraph = class {
304
545
  this.authorizationService = args.authorizationService;
305
546
  this.syncServingGate = args.syncServingGate;
306
547
  this.path = args.path ?? "";
548
+ this.#attachments = args.attachments;
549
+ this.credentials = args.credentials ?? createCredentialInvalidator(void 0);
550
+ }
551
+ /**
552
+ * An attachment client bound to this request's caller, memoized per request.
553
+ *
554
+ * @throws Error when the host provides no attachment client to subgraphs.
555
+ */
556
+ attachmentsFor(ctx) {
557
+ if (!this.#attachments) throw new Error("This host provides no attachment client to subgraphs");
558
+ let client = this.#attachmentClientMemo.get(ctx);
559
+ if (!client) {
560
+ client = this.#attachments.forSubject(callerSubject(ctx.user));
561
+ this.#attachmentClientMemo.set(ctx, client);
562
+ }
563
+ return client;
307
564
  }
308
565
  async onSetup() {}
309
566
  async onDisconnect() {}
@@ -361,6 +618,13 @@ var BaseSubgraph = class {
361
618
  async canReadDocument(documentId, ctx) {
362
619
  return this.authorizationService.canRead(documentId, ctx.user?.address);
363
620
  }
621
+ /** Drops the items the host's own ACL refuses the caller. */
622
+ async readableByHost(items, ctx) {
623
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return [...items];
624
+ const readable = [];
625
+ for (const item of items) if (await this.canReadDocument(item.id, ctx)) readable.push(item);
626
+ return readable;
627
+ }
364
628
  /**
365
629
  * The principal a request decides as: the authenticated caller's address, and
366
630
  * the did:key of the app instance whose token authenticated it.
@@ -372,10 +636,33 @@ var BaseSubgraph = class {
372
636
  * carries the same key. Anonymous callers supply neither.
373
637
  */
374
638
  viewSubject(ctx) {
375
- return {
376
- address: ctx.user?.address,
377
- key: ctx.user?.appKey
378
- };
639
+ return callerSubject(ctx.user);
640
+ }
641
+ /** Whether a listing would serve the document to the caller; fails closed. */
642
+ async servesDocument(documentId, ctx) {
643
+ if (!documentId) return false;
644
+ try {
645
+ return await this.servesDocumentOrThrows(documentId, ctx);
646
+ } catch {
647
+ return false;
648
+ }
649
+ }
650
+ /** {@link servesDocument}, but a reactor that cannot answer throws. */
651
+ servesDocumentOrThrows(identifier, ctx, view) {
652
+ return this.reactorClient.isServed(identifier, {
653
+ ...view,
654
+ subject: this.viewSubject(ctx)
655
+ });
656
+ }
657
+ /**
658
+ * Whether a listing would serve the document to the caller: the reactor read
659
+ * gate, then the host's legacy layer, as `findDocuments` applies them. Absent
660
+ * or withheld is `false`; a failure to decide throws.
661
+ */
662
+ async listsDocument(identifier, ctx, view) {
663
+ if (!await this.servesDocumentOrThrows(identifier, ctx, view)) return false;
664
+ if (this.authorizationService.isSupremeAdmin(ctx.user?.address)) return true;
665
+ return this.canReadDocument(await this.resolveCanonicalDocumentId(identifier, ctx), ctx);
379
666
  }
380
667
  /**
381
668
  * Asserts read access, resolving a slug first. Returns a handle whose
@@ -518,6 +805,7 @@ async function resolveLinkedPackage(packageName, subPath) {
518
805
  //#endregion
519
806
  //#region src/packages/util.ts
520
807
  childLogger(["reactor-api", "packages/util"]);
808
+ const PACKAGE_MODULE_FAILED = "ERR_PACKAGE_MODULE_FAILED";
521
809
  /**
522
810
  * Tries to import document models from a package. This function cannot throw.
523
811
  */
@@ -555,6 +843,30 @@ async function loadDependency(packageName, subPath) {
555
843
  throw e;
556
844
  }
557
845
  }
846
+ /**
847
+ * The subgraphs a package's `powerhouse.manifest.json` declares, when the
848
+ * manifest is reachable — which it is for a package identified by an
849
+ * absolute path (how every local project reaches the loaders). Lets the
850
+ * package manager warn when a manifest promises subgraphs and the loaders
851
+ * deliver none, instead of failing silently. For a bare package name the
852
+ * manifest would have to be resolved through the module system; until a
853
+ * caller needs that, a bare name answers [] rather than guessing.
854
+ */
855
+ function manifestDeclaredSubgraphs(identifier) {
856
+ if (!path.isAbsolute(identifier)) return [];
857
+ try {
858
+ const raw = readFileSync(path.join(identifier, "powerhouse.manifest.json"), "utf-8");
859
+ const manifest = JSON.parse(raw);
860
+ if (!Array.isArray(manifest.subgraphs)) return [];
861
+ return manifest.subgraphs.map((subgraph) => {
862
+ if (typeof subgraph !== "object" || subgraph === null) return;
863
+ const { id, name } = subgraph;
864
+ return id ?? name;
865
+ }).filter((value) => typeof value === "string" && value.length > 0);
866
+ } catch {
867
+ return [];
868
+ }
869
+ }
558
870
  function isUpgradeManifest(value) {
559
871
  return typeof value === "object" && value !== null && "documentType" in value && "supportedVersions" in value && "upgrades" in value;
560
872
  }
@@ -572,15 +884,30 @@ function extractUpgradeManifests(namespace) {
572
884
  else add(value);
573
885
  return Array.from(manifests.values());
574
886
  }
887
+ /** Calls superseded before the timer fires settle with the run that follows. */
575
888
  function debounce(func, delay = 250) {
576
889
  let timer;
577
- return (immediate = false, ...args) => {
578
- if (timer) clearTimeout(timer);
890
+ let waiting = [];
891
+ const run = async () => {
892
+ timer = void 0;
893
+ const callers = waiting;
894
+ waiting = [];
895
+ try {
896
+ const value = await func();
897
+ callers.forEach((caller) => caller.resolve(value));
898
+ } catch (error) {
899
+ callers.forEach((caller) => caller.reject(error));
900
+ }
901
+ };
902
+ return (immediate = false) => {
903
+ clearTimeout(timer);
579
904
  return new Promise((resolve, reject) => {
580
- if (immediate) func(...args).then(resolve).catch(reject);
581
- else timer = setTimeout(() => {
582
- func(...args).then(resolve).catch(reject);
583
- }, delay);
905
+ waiting.push({
906
+ resolve,
907
+ reject
908
+ });
909
+ if (immediate) run();
910
+ else timer = setTimeout(() => void run(), delay);
584
911
  });
585
912
  };
586
913
  }
@@ -589,12 +916,32 @@ function isSubpath(parent, dir) {
589
916
  return relative && !relative.startsWith("..") && !path.isAbsolute(relative);
590
917
  }
591
918
  //#endregion
919
+ //#region src/utils/detached.ts
920
+ /** Logs `error` as the message's last replacement and reports it. */
921
+ function reportFailure({ logger, report }, error, message, ...args) {
922
+ logger.error(message, ...args, error);
923
+ try {
924
+ report?.(error);
925
+ } catch (reportError) {
926
+ logger.error("Reporting a failure failed: @error", reportError);
927
+ }
928
+ }
929
+ /** Runs work nobody awaits: a failure is logged and reported, never thrown. */
930
+ async function runDetached(label, task, options) {
931
+ try {
932
+ await task();
933
+ } catch (error) {
934
+ reportFailure(options, error, "@label failed: @error", label);
935
+ }
936
+ }
937
+ //#endregion
592
938
  //#region src/graphql/utils.ts
593
939
  function isSubgraphClass(candidate) {
594
940
  if (typeof candidate !== "function") return false;
595
941
  let proto = Object.getPrototypeOf(candidate);
596
- while (proto) {
597
- if (Object.prototype.isPrototypeOf.call(proto, BaseSubgraph)) return true;
942
+ while (typeof proto === "function") {
943
+ if (proto === BaseSubgraph) return true;
944
+ if (proto.name === "BaseSubgraph") return true;
598
945
  proto = Object.getPrototypeOf(proto);
599
946
  }
600
947
  return false;
@@ -647,7 +994,184 @@ function buildGraphQlDriveDocument(doc) {
647
994
  };
648
995
  }
649
996
  //#endregion
650
- export { createAuthorizationService as _, isSubgraphClass as a, MalformedStoredOperationError as b, isSubpath as c, loadSubgraphs as d, BaseSubgraph as f, AuthorizedDocumentHandle as g, AuthorizationPolicy as h, buildGraphqlOperations as i, loadDocumentModels as l, createCanonicalDocumentIdResolver as m, buildGraphQlDriveDocument as n, debounce as o, CanonicalDocumentIdResolutionError as p, buildGraphqlOperation as r, extractUpgradeManifests as s, buildGraphQlDocument as t, loadProcessors as u, AuthEvaluationUnsupportedError as v, ForbiddenError as y };
997
+ //#region src/packages/document-model-detection.ts
998
+ /**
999
+ * The one acceptance rule for a package's `document-models` module.
1000
+ *
1001
+ * The three package loaders duck-typed this independently and disagreed on
1002
+ * one case: the http loader required `documentModel` to be non-null, while
1003
+ * the import and vite loaders accepted any object merely carrying the key,
1004
+ * so an export shaped `{ documentModel: null }` registered as a model under
1005
+ * two loaders and vanished under the third. The strict rule is the correct
1006
+ * one — a module without its documentModel cannot define a document type —
1007
+ * and this predicate is now the single rule all three share, the same way
1008
+ * extractSubgraphs unified the subgraph rule.
1009
+ */
1010
+ function isDocumentModelModule(candidate) {
1011
+ if (candidate === null || typeof candidate !== "object") return false;
1012
+ if (!("documentModel" in candidate)) return false;
1013
+ const model = candidate.documentModel;
1014
+ return model !== null && model !== void 0;
1015
+ }
1016
+ /** Collects the document-model modules among a namespace's exports. */
1017
+ function extractDocumentModels(namespace) {
1018
+ return Object.values(namespace).filter(isDocumentModelModule);
1019
+ }
1020
+ //#endregion
1021
+ //#region src/packages/pieces.ts
1022
+ /** The sub-entry every loader asks a package for its pieces through. */
1023
+ const PIECES_SUBPATH = "pieces";
1024
+ const BUILT_PIECE_LIST = packageJsonExports["./pieces"].node;
1025
+ /** Where a package keeps its piece sources, for telling unbuilt from absent. */
1026
+ const PIECE_SOURCE_LIST = join(PIECES_SUBPATH, "index.ts");
1027
+ /** The nearest enclosing package.json, which `exports` usually hides. */
1028
+ function packageRootOf(dir) {
1029
+ let current = dir;
1030
+ while (!existsSync(join(current, "package.json"))) {
1031
+ const parent = dirname(current);
1032
+ if (parent === current) return void 0;
1033
+ current = parent;
1034
+ }
1035
+ return current;
1036
+ }
1037
+ function resolvePieceList(specifier, hostDir) {
1038
+ try {
1039
+ return fileURLToPath(import.meta.resolve(specifier));
1040
+ } catch (error) {
1041
+ try {
1042
+ return createRequire(join(hostDir, "package.json")).resolve(specifier);
1043
+ } catch {
1044
+ throw error;
1045
+ }
1046
+ }
1047
+ }
1048
+ function pieceListLocation(identifier, hostDir = process.cwd()) {
1049
+ if (isAbsolute(identifier)) return {
1050
+ root: identifier,
1051
+ listPath: join(identifier, BUILT_PIECE_LIST)
1052
+ };
1053
+ const listPath = resolvePieceList(`${identifier}/${PIECES_SUBPATH}`, hostDir);
1054
+ const root = packageRootOf(dirname(listPath));
1055
+ if (!root) throw new Error(`No package.json above ${listPath}`);
1056
+ return {
1057
+ root,
1058
+ listPath
1059
+ };
1060
+ }
1061
+ function packageVersionAt(root) {
1062
+ try {
1063
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
1064
+ return typeof pkg.version === "string" && pkg.version !== "" ? pkg.version : void 0;
1065
+ } catch {
1066
+ return;
1067
+ }
1068
+ }
1069
+ function locatePieces(declared, context) {
1070
+ const { root, identifier, logger, version } = context;
1071
+ const located = [];
1072
+ for (const piece of declared) {
1073
+ const where = piece.entry ?? piece.bundle;
1074
+ if (typeof where !== "string" || where === "") {
1075
+ logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
1076
+ continue;
1077
+ }
1078
+ const path = isAbsolute(where) ? where : join(root, where);
1079
+ if (!(piece.entry ? existsSync(path) : existsSync(join(path, "package.json")))) {
1080
+ logger.warn("Piece @piece of @pkg is declared but not built at @path", piece.name, identifier, path);
1081
+ continue;
1082
+ }
1083
+ located.push({
1084
+ name: piece.name,
1085
+ version,
1086
+ ...piece.entry ? { entryPath: path } : { bundleDir: path }
1087
+ });
1088
+ }
1089
+ return located;
1090
+ }
1091
+ function declaredPieces(module, identifier, logger) {
1092
+ const namespace = module ?? {};
1093
+ const declared = namespace.pieces ?? namespace.default;
1094
+ if (!Array.isArray(declared)) {
1095
+ logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", identifier);
1096
+ return;
1097
+ }
1098
+ return declared;
1099
+ }
1100
+ function piecesFromCdnList(module, baseUrl, identifier, logger, version) {
1101
+ const declared = declaredPieces(module, identifier, logger);
1102
+ if (!declared) return [];
1103
+ const located = [];
1104
+ for (const piece of declared) {
1105
+ const where = piece.entry ?? piece.bundle;
1106
+ if (typeof where !== "string" || where === "") {
1107
+ logger.warn("Piece @piece of @pkg declares neither a bundle nor an entry", piece.name, identifier);
1108
+ continue;
1109
+ }
1110
+ located.push({
1111
+ name: piece.name,
1112
+ version,
1113
+ entryUrl: `${baseUrl}${where.replace(/^dist\/node\/pieces\//, "")}`
1114
+ });
1115
+ }
1116
+ return located;
1117
+ }
1118
+ function piecesFromListModule(module, context) {
1119
+ const namespace = module ?? {};
1120
+ const declared = namespace.pieces ?? namespace.default;
1121
+ if (!Array.isArray(declared)) {
1122
+ context.logger.warn("The pieces list of @pkg exports no \"pieces\" array; it contributes none", context.identifier);
1123
+ return [];
1124
+ }
1125
+ const version = packageVersionAt(context.root);
1126
+ if (!version) {
1127
+ 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);
1128
+ return [];
1129
+ }
1130
+ return locatePieces(declared, {
1131
+ ...context,
1132
+ version
1133
+ });
1134
+ }
1135
+ //#endregion
1136
+ //#region src/packages/subgraph-extraction.ts
1137
+ /**
1138
+ * The one acceptance rule for a package's `subgraphs` module.
1139
+ *
1140
+ * All three package loaders (vite, import, http) consume the same generated
1141
+ * `subgraphs/index` file, and each used to apply its own rule — the vite
1142
+ * loader required a namespace whose alias equalled the class name inside it,
1143
+ * the http loader took any function one level deep, and the import loader
1144
+ * took every nested value. An export that registered under one loader could
1145
+ * silently vanish under another (the codegen-does-not-register-subgraphs
1146
+ * report). This is now the single rule they all share:
1147
+ *
1148
+ * - an export that is itself a subgraph class is accepted (named or default
1149
+ * export of the class);
1150
+ * - any subgraph class among the values of an exported object is accepted
1151
+ * (a `export * as Alias from ...` namespace under any alias, or a
1152
+ * default-exported object of classes);
1153
+ * - everything else — constants, configs, functions and classes that do not
1154
+ * extend BaseSubgraph — is dropped.
1155
+ *
1156
+ * Codegen emits `export * as <ClassName> from "./<dir>/index.js"`
1157
+ * (makeSubgraphsIndexFile in packages/codegen), which the namespace branch
1158
+ * accepts regardless of the alias; hand-written packages may re-export a
1159
+ * class directly, which the direct branch accepts. A class reached through
1160
+ * both branches is returned once.
1161
+ */
1162
+ function extractSubgraphs(namespace) {
1163
+ const found = [];
1164
+ const add = (candidate) => {
1165
+ if (isSubgraphClass(candidate) && !found.includes(candidate)) found.push(candidate);
1166
+ };
1167
+ for (const value of Object.values(namespace)) {
1168
+ add(value);
1169
+ if (value !== null && typeof value === "object") for (const inner of Object.values(value)) add(inner);
1170
+ }
1171
+ return found;
1172
+ }
1173
+ //#endregion
1174
+ export { createCanonicalDocumentIdResolver as A, loadSubgraphs as C, AuthService as D, callerSubject as E, AuthenticationRequiredError as F, ForbiddenError as I, MalformedStoredOperationError as L, AuthorizedDocumentHandle as M, createAuthorizationService as N, createCredentialInvalidator as O, AuthEvaluationUnsupportedError as P, RefusalNotRecordedError as R, loadProcessors as S, BaseSubgraph as T, PACKAGE_MODULE_FAILED as _, packageRootOf as a, isSubpath as b, piecesFromListModule as c, buildGraphQlDriveDocument as d, buildGraphqlOperation as f, runDetached as g, reportFailure as h, PIECE_SOURCE_LIST as i, AuthorizationPolicy as j, CanonicalDocumentIdResolutionError as k, extractDocumentModels as l, isSubgraphClass as m, BUILT_PIECE_LIST as n, pieceListLocation as o, buildGraphqlOperations as p, PIECES_SUBPATH as r, piecesFromCdnList as s, extractSubgraphs as t, buildGraphQlDocument as u, debounce as v, manifestDeclaredSubgraphs as w, loadDocumentModels as x, extractUpgradeManifests as y };
651
1175
 
652
- //# sourceMappingURL=utils-XWVecaNn.mjs.map
653
- //# debugId=df700b05-17ec-5ac9-b31f-f6f9cfcfa5f5
1176
+ //# sourceMappingURL=subgraph-extraction-cSpPp3Hq.mjs.map
1177
+ //# debugId=e49cb480-7b71-5bff-8aad-d8fe772df5e1