@powerhousedao/reactor-api 6.2.3-dev.79 → 6.2.3-dev.80

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 (29) hide show
  1. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs +2 -2
  2. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -1
  3. package/dist/{base-document-models-ux7TZ9X3.mjs → base-document-models-D-cmBBYJ.mjs} +116 -27
  4. package/dist/base-document-models-D-cmBBYJ.mjs.map +1 -0
  5. package/dist/{create-schema-BUk-IQCT.d.mts → create-schema-Dio_7akA.d.mts} +22 -7
  6. package/dist/create-schema-Dio_7akA.d.mts.map +1 -0
  7. package/dist/error-info-BaEL50f5.mjs +2 -2
  8. package/dist/error-info-BaEL50f5.mjs.map +1 -1
  9. package/dist/index.d.mts +297 -7
  10. package/dist/index.d.mts.map +1 -1
  11. package/dist/index.mjs +607 -138
  12. package/dist/index.mjs.map +1 -1
  13. package/dist/{package-subgraph-check-BGfeyfnc.mjs → package-subgraph-check-C0PD_Tj9.mjs} +4 -4
  14. package/dist/{package-subgraph-check-BGfeyfnc.mjs.map → package-subgraph-check-C0PD_Tj9.mjs.map} +1 -1
  15. package/dist/src/graphql/subgraph-types.d.mts +1 -1
  16. package/dist/src/graphql/subgraph-types.mjs +1 -1
  17. package/dist/src/packages/vite-loader.d.mts +4 -1
  18. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  19. package/dist/src/packages/vite-loader.mjs +31 -13
  20. package/dist/src/packages/vite-loader.mjs.map +1 -1
  21. package/dist/{subgraph-extraction-BYKOycxo.mjs → subgraph-extraction-BA9WKjn1.mjs} +470 -10
  22. package/dist/subgraph-extraction-BA9WKjn1.mjs.map +1 -0
  23. package/dist/{types-BEpxtyKW.d.mts → types-PXB1ctpi.d.mts} +19 -2
  24. package/dist/types-PXB1ctpi.d.mts.map +1 -0
  25. package/package.json +13 -14
  26. package/dist/base-document-models-ux7TZ9X3.mjs.map +0 -1
  27. package/dist/create-schema-BUk-IQCT.d.mts.map +0 -1
  28. package/dist/subgraph-extraction-BYKOycxo.mjs.map +0 -1
  29. package/dist/types-BEpxtyKW.d.mts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,20 +1,22 @@
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]="ef156955-2531-5a13-8ece-12e68bf6d841")}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]="31a04f4e-9c99-5095-b7d0-1c70af59a2fc")}catch(e){}}();
3
3
  import { t as __exportAll } from "./rolldown-runtime-8H4AJuhK.mjs";
4
- import { A as CanonicalDocumentIdResolutionError, C as loadSubgraphs, D as RequestClientBinder, E as callerSubject, F as AuthEvaluationUnsupportedError, I as AuthenticationRequiredError, L as ForbiddenError, M as AuthorizationPolicy, N as AuthorizedDocumentHandle, O as AuthService, P as createAuthorizationService, R as MalformedStoredOperationError, S as loadProcessors, T as BaseSubgraph, _ as PACKAGE_MODULE_FAILED, c as piecesFromListModule, d as buildGraphQlDriveDocument, f as buildGraphqlOperation, g as runDetached, h as reportFailure, i as PIECE_SOURCE_LIST, j as createCanonicalDocumentIdResolver, k as createCredentialInvalidator, l as extractDocumentModels, m as isSubgraphClass, o as pieceListLocation, p as buildGraphqlOperations, s as piecesFromCdnList, t as extractSubgraphs, u as buildGraphQlDocument, v as debounce, w as manifestDeclaredSubgraphs, x as loadDocumentModels, y as extractUpgradeManifests, z as RefusalNotRecordedError } from "./subgraph-extraction-BYKOycxo.mjs";
5
- import { A as getDocumentModelSubgraphName, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as reservedTypeNamesTaken, I as typeDefinitionNames, L as schema_default$1, M as getGeneratedDocumentModelTypes, N as hasOperationSchemas, O as generatedTypesOf, P as reservedTypeNames, S as buildSubgraphSchemaModule, T as documentModelSubgraphTypes, _ as describeOwnershipConflicts, a as inspectionAdminTypeDefs, b as assembleSubgraphTypeDefs, c as HOST_ORIGIN, d as byClaimPriority, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getDocumentModelTypeDefs, k as getDocumentModelSchemaName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default$2, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, w as createSchema, x as buildDocumentModelSchema, y as SubgraphTypeCollisionError } from "./base-document-models-ux7TZ9X3.mjs";
4
+ import { A as RequestClientBinder, B as CanonicalDocumentIdResolutionError, C as loadDocumentModels, D as manifestDeclaredSubgraphs, E as loadSubgraphs, F as READABLE_DOCUMENTS_NAMESPACE, G as AuthEvaluationUnsupportedError, H as AuthorizationPolicy, I as ReadableDocumentsProjection, J as MalformedStoredOperationError, K as AuthenticationRequiredError, L as applyReadableFilter, M as createCredentialInvalidator, N as DEFAULT_ROOT_TYPES, O as BaseSubgraph, P as EVERYONE, R as isDocumentListed, T as loadScalars, U as AuthorizedDocumentHandle, V as createCanonicalDocumentIdResolver, W as createAuthorizationService, Y as RefusalNotRecordedError, _ as runDetached, a as PIECE_SOURCE_LIST, b as extractUpgradeManifests, c as piecesFromCdnList, d as buildGraphQlDocument, f as buildGraphQlDriveDocument, g as reportFailure, h as isSubgraphClass, j as AuthService, k as callerSubject, l as piecesFromListModule, m as buildGraphqlOperations, n as scalarExportsOf, p as buildGraphqlOperation, q as ForbiddenError, s as pieceListLocation, t as extractSubgraphs, u as extractDocumentModels, v as PACKAGE_MODULE_FAILED, w as loadProcessors, x as failedLoadHeader, y as debounce, z as readableDocumentsSubquery } from "./subgraph-extraction-BA9WKjn1.mjs";
5
+ import { A as getDocumentModelSubgraphName, C as createMergedSchema, D as generateDocumentModelSchema, E as findSubgraphTypeCollisions, F as reservedTypeNamesTaken, I as typeDefinitionNames, L as EMPTY_SCALAR_REGISTRY, M as getGeneratedDocumentModelTypes, N as hasOperationSchemas, O as generatedTypesOf, P as reservedTypeNames, R as sameScalarRegistry, S as buildSubgraphSchemaModule, T as documentModelSubgraphTypes, _ as describeOwnershipConflicts, a as inspectionAdminTypeDefs, b as assembleSubgraphTypeDefs, c as HOST_ORIGIN, d as byClaimPriority, f as decideAdmission, g as collectSubgraphClaims, h as supergraphClaimLosers, i as inspectionTypeDefs, j as getDocumentModelTypeDefs, k as getDocumentModelSchemaName, l as RegistrationOrder, m as documentModelSubgraphSources, n as systemTypeDefs, o as CORE_ORIGIN, p as describeOrigin, r as schema_default$2, s as DOCUMENT_MODEL_ORIGIN, t as baseDocumentModels, u as admitDocumentModels, v as DocumentModelSchemaCache, w as createSchema, x as buildDocumentModelSchema, y as SubgraphTypeCollisionError, z as schema_default$1 } from "./base-document-models-D-cmBBYJ.mjs";
6
6
  import { n as createApolloFetchHandler } from "./adapter-gateway-apollo-D-EdZ4e-.mjs";
7
7
  import { a as resolvePgliteMaintenance, m as PGLITE_UTC_PARSERS, r as createDurableNodeFs } from "./error-info-BaEL50f5.mjs";
8
8
  import { h as preparePgliteDataDir, m as openCurrentPgliteForVerify } from "./pglite-node-DGms6Ssa.mjs";
9
- import { findPackageJSON, isBuiltin } from "node:module";
9
+ import nodeModule, { isBuiltin } from "node:module";
10
10
  import { AttachmentBuilder, AttachmentNotFound, AttachmentReferenceIndexBuilder, createRef, createS3AttachmentBackend, parseAttachmentStorageConfig, parseRef, validateReserveMetadata } from "@powerhousedao/reactor-attachments";
11
11
  import { ConsoleLogger, childLogger } from "document-model";
12
12
  import { AnalyticsQueryEngine } from "@powerhousedao/analytics-engine-core";
13
13
  import { AnalyticsModel, AnalyticsResolvers, typedefs } from "@powerhousedao/analytics-engine-graphql";
14
14
  import { gql } from "graphql-tag";
15
- import { GraphQLError, Kind, OperationTypeNode, buildASTSchema, getOperationAST, isTypeDefinitionNode, isTypeExtensionNode, parse, print, validateSchema, valueFromASTUntyped, visit } from "graphql";
15
+ import { GraphQLError, Kind, OperationTypeNode, buildASTSchema, getOperationAST, isTypeDefinitionNode, isTypeExtensionNode, parse, print, specifiedScalarTypes, validateSchema, valueFromASTUntyped, visit } from "graphql";
16
16
  import { AuthEnforcementDisabledError, BareReadGate, BatchJobFailedError, CATCH_UP_LOAD_WINDOW_MS, ChannelError, ChannelErrorSource, DEFAULT_DRIVE_CONTAINER_TYPES, DriveCollectionId, DriveInspection, FacadeWriteClient, InvalidDeadLetterCursorError, JOB_NOT_FOUND_ERROR_NAME, JobStatus, ModelReadGate, PropagationMode as PropagationMode$1, READ_ONLY_ACCESS, SyncOperation, SyncScopeGate, consolidateSyncOperations, createReactorHostModuleBase, createReactorInspector, driveIdFromUrl, envelopesToSyncOperations, isCatchUpLevel, parseDriveUrl, readDecisionModel, supportsPurgeRefusals, syncOperationErrorType, toWireCatchUpPriority, toWireDeadLetter, toWireQueueState, warnOnce } from "@powerhousedao/reactor";
17
17
  import { deserializeSignature, readPeerManifest, serializeSignature, setName } from "@powerhousedao/shared/document-model";
18
+ import { createRelationalDb, getCodegenStatusRegistry } from "@powerhousedao/shared/processors";
19
+ import { Kysely, Migrator, sql } from "kysely";
18
20
  import { fetchDelegationCredential, resolveSwitchboardEndpoint } from "@renown/sdk";
19
21
  import { AsyncLocalStorage } from "node:async_hooks";
20
22
  import path, { isAbsolute, join } from "node:path";
@@ -26,9 +28,10 @@ import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from
26
28
  import nodeFs, { existsSync, readFileSync, watchFile } from "node:fs";
27
29
  import { monitorEventLoopDelay } from "node:perf_hooks";
28
30
  import { pathToFileURL } from "node:url";
29
- import { camelCase } from "change-case";
31
+ import { SCALAR_DEFINITION_VERSION, getCatalogScalar } from "document-model/scalars";
30
32
  import * as z$1 from "zod";
31
33
  import { z } from "zod";
34
+ import { camelCase } from "change-case";
32
35
  import { ApolloServer } from "@apollo/server";
33
36
  import { ApolloServerPluginInlineTraceDisabled } from "@apollo/server/plugin/disabled";
34
37
  import { ApolloServerPluginLandingPageLocalDefault } from "@apollo/server/plugin/landingPage/default";
@@ -39,11 +42,11 @@ import { createHandler } from "graphql-sse/lib/use/fetch";
39
42
  import lzString from "lz-string";
40
43
  import { PubSub, withFilter } from "graphql-subscriptions";
41
44
  import { buildTreeUrl } from "@powerhousedao/shared";
45
+ import { packageJsonExports } from "@powerhousedao/shared/clis/constants";
42
46
  import { resolvePhDir } from "@powerhousedao/shared/clis/ph-dir";
43
47
  import { init, parse as parse$1 } from "es-module-lexer";
44
48
  import { chmod, lstat, mkdir, readFile, readdir, readlink, realpath, rename, rm, stat, symlink, writeFile } from "node:fs/promises";
45
49
  import { getConfig } from "@powerhousedao/config/node";
46
- import { createRelationalDb, getCodegenStatusRegistry } from "@powerhousedao/shared/processors";
47
50
  import EventEmitter from "node:events";
48
51
  import { PostgresAnalyticsStore } from "@powerhousedao/analytics-engine-pg";
49
52
  import { createAttachmentClient } from "@powerhousedao/reactor-attachments/client";
@@ -51,7 +54,6 @@ import { setupMcpServer } from "@powerhousedao/reactor-mcp";
51
54
  import { tmpdir } from "node:os";
52
55
  import { WebSocketServer } from "ws";
53
56
  import { isAttachmentHash, readGateAllowsAttachmentRead, scopeGateAllowsAttachmentRead } from "@powerhousedao/reactor-attachments/replication";
54
- import { Kysely, Migrator, sql } from "kysely";
55
57
  import { PGlite } from "@electric-sql/pglite";
56
58
  import { NodeFS } from "@electric-sql/pglite/nodefs";
57
59
  import knex from "knex";
@@ -642,12 +644,102 @@ var AuthSubgraph = class extends BaseSubgraph {
642
644
  }
643
645
  };
644
646
  //#endregion
