@powerhousedao/reactor-api 6.2.3-dev.8 → 6.2.3-dev.81
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.
- package/README.md +7 -2
- package/dist/{adapter-gateway-apollo-CxJNBVyD.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +23 -23
- package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
- package/dist/{adapter-gateway-mercurius-CZVy88Za.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +4 -12
- package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
- package/dist/{adapter-http-express-B39rPhqH.mjs → adapter-http-express-P0t-mdMV.mjs} +10 -10
- package/dist/adapter-http-express-P0t-mdMV.mjs.map +1 -0
- package/dist/{adapter-http-fastify-BwXO6rqE.mjs → adapter-http-fastify-D0OP5q9K.mjs} +13 -12
- package/dist/adapter-http-fastify-D0OP5q9K.mjs.map +1 -0
- package/dist/base-document-models-D-cmBBYJ.mjs +1583 -0
- package/dist/base-document-models-D-cmBBYJ.mjs.map +1 -0
- package/dist/create-schema-Dio_7akA.d.mts +159 -0
- package/dist/create-schema-Dio_7akA.d.mts.map +1 -0
- package/dist/error-info-BaEL50f5.mjs +486 -0
- package/dist/error-info-BaEL50f5.mjs.map +1 -0
- package/dist/index.d.mts +3083 -980
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +6849 -2736
- package/dist/index.mjs.map +1 -1
- package/dist/package-subgraph-check-C0PD_Tj9.mjs +138 -0
- package/dist/package-subgraph-check-C0PD_Tj9.mjs.map +1 -0
- package/dist/pglite-like-CKQEL_Q0.d.mts +27 -0
- package/dist/pglite-like-CKQEL_Q0.d.mts.map +1 -0
- package/dist/pglite-node-DGms6Ssa.mjs +715 -0
- package/dist/pglite-node-DGms6Ssa.mjs.map +1 -0
- package/dist/rolldown-runtime-8H4AJuhK.mjs +16 -0
- package/dist/run-node-handler-CQjyjOuN.mjs +52 -0
- package/dist/run-node-handler-CQjyjOuN.mjs.map +1 -0
- package/dist/src/graphql/subgraph-types.d.mts +43 -0
- package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
- package/dist/src/graphql/subgraph-types.mjs +14 -0
- package/dist/src/graphql/subgraph-types.mjs.map +1 -0
- package/dist/src/packages/https-hooks.d.mts +4 -4
- package/dist/src/packages/https-hooks.d.mts.map +1 -1
- package/dist/src/packages/https-hooks.mjs +2 -2
- package/dist/src/packages/https-hooks.mjs.map +1 -1
- package/dist/src/packages/vite-loader.d.mts +30 -9
- package/dist/src/packages/vite-loader.d.mts.map +1 -1
- package/dist/src/packages/vite-loader.mjs +198 -85
- package/dist/src/packages/vite-loader.mjs.map +1 -1
- package/dist/src/pglite/pglite-node.d.mts +393 -0
- package/dist/src/pglite/pglite-node.d.mts.map +1 -0
- package/dist/src/pglite/pglite-node.mjs +5 -0
- package/dist/src/pglite/worker/entry.d.mts +2 -0
- package/dist/src/pglite/worker/entry.mjs +251 -0
- package/dist/src/pglite/worker/entry.mjs.map +1 -0
- package/dist/subgraph-extraction-BA9WKjn1.mjs +1877 -0
- package/dist/subgraph-extraction-BA9WKjn1.mjs.map +1 -0
- package/dist/subgraph-schema-owner-BEjuk2Xv.mjs +10 -0
- package/dist/subgraph-schema-owner-BEjuk2Xv.mjs.map +1 -0
- package/dist/types-PXB1ctpi.d.mts +99 -0
- package/dist/types-PXB1ctpi.d.mts.map +1 -0
- package/package.json +30 -21
- package/dist/adapter-gateway-apollo-CxJNBVyD.mjs.map +0 -1
- package/dist/adapter-gateway-apollo-DowrX6E_.mjs +0 -4
- package/dist/adapter-gateway-mercurius-CZVy88Za.mjs.map +0 -1
- package/dist/adapter-gateway-stitching-CaZjvRzx.mjs +0 -316
- package/dist/adapter-gateway-stitching-CaZjvRzx.mjs.map +0 -1
- package/dist/adapter-http-express-B39rPhqH.mjs.map +0 -1
- package/dist/adapter-http-fastify-BwXO6rqE.mjs.map +0 -1
- package/dist/path-normalize-BOQwY9wR.mjs +0 -23
- package/dist/path-normalize-BOQwY9wR.mjs.map +0 -1
- package/dist/types-DcYyNcHJ.d.mts +0 -48
- package/dist/types-DcYyNcHJ.d.mts.map +0 -1
- package/dist/utils-XWVecaNn.mjs +0 -653
- package/dist/utils-XWVecaNn.mjs.map +0 -1
- package/dist/websocket-DncAB9XK.mjs +0 -18
- package/dist/websocket-DncAB9XK.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"base-document-models-D-cmBBYJ.mjs","sources":["../src/graphql/auth/schema.graphql","../src/utils/scalar-types.ts","../src/utils/create-schema.ts","../src/graphql/subgraph-type-ownership.ts","../src/graphql/subgraph-admission.ts","../src/graphql/inspection/admin-schema.ts","../src/graphql/inspection/schema.ts","../src/graphql/reactor/schema.graphql","../src/graphql/system/schema.ts","../src/packages/base-document-models.ts"],"sourcesContent":["\"# Auth Subgraph Schema\\n# Contains all document permission and authorization related types\\n\\nscalar DateTime\\n\\n# Permission levels for documents\\nenum DocumentPermissionLevel {\\n # Can fetch and read the document\\n READ\\n # Can push updates and modify the document\\n WRITE\\n # Can manage document permissions and settings\\n ADMIN\\n}\\n\\n# Document permission entry\\ntype DocumentPermissionEntry {\\n documentId: String!\\n userAddress: String!\\n permission: DocumentPermissionLevel!\\n grantedBy: String!\\n createdAt: DateTime!\\n updatedAt: DateTime!\\n}\\n\\n# Operation user permission entry\\ntype OperationUserPermission {\\n documentId: String!\\n operationType: String!\\n userAddress: String!\\n grantedBy: String!\\n createdAt: DateTime!\\n}\\n\\n# Combined document access info\\ntype DocumentAccessInfo {\\n documentId: String!\\n permissions: [DocumentPermissionEntry!]!\\n}\\n\\n# Operation permissions info\\ntype OperationPermissionsInfo {\\n documentId: String!\\n operationType: String!\\n userPermissions: [OperationUserPermission!]!\\n}\\n\\n# Document protection info\\ntype DocumentProtectionInfo {\\n documentId: String!\\n protected: Boolean!\\n ownerAddress: String\\n}\\n\\ntype Query {\\n # Get permissions for a document (requires ADMIN permission or global admin)\\n documentAccess(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n ): DocumentAccessInfo!\\n\\n # Get protection status for a document (requires ADMIN permission or global admin)\\n documentProtection(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n ): DocumentProtectionInfo!\\n\\n # Get all documents the current user has explicit access to\\n userDocumentPermissions: [DocumentPermissionEntry!]!\\n\\n # Get operation permissions for a document and operation type\\n # (requires ADMIN permission or global admin)\\n operationPermissions(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n operationType: String!\\n ): OperationPermissionsInfo!\\n\\n # Check if the current user can execute a specific operation on a document\\n canExecuteOperation(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n operationType: String!\\n ): Boolean!\\n}\\n\\ntype Mutation {\\n # Set document protection status (requires ADMIN permission or global admin)\\n setDocumentProtection(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n protected: Boolean!\\n ): DocumentProtectionInfo!\\n\\n # Transfer document ownership (requires ADMIN permission or global admin)\\n transferDocumentOwnership(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n newOwnerAddress: String!\\n ): DocumentProtectionInfo!\\n\\n # Grant a user permission on a document (requires ADMIN permission or global admin)\\n grantDocumentPermission(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n userAddress: String!\\n permission: DocumentPermissionLevel!\\n ): DocumentPermissionEntry!\\n\\n # Revoke a user's permission on a document (requires ADMIN permission or global admin)\\n revokeDocumentPermission(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n userAddress: String!\\n ): Boolean!\\n\\n # --- Operation Permissions ---\\n\\n # Grant a user permission to execute an operation on a document\\n grantOperationPermission(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n operationType: String!\\n userAddress: String!\\n ): OperationUserPermission!\\n\\n # Revoke a user's permission to execute an operation\\n revokeOperationPermission(\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n operationType: String!\\n userAddress: String!\\n ): Boolean!\\n}\\n\"","import { scalarCatalog, type ScalarDefinition } from \"document-model/scalars\";\nimport {\n GraphQLScalarType,\n type ValueNode,\n valueFromASTUntyped,\n visit,\n} from \"graphql\";\nimport { GraphQLJSON, GraphQLJSONObject } from \"graphql-type-json\";\nimport { inspect, isDeepStrictEqual } from \"node:util\";\nimport { z } from \"zod\";\n\nexport type RegisteredScalar = {\n readonly definition: ScalarDefinition;\n readonly packageName: string;\n};\n\n/** The scalars packages register through their `./scalars` entry, by name. */\nexport type ScalarRegistry = ReadonlyMap<string, RegisteredScalar>;\n\nexport const EMPTY_SCALAR_REGISTRY: ScalarRegistry = new Map();\n\nexport function sameScalarRegistry(a: ScalarRegistry, b: ScalarRegistry) {\n if (a.size !== b.size) return false;\n for (const [name, scalar] of a) {\n const other = b.get(name);\n if (\n other?.definition !== scalar.definition ||\n other.packageName !== scalar.packageName\n ) {\n return false;\n }\n }\n return true;\n}\n\nexport const catalogScalarSdl = scalarCatalog\n .map(({ name }) => `scalar ${name}`)\n .join(\"\\n\");\n\nexport const catalogResolvers = Object.fromEntries(\n scalarCatalog.map(({ name }) => [\n name,\n new GraphQLScalarType({\n serialize: (value) => value,\n parseValue: (value) => value,\n parseLiteral: valueFromASTUntyped,\n ...(name === \"JSONObject\"\n ? GraphQLJSONObject.toConfig()\n : name === \"Unknown\"\n ? GraphQLJSON.toConfig()\n : {}),\n name,\n }),\n ]),\n);\n\nfunction hasVariable(ast: ValueNode): boolean {\n let found = false;\n visit(ast, {\n Variable() {\n found = true;\n },\n });\n return found;\n}\n\nfunction losslessJson(value: unknown): { readonly json: unknown } | undefined {\n try {\n const json: unknown = JSON.parse(JSON.stringify(value));\n return isDeepStrictEqual(json, value) ? { json } : undefined;\n } catch {\n return undefined;\n }\n}\n\nfunction show(value: unknown): string {\n try {\n return losslessJson(value)\n ? JSON.stringify(value)\n : inspect(value, { customInspect: false, breakLength: Infinity });\n } catch {\n return \"a value that cannot be printed\";\n }\n}\n\n/** Validates with the definition's schema and accepts only a canonical value. */\nexport function registeredScalarType(\n definition: ScalarDefinition,\n): GraphQLScalarType {\n const check = (value: unknown): unknown => {\n const result = definition.schema.safeParse(value);\n if (!result.success) {\n // Not a GraphQLError: graphql-js wraps a plain error with the type, the\n // value and its location, and would wrap one from another graphql copy\n // anyway, so the message is the same whichever copy validates.\n throw new Error(`${definition.name}: ${z.prettifyError(result.error)}`);\n }\n const output = losslessJson(result.data);\n if (!output) {\n throw new Error(\n `${definition.name}: the schema output is not JSON: ${show(result.data)}`,\n );\n }\n const reparsed = definition.schema.safeParse(output.json);\n if (reparsed.success && isDeepStrictEqual(reparsed.data, result.data)) {\n return result.data;\n }\n const outcome = reparsed.success\n ? `parses to ${show(reparsed.data)}.`\n : `fails it: ${z.prettifyError(reparsed.error)}`;\n throw new Error(\n `${definition.name}: the schema must accept its own output unchanged, but ${show(result.data)} ${outcome}`,\n );\n };\n return new GraphQLScalarType({\n name: definition.name,\n description: definition.description,\n serialize: (value) => value,\n parseValue: check,\n parseLiteral: (ast, variables) => {\n // Validation reads a literal before variables exist; one that nests a\n // variable is checked at execution, when they do.\n if (variables == null && hasVariable(ast)) return null;\n return check(valueFromASTUntyped(ast, variables));\n },\n });\n}\n","import {\n buildSubgraphSchema,\n type GraphQLResolverMap,\n type GraphQLSchemaModule,\n} from \"@apollo/subgraph\";\nimport type { Context } from \"@powerhousedao/reactor-api\";\nimport type {\n DocumentModelGlobalState,\n DocumentModelModule,\n} from \"@powerhousedao/shared/document-model\";\nimport { camelCase, kebabCase, pascalCase } from \"change-case\";\nimport { childLogger } from \"document-model\";\nimport {\n type ASTNode,\n type DefinitionNode,\n type DocumentNode,\n Kind,\n Lexer,\n type NameNode,\n parse,\n print,\n Source,\n TokenKind,\n visit,\n} from \"graphql\";\nimport { gql } from \"graphql-tag\";\nimport { createHash } from \"node:crypto\";\nimport {\n catalogResolvers,\n catalogScalarSdl,\n EMPTY_SCALAR_REGISTRY,\n registeredScalarType,\n type ScalarRegistry,\n} from \"./scalar-types.js\";\n\nconst logger = childLogger([\"reactor-api\", \"create-schema\"]);\n\n/**\n * Revision type - matches the definition in reactor/schema.graphql.\n * Used by PHDocument and document mutation results.\n */\nconst RevisionType = `\n type Revision {\n scope: String!\n revision: Int!\n }\n`;\n\n/**\n * A subgraph defines a type whose name the generated document-model schema\n * owns, so one of the two definitions would be lost.\n */\nexport class SubgraphTypeCollisionError extends Error {\n readonly typeNames: string[];\n\n constructor(typeNames: string[]) {\n super(\n `Subgraph defines types reserved by the document-model schema: ${typeNames.join(\", \")}`,\n );\n this.name = \"SubgraphTypeCollisionError\";\n this.typeNames = typeNames;\n }\n}\n\n/**\n * Type-system definition kinds that GraphQL requires to be uniquely named.\n * A subgraph SDL with two definitions sharing a name fails federation\n * composition (\"There can be only one type named X\"), which is fatal to the\n * whole gateway. We dedupe these by name; field/operation/extension nodes are\n * left untouched.\n */\nconst TYPE_DEFINITION_KINDS = new Set<Kind>([\n Kind.OBJECT_TYPE_DEFINITION,\n Kind.ENUM_TYPE_DEFINITION,\n Kind.INPUT_OBJECT_TYPE_DEFINITION,\n Kind.INTERFACE_TYPE_DEFINITION,\n Kind.UNION_TYPE_DEFINITION,\n Kind.SCALAR_TYPE_DEFINITION,\n]);\n\n/**\n * Drop duplicate type-system definitions by name, keeping the first occurrence.\n * Deduping is by name across ALL kinds (a `type` and an `enum` sharing a name\n * collide in GraphQL too), so the first definition of a given name wins\n * regardless of kind. State types are emitted before operation types, so\n * keep-first preserves the authoritative state definition. This heals a document\n * model that defines the same name twice (global+local, state+operation, or\n * twice in one scope) so the assembled subgraph SDL composes instead of crashing\n * the gateway (Sentry #917).\n */\nconst dedupeTypeDefinitions = (\n definitions: readonly DefinitionNode[],\n seen = new Set<string>(),\n): DefinitionNode[] =>\n definitions.filter((def) => {\n const name = typeDefinitionName(def);\n if (name === undefined) return true;\n if (seen.has(name)) {\n // A duplicate here would otherwise crash supergraph composition; log it so\n // production has a breadcrumb of which model shipped a duplicate name.\n logger.debug(`Dropping duplicate type definition: ${name}`);\n return false;\n }\n seen.add(name);\n return true;\n });\n\nfunction typeDefinitionName(def: DefinitionNode): string | undefined {\n if (!TYPE_DEFINITION_KINDS.has(def.kind)) return undefined;\n return (def as { name?: { value: string } }).name?.value;\n}\n\nconst EMPTY_DOCUMENT: DocumentNode = { kind: Kind.DOCUMENT, definitions: [] };\n\nconst OUTPUT_TYPE_KINDS = [\n Kind.OBJECT_TYPE_DEFINITION,\n Kind.OBJECT_TYPE_EXTENSION,\n Kind.ENUM_TYPE_DEFINITION,\n Kind.ENUM_TYPE_EXTENSION,\n Kind.UNION_TYPE_DEFINITION,\n Kind.UNION_TYPE_EXTENSION,\n Kind.INTERFACE_TYPE_DEFINITION,\n Kind.INTERFACE_TYPE_EXTENSION,\n];\n\n// Kinds whose names get prefixed: state schemas (inputs stripped) and operation schemas.\nconst STATE_PREFIX_KINDS = new Set<Kind>(OUTPUT_TYPE_KINDS);\nconst ALL_PREFIX_KINDS = new Set<Kind>([\n ...OUTPUT_TYPE_KINDS,\n Kind.INPUT_OBJECT_TYPE_DEFINITION,\n Kind.INPUT_OBJECT_TYPE_EXTENSION,\n]);\n\n// Nodes whose `name` is a type name: definitions, extensions and references.\nconst TYPE_NAME_KINDS = new Set<Kind>([\n ...ALL_PREFIX_KINDS,\n Kind.SCALAR_TYPE_DEFINITION,\n Kind.SCALAR_TYPE_EXTENSION,\n Kind.NAMED_TYPE,\n]);\n\n// Stub local state types dropped from legacy models.\nconst LOCAL_STATE_STUBS = new Set([\n \"AccountSnapshotLocalState\",\n \"BudgetStatementLocalState\",\n \"ScopeFrameworkLocalState\",\n]);\n\n/** Parse SDL; blank or comment-only input yields an empty document. */\nfunction parseSdl(sdl: string): DocumentNode {\n const source = new Source(sdl);\n if (new Lexer(source).advance().kind === TokenKind.EOF) return EMPTY_DOCUMENT;\n try {\n return parse(source, { noLocation: true });\n } catch (error) {\n // Retry without stray semicolons, which GraphQL rejects.\n const withoutSemicolons = sdl.replaceAll(\";\", \"\");\n if (withoutSemicolons === sdl) throw error;\n return parse(withoutSemicolons, { noLocation: true });\n }\n}\n\nfunction definedTypeNames(\n doc: DocumentNode,\n kinds: ReadonlySet<Kind>,\n): string[] {\n return doc.definitions\n .filter((def) => kinds.has(def.kind))\n .map((def) => (def as DefinitionNode & { name: NameNode }).name.value);\n}\n\n/** Prefix type definition names and type references found in `names`. */\nfunction prefixTypeNames(\n doc: DocumentNode,\n prefix: string,\n names: ReadonlySet<string>,\n): DocumentNode {\n return visit(doc, {\n enter(node: ASTNode) {\n if (!TYPE_NAME_KINDS.has(node.kind)) return undefined;\n const { name } = node as ASTNode & { name: NameNode };\n if (!names.has(name.value)) return undefined;\n return { ...node, name: { ...name, value: `${prefix}_${name.value}` } };\n },\n });\n}\n\n/** State schema definitions without inputs, `DateTime` or the given object types. */\nfunction stateTypeDefinitions(\n sdl: string,\n droppedObjectTypes: ReadonlySet<string> = new Set(),\n): DefinitionNode[] {\n return parseSdl(sdl).definitions.filter(\n (def) =>\n def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION &&\n def.kind !== Kind.INPUT_OBJECT_TYPE_EXTENSION &&\n !(\n def.kind === Kind.SCALAR_TYPE_DEFINITION &&\n def.name.value === \"DateTime\"\n ) &&\n !(\n def.kind === Kind.OBJECT_TYPE_DEFINITION &&\n droppedObjectTypes.has(def.name.value)\n ),\n );\n}\n\n/**\n * Prefixed operation schemas per module. The first definition of each module\n * carries a \"Module: <Name>\" description unless it has its own.\n */\nfunction buildModuleSchemas(\n specification: DocumentModelGlobalState[\"specifications\"][0] | undefined,\n documentName: string,\n allTypeNames: string[],\n hasValidSchema: (schema: string | null | undefined) => boolean,\n): string {\n const names = new Set(allTypeNames);\n return (\n specification?.modules\n .map((module) => {\n const definitions = module.operations\n .filter((op) => hasValidSchema(op.schema))\n .flatMap((op) => {\n const doc = parseSdl(op.schema ?? \"\");\n const opNames = new Set([\n ...names,\n ...definedTypeNames(doc, ALL_PREFIX_KINDS),\n ]);\n return prefixTypeNames(doc, documentName, opNames).definitions;\n });\n if (definitions.length === 0) return \"\";\n const [first, ...rest] = definitions;\n const header =\n \"description\" in first && !first.description\n ? {\n ...first,\n description: {\n kind: Kind.STRING,\n value: `Module: ${pascalCase(module.name)}`,\n block: true,\n },\n }\n : first;\n return print({\n kind: Kind.DOCUMENT,\n definitions: [header as DefinitionNode, ...rest],\n });\n })\n .filter(Boolean)\n .join(\"\\n\") ?? \"\"\n );\n}\n\nexport type SubgraphSchemaOptions = {\n /**\n * Types the subgraph's own schema generator emits, as a document model's\n * subgraph has. These may repeat a generated definition, which is kept.\n */\n ownTypeNames?: ReadonlySet<string>;\n} & (\n | {\n /** Generated types already built for `documentModels`, with their scalars. */\n generated?: GeneratedDocumentModelTypes;\n scalars?: never;\n }\n | { generated?: never; scalars?: ScalarRegistry }\n);\n\nexport const buildSubgraphSchemaModule = (\n documentModels: DocumentModelModule[],\n resolvers: GraphQLResolverMap<Context>,\n typeDefs: DocumentNode,\n options: SubgraphSchemaOptions = {},\n): GraphQLSchemaModule => {\n const generated =\n options.generated ??\n getGeneratedDocumentModelTypes(documentModels, undefined, options.scalars);\n const newResolvers = {\n ...catalogResolvers,\n ...Object.fromEntries(\n Array.from(generated.scalars, ([name, { definition }]) => [\n name,\n registeredScalarType(definition),\n ]),\n ),\n ...resolvers,\n JSONObject: catalogResolvers.JSONObject,\n Unknown: catalogResolvers.Unknown,\n };\n\n return {\n typeDefs: assembleSubgraphTypeDefs(\n generated,\n typeDefs,\n options.ownTypeNames,\n ),\n resolvers: newResolvers,\n };\n};\nexport const createSchema = (\n documentModels: DocumentModelModule[],\n resolvers: GraphQLResolverMap<Context>,\n typeDefs: DocumentNode,\n options: SubgraphSchemaOptions = {},\n) => {\n // Array form: @apollo/subgraph 2.15 dropped the bare-module overload.\n return buildSubgraphSchema([\n buildSubgraphSchemaModule(documentModels, resolvers, typeDefs, options),\n ]);\n};\n\n/**\n * Create a merged GraphQL schema from multiple subgraph modules.\n * Uses buildSubgraphSchema's array overload to combine type definitions\n * and resolvers from multiple subgraphs into a single executable schema.\n */\nexport const createMergedSchema = (modules: GraphQLSchemaModule[]) => {\n return buildSubgraphSchema(modules);\n};\n\nexport function getDocumentModelSchemaName(\n documentModel: DocumentModelGlobalState,\n) {\n return pascalCase(documentModel.name.replaceAll(\"/\", \" \"));\n}\n\n/** The name the model's own subgraph registers under. */\nexport function getDocumentModelSubgraphName(\n documentModel: DocumentModelGlobalState,\n): string {\n return kebabCase(documentModel.name);\n}\n\n/**\n * The generated document-model types followed by the subgraph's own. Throws\n * {@link SubgraphTypeCollisionError} when the subgraph defines a generated\n * name not in `ownTypeNames`.\n */\nexport const getDocumentModelTypeDefs = (\n documentModels: DocumentModelModule[],\n typeDefs: DocumentNode,\n ownTypeNames?: ReadonlySet<string>,\n): DocumentNode =>\n assembleSubgraphTypeDefs(\n getGeneratedDocumentModelTypes(documentModels),\n typeDefs,\n ownTypeNames,\n );\n\n/** Names of the type definitions in `doc`. */\nexport function typeDefinitionNames(doc: DocumentNode): Set<string> {\n return new Set(\n doc.definitions\n .map(typeDefinitionName)\n .filter((name) => name !== undefined),\n );\n}\n\n/** The generated document-model schema every subgraph is assembled onto. */\nexport type GeneratedDocumentModelTypes = {\n definitions: readonly DefinitionNode[];\n names: ReadonlySet<string>;\n scalars: ScalarRegistry;\n};\n\n/** The definitions `documentModel` adds to the generated schema. */\nfunction documentModelDefinitions(\n documentModel: DocumentModelGlobalState,\n): DefinitionNode[] {\n const dmSchemaName = getDocumentModelSchemaName(documentModel);\n // Use only the latest specification to avoid duplicate type definitions\n // when a document model has multiple versions (e.g. v1, v2).\n const latestSpec = documentModel.specifications.at(-1);\n const globalSchema = latestSpec?.state.global.schema ?? \"\";\n const localSchema = latestSpec?.state.local.schema ?? \"\";\n const definitions = [\n ...stateTypeDefinitions(globalSchema),\n ...stateTypeDefinitions(localSchema, LOCAL_STATE_STUBS),\n ];\n const stateDoc: DocumentNode = { kind: Kind.DOCUMENT, definitions };\n const prefixed = prefixTypeNames(\n stateDoc,\n dmSchemaName,\n new Set(definedTypeNames(stateDoc, STATE_PREFIX_KINDS)),\n );\n const documentType = parseSdl(`\n type ${dmSchemaName} implements IDocument {\n id: String!\n name: String!\n documentType: String!\n operations(skip: Int, first: Int): [Operation!]!\n revision: Int!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n ${dmSchemaName !== \"DocumentModel\" ? `initialState: ${dmSchemaName}_${dmSchemaName}State!` : \"\"}\n ${dmSchemaName !== \"DocumentModel\" ? `state: ${dmSchemaName}_${dmSchemaName}State!` : \"\"}\n stateJSON: JSONObject\n }`);\n return [...prefixed.definitions, ...documentType.definitions];\n}\n\n/** The part of a document model module its schema is built from. */\nexport type DocumentModelSource = {\n documentModel: { global: DocumentModelGlobalState };\n};\n\n/** Type name → whether every definition of that name is a scalar. */\nexport type ReservedTypeNames = ReadonlyMap<string, boolean>;\n\nfunction addScalarFlags(\n definitions: readonly DefinitionNode[],\n into: Map<string, boolean>,\n): Map<string, boolean> {\n for (const def of definitions) {\n const name = typeDefinitionName(def);\n if (name === undefined) continue;\n const scalar = def.kind === Kind.SCALAR_TYPE_DEFINITION;\n into.set(name, scalar && (into.get(name) ?? true));\n }\n return into;\n}\n\nlet fixedGeneratedTypes: ReservedTypeNames | undefined;\n\n/**\n * Type names no document model may generate: the root types, the generated\n * types every schema carries, and the types of `coreTypeDefs`.\n */\nexport function reservedTypeNames(\n coreTypeDefs: Iterable<DocumentNode>,\n): ReservedTypeNames {\n fixedGeneratedTypes ??= addScalarFlags(\n getGeneratedDocumentModelTypes([]).definitions,\n new Map(),\n );\n const reserved = new Map([\n [\"Query\", false],\n [\"Mutation\", false],\n [\"Subscription\", false],\n ...fixedGeneratedTypes,\n ]);\n for (const typeDefs of coreTypeDefs) {\n addScalarFlags(typeDefs.definitions, reserved);\n }\n return reserved;\n}\n\n/**\n * The reserved names `documentModel`'s generated types take. A scalar may\n * repeat a reserved scalar: the duplicate is dropped on assembly.\n */\nexport function reservedTypeNamesTaken(\n documentModel: DocumentModelSource,\n reserved: ReservedTypeNames,\n definitions: readonly DefinitionNode[] = documentModelDefinitions(\n documentModel.documentModel.global,\n ),\n): string[] {\n const generated = addScalarFlags(definitions, new Map());\n return Array.from(generated)\n .filter(\n ([name, scalar]) => reserved.has(name) && !(scalar && reserved.get(name)),\n )\n .map(([name]) => name);\n}\n\nconst CATALOG_SCALARS = gql`\n ${catalogScalarSdl}\n`.definitions;\n\nconst HOST_TYPES = gql`\n type PHOperationContext {\n signer: Signer\n }\n\n type Signer {\n user: SignerUser\n app: SignerApp\n signatures: [String!]!\n }\n\n type SignerUser {\n address: String!\n networkId: String!\n chainId: Int!\n }\n\n type SignerApp {\n name: String!\n key: String!\n }\n\n type Operation {\n id: String!\n type: String!\n index: Int!\n timestampUtcMs: DateTime!\n hash: String!\n skip: Int\n inputText: String\n error: String\n context: PHOperationContext\n }\n\n interface IDocument {\n id: String!\n name: String!\n documentType: String!\n revision: Int!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n operations(first: Int, skip: Int): [Operation!]!\n stateJSON: JSONObject\n }\n`.definitions;\n\n/**\n * A federation gateway composes this SDL, not the schema built from it, so the\n * description is declared here as well as on the resolver.\n */\nfunction generatedHead(scalars: ScalarRegistry): readonly DefinitionNode[] {\n return [\n ...CATALOG_SCALARS,\n ...Array.from(scalars, ([name, { definition }]): DefinitionNode => ({\n kind: Kind.SCALAR_TYPE_DEFINITION,\n name: { kind: Kind.NAME, value: name },\n description:\n definition.description === undefined\n ? undefined\n : {\n kind: Kind.STRING,\n value: definition.description,\n block: true,\n },\n })),\n ...HOST_TYPES,\n ];\n}\n\nconst GENERATED_TAIL = gql`\n type GqlDocument implements IDocument {\n id: String!\n name: String!\n documentType: String!\n revision: Int!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n operations(first: Int, skip: Int): [Operation!]!\n stateJSON: JSONObject\n }\n\n type DriveDocument implements IDocument {\n id: String!\n name: String!\n documentType: String!\n revision: Int!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n operations(first: Int, skip: Int): [Operation!]!\n stateJSON: JSONObject\n }\n`.definitions;\n\n/**\n * The generated schema for `documentModels`. `schemas` supplies models'\n * definitions already built; the others are built here.\n */\nexport function getGeneratedDocumentModelTypes(\n documentModels: readonly DocumentModelSource[],\n schemas?: ReadonlyMap<DocumentModelSource, DocumentModelSchema>,\n scalars: ScalarRegistry = EMPTY_SCALAR_REGISTRY,\n): GeneratedDocumentModelTypes {\n return generatedTypesFrom(\n documentModels.map((model) => ({\n global: model.documentModel.global,\n generated: schemas?.get(model)?.generated,\n })),\n scalars,\n );\n}\n\n/** {@link getGeneratedDocumentModelTypes} from the models' global states. */\nexport function generatedTypesOf(\n documentModels: readonly DocumentModelGlobalState[],\n): GeneratedDocumentModelTypes {\n return generatedTypesFrom(\n documentModels.map((global) => ({ global })),\n EMPTY_SCALAR_REGISTRY,\n );\n}\n\nfunction generatedTypesFrom(\n documentModels: readonly {\n global: DocumentModelGlobalState;\n generated?: readonly DefinitionNode[];\n }[],\n scalars: ScalarRegistry,\n): GeneratedDocumentModelTypes {\n const modelDefinitions: DefinitionNode[] = [];\n const addedDocumentModels = new Set<string>();\n documentModels.forEach(({ global, generated }) => {\n const dmSchemaName = getDocumentModelSchemaName(global);\n if (addedDocumentModels.has(dmSchemaName)) {\n logger.debug(\n `Skipping document model with duplicate name: ${dmSchemaName}`,\n );\n return;\n }\n addedDocumentModels.add(dmSchemaName);\n modelDefinitions.push(...(generated ?? documentModelDefinitions(global)));\n });\n\n const definitions = dedupeTypeDefinitions([\n ...generatedHead(scalars),\n ...modelDefinitions,\n ...GENERATED_TAIL,\n ]);\n const names = new Set(\n definitions.map(typeDefinitionName).filter((name) => name !== undefined),\n );\n return { definitions, names, scalars };\n}\n\n/** What a document model contributes to the GraphQL schema. */\nexport type DocumentModelSchema = {\n /** Its definitions in the generated schema every subgraph carries. */\n generated: readonly DefinitionNode[];\n /** Its own subgraph's types, when it has operations to serve. */\n subgraph?: { typeDefs: DocumentNode; typeNames: ReadonlySet<string> };\n /** Why its own subgraph cannot be served; its generated types still can. */\n subgraphError?: Error;\n};\n\nconst hasValidSchema = (schema: string | null | undefined): boolean =>\n !!(schema && /\\b(input|type|enum|union|interface)\\s+\\w+/.test(schema));\n\n/** Whether any operation of the latest specification has a schema. */\nexport function hasOperationSchemas(documentModel: DocumentModelGlobalState) {\n const specification = documentModel.specifications.at(-1);\n if (!specification) return false;\n return specification.modules.some((module) =>\n module.operations.some((op) => hasValidSchema(op.schema)),\n );\n}\n\n/** The types of a document model's own subgraph. */\nexport function documentModelSubgraphTypes(\n documentModel: DocumentModelGlobalState,\n): { typeDefs: DocumentNode; typeNames: ReadonlySet<string> } {\n const typeDefs = generateDocumentModelSchema(documentModel, {\n useNewApi: true,\n });\n return { typeDefs, typeNames: typeDefinitionNames(typeDefs) };\n}\n\nconst toError = (error: unknown): Error =>\n error instanceof Error ? error : new Error(String(error));\n\n/** Build `subgraph` over the generated types of `documentModel` alone. */\nfunction checkBuilds(\n documentModel: DocumentModelSource,\n generated: readonly DefinitionNode[],\n subgraph?: DocumentModelSchema[\"subgraph\"],\n): void {\n buildSubgraphSchema([\n {\n typeDefs: assembleSubgraphTypeDefs(\n getGeneratedDocumentModelTypes(\n [documentModel],\n new Map([[documentModel, { generated }]]),\n ),\n subgraph?.typeDefs ?? EMPTY_DOCUMENT,\n subgraph?.typeNames,\n ),\n },\n ]);\n}\n\n/** Throws when the generated types every subgraph carries do not build. */\nexport function buildDocumentModelSchema(\n documentModel: DocumentModelSource,\n options: { subgraph?: boolean } = {},\n): DocumentModelSchema {\n const generated = documentModelDefinitions(\n documentModel.documentModel.global,\n );\n if (\n options.subgraph === false ||\n !hasOperationSchemas(documentModel.documentModel.global)\n ) {\n checkBuilds(documentModel, generated);\n return { generated };\n }\n try {\n const subgraph = documentModelSubgraphTypes(\n documentModel.documentModel.global,\n );\n checkBuilds(documentModel, generated, subgraph);\n return { generated, subgraph };\n } catch (error) {\n checkBuilds(documentModel, generated);\n return { generated, subgraphError: toError(error) };\n }\n}\n\n/** A document model's schema, or why it is unusable, under its source key. */\nexport type ResolvedDocumentModelSchema<\n T extends DocumentModelSource = DocumentModelModule,\n> = {\n model: T;\n key: string;\n} & (\n | { schema: DocumentModelSchema; error?: undefined }\n | { schema?: undefined; error: Error }\n);\n\n/** Hash of everything {@link buildDocumentModelSchema} reads. */\nfunction schemaSourceKey(documentModel: DocumentModelSource): string {\n const { name, specifications } = documentModel.documentModel.global;\n return createHash(\"sha256\")\n .update(JSON.stringify([name, specifications.at(-1)]))\n .digest(\"base64\");\n}\n\n/** Schemas and failures by source hash, for the last resolve's models only. */\nexport class DocumentModelSchemaCache<\n T extends DocumentModelSource = DocumentModelModule,\n> {\n #entries = new Map<string, DocumentModelSchema | Error>();\n readonly #build: (documentModel: T) => DocumentModelSchema;\n\n constructor(\n build: (documentModel: T) => DocumentModelSchema = buildDocumentModelSchema,\n ) {\n this.#build = build;\n }\n\n resolve(documentModels: readonly T[]): ResolvedDocumentModelSchema<T>[] {\n const entries = new Map<string, DocumentModelSchema | Error>();\n const resolved = documentModels.map(\n (model): ResolvedDocumentModelSchema<T> => {\n let key: string;\n let entry: DocumentModelSchema | Error | undefined;\n try {\n key = schemaSourceKey(model);\n entry = entries.get(key) ?? this.#entries.get(key);\n } catch (error) {\n key = `unkeyed:${model.documentModel.global.id}`;\n entry = toError(error);\n }\n if (entry === undefined) {\n try {\n entry = this.#build(model);\n } catch (error) {\n entry = toError(error);\n }\n }\n entries.set(key, entry);\n return entry instanceof Error\n ? { model, key, error: entry }\n : { model, key, schema: entry };\n },\n );\n this.#entries = entries;\n return resolved;\n }\n}\n\n/**\n * Names of the generated types `typeDefs` redefines, other than those a\n * model's own subgraph may repeat. Scalars are dropped on assembly, so they\n * never collide.\n */\nexport function findSubgraphTypeCollisions(\n generated: Pick<GeneratedDocumentModelTypes, \"names\">,\n typeDefs: DocumentNode,\n ownTypeNames?: ReadonlySet<string>,\n): string[] {\n const collisions: string[] = [];\n for (const def of typeDefs.definitions) {\n if (def.kind === Kind.SCALAR_TYPE_DEFINITION) continue;\n const name = typeDefinitionName(def);\n if (name === undefined || !generated.names.has(name)) continue;\n if (ownTypeNames?.has(name)) continue;\n collisions.push(name);\n }\n return collisions;\n}\n\n/** Throws {@link SubgraphTypeCollisionError}; see {@link getDocumentModelTypeDefs}. */\nexport function assembleSubgraphTypeDefs(\n generated: GeneratedDocumentModelTypes,\n typeDefs: DocumentNode,\n ownTypeNames?: ReadonlySet<string>,\n): DocumentNode {\n const collisions = findSubgraphTypeCollisions(\n generated,\n typeDefs,\n ownTypeNames,\n );\n if (collisions.length > 0) {\n throw new SubgraphTypeCollisionError(collisions);\n }\n const subgraphDefinitions = typeDefs.definitions.filter(\n (def) => def.kind !== Kind.SCALAR_TYPE_DEFINITION,\n );\n\n return {\n kind: Kind.DOCUMENT,\n definitions: [\n ...generated.definitions,\n ...dedupeTypeDefinitions(subgraphDefinitions, new Set(generated.names)),\n ],\n };\n}\n\n/**\n * Extract the names of types defined in a GraphQL schema.\n * Unparseable schemas yield no names.\n */\nfunction extractTypeNames(schema: string): string[] {\n try {\n return definedTypeNames(parseSdl(schema), ALL_PREFIX_KINDS);\n } catch (error) {\n logger.debug(`Skipping unparseable schema: ${String(error)}`);\n return [];\n }\n}\n\n/**\n * Print the input type definitions of a GraphQL schema.\n * @param excludeTypeNames - Input type names to leave out\n */\nfunction extractInputTypeDefinitions(\n schema: string,\n excludeTypeNames: Set<string> = new Set(),\n): string {\n const definitions = parseSdl(schema).definitions.filter(\n (def) =>\n def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION &&\n !excludeTypeNames.has(def.name.value),\n );\n if (definitions.length === 0) return \"\";\n return print({ kind: Kind.DOCUMENT, definitions });\n}\n\n/**\n * AST type node shape for recursive type conversion.\n */\ntype GraphQLTypeNode = {\n kind: Kind;\n name?: { value: string };\n type?: GraphQLTypeNode;\n};\n\n/**\n * Extract the root state type name from a scope's GraphQL schema.\n * Uses the naming convention: {DocumentName}State for global,\n * {DocumentName}{PascalScope}State for other scopes (e.g., DocumentDriveLocalState).\n * Falls back to the last ObjectTypeDefinition (root types are conventionally last).\n */\nfunction extractRootTypeName(\n schema: string,\n documentName: string,\n scopeName: string,\n): string | null {\n try {\n const ast = parse(schema);\n\n // Try conventions:\n // 1. {DocumentName}State for global, {DocumentName}{Scope}State otherwise\n // 2. {DocumentName}GlobalState (DocumentModel uses this variant)\n const scopeSuffix = scopeName === \"global\" ? \"\" : pascalCase(scopeName);\n const candidates = [\n `${documentName}${scopeSuffix}State`,\n `${documentName}${pascalCase(scopeName)}State`,\n ];\n\n let lastObjectType: string | null = null;\n for (const def of ast.definitions) {\n if (def.kind === Kind.OBJECT_TYPE_DEFINITION) {\n if (candidates.includes(def.name.value)) {\n return def.name.value;\n }\n lastObjectType = def.name.value;\n }\n }\n\n // Fallback: last object type (root state types are defined last by convention)\n return lastObjectType;\n } catch {\n // ignore parse errors\n }\n return null;\n}\n\n/**\n * Convert a GraphQL output type AST node to an optional input type string.\n * Strips non-null markers and converts object type references to Input suffix.\n */\nfunction convertTypeNodeToInput(\n typeNode: GraphQLTypeNode,\n objectNames: Set<string>,\n unionNames: Set<string>,\n interfaceNames: Set<string>,\n): string {\n if (typeNode.kind === Kind.NON_NULL_TYPE && typeNode.type) {\n return convertTypeNodeToInput(\n typeNode.type,\n objectNames,\n unionNames,\n interfaceNames,\n );\n }\n if (typeNode.kind === Kind.LIST_TYPE && typeNode.type) {\n const inner = convertTypeNodeToInput(\n typeNode.type,\n objectNames,\n unionNames,\n interfaceNames,\n );\n return `[${inner}]`;\n }\n if (typeNode.kind === Kind.NAMED_TYPE && typeNode.name) {\n const name = typeNode.name.value;\n if (objectNames.has(name)) return `${name}Input`;\n if (unionNames.has(name) || interfaceNames.has(name)) return \"JSONObject\";\n return name;\n }\n return \"JSONObject\";\n}\n\n/**\n * Generate GraphQL input type definitions from a state schema string.\n * Converts output type definitions to input types with all fields optional.\n * - Object type references get Input suffix\n * - Union/interface references become JSONObject\n * - Enums and scalars remain unchanged\n */\nfunction generateStateInputTypes(\n stateSchema: string,\n excludeTypeNames?: Set<string>,\n): string {\n if (!stateSchema || !stateSchema.trim()) return \"\";\n\n let ast;\n try {\n ast = parse(stateSchema);\n } catch {\n return \"\";\n }\n\n const enumNames = new Set<string>();\n const unionNames = new Set<string>();\n const interfaceNames = new Set<string>();\n const objectNames = new Set<string>();\n const existingInputNames = new Set<string>();\n\n for (const def of ast.definitions) {\n switch (def.kind) {\n case Kind.ENUM_TYPE_DEFINITION:\n enumNames.add(def.name.value);\n break;\n case Kind.UNION_TYPE_DEFINITION:\n unionNames.add(def.name.value);\n break;\n case Kind.INTERFACE_TYPE_DEFINITION:\n interfaceNames.add(def.name.value);\n break;\n case Kind.OBJECT_TYPE_DEFINITION:\n objectNames.add(def.name.value);\n break;\n case Kind.INPUT_OBJECT_TYPE_DEFINITION:\n existingInputNames.add(def.name.value);\n break;\n }\n }\n\n const inputTypes: string[] = [];\n\n for (const def of ast.definitions) {\n if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;\n // Skip if an input type with the same name already exists in the schema\n // or in operation schemas (to avoid duplicates with moduleSchemas)\n const inputName = `${def.name.value}Input`;\n if (existingInputNames.has(inputName)) continue;\n if (excludeTypeNames?.has(inputName)) continue;\n const fields = def.fields ?? [];\n if (fields.length === 0) continue;\n\n const inputFields = fields.map((field) => {\n const fieldName = field.name.value;\n const fieldType = convertTypeNodeToInput(\n field.type as GraphQLTypeNode,\n objectNames,\n unionNames,\n interfaceNames,\n );\n return ` ${fieldName}: ${fieldType}`;\n });\n\n inputTypes.push(\n `input ${def.name.value}Input {\\n${inputFields.join(\"\\n\")}\\n}`,\n );\n }\n\n return inputTypes.join(\"\\n\\n\");\n}\n\n/**\n * Apply type prefixes to GraphQL schema to namespace types and avoid collisions.\n * Inlined from @powerhousedao/common/utils to avoid ES module import issues.\n * @param {string} schema - GraphQL schema string\n * @param {string} prefix - Prefix to apply to type names\n * @param {string[]} externalTypeNames - Type names from other schemas to also prefix\n * @returns {string} Schema with prefixed types\n */\nfunction applyGraphQLTypePrefixes(\n schema: string,\n prefix: string,\n externalTypeNames: string[] = [],\n): string {\n if (!schema || !schema.trim()) {\n return schema;\n }\n\n const doc = parseSdl(schema);\n const names = new Set([\n ...definedTypeNames(doc, ALL_PREFIX_KINDS),\n ...externalTypeNames,\n ]);\n if (names.size === 0) return schema;\n return print(prefixTypeNames(doc, prefix, names));\n}\n\n/**\n * Options for generating document model GraphQL schemas.\n */\nexport interface DocumentModelSchemaOptions {\n /**\n * When true, generates new API patterns:\n * - Mutations return full document objects (MutationResult type)\n * - Adds createEmptyDocument mutation\n * - Makes docId and input parameters required\n * @default false\n */\n useNewApi?: boolean;\n}\n\n/**\n * Generate a GraphQL schema for a document model.\n *\n * @param documentModel - The document model global state\n * @param options - Schema generation options\n * @returns GraphQL DocumentNode\n */\nexport function generateDocumentModelSchema(\n documentModel: DocumentModelGlobalState,\n options: DocumentModelSchemaOptions = {},\n): DocumentNode {\n const { useNewApi = false } = options;\n\n const specification = documentModel.specifications.at(-1);\n const documentName = getDocumentModelSchemaName(documentModel);\n const globalStateSchema = specification?.state.global.schema;\n const localStateSchema = specification?.state.local.schema;\n const globalStateTypeNames = extractTypeNames(globalStateSchema ?? \"\");\n const localStateTypeNames = extractTypeNames(localStateSchema ?? \"\");\n const stateTypeNames = [...globalStateTypeNames, ...localStateTypeNames];\n\n // Collect ALL type names from all operations' schemas\n const allOperationTypeNames =\n specification?.modules.flatMap((module) =>\n module.operations.flatMap((op) => extractTypeNames(op.schema ?? \"\")),\n ) ?? [];\n\n // Combine state types and all operation types for prefixing\n const allTypeNames = [\n ...new Set([...stateTypeNames, ...allOperationTypeNames]),\n ];\n\n // Extract input type definitions from state schema, excluding operation-specific inputs\n // (those are already defined in op.schema)\n const operationInputTypeNames = new Set(allOperationTypeNames);\n const stateInputTypes = extractInputTypeDefinitions(\n globalStateSchema ?? \"\",\n operationInputTypeNames,\n );\n const prefixedStateInputTypes = applyGraphQLTypePrefixes(\n stateInputTypes,\n documentName,\n allTypeNames,\n );\n\n if (useNewApi) {\n // New API: flat queries, typed state, async mutations\n return generateNewApiSchema(\n documentName,\n specification,\n prefixedStateInputTypes,\n allTypeNames,\n hasValidSchema,\n );\n }\n\n // Legacy API\n return generateLegacyApiSchema(\n documentName,\n specification,\n prefixedStateInputTypes,\n allTypeNames,\n hasValidSchema,\n );\n}\n\n/**\n * Generate legacy API schema with nested queries\n */\nfunction generateLegacyApiSchema(\n documentName: string,\n specification: DocumentModelGlobalState[\"specifications\"][0] | undefined,\n prefixedStateInputTypes: string,\n allTypeNames: string[],\n hasValidSchema: (schema: string | null | undefined) => boolean,\n): DocumentNode {\n const createDocumentMutation = `${documentName}_createDocument(name:String!, driveId:String): String`;\n\n const operationMutations =\n specification?.modules\n .flatMap((module) =>\n module.operations\n .filter((op) => op.name && hasValidSchema(op.schema))\n .map(\n (op) =>\n `${documentName}_${camelCase(op.name!)}(\n driveId: String, docId: PHID, input: ${documentName}_${pascalCase(op.name!)}Input): Int`,\n ),\n )\n .join(\"\\n \") ?? \"\";\n\n const moduleSchemas = buildModuleSchemas(\n specification,\n documentName,\n allTypeNames,\n hasValidSchema,\n );\n\n return gql`\n \"\"\"\n Queries: ${documentName} Document\n \"\"\"\n\n type ${documentName}Queries {\n getDocument(docId: PHID!, driveId: PHID): ${documentName}\n getDocuments(driveId: String!): [${documentName}!]\n }\n\n type Query {\n ${documentName}: ${documentName}Queries\n }\n\n \"\"\"\n Mutations: ${documentName}\n \"\"\"\n type Mutation {\n ${createDocumentMutation}\n\n ${operationMutations}\n }\n\n ${\n prefixedStateInputTypes\n ? `\"\"\"\n Input Types from State Schema\n \"\"\"\n ${prefixedStateInputTypes}`\n : \"\"\n }\n\n ${moduleSchemas}`;\n}\n\n/**\n * Generate new API schema with flat queries, typed state, and async mutations.\n * Note: State schema types are NOT included here because they are already defined\n * in getDocumentModelTypeDefs() which is used during schema composition.\n * Including them here would cause duplicate type definitions.\n */\nfunction generateNewApiSchema(\n documentName: string,\n specification: DocumentModelGlobalState[\"specifications\"][0] | undefined,\n prefixedStateInputTypes: string,\n allTypeNames: string[],\n hasValidSchema: (schema: string | null | undefined) => boolean,\n): DocumentNode {\n // Use full state type for all document models\n const stateType = `${documentName}_FullState!`;\n\n // Shared base types for document state structure (same for all document types)\n const sharedBaseTypes = `\n \"\"\"Hash configuration for document state\"\"\"\n type ${documentName}_PHHashConfig {\n algorithm: String!\n encoding: String!\n }\n\n \"\"\"Document scope state (same for all document types)\"\"\"\n type ${documentName}_PHDocumentScopeState {\n version: Int!\n hash: ${documentName}_PHHashConfig!\n isDeleted: Boolean\n deletedAtUtcIso: String\n deletedBy: String\n deletionReason: String\n }\n `;\n\n // Full state type with all scopes (auth, document, global, local)\n // Note: DocumentModel uses different naming convention (GlobalState suffix instead of State)\n // For local state, check if the specification defines a local state type\n const localSchema = specification?.state.local.schema ?? \"\";\n const hasLocalStateType = localSchema.includes(\n `type ${documentName}LocalState`,\n );\n\n const globalStateType =\n documentName === \"DocumentModel\"\n ? `${documentName}_${documentName}GlobalState!`\n : `${documentName}_${documentName}State!`;\n const localStateType = !hasLocalStateType\n ? \"JSONObject!\"\n : `${documentName}_${documentName}LocalState!`;\n\n const fullStateType = `\n \"\"\"Full state with all scopes for ${documentName}\"\"\"\n type ${documentName}_FullState {\n auth: JSONObject!\n document: ${documentName}_PHDocumentScopeState!\n global: ${globalStateType}\n local: ${localStateType}\n }\n `;\n\n // Common input types - use extend to avoid conflicts with other subgraphs\n const commonInputTypes = `\n input ${documentName}_ViewFilterInput {\n branch: String\n scopes: [String!]\n }\n\n input ${documentName}_PagingInput {\n limit: Int\n offset: Int\n cursor: String\n }\n\n input ${documentName}_SearchFilterInput {\n parentId: String\n identifiers: [String!] @deprecated(reason: \"Ignored. Filter by parentId.\")\n }\n `;\n\n // Revision type - imported from shared-schema.ts for consistency with ReactorSubgraph\n // Must be defined in each subgraph for Apollo Federation\n const revisionType = RevisionType;\n\n // Result types with typed state (or JSONObject for DocumentModel)\n // The state type (${documentName}_${documentName}State) is defined in getDocumentModelTypeDefs()\n // Uses revisionsList with shared Revision type to match ReactorSubgraph pattern\n const resultTypes = `\n \"\"\"\n Mutation result type for ${documentName} operations with typed state.\n Matches ReactorSubgraph PHDocument pattern with revisionsList.\n \"\"\"\n type ${documentName}MutationResult {\n id: String!\n slug: String\n preferredEditor: String\n name: String!\n documentType: String!\n state: ${stateType}\n revisionsList: [Revision!]!\n createdAtUtcIso: DateTime!\n lastModifiedAtUtcIso: DateTime!\n }\n\n \"\"\"\n Document with children for ${documentName}\n \"\"\"\n type ${documentName}_DocumentWithChildren {\n document: ${documentName}MutationResult!\n childIds: [String!]!\n }\n\n \"\"\"\n Paginated result type for ${documentName} documents\n \"\"\"\n type ${documentName}_DocumentResultPage {\n items: [${documentName}MutationResult!]!\n hasNextPage: Boolean!\n hasPreviousPage: Boolean!\n cursor: String\n }\n `;\n\n // Queries nested under ${documentName} namespace\n const queries = `\n type ${documentName}Queries {\n \"\"\"Get a specific ${documentName} document by identifier\"\"\"\n document(idOrSlug: String, identifier: String @deprecated(reason: \"Use idOrSlug.\"), view: ${documentName}_ViewFilterInput): ${documentName}_DocumentWithChildren\n\n \"\"\"Get all ${documentName} documents (paged)\"\"\"\n documents(paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!\n\n \"\"\"Find ${documentName} documents by search criteria\"\"\"\n findDocuments(search: ${documentName}_SearchFilterInput, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!\n\n \"\"\"Get outgoing relationships of a ${documentName} document\"\"\"\n documentOutgoingRelationships(sourceIdOrSlug: String, sourceIdentifier: String @deprecated(reason: \"Use sourceIdOrSlug.\"), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!\n\n \"\"\"Get incoming relationships to a ${documentName} document\"\"\"\n documentIncomingRelationships(targetIdOrSlug: String, targetIdentifier: String @deprecated(reason: \"Use targetIdOrSlug.\"), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!\n }\n `;\n\n // Generate initial state input types for each scope\n let initialStateInputSchema = \"\";\n if (specification) {\n const scopeFields: string[] = [];\n const generatedInputTypeParts: string[] = [];\n\n for (const [scopeName, scopeState] of Object.entries(specification.state)) {\n const schema = (scopeState as { schema?: string }).schema ?? \"\";\n if (hasValidSchema(schema)) {\n const rootTypeName = extractRootTypeName(\n schema,\n documentName,\n scopeName,\n );\n if (!rootTypeName) {\n scopeFields.push(` ${scopeName}: JSONObject`);\n continue;\n }\n const scopeInputTypes = generateStateInputTypes(\n schema,\n new Set(allTypeNames),\n );\n if (!scopeInputTypes) {\n scopeFields.push(` ${scopeName}: JSONObject`);\n continue;\n }\n const prefixedScopeInputTypes = applyGraphQLTypePrefixes(\n scopeInputTypes,\n documentName,\n allTypeNames,\n );\n scopeFields.push(\n ` ${scopeName}: ${documentName}_${rootTypeName}Input`,\n );\n generatedInputTypeParts.push(prefixedScopeInputTypes);\n } else {\n scopeFields.push(` ${scopeName}: JSONObject`);\n }\n }\n\n if (scopeFields.length > 0) {\n const inputTypeDefs = generatedInputTypeParts.join(\"\\n\\n\");\n const wrapper = `input ${documentName}_InitialStateInput {\\n${scopeFields.join(\"\\n\")}\\n}`;\n initialStateInputSchema = inputTypeDefs\n ? `${inputTypeDefs}\\n\\n${wrapper}`\n : wrapper;\n }\n }\n\n // Mutations nested under ${documentName} namespace\n const createDocumentMutation = initialStateInputSchema\n ? `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\"), slug: String, preferredEditor: String, initialState: ${documentName}_InitialStateInput): ${documentName}MutationResult!`\n : `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\"), preferredEditor: String): ${documentName}MutationResult!`;\n const createEmptyDocumentMutation = `createEmptyDocument(parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: \"Use parentIdOrSlug.\")): ${documentName}MutationResult!`;\n\n const operationMutations =\n specification?.modules\n .flatMap((module) =>\n module.operations\n .filter((op) => op.name && hasValidSchema(op.schema))\n .flatMap((op) => [\n // Sync mutation\n `${camelCase(op.name!)}(documentIdOrSlug: String, docId: PHID @deprecated(reason: \"Use documentIdOrSlug.\"), input: ${documentName}_${pascalCase(op.name!)}Input!): ${documentName}MutationResult!`,\n // Async mutation\n `${camelCase(op.name!)}Async(documentIdOrSlug: String, docId: PHID @deprecated(reason: \"Use documentIdOrSlug.\"), input: ${documentName}_${pascalCase(op.name!)}Input!): String!`,\n ]),\n )\n .join(\"\\n \") ?? \"\";\n\n const moduleSchemas = buildModuleSchemas(\n specification,\n documentName,\n allTypeNames,\n hasValidSchema,\n );\n\n return gql`\n ${catalogScalarSdl}\n\n ${revisionType}\n\n ${sharedBaseTypes}\n\n ${fullStateType}\n\n ${commonInputTypes}\n\n ${resultTypes}\n\n \"\"\"\n Queries: ${documentName} Document\n \"\"\"\n ${queries}\n\n \"\"\"\n Mutations: ${documentName}\n \"\"\"\n type ${documentName}Mutations {\n ${createDocumentMutation}\n ${createEmptyDocumentMutation}\n\n ${operationMutations}\n }\n\n type Query {\n ${documentName}: ${documentName}Queries!\n }\n\n type Mutation {\n ${documentName}: ${documentName}Mutations!\n }\n\n ${\n prefixedStateInputTypes\n ? `\"\"\"\n Input Types from State Schema\n \"\"\"\n ${prefixedStateInputTypes}`\n : \"\"\n }\n\n ${\n initialStateInputSchema\n ? `\"\"\"\n Input Types for Initial State\n \"\"\"\n ${initialStateInputSchema}`\n : \"\"\n }\n\n ${moduleSchemas}`;\n}\n","import {\n type ASTNode,\n type DefinitionNode,\n type DocumentNode,\n isTypeDefinitionNode,\n isTypeExtensionNode,\n Kind,\n type NamedTypeNode,\n type TypeDefinitionNode,\n type TypeExtensionNode,\n print,\n visit,\n} from \"graphql\";\n\nconst ROOT_TYPE_NAMES = new Set([\"Query\", \"Mutation\", \"Subscription\"]);\n\n/** Normalized definitions by type name or root field (`Query.field`). */\nexport type SubgraphClaims = ReadonlyMap<string, string>;\n\ntype Named = { name: { value: string } };\n\nconst byName = <T extends Named>(nodes: readonly T[] | undefined) =>\n nodes &&\n [...nodes].sort((a, b) =>\n a.name.value < b.name.value ? -1 : a.name.value > b.name.value ? 1 : 0,\n );\n\n/** Printed without descriptions, with named members in name order. */\nexport function normalizeDefinition(node: ASTNode): string {\n const normalized = visit(node, {\n leave(current) {\n const copy: Record<string, unknown> = { ...current };\n delete copy.loc;\n if (\"description\" in copy) copy.description = undefined;\n if (current.kind === Kind.STRING) copy.block = false;\n for (const key of [\"fields\", \"arguments\", \"interfaces\"]) {\n if (Array.isArray(copy[key])) {\n copy[key] = byName(copy[key] as Named[]);\n }\n }\n if (\n current.kind === Kind.ENUM_TYPE_DEFINITION ||\n current.kind === Kind.ENUM_TYPE_EXTENSION\n ) {\n copy.values = byName(current.values);\n }\n if (\n current.kind === Kind.UNION_TYPE_DEFINITION ||\n current.kind === Kind.UNION_TYPE_EXTENSION\n ) {\n copy.types = byName(current.types as readonly NamedTypeNode[]);\n }\n return copy as unknown as ASTNode;\n },\n });\n return print(normalized);\n}\n\nfunction isScalar(def: DefinitionNode): boolean {\n return (\n def.kind === Kind.SCALAR_TYPE_DEFINITION ||\n def.kind === Kind.SCALAR_TYPE_EXTENSION\n );\n}\n\n/** Type and root-field claims, without scalars or generated types. */\nexport function collectSubgraphClaims(\n typeDefs: DocumentNode,\n generatedNames: ReadonlySet<string>,\n): SubgraphClaims {\n const types = new Map<string, (TypeDefinitionNode | TypeExtensionNode)[]>();\n const claims = new Map<string, string>();\n for (const def of typeDefs.definitions) {\n if (!isTypeDefinitionNode(def) && !isTypeExtensionNode(def)) continue;\n if (isScalar(def)) continue;\n const node: TypeDefinitionNode | TypeExtensionNode = def;\n const name = node.name.value;\n if (ROOT_TYPE_NAMES.has(name)) {\n if (!(\"fields\" in node)) continue;\n for (const field of node.fields ?? []) {\n const key = `${name}.${field.name.value}`;\n const definition = normalizeDefinition(field);\n const previous = claims.get(key);\n claims.set(\n key,\n previous === undefined ? definition : `${previous}\\n${definition}`,\n );\n }\n continue;\n }\n if (isTypeDefinitionNode(node) && generatedNames.has(name)) continue;\n const nodes = types.get(name) ?? [];\n nodes.push(node);\n types.set(name, nodes);\n }\n for (const [name, nodes] of types) {\n const merged = mergeTypeNodes(nodes);\n claims.set(\n name,\n merged\n ? normalizeDefinition(merged)\n : nodes.map(normalizeDefinition).sort().join(\"\\n\"),\n );\n }\n return claims;\n}\n\nconst EXTENSION_KINDS: Partial<Record<Kind, Kind>> = {\n [Kind.OBJECT_TYPE_DEFINITION]: Kind.OBJECT_TYPE_EXTENSION,\n [Kind.INTERFACE_TYPE_DEFINITION]: Kind.INTERFACE_TYPE_EXTENSION,\n [Kind.UNION_TYPE_DEFINITION]: Kind.UNION_TYPE_EXTENSION,\n [Kind.ENUM_TYPE_DEFINITION]: Kind.ENUM_TYPE_EXTENSION,\n [Kind.INPUT_OBJECT_TYPE_DEFINITION]: Kind.INPUT_OBJECT_TYPE_EXTENSION,\n};\n\n/** One definition plus its same-kind extensions, as a single definition. */\nfunction mergeTypeNodes(\n nodes: readonly (TypeDefinitionNode | TypeExtensionNode)[],\n): ASTNode | undefined {\n if (nodes.length === 1) return nodes[0];\n const definitions = nodes.filter(isTypeDefinitionNode);\n if (definitions.length !== 1) return undefined;\n const [definition] = definitions;\n const extensionKind = EXTENSION_KINDS[definition.kind];\n const merged: Record<string, readonly unknown[] | undefined> = {\n ...(definition as unknown as Record<string, readonly unknown[]>),\n };\n for (const node of nodes) {\n if (node === definition) continue;\n if (node.kind !== extensionKind) return undefined;\n const members = node as unknown as Record<string, readonly unknown[]>;\n for (const key of [\n \"fields\",\n \"interfaces\",\n \"values\",\n \"types\",\n \"directives\",\n ]) {\n const extra = members[key] as readonly unknown[] | undefined;\n if (extra) merged[key] = [...(merged[key] ?? []), ...extra];\n }\n }\n return merged as unknown as ASTNode;\n}\n\nfunction isRootFieldClaim(claim: string): boolean {\n return claim.includes(\".\");\n}\n\nexport type OwnershipConflict = { claim: string; owner: string };\n\n/** Candidates, in priority order, that lose a claim to an earlier one. */\nexport function resolveClaimOwnership<T>(\n candidates: Iterable<{ candidate: T; name: string; claims: SubgraphClaims }>,\n): Map<T, OwnershipConflict[]> {\n const owners = new Map<string, { definition: string; owner: string }>();\n const excluded = new Map<T, OwnershipConflict[]>();\n for (const { candidate, name, claims } of candidates) {\n const conflicts: OwnershipConflict[] = [];\n for (const [claim, definition] of claims) {\n const owned = owners.get(claim);\n // A root field has one resolver, so only its owner may serve it.\n if (\n owned &&\n (isRootFieldClaim(claim) || owned.definition !== definition)\n ) {\n conflicts.push({ claim, owner: owned.owner });\n }\n }\n if (conflicts.length > 0) {\n excluded.set(candidate, conflicts);\n continue;\n }\n for (const [claim, definition] of claims) {\n if (!owners.has(claim)) owners.set(claim, { definition, owner: name });\n }\n }\n return excluded;\n}\n\nexport function describeOwnershipConflicts(\n conflicts: readonly OwnershipConflict[],\n): string {\n return `claims owned by another subgraph: ${conflicts\n .map(({ claim, owner }) => `${claim} (owned by \"${owner}\")`)\n .join(\", \")}`;\n}\n","import {\n type DocumentModelSchema,\n type DocumentModelSource,\n type ReservedTypeNames,\n type ResolvedDocumentModelSchema,\n reservedTypeNamesTaken,\n} from \"../utils/create-schema.js\";\nimport {\n type OwnershipConflict,\n resolveClaimOwnership,\n type SubgraphClaims,\n} from \"./subgraph-type-ownership.js\";\n\n/** Where a subgraph came from; a package origin is the package name. */\nexport const CORE_ORIGIN = Symbol(\"core\");\nexport const DOCUMENT_MODEL_ORIGIN = Symbol(\"document-models\");\nexport const HOST_ORIGIN = Symbol(\"host\");\nexport type SubgraphOrigin =\n | string\n | typeof CORE_ORIGIN\n | typeof DOCUMENT_MODEL_ORIGIN\n | typeof HOST_ORIGIN;\n\nexport function describeOrigin(origin: SubgraphOrigin): string {\n if (origin === CORE_ORIGIN) return \"core\";\n if (origin === DOCUMENT_MODEL_ORIGIN) return \"document models\";\n if (origin === HOST_ORIGIN) return \"the host\";\n return `package ${origin}`;\n}\n\nfunction rank(origin: SubgraphOrigin): number {\n if (origin === CORE_ORIGIN) return 3;\n if (origin === HOST_ORIGIN) return 2;\n if (origin === DOCUMENT_MODEL_ORIGIN) return 1;\n return 0;\n}\n\nexport type DocumentModelRefusal<T> = {\n model: T;\n key: string;\n /** Specification version of the refused model. */\n version: number;\n /** The latest version is refused, so no version of the model is served. */\n everyVersion: boolean;\n /** Only the model's own subgraph is refused; its generated types stay. */\n subgraphOnly: boolean;\n reason: string;\n};\n\nexport type DocumentModelAdmission<T> = {\n admitted: T[];\n schemas: Map<T, DocumentModelSchema>;\n refusals: DocumentModelRefusal<T>[];\n};\n\n/** Usable models; a refused latest version refuses every version of its model. */\nexport function admitDocumentModels<T extends DocumentModelSource>(\n resolved: readonly ResolvedDocumentModelSchema<T>[],\n reserved: ReservedTypeNames,\n): DocumentModelAdmission<T> {\n const latest = new Set(\n filterLatestDocumentModelVersions(resolved.map(({ model }) => model)),\n );\n const candidates: {\n model: T;\n key: string;\n schema?: DocumentModelSchema;\n refusal?: { reason: string; subgraphOnly: boolean };\n }[] = [];\n for (const { model, key, schema, error } of resolved) {\n if (!schema) {\n const reason = `has an unusable schema: ${error.message}`;\n candidates.push({ model, key, refusal: { reason, subgraphOnly: false } });\n continue;\n }\n const taken = reservedTypeNamesTaken(model, reserved, schema.generated);\n if (taken.length > 0) {\n const reason = `generates reserved type names: ${taken.join(\", \")}`;\n candidates.push({ model, key, refusal: { reason, subgraphOnly: false } });\n continue;\n }\n const refusal = schema.subgraphError && {\n reason: `has an unusable subgraph schema: ${schema.subgraphError.message}`,\n subgraphOnly: true,\n };\n candidates.push({ model, key, schema, refusal });\n }\n\n const refusedModels = new Set(\n candidates\n .filter(({ model, refusal }) => refusal && latest.has(model))\n .map(({ model }) => model.documentModel.global.name),\n );\n const admission: DocumentModelAdmission<T> = {\n admitted: [],\n schemas: new Map(),\n refusals: [],\n };\n for (const { model, key, schema, refusal } of candidates) {\n const everyVersion = latest.has(model);\n if (!everyVersion && refusedModels.has(model.documentModel.global.name)) {\n continue;\n }\n if (refusal) {\n admission.refusals.push({\n model,\n key,\n version: specVersion(model),\n everyVersion,\n ...refusal,\n });\n }\n if (schema) {\n admission.schemas.set(model, schema);\n admission.admitted.push(model);\n }\n }\n return admission;\n}\n\nconst DOCUMENT_MODELS_TO_EXCLUDE: string[] = [];\n\nconst specVersion = (model: DocumentModelSource) =>\n model.documentModel.global.specifications.at(-1)?.version ?? 0;\n\n/** The latest version of each document model. */\nfunction filterLatestDocumentModelVersions<T extends DocumentModelSource>(\n documentModels: readonly T[],\n): T[] {\n const latestByName = new Map<string, T>();\n\n for (const documentModel of documentModels) {\n const name = documentModel.documentModel.global.name;\n const existing = latestByName.get(name);\n\n if (!existing || specVersion(documentModel) > specVersion(existing)) {\n latestByName.set(name, documentModel);\n }\n }\n\n return Array.from(latestByName.values());\n}\n\n/** The admitted models that serve a subgraph of their own, with its types. */\nexport function documentModelSubgraphSources<T extends DocumentModelSource>(\n admitted: readonly T[],\n schemas: ReadonlyMap<T, DocumentModelSchema>,\n): { model: T; types: NonNullable<DocumentModelSchema[\"subgraph\"]> }[] {\n const sources: {\n model: T;\n types: NonNullable<DocumentModelSchema[\"subgraph\"]>;\n }[] = [];\n for (const model of filterLatestDocumentModelVersions(admitted)) {\n if (DOCUMENT_MODELS_TO_EXCLUDE.includes(model.documentModel.global.id)) {\n continue;\n }\n const types = schemas.get(model)?.subgraph;\n if (types) sources.push({ model, types });\n }\n return sources;\n}\n\nexport type Admission<T> =\n | { action: \"skip\" }\n | { action: \"reject\"; reason: \"core name\" }\n | { action: \"reject\"; reason: \"rank\"; holderOrigin: SubgraphOrigin }\n | { action: \"reject\"; reason: \"collision\"; collisions: string[] }\n | { action: \"add\"; replaces: T[]; evicts: T[] };\n\n/** Same origin replaces, higher rank evicts, else refused; core names never move (#2972). */\nexport function decideAdmission<T>(\n candidate: T,\n origin: SubgraphOrigin,\n holders: readonly { holder: T; origin: SubgraphOrigin }[],\n collisions: () => string[],\n): Admission<T> {\n if (\n origin !== CORE_ORIGIN &&\n holders.some((holder) => holder.origin === CORE_ORIGIN)\n ) {\n return { action: \"reject\", reason: \"core name\" };\n }\n if (holders.some(({ holder }) => holder === candidate)) {\n return { action: \"skip\" };\n }\n const rivals = holders.filter((holder) => holder.origin !== origin);\n for (const rival of rivals) {\n if (rank(origin) <= rank(rival.origin)) {\n return { action: \"reject\", reason: \"rank\", holderOrigin: rival.origin };\n }\n }\n const found = origin === CORE_ORIGIN ? [] : collisions();\n if (found.length > 0) {\n return { action: \"reject\", reason: \"collision\", collisions: found };\n }\n return {\n action: \"add\",\n replaces: holders\n .filter((holder) => holder.origin === origin)\n .map(({ holder }) => holder),\n evicts: rivals.map(({ holder }) => holder),\n };\n}\n\n/** The order origins first registered in, and names within each. */\nexport class RegistrationOrder {\n readonly #origins = new Map<\n SubgraphOrigin,\n { order: number; names: Map<string, number> }\n >();\n\n record(origin: SubgraphOrigin, name: string): void {\n let entry = this.#origins.get(origin);\n if (!entry) {\n entry = { order: this.#origins.size, names: new Map() };\n this.#origins.set(origin, entry);\n }\n if (!entry.names.has(name)) entry.names.set(name, entry.names.size);\n }\n\n of(origin: SubgraphOrigin, name: string): [number, number] {\n const entry = this.#origins.get(origin);\n return [entry?.order ?? Infinity, entry?.names.get(name) ?? Infinity];\n }\n}\n\nexport type SupergraphMember<T> = {\n member: T;\n name: string;\n origin: SubgraphOrigin;\n claims: SubgraphClaims;\n};\n\n/** Rank, then first registration. */\nexport function byClaimPriority<T>(\n members: Iterable<T>,\n originOf: (member: T) => SubgraphOrigin,\n nameOf: (member: T) => string,\n order: RegistrationOrder,\n): T[] {\n return Array.from(members, (member) => {\n const origin = originOf(member);\n return {\n member,\n priority: [-rank(origin), ...order.of(origin, nameOf(member))],\n };\n })\n .sort((a, b) => {\n const i = a.priority.findIndex((value, j) => value !== b.priority[j]);\n return i === -1 ? 0 : a.priority[i] - b.priority[i];\n })\n .map(({ member }) => member);\n}\n\n/** Members that lose a claim: claims go by byClaimPriority. */\nexport function supergraphClaimLosers<T>(\n members: Iterable<SupergraphMember<T>>,\n order: RegistrationOrder,\n): Map<T, OwnershipConflict[]> {\n return resolveClaimOwnership(\n byClaimPriority(\n members,\n (member) => member.origin,\n (member) => member.name,\n order,\n ).map((member) => ({\n candidate: member.member,\n name: member.name,\n claims: member.claims,\n })),\n );\n}\n","import { gql } from \"graphql-tag\";\n\nexport const inspectionAdminTypeDefs = gql`\n \"\"\"\n The levers a listed admin may pull. Only served when the host enables\n inspection-admin; every field refuses any other caller.\n \"\"\"\n type InspectionAdmin {\n \"Processor retry and rerun are served.\"\n processors: Boolean!\n \"The catch-up priority can be set.\"\n catchUpPriority: Boolean!\n }\n\n type Query {\n inspectionAdmin: InspectionAdmin!\n }\n\n type Mutation {\n \"Clears a processor's error and replays from its cursor.\"\n inspectionRetryProcessor(processorId: String!): Boolean!\n \"\"\"\n Replays a processor. With clear, it and the processors sharing its clear\n scope are cleared and replayed from their floor; otherwise its cursor moves\n back to fromOrdinal, between its floor and its cursor. Answers once the\n replay ends or has run for two seconds; its progress shows in the\n processor's lastOrdinal, and a later failure in its status and the log.\n \"\"\"\n inspectionRerunProcessor(\n processorId: String!\n clear: Boolean!\n fromOrdinal: Float!\n ): Boolean!\n \"\"\"\n Sets the pace of processor backfills: mode dynamic hands the level to the\n load controller (level must be absent); mode fixed holds level, 0-7.\n \"\"\"\n inspectionSetCatchUpPriority(mode: String!, level: Int): Boolean!\n }\n`;\n","import { gql } from \"graphql-tag\";\n\n// Pinned by test to INSPECTION_WIRE_FIELDS/ROOT_FIELDS; ordinals are Float.\nexport const inspectionTypeDefs = gql`\n type ReactorStorageFacts {\n engine: String!\n persistence: String!\n durable: Boolean!\n selfHeal: Boolean!\n }\n\n type InspectorAccess {\n admin: Boolean!\n sql: Boolean!\n }\n\n \"\"\"\n What this reactor reports about itself. access is null unless the caller is\n one of the host's admins.\n \"\"\"\n type ReactorInfo {\n storage: ReactorStorageFacts!\n workflows: Boolean!\n syncChannels: [String!]!\n access: InspectorAccess\n }\n\n type InspectionDocumentModel {\n documentType: String!\n name: String!\n version: Int!\n supportedVersions: [Int!]!\n }\n\n type InspectionDrive {\n driveId: String!\n name: String!\n branch: String!\n collectionId: String!\n documentType: String!\n nodeCount: Int!\n fileCount: Int!\n folderCount: Int!\n otherNodeCount: Int!\n unreadableNodeCount: Int!\n icon: String\n }\n\n type InspectionDrivePage {\n results: [InspectionDrive!]!\n nextCursor: String\n }\n\n type InspectionDriveIntegrityRef {\n id: String!\n documentType: String!\n }\n\n type InspectionDriveIntegrity {\n driveId: String!\n checkedNodeCount: Int!\n totalFileNodeCount: Int!\n \"\"\"\n File nodes whose document is missing or not served to you; the two are\n reported alike so a withheld document's existence does not leak.\n \"\"\"\n missingDocuments: [InspectionDriveIntegrityRef!]!\n unsupportedTypes: [InspectionDriveIntegrityRef!]!\n }\n\n type InspectionAttachmentInfo {\n present: Boolean!\n storeKind: String!\n hasReplicator: Boolean!\n replicatorRunning: Boolean!\n backlogScanned: Boolean!\n refsSeen: Int!\n held: Int!\n bytesHeld: Float!\n queued: Int!\n fetching: Int!\n pendingFetches: Int!\n waiting: Int!\n notFound: Int!\n failed: Int!\n lastError: String\n }\n\n \"\"\"\n A queued job without its actions or operations.\n \"\"\"\n type InspectionQueueJob {\n id: String!\n kind: String!\n documentId: String!\n scope: String!\n branch: String!\n status: String!\n actionCount: Int!\n operationCount: Int!\n retryCount: Int!\n }\n\n type InspectionQueueState {\n isPaused: Boolean!\n totalPending: Int!\n totalExecuting: Int!\n pendingJobs: [InspectionQueueJob!]!\n executingJobs: [InspectionQueueJob!]!\n }\n\n type InspectionProcessor {\n processorId: String!\n factoryId: String!\n driveId: String!\n processorIndex: Int!\n lastOrdinal: Float!\n status: String!\n lastError: String\n lastErrorTimestampUtcMs: Float\n floor: Float!\n clearable: Boolean!\n runFrom: Float!\n phase: String!\n }\n\n \"\"\"\n What one catch-up priority level sets. giveWay is stop (level 0: no page is\n read until the level rises), pause (pauseMs between pages), yield (one\n event-loop turn) or none.\n \"\"\"\n type InspectionCatchUpLevelSettings {\n slots: Int!\n pageSize: Int!\n pauseMs: Int!\n giveWay: String!\n }\n\n \"\"\"\n The host's load over its last window, as the dynamic controller read it.\n \"\"\"\n type InspectionCatchUpLoadSample {\n requests: Int!\n p95LatencyMs: Float!\n eventLoopDelayMs: Float!\n idleForMs: Float!\n }\n\n \"\"\"\n The pace of processor backfills. mode is fixed or dynamic; level is 0-7.\n sample is null until a dynamic tick has sampled the host's load.\n \"\"\"\n type InspectionCatchUpPriority {\n mode: String!\n level: Int!\n settings: InspectionCatchUpLevelSettings!\n reason: String!\n sample: InspectionCatchUpLoadSample\n }\n\n \"\"\"\n healthy means something only when tracked; an untracked store reports false.\n \"\"\"\n type InspectionStorageHealth {\n tracked: Boolean!\n healthy: Boolean!\n everRecreated: Boolean!\n recreateCount: Int!\n }\n\n \"\"\"\n Issues in scopes the caller may not read are left out.\n \"\"\"\n type InspectionValidation {\n documentId: String!\n isConsistent: Boolean!\n keyframeIssues: [JSONObject!]!\n snapshotIssues: [JSONObject!]!\n streamOrderIssues: [JSONObject!]!\n }\n\n type InspectionCursor {\n cursorType: String!\n cursorOrdinal: Float!\n lastSyncedAtUtcMs: Float\n liveAckOrdinal: Float!\n liveLatestOrdinal: Float!\n }\n\n type InspectionMailboxDepths {\n inbox: Int!\n outbox: Int!\n deadLetter: Int!\n }\n\n type InspectionConnectionHealth {\n snapshot: JSONObject!\n neverSucceeded: Boolean!\n stalenessMs: Float\n }\n\n type InspectionRemote {\n remoteName: String!\n remoteId: String!\n inboxCursor: InspectionCursor!\n outboxCursor: InspectionCursor!\n mailboxDepths: InspectionMailboxDepths!\n connection: InspectionConnectionHealth!\n meta: JSONObject!\n }\n\n \"\"\"\n A dead letter without its operations.\n \"\"\"\n type InspectionDeadLetter {\n id: String!\n jobId: String!\n documentId: String!\n branch: String!\n scopes: [String!]!\n errorType: String!\n errorMessage: String!\n operationCount: Int!\n }\n\n type InspectionDeadLetterPage {\n remoteName: String!\n results: [InspectionDeadLetter!]!\n nextCursor: String\n }\n\n \"\"\"\n Reads only. info and documentModels serve every caller; drive and document\n reads are made as the caller through the reactor read gate; the rest need\n one of the host's admins.\n \"\"\"\n type ReactorInspection {\n info: ReactorInfo!\n documentModels: [InspectionDocumentModel!]!\n drives(cursor: String, limit: Int): InspectionDrivePage!\n \"\"\"\n Reads every file node's document. Throttled per caller.\n \"\"\"\n driveIntegrity(driveId: String!, branch: String!): InspectionDriveIntegrity!\n attachmentInfo: InspectionAttachmentInfo!\n queueState: InspectionQueueState!\n processors: [InspectionProcessor!]!\n catchUpStatus: JSONObject!\n catchUpPriority: InspectionCatchUpPriority!\n storageHealth: InspectionStorageHealth!\n \"\"\"\n Replays the whole document; expensive. Throttled per caller.\n \"\"\"\n validateDocument(documentId: String!, branch: String): InspectionValidation!\n remotes: [InspectionRemote!]!\n remote(remoteName: String!): InspectionRemote!\n deadLetters(\n remoteName: String!\n cursor: String\n limit: Int\n ): InspectionDeadLetterPage!\n }\n\n type Query {\n inspection: ReactorInspection!\n }\n`;\n","\"# Scalar types (for codegen - also defined in create-schema.ts)\\nscalar JSONObject\\nscalar DateTime\\n\\n# Input types\\ninput PagingInput {\\n limit: Int\\n offset: Int\\n cursor: String\\n}\\n\\ninput ViewFilterInput {\\n branch: String\\n scopes: [String!]\\n}\\n\\ninput SearchFilterInput {\\n type: String\\n parentId: String\\n identifiers: [String!]\\n @deprecated(reason: \\\"Ignored. Filter by type or parentId.\\\")\\n}\\n\\ninput OperationsFilterInput {\\n documentIdOrSlug: String\\n documentId: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n branch: String\\n scopes: [String!]\\n actionTypes: [String!]\\n sinceRevision: Int\\n timestampFrom: String\\n timestampTo: String\\n}\\n\\n\\\"A consistency token's coordinate, as ConsistencyCoordinate reports it.\\\"\\ninput ConsistencyCoordinateInput {\\n documentId: String!\\n scope: String!\\n branch: String!\\n operationIndex: Int!\\n}\\n\\n\\\"\\\"\\\"\\nA consistency token, as JobInfo.consistencyToken reports it. A read given one\\nwaits until the read models it reads from hold every coordinate it names.\\n\\\"\\\"\\\"\\ninput ConsistencyTokenInput {\\n version: Int!\\n createdAtUtcIso: String!\\n coordinates: [ConsistencyCoordinateInput!]!\\n}\\n\\ninput DocumentOperationsFilterInput {\\n branch: String\\n scopes: [String!]\\n actionTypes: [String!]\\n sinceRevision: Int\\n timestampFrom: String\\n timestampTo: String\\n}\\n\\n# Enums\\nenum PropagationMode {\\n CASCADE\\n ORPHAN\\n}\\n\\nenum DocumentChangeType {\\n CREATED\\n DELETED\\n UPDATED\\n PARENT_ADDED\\n PARENT_REMOVED\\n CHILD_ADDED\\n CHILD_REMOVED\\n}\\n\\n# Object types\\ntype DocumentModelGlobalState {\\n id: String!\\n name: String!\\n namespace: String\\n version: String\\n specification: JSONObject!\\n}\\n\\ntype DocumentModelResultPage {\\n items: [DocumentModelGlobalState!]!\\n hasNextPage: Boolean!\\n hasPreviousPage: Boolean!\\n cursor: String\\n}\\n\\ntype Revision {\\n scope: String!\\n revision: Int!\\n}\\n\\ntype PHDocument {\\n id: String!\\n slug: String\\n preferredEditor: String\\n meta: JSONObject\\n protocolVersions: JSONObject\\n name: String!\\n documentType: String!\\n state: JSONObject!\\n revisionsList: [Revision!]!\\n createdAtUtcIso: DateTime!\\n lastModifiedAtUtcIso: DateTime!\\n operations(\\n filter: DocumentOperationsFilterInput\\n paging: PagingInput\\n ): ReactorOperationResultPage\\n}\\n\\ntype PHDocumentResultPage {\\n items: [PHDocument!]!\\n hasNextPage: Boolean!\\n hasPreviousPage: Boolean!\\n cursor: String\\n}\\n\\n# A directed edge between two documents, with the metadata recorded against it.\\ntype DocumentRelationship {\\n sourceId: String!\\n targetId: String!\\n relationshipType: String!\\n metadata: JSONObject\\n createdAt: DateTime!\\n updatedAt: DateTime!\\n}\\n\\ntype DocumentRelationshipResultPage {\\n items: [DocumentRelationship!]!\\n hasNextPage: Boolean!\\n hasPreviousPage: Boolean!\\n cursor: String\\n}\\n\\ntype ReactorOperationResultPage {\\n items: [ReactorOperation!]!\\n hasNextPage: Boolean!\\n hasPreviousPage: Boolean!\\n cursor: String\\n}\\n\\ntype DeadLetterInfo {\\n documentId: String!\\n error: String!\\n \\\"\\\"\\\"\\n How the origin classified the failure. A peer needs this to mirror the origin's\\n quarantine decision; without it a held auth operation would freeze the document\\n on the peer side while the origin kept syncing.\\n \\\"\\\"\\\"\\n errorType: String\\n jobId: String!\\n branch: String!\\n scopes: [String!]!\\n operationCount: Int!\\n}\\n\\ntype PollSyncEnvelopesResult {\\n envelopes: [SyncEnvelope!]!\\n ackOrdinal: Int!\\n deadLetters: [DeadLetterInfo!]!\\n hasMore: Boolean!\\n # The server's current manifest revision\\n manifestRevision: String\\n # The client's manifest revision as the server holds it\\n peerManifestRevision: String\\n}\\n\\ntype SyncHoldReason {\\n protocol: String!\\n version: Int!\\n peerSupports: [Int!]!\\n}\\n\\n# A document held back from a remote whose peer cannot run its versions\\ntype SyncHold {\\n remoteName: String!\\n documentId: String!\\n branch: String!\\n reason: SyncHoldReason!\\n heldAtUtcMs: String!\\n}\\n\\ntype PeerAgreementMember {\\n remoteName: String!\\n # False for a peer that announced nothing: it gets the baselines\\n announced: Boolean!\\n protocols: JSONObject!\\n features: JSONObject!\\n}\\n\\ntype PeerAgreementLimit {\\n protocol: String!\\n # The remotes whose peers lack the version new documents would take\\n remoteNames: [String!]!\\n}\\n\\ntype PeerAgreement {\\n collectionId: String!\\n local: JSONObject!\\n members: [PeerAgreementMember!]!\\n limitedBy: [PeerAgreementLimit!]!\\n}\\n\\n# The kind of a drive node.\\nenum DriveNodeKind {\\n FILE\\n FOLDER\\n}\\n\\n# A file node: the document it names, placed in a drive.\\ntype DriveFileNode {\\n id: ID!\\n driveId: ID!\\n name: String!\\n parentFolder: ID\\n documentType: String!\\n}\\n\\n# A folder node.\\ntype DriveFolderNode {\\n id: ID!\\n driveId: ID!\\n name: String!\\n parentFolder: ID\\n}\\n\\n# A drive node, of any drive document type.\\nunion DriveNode = DriveFileNode | DriveFolderNode\\n\\n# A page of drive nodes. nextCursor resumes after the last node served.\\ntype DriveNodePage {\\n results: [DriveNode!]!\\n nextCursor: String\\n hasMore: Boolean!\\n}\\n\\ntype DocumentWithChildren {\\n document: PHDocument!\\n childIds: [String!]!\\n}\\n\\n# What a new document gets when its creator chooses nothing\\ntype CreateDefaults {\\n # \\\"legacy\\\" or \\\"v2-required\\\"; a client refuses a value it does not know\\n signaturePolicy: String!\\n protocolVersions: JSONObject!\\n}\\n\\ntype MoveRelationshipResult {\\n source: PHDocument!\\n target: PHDocument!\\n}\\n\\ntype ConsistencyCoordinate {\\n documentId: String!\\n scope: String!\\n branch: String!\\n operationIndex: Int!\\n}\\n\\n\\\"\\\"\\\"\\nThe write positions a job reached, for read-after-write. Only meaningful once\\nthe job has completed.\\n\\\"\\\"\\\"\\ntype ConsistencyToken {\\n version: Int!\\n createdAtUtcIso: String!\\n coordinates: [ConsistencyCoordinate!]!\\n}\\n\\n\\\"The batch a job was submitted in.\\\"\\ntype JobBatchMeta {\\n batchId: String!\\n batchJobIds: [String!]!\\n}\\n\\ntype JobInfo {\\n id: String!\\n\\n \\\"\\\"\\\"\\n The document the job operates on. Empty for a job this server does not know,\\n which then comes back FAILED with \\\"Job not found\\\".\\n \\\"\\\"\\\"\\n documentId: String!\\n status: String!\\n\\n \\\"\\\"\\\"\\n What the job produced, once it has produced anything. Null until then, which\\n is the state every job is in when it is handed back from a submission.\\n \\\"\\\"\\\"\\n result: JSONObject\\n\\n error: String\\n\\n \\\"The error's class name, such as `DocumentAlreadyExistsError`, when it failed.\\\"\\n errorName: String\\n createdAt: DateTime!\\n completedAt: DateTime\\n consistencyToken: ConsistencyToken!\\n meta: JobBatchMeta!\\n}\\n\\n\\\"\\\"\\\"\\nOne job's outcome within a batch, pairing the plan key the caller gave with the\\njob that applied it. Mirrors one entry of the `Record<string, JobInfo>` that\\n`IReactor.executeBatch` returns (packages/reactor/src/core/types.ts).\\n\\\"\\\"\\\"\\ntype BatchJobResult {\\n key: String!\\n job: JobInfo!\\n}\\n\\n\\\"\\\"\\\"\\nThe outcome of a batch mutation, one entry per job the request named. The wire\\nshape of `BatchExecutionResult` (`{ jobs }`), keyed on each entry by the plan\\nkey rather than by position so the client can rebuild the record. The batch is\\nnot atomic: each job commits on its own and a failed job releases its\\ndependents, so each entry's status says what happened to that job, and\\nre-submitting re-applies the jobs that succeeded.\\n\\\"\\\"\\\"\\ntype BatchExecutionResult {\\n jobs: [BatchJobResult!]!\\n}\\n\\ntype DocumentChangeEvent {\\n type: DocumentChangeType!\\n documents: [PHDocument!]!\\n context: DocumentChangeContext\\n}\\n\\ntype DocumentChangeContext {\\n parentId: String\\n childId: String\\n}\\n\\ntype JobChangeEvent {\\n jobId: String!\\n status: String!\\n\\n \\\"\\\"\\\"\\n What the job produced, once it has produced anything. Nullable for the same\\n reason as `JobInfo.result`: a job that has not written yet has produced\\n nothing, and an empty object would claim otherwise.\\n \\\"\\\"\\\"\\n result: JSONObject\\n\\n error: String\\n}\\n\\ntype ReactorSignerUser {\\n address: String!\\n networkId: String!\\n chainId: Int!\\n}\\n\\ntype ReactorSignerApp {\\n name: String!\\n key: String!\\n}\\n\\ntype ReactorSigner {\\n user: ReactorSignerUser\\n app: ReactorSignerApp\\n signatures: [String!]!\\n}\\n\\ntype ActionContext {\\n signer: ReactorSigner\\n}\\n\\ntype Action {\\n id: String!\\n type: String!\\n timestampUtcMs: String!\\n input: JSONObject!\\n scope: String!\\n context: ActionContext\\n}\\n\\n\\\"\\\"\\\"\\nOne operation an authorization preflight predicts a verdict for.\\n\\n`input` is what a conditional grant reads, so a candidate standing for a\\nfilled-in form carries that form's input. Omitting it predicts the verdict an\\nempty input earns, not the verdict the filled-in form will get.\\n\\\"\\\"\\\"\\ninput ActionCandidateInput {\\n scope: String!\\n type: String!\\n input: JSONObject\\n}\\n\\nenum AuthDecision {\\n ALLOW\\n DENY\\n}\\n\\n\\\"\\\"\\\"\\nOne candidate's predicted verdict. `reason` carries the refusal a DENY is\\nrecorded with, and is null on an ALLOW.\\n\\\"\\\"\\\"\\ntype ActionEvaluation {\\n decision: AuthDecision!\\n reason: String\\n}\\n\\n\\\"\\\"\\\"\\nThe predicted verdicts for a set of candidates, in the order they were given,\\nwith the aggregates a caller branches on.\\n\\nThe aggregates are redundant -- a verdict is binary -- and all four are returned\\nso a caller reads the one its question is phrased in rather than negating\\nanother. Over no candidates every aggregate is false: nothing is allowed and\\nnothing is denied.\\n\\\"\\\"\\\"\\ntype ActionEvaluations {\\n evaluations: [ActionEvaluation!]!\\n allAllowed: Boolean!\\n anyAllowed: Boolean!\\n allDenied: Boolean!\\n anyDenied: Boolean!\\n}\\n\\n# Input types for sync operations\\n\\\"\\\"\\\"\\nAn action's context, as a caller submits it.\\n\\nDeclares every field `ActionContext` carries, because an input object rejects a\\nfield it does not declare: an action stamped with the head it applies to - which\\nis what a signing client sends - is refused outright if these are missing, and\\nthat refusal is a whole-request one, not a per-field one.\\n\\n`prevOpHash` and `prevOpIndex` are the scope head the action was composed\\nagainst. They are recorded rather than enforced; a signature is verified from\\nthe params carried in its own tuple, which do not include them.\\n\\\"\\\"\\\"\\ninput ActionContextInput {\\n \\\"\\\"\\\"\\n The index of the last operation in the scope the action applies to.\\n \\\"\\\"\\\"\\n prevOpIndex: Int\\n\\n \\\"\\\"\\\"\\n The hash of the state the action applies to.\\n \\\"\\\"\\\"\\n prevOpHash: String\\n\\n \\\"\\\"\\\"\\n Covers replay of an operation that would otherwise be a no-op.\\n \\\"\\\"\\\"\\n nonce: String\\n\\n signer: ReactorSignerInput\\n}\\n\\ninput ReactorSignerInput {\\n user: ReactorSignerUserInput\\n app: ReactorSignerAppInput\\n signatures: [String!]!\\n}\\n\\ninput ReactorSignerUserInput {\\n address: String!\\n networkId: String!\\n chainId: Int!\\n}\\n\\ninput ReactorSignerAppInput {\\n name: String!\\n key: String!\\n}\\n\\ninput ActionInput {\\n id: String!\\n type: String!\\n timestampUtcMs: String!\\n input: JSONObject!\\n scope: String!\\n context: ActionContextInput\\n}\\n\\n\\\"\\\"\\\"\\nOne mutation job of a batch, mirroring the reactor's `ExecutionJobPlan`\\n(packages/reactor/src/core/types.ts). The batch runs its jobs in dependency\\norder only, not atomically: each job commits on its own with no batch rollback,\\nand a failed job still releases its dependents.\\n\\n`documentIdOrSlug` is the document the job's actions apply to -- an id that does\\nnot yet exist when the job's actions create it. `actions` are coerced against\\n`ActionInput` and passed through exactly as `execute` does, so a client-signed\\naction keeps its signature. `scope` is the single scope every action in the job\\nshares, and `dependsOn` names the plan keys this job is ordered after. `branch`\\ndefaults to `main`.\\n\\\"\\\"\\\"\\ninput ExecutionJobInput {\\n key: String!\\n documentIdOrSlug: String!\\n scope: String!\\n branch: String\\n actions: [ActionInput!]!\\n dependsOn: [String!]!\\n}\\n\\n# Synchronization types\\ntype ReactorOperation {\\n index: Int!\\n timestampUtcMs: String!\\n hash: String!\\n skip: Int!\\n error: String\\n deniedReason: String\\n id: String\\n action: Action!\\n}\\n\\ninput OperationInput {\\n index: Int!\\n timestampUtcMs: String!\\n hash: String!\\n skip: Int!\\n error: String\\n deniedReason: String\\n id: String\\n action: ActionInput!\\n}\\n\\ntype OperationContext {\\n documentId: String!\\n documentType: String!\\n scope: String!\\n branch: String!\\n ordinal: Int!\\n}\\n\\ninput OperationContextInput {\\n documentId: String!\\n documentType: String!\\n scope: String!\\n branch: String!\\n ordinal: Int!\\n}\\n\\ntype OperationWithContext {\\n operation: ReactorOperation!\\n context: OperationContext!\\n}\\n\\ninput OperationWithContextInput {\\n operation: OperationInput!\\n context: OperationContextInput!\\n}\\n\\ntype ChannelMeta {\\n id: String!\\n}\\n\\ninput ChannelMetaInput {\\n id: String!\\n}\\n\\ntype RemoteCursor {\\n remoteName: String!\\n cursorOrdinal: Int!\\n lastSyncedAtUtcMs: String\\n}\\n\\ninput RemoteCursorInput {\\n remoteName: String!\\n cursorOrdinal: Int!\\n lastSyncedAtUtcMs: String\\n}\\n\\nenum SyncEnvelopeType {\\n OPERATIONS\\n ACK\\n}\\n\\ntype SyncEnvelope {\\n type: SyncEnvelopeType!\\n channelMeta: ChannelMeta!\\n operations: [OperationWithContext!]\\n cursor: RemoteCursor\\n key: String\\n dependsOn: [String!]\\n}\\n\\ninput SyncEnvelopeInput {\\n type: SyncEnvelopeType!\\n channelMeta: ChannelMetaInput!\\n operations: [OperationWithContextInput!]\\n cursor: RemoteCursorInput\\n key: String\\n dependsOn: [String!]\\n}\\n\\ninput RemoteFilterInput {\\n documentId: [String!]!\\n scope: [String!]!\\n branch: String!\\n}\\n\\ninput SyncRefusalInput {\\n documentId: String!\\n branch: String!\\n # \\\"marker\\\" for a refused purge marker; absent for UNSUPPORTED_PROTOCOL\\n kind: String\\n}\\n\\ninput TouchChannelInput {\\n id: String!\\n name: String!\\n collectionId: String!\\n filter: RemoteFilterInput!\\n sinceTimestampUtcMs: String!\\n # The client's peer manifest; absent from a client without peer agreement\\n manifest: JSONObject\\n}\\n\\ntype TouchChannelResult {\\n success: Boolean!\\n ackOrdinal: Int!\\n # The server's peer manifest\\n manifest: JSONObject\\n}\\n\\ntype Query {\\n # Get document models for a namespace\\n documentModels(\\n namespace: String\\n paging: PagingInput\\n ): DocumentModelResultPage!\\n\\n # Get a specific document by ID or slug\\n document(\\n idOrSlug: String\\n identifier: String @deprecated(reason: \\\"Use idOrSlug.\\\")\\n view: ViewFilterInput\\n consistency: ConsistencyTokenInput\\n ): DocumentWithChildren\\n\\n # Get outgoing relationships of a given type from a source document\\n documentOutgoingRelationships(\\n sourceIdOrSlug: String\\n sourceIdentifier: String @deprecated(reason: \\\"Use sourceIdOrSlug.\\\")\\n relationshipType: String!\\n view: ViewFilterInput\\n paging: PagingInput\\n consistency: ConsistencyTokenInput\\n ): PHDocumentResultPage!\\n\\n # Get incoming relationships of a given type to a target document\\n documentIncomingRelationships(\\n targetIdOrSlug: String\\n targetIdentifier: String @deprecated(reason: \\\"Use targetIdOrSlug.\\\")\\n relationshipType: String!\\n view: ViewFilterInput\\n paging: PagingInput\\n consistency: ConsistencyTokenInput\\n ): PHDocumentResultPage!\\n\\n # Get the outgoing relationship edges of a source document. Unlike\\n # documentOutgoingRelationships, which returns the documents at the far end,\\n # this returns the edges themselves, carrying their metadata and timestamps.\\n # Omit relationshipType to return edges of every type.\\n documentOutgoingRelationshipEdges(\\n sourceIdOrSlug: String\\n sourceIdentifier: String @deprecated(reason: \\\"Use sourceIdOrSlug.\\\")\\n relationshipType: String\\n view: ViewFilterInput\\n paging: PagingInput\\n consistency: ConsistencyTokenInput\\n ): DocumentRelationshipResultPage!\\n\\n # Get the incoming relationship edges of a target document. Unlike\\n # documentIncomingRelationships, which returns the documents at the far end,\\n # this returns the edges themselves, carrying their metadata and timestamps.\\n # Omit relationshipType to return edges of every type.\\n documentIncomingRelationshipEdges(\\n targetIdOrSlug: String\\n targetIdentifier: String @deprecated(reason: \\\"Use targetIdOrSlug.\\\")\\n relationshipType: String\\n view: ViewFilterInput\\n paging: PagingInput\\n consistency: ConsistencyTokenInput\\n ): DocumentRelationshipResultPage!\\n\\n # Find documents by search criteria\\n findDocuments(\\n search: SearchFilterInput\\n view: ViewFilterInput\\n paging: PagingInput\\n consistency: ConsistencyTokenInput\\n ): PHDocumentResultPage!\\n\\n # Get job status\\n jobStatus(jobId: String!): JobInfo\\n\\n # Whether findDocuments would serve the document to the caller. Absent or\\n # withheld is false; a server that cannot decide answers with an error.\\n documentServed(idOrSlug: String!, view: ViewFilterInput): Boolean!\\n\\n # The signature policy and protocol versions a new document gets, under the\\n # parent when one is named. A parent the caller may not read is refused.\\n # With documentType, protocolVersions fit that type's reducer.\\n createDefaults(parentIdOrSlug: String, documentType: String): CreateDefaults!\\n\\n # Get operations for a document with filtering and pagination\\n documentOperations(\\n filter: OperationsFilterInput!\\n paging: PagingInput\\n ): ReactorOperationResultPage!\\n\\n \\\"\\\"\\\"\\n Predicts whether the calling subject would be admitted to execute each of a\\n set of candidate operations, without submitting any of them. A UI asks this to\\n disable a control rather than offer an action that fails on submit.\\n\\n The answer is a prediction, not a promise:\\n\\n - Real admission compiles an append condition over everything it read and the\\n store enforces it at write time. A preflight reads no future, so a policy\\n change landing between this answer and the submit changes the verdict. The\\n submit path stays the only authority.\\n - The verdict is evaluated at the stream heads, so it is correct for a\\n candidate about to be submitted. A backdated submission is out of contract;\\n the reactor decides that one by position.\\n - A candidate whose verdict depends on its input has to carry that input, since\\n a conditional grant reads it.\\n\\n The subject is the authenticated caller and cannot be named in the request:\\n answering for an arbitrary subject would disclose what a policy grants\\n somebody else. It carries both the caller's address and the did:key of the app\\n instance whose token authenticated the request, so a policy naming either\\n matches the same principal the write path presents.\\n\\n Requires the reactor's authEnforcement feature flag. Without it the reactor\\n holds no decision model, so this fails with extensions.code\\n AUTH_EVALUATION_UNSUPPORTED rather than guessing.\\n \\\"\\\"\\\"\\n evaluateActions(\\n documentIdOrSlug: String\\n documentIdentifier: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n branch: String\\n candidates: [ActionCandidateInput!]!\\n ): ActionEvaluations!\\n\\n \\\"\\\"\\\"\\n Polls for sync envelopes from a channel.\\n\\n An operation stored before the API required an action id cannot be\\n represented by this schema, and rather than serving a partial response beside\\n a bare non-null violation, this fails with extensions.code\\n MALFORMED_STORED_OPERATION naming the operation. That code means the failure\\n is worth polling through: the document holding the operation needs repairing,\\n but the channel serves every other document, and a peer that stopped polling\\n would stop receiving those too.\\n \\\"\\\"\\\"\\n pollSyncEnvelopes(\\n channelId: String!\\n outboxAck: Int!\\n outboxLatest: Int!\\n # The client's manifest revision; absent from a client without peer agreement\\n manifestRevision: String\\n # Documents the client refused from earlier polls: held, or a refused marker\\n refusals: [SyncRefusalInput!]\\n ): PollSyncEnvelopesResult!\\n\\n # Supreme admin, or the address the named remote's channel is bound to\\n syncHolds(remoteName: String, documentId: String): [SyncHold!]!\\n\\n # Supreme admin, or an address bound to a channel in the collection\\n peerAgreement(collectionId: String!): PeerAgreement!\\n\\n # A drive's nodes, for every drive document type. Omit parentFolder for every\\n # node in the drive; pass null for the root level. A drive the caller may not\\n # read lists nothing, and a file node is listed only with its document.\\n driveNodes(\\n driveId: ID!\\n parentFolder: ID\\n paging: PagingInput\\n kind: DriveNodeKind\\n ): DriveNodePage!\\n\\n # One drive node; null when absent or withheld from the caller.\\n driveNode(driveId: ID!, id: ID!): DriveNode\\n\\n # Every node under root (inclusive) the caller may read.\\n driveDescendants(driveId: ID!, root: ID!): [DriveNode!]!\\n}\\n\\ntype Mutation {\\n # Create a new document\\n createDocument(\\n document: JSONObject!\\n parentIdOrSlug: String\\n parentIdentifier: String @deprecated(reason: \\\"Use parentIdOrSlug.\\\")\\n ): PHDocument!\\n\\n # Create an empty document of specified type\\n createEmptyDocument(\\n documentType: String!\\n parentIdOrSlug: String\\n parentIdentifier: String @deprecated(reason: \\\"Use parentIdOrSlug.\\\")\\n ): PHDocument!\\n\\n \\\"\\\"\\\"\\n Applies actions to a document and waits for the result.\\n\\n Each action is coerced against `ActionInput`, so one missing a field the wire\\n declares is refused before any work starts. The id in particular: it is hashed\\n into the operation id and replay dedupes by it, so an action without one is\\n stored under an operation id shared by every id-less operation on the same\\n document, scope and branch.\\n\\n Named for `IReactorClient.execute`, which this is the wire form of. `branch`\\n defaults to `main`.\\n \\\"\\\"\\\"\\n execute(\\n documentIdOrSlug: String\\n documentIdentifier: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n actions: [ActionInput!]!\\n branch: String\\n ): PHDocument!\\n\\n \\\"\\\"\\\"\\n Submits actions to a document and returns the job that will apply them.\\n\\n Coerced exactly as `execute` is, so a malformed action is refused here rather\\n than surfacing later as a failed job. Returns the job rather than only its id,\\n so a caller has the status and the creation time it would otherwise have to\\n ask for; `result` is null until the job produces one.\\n \\\"\\\"\\\"\\n executeAsync(\\n documentIdOrSlug: String\\n documentIdentifier: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n actions: [ActionInput!]!\\n branch: String\\n ): JobInfo!\\n\\n \\\"\\\"\\\"\\n Applies multiple mutation jobs in dependency order and waits for all of them,\\n the wire form of `IReactorClient.executeBatch`. Each job's actions are coerced\\n against `ActionInput` exactly as `execute` is, so client-signed actions pass\\n through unchanged, and `dependsOn` orders the jobs. It is synchronous: the jobs\\n are applied and awaited before the result returns, so every returned `JobInfo`\\n is a completed one rather than the pending receipt the in-process reactor hands\\n back. A batch is ordering, not a transaction: each job commits on its own, and\\n a failed job still releases the jobs that depend on it, so any job, before or\\n after a failure, may have committed. A failed job is therefore returned as a\\n FAILED entry with its `error` and `errorName`, beside the final state of every\\n other job, rather than failing the mutation. The mutation itself fails only\\n when no job state can be reported.\\n\\n A job carrying `CREATE_DOCUMENT` must be the batch's only job, with the create\\n as its first action naming the job's document. Its other actions may only be\\n an `UPGRADE_DOCUMENT` of the new document and `ADD_RELATIONSHIP`s targeting\\n it. It is authorized like `createDocument`: write on every source of those\\n relationships, or the right to create when there is none.\\n \\\"\\\"\\\"\\n executeBatch(jobs: [ExecutionJobInput!]!): BatchExecutionResult!\\n\\n # Apply actions to a document (synchronous)\\n mutateDocument(\\n documentIdentifier: String!\\n actions: [JSONObject!]!\\n view: ViewFilterInput\\n ): PHDocument!\\n @deprecated(\\n reason: \\\"Use execute. Actions here are untyped, so a malformed one is refused by a hand-written check rather than by the schema, and `view.scopes` is accepted but ignored.\\\"\\n )\\n\\n # Submit actions to a document (asynchronous)\\n mutateDocumentAsync(\\n documentIdentifier: String!\\n actions: [JSONObject!]!\\n view: ViewFilterInput\\n ): String!\\n @deprecated(\\n reason: \\\"Use executeAsync, which is typed and returns the job rather than only its id.\\\"\\n )\\n\\n # Rename a document\\n renameDocument(\\n documentIdOrSlug: String\\n documentIdentifier: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n name: String!\\n branch: String\\n ): PHDocument!\\n\\n # Update the preferred editor recorded in the document header meta.\\n # Pass null/omit to clear it.\\n setPreferredEditor(\\n documentIdOrSlug: String\\n documentIdentifier: String @deprecated(reason: \\\"Use documentIdOrSlug.\\\")\\n preferredEditor: String\\n branch: String\\n ): PHDocument!\\n\\n # Add a relationship between two documents. Adding one that already exists is\\n # a no-op, metadata included -- use updateRelationship to change an edge.\\n addRelationship(\\n sourceIdOrSlug: String\\n sourceIdentifier: String @deprecated(reason: \\\"Use sourceIdOrSlug.\\\")\\n targetIdOrSlug: String\\n targetIdentifier: String @deprecated(reason: \\\"Use targetIdOrSlug.\\\")\\n relationshipType: String!\\n metadata: JSONObject\\n branch: String\\n ): PHDocument!\\n\\n # Replace the metadata of an existing relationship, preserving its createdAt.\\n # Omitting metadata, or passing null, clears it.\\n updateRelationship(\\n sourceIdOrSlug: String\\n sourceIdentifier: String @deprecated(reason: \\\"Use sourceIdOrSlug.\\\")\\n targetIdOrSlug: String\\n targetIdentifier: String @deprecated(reason: \\\"Use targetIdOrSlug.\\\")\\n relationshipType: String!\\n metadata: JSONObject\\n branch: String\\n ): PHDocument!\\n\\n # Remove a relationship between two documents\\n removeRelationship(\\n sourceIdOrSlug: String\\n sourceIdentifier: String @deprecated(reason: \\\"Use sourceIdOrSlug.\\\")\\n targetIdOrSlug: String\\n targetIdentifier: String @deprecated(reason: \\\"Use targetIdOrSlug.\\\")\\n relationshipType: String!\\n branch: String\\n ): PHDocument!\\n\\n # Move a relationship from one source to another\\n moveRelationship(\\n sourceParentIdOrSlug: String\\n sourceParentIdentifier: String\\n @deprecated(reason: \\\"Use sourceParentIdOrSlug.\\\")\\n targetParentIdOrSlug: String\\n targetParentIdentifier: String\\n @deprecated(reason: \\\"Use targetParentIdOrSlug.\\\")\\n targetIdOrSlug: String\\n targetIdentifier: String @deprecated(reason: \\\"Use targetIdOrSlug.\\\")\\n relationshipType: String!\\n branch: String\\n ): MoveRelationshipResult!\\n\\n # Delete a single document\\n deleteDocument(\\n idOrSlug: String\\n identifier: String @deprecated(reason: \\\"Use idOrSlug.\\\")\\n propagate: PropagationMode\\n ): Boolean!\\n\\n # Delete multiple documents\\n deleteDocuments(\\n idsOrSlugs: [String!]\\n identifiers: [String!] @deprecated(reason: \\\"Use idsOrSlugs.\\\")\\n propagate: PropagationMode\\n ): Boolean!\\n\\n # Touch (create or update) a channel for sync\\n touchChannel(input: TouchChannelInput!): TouchChannelResult!\\n\\n # Push sync envelopes to a channel\\n pushSyncEnvelopes(\\n envelopes: [SyncEnvelopeInput!]!\\n # The server's manifest revision the client gated these envelopes under\\n peerManifestRevision: String\\n ): Boolean!\\n}\\n\\ntype Subscription {\\n # Subscribe to document changes\\n documentChanges(\\n search: SearchFilterInput\\n view: ViewFilterInput\\n ): DocumentChangeEvent!\\n\\n # Subscribe to job changes\\n jobChanges(jobId: String!): JobChangeEvent!\\n}\\n\"","import { gql } from \"graphql-tag\";\n\nexport const systemTypeDefs = gql`\n type SystemInfo {\n version: String!\n gitHash: String!\n gitUrl: String\n }\n\n type Query {\n system: SystemInfo!\n }\n`;\n","import { reactorDriveDocumentModelModule } from \"@powerhousedao/reactor-drive\";\nimport { ReactorGroupV1 } from \"@powerhousedao/reactor-group\";\nimport { driveDocumentModelModule } from \"@powerhousedao/shared/document-drive\";\nimport type { DocumentModelModule } from \"@powerhousedao/shared/document-model\";\nimport { documentModelDocumentModelModule } from \"document-model\";\n\n/** The models every host loads before any package's, by source package. */\nexport const baseDocumentModels: ReadonlyArray<\n readonly [string, DocumentModelModule]\n> = [\n [\n \"document-drive\",\n driveDocumentModelModule as unknown as DocumentModelModule,\n ],\n [\n \"document-model\",\n documentModelDocumentModelModule as unknown as DocumentModelModule,\n ],\n [\n \"reactor-drive\",\n reactorDriveDocumentModelModule as unknown as DocumentModelModule,\n ],\n [\"reactor-group\", ReactorGroupV1 as unknown as DocumentModelModule],\n];\n"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,IAAA,mBAAA;;;ACmBA,MAAa,wCAAwC,IAAI,IAAI;AAE7D,SAAgB,mBAAmB,GAAmB,GAAmB;CACvE,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO;CAC9B,KAAK,MAAM,CAAC,MAAM,WAAW,GAAG;EAC9B,MAAM,QAAQ,EAAE,IAAI,IAAI;EACxB,IACE,OAAO,eAAe,OAAO,cAC7B,MAAM,gBAAgB,OAAO,aAE7B,OAAO;CAEX;CACA,OAAO;AACT;AAEA,MAAa,mBAAmB,cAC7B,KAAK,EAAE,WAAW,UAAU,MAAM,CAAC,CACnC,KAAK,IAAI;AAEZ,MAAa,mBAAmB,OAAO,YACrC,cAAc,KAAK,EAAE,WAAW,CAC9B,MACA,IAAI,kBAAkB;CACpB,YAAY,UAAU;CACtB,aAAa,UAAU;CACvB,cAAc;CACd,GAAI,SAAS,eACT,kBAAkB,SAAS,IAC3B,SAAS,YACP,YAAY,SAAS,IACrB,CAAC;CACP;AACF,CAAC,CACH,CAAC,CACH;AAEA,SAAS,YAAY,KAAyB;CAC5C,IAAI,QAAQ;CACZ,MAAM,KAAK,EACT,WAAW;EACT,QAAQ;CACV,EACF,CAAC;CACD,OAAO;AACT;AAEA,SAAS,aAAa,OAAwD;CAC5E,IAAI;EACF,MAAM,OAAgB,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC;EACtD,OAAO,kBAAkB,MAAM,KAAK,IAAI,EAAE,KAAK,IAAI,KAAA;CACrD,QAAQ;EACN;CACF;AACF;AAEA,SAAS,KAAK,OAAwB;CACpC,I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-f5342ed231ba"}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { DefinitionNode, DocumentNode, GraphQLScalarType } from "graphql";
|
|
2
|
+
import { DocumentModelGlobalState, DocumentModelModule } from "@powerhousedao/shared/document-model";
|
|
3
|
+
import { ScalarDefinition } from "document-model/scalars";
|
|
4
|
+
import { GraphQLResolverMap, GraphQLSchemaModule } from "@apollo/subgraph";
|
|
5
|
+
import { Context } from "@powerhousedao/reactor-api";
|
|
6
|
+
//#region src/utils/scalar-types.d.ts
|
|
7
|
+
type RegisteredScalar = {
|
|
8
|
+
readonly definition: ScalarDefinition;
|
|
9
|
+
readonly packageName: string;
|
|
10
|
+
};
|
|
11
|
+
/** The scalars packages register through their `./scalars` entry, by name. */
|
|
12
|
+
type ScalarRegistry = ReadonlyMap<string, RegisteredScalar>;
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/utils/create-schema.d.ts
|
|
15
|
+
/**
|
|
16
|
+
* A subgraph defines a type whose name the generated document-model schema
|
|
17
|
+
* owns, so one of the two definitions would be lost.
|
|
18
|
+
*/
|
|
19
|
+
declare class SubgraphTypeCollisionError extends Error {
|
|
20
|
+
readonly typeNames: string[];
|
|
21
|
+
constructor(typeNames: string[]);
|
|
22
|
+
}
|
|
23
|
+
type SubgraphSchemaOptions = {
|
|
24
|
+
/**
|
|
25
|
+
* Types the subgraph's own schema generator emits, as a document model's
|
|
26
|
+
* subgraph has. These may repeat a generated definition, which is kept.
|
|
27
|
+
*/
|
|
28
|
+
ownTypeNames?: ReadonlySet<string>;
|
|
29
|
+
} & ({
|
|
30
|
+
/** Generated types already built for `documentModels`, with their scalars. */
|
|
31
|
+
generated?: GeneratedDocumentModelTypes;
|
|
32
|
+
scalars?: never;
|
|
33
|
+
} | {
|
|
34
|
+
generated?: never;
|
|
35
|
+
scalars?: ScalarRegistry;
|
|
36
|
+
});
|
|
37
|
+
declare const buildSubgraphSchemaModule: (documentModels: DocumentModelModule[], resolvers: GraphQLResolverMap<Context>, typeDefs: DocumentNode, options?: SubgraphSchemaOptions) => GraphQLSchemaModule;
|
|
38
|
+
declare const createSchema: (documentModels: DocumentModelModule[], resolvers: GraphQLResolverMap<Context>, typeDefs: DocumentNode, options?: SubgraphSchemaOptions) => import("graphql").GraphQLSchema;
|
|
39
|
+
/**
|
|
40
|
+
* Create a merged GraphQL schema from multiple subgraph modules.
|
|
41
|
+
* Uses buildSubgraphSchema's array overload to combine type definitions
|
|
42
|
+
* and resolvers from multiple subgraphs into a single executable schema.
|
|
43
|
+
*/
|
|
44
|
+
declare const createMergedSchema: (modules: GraphQLSchemaModule[]) => import("graphql").GraphQLSchema;
|
|
45
|
+
declare function getDocumentModelSchemaName(documentModel: DocumentModelGlobalState): string;
|
|
46
|
+
/** The name the model's own subgraph registers under. */
|
|
47
|
+
declare function getDocumentModelSubgraphName(documentModel: DocumentModelGlobalState): string;
|
|
48
|
+
/**
|
|
49
|
+
* The generated document-model types followed by the subgraph's own. Throws
|
|
50
|
+
* {@link SubgraphTypeCollisionError} when the subgraph defines a generated
|
|
51
|
+
* name not in `ownTypeNames`.
|
|
52
|
+
*/
|
|
53
|
+
declare const getDocumentModelTypeDefs: (documentModels: DocumentModelModule[], typeDefs: DocumentNode, ownTypeNames?: ReadonlySet<string>) => DocumentNode;
|
|
54
|
+
/** Names of the type definitions in `doc`. */
|
|
55
|
+
declare function typeDefinitionNames(doc: DocumentNode): Set<string>;
|
|
56
|
+
/** The generated document-model schema every subgraph is assembled onto. */
|
|
57
|
+
type GeneratedDocumentModelTypes = {
|
|
58
|
+
definitions: readonly DefinitionNode[];
|
|
59
|
+
names: ReadonlySet<string>;
|
|
60
|
+
scalars: ScalarRegistry;
|
|
61
|
+
};
|
|
62
|
+
/** The part of a document model module its schema is built from. */
|
|
63
|
+
type DocumentModelSource = {
|
|
64
|
+
documentModel: {
|
|
65
|
+
global: DocumentModelGlobalState;
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
/** Type name → whether every definition of that name is a scalar. */
|
|
69
|
+
type ReservedTypeNames = ReadonlyMap<string, boolean>;
|
|
70
|
+
/**
|
|
71
|
+
* Type names no document model may generate: the root types, the generated
|
|
72
|
+
* types every schema carries, and the types of `coreTypeDefs`.
|
|
73
|
+
*/
|
|
74
|
+
declare function reservedTypeNames(coreTypeDefs: Iterable<DocumentNode>): ReservedTypeNames;
|
|
75
|
+
/**
|
|
76
|
+
* The reserved names `documentModel`'s generated types take. A scalar may
|
|
77
|
+
* repeat a reserved scalar: the duplicate is dropped on assembly.
|
|
78
|
+
*/
|
|
79
|
+
declare function reservedTypeNamesTaken(documentModel: DocumentModelSource, reserved: ReservedTypeNames, definitions?: readonly DefinitionNode[]): string[];
|
|
80
|
+
/**
|
|
81
|
+
* The generated schema for `documentModels`. `schemas` supplies models'
|
|
82
|
+
* definitions already built; the others are built here.
|
|
83
|
+
*/
|
|
84
|
+
declare function getGeneratedDocumentModelTypes(documentModels: readonly DocumentModelSource[], schemas?: ReadonlyMap<DocumentModelSource, DocumentModelSchema>, scalars?: ScalarRegistry): GeneratedDocumentModelTypes;
|
|
85
|
+
/** {@link getGeneratedDocumentModelTypes} from the models' global states. */
|
|
86
|
+
declare function generatedTypesOf(documentModels: readonly DocumentModelGlobalState[]): GeneratedDocumentModelTypes;
|
|
87
|
+
/** What a document model contributes to the GraphQL schema. */
|
|
88
|
+
type DocumentModelSchema = {
|
|
89
|
+
/** Its definitions in the generated schema every subgraph carries. */
|
|
90
|
+
generated: readonly DefinitionNode[];
|
|
91
|
+
/** Its own subgraph's types, when it has operations to serve. */
|
|
92
|
+
subgraph?: {
|
|
93
|
+
typeDefs: DocumentNode;
|
|
94
|
+
typeNames: ReadonlySet<string>;
|
|
95
|
+
};
|
|
96
|
+
/** Why its own subgraph cannot be served; its generated types still can. */
|
|
97
|
+
subgraphError?: Error;
|
|
98
|
+
};
|
|
99
|
+
/** Whether any operation of the latest specification has a schema. */
|
|
100
|
+
declare function hasOperationSchemas(documentModel: DocumentModelGlobalState): boolean;
|
|
101
|
+
/** The types of a document model's own subgraph. */
|
|
102
|
+
declare function documentModelSubgraphTypes(documentModel: DocumentModelGlobalState): {
|
|
103
|
+
typeDefs: DocumentNode;
|
|
104
|
+
typeNames: ReadonlySet<string>;
|
|
105
|
+
};
|
|
106
|
+
/** Throws when the generated types every subgraph carries do not build. */
|
|
107
|
+
declare function buildDocumentModelSchema(documentModel: DocumentModelSource, options?: {
|
|
108
|
+
subgraph?: boolean;
|
|
109
|
+
}): DocumentModelSchema;
|
|
110
|
+
/** A document model's schema, or why it is unusable, under its source key. */
|
|
111
|
+
type ResolvedDocumentModelSchema<T extends DocumentModelSource = DocumentModelModule> = {
|
|
112
|
+
model: T;
|
|
113
|
+
key: string;
|
|
114
|
+
} & ({
|
|
115
|
+
schema: DocumentModelSchema;
|
|
116
|
+
error?: undefined;
|
|
117
|
+
} | {
|
|
118
|
+
schema?: undefined;
|
|
119
|
+
error: Error;
|
|
120
|
+
});
|
|
121
|
+
/** Schemas and failures by source hash, for the last resolve's models only. */
|
|
122
|
+
declare class DocumentModelSchemaCache<T extends DocumentModelSource = DocumentModelModule> {
|
|
123
|
+
#private;
|
|
124
|
+
constructor(build?: (documentModel: T) => DocumentModelSchema);
|
|
125
|
+
resolve(documentModels: readonly T[]): ResolvedDocumentModelSchema<T>[];
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Names of the generated types `typeDefs` redefines, other than those a
|
|
129
|
+
* model's own subgraph may repeat. Scalars are dropped on assembly, so they
|
|
130
|
+
* never collide.
|
|
131
|
+
*/
|
|
132
|
+
declare function findSubgraphTypeCollisions(generated: Pick<GeneratedDocumentModelTypes, "names">, typeDefs: DocumentNode, ownTypeNames?: ReadonlySet<string>): string[];
|
|
133
|
+
/** Throws {@link SubgraphTypeCollisionError}; see {@link getDocumentModelTypeDefs}. */
|
|
134
|
+
declare function assembleSubgraphTypeDefs(generated: GeneratedDocumentModelTypes, typeDefs: DocumentNode, ownTypeNames?: ReadonlySet<string>): DocumentNode;
|
|
135
|
+
/**
|
|
136
|
+
* Options for generating document model GraphQL schemas.
|
|
137
|
+
*/
|
|
138
|
+
interface DocumentModelSchemaOptions {
|
|
139
|
+
/**
|
|
140
|
+
* When true, generates new API patterns:
|
|
141
|
+
* - Mutations return full document objects (MutationResult type)
|
|
142
|
+
* - Adds createEmptyDocument mutation
|
|
143
|
+
* - Makes docId and input parameters required
|
|
144
|
+
* @default false
|
|
145
|
+
*/
|
|
146
|
+
useNewApi?: boolean;
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Generate a GraphQL schema for a document model.
|
|
150
|
+
*
|
|
151
|
+
* @param documentModel - The document model global state
|
|
152
|
+
* @param options - Schema generation options
|
|
153
|
+
* @returns GraphQL DocumentNode
|
|
154
|
+
*/
|
|
155
|
+
declare function generateDocumentModelSchema(documentModel: DocumentModelGlobalState, options?: DocumentModelSchemaOptions): DocumentNode;
|
|
156
|
+
//#endregion
|
|
157
|
+
export { hasOperationSchemas as C, RegisteredScalar as D, typeDefinitionNames as E, ScalarRegistry as O, getGeneratedDocumentModelTypes as S, reservedTypeNamesTaken as T, generateDocumentModelSchema as _, GeneratedDocumentModelTypes as a, getDocumentModelSubgraphName as b, SubgraphSchemaOptions as c, buildDocumentModelSchema as d, buildSubgraphSchemaModule as f, findSubgraphTypeCollisions as g, documentModelSubgraphTypes as h, DocumentModelSource as i, SubgraphTypeCollisionError as l, createSchema as m, DocumentModelSchemaCache as n, ReservedTypeNames as o, createMergedSchema as p, DocumentModelSchemaOptions as r, ResolvedDocumentModelSchema as s, DocumentModelSchema as t, assembleSubgraphTypeDefs as u, generatedTypesOf as v, reservedTypeNames as w, getDocumentModelTypeDefs as x, getDocumentModelSchemaName as y };
|
|
158
|
+
export {};
|
|
159
|
+
//# sourceMappingURL=create-schema-Dio_7akA.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"create-schema-Dio_7akA.d.mts","names":[],"sources":["../src/utils/scalar-types.ts","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