647
+ //#region src/graphql/index-subgraph.ts
648
+ const NO_RESTRICTION = (query) => query;
649
+ /** The named type behind lists and non-nulls. */
650
+ function namedType(type) {
651
+ return type.kind === Kind.NAMED_TYPE ? type.name.value : namedType(type.type);
652
+ }
653
+ /** The query container types (`type Query { emailIndex: EmailIndexQueries! }`) and their fields. */
654
+ function queryContainers(typeDefs) {
655
+ const types = /* @__PURE__ */ new Map();
656
+ for (const def of typeDefs.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION || def.kind === Kind.OBJECT_TYPE_EXTENSION) types.set(def.name.value, def.fields ?? []);
657
+ const containers = /* @__PURE__ */ new Map();
658
+ for (const field of types.get("Query") ?? []) {
659
+ const name = namedType(field.type);
660
+ const fields = types.get(name);
661
+ if (fields) containers.set(name, fields);
662
+ }
663
+ return containers;
664
+ }
665
+ /**
666
+ * Every field of every query container type has a handler and an access
667
+ * entry whose scope argument the field takes; nothing is declared that the
668
+ * schema does not have. Throws naming each gap: the definition fails where
669
+ * it is written, not on the first refused request.
670
+ */
671
+ function assertIndexAccessComplete(definition) {
672
+ const containers = queryContainers(definition.typeDefs);
673
+ const known = /* @__PURE__ */ new Set();
674
+ const problems = [];
675
+ const entries = definition.access.fields;
676
+ for (const [type, fields] of containers) for (const field of fields) {
677
+ const key = `${type}.${field.name.value}`;
678
+ known.add(key);
679
+ const access = entries[key];
680
+ if (!access) problems.push(`${key}: no access entry (declare rows/column, or public: true)`);
681
+ if (!(key in definition.queries)) problems.push(`${key}: no query handler`);
682
+ if (access && !("public" in access)) {
683
+ const arg = definition.access.scope.drive;
684
+ if (!field.arguments?.some((a) => a.name.value === arg)) problems.push(`${key}: takes no "${arg}" argument, which names its scope`);
685
+ if (access.column.trim() === "") problems.push(`${key}: no column names the row's document`);
686
+ }
687
+ }
688
+ for (const key of Object.keys(definition.access.fields)) if (!known.has(key)) problems.push(`${key}: declared, but not a query field of the schema`);
689
+ for (const key of Object.keys(definition.queries)) if (!known.has(key)) problems.push(`${key}: has a handler, but is not a query field of the schema`);
690
+ if (containers.size === 0) problems.push("the schema's Query type names no container type");
691
+ if (problems.length > 0) throw new Error(`Index subgraph "${definition.name}" is not fully declared:\n- ${problems.join("\n- ")}`);
692
+ }
693
+ /** The subgraph class the host registers; validated at definition time. */
694
+ function defineIndexSubgraph(definition) {
695
+ assertIndexAccessComplete(definition);
696
+ return class IndexSubgraph extends BaseSubgraph {
697
+ name = definition.name;
698
+ typeDefs = definition.typeDefs;
699
+ resolvers = buildResolvers(definition, this);
700
+ additionalContextFields = {};
701
+ async onSetup() {}
702
+ async onDisconnect() {}
703
+ };
704
+ }
705
+ function buildResolvers(definition, subgraph) {
706
+ const resolvers = {};
707
+ for (const [type, fields] of Object.entries(definition.resolvers ?? {})) resolvers[type] = { ...fields };
708
+ for (const [key, handler] of Object.entries(definition.queries)) {
709
+ const [type, field] = key.split(".");
710
+ const access = definition.access.fields[key];
711
+ (resolvers[type] ??= {})[field] = async (_parent, args, ctx) => {
712
+ const driveId = String(args[definition.access.scope.drive]);
713
+ const filter = "public" in access ? { kind: "all" } : await subgraph.indexAccess(ctx, driveId);
714
+ const restrict = "public" in access ? NO_RESTRICTION : (query, column = access.column) => applyReadableFilter(query, column, filter, { passWhen: access.passWhen });
715
+ return handler({
716
+ args,
717
+ ctx,
718
+ db: definition.index(driveId, subgraph.relationalDb),
719
+ scope: { drive: driveId },
720
+ access: filter,
721
+ restrict
722
+ });
723
+ };
724
+ }
725
+ return resolvers;
726
+ }
727
+ //#endregion
645
728
  //#region src/graphql/gateway/auth-middleware.ts
646
729
  const authContextMap = /* @__PURE__ */ new WeakMap();
647
730
  /** Internal — only `graphql-manager.ts` should call this. */
648
731
  function getAuthContext(request) {
649
732
  return authContextMap.get(request);
650
733
  }
734
+ /**
735
+ * Internal — for a request the host builds itself (an in-process subgraph
736
+ * query on behalf of a principal it already knows), what the auth
737
+ * middleware would have recorded had the request carried that principal's
738
+ * bearer. Only `graphql-manager.ts` should call this.
739
+ */
740
+ function setAuthContext(request, context) {
741
+ authContextMap.set(request, context);
742
+ }
651
743
  function createAuthFetchMiddleware(authService) {
652
744
  return (next) => async (request) => {
653
745
  const result = await authService.authenticateRequest(request);
@@ -3474,7 +3566,7 @@ async function document(read, args, subject) {
3474
3566
  try {
3475
3567
  result = await read.get(args.idOrSlug, view, void 0, token);
3476
3568
  } catch (error) {
3477
- throw new GraphQLError(`Failed to fetch document: ${error instanceof Error ? error.message : "Unknown error"}`);
3569
+ throw new GraphQLError(`Failed to fetch document: ${error instanceof Error ? error.message : "Unknown error"}`, notFoundExtensions(error));
3478
3570
  }
3479
3571
  let children;
3480
3572
  try {
@@ -3711,7 +3803,7 @@ async function documentOperations(read, args, subject) {
3711
3803
  try {
3712
3804
  result = await read.getOperations(args.filter.documentIdOrSlug, view, operationFilter, paging);
3713
3805
  } catch (error) {
3714
- throw new GraphQLError(`Failed to fetch document operations: ${error instanceof Error ? error.message : "Unknown error"}`);
3806
+ throw new GraphQLError(`Failed to fetch document operations: ${error instanceof Error ? error.message : "Unknown error"}`, notFoundExtensions(error));
3715
3807
  }
3716
3808
  try {
3717
3809
  return toOperationResultPage(result);
@@ -3755,6 +3847,15 @@ async function evaluateActions(write, args, subject) {
3755
3847
  };
3756
3848
  }
3757
3849
  const isDocumentNotFound = (error) => error instanceof Error && error.name === "DocumentNotFoundError";
3850
+ /** A missing document is an answer, not a failure: its GraphQL error says NOT_FOUND. */
3851
+ function notFoundExtensions(error) {
3852
+ return isDocumentNotFound(error) ? { extensions: { code: "NOT_FOUND" } } : void 0;
3853
+ }
3854
+ /** Whether a resolver failed because the document does not exist (NOT_FOUND or the reactor's error). */
3855
+ function isNotFoundError(error) {
3856
+ if (isDocumentNotFound(error)) return true;
3857
+ return error instanceof GraphQLError && error.extensions.code === "NOT_FOUND";
3858
+ }
3758
3859
  /** Refuses a slug another document holds: the reactor would move it to the new one. */
3759
3860
  async function assertSlugAvailable(read, slug, documentId) {
3760
3861
  if (!slug || slug === documentId) return;
@@ -4571,12 +4672,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4571
4672
  items: await this.readableByHost(page.items, ctx)
4572
4673
  };
4573
4674
  }
4574
- /**
4575
- * Generate __resolveType functions for union types found in the document model schema.
4576
- * Parses the state schema to find union definitions and their member types,
4577
- * then uses unique field presence to discriminate between member types at runtime.
4578
- */
4579
- generateUnionResolvers() {
4675
+ generateAbstractTypeResolvers() {
4580
4676
  const documentName = getDocumentModelSchemaName(this.documentModel.documentModel.global);
4581
4677
  const specification = this.documentModel.documentModel.global.specifications.at(-1);
4582
4678
  if (!specification) return {};
@@ -4589,12 +4685,21 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4589
4685
  return {};
4590
4686
  }
4591
4687
  const objectFieldsMap = /* @__PURE__ */ new Map();
4592
- for (const def of ast.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) objectFieldsMap.set(def.name.value, def.fields?.map((f) => f.name.value) ?? []);
4688
+ const objectInterfaces = /* @__PURE__ */ new Map();
4689
+ const unionMembers = /* @__PURE__ */ new Map();
4690
+ for (const def of ast.definitions) {
4691
+ if (def.kind === Kind.UNION_TYPE_DEFINITION || def.kind === Kind.UNION_TYPE_EXTENSION) unionMembers.set(def.name.value, [...unionMembers.get(def.name.value) ?? [], ...def.types?.map((t) => t.name.value) ?? []]);
4692
+ if (def.kind === Kind.OBJECT_TYPE_DEFINITION || def.kind === Kind.OBJECT_TYPE_EXTENSION) {
4693
+ const name = def.name.value;
4694
+ objectFieldsMap.set(name, [...objectFieldsMap.get(name) ?? [], ...def.fields?.map((f) => f.name.value) ?? []]);
4695
+ objectInterfaces.set(name, [...objectInterfaces.get(name) ?? [], ...def.interfaces?.map((i) => i.name.value) ?? []]);
4696
+ }
4697
+ }
4593
4698
  const resolvers = {};
4594
4699
  for (const def of ast.definitions) {
4595
- if (def.kind !== Kind.UNION_TYPE_DEFINITION) continue;
4596
- const unionName = def.name.value;
4597
- const memberTypes = def.types?.map((t) => t.name.value) ?? [];
4700
+ if (def.kind !== Kind.UNION_TYPE_DEFINITION && def.kind !== Kind.INTERFACE_TYPE_DEFINITION) continue;
4701
+ const abstractName = def.name.value;
4702
+ const memberTypes = def.kind === Kind.UNION_TYPE_DEFINITION ? unionMembers.get(abstractName) ?? [] : [...objectInterfaces].filter(([, interfaces]) => interfaces.includes(abstractName)).map(([objectName]) => objectName);
4598
4703
  if (memberTypes.length === 0) continue;
4599
4704
  const uniqueFields = {};
4600
4705
  for (const memberType of memberTypes) {
@@ -4602,8 +4707,9 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4602
4707
  const otherFields = new Set(memberTypes.filter((t) => t !== memberType).flatMap((t) => objectFieldsMap.get(t) ?? []));
4603
4708
  uniqueFields[memberType] = ownFields.filter((f) => !otherFields.has(f));
4604
4709
  }
4605
- const prefixedUnionName = `${documentName}_${unionName}`;
4606
- resolvers[prefixedUnionName] = { __resolveType: (obj) => {
4710
+ resolvers[`${documentName}_${abstractName}`] = { __resolveType: (obj) => {
4711
+ const declared = memberTypes.find((memberType) => obj.__typename === memberType || obj.__typename === `${documentName}_${memberType}`);
4712
+ if (declared) return `${documentName}_${declared}`;
4607
4713
  for (const memberType of memberTypes) {
4608
4714
  const fields = uniqueFields[memberType] ?? [];
4609
4715
  if (fields.length > 0 && fields.some((f) => f in obj)) return `${documentName}_${memberType}`;
@@ -4622,7 +4728,7 @@ var DocumentModelSubgraph = class extends BaseSubgraph {
4622
4728
  const documentName = getDocumentModelSchemaName(this.documentModel.documentModel.global);
4623
4729
  const operations = this.documentModel.documentModel.global.specifications.at(-1)?.modules.flatMap((module) => module.operations.filter((op) => op.name)) ?? [];
4624
4730
  return {
4625
- ...this.generateUnionResolvers(),
4731
+ ...this.generateAbstractTypeResolvers(),
4626
4732
  Query: { [documentName]: () => ({}) },
4627
4733
  [`${documentName}Queries`]: {
4628
4734
  document: async (_, args, ctx) => {
@@ -5603,6 +5709,8 @@ var GraphQLManager = class {
5603
5709
  driveOwnershipCache;
5604
5710
  /** Cached document models for schema generation - updated on init and regenerate */
5605
5711
  cachedDocumentModels = [];
5712
+ /** Every model the reactor reported at the last fetch, admitted or not. */
5713
+ #fetchedModels = [];
5606
5714
  subgraphHandlerCache = /* @__PURE__ */ new Map();
5607
5715
  /** subgraphPath → the http adapter handle of its mounted route. */
5608
5716
  subgraphRouteHandles = /* @__PURE__ */ new Map();
@@ -5635,6 +5743,14 @@ var GraphQLManager = class {
5635
5743
  * and runs inline too. */
5636
5744
  #inHook = new AsyncLocalStorage();
5637
5745
  #generatedTypes;
5746
+ /** The scalars the package manager registered. */
5747
+ #scalarRegistry = EMPTY_SCALAR_REGISTRY;
5748
+ /** The registered scalars the schema declares, resolves and reserves: those
5749
+ * whose name no registered core or host subgraph defines. */
5750
+ #scalars = EMPTY_SCALAR_REGISTRY;
5751
+ /** Scalar refusals logged: name, package and the subgraph owning the name. */
5752
+ #scalarRefusals = /* @__PURE__ */ new Set();
5753
+ #loggedScalarResolvers = /* @__PURE__ */ new WeakMap();
5638
5754
  /** Generated types no document model contributes, but `IDocument`. */
5639
5755
  #modelFreeTypeNames;
5640
5756
  #usesModelTypesMemo = /* @__PURE__ */ new WeakMap();
@@ -5684,6 +5800,7 @@ var GraphQLManager = class {
5684
5800
  featureFlags;
5685
5801
  port;
5686
5802
  syncServingGate;
5803
+ readableDocuments;
5687
5804
  httpRoutes;
5688
5805
  attachments;
5689
5806
  inspection;
@@ -5721,6 +5838,7 @@ var GraphQLManager = class {
5721
5838
  this.reactorDriveClient = options.reactorDriveClient;
5722
5839
  this.driveNodes = options.driveNodes;
5723
5840
  this.syncServingGate = options.syncServingGate;
5841
+ this.readableDocuments = options.readableDocuments;
5724
5842
  this.httpRoutes = options.httpRoutes;
5725
5843
  this.attachments = options.attachments;
5726
5844
  this.inspection = options.inspection;
@@ -5734,7 +5852,9 @@ var GraphQLManager = class {
5734
5852
  logger: this.logger
5735
5853
  });
5736
5854
  }
5737
- async init(coreSubgraphs, authMiddleware, requireAuthMiddleware) {
5855
+ async init(coreSubgraphs, authMiddleware, requireAuthMiddleware, scalars = EMPTY_SCALAR_REGISTRY) {
5856
+ this.#scalarRegistry = scalars;
5857
+ await this.#syncScalars();
5738
5858
  this.#authMiddleware = authMiddleware;
5739
5859
  this.#requireAuthMiddleware = requireAuthMiddleware;
5740
5860
  this.logger.debug(`Initializing Subgraph Manager...`);
@@ -5742,6 +5862,7 @@ var GraphQLManager = class {
5742
5862
  this.#driveMiddleware = createDriveFetchMiddleware(this.driveOwnershipCache);
5743
5863
  this.logger.debug(`Drive ownership cache populated with ${this.driveOwnershipCache.size()} drives`);
5744
5864
  const models = (await this.#readClient.getDocumentModelModules()).results;
5865
+ this.#fetchedModels = models;
5745
5866
  if (!models.find((it) => it.documentModel.global.name === "DocumentDrive")) throw new Error("DocumentDrive model required");
5746
5867
  await this.gatewayAdapter.start(this.httpServer);
5747
5868
  this.httpAdapter.setupMiddleware({ bodyLimit: "50mb" });
@@ -5782,6 +5903,66 @@ var GraphQLManager = class {
5782
5903
  await this.#createSupergraphGateway();
5783
5904
  return this.updateRouter();
5784
5905
  }
5906
+ /** Rejects when the rebuild fails; the next change retries it. */
5907
+ async applyScalarRegistry(scalars) {
5908
+ if (scalars === this.#scalarRegistry) return;
5909
+ if (this.#inHook.getStore()?.active) {
5910
+ this.#scalarRegistry = scalars;
5911
+ return;
5912
+ }
5913
+ await this.#enqueue(async () => {
5914
+ this.#scalarRegistry = scalars;
5915
+ await this.#syncScalars();
5916
+ });
5917
+ }
5918
+ /** Admit the scalars against the registered subgraphs and, once models are
5919
+ * served, rebuild against them if they changed. */
5920
+ async #syncScalars() {
5921
+ const admitted = this.#admitScalars();
5922
+ if (admitted === this.#scalars) return;
5923
+ const previous = this.#scalars;
5924
+ this.#scalars = admitted;
5925
+ if (!this.initialized) return;
5926
+ try {
5927
+ if (this.featureFlags.enableDocumentModelSubgraphs) await this.#regenerateDocumentModelSubgraphs();
5928
+ else {
5929
+ this.cachedDocumentModels = this.#admitModels(this.#fetchedModels);
5930
+ this.#scheduleRouterUpdate();
5931
+ }
5932
+ } catch (error) {
5933
+ this.#scalars = previous;
5934
+ throw error;
5935
+ }
5936
+ await this.#syncScalars();
5937
+ }
5938
+ /** The registered scalars whose name no registered core or host subgraph
5939
+ * defines; that subgraph keeps the name. Package subgraphs reserve nothing.
5940
+ * Each refusal logs once until it goes away. */
5941
+ #admitScalars() {
5942
+ const registered = { names: new Set(this.#scalarRegistry.keys()) };
5943
+ const subgraphs = new Set([this.coreSubgraphsMap, this.subgraphs].flatMap((map) => Array.from(map.values()).flat()));
5944
+ const owners = /* @__PURE__ */ new Map();
5945
+ for (const subgraph of subgraphs) {
5946
+ const origin = this.#originOf(subgraph);
5947
+ if (origin !== CORE_ORIGIN && origin !== HOST_ORIGIN) continue;
5948
+ for (const name of findSubgraphTypeCollisions(registered, subgraph.typeDefs)) if (!owners.has(name)) owners.set(name, subgraph);
5949
+ }
5950
+ const admitted = /* @__PURE__ */ new Map();
5951
+ const logged = /* @__PURE__ */ new Set();
5952
+ for (const [name, scalar] of this.#scalarRegistry) {
5953
+ const owner = owners.get(name);
5954
+ if (!owner) {
5955
+ admitted.set(name, scalar);
5956
+ continue;
5957
+ }
5958
+ const refusal = `${name}\n${scalar.packageName}\n${owner.name}`;
5959
+ logged.add(refusal);
5960
+ if (this.#scalarRefusals.has(refusal)) continue;
5961
+ this.logger.error("Refusing scalar @scalar of package @package: subgraph @subgraph defines a type of that name", name, scalar.packageName, owner.name);
5962
+ }
5963
+ this.#scalarRefusals = logged;
5964
+ return sameScalarRegistry(admitted, this.#scalars) ? this.#scalars : admitted;
5965
+ }
5785
5966
  /**
5786
5967
  * Regenerate document model subgraphs when models are dynamically loaded.
5787
5968
  * Fetches current modules from reactor client (source of truth).
@@ -5793,6 +5974,7 @@ var GraphQLManager = class {
5793
5974
  async #regenerateDocumentModelSubgraphs() {
5794
5975
  try {
5795
5976
  const models = (await this.#readClient.getDocumentModelModules()).results;
5977
+ this.#fetchedModels = models;
5796
5978
  this.cachedDocumentModels = this.#admitModels(models);
5797
5979
  const registeredNames = await this.#setupDocumentModelSubgraphs("graphql", this.cachedDocumentModels);
5798
5980
  await this.#pruneOrigin(DOCUMENT_MODEL_ORIGIN, registeredNames);
@@ -5815,7 +5997,8 @@ var GraphQLManager = class {
5815
5997
  }
5816
5998
  /** Models whose schemas build and take no reserved name. */
5817
5999
  #admitModels(models) {
5818
- const reserved = reservedTypeNames(Array.from(this.coreSubgraphsMap.values(), (subgraphs) => subgraphs.map((subgraph) => subgraph.typeDefs)).flat());
6000
+ const reserved = new Map(reservedTypeNames(Array.from(this.coreSubgraphsMap.values(), (subgraphs) => subgraphs.map((subgraph) => subgraph.typeDefs)).flat()));
6001
+ for (const name of this.#scalars.keys()) reserved.set(name, true);
5819
6002
  const { admitted, schemas, refusals } = admitDocumentModels(this.#schemaCache.resolve(models), reserved);
5820
6003
  const logged = /* @__PURE__ */ new Set();
5821
6004
  for (const refused of refusals) {
@@ -5845,6 +6028,7 @@ var GraphQLManager = class {
5845
6028
  documentPermissionService: this.documentPermissionService,
5846
6029
  authorizationService: this.authorizationService,
5847
6030
  syncServingGate: this.syncServingGate,
6031
+ readableDocuments: this.readableDocuments,
5848
6032
  attachments: this.attachments,
5849
6033
  inspection: this.inspection
5850
6034
  }, types);
@@ -5863,6 +6047,47 @@ var GraphQLManager = class {
5863
6047
  if (found) return found;
5864
6048
  }
5865
6049
  }
6050
+ /**
6051
+ * Runs a query against one registered subgraph in process, as `user`:
6052
+ * the same resolvers, the same request context and the same
6053
+ * authenticated-caller floor an HTTP request to `/graphql/<name>` gets,
6054
+ * without HTTP. For a host-side caller that acts for a principal (the
6055
+ * workflow runtime, for a piece's index lookup as the run's user).
6056
+ *
6057
+ * Only `query` operations: a mutation is a write, and writes go through
6058
+ * the write half, which signs and journals them.
6059
+ */
6060
+ async executeSubgraph(name, request) {
6061
+ const entry = this.#internalSubgraphHandlers.get(name);
6062
+ if (!entry) throw new Error(this.getSubgraphByName(name) ? `Subgraph "${name}" is registered but has no handler yet` : `Unknown subgraph: ${name}`);
6063
+ if (this.#requireAuthMiddleware !== void 0 && !request.user) throw new AuthenticationRequiredError();
6064
+ const operation = getOperationAST(parse(request.query), void 0);
6065
+ if (operation?.operation !== OperationTypeNode.QUERY) throw new Error(`executeSubgraph runs queries only; ${operation?.operation ?? "no operation"} refused`);
6066
+ const url = new URL(entry.path, `http://localhost:${this.port}/`);
6067
+ const http = new Request(url, {
6068
+ method: "POST",
6069
+ headers: {
6070
+ "content-type": "application/json",
6071
+ accept: "application/json"
6072
+ },
6073
+ body: JSON.stringify({
6074
+ query: request.query,
6075
+ variables: request.variables ?? {}
6076
+ })
6077
+ });
6078
+ if (request.user) setAuthContext(http, {
6079
+ user: request.user,
6080
+ admins: this.authorizationService.config.admins,
6081
+ auth_enabled: this.authService !== void 0
6082
+ });
6083
+ const response = await entry.handler(http);
6084
+ const body = await response.json().catch(() => void 0);
6085
+ if (!response.ok && !body?.errors?.length) throw new Error(`Subgraph "${name}" query failed: ${response.status}${body ? ` ${JSON.stringify(body)}` : ""}`);
6086
+ return {
6087
+ data: body?.data ?? null,
6088
+ ...body?.errors?.length ? { errors: body.errors.map((e) => ({ message: e.message })) } : {}
6089
+ };
6090
+ }
5866
6091
  /** Every registered subgraph named `name`, core or not, in any bucket: the
5867
6092
  * in-process handler map is keyed by bare name, so a name has one owner. */
5868
6093
  #holdersOf(name) {
@@ -5876,18 +6101,19 @@ var GraphQLManager = class {
5876
6101
  return supergraph === "" || supergraph === "graphql" ? [supergraph] : [supergraph, "graphql"];
5877
6102
  }
5878
6103
  #generated() {
5879
- if (this.#generatedTypes?.models !== this.cachedDocumentModels) {
5880
- const types = getGeneratedDocumentModelTypes(this.cachedDocumentModels, this.#modelSchemas);
5881
- const sdl = print({
5882
- kind: Kind.DOCUMENT,
5883
- definitions: types.definitions
5884
- });
5885
- this.#generatedTypes = {
5886
- models: this.cachedDocumentModels,
5887
- types: sdl === this.#generatedTypes?.sdl ? this.#generatedTypes.types : types,
5888
- sdl
5889
- };
5890
- }
6104
+ const previous = this.#generatedTypes;
6105
+ const sameScalars = previous?.types.scalars === this.#scalars;
6106
+ if (previous?.models === this.cachedDocumentModels && sameScalars) return previous.types;
6107
+ const types = getGeneratedDocumentModelTypes(this.cachedDocumentModels, this.#modelSchemas, this.#scalars);
6108
+ const sdl = print({
6109
+ kind: Kind.DOCUMENT,
6110
+ definitions: types.definitions
6111
+ });
6112
+ this.#generatedTypes = {
6113
+ models: this.cachedDocumentModels,
6114
+ types: previous?.sdl === sdl && sameScalars ? previous.types : types,
6115
+ sdl
6116
+ };
5891
6117
  return this.#generatedTypes.types;
5892
6118
  }
5893
6119
  #schemaOptions(subgraph) {
@@ -5896,6 +6122,19 @@ var GraphQLManager = class {
5896
6122
  ownTypeNames: subgraph instanceof DocumentModelSubgraph ? subgraph.generatedTypeNames : void 0
5897
6123
  };
5898
6124
  }
6125
+ #warnAuthoredScalarResolvers(subgraph) {
6126
+ let logged = this.#loggedScalarResolvers.get(subgraph);
6127
+ if (!logged) {
6128
+ logged = /* @__PURE__ */ new Set();
6129
+ this.#loggedScalarResolvers.set(subgraph, logged);
6130
+ }
6131
+ for (const scalar of Object.keys(subgraph.resolvers)) {
6132
+ if (!this.#scalars.has(scalar)) continue;
6133
+ if (logged.has(scalar)) continue;
6134
+ logged.add(scalar);
6135
+ this.logger.warn("Subgraph @name provides its own resolver for registered scalar @scalar; the registered validation is not applied.", subgraph.name, scalar);
6136
+ }
6137
+ }
5899
6138
  /** Whether `subgraph`'s own typeDefs refer to a document model's types. */
5900
6139
  #usesModelTypes(subgraph) {
5901
6140
  const memo = this.#usesModelTypesMemo.get(subgraph);
@@ -5924,10 +6163,14 @@ var GraphQLManager = class {
5924
6163
  this.#usesModelTypesMemo.set(subgraph, uses);
5925
6164
  return uses;
5926
6165
  }
5927
- /** The generated type names `subgraph` redefines under the current models. */
5928
- #typeCollisions(subgraph) {
6166
+ /** The generated type names `subgraph` redefines under the current models.
6167
+ * A core or host subgraph takes a registered scalar's name instead. */
6168
+ #typeCollisions(subgraph, origin = this.#originOf(subgraph)) {
5929
6169
  try {
5930
- return findSubgraphTypeCollisions(this.#generated(), subgraph.typeDefs, this.#schemaOptions(subgraph).ownTypeNames);
6170
+ const collisions = findSubgraphTypeCollisions(this.#generated(), subgraph.typeDefs, this.#schemaOptions(subgraph).ownTypeNames);
6171
+ if (origin !== CORE_ORIGIN && origin !== HOST_ORIGIN || !collisions.some((name) => this.#scalars.has(name))) return collisions;
6172
+ const modelTypes = getGeneratedDocumentModelTypes(this.cachedDocumentModels, this.#modelSchemas).names;
6173
+ return collisions.filter((name) => !this.#scalars.has(name) || modelTypes.has(name));
5931
6174
  } catch {
5932
6175
  return [];
5933
6176
  }
@@ -5952,7 +6195,7 @@ var GraphQLManager = class {
5952
6195
  const admission = decideAdmission(instance, origin, Array.from(this.#holdersOf(instance.name), (holder) => ({
5953
6196
  holder,
5954
6197
  origin: this.#originOf(holder)
5955
- })), () => this.#typeCollisions(instance));
6198
+ })), () => this.#typeCollisions(instance, origin));
5956
6199
  switch (admission.action) {
5957
6200
  case "skip": return {
5958
6201
  action: "skip",
@@ -6086,9 +6329,22 @@ var GraphQLManager = class {
6086
6329
  async registerSubgraphInstance(subgraphInstance, supergraph = "", core = false) {
6087
6330
  return this.#serialize(() => this.#addSubgraphInstance(subgraphInstance, supergraph, core));
6088
6331
  }
6332
+ /** Every change ends by admitting the scalars again, whether or not it
6333
+ * succeeded: a subgraph that never registered must not keep a name. */
6089
6334
  #serialize(task) {
6090
6335
  if (this.#inHook.getStore()?.active) return task();
6091
- const run = this.#registryChanges.then(() => this.#inHook.exit(task));
6336
+ return this.#enqueue(async () => {
6337
+ try {
6338
+ return await task();
6339
+ } finally {
6340
+ await this.#syncScalars().catch((error) => {
6341
+ reportFailure(this.#reporting, error, "Could not apply the registered scalars after a change: @error");
6342
+ });
6343
+ }
6344
+ });
6345
+ }
6346
+ #enqueue(change) {
6347
+ const run = this.#registryChanges.then(() => this.#inHook.exit(change));
6092
6348
  this.#registryChanges = run.catch(() => void 0);
6093
6349
  return run;
6094
6350
  }
@@ -6200,6 +6456,7 @@ var GraphQLManager = class {
6200
6456
  documentPermissionService: this.documentPermissionService,
6201
6457
  authorizationService: this.authorizationService,
6202
6458
  syncServingGate: this.syncServingGate,
6459
+ readableDocuments: this.readableDocuments,
6203
6460
  attachments: this.attachments,
6204
6461
  inspection: this.inspection,
6205
6462
  credentials: createCredentialInvalidator(this.authService)
@@ -6450,13 +6707,14 @@ var GraphQLManager = class {
6450
6707
  const cached = this.subgraphHandlerCache.get(subgraphPath);
6451
6708
  if (cached) {
6452
6709
  if (cached.subgraph === subgraph) {
6453
- if (cached.generated === this.#generated() || !this.#usesModelTypes(subgraph)) continue;
6710
+ if (cached.generated === this.#generated() || !this.#usesModelTypes(subgraph) && cached.generated.scalars === this.#scalars) continue;
6454
6711
  } else if (this.#origins.has(cached.subgraph)) {
6455
6712
  this.logger.warn("Subgraph path @path already mounted by @kept; @name is shadowed and will not be mounted", subgraphPath, cached.subgraph.name, subgraph.name);
6456
6713
  continue;
6457
6714
  } else this.#unmountSubgraph(cached.subgraph, supergraph);
6458
6715
  }
6459
6716
  const generated = this.#generated();
6717
+ this.#warnAuthoredScalarResolvers(subgraph);
6460
6718
  const schema = createSchema(this.cachedDocumentModels, this.#boundResolvers(subgraph), subgraph.typeDefs, this.#schemaOptions(subgraph));
6461
6719
  const rawHandler = await this.gatewayAdapter.createHandler(schema, this.#makeContextFactory());
6462
6720
  if (!subgraphsMap.get(supergraph)?.includes(subgraph)) continue;
@@ -6569,6 +6827,7 @@ var GraphQLManager = class {
6569
6827
  return false;
6570
6828
  }
6571
6829
  #buildSubgraphSchemaModule(subgraph) {
6830
+ this.#warnAuthoredScalarResolvers(subgraph);
6572
6831
  return buildSubgraphSchemaModule(this.cachedDocumentModels, this.#boundResolvers(subgraph), subgraph.typeDefs, this.#schemaOptions(subgraph));
6573
6832
  }
6574
6833
  #getSubgraphDefinitions() {
@@ -7828,6 +8087,16 @@ function ensureJobSubscription(read, jobId) {
7828
8087
  //#region src/graphql/reactor/subgraph.ts
7829
8088
  var ReactorSubgraph = class extends BaseSubgraph {
7830
8089
  logger = new ConsoleLogger(["ReactorSubgraph"]);
8090
+ /**
8091
+ * A resolver's failure: a document that does not exist is an answer (a
8092
+ * client asking for one it just removed), logged at info; anything else
8093
+ * is an error.
8094
+ */
8095
+ logFailure(message, ...replacements) {
8096
+ const error = replacements[replacements.length - 1];
8097
+ if (isNotFoundError(error)) this.logger.info(message, ...replacements);
8098
+ else this.logger.error(message, ...replacements);
8099
+ }
7831
8100
  constructor(args) {
7832
8101
  super(args);
7833
8102
  this.logger.verbose(`constructor()`);
@@ -7995,7 +8264,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
7995
8264
  paging: args.paging
7996
8265
  }, this.viewSubject(ctx));
7997
8266
  } catch (error) {
7998
- this.logger.error("Error in PHDocument.operations: @Error", error);
8267
+ this.logFailure("Error in PHDocument.operations: @Error", error);
7999
8268
  throw error;
8000
8269
  }
8001
8270
  } },
@@ -8005,7 +8274,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8005
8274
  try {
8006
8275
  return await documentModels(this.clientsOf(ctx).read, args);
8007
8276
  } catch (error) {
8008
- this.logger.error("Error in documentModels: @Error", error);
8277
+ this.logFailure("Error in documentModels: @Error", error);
8009
8278
  throw error;
8010
8279
  }
8011
8280
  },
@@ -8020,7 +8289,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8020
8289
  consistency: args.consistency
8021
8290
  }, this.viewSubject(ctx));
8022
8291
  } catch (error) {
8023
- this.logger.error("Error in document: @Error", error);
8292
+ this.logFailure("Error in document: @Error", error);
8024
8293
  throw error;
8025
8294
  }
8026
8295
  },
@@ -8037,7 +8306,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8037
8306
  consistency: args.consistency
8038
8307
  }, this.viewSubject(ctx));
8039
8308
  } catch (error) {
8040
- this.logger.error("Error in documentOutgoingRelationships: @Error", error);
8309
+ this.logFailure("Error in documentOutgoingRelationships: @Error", error);
8041
8310
  throw error;
8042
8311
  }
8043
8312
  },
@@ -8058,7 +8327,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8058
8327
  items: await this.readableByHost(result.items, ctx)
8059
8328
  };
8060
8329
  } catch (error) {
8061
- this.logger.error("Error in documentIncomingRelationships: @Error", error);
8330
+ this.logFailure("Error in documentIncomingRelationships: @Error", error);
8062
8331
  throw error;
8063
8332
  }
8064
8333
  },
@@ -8076,7 +8345,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8076
8345
  }, this.viewSubject(ctx));
8077
8346
  return await this.filterRelationshipEdges(result, "targetId", ctx);
8078
8347
  } catch (error) {
8079
- this.logger.error("Error in documentOutgoingRelationshipEdges: @Error", error);
8348
+ this.logFailure("Error in documentOutgoingRelationshipEdges: @Error", error);
8080
8349
  throw error;
8081
8350
  }
8082
8351
  },
@@ -8094,7 +8363,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8094
8363
  }, this.viewSubject(ctx));
8095
8364
  return await this.filterRelationshipEdges(result, "sourceId", ctx);
8096
8365
  } catch (error) {
8097
- this.logger.error("Error in documentIncomingRelationshipEdges: @Error", error);
8366
+ this.logFailure("Error in documentIncomingRelationshipEdges: @Error", error);
8098
8367
  throw error;
8099
8368
  }
8100
8369
  },
@@ -8110,7 +8379,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8110
8379
  items: await this.readableByHost(result.items, ctx)
8111
8380
  };
8112
8381
  } catch (error) {
8113
- this.logger.error("Error in findDocuments: @Error", error);
8382
+ this.logFailure("Error in findDocuments: @Error", error);
8114
8383
  throw error;
8115
8384
  }
8116
8385
  },
@@ -8129,7 +8398,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8129
8398
  };
8130
8399
  return await jobStatus(this.clientsOf(ctx).read, args, readable, readable);
8131
8400
  } catch (error) {
8132
- this.logger.error("Error in jobStatus: @Error", error);
8401
+ this.logFailure("Error in jobStatus: @Error", error);
8133
8402
  throw error;
8134
8403
  }
8135
8404
  },
@@ -8141,7 +8410,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8141
8410
  scopes: args.view?.scopes ? [...args.view.scopes] : void 0
8142
8411
  });
8143
8412
  } catch (error) {
8144
- this.logger.error("Error in documentServed: @Error", error);
8413
+ this.logFailure("Error in documentServed: @Error", error);
8145
8414
  throw error;
8146
8415
  }
8147
8416
  },
@@ -8164,7 +8433,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8164
8433
  if (parentIdOrSlug !== void 0 && !await this.listsDocument(parentIdOrSlug, ctx)) throw new ForbiddenError("to read this document");
8165
8434
  return await createDefaults(this.clientsOf(ctx).read, parentIdOrSlug, args.documentType ?? void 0);
8166
8435
  } catch (error) {
8167
- this.logger.error("Error in createDefaults: @Error", error);
8436
+ this.logFailure("Error in createDefaults: @Error", error);
8168
8437
  throw error;
8169
8438
  }
8170
8439
  },
@@ -8184,7 +8453,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8184
8453
  paging: args.paging
8185
8454
  }, this.viewSubject(ctx));
8186
8455
  } catch (error) {
8187
- this.logger.error("Error in documentOperations: @Error", error);
8456
+ this.logFailure("Error in documentOperations: @Error", error);
8188
8457
  throw error;
8189
8458
  }
8190
8459
  },
@@ -8206,7 +8475,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8206
8475
  candidates: args.candidates
8207
8476
  }, this.viewSubject(ctx));
8208
8477
  } catch (error) {
8209
- this.logger.error("Error in evaluateActions: @Error", error);
8478
+ this.logFailure("Error in evaluateActions: @Error", error);
8210
8479
  throw error;
8211
8480
  }
8212
8481
  },
@@ -8254,7 +8523,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8254
8523
  const heldOpIds = gate && gated ? await collectHeldSyncOperations(gated, gate, this.viewSubject(ctx)) : /* @__PURE__ */ new Set();
8255
8524
  return pollSyncEnvelopes(this.syncManager, args, forbiddenIds, heldOpIds, gated && new Set(gated.map((syncOp) => syncOp.id)));
8256
8525
  } catch (error) {
8257
- this.logger.error("Error in pollSyncEnvelopes(@args): @Error", args, error);
8526
+ this.logFailure("Error in pollSyncEnvelopes(@args): @Error", args, error);
8258
8527
  throw error;
8259
8528
  }
8260
8529
  }
@@ -8276,7 +8545,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8276
8545
  if (ctx.user?.address && result?.id) await this.documentPermissionService?.initializeDocumentProtection(result.id, ctx.user.address, this.authorizationService.config.defaultProtection);
8277
8546
  return result;
8278
8547
  } catch (error) {
8279
- this.logger.error("Error in createDocument(@args): @Error", args, error);
8548
+ this.logFailure("Error in createDocument(@args): @Error", args, error);
8280
8549
  throw error;
8281
8550
  }
8282
8551
  },
@@ -8296,7 +8565,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8296
8565
  if (ctx.user?.address && result?.id) await this.documentPermissionService?.initializeDocumentProtection(result.id, ctx.user.address, this.authorizationService.config.defaultProtection);
8297
8566
  return result;
8298
8567
  } catch (error) {
8299
- this.logger.error("Error in createEmptyDocument(@args): @Error", args, error);
8568
+ this.logFailure("Error in createEmptyDocument(@args): @Error", args, error);
8300
8569
  throw error;
8301
8570
  }
8302
8571
  },
@@ -8311,7 +8580,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8311
8580
  branch: args.branch
8312
8581
  }, this.viewSubject(ctx));
8313
8582
  } catch (error) {
8314
- this.logger.error("Error in execute(@args): @Error", args, error);
8583
+ this.logFailure("Error in execute(@args): @Error", args, error);
8315
8584
  throw error;
8316
8585
  }
8317
8586
  },
@@ -8326,7 +8595,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8326
8595
  branch: args.branch
8327
8596
  });
8328
8597
  } catch (error) {
8329
- this.logger.error("Error in executeAsync(@args): @Error", args, error);
8598
+ this.logFailure("Error in executeAsync(@args): @Error", args, error);
8330
8599
  throw error;
8331
8600
  }
8332
8601
  },
@@ -8353,7 +8622,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8353
8622
  }
8354
8623
  return await executeBatch(this.clientsOf(ctx).write, { jobs });
8355
8624
  } catch (error) {
8356
- this.logger.error("Error in executeBatch(@args): @Error", args, error);
8625
+ this.logFailure("Error in executeBatch(@args): @Error", args, error);
8357
8626
  throw error;
8358
8627
  }
8359
8628
  },
@@ -8366,7 +8635,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8366
8635
  documentIdentifier: handle.fetchIdentifier
8367
8636
  }, this.viewSubject(ctx));
8368
8637
  } catch (error) {
8369
- this.logger.error("Error in mutateDocument(@args): @Error", args, error);
8638
+ this.logFailure("Error in mutateDocument(@args): @Error", args, error);
8370
8639
  throw error;
8371
8640
  }
8372
8641
  },
@@ -8379,7 +8648,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8379
8648
  documentIdentifier: handle.fetchIdentifier
8380
8649
  });
8381
8650
  } catch (error) {
8382
- this.logger.error("Error in mutateDocumentAsync(@args): @Error", args, error);
8651
+ this.logFailure("Error in mutateDocumentAsync(@args): @Error", args, error);
8383
8652
  throw error;
8384
8653
  }
8385
8654
  },
@@ -8394,7 +8663,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8394
8663
  branch: args.branch
8395
8664
  }, void 0, this.viewSubject(ctx));
8396
8665
  } catch (error) {
8397
- this.logger.error("Error in renameDocument(@args): @Error", args, error);
8666
+ this.logFailure("Error in renameDocument(@args): @Error", args, error);
8398
8667
  throw error;
8399
8668
  }
8400
8669
  },
@@ -8409,7 +8678,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8409
8678
  branch: args.branch
8410
8679
  }, void 0, this.viewSubject(ctx));
8411
8680
  } catch (error) {
8412
- this.logger.error("Error in setPreferredEditor(@args): @Error", args, error);
8681
+ this.logFailure("Error in setPreferredEditor(@args): @Error", args, error);
8413
8682
  throw error;
8414
8683
  }
8415
8684
  },
@@ -8427,7 +8696,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8427
8696
  branch: args.branch
8428
8697
  }, this.viewSubject(ctx));
8429
8698
  } catch (error) {
8430
- this.logger.error("Error in addRelationship(@args): @Error", args, error);
8699
+ this.logFailure("Error in addRelationship(@args): @Error", args, error);
8431
8700
  throw error;
8432
8701
  }
8433
8702
  },
@@ -8445,7 +8714,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8445
8714
  branch: args.branch
8446
8715
  }, this.viewSubject(ctx));
8447
8716
  } catch (error) {
8448
- this.logger.error("Error in updateRelationship(@args): @Error", args, error);
8717
+ this.logFailure("Error in updateRelationship(@args): @Error", args, error);
8449
8718
  throw error;
8450
8719
  }
8451
8720
  },
@@ -8462,7 +8731,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8462
8731
  branch: args.branch
8463
8732
  }, this.viewSubject(ctx));
8464
8733
  } catch (error) {
8465
- this.logger.error("Error in removeRelationship(@args): @Error", args, error);
8734
+ this.logFailure("Error in removeRelationship(@args): @Error", args, error);
8466
8735
  throw error;
8467
8736
  }
8468
8737
  },
@@ -8482,7 +8751,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8482
8751
  branch: args.branch
8483
8752
  }, this.viewSubject(ctx));
8484
8753
  } catch (error) {
8485
- this.logger.error("Error in moveRelationship(@args): @Error", args, error);
8754
+ this.logFailure("Error in moveRelationship(@args): @Error", args, error);
8486
8755
  throw error;
8487
8756
  }
8488
8757
  },
@@ -8498,7 +8767,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8498
8767
  if (result && driveIdToInvalidate) this.graphqlManager.driveOwnershipCache.remove(driveIdToInvalidate);
8499
8768
  return result;
8500
8769
  } catch (error) {
8501
- this.logger.error("Error in deleteDocument(@args): @Error", args, error);
8770
+ this.logFailure("Error in deleteDocument(@args): @Error", args, error);
8502
8771
  throw error;
8503
8772
  }
8504
8773
  },
@@ -8515,7 +8784,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8515
8784
  propagate: args.propagate
8516
8785
  });
8517
8786
  } catch (error) {
8518
- this.logger.error("Error in deleteDocuments(@args): @Error", args, error);
8787
+ this.logFailure("Error in deleteDocuments(@args): @Error", args, error);
8519
8788
  throw error;
8520
8789
  }
8521
8790
  },
@@ -8529,7 +8798,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8529
8798
  await this.#bindOrRefuseChannel(args.input.id, ctx);
8530
8799
  return await touchChannel(this.syncManager, args, this.#creatorBinding(ctx));
8531
8800
  } catch (error) {
8532
- this.logger.error("Error in touchChannel(@args): @Error", args, error);
8801
+ this.logFailure("Error in touchChannel(@args): @Error", args, error);
8533
8802
  throw error;
8534
8803
  }
8535
8804
  },
@@ -8582,7 +8851,7 @@ var ReactorSubgraph = class extends BaseSubgraph {
8582
8851
  })) };
8583
8852
  return await pushSyncEnvelopes(this.syncManager, mutableArgs);
8584
8853
  } catch (error) {
8585
- this.logger.error("Error in pushSyncEnvelopes(@args): @Error", args, error);
8854
+ this.logFailure("Error in pushSyncEnvelopes(@args): @Error", args, error);
8586
8855
  throw error;
8587
8856
  }
8588
8857
  }
@@ -8652,10 +8921,10 @@ const ADMIN_USERS = new Proxy([], {
8652
8921
  //#endregion
8653
8922
  //#region src/graphql/system/version.ts
8654
8923
  function getVersion() {
8655
- return "6.2.3-dev.79";
8924
+ return "6.2.3-dev.80";
8656
8925
  }
8657
8926
  function getGitHash() {
8658
- return "e1e361faacfb9bf18a46dcb7a0c5af6033b6b453";
8927
+ return "8bf7e24674c3274d665b8fb36901af55c50921dc";
8659
8928
  }
8660
8929
  function getGitUrl() {
8661
8930
  return buildTreeUrl(getGitHash());
@@ -8678,6 +8947,7 @@ var SystemSubgraph = class extends BaseSubgraph {
8678
8947
  const PACKAGE_ENTRIES = {
8679
8948
  documentModels: "node/document-models/index.mjs",
8680
8949
  subgraphs: "node/subgraphs/index.mjs",
8950
+ scalars: "node/scalars/index.mjs",
8681
8951
  processors: "node/processors/index.mjs"
8682
8952
  };
8683
8953
  const REGISTRY_ENTRY_ABSENT = "ERR_REGISTRY_ENTRY_ABSENT";
@@ -8798,7 +9068,7 @@ var RegistryPackageCache = class {
8798
9068
  await this.discard(dir);
8799
9069
  return null;
8800
9070
  }
8801
- if (typeof manifest.externalDependencies !== "object") {
9071
+ if (typeof manifest.externalDependencies !== "object" || !Array.isArray(manifest.entryKinds) || Object.keys(PACKAGE_ENTRIES).some((kind) => !manifest.entryKinds.includes(kind))) {
8802
9072
  await this.discard(dir);
8803
9073
  return null;
8804
9074
  }
@@ -8912,12 +9182,13 @@ var RegistryPackageCache = class {
8912
9182
  }
8913
9183
  const entries = {};
8914
9184
  for (const [kind, rel] of Object.entries(PACKAGE_ENTRIES)) if (rel in files) entries[kind] = rel;
8915
- if (Object.keys(entries).length === 0) throw new Error(`${name}@${version} serves no document models, subgraphs or processors`);
9185
+ if (Object.keys(entries).length === 0) throw new Error(`${name}@${version} serves no document models, subgraphs, scalars or processors`);
8916
9186
  const packageManifest = await this.fetchBounded(new URL(PACKAGE_MANIFEST, base).href, true);
8917
9187
  return {
8918
9188
  name,
8919
9189
  version,
8920
9190
  entries,
9191
+ entryKinds: Object.keys(PACKAGE_ENTRIES),
8921
9192
  files: Object.fromEntries(Object.entries(files).sort(([a], [b]) => a.localeCompare(b))),
8922
9193
  bareImports: [...bare].sort(),
8923
9194
  externalDependencies: externalDependenciesOf(packageManifest)
@@ -9059,7 +9330,7 @@ function packageNameOf(specifier) {
9059
9330
  function packageRoot(specifier, pkg, base) {
9060
9331
  let found;
9061
9332
  try {
9062
- found = findPackageJSON(specifier, base);
9333
+ found = nodeModule.findPackageJSON(specifier, base);
9063
9334
  } catch {
9064
9335
  return null;
9065
9336
  }
@@ -9256,7 +9527,7 @@ var HttpPackageLoader = class {
9256
9527
  if (cached) {
9257
9528
  const filePath = cached.entries[kind];
9258
9529
  if (!filePath) throw Object.assign(/* @__PURE__ */ new Error(`${packageName}@${cached.version} serves no ${kind}`), { code: REGISTRY_ENTRY_ABSENT });
9259
- if (kind !== "documentModels") this.assertExternalDependencies(cached);
9530
+ if (kind !== "documentModels" && kind !== "scalars") this.assertExternalDependencies(cached);
9260
9531
  return {
9261
9532
  module: await import(
9262
9533
  /* @vite-ignore */
@@ -9280,7 +9551,7 @@ var HttpPackageLoader = class {
9280
9551
  const list = missing.map((dep) => `${dep}@${cached.externalDependencies[dep]}`).join(", ");
9281
9552
  if (!this.reportedExternal.has(id)) {
9282
9553
  this.reportedExternal.add(id);
9283
- this.logger.error("@package needs packages with native addons or WebAssembly modules that are not installed (@deps); its subgraphs and processors are not loaded, its document models and pieces are. Install it locally with `ph install --local @name`, or list it in PH_PACKAGES for a Docker image.", id, list, cached.name);
9554
+ this.logger.error("@package needs packages with native addons or WebAssembly modules that are not installed (@deps); its subgraphs and processors are not loaded, its document models, scalars and pieces are. Install it locally with `ph install --local @name`, or list it in PH_PACKAGES for a Docker image.", id, list, cached.name);
9284
9555
  }
9285
9556
  throw Object.assign(/* @__PURE__ */ new Error(`${id} needs external dependencies that are not installed: ${list}`), { code: REGISTRY_EXTERNAL_DEPS_MISSING });
9286
9557
  }
@@ -9308,6 +9579,13 @@ var HttpPackageLoader = class {
9308
9579
  this.logger.verbose(`Loaded ${subgraphs.length} subgraphs from ${packageName}`);
9309
9580
  return subgraphs;
9310
9581
  }
9582
+ async loadScalars(packageSpec) {
9583
+ const { name: packageName } = this.parsePackageSpec(packageSpec);
9584
+ const { module } = await this.importEntry(packageSpec, "scalars");
9585
+ const scalars = scalarExportsOf(module);
9586
+ this.logger.verbose(`Loaded ${scalars.length} scalars from ${packageName}`);
9587
+ return scalars;
9588
+ }
9311
9589
  async loadProcessors(packageSpec) {
9312
9590
  const { name: packageName } = this.parsePackageSpec(packageSpec);
9313
9591
  const { module } = await this.importEntry(packageSpec, "processors");
@@ -9479,6 +9757,12 @@ var ImportPackageLoader = class {
9479
9757
  this.logger.verbose(` ➜ Loaded ${subgraphs.length} Subgraphs from: ${identifier}`);
9480
9758
  return subgraphs;
9481
9759
  }
9760
+ async loadScalars(identifier) {
9761
+ this.logger.verbose(`Loading scalars from package: ${identifier}`);
9762
+ const scalars = scalarExportsOf(await loadScalars(identifier));
9763
+ this.logger.verbose(` ➜ Loaded ${scalars.length} Scalars from: ${identifier}`);
9764
+ return scalars;
9765
+ }
9482
9766
  async loadProcessors(identifier) {
9483
9767
  this.logger.verbose(`Loading processors from package: ${identifier}`);
9484
9768
  const factory = (await loadProcessors(identifier))?.processorFactory;
@@ -9516,7 +9800,84 @@ var ImportPackageLoader = class {
9516
9800
  }
9517
9801
  };
9518
9802
  //#endregion
9803
+ //#region src/packages/scalar-registry.ts
9804
+ function reservedBy(name) {
9805
+ if (specifiedScalarTypes.some((type) => type.name === name)) return "GraphQL built-in";
9806
+ if (getCatalogScalar(name)) return "catalog";
9807
+ return reservedTypeNames([]).has(name) ? "document-model schema" : void 0;
9808
+ }
9809
+ function buildScalarRegistry(packages) {
9810
+ const registry = /* @__PURE__ */ new Map();
9811
+ const refusals = [];
9812
+ for (const [packageName, exports] of packages) for (const entry of exports) {
9813
+ if (!("definition" in entry)) {
9814
+ refusals.push({
9815
+ kind: "unsupported-version",
9816
+ packageName,
9817
+ exportName: entry.exportName,
9818
+ version: entry.unsupportedVersion
9819
+ });
9820
+ continue;
9821
+ }
9822
+ const { exportName, definition } = entry;
9823
+ const { name } = definition;
9824
+ if (exportName !== name) {
9825
+ refusals.push({
9826
+ kind: "export-key-mismatch",
9827
+ packageName,
9828
+ exportName,
9829
+ name
9830
+ });
9831
+ continue;
9832
+ }
9833
+ const reserved = reservedBy(name);
9834
+ if (reserved) {
9835
+ refusals.push({
9836
+ kind: "reserved-name",
9837
+ packageName,
9838
+ exportName,
9839
+ name,
9840
+ reservedBy: reserved
9841
+ });
9842
+ continue;
9843
+ }
9844
+ const holder = registry.get(name);
9845
+ if (holder?.definition === definition) continue;
9846
+ if (holder) {
9847
+ refusals.push({
9848
+ kind: "duplicate-name",
9849
+ packageName,
9850
+ name,
9851
+ registeredBy: holder.packageName
9852
+ });
9853
+ continue;
9854
+ }
9855
+ registry.set(name, {
9856
+ definition,
9857
+ packageName
9858
+ });
9859
+ }
9860
+ return {
9861
+ registry,
9862
+ refusals
9863
+ };
9864
+ }
9865
+ const RESERVER = {
9866
+ "GraphQL built-in": "GraphQL as a built-in scalar",
9867
+ catalog: "the scalar catalog",
9868
+ "document-model schema": "the document-model schema"
9869
+ };
9870
+ function describeScalarRefusal(refusal) {
9871
+ switch (refusal.kind) {
9872
+ case "reserved-name": return `Export ${refusal.exportName} of package ${refusal.packageName} is refused: the name ${refusal.name} is reserved by ${RESERVER[refusal.reservedBy]}.`;
9873
+ case "duplicate-name": return `Scalar ${refusal.name} of package ${refusal.packageName} is refused: package ${refusal.registeredBy} already registers a different ${refusal.name}.`;
9874
+ case "export-key-mismatch": return `Scalar ${refusal.name} of package ${refusal.packageName} is refused: it is exported as ${refusal.exportName}, and the export name must equal the scalar name.`;
9875
+ case "unsupported-version": return `Export ${refusal.exportName} of package ${refusal.packageName} is refused: its scalar definition format version ${String(refusal.version)} is not supported; this host supports version ${SCALAR_DEFINITION_VERSION}.`;
9876
+ }
9877
+ }
9878
+ //#endregion
9519
9879
  //#region src/packages/package-manager.ts
9880
+ const BUILT_SCALARS_ENTRY = packageJsonExports["./scalars"].node.slice(1);
9520
9881
  /**
9521
9882
  * A loader throwing "this package isn't mine to load" is normal — loaders are
9522
9883
  * fallbacks for each other. These shapes mean "not found here", not "broken".
@@ -9536,6 +9897,7 @@ function isExpectedLoaderMiss(error, pkg, subPath) {
9536
9897
  if (code === "ERR_REGISTRY_ENTRY_ABSENT") return true;
9537
9898
  if (code === "ERR_PACKAGE_PATH_NOT_EXPORTED" && subPath !== void 0 && error.message.includes(`'./${subPath}'`)) return true;
9538
9899
  if (subPath !== void 0 && new RegExp(`^Failed to fetch \\S*/${subPath}/index\\.mjs: 404$`).test(error.message)) return true;
9900
+ if (code === "ERR_MODULE_NOT_FOUND" && subPath === "scalars" && "url" in error && typeof error.url === "string" && error.url.endsWith(BUILT_SCALARS_ENTRY)) return true;
9539
9901
  if (error.message.startsWith("Invalid package name:")) return true;
9540
9902
  if (code === "ERR_MODULE_NOT_FOUND") return error.message.includes(`'${pkg}'`) || error.message.includes(`"${pkg}"`) || error.message.includes(`'${pkg}/`) || error.message.includes(`"${pkg}/`);
9541
9903
  return false;
@@ -9561,6 +9923,9 @@ var PackageManager = class {
9561
9923
  docModelsMap = /* @__PURE__ */ new Map();
9562
9924
  upgradeManifestsMap = /* @__PURE__ */ new Map();
9563
9925
  subgraphsMap = /* @__PURE__ */ new Map();
9926
+ scalarsMap = /* @__PURE__ */ new Map();
9927
+ scalarRegistry = EMPTY_SCALAR_REGISTRY;
9928
+ loggedScalarRefusals = /* @__PURE__ */ new Set();
9564
9929
  processorMap = /* @__PURE__ */ new Map();
9565
9930
  piecesMap = /* @__PURE__ */ new Map();
9566
9931
  configWatcher;
@@ -9595,6 +9960,7 @@ var PackageManager = class {
9595
9960
  }
9596
9961
  async loadPackagesNow(requested, requestedAt) {
9597
9962
  this.logger.info("Loading packages: @packages", requested.join(", "));
9963
+ const scalarsMap = this.settle("scalars", await this.loadScalars(requested), this.scalarsMap);
9598
9964
  const documentModelLoads = await this.loadDocumentModels(requested);
9599
9965
  const failed = requested.filter((pkg) => documentModelLoads.get(pkg)?.status === "failed");
9600
9966
  const upgradeManifestsMap = await this.loadUpgradeManifests(requested.filter((pkg) => !failed.includes(pkg)));
@@ -9608,6 +9974,7 @@ var PackageManager = class {
9608
9974
  const piecesMap = this.settle("pieces", await this.loadPieces(requested), this.piecesMap);
9609
9975
  const removed = requested.filter((pkg) => (this.removedAt.get(pkg) ?? 0) > requestedAt);
9610
9976
  for (const map of [
9977
+ scalarsMap,
9611
9978
  documentModelsMap,
9612
9979
  upgradeManifestsMap,
9613
9980
  subgraphsMap,
@@ -9615,6 +9982,7 @@ var PackageManager = class {
9615
9982
  piecesMap
9616
9983
  ]) removed.forEach((pkg) => map.delete(pkg));
9617
9984
  const packages = requested.filter((pkg) => !removed.includes(pkg));
9985
+ this.updateScalarsMap(scalarsMap);
9618
9986
  this.upgradeManifestsMap = upgradeManifestsMap;
9619
9987
  this.updatePackagesMap(documentModelsMap);
9620
9988
  this.updateSubgraphsMap(subgraphsMap);
@@ -9632,6 +10000,7 @@ var PackageManager = class {
9632
10000
  documentModels: getUniqueDocumentModels(...Array.from(documentModelsMap.values())),
9633
10001
  upgradeManifests: this.getUniqueUpgradeManifests(),
9634
10002
  subgraphs: subgraphsMap,
10003
+ scalars: scalarsMap,
9635
10004
  processors: processorsMap,
9636
10005
  pieces: piecesMap
9637
10006
  };
@@ -9644,14 +10013,14 @@ var PackageManager = class {
9644
10013
  }
9645
10014
  return settled;
9646
10015
  }
9647
- async loadEach(kind, packages, load) {
10016
+ async loadEach(kind, packages, loaders, load) {
9648
10017
  this.logger.debug(`Loading ${kind} from packages: ${packages.join(", ")}`);
9649
10018
  const subPath = subPathOf(kind);
9650
10019
  const loads = /* @__PURE__ */ new Map();
9651
10020
  for (const pkg of packages) {
9652
10021
  const failures = [];
9653
10022
  let loaded;
9654
- for (const loader of this.loaders) try {
10023
+ for (const loader of loaders) try {
9655
10024
  loaded = {
9656
10025
  status: "loaded",
9657
10026
  value: await load(loader, pkg)
@@ -9672,7 +10041,7 @@ var PackageManager = class {
9672
10041
  return loads;
9673
10042
  }
9674
10043
  loadDocumentModels(packages) {
9675
- return this.loadEach("document models", packages, async (loader, pkg) => {
10044
+ return this.loadEach("document models", packages, this.loaders, async (loader, pkg) => {
9676
10045
  const documentModels = await loader.loadDocumentModels(pkg);
9677
10046
  this.logger.info(`[${loader.name}] Loaded document models from package @pkg: @documentModels`, pkg, documentModels.map((dm) => dm.documentModel.global.id));
9678
10047
  return documentModels;
@@ -9699,7 +10068,7 @@ var PackageManager = class {
9699
10068
  return manifestsMap;
9700
10069
  }
9701
10070
  async loadSubgraphs(packages) {
9702
- const loads = await this.loadEach("subgraphs", packages, (loader, pkg) => loader.loadSubgraphs(pkg));
10071
+ const loads = await this.loadEach("subgraphs", packages, this.loaders, (loader, pkg) => loader.loadSubgraphs(pkg));
9703
10072
  for (const [pkg, load] of loads) {
9704
10073
  if (load.status === "loaded" && load.value.length > 0) continue;
9705
10074
  const declared = manifestDeclaredSubgraphs(pkg);
@@ -9707,14 +10076,17 @@ var PackageManager = class {
9707
10076
  }
9708
10077
  return loads;
9709
10078
  }
10079
+ loadScalars(packages) {
10080
+ return this.loadEach("scalars", packages, this.loaders.filter((loader) => loader.loadScalars !== void 0), (loader, pkg) => loader.loadScalars(pkg));
10081
+ }
9710
10082
  loadProcessors(packages) {
9711
- return this.loadEach("processors", packages, async (loader, pkg) => {
10083
+ return this.loadEach("processors", packages, this.loaders, async (loader, pkg) => {
9712
10084
  const processors = await loader.loadProcessors(pkg);
9713
10085
  return processors ? [processors] : [];
9714
10086
  });
9715
10087
  }
9716
10088
  async loadPieces(packages) {
9717
- const loads = await this.loadEach("pieces", packages, (loader, pkg) => loader.loadPieces(pkg));
10089
+ const loads = await this.loadEach("pieces", packages, this.loaders, (loader, pkg) => loader.loadPieces(pkg));
9718
10090
  for (const [pkg, load] of loads) {
9719
10091
  if (load.status !== "loaded" || load.value.length === 0) continue;
9720
10092
  this.logger.info("Loaded @count piece(s) from package @pkg: @pieces", load.value.length, pkg, load.value.map((piece) => piece.name).join(", "));
@@ -9726,10 +10098,12 @@ var PackageManager = class {
9726
10098
  const subPath = subPathOf(kind);
9727
10099
  const realFailures = failures.filter(({ error }) => !isExpectedLoaderMiss(error, pkg, subPath) && !ALREADY_LOGGED.has(error?.code ?? ""));
9728
10100
  if (realFailures.length === 0) return;
9729
- const details = realFailures.map(({ loader, error }) => {
9730
- return ` [${loader}] ${error instanceof Error ? error.message : String(error)}`;
9731
- }).join("\n");
9732
- this.logger.warn(`All package loaders failed to load ${kind} from @pkg:\n@details`, pkg, details);
10101
+ this.warnFailedLoad(kind, pkg, realFailures.map(({ loader, error }) => {
10102
+ return `[${loader}] ${error instanceof Error ? error.message : String(error)}`;
10103
+ }));
10104
+ }
10105
+ warnFailedLoad(kind, pkg, reasons) {
10106
+ this.logger.warn(`${failedLoadHeader(kind)}\n@reasons`, pkg, reasons.map((reason) => ` ${reason}`).join("\n"));
9733
10107
  }
9734
10108
  withReload(kind, current, pkg, load) {
9735
10109
  if (load?.status === "failed") {
@@ -9763,6 +10137,17 @@ var PackageManager = class {
9763
10137
  const next = this.withReload("subgraphs", this.subgraphsMap, pkg, load);
9764
10138
  if (next) this.updateSubgraphsMap(next);
9765
10139
  }
10140
+ async updateScalarsForPackage(pkg) {
10141
+ this.logger.debug(`Updating scalars for package: ${pkg}`);
10142
+ const load = (await this.loadScalars([pkg])).get(pkg);
10143
+ if (!this.subscribedPackages.has(pkg)) return;
10144
+ const next = this.withReload("scalars", this.scalarsMap, pkg, load);
10145
+ if (!next) return;
10146
+ this.updateScalarsMap(new Map(Array.from(this.subscribedPackages).flatMap((loaded) => {
10147
+ const exports = next.get(loaded);
10148
+ return exports ? [[loaded, exports]] : [];
10149
+ })));
10150
+ }
9766
10151
  async updateProcessorsForPackage(pkg) {
9767
10152
  this.logger.debug(`Updating processors for package: ${pkg}`);
9768
10153
  const load = (await this.loadProcessors([pkg])).get(pkg);
@@ -9794,11 +10179,13 @@ var PackageManager = class {
9794
10179
  for (const pkg of packages) {
9795
10180
  const onDocumentModels = this.getDebouncedUpdateCallback(pkg, "document-models", () => this.updateDocumentModelsForPackage(pkg));
9796
10181
  const onSubgraphs = this.getDebouncedUpdateCallback(pkg, "subgraphs", () => this.updateSubgraphsForPackage(pkg));
10182
+ const onScalars = this.getDebouncedUpdateCallback(pkg, "scalars", () => this.updateScalarsForPackage(pkg));
9797
10183
  const onProcessors = this.getDebouncedUpdateCallback(pkg, "processors", () => this.updateProcessorsForPackage(pkg));
9798
10184
  const onPieces = this.getDebouncedUpdateCallback(pkg, "pieces", () => this.updatePiecesForPackage(pkg));
9799
10185
  for (const loader of this.loaders) {
9800
10186
  if (loader.onDocumentModelsChange) unsubs.push(loader.onDocumentModelsChange(pkg, onDocumentModels));
9801
10187
  if (loader.onSubgraphsChange) unsubs.push(loader.onSubgraphsChange(pkg, onSubgraphs));
10188
+ if (loader.onScalarsChange) unsubs.push(loader.onScalarsChange(pkg, onScalars));
9802
10189
  if (loader.onProcessorsChange) unsubs.push(loader.onProcessorsChange(pkg, onProcessors));
9803
10190
  if (loader.onPiecesChange) unsubs.push(loader.onPiecesChange(pkg, onPieces));
9804
10191
  }
@@ -9840,6 +10227,25 @@ var PackageManager = class {
9840
10227
  this.subgraphsMap = subgraphsMap;
9841
10228
  this.eventEmitter.emit("subgraphsChange", subgraphsMap);
9842
10229
  }
10230
+ updateScalarsMap(scalarsMap) {
10231
+ this.scalarsMap = scalarsMap;
10232
+ const { registry, refusals } = buildScalarRegistry(scalarsMap);
10233
+ const reported = /* @__PURE__ */ new Set();
10234
+ const unreported = /* @__PURE__ */ new Map();
10235
+ for (const refusal of refusals) {
10236
+ const reason = describeScalarRefusal(refusal);
10237
+ reported.add(reason);
10238
+ if (this.loggedScalarRefusals.has(reason)) continue;
10239
+ const reasons = unreported.get(refusal.packageName) ?? [];
10240
+ reasons.push(reason);
10241
+ unreported.set(refusal.packageName, reasons);
10242
+ }
10243
+ for (const [pkg, reasons] of unreported) this.warnFailedLoad("scalars", pkg, reasons);
10244
+ this.loggedScalarRefusals = reported;
10245
+ if (sameScalarRegistry(registry, this.scalarRegistry)) return;
10246
+ this.scalarRegistry = registry;
10247
+ this.eventEmitter.emit("scalarsChange", registry);
10248
+ }
9843
10249
  updateProcessorsMap(processorsMap) {
9844
10250
  const oldPackages = Array.from(this.processorMap.keys());
9845
10251
  const newPackages = Array.from(processorsMap.keys());
@@ -9862,6 +10268,10 @@ var PackageManager = class {
9862
10268
  getDocumentModels() {
9863
10269
  return new Map(this.docModelsMap);
9864
10270
  }
10271
+ /** The scalars registered from every loaded package's `./scalars` entry. */
10272
+ getScalarRegistry() {
10273
+ return this.scalarRegistry;
10274
+ }
9865
10275
  /** The pieces every loaded package ships, keyed by the package. */
9866
10276
  getPieces() {
9867
10277
  return new Map(this.piecesMap);
@@ -9886,6 +10296,7 @@ var PackageManager = class {
9886
10296
  this.subgraphsMap = dropKey(this.subgraphsMap);
9887
10297
  this.processorMap = dropKey(this.processorMap);
9888
10298
  this.piecesMap = dropKey(this.piecesMap);
10299
+ this.updateScalarsMap(dropKey(this.scalarsMap));
9889
10300
  this.updatePackagesMap(this.docModelsMap);
9890
10301
  this.updateSubgraphsMap(this.subgraphsMap);
9891
10302
  this.updateProcessorsMap(this.processorMap);
@@ -9901,6 +10312,12 @@ var PackageManager = class {
9901
10312
  runDetached("Subgraphs change listener", () => handler(subgraphs), this.detached);
9902
10313
  });
9903
10314
  }
10315
+ /** Called when the registry changes; an equal rebuild is not a change. */
10316
+ onScalarsChange(handler) {
10317
+ this.eventEmitter.on("scalarsChange", (scalars) => {
10318
+ runDetached("Scalars change listener", () => handler(scalars), this.detached);
10319
+ });
10320
+ }
9904
10321
  onProcessorsChange(handler) {
9905
10322
  this.eventEmitter.on("processorsChange", (processors) => {
9906
10323
  runDetached("Processors change listener", () => handler(processors), this.detached);
@@ -10497,6 +10914,13 @@ function setupEventListeners(pkgManager, graphqlManager, reactorProcessorManager
10497
10914
  reportFailure(reporting, error, "Document model change left subgraphs stale: @error");
10498
10915
  }
10499
10916
  });
10917
+ pkgManager.onScalarsChange(async (scalars) => {
10918
+ try {
10919
+ await graphqlManager.applyScalarRegistry(scalars);
10920
+ } catch (error) {
10921
+ reportFailure(reporting, error, "Scalar change left subgraphs stale: @error");
10922
+ }
10923
+ });
10500
10924
  pkgManager.onSubgraphsChange(async (packagedSubgraphs) => {
10501
10925
  try {
10502
10926
  await graphqlManager.applyPackageSubgraphs(packagedSubgraphs);
@@ -10578,12 +11002,30 @@ var DocumentPermissionService = class {
10578
11002
  * the document it touched.
10579
11003
  */
10580
11004
  permissionCache;
11005
+ #listeners = /* @__PURE__ */ new Set();
10581
11006
  constructor(db, config = { defaultProtection: false }, cacheOptions = DEFAULT_PERMISSION_CACHE_OPTIONS) {
10582
11007
  this.db = db;
10583
11008
  this.config = config;
10584
11009
  this.permissionCache = new PermissionCache((documentIds) => this.loadPermissionSnapshots(documentIds), cacheOptions);
10585
11010
  }
10586
11011
  /**
11012
+ * Called with the document id after every write through this service
11013
+ * (grant, revoke, protection, owner, deletion), once the cache entry is
11014
+ * invalidated: what a projection of the permission data (the readable
11015
+ * documents read model) follows. Returns the unsubscribe.
11016
+ */
11017
+ onChange(listener) {
11018
+ this.#listeners.add(listener);
11019
+ return () => this.#listeners.delete(listener);
11020
+ }
11021
+ /** The one place a write ends: the cache entry goes, the listeners hear. */
11022
+ #touched(documentId) {
11023
+ this.permissionCache.invalidate(documentId);
11024
+ for (const listener of this.#listeners) try {
11025
+ listener(documentId);
11026
+ } catch {}
11027
+ }
11028
+ /**
10587
11029
  * Get the permission level for a user on a specific document.
10588
11030
  * Returns null if no permission is set.
10589
11031
  */
@@ -10633,7 +11075,7 @@ var DocumentPermissionService = class {
10633
11075
  permission,
10634
11076
  grantedBy: grantedBy.toLowerCase(),
10635
11077
  updatedAt: now
10636
- })).execute().finally(() => this.permissionCache.invalidate(documentId));
11078
+ })).execute().finally(() => this.#touched(documentId));
10637
11079
  return await this.db.selectFrom("DocumentPermission").select([
10638
11080
  "documentId",
10639
11081
  "userAddress",
@@ -10647,14 +11089,14 @@ var DocumentPermissionService = class {
10647
11089
  * Revoke a user's permission on a document
10648
11090
  */
10649
11091
  async revokePermission(documentId, userAddress) {
10650
- await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).where("userAddress", "=", userAddress.toLowerCase()).execute().finally(() => this.permissionCache.invalidate(documentId));
11092
+ await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).where("userAddress", "=", userAddress.toLowerCase()).execute().finally(() => this.#touched(documentId));
10651
11093
  }
10652
11094
  /**
10653
11095
  * Delete all permissions for a document (used when deleting a document)
10654
11096
  */
10655
11097
  async deleteAllDocumentPermissions(documentId) {
10656
- const permissions = await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).returning("id").execute().finally(() => this.permissionCache.invalidate(documentId));
10657
- const operations = await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).returning("id").execute().finally(() => this.permissionCache.invalidate(documentId));
11098
+ const permissions = await this.db.deleteFrom("DocumentPermission").where("documentId", "=", documentId).returning("id").execute().finally(() => this.#touched(documentId));
11099
+ const operations = await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).returning("id").execute().finally(() => this.#touched(documentId));
10658
11100
  return {
10659
11101
  DocumentPermission: permissions.length,
10660
11102
  OperationUserPermission: operations.length
@@ -10662,7 +11104,7 @@ var DocumentPermissionService = class {
10662
11104
  }
10663
11105
  /** Delete a document's protection row, which names its owner. */
10664
11106
  async deleteDocumentProtection(documentId) {
10665
- return (await this.db.deleteFrom("DocumentProtection").where("documentId", "=", documentId).returning("documentId").execute().finally(() => this.permissionCache.invalidate(documentId))).length;
11107
+ return (await this.db.deleteFrom("DocumentProtection").where("documentId", "=", documentId).returning("documentId").execute().finally(() => this.#touched(documentId))).length;
10666
11108
  }
10667
11109
  /** Every row that names the address, for a subject access request. */
10668
11110
  async rowsForAddress(address) {
@@ -10702,7 +11144,7 @@ var DocumentPermissionService = class {
10702
11144
  "documentId",
10703
11145
  "operationType",
10704
11146
  "userAddress"
10705
- ]).doNothing()).execute().finally(() => this.permissionCache.invalidate(documentId));
11147
+ ]).doNothing()).execute().finally(() => this.#touched(documentId));
10706
11148
  return await this.db.selectFrom("OperationUserPermission").select([
10707
11149
  "documentId",
10708
11150
  "operationType",
@@ -10715,7 +11157,7 @@ var DocumentPermissionService = class {
10715
11157
  * Revoke a user's permission to execute an operation
10716
11158
  */
10717
11159
  async revokeOperationPermission(documentId, operationType, userAddress) {
10718
- await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).where("operationType", "=", operationType).where("userAddress", "=", userAddress.toLowerCase()).execute().finally(() => this.permissionCache.invalidate(documentId));
11160
+ await this.db.deleteFrom("OperationUserPermission").where("documentId", "=", documentId).where("operationType", "=", operationType).where("userAddress", "=", userAddress.toLowerCase()).execute().finally(() => this.#touched(documentId));
10719
11161
  }
10720
11162
  /**
10721
11163
  * Get all users with permission to execute an operation
@@ -10839,7 +11281,7 @@ var DocumentPermissionService = class {
10839
11281
  }).onConflict((oc) => oc.column("documentId").doUpdateSet({
10840
11282
  protected: isProtected,
10841
11283
  updatedAt: now
10842
- })).execute().finally(() => this.permissionCache.invalidate(documentId));
11284
+ })).execute().finally(() => this.#touched(documentId));
10843
11285
  }
10844
11286
  /**
10845
11287
  * Get the owner address for a document, or null if not set.
@@ -10862,7 +11304,7 @@ var DocumentPermissionService = class {
10862
11304
  }).onConflict((oc) => oc.column("documentId").doUpdateSet({
10863
11305
  ownerAddress: normalizedAddress,
10864
11306
  updatedAt: now
10865
- })).execute().finally(() => this.permissionCache.invalidate(documentId));
11307
+ })).execute().finally(() => this.#touched(documentId));
10866
11308
  }
10867
11309
  /**
10868
11310
  * Initialize protection for a newly created document.
@@ -10881,7 +11323,7 @@ var DocumentPermissionService = class {
10881
11323
  }).onConflict((oc) => oc.column("documentId").doUpdateSet({
10882
11324
  ownerAddress: normalizedAddress,
10883
11325
  updatedAt: now
10884
- })).execute().finally(() => this.permissionCache.invalidate(documentId));
11326
+ })).execute().finally(() => this.#touched(documentId));
10885
11327
  await this.grantPermission(documentId, normalizedAddress, "ADMIN", normalizedAddress);
10886
11328
  }
10887
11329
  /**
@@ -10921,51 +11363,59 @@ function createGetParentIdsFn(read) {
10921
11363
  }
10922
11364
  //#endregion
10923
11365
  //#region src/services/mcp-request-authorizer.ts
10924
- /**
10925
- * Authorization gate for the /mcp endpoint (AUTH_REVIEW S-C1). MCP tools have
10926
- * unrestricted reactor access, so access is limited to supreme admins when
10927
- * auth is enabled. OPEN policy is public; any other policy without an
10928
- * AuthService fails closed. The tools read as the caller: anonymous under OPEN,
10929
- * else the admin's address and the app key its token carries.
10930
- */
10931
- function createMcpRequestAuthorizer(authService, authorizationService) {
11366
+ /** The /mcp gate, as GraphQL's: a bad bearer is a 401, anonymous passes unless the
11367
+ * floor is on, and the tools answer to the caller's IAuthorizationService decisions. */
11368
+ function createMcpRequestAuthorizer(authService, authorizationService, options) {
10932
11369
  return async (req) => {
10933
- if (!authService) {
10934
- if (authorizationService.config.policy === AuthorizationPolicy.OPEN) return {
10935
- authorized: true,
10936
- subject: {}
10937
- };
10938
- return {
11370
+ let user;
11371
+ if (authService) {
11372
+ const context = await authService.verifyBearer(req.headers.authorization);
11373
+ if (context instanceof Response) return {
10939
11374
  authorized: false,
10940
- status: 401,
10941
- message: "Authentication required"
11375
+ status: context.status,
11376
+ message: "Authentication failed"
10942
11377
  };
11378
+ user = context.user;
10943
11379
  }
10944
- const context = await authService.verifyBearer(req.headers.authorization);
10945
- if (context instanceof Response) return {
10946
- authorized: false,
10947
- status: context.status,
10948
- message: "Authentication failed"
10949
- };
10950
- if (!context.user) return {
11380
+ if (!user && options.requireAuthenticatedCaller) return {
10951
11381
  authorized: false,
10952
11382
  status: 401,
10953
11383
  message: "Authentication required"
10954
11384
  };
10955
- if (!authorizationService.isSupremeAdmin(context.user.address)) return {
10956
- authorized: false,
10957
- status: 403,
10958
- message: "Forbidden: MCP access requires an administrator"
10959
- };
10960
11385
  return {
10961
11386
  authorized: true,
10962
- subject: {
10963
- address: context.user.address,
10964
- key: context.user.appKey
10965
- }
11387
+ subject: user ? {
11388
+ address: user.address,
11389
+ key: user.appKey
11390
+ } : {},
11391
+ access: hostAccess(authorizationService, options, user?.address)
10966
11392
  };
10967
11393
  };
10968
11394
  }
11395
+ function hostAccess(authorization, options, address) {
11396
+ const { resolveDocumentId, documentPermissionService } = options;
11397
+ const decide = async (identifier, check) => {
11398
+ let id;
11399
+ try {
11400
+ id = await resolveDocumentId(identifier);
11401
+ } catch {
11402
+ return false;
11403
+ }
11404
+ return check(id);
11405
+ };
11406
+ return {
11407
+ unrestricted: authorization.isSupremeAdmin(address),
11408
+ authenticated: address !== void 0,
11409
+ canRead: (identifier) => decide(identifier, (id) => authorization.canRead(id, address)),
11410
+ canWrite: (identifier) => decide(identifier, (id) => authorization.canWrite(id, address)),
11411
+ canMutate: (identifier, operationType) => decide(identifier, (id) => authorization.canMutate(id, operationType, address)),
11412
+ canCreate: () => authorization.canCreate(address),
11413
+ created: async (documentId) => {
11414
+ if (!address) return;
11415
+ await documentPermissionService?.initializeDocumentProtection(documentId, address, authorization.config.defaultProtection);
11416
+ }
11417
+ };
11418
+ }
10969
11419
  //#endregion
10970
11420
  //#region src/services/sync-serving-gate.ts
10971
11421
  /**
@@ -11286,7 +11736,7 @@ function makeDbClosers(knexInstance, pglite, logger) {
11286
11736
  /**
11287
11737
  * Sets up the subgraph manager and registers subgraphs
11288
11738
  */
11289
- async function setupGraphQLManager({ settings, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, clients, relationalDb, analyticsStore, syncManager, subgraphs, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, driveNodes, syncServingGate, httpRoutes, attachments, inspection, driveStore, reportError }) {
11739
+ async function setupGraphQLManager({ settings, httpAdapter, authFetchMiddleware, requireAuthFetchMiddleware, httpServer, wsServer, clients, relationalDb, analyticsStore, syncManager, subgraphs, scalars, logger, authorizationService, authService, documentPermissionService, enableDocumentModelSubgraphs, port, reactorDriveClient, driveNodes, syncServingGate, readableDocuments, httpRoutes, attachments, inspection, driveStore, reportError }) {
11290
11740
  const graphqlManager = new GraphQLManager({
11291
11741
  wsCredentialRecheckIntervalMs: settings.wsCredentialRecheckIntervalMs,
11292
11742
  path: settings.basePath,
@@ -11309,13 +11759,14 @@ async function setupGraphQLManager({ settings, httpAdapter, authFetchMiddleware,
11309
11759
  reactorDriveClient,
11310
11760
  driveNodes,
11311
11761
  syncServingGate,
11762
+ readableDocuments,
11312
11763
  httpRoutes,
11313
11764
  attachments,
11314
11765
  inspection,
11315
11766
  driveStore,
11316
11767
  reportError
11317
11768
  });
11318
- await graphqlManager.init(subgraphs.core, authFetchMiddleware, requireAuthFetchMiddleware);
11769
+ await graphqlManager.init(subgraphs.core, authFetchMiddleware, requireAuthFetchMiddleware, scalars);
11319
11770
  await graphqlManager.applyPackageSubgraphs(subgraphs.extended);
11320
11771
  await graphqlManager.updateRouter();
11321
11772
  return graphqlManager;
@@ -11579,6 +12030,16 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11579
12030
  listenPort.current = boundPort;
11580
12031
  const authorizationService = createAuthorizationService(authorizationConfig, documentPermissionService, createGetParentIdsFn(clients.read));
11581
12032
  logger.info(`Authorization service initialized (policy: ${authorizationConfig.policy})`);
12033
+ const readableDocuments = new ReadableDocumentsProjection({
12034
+ relationalDb,
12035
+ read: clients.read,
12036
+ permissions: documentPermissionService,
12037
+ config: authorizationConfig,
12038
+ logger: logger.child(["readable-documents"])
12039
+ });
12040
+ readableDocuments.start().catch((error) => {
12041
+ logger.error("The readable-documents read model could not start; index subgraphs serve only admins until it does: @error", error);
12042
+ });
11582
12043
  assertAttachmentPolicyReadsAllowed(attachmentReadsFollowDocumentPolicy, syncServingGate !== void 0);
11583
12044
  const floor = requireAuthFetchMiddleware !== void 0;
11584
12045
  const attachmentAccess = new AttachmentAccessService(createCanonicalDocumentIdResolver({ read: clients.read }), authorizationService, attachmentReferenceIndex.store, attachmentReferenceProjection, clients.read, attachmentReadsFollowDocumentPolicy ? syncServingGate : void 0, {
@@ -11607,6 +12068,7 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11607
12068
  extended: subgraphs,
11608
12069
  core: coreSubgraphs
11609
12070
  },
12071
+ scalars: packages.getScalarRegistry(),
11610
12072
  logger: logger.child(["graphql-manager"]),
11611
12073
  authorizationService,
11612
12074
  authService,
@@ -11616,6 +12078,7 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11616
12078
  reactorDriveClient,
11617
12079
  driveNodes,
11618
12080
  syncServingGate,
12081
+ readableDocuments,
11619
12082
  httpRoutes,
11620
12083
  attachments: attachmentClientProvider,
11621
12084
  inspection,
@@ -11630,10 +12093,15 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11630
12093
  await setupMcpServer({
11631
12094
  client: clients.client,
11632
12095
  syncManager,
11633
- authorizeRequest: createMcpRequestAuthorizer(authService, authorizationService)
12096
+ authorizeRequest: createMcpRequestAuthorizer(authService, authorizationService, {
12097
+ requireAuthenticatedCaller: floor,
12098
+ resolveDocumentId: createCanonicalDocumentIdResolver({ read: clients.read }),
12099
+ documentPermissionService
12100
+ })
11634
12101
  }, httpAdapter);
11635
12102
  logger.info(`MCP server available at http://localhost:${boundPort}/mcp`);
11636
12103
  }
12104
+ dbClosers.unshift(() => readableDocuments.stop());
11637
12105
  const dispose = buildApiDispose({
11638
12106
  graphqlManager,
11639
12107
  httpRoutes,
@@ -11657,6 +12125,7 @@ async function _setupAPI(clients, syncManager, reactorProcessorManager, httpAdap
11657
12125
  requireAuthenticatedCaller: floor,
11658
12126
  authorizationService,
11659
12127
  relationalDb,
12128
+ readableDocuments,
11660
12129
  inspection,
11661
12130
  dispose
11662
12131
  };
@@ -11941,7 +12410,7 @@ var PackageManagementService = class {
11941
12410
  }
11942
12411
  };
11943
12412
  //#endregion
11944
- export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, ConsistencyCoordinateInputSchema, ConsistencyTokenInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DEFAULT_PERMISSION_CACHE_OPTIONS, DEFAULT_PERMISSION_CACHE_TTL_MS, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentPermissionSnapshot, DocumentRelationshipFieldsFragmentDoc, DriveNodeFieldsFragmentDoc, DriveNodeKind, DriveNodeKindSchema, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetCreateProtocolVersionsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetDriveDescendantsDocument, GetDriveNodeDocument, GetDriveNodesDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionAdminSubgraph, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, NodeEventLoopDelay, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PermissionCache, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, RequestLoadRecorder, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionAdminTypeDefs, inspectionTypeDefs, isCountedRequest, isDefinedNonNullAny, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, reactorApiConfigFromEnv, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolvePermissionCacheTtlMs, resolveRenownConfig, runDetached, typeDefinitionNames, verifyWebhook };
12413
+ export { ADMIN_USERS, ActionCandidateInputSchema, ActionContextInputSchema, ActionInputSchema, AddRelationshipDocument, AnalyticsSubgraph, AttachmentAccessFailed, AttachmentAccessService, AttachmentAccessUnavailable, AttachmentClientProvider, AuthDecision, AuthDecisionSchema, AuthEvaluationUnsupportedError, AuthService, AuthSubgraph, AuthenticationRequiredError, AuthorizationPolicy, AuthorizedAttachmentService, AuthorizedDocumentHandle, BaseSubgraph, CORE_PACKAGE_NAME, CanonicalDocumentIdResolutionError, ChannelMetaInputSchema, ConsistencyCoordinateInputSchema, ConsistencyTokenInputSchema, CreateDocumentDocument, CreateEmptyDocumentDocument, DEFAULT_INSPECTION_THROTTLE, DEFAULT_PERMISSION_CACHE_OPTIONS, DEFAULT_PERMISSION_CACHE_TTL_MS, DEFAULT_ROOT_TYPES, DeleteDocumentDocument, DeleteDocumentsDocument, DocumentChangeType, DocumentChangeTypeSchema, DocumentChangesDocument, DocumentModelSchemaCache, DocumentOperationsFilterInputSchema, DocumentPermissionService, DocumentPermissionSnapshot, DocumentRelationshipFieldsFragmentDoc, DriveNodeFieldsFragmentDoc, DriveNodeKind, DriveNodeKindSchema, EVERYONE, EvaluateActionsDocument, ExecuteBatchDocument, ExecutionJobInputSchema, FindDocumentsDocument, ForbiddenError, GetCreateDefaultsDocument, GetCreateProtocolVersionsDocument, GetDocumentDocument, GetDocumentIncomingRelationshipEdgesDocument, GetDocumentIncomingRelationshipsDocument, GetDocumentModelsDocument, GetDocumentOperationsDocument, GetDocumentOutgoingRelationshipEdgesDocument, GetDocumentOutgoingRelationshipsDocument, GetDocumentServedDocument, GetDocumentWithOperationsDocument, GetDriveDescendantsDocument, GetDriveNodeDocument, GetDriveNodesDocument, GetJobStatusDocument, GraphQLManager, HttpDocumentModelLoader, HttpPackageLoader, HttpRouteService, ImportPackageLoader, InMemoryPackageStorage, InspectionAdminSubgraph, InspectionSubgraph, InspectionThrottle, InspectionThrottledError, InvalidNamespaceError, JobChangesDocument, JobInfoFieldsFragmentDoc, MalformedStoredOperationError, MemoryWebhookStore, MoveRelationshipDocument, MutateDocumentAsyncDocument, MutateDocumentDocument, NodeEventLoopDelay, OperationContextInputSchema, OperationInputSchema, OperationWithContextInputSchema, OperationsFilterInputSchema, PACKAGE_ROUTE_SEGMENT, PGLITE_UTC_PARSERS, PackageManagementService, PackageManager, PackagesSubgraph, PagingInputSchema, PermissionCache, PhDocumentFieldsFragmentDoc, PollSyncEnvelopesDocument, PrivacyPermissionAdapter, PropagationMode, PropagationModeSchema, PushSyncEnvelopesDocument, READABLE_DOCUMENTS_NAMESPACE, ReactorSignerAppInputSchema, ReactorSignerInputSchema, ReactorSignerUserInputSchema, ReactorSubgraph, ReadableDocumentsProjection, RefusalNotRecordedError, RelationalWebhookStore, RemoteCursorInputSchema, RemoteFilterInputSchema, RemoveRelationshipDocument, RenameDocumentDocument, RequestLoadRecorder, SearchFilterInputSchema, SetPreferredEditorDocument, SubgraphTypeCollisionError, SyncEnvelopeInputSchema, SyncEnvelopeType, SyncEnvelopeTypeSchema, SyncRefusalInputSchema, SystemSubgraph, TouchChannelDocument, TouchChannelInputSchema, UpdateRelationshipDocument, ViewFilterInputSchema, WEBHOOK_SEGMENT, WS_AUTH_CLOSE_REASONS, WS_CLOSE_REASON_AUTHENTICATION_REQUIRED, WS_CLOSE_REASON_BEARER_REJECTED, WS_CLOSE_REASON_CREDENTIAL_REVOKED, WebhookService, applyReadableFilter, assembleSubgraphTypeDefs, assertAttachmentPolicyReadsAllowed, assertAuthRequiredForDocumentPermissions, assertCredentialVerifierForSource, assertHostMountPath, assertIndexAccessComplete, assertRequireAuthenticatedCallerAllowed, assertSkipCredentialVerificationAllowed, baseDocumentModels, buildDocumentModelSchema, buildGraphQlDocument, buildGraphQlDriveDocument, buildGraphqlOperation, buildGraphqlOperations, buildSubgraphSchemaModule, callerSubject, createAuthFetchMiddleware, createCanonicalDocumentIdResolver, createCredentialInvalidator, createGatewayAdapter, createHttpAdapter, createInspectionResolvers, createMergedSchema, createReactorGraphQLClient, createReactorInspectionSource, createRenownCredentialVerifier, createSchema, createWsAuthHandlers, decodeExplorerUrlState, defineIndexSubgraph, definedNonNullAnySchema, documentModelSubgraphTypes, driveIdFromUrl, extractSubgraphs, extractSubgraphsFromModule, findSubgraphTypeCollisions, generateDocumentModelSchema, generatedTypesOf, getAuthContext, getDbClient, getDocumentModelSchemaName, getDocumentModelSubgraphName, getDocumentModelTypeDefs, getExplorerPrefix, getGeneratedDocumentModelTypes, getGitHash, getGitUrl, getSdk, getUniqueDocumentModels, getUniqueUpgradeManifests, getVersion, hasOperationSchemas, initAnalyticsStoreSql, initializeAndStartAPI, inspectionAdminTypeDefs, inspectionTypeDefs, isCountedRequest, isDefinedNonNullAny, isDocumentListed, isExpectedLoaderMiss, isListedAdmin, isPostgresConnectionString, isSubgraphClass, namespacePath, namespaceSegments, newWebhookToken, parseDriveUrl, parseWebhookBody, piecesBaseUrl, reactorApiConfigFromEnv, readableDocumentsSubquery, redactHeaders, renderGraphqlPlayground, reportFailure, reservedTypeNames, reservedTypeNamesTaken, resolveCredentialCacheTtlMs, resolvePackageName, resolvePermissionCacheTtlMs, resolveRenownConfig, runDetached, setAuthContext, typeDefinitionNames, verifyWebhook };
11945
12414
 
11946
12415
  //# sourceMappingURL=index.mjs.map
11947
- //# debugId=ef156955-2531-5a13-8ece-12e68bf6d841
12416
+ //# debugId=31a04f4e-9c99-5095-b7d0-1c70af59a2fc