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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +7 -2
  2. package/dist/{adapter-gateway-apollo-CxJNBVyD.mjs → adapter-gateway-apollo-D-EdZ4e-.mjs} +23 -23
  3. package/dist/adapter-gateway-apollo-D-EdZ4e-.mjs.map +1 -0
  4. package/dist/{adapter-gateway-mercurius-CZVy88Za.mjs → adapter-gateway-mercurius-CdxLge5p.mjs} +4 -12
  5. package/dist/adapter-gateway-mercurius-CdxLge5p.mjs.map +1 -0
  6. package/dist/{adapter-http-express-B39rPhqH.mjs → adapter-http-express-78KD77cI.mjs} +11 -11
  7. package/dist/adapter-http-express-78KD77cI.mjs.map +1 -0
  8. package/dist/{adapter-http-fastify-BwXO6rqE.mjs → adapter-http-fastify-Dk7aT_xw.mjs} +14 -13
  9. package/dist/adapter-http-fastify-Dk7aT_xw.mjs.map +1 -0
  10. package/dist/base-document-models-caJpqTLw.mjs +2083 -0
  11. package/dist/base-document-models-caJpqTLw.mjs.map +1 -0
  12. package/dist/create-schema-BCArFBv9.d.mts +167 -0
  13. package/dist/create-schema-BCArFBv9.d.mts.map +1 -0
  14. package/dist/error-info-Cr6oQACe.mjs +601 -0
  15. package/dist/error-info-Cr6oQACe.mjs.map +1 -0
  16. package/dist/index.d.mts +3180 -1021
  17. package/dist/index.d.mts.map +1 -1
  18. package/dist/index.mjs +7197 -2728
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/package-subgraph-check-BxKx9kcQ.mjs +138 -0
  21. package/dist/package-subgraph-check-BxKx9kcQ.mjs.map +1 -0
  22. package/dist/pglite-like-CKQEL_Q0.d.mts +27 -0
  23. package/dist/pglite-like-CKQEL_Q0.d.mts.map +1 -0
  24. package/dist/pglite-node-CcX2YT-l.mjs +744 -0
  25. package/dist/pglite-node-CcX2YT-l.mjs.map +1 -0
  26. package/dist/rolldown-runtime-8H4AJuhK.mjs +16 -0
  27. package/dist/run-node-handler-CQjyjOuN.mjs +52 -0
  28. package/dist/run-node-handler-CQjyjOuN.mjs.map +1 -0
  29. package/dist/src/graphql/subgraph-types.d.mts +43 -0
  30. package/dist/src/graphql/subgraph-types.d.mts.map +1 -0
  31. package/dist/src/graphql/subgraph-types.mjs +14 -0
  32. package/dist/src/graphql/subgraph-types.mjs.map +1 -0
  33. package/dist/src/packages/https-hooks.d.mts +4 -4
  34. package/dist/src/packages/https-hooks.d.mts.map +1 -1
  35. package/dist/src/packages/https-hooks.mjs +2 -2
  36. package/dist/src/packages/https-hooks.mjs.map +1 -1
  37. package/dist/src/packages/vite-loader.d.mts +30 -9
  38. package/dist/src/packages/vite-loader.d.mts.map +1 -1
  39. package/dist/src/packages/vite-loader.mjs +205 -85
  40. package/dist/src/packages/vite-loader.mjs.map +1 -1
  41. package/dist/src/pglite/pglite-node.d.mts +434 -0
  42. package/dist/src/pglite/pglite-node.d.mts.map +1 -0
  43. package/dist/src/pglite/pglite-node.mjs +5 -0
  44. package/dist/src/pglite/worker/entry.d.mts +2 -0
  45. package/dist/src/pglite/worker/entry.mjs +298 -0
  46. package/dist/src/pglite/worker/entry.mjs.map +1 -0
  47. package/dist/subgraph-extraction-C_hFvSaS.mjs +1884 -0
  48. package/dist/subgraph-extraction-C_hFvSaS.mjs.map +1 -0
  49. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs +10 -0
  50. package/dist/subgraph-schema-owner-BEjuk2Xv.mjs.map +1 -0
  51. package/dist/types-Bz_xjf8j.d.mts +105 -0
  52. package/dist/types-Bz_xjf8j.d.mts.map +1 -0
  53. package/package.json +39 -26
  54. package/dist/adapter-gateway-apollo-CxJNBVyD.mjs.map +0 -1
  55. package/dist/adapter-gateway-apollo-DowrX6E_.mjs +0 -4
  56. package/dist/adapter-gateway-mercurius-CZVy88Za.mjs.map +0 -1
  57. package/dist/adapter-gateway-stitching-CaZjvRzx.mjs +0 -316
  58. package/dist/adapter-gateway-stitching-CaZjvRzx.mjs.map +0 -1
  59. package/dist/adapter-http-express-B39rPhqH.mjs.map +0 -1
  60. package/dist/adapter-http-fastify-BwXO6rqE.mjs.map +0 -1
  61. package/dist/path-normalize-BOQwY9wR.mjs +0 -23
  62. package/dist/path-normalize-BOQwY9wR.mjs.map +0 -1
  63. package/dist/types-DcYyNcHJ.d.mts +0 -48
  64. package/dist/types-DcYyNcHJ.d.mts.map +0 -1
  65. package/dist/utils-XWVecaNn.mjs +0 -653
  66. package/dist/utils-XWVecaNn.mjs.map +0 -1
  67. package/dist/websocket-DncAB9XK.mjs +0 -18
  68. package/dist/websocket-DncAB9XK.mjs.map +0 -1
@@ -0,0 +1,2083 @@
1
+
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7047ae02-c917-5a70-b56d-3b9b84ac2d2a")}catch(e){}}();
3
+ import { childLogger, documentModelDocumentModelModule, inspectDocumentModelDefinition, projectDocumentModelGraphQL } from "document-model";
4
+ import { gql } from "graphql-tag";
5
+ import { GraphQLScalarType, Kind, Lexer, Source, TokenKind, isTypeDefinitionNode, isTypeExtensionNode, parse, print, valueFromASTUntyped, visit } from "graphql";
6
+ import { createHash } from "node:crypto";
7
+ import { scalarCatalog } from "document-model/scalars";
8
+ import { z } from "zod";
9
+ import { camelCase, constantCase, kebabCase, pascalCase } from "change-case";
10
+ import { GraphQLJSON, GraphQLJSONObject } from "graphql-type-json";
11
+ import { inspect, isDeepStrictEqual } from "node:util";
12
+ import { buildSubgraphSchema } from "@apollo/subgraph";
13
+ import { reactorDriveDocumentModelModule } from "@powerhousedao/reactor-drive";
14
+ import { ReactorGroupV1 } from "@powerhousedao/reactor-group";
15
+ import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
16
+ //#region src/graphql/auth/schema.graphql
17
+ var schema_default$1 = "# 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";
18
+ //#endregion
19
+ //#region src/utils/scalar-types.ts
20
+ const EMPTY_SCALAR_REGISTRY = /* @__PURE__ */ new Map();
21
+ function sameScalarRegistry(a, b) {
22
+ if (a.size !== b.size) return false;
23
+ for (const [name, scalar] of a) {
24
+ const other = b.get(name);
25
+ if (other?.definition !== scalar.definition || other.packageName !== scalar.packageName) return false;
26
+ }
27
+ return true;
28
+ }
29
+ const catalogScalarSdl = scalarCatalog.map(({ name }) => `scalar ${name}`).join("\n");
30
+ const catalogResolvers = Object.fromEntries(scalarCatalog.map(({ name }) => [name, new GraphQLScalarType({
31
+ serialize: (value) => value,
32
+ parseValue: (value) => value,
33
+ parseLiteral: valueFromASTUntyped,
34
+ ...name === "JSONObject" ? GraphQLJSONObject.toConfig() : name === "Unknown" ? GraphQLJSON.toConfig() : {},
35
+ name
36
+ })]));
37
+ function hasVariable(ast) {
38
+ let found = false;
39
+ visit(ast, { Variable() {
40
+ found = true;
41
+ } });
42
+ return found;
43
+ }
44
+ function losslessJson(value) {
45
+ try {
46
+ const json = JSON.parse(JSON.stringify(value));
47
+ return isDeepStrictEqual(json, value) ? { json } : void 0;
48
+ } catch {
49
+ return;
50
+ }
51
+ }
52
+ function show(value) {
53
+ try {
54
+ return losslessJson(value) ? JSON.stringify(value) : inspect(value, {
55
+ customInspect: false,
56
+ breakLength: Infinity
57
+ });
58
+ } catch {
59
+ return "a value that cannot be printed";
60
+ }
61
+ }
62
+ /** Validates with the definition's schema and accepts only a canonical value. */
63
+ function registeredScalarType(definition) {
64
+ const check = (value) => {
65
+ const result = definition.schema.safeParse(value);
66
+ if (!result.success) throw new Error(`${definition.name}: ${z.prettifyError(result.error)}`);
67
+ const output = losslessJson(result.data);
68
+ if (!output) throw new Error(`${definition.name}: the schema output is not JSON: ${show(result.data)}`);
69
+ const reparsed = definition.schema.safeParse(output.json);
70
+ if (reparsed.success && isDeepStrictEqual(reparsed.data, result.data)) return result.data;
71
+ const outcome = reparsed.success ? `parses to ${show(reparsed.data)}.` : `fails it: ${z.prettifyError(reparsed.error)}`;
72
+ throw new Error(`${definition.name}: the schema must accept its own output unchanged, but ${show(result.data)} ${outcome}`);
73
+ };
74
+ return new GraphQLScalarType({
75
+ name: definition.name,
76
+ description: definition.description,
77
+ serialize: (value) => value,
78
+ parseValue: check,
79
+ parseLiteral: (ast, variables) => {
80
+ if (variables == null && hasVariable(ast)) return null;
81
+ return check(valueFromASTUntyped(ast, variables));
82
+ }
83
+ });
84
+ }
85
+ //#endregion
86
+ //#region src/graphql/model-schema-templates.ts
87
+ /**
88
+ * Revision type - matches the definition in reactor/schema.graphql.
89
+ * Used by PHDocument and document mutation results.
90
+ */
91
+ const RevisionType = `
92
+ type Revision {
93
+ scope: String!
94
+ revision: Int!
95
+ }
96
+ `;
97
+ const hasValidSchema = (schema) => !!(schema && /\b(input|type|enum|union|interface)\s+\w+/.test(schema));
98
+ function getDocumentModelSchemaName(documentModel) {
99
+ return pascalCase(documentModel.name.replaceAll("/", " "));
100
+ }
101
+ function generateModelSchema(projection, options) {
102
+ return options.useNewApi === true ? generateNewApiSchema(projection) : generateLegacyApiSchema(projection);
103
+ }
104
+ /**
105
+ * The modules' operation schemas. The first definition of each module carries
106
+ * a "Module: <Name>" description unless it has its own.
107
+ */
108
+ function printModuleSchemas(modules) {
109
+ return modules.map(({ name, sdl }) => {
110
+ const document = parse(sdl);
111
+ const [first, ...rest] = document.definitions;
112
+ if ("description" in first && first.description === void 0) return print({
113
+ ...document,
114
+ definitions: [{
115
+ ...first,
116
+ description: {
117
+ kind: Kind.STRING,
118
+ value: `Module: ${pascalCase(name)}`,
119
+ block: true
120
+ }
121
+ }, ...rest]
122
+ });
123
+ return print(document);
124
+ }).join("\n");
125
+ }
126
+ /**
127
+ * Generate legacy API schema with nested queries
128
+ */
129
+ function generateLegacyApiSchema(projection) {
130
+ const { documentName } = projection;
131
+ const createDocumentMutation = `${documentName}_createDocument(name:String!, driveId:String): String`;
132
+ const operationMutations = projection.operations.map(({ camelName, inputTypeName }) => `${documentName}_${camelName}(
133
+ driveId: String, docId: PHID, input: ${inputTypeName}): Int`).join("\n ");
134
+ return gql`
135
+ """
136
+ Queries: ${documentName} Document
137
+ """
138
+
139
+ type ${documentName}Queries {
140
+ getDocument(docId: PHID!, driveId: PHID): ${documentName}
141
+ getDocuments(driveId: String!): [${documentName}!]
142
+ }
143
+
144
+ type Query {
145
+ ${documentName}: ${documentName}Queries
146
+ }
147
+
148
+ """
149
+ Mutations: ${documentName}
150
+ """
151
+ type Mutation {
152
+ ${createDocumentMutation}
153
+
154
+ ${operationMutations}
155
+ }
156
+
157
+ ${projection.stateInputTypes ? `"""
158
+ Input Types from State Schema
159
+ """
160
+ ${projection.stateInputTypes}` : ""}
161
+
162
+ ${printModuleSchemas(projection.modules)}`;
163
+ }
164
+ /**
165
+ * Generate new API schema with flat queries, typed state, and async mutations.
166
+ * Note: State schema types are NOT included here because they are already defined
167
+ * in getDocumentModelTypeDefs() which is used during schema composition.
168
+ * Including them here would cause duplicate type definitions.
169
+ */
170
+ function generateNewApiSchema(projection) {
171
+ const { documentName } = projection;
172
+ const stateType = `${documentName}_FullState!`;
173
+ const sharedBaseTypes = `
174
+ """Hash configuration for document state"""
175
+ type ${documentName}_PHHashConfig {
176
+ algorithm: String!
177
+ encoding: String!
178
+ }
179
+
180
+ """Document scope state (same for all document types)"""
181
+ type ${documentName}_PHDocumentScopeState {
182
+ version: Int!
183
+ hash: ${documentName}_PHHashConfig!
184
+ isDeleted: Boolean
185
+ deletedAtUtcIso: String
186
+ deletedBy: String
187
+ deletionReason: String
188
+ }
189
+ `;
190
+ const fullStateType = `
191
+ """Full state with all scopes for ${documentName}"""
192
+ type ${documentName}_FullState {
193
+ auth: JSONObject!
194
+ document: ${documentName}_PHDocumentScopeState!
195
+ global: ${`${projection.globalStateTypeName}!`}
196
+ local: ${projection.localStateTypeName === null ? "JSONObject!" : `${projection.localStateTypeName}!`}
197
+ }
198
+ `;
199
+ const commonInputTypes = `
200
+ input ${documentName}_ViewFilterInput {
201
+ branch: String
202
+ scopes: [String!]
203
+ }
204
+
205
+ input ${documentName}_PagingInput {
206
+ limit: Int
207
+ offset: Int
208
+ cursor: String
209
+ }
210
+
211
+ input ${documentName}_SearchFilterInput {
212
+ parentId: String
213
+ identifiers: [String!] @deprecated(reason: "Ignored. Filter by parentId.")
214
+ }
215
+ `;
216
+ const resultTypes = `
217
+ """
218
+ Mutation result type for ${documentName} operations with typed state.
219
+ Matches ReactorSubgraph PHDocument pattern with revisionsList.
220
+ """
221
+ type ${documentName}MutationResult {
222
+ id: String!
223
+ slug: String
224
+ preferredEditor: String
225
+ name: String!
226
+ documentType: String!
227
+ state: ${stateType}
228
+ revisionsList: [Revision!]!
229
+ createdAtUtcIso: DateTime!
230
+ lastModifiedAtUtcIso: DateTime!
231
+ }
232
+
233
+ """
234
+ Document with children for ${documentName}
235
+ """
236
+ type ${documentName}_DocumentWithChildren {
237
+ document: ${documentName}MutationResult!
238
+ childIds: [String!]!
239
+ }
240
+
241
+ """
242
+ Paginated result type for ${documentName} documents
243
+ """
244
+ type ${documentName}_DocumentResultPage {
245
+ items: [${documentName}MutationResult!]!
246
+ hasNextPage: Boolean!
247
+ hasPreviousPage: Boolean!
248
+ cursor: String
249
+ }
250
+ `;
251
+ const queries = `
252
+ type ${documentName}Queries {
253
+ """Get a specific ${documentName} document by identifier"""
254
+ document(idOrSlug: String, identifier: String @deprecated(reason: "Use idOrSlug."), view: ${documentName}_ViewFilterInput): ${documentName}_DocumentWithChildren
255
+
256
+ """Get all ${documentName} documents (paged)"""
257
+ documents(paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
258
+
259
+ """Find ${documentName} documents by search criteria"""
260
+ findDocuments(search: ${documentName}_SearchFilterInput, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
261
+
262
+ """Get outgoing relationships of a ${documentName} document"""
263
+ documentOutgoingRelationships(sourceIdOrSlug: String, sourceIdentifier: String @deprecated(reason: "Use sourceIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
264
+
265
+ """Get incoming relationships to a ${documentName} document"""
266
+ documentIncomingRelationships(targetIdOrSlug: String, targetIdentifier: String @deprecated(reason: "Use targetIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
267
+ }
268
+ `;
269
+ const { initialState } = projection;
270
+ const initialStateInputSchema = initialState.scopes.length === 0 ? "" : [initialState.inputTypes, `input ${documentName}_InitialStateInput {\n${initialState.scopes.map(({ name, type }) => ` ${name}: ${type}`).join("\n")}\n}`].filter(Boolean).join("\n\n");
271
+ const createDocumentMutation = initialStateInputSchema ? `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug."), slug: String, preferredEditor: String, initialState: ${documentName}_InitialStateInput): ${documentName}MutationResult!` : `createDocument(name: String!, parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug."), preferredEditor: String): ${documentName}MutationResult!`;
272
+ const createEmptyDocumentMutation = `createEmptyDocument(parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug.")): ${documentName}MutationResult!`;
273
+ const operationMutations = projection.operations.flatMap(({ camelName, inputTypeName }) => [`${camelName}(documentIdOrSlug: String, docId: PHID @deprecated(reason: "Use documentIdOrSlug."), input: ${inputTypeName}!): ${documentName}MutationResult!`, `${camelName}Async(documentIdOrSlug: String, docId: PHID @deprecated(reason: "Use documentIdOrSlug."), input: ${inputTypeName}!): String!`]).join("\n ");
274
+ return gql`
275
+ ${catalogScalarSdl}
276
+
277
+ ${RevisionType}
278
+
279
+ ${sharedBaseTypes}
280
+
281
+ ${fullStateType}
282
+
283
+ ${commonInputTypes}
284
+
285
+ ${resultTypes}
286
+
287
+ """
288
+ Queries: ${documentName} Document
289
+ """
290
+ ${queries}
291
+
292
+ """
293
+ Mutations: ${documentName}
294
+ """
295
+ type ${documentName}Mutations {
296
+ ${createDocumentMutation}
297
+ ${createEmptyDocumentMutation}
298
+
299
+ ${operationMutations}
300
+ }
301
+
302
+ type Query {
303
+ ${documentName}: ${documentName}Queries!
304
+ }
305
+
306
+ type Mutation {
307
+ ${documentName}: ${documentName}Mutations!
308
+ }
309
+
310
+ ${projection.stateInputTypes ? `"""
311
+ Input Types from State Schema
312
+ """
313
+ ${projection.stateInputTypes}` : ""}
314
+
315
+ ${initialStateInputSchema ? `"""
316
+ Input Types for Initial State
317
+ """
318
+ ${initialStateInputSchema}` : ""}
319
+
320
+ ${printModuleSchemas(projection.modules)}`;
321
+ }
322
+ //#endregion
323
+ //#region src/graphql/document-model-schema/schema-ast.ts
324
+ const EMPTY_DOCUMENT = {
325
+ kind: Kind.DOCUMENT,
326
+ definitions: []
327
+ };
328
+ const OUTPUT_TYPE_KINDS = [
329
+ Kind.OBJECT_TYPE_DEFINITION,
330
+ Kind.OBJECT_TYPE_EXTENSION,
331
+ Kind.ENUM_TYPE_DEFINITION,
332
+ Kind.ENUM_TYPE_EXTENSION,
333
+ Kind.UNION_TYPE_DEFINITION,
334
+ Kind.UNION_TYPE_EXTENSION,
335
+ Kind.INTERFACE_TYPE_DEFINITION,
336
+ Kind.INTERFACE_TYPE_EXTENSION
337
+ ];
338
+ const STATE_PREFIX_KINDS = new Set(OUTPUT_TYPE_KINDS);
339
+ const ALL_PREFIX_KINDS = /* @__PURE__ */ new Set([
340
+ ...OUTPUT_TYPE_KINDS,
341
+ Kind.INPUT_OBJECT_TYPE_DEFINITION,
342
+ Kind.INPUT_OBJECT_TYPE_EXTENSION
343
+ ]);
344
+ const TYPE_NAME_KINDS = /* @__PURE__ */ new Set([
345
+ ...ALL_PREFIX_KINDS,
346
+ Kind.SCALAR_TYPE_DEFINITION,
347
+ Kind.SCALAR_TYPE_EXTENSION,
348
+ Kind.NAMED_TYPE
349
+ ]);
350
+ const LOCAL_STATE_STUBS = /* @__PURE__ */ new Set([
351
+ "AccountSnapshotLocalState",
352
+ "BudgetStatementLocalState",
353
+ "ScopeFrameworkLocalState"
354
+ ]);
355
+ /** Parse SDL; blank or comment-only input yields an empty document. */
356
+ function parseSdl(sdl) {
357
+ const source = new Source(sdl);
358
+ if (new Lexer(source).advance().kind === TokenKind.EOF) return EMPTY_DOCUMENT;
359
+ try {
360
+ return parse(source, { noLocation: true });
361
+ } catch (error) {
362
+ const withoutSemicolons = sdl.replaceAll(";", "");
363
+ if (withoutSemicolons === sdl) throw error;
364
+ return parse(withoutSemicolons, { noLocation: true });
365
+ }
366
+ }
367
+ function definedTypeNames(doc, kinds) {
368
+ return doc.definitions.filter((def) => kinds.has(def.kind)).map((def) => def.name.value);
369
+ }
370
+ const UNSERVED_DIRECTIVES = /* @__PURE__ */ new Set(["equals"]);
371
+ /** Prefix type definition names and type references found in `names`. */
372
+ function prefixTypeNames(doc, prefix, names) {
373
+ return visit(doc, {
374
+ Directive: (node) => UNSERVED_DIRECTIVES.has(node.name.value) ? null : void 0,
375
+ enter(node) {
376
+ if (!TYPE_NAME_KINDS.has(node.kind)) return void 0;
377
+ const { name } = node;
378
+ if (!names.has(name.value)) return void 0;
379
+ return {
380
+ ...node,
381
+ name: {
382
+ ...name,
383
+ value: `${prefix}_${name.value}`
384
+ }
385
+ };
386
+ }
387
+ });
388
+ }
389
+ /** State schema definitions without inputs, `DateTime` or the given object types. */
390
+ function stateDefinitions(doc, droppedObjectTypes = /* @__PURE__ */ new Set()) {
391
+ return doc.definitions.filter((def) => def.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION && def.kind !== Kind.INPUT_OBJECT_TYPE_EXTENSION && !(def.kind === Kind.SCALAR_TYPE_DEFINITION && def.name.value === "DateTime") && !(def.kind === Kind.OBJECT_TYPE_DEFINITION && droppedObjectTypes.has(def.name.value)));
392
+ }
393
+ /** The state types and the document type a model adds to the generated schema. */
394
+ function generatedModelDefinitions(dmSchemaName, global, local) {
395
+ const stateDoc = {
396
+ kind: Kind.DOCUMENT,
397
+ definitions: [...stateDefinitions(global), ...stateDefinitions(local, LOCAL_STATE_STUBS)]
398
+ };
399
+ const prefixed = prefixTypeNames(stateDoc, dmSchemaName, new Set(definedTypeNames(stateDoc, STATE_PREFIX_KINDS)));
400
+ const documentType = parseSdl(`
401
+ type ${dmSchemaName} implements IDocument {
402
+ id: String!
403
+ name: String!
404
+ documentType: String!
405
+ operations(skip: Int, first: Int): [Operation!]!
406
+ revision: Int!
407
+ createdAtUtcIso: DateTime!
408
+ lastModifiedAtUtcIso: DateTime!
409
+ ${dmSchemaName !== "DocumentModel" ? `initialState: ${dmSchemaName}_${dmSchemaName}State!` : ""}
410
+ ${dmSchemaName !== "DocumentModel" ? `state: ${dmSchemaName}_${dmSchemaName}State!` : ""}
411
+ stateJSON: JSONObject
412
+ }`);
413
+ return [...prefixed.definitions, ...documentType.definitions];
414
+ }
415
+ /**
416
+ * Print the input type definitions of a schema document.
417
+ * @param excludeTypeNames - Input type names to leave out
418
+ */
419
+ function printInputTypeDefinitions(doc, excludeTypeNames = /* @__PURE__ */ new Set()) {
420
+ const definitions = doc.definitions.filter((def) => def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION && !excludeTypeNames.has(def.name.value));
421
+ if (definitions.length === 0) return "";
422
+ return print({
423
+ kind: Kind.DOCUMENT,
424
+ definitions
425
+ });
426
+ }
427
+ /**
428
+ * Apply type prefixes to GraphQL schema to namespace types and avoid collisions.
429
+ * Inlined from @powerhousedao/common/utils to avoid ES module import issues.
430
+ * @param {string} schema - GraphQL schema string
431
+ * @param {string} prefix - Prefix to apply to type names
432
+ * @param {string[]} externalTypeNames - Type names from other schemas to also prefix
433
+ * @returns {string} Schema with prefixed types
434
+ */
435
+ function applyGraphQLTypePrefixes(schema, prefix, externalTypeNames = []) {
436
+ if (!schema || !schema.trim()) return schema;
437
+ const doc = parseSdl(schema);
438
+ const names = /* @__PURE__ */ new Set([...definedTypeNames(doc, ALL_PREFIX_KINDS), ...externalTypeNames]);
439
+ if (names.size === 0) return schema;
440
+ return print(prefixTypeNames(doc, prefix, names));
441
+ }
442
+ function printModuleOperations(operations, documentName, names) {
443
+ const definitions = operations.flatMap((doc) => {
444
+ return prefixTypeNames(doc, documentName, /* @__PURE__ */ new Set([...names, ...definedTypeNames(doc, ALL_PREFIX_KINDS)])).definitions;
445
+ });
446
+ return definitions.length === 0 ? null : print({
447
+ kind: Kind.DOCUMENT,
448
+ definitions
449
+ });
450
+ }
451
+ function globalStateTypeName(documentName) {
452
+ return documentName === "DocumentModel" ? `${documentName}_${documentName}GlobalState` : `${documentName}_${documentName}State`;
453
+ }
454
+ /**
455
+ * Extract the root state type name from a scope's GraphQL schema.
456
+ * Uses the naming convention: {DocumentName}State for global,
457
+ * {DocumentName}{PascalScope}State for other scopes (e.g., DocumentDriveLocalState).
458
+ * Falls back to the last ObjectTypeDefinition (root types are conventionally last).
459
+ */
460
+ function rootTypeName(ast, documentName, scopeName) {
461
+ const candidates = [`${documentName}${scopeName === "global" ? "" : pascalCase(scopeName)}State`, `${documentName}${pascalCase(scopeName)}State`];
462
+ let lastObjectType = null;
463
+ for (const def of ast.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) {
464
+ if (candidates.includes(def.name.value)) return def.name.value;
465
+ lastObjectType = def.name.value;
466
+ }
467
+ return lastObjectType;
468
+ }
469
+ /**
470
+ * Convert a GraphQL output type AST node to an optional input type string.
471
+ * Strips non-null markers and converts object type references to Input suffix.
472
+ */
473
+ function convertTypeNodeToInput(typeNode, objectNames, unionNames, interfaceNames) {
474
+ if (typeNode.kind === Kind.NON_NULL_TYPE && typeNode.type) return convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames);
475
+ if (typeNode.kind === Kind.LIST_TYPE && typeNode.type) return `[${convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames)}]`;
476
+ if (typeNode.kind === Kind.NAMED_TYPE && typeNode.name) {
477
+ const name = typeNode.name.value;
478
+ if (objectNames.has(name)) return `${name}Input`;
479
+ if (unionNames.has(name) || interfaceNames.has(name)) return "JSONObject";
480
+ return name;
481
+ }
482
+ return "JSONObject";
483
+ }
484
+ /**
485
+ * Generate GraphQL input type definitions from a state schema document.
486
+ * Converts output type definitions to input types with all fields optional.
487
+ * - Object type references get Input suffix
488
+ * - Union/interface references become JSONObject
489
+ * - Enums and scalars remain unchanged
490
+ */
491
+ function stateInputTypes(ast, excludeTypeNames) {
492
+ const enumNames = /* @__PURE__ */ new Set();
493
+ const unionNames = /* @__PURE__ */ new Set();
494
+ const interfaceNames = /* @__PURE__ */ new Set();
495
+ const objectNames = /* @__PURE__ */ new Set();
496
+ const existingInputNames = /* @__PURE__ */ new Set();
497
+ for (const def of ast.definitions) switch (def.kind) {
498
+ case Kind.ENUM_TYPE_DEFINITION:
499
+ enumNames.add(def.name.value);
500
+ break;
501
+ case Kind.UNION_TYPE_DEFINITION:
502
+ unionNames.add(def.name.value);
503
+ break;
504
+ case Kind.INTERFACE_TYPE_DEFINITION:
505
+ interfaceNames.add(def.name.value);
506
+ break;
507
+ case Kind.OBJECT_TYPE_DEFINITION:
508
+ objectNames.add(def.name.value);
509
+ break;
510
+ case Kind.INPUT_OBJECT_TYPE_DEFINITION: existingInputNames.add(def.name.value);
511
+ }
512
+ const inputTypes = [];
513
+ for (const def of ast.definitions) {
514
+ if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;
515
+ const inputName = `${def.name.value}Input`;
516
+ if (existingInputNames.has(inputName)) continue;
517
+ if (excludeTypeNames?.has(inputName)) continue;
518
+ const fields = def.fields ?? [];
519
+ if (fields.length === 0) continue;
520
+ const inputFields = fields.map((field) => {
521
+ return ` ${field.name.value}: ${convertTypeNodeToInput(field.type, objectNames, unionNames, interfaceNames)}`;
522
+ });
523
+ inputTypes.push(`input ${def.name.value}Input {\n${inputFields.join("\n")}\n}`);
524
+ }
525
+ return inputTypes.join("\n\n");
526
+ }
527
+ function scopeInitialState(ast, documentName, scopeName, allTypeNames) {
528
+ const rootName = rootTypeName(ast, documentName, scopeName);
529
+ if (!rootName) return { type: "JSONObject" };
530
+ const scopeInputTypes = stateInputTypes(ast, new Set(allTypeNames));
531
+ if (!scopeInputTypes) return { type: "JSONObject" };
532
+ return {
533
+ type: `${documentName}_${rootName}Input`,
534
+ inputTypes: applyGraphQLTypePrefixes(scopeInputTypes, documentName, allTypeNames)
535
+ };
536
+ }
537
+ //#endregion
538
+ //#region src/graphql/document-model-schema/model-projection.ts
539
+ function buildModelProjection(documentName, documents) {
540
+ const allTypeNames = [.../* @__PURE__ */ new Set([...documents.stateTypeNames, ...documents.operationTypeNames])];
541
+ const names = new Set(allTypeNames);
542
+ const modules = documents.modules.flatMap(({ name, operations }) => {
543
+ const sdl = printModuleOperations(operations, documentName, names);
544
+ return sdl === null ? [] : [{
545
+ name,
546
+ sdl
547
+ }];
548
+ });
549
+ const scopes = documents.scopes.map(({ name, document }) => document === null ? {
550
+ name,
551
+ type: "JSONObject"
552
+ } : {
553
+ name,
554
+ ...scopeInitialState(document, documentName, name, allTypeNames)
555
+ });
556
+ return {
557
+ documentName,
558
+ operations: documents.operations,
559
+ modules,
560
+ stateInputTypes: applyGraphQLTypePrefixes(printInputTypeDefinitions(documents.global, new Set(documents.operationTypeNames)), documentName, allTypeNames),
561
+ globalStateTypeName: globalStateTypeName(documentName),
562
+ localStateTypeName: documents.hasLocalRoot ? `${documentName}_${documentName}LocalState` : null,
563
+ initialState: {
564
+ inputTypes: scopes.flatMap(({ inputTypes }) => inputTypes ?? []).join("\n\n"),
565
+ scopes: scopes.map(({ name, type }) => ({
566
+ name,
567
+ type
568
+ }))
569
+ }
570
+ };
571
+ }
572
+ //#endregion
573
+ //#region src/graphql/document-model-schema/stored-projection.ts
574
+ const logger$2 = childLogger(["reactor-api", "create-schema"]);
575
+ /**
576
+ * Reads a model's schema out of its latest stored specification's SDL, on
577
+ * every call. Malformed SDL fails, or falls back, where it always has.
578
+ */
579
+ function storedSchemaSource(global) {
580
+ return {
581
+ packageScalars: [],
582
+ hasOperationSchemas: () => {
583
+ const specification = global.specifications.at(-1);
584
+ if (!specification) return false;
585
+ return specification.modules.some((module) => module.operations.some((op) => hasValidSchema(op.schema)));
586
+ },
587
+ modelDefinitions: () => {
588
+ const dmSchemaName = getDocumentModelSchemaName(global);
589
+ const latestSpec = global.specifications.at(-1);
590
+ const globalSchema = latestSpec?.state.global.schema ?? "";
591
+ const localSchema = latestSpec?.state.local.schema ?? "";
592
+ return generatedModelDefinitions(dmSchemaName, parseSdl(globalSchema), parseSdl(localSchema));
593
+ },
594
+ modelProjection: () => {
595
+ const documentName = getDocumentModelSchemaName(global);
596
+ return buildModelProjection(documentName, storedDocuments(global.specifications.at(-1), documentName));
597
+ },
598
+ stateDefinitions: () => {
599
+ const specification = global.specifications.at(-1);
600
+ if (!specification) return [];
601
+ const fullSchema = `${specification.state.global.schema ?? ""}\n${specification.state.local.schema ?? ""}`;
602
+ if (!fullSchema.trim()) return [];
603
+ try {
604
+ return parse(fullSchema).definitions;
605
+ } catch {
606
+ return [];
607
+ }
608
+ },
609
+ mutationOperations: () => global.specifications.at(-1)?.modules.flatMap((module) => module.operations.filter((op) => op.name)).map((op) => ({
610
+ camelName: camelCase(op.name),
611
+ storedName: op.name,
612
+ permissionKey: constantCase(op.name),
613
+ creatorKey: camelCase(op.name)
614
+ })) ?? []
615
+ };
616
+ }
617
+ /**
618
+ * Type names a schema defines. Unparseable schemas yield no names.
619
+ */
620
+ function extractTypeNames(schema) {
621
+ try {
622
+ return definedTypeNames(parseSdl(schema), ALL_PREFIX_KINDS);
623
+ } catch (error) {
624
+ logger$2.debug(`Skipping unparseable schema: ${String(error)}`);
625
+ return [];
626
+ }
627
+ }
628
+ /**
629
+ * The template documents of a stored specification. Type names skip
630
+ * unparseable schemas; the global state and served operation schemas must
631
+ * parse; a scope schema that does not parse strictly is served as `JSONObject`.
632
+ */
633
+ function storedDocuments(specification, documentName) {
634
+ const globalStateSchema = specification?.state.global.schema;
635
+ const localStateSchema = specification?.state.local.schema;
636
+ const stateTypeNames = [...extractTypeNames(globalStateSchema ?? ""), ...extractTypeNames(localStateSchema ?? "")];
637
+ const operationTypeNames = specification?.modules.flatMap((module) => module.operations.flatMap((op) => extractTypeNames(op.schema ?? ""))) ?? [];
638
+ const global = parseSdl(globalStateSchema ?? "");
639
+ const operations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).map((op) => ({
640
+ camelName: camelCase(op.name),
641
+ inputTypeName: `${documentName}_${pascalCase(op.name)}Input`
642
+ }))) ?? [];
643
+ return {
644
+ global,
645
+ stateTypeNames,
646
+ operationTypeNames,
647
+ modules: specification?.modules.map((module) => ({
648
+ name: module.name,
649
+ operations: module.operations.filter((op) => hasValidSchema(op.schema)).map((op) => parseSdl(op.schema ?? ""))
650
+ })) ?? [],
651
+ operations,
652
+ hasLocalRoot: (localStateSchema ?? "").includes(`type ${documentName}LocalState`),
653
+ scopes: storedScopes(specification)
654
+ };
655
+ }
656
+ function storedScopes(specification) {
657
+ if (!specification) return [];
658
+ return Object.entries(specification.state).map(([name, scopeState]) => {
659
+ const schema = scopeState.schema ?? "";
660
+ if (!hasValidSchema(schema)) return {
661
+ name,
662
+ document: null
663
+ };
664
+ try {
665
+ return {
666
+ name,
667
+ document: parse(schema)
668
+ };
669
+ } catch {
670
+ return {
671
+ name,
672
+ document: null
673
+ };
674
+ }
675
+ });
676
+ }
677
+ //#endregion
678
+ //#region src/graphql/document-model-schema/structured-projection.ts
679
+ const documentOf = (segment) => segment === null ? EMPTY_DOCUMENT : segment.document;
680
+ const inputOf = (operation) => operation.input;
681
+ function once(compute) {
682
+ let cached;
683
+ return () => (cached ??= { value: compute() }).value;
684
+ }
685
+ /**
686
+ * Adapts a definition's GraphQL projection. Each value is derived on first use
687
+ * and kept, since the projection is an immutable snapshot.
688
+ */
689
+ function structuredSchemaSource(projection, global) {
690
+ const name = getDocumentModelSchemaName(global);
691
+ const documentName = () => name;
692
+ const globalDocument = documentOf(projection.global);
693
+ const localDocument = documentOf(projection.local);
694
+ const mutationOperations = once(() => projection.modules.flatMap((module) => module.operations.flatMap((operation) => {
695
+ const input = inputOf(operation)?.definitions[0];
696
+ if (input?.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION) return [];
697
+ return [{
698
+ camelName: camelCase(operation.name),
699
+ inputTypeName: `${documentName()}_${input.name.value}`,
700
+ storedName: operation.name,
701
+ permissionKey: operation.actionType,
702
+ creatorKey: operation.creatorKey
703
+ }];
704
+ })));
705
+ return {
706
+ packageScalars: projection.packageScalars,
707
+ mutationOperations,
708
+ hasOperationSchemas: once(() => projection.modules.some((module) => module.operations.some((op) => op.input !== null))),
709
+ modelDefinitions: once(() => generatedModelDefinitions(documentName(), globalDocument, localDocument)),
710
+ stateDefinitions: once(() => [...globalDocument.definitions, ...localDocument.definitions]),
711
+ modelProjection: once(() => {
712
+ const name = documentName();
713
+ const operationInputs = projection.modules.map((module) => module.operations.flatMap((operation) => inputOf(operation) ?? []));
714
+ const localRoot = `${name}LocalState`;
715
+ return buildModelProjection(name, {
716
+ global: globalDocument,
717
+ stateTypeNames: [...definedTypeNames(globalDocument, ALL_PREFIX_KINDS), ...definedTypeNames(localDocument, ALL_PREFIX_KINDS)],
718
+ operationTypeNames: operationInputs.flat().flatMap((input) => definedTypeNames(input, ALL_PREFIX_KINDS)),
719
+ modules: projection.modules.map((module, index) => ({
720
+ name: module.name,
721
+ operations: operationInputs[index] ?? []
722
+ })),
723
+ operations: mutationOperations(),
724
+ hasLocalRoot: localDocument.definitions.some((def) => def.kind === Kind.OBJECT_TYPE_DEFINITION && def.name.value === localRoot),
725
+ scopes: [{
726
+ name: "global",
727
+ document: globalDocument
728
+ }, {
729
+ name: "local",
730
+ document: projection.local === null ? null : localDocument
731
+ }]
732
+ });
733
+ })
734
+ };
735
+ }
736
+ //#endregion
737
+ //#region src/graphql/document-model-schema/source.ts
738
+ const logger$1 = childLogger(["reactor-api", "document-model-schema"]);
739
+ const logged = /* @__PURE__ */ new Set();
740
+ function warnOnce(documentType, reason, detail) {
741
+ const key = `${documentType}\n${reason}`;
742
+ if (logged.has(key)) return;
743
+ logged.add(key);
744
+ logger$1.warn("Serving document model @documentType from its stored model: its definition is @reason: @detail", documentType, reason, detail);
745
+ }
746
+ const projected = /* @__PURE__ */ new WeakMap();
747
+ function project(inspection) {
748
+ let entry = projected.get(inspection.specification);
749
+ if (entry === void 0) {
750
+ try {
751
+ entry = {
752
+ projection: projectDocumentModelGraphQL(inspection.definition, inspection.specification),
753
+ sources: /* @__PURE__ */ new Map()
754
+ };
755
+ } catch (error) {
756
+ entry = { error };
757
+ }
758
+ projected.set(inspection.specification, entry);
759
+ }
760
+ return entry;
761
+ }
762
+ const snapshotDigests = /* @__PURE__ */ new WeakMap();
763
+ /**
764
+ * The cache-key part a model's definition adds: a digest of the inspected
765
+ * snapshot when the schema is built from it, else `null`, so a model served
766
+ * from its stored SDL keeps main's key. Inspection is memoized per definition
767
+ * object, so this runs once per loaded definition.
768
+ */
769
+ function structuredDefinitionDigest(model) {
770
+ let inspection;
771
+ try {
772
+ inspection = inspectDocumentModelDefinition(model);
773
+ } catch {
774
+ return null;
775
+ }
776
+ if (inspection.kind !== "structured") return null;
777
+ let digest = snapshotDigests.get(inspection.definition);
778
+ if (digest === void 0) {
779
+ digest = createHash("sha256").update(JSON.stringify(inspection.definition)).digest("base64");
780
+ snapshotDigests.set(inspection.definition, digest);
781
+ }
782
+ return digest;
783
+ }
784
+ /**
785
+ * The one place a host selects how a document model's schema is built: from
786
+ * its structured definition when it carries a valid, matching one, else from
787
+ * its stored SDL. Logs nothing; `fallback` says why a definition is not served.
788
+ */
789
+ function selectDocumentModelSchemaSource(model) {
790
+ const { global } = model.documentModel;
791
+ let inspection;
792
+ try {
793
+ inspection = inspectDocumentModelDefinition(model);
794
+ } catch (error) {
795
+ return {
796
+ source: storedSchemaSource(global),
797
+ fallback: {
798
+ reason: "unreadable",
799
+ error
800
+ }
801
+ };
802
+ }
803
+ if (inspection.kind === "stored") return {
804
+ source: storedSchemaSource(global),
805
+ ...(inspection.reason === "invalid" || inspection.reason === "mismatch") && { fallback: {
806
+ reason: inspection.reason,
807
+ diagnostics: inspection.diagnostics
808
+ } }
809
+ };
810
+ const entry = project(inspection);
811
+ if ("error" in entry) return {
812
+ source: storedSchemaSource(global),
813
+ fallback: {
814
+ reason: "unreadable",
815
+ error: entry.error
816
+ }
817
+ };
818
+ let source = entry.sources.get(global.name);
819
+ if (source === void 0) {
820
+ source = structuredSchemaSource(entry.projection, global);
821
+ entry.sources.set(global.name, source);
822
+ }
823
+ return { source };
824
+ }
825
+ /** {@link selectDocumentModelSchemaSource}, logging a fallback once per document type and reason. */
826
+ function documentModelSchemaSource(model) {
827
+ const { source, fallback } = selectDocumentModelSchemaSource(model);
828
+ if (fallback !== void 0) warnOnce(model.documentModel.global.id, fallback.reason, "diagnostics" in fallback ? fallback.diagnostics : fallback.error);
829
+ return source;
830
+ }
831
+ //#endregion
832
+ //#region src/utils/create-schema.ts
833
+ const logger = childLogger(["reactor-api", "create-schema"]);
834
+ /**
835
+ * A subgraph defines a type whose name the generated document-model schema
836
+ * owns, so one of the two definitions would be lost.
837
+ */
838
+ var SubgraphTypeCollisionError = class extends Error {
839
+ typeNames;
840
+ constructor(typeNames) {
841
+ super(`Subgraph defines types reserved by the document-model schema: ${typeNames.join(", ")}`);
842
+ this.name = "SubgraphTypeCollisionError";
843
+ this.typeNames = typeNames;
844
+ }
845
+ };
846
+ /**
847
+ * Type-system definition kinds that GraphQL requires to be uniquely named.
848
+ * A subgraph SDL with two definitions sharing a name fails federation
849
+ * composition ("There can be only one type named X"), which is fatal to the
850
+ * whole gateway. We dedupe these by name; field/operation/extension nodes are
851
+ * left untouched.
852
+ */
853
+ const TYPE_DEFINITION_KINDS = /* @__PURE__ */ new Set([
854
+ Kind.OBJECT_TYPE_DEFINITION,
855
+ Kind.ENUM_TYPE_DEFINITION,
856
+ Kind.INPUT_OBJECT_TYPE_DEFINITION,
857
+ Kind.INTERFACE_TYPE_DEFINITION,
858
+ Kind.UNION_TYPE_DEFINITION,
859
+ Kind.SCALAR_TYPE_DEFINITION
860
+ ]);
861
+ /**
862
+ * Drop duplicate type-system definitions by name, keeping the first occurrence.
863
+ * Deduping is by name across ALL kinds (a `type` and an `enum` sharing a name
864
+ * collide in GraphQL too), so the first definition of a given name wins
865
+ * regardless of kind. State types are emitted before operation types, so
866
+ * keep-first preserves the authoritative state definition. This heals a document
867
+ * model that defines the same name twice (global+local, state+operation, or
868
+ * twice in one scope) so the assembled subgraph SDL composes instead of crashing
869
+ * the gateway (Sentry #917).
870
+ */
871
+ const dedupeTypeDefinitions = (definitions, seen = /* @__PURE__ */ new Set()) => definitions.filter((def) => {
872
+ const name = typeDefinitionName(def);
873
+ if (name === void 0) return true;
874
+ if (seen.has(name)) {
875
+ logger.debug(`Dropping duplicate type definition: ${name}`);
876
+ return false;
877
+ }
878
+ seen.add(name);
879
+ return true;
880
+ });
881
+ function typeDefinitionName(def) {
882
+ if (!TYPE_DEFINITION_KINDS.has(def.kind)) return void 0;
883
+ return def.name?.value;
884
+ }
885
+ const buildSubgraphSchemaModule = (documentModels, resolvers, typeDefs, options = {}) => {
886
+ const generated = options.generated ?? getGeneratedDocumentModelTypes(documentModels, void 0, options.scalars);
887
+ const newResolvers = {
888
+ ...catalogResolvers,
889
+ ...Object.fromEntries(Array.from(generated.scalars, ([name, { definition }]) => [name, registeredScalarType(definition)])),
890
+ ...resolvers,
891
+ JSONObject: catalogResolvers.JSONObject,
892
+ Unknown: catalogResolvers.Unknown
893
+ };
894
+ return {
895
+ typeDefs: assembleSubgraphTypeDefs(generated, typeDefs, options.ownTypeNames),
896
+ resolvers: newResolvers
897
+ };
898
+ };
899
+ const createSchema = (documentModels, resolvers, typeDefs, options = {}) => {
900
+ return buildSubgraphSchema([buildSubgraphSchemaModule(documentModels, resolvers, typeDefs, options)]);
901
+ };
902
+ /**
903
+ * Create a merged GraphQL schema from multiple subgraph modules.
904
+ * Uses buildSubgraphSchema's array overload to combine type definitions
905
+ * and resolvers from multiple subgraphs into a single executable schema.
906
+ */
907
+ const createMergedSchema = (modules) => {
908
+ return buildSubgraphSchema(modules);
909
+ };
910
+ /** The name the model's own subgraph registers under. */
911
+ function getDocumentModelSubgraphName(documentModel) {
912
+ return kebabCase(documentModel.name);
913
+ }
914
+ /**
915
+ * The generated document-model types followed by the subgraph's own. Throws
916
+ * {@link SubgraphTypeCollisionError} when the subgraph defines a generated
917
+ * name not in `ownTypeNames`.
918
+ */
919
+ const getDocumentModelTypeDefs = (documentModels, typeDefs, ownTypeNames) => assembleSubgraphTypeDefs(getGeneratedDocumentModelTypes(documentModels), typeDefs, ownTypeNames);
920
+ /** Names of the type definitions in `doc`. */
921
+ function typeDefinitionNames(doc) {
922
+ return new Set(doc.definitions.map(typeDefinitionName).filter((name) => name !== void 0));
923
+ }
924
+ /** The definitions `documentModel` adds to the generated schema. */
925
+ function documentModelDefinitions(documentModel) {
926
+ return documentModelSchemaSource(documentModel).modelDefinitions();
927
+ }
928
+ function sourceOf(documentModel) {
929
+ return "documentModel" in documentModel ? documentModel : { documentModel: { global: documentModel } };
930
+ }
931
+ function addScalarFlags(definitions, into) {
932
+ for (const def of definitions) {
933
+ const name = typeDefinitionName(def);
934
+ if (name === void 0) continue;
935
+ const scalar = def.kind === Kind.SCALAR_TYPE_DEFINITION;
936
+ into.set(name, scalar && (into.get(name) ?? true));
937
+ }
938
+ return into;
939
+ }
940
+ let fixedGeneratedTypes;
941
+ /**
942
+ * Type names no document model may generate: the root types, the generated
943
+ * types every schema carries, and the types of `coreTypeDefs`.
944
+ */
945
+ function reservedTypeNames(coreTypeDefs) {
946
+ fixedGeneratedTypes ??= addScalarFlags(getGeneratedDocumentModelTypes([]).definitions, /* @__PURE__ */ new Map());
947
+ const reserved = new Map([
948
+ ["Query", false],
949
+ ["Mutation", false],
950
+ ["Subscription", false],
951
+ ...fixedGeneratedTypes
952
+ ]);
953
+ for (const typeDefs of coreTypeDefs) addScalarFlags(typeDefs.definitions, reserved);
954
+ return reserved;
955
+ }
956
+ /**
957
+ * The reserved names `documentModel`'s generated types take. A scalar may
958
+ * repeat a reserved scalar: the duplicate is dropped on assembly.
959
+ */
960
+ function reservedTypeNamesTaken(documentModel, reserved, definitions = documentModelDefinitions(documentModel)) {
961
+ const generated = addScalarFlags(definitions, /* @__PURE__ */ new Map());
962
+ return Array.from(generated).filter(([name, scalar]) => reserved.has(name) && !(scalar && reserved.get(name))).map(([name]) => name);
963
+ }
964
+ const CATALOG_SCALARS = gql`
965
+ ${catalogScalarSdl}
966
+ `.definitions;
967
+ const HOST_TYPES = gql`
968
+ type PHOperationContext {
969
+ signer: Signer
970
+ }
971
+
972
+ type Signer {
973
+ user: SignerUser
974
+ app: SignerApp
975
+ signatures: [String!]!
976
+ }
977
+
978
+ type SignerUser {
979
+ address: String!
980
+ networkId: String!
981
+ chainId: Int!
982
+ }
983
+
984
+ type SignerApp {
985
+ name: String!
986
+ key: String!
987
+ }
988
+
989
+ type Operation {
990
+ id: String!
991
+ type: String!
992
+ index: Int!
993
+ timestampUtcMs: DateTime!
994
+ hash: String!
995
+ skip: Int
996
+ inputText: String
997
+ error: String
998
+ context: PHOperationContext
999
+ }
1000
+
1001
+ interface IDocument {
1002
+ id: String!
1003
+ name: String!
1004
+ documentType: String!
1005
+ revision: Int!
1006
+ createdAtUtcIso: DateTime!
1007
+ lastModifiedAtUtcIso: DateTime!
1008
+ operations(first: Int, skip: Int): [Operation!]!
1009
+ stateJSON: JSONObject
1010
+ }
1011
+ `.definitions;
1012
+ /**
1013
+ * A federation gateway composes this SDL, not the schema built from it, so the
1014
+ * description is declared here as well as on the resolver.
1015
+ */
1016
+ function generatedHead(scalars) {
1017
+ return [
1018
+ ...CATALOG_SCALARS,
1019
+ ...Array.from(scalars, ([name, { definition }]) => ({
1020
+ kind: Kind.SCALAR_TYPE_DEFINITION,
1021
+ name: {
1022
+ kind: Kind.NAME,
1023
+ value: name
1024
+ },
1025
+ description: definition.description === void 0 ? void 0 : {
1026
+ kind: Kind.STRING,
1027
+ value: definition.description,
1028
+ block: true
1029
+ }
1030
+ })),
1031
+ ...HOST_TYPES
1032
+ ];
1033
+ }
1034
+ const GENERATED_TAIL = gql`
1035
+ type GqlDocument implements IDocument {
1036
+ id: String!
1037
+ name: String!
1038
+ documentType: String!
1039
+ revision: Int!
1040
+ createdAtUtcIso: DateTime!
1041
+ lastModifiedAtUtcIso: DateTime!
1042
+ operations(first: Int, skip: Int): [Operation!]!
1043
+ stateJSON: JSONObject
1044
+ }
1045
+
1046
+ type DriveDocument implements IDocument {
1047
+ id: String!
1048
+ name: String!
1049
+ documentType: String!
1050
+ revision: Int!
1051
+ createdAtUtcIso: DateTime!
1052
+ lastModifiedAtUtcIso: DateTime!
1053
+ operations(first: Int, skip: Int): [Operation!]!
1054
+ stateJSON: JSONObject
1055
+ }
1056
+ `.definitions;
1057
+ /**
1058
+ * The generated schema for `documentModels`. `schemas` supplies models'
1059
+ * definitions already built; the others are built here.
1060
+ */
1061
+ function getGeneratedDocumentModelTypes(documentModels, schemas, scalars = EMPTY_SCALAR_REGISTRY) {
1062
+ return generatedTypesFrom(documentModels.map((model) => ({
1063
+ model,
1064
+ generated: schemas?.get(model)?.generated
1065
+ })), scalars);
1066
+ }
1067
+ /** {@link getGeneratedDocumentModelTypes} from the models' global states. */
1068
+ function generatedTypesOf(documentModels) {
1069
+ return generatedTypesFrom(documentModels.map((global) => ({ model: sourceOf(global) })), EMPTY_SCALAR_REGISTRY);
1070
+ }
1071
+ function generatedTypesFrom(documentModels, scalars) {
1072
+ const modelDefinitions = [];
1073
+ const addedDocumentModels = /* @__PURE__ */ new Set();
1074
+ documentModels.forEach(({ model, generated }) => {
1075
+ const dmSchemaName = getDocumentModelSchemaName(model.documentModel.global);
1076
+ if (addedDocumentModels.has(dmSchemaName)) {
1077
+ logger.debug(`Skipping document model with duplicate name: ${dmSchemaName}`);
1078
+ return;
1079
+ }
1080
+ addedDocumentModels.add(dmSchemaName);
1081
+ modelDefinitions.push(...generated ?? documentModelDefinitions(model));
1082
+ });
1083
+ const definitions = dedupeTypeDefinitions([
1084
+ ...generatedHead(scalars),
1085
+ ...modelDefinitions,
1086
+ ...GENERATED_TAIL
1087
+ ]);
1088
+ return {
1089
+ definitions,
1090
+ names: new Set(definitions.map(typeDefinitionName).filter((name) => name !== void 0)),
1091
+ scalars
1092
+ };
1093
+ }
1094
+ /** Whether any operation of the latest specification has a schema. */
1095
+ function hasOperationSchemas(documentModel) {
1096
+ return documentModelSchemaSource(sourceOf(documentModel)).hasOperationSchemas();
1097
+ }
1098
+ /** The types of a document model's own subgraph. */
1099
+ function documentModelSubgraphTypes(documentModel) {
1100
+ const typeDefs = generateDocumentModelSchema(documentModel, { useNewApi: true });
1101
+ return {
1102
+ typeDefs,
1103
+ typeNames: typeDefinitionNames(typeDefs)
1104
+ };
1105
+ }
1106
+ const toError = (error) => error instanceof Error ? error : new Error(String(error));
1107
+ /** Build `subgraph` over the generated types of `documentModel` alone. */
1108
+ function checkBuilds(documentModel, generated, subgraph) {
1109
+ buildSubgraphSchema([{ typeDefs: assembleSubgraphTypeDefs(getGeneratedDocumentModelTypes([documentModel], /* @__PURE__ */ new Map([[documentModel, { generated }]])), subgraph?.typeDefs ?? EMPTY_DOCUMENT, subgraph?.typeNames) }]);
1110
+ }
1111
+ /** Throws when the generated types every subgraph carries do not build. */
1112
+ function buildDocumentModelSchema(documentModel, options = {}) {
1113
+ const generated = documentModelDefinitions(documentModel);
1114
+ if (options.subgraph === false || !hasOperationSchemas(documentModel)) {
1115
+ checkBuilds(documentModel, generated);
1116
+ return { generated };
1117
+ }
1118
+ try {
1119
+ const subgraph = documentModelSubgraphTypes(documentModel);
1120
+ checkBuilds(documentModel, generated, subgraph);
1121
+ return {
1122
+ generated,
1123
+ subgraph
1124
+ };
1125
+ } catch (error) {
1126
+ checkBuilds(documentModel, generated);
1127
+ return {
1128
+ generated,
1129
+ subgraphError: toError(error)
1130
+ };
1131
+ }
1132
+ }
1133
+ /** Hash of everything {@link buildDocumentModelSchema} reads. */
1134
+ function schemaSourceKey(documentModel) {
1135
+ const { name, specifications } = documentModel.documentModel.global;
1136
+ const hash = createHash("sha256").update(JSON.stringify([name, specifications.at(-1)]));
1137
+ const definition = structuredDefinitionDigest(documentModel);
1138
+ if (definition !== null) hash.update(definition);
1139
+ return hash.digest("base64");
1140
+ }
1141
+ /** Schemas and failures by source hash, for the last resolve's models only. */
1142
+ var DocumentModelSchemaCache = class {
1143
+ #entries = /* @__PURE__ */ new Map();
1144
+ #build;
1145
+ constructor(build = buildDocumentModelSchema) {
1146
+ this.#build = build;
1147
+ }
1148
+ resolve(documentModels) {
1149
+ const entries = /* @__PURE__ */ new Map();
1150
+ const resolved = documentModels.map((model) => {
1151
+ let key;
1152
+ let entry;
1153
+ try {
1154
+ key = schemaSourceKey(model);
1155
+ entry = entries.get(key) ?? this.#entries.get(key);
1156
+ } catch (error) {
1157
+ key = `unkeyed:${model.documentModel.global.id}`;
1158
+ entry = toError(error);
1159
+ }
1160
+ if (entry === void 0) try {
1161
+ entry = this.#build(model);
1162
+ } catch (error) {
1163
+ entry = toError(error);
1164
+ }
1165
+ entries.set(key, entry);
1166
+ return entry instanceof Error ? {
1167
+ model,
1168
+ key,
1169
+ error: entry
1170
+ } : {
1171
+ model,
1172
+ key,
1173
+ schema: entry
1174
+ };
1175
+ });
1176
+ this.#entries = entries;
1177
+ return resolved;
1178
+ }
1179
+ };
1180
+ /**
1181
+ * Names of the generated types `typeDefs` redefines, other than those a
1182
+ * model's own subgraph may repeat. Scalars are dropped on assembly, so they
1183
+ * never collide.
1184
+ */
1185
+ function findSubgraphTypeCollisions(generated, typeDefs, ownTypeNames) {
1186
+ const collisions = [];
1187
+ for (const def of typeDefs.definitions) {
1188
+ if (def.kind === Kind.SCALAR_TYPE_DEFINITION) continue;
1189
+ const name = typeDefinitionName(def);
1190
+ if (name === void 0 || !generated.names.has(name)) continue;
1191
+ if (ownTypeNames?.has(name)) continue;
1192
+ collisions.push(name);
1193
+ }
1194
+ return collisions;
1195
+ }
1196
+ /** Throws {@link SubgraphTypeCollisionError}; see {@link getDocumentModelTypeDefs}. */
1197
+ function assembleSubgraphTypeDefs(generated, typeDefs, ownTypeNames) {
1198
+ const collisions = findSubgraphTypeCollisions(generated, typeDefs, ownTypeNames);
1199
+ if (collisions.length > 0) throw new SubgraphTypeCollisionError(collisions);
1200
+ const subgraphDefinitions = typeDefs.definitions.filter((def) => def.kind !== Kind.SCALAR_TYPE_DEFINITION);
1201
+ return {
1202
+ kind: Kind.DOCUMENT,
1203
+ definitions: [...generated.definitions, ...dedupeTypeDefinitions(subgraphDefinitions, new Set(generated.names))]
1204
+ };
1205
+ }
1206
+ /**
1207
+ * Generate a GraphQL schema for a document model.
1208
+ *
1209
+ * @param documentModel - The document model global state
1210
+ * @param options - Schema generation options
1211
+ * @returns GraphQL DocumentNode
1212
+ */
1213
+ function generateDocumentModelSchema(documentModel, options = {}) {
1214
+ return generateModelSchema(documentModelSchemaSource(sourceOf(documentModel)).modelProjection(), options);
1215
+ }
1216
+ //#endregion
1217
+ //#region src/graphql/subgraph-type-ownership.ts
1218
+ const ROOT_TYPE_NAMES = /* @__PURE__ */ new Set([
1219
+ "Query",
1220
+ "Mutation",
1221
+ "Subscription"
1222
+ ]);
1223
+ const byName = (nodes) => nodes && [...nodes].sort((a, b) => a.name.value < b.name.value ? -1 : a.name.value > b.name.value ? 1 : 0);
1224
+ /** Printed without descriptions, with named members in name order. */
1225
+ function normalizeDefinition(node) {
1226
+ const normalized = visit(node, { leave(current) {
1227
+ const copy = { ...current };
1228
+ delete copy.loc;
1229
+ if ("description" in copy) copy.description = void 0;
1230
+ if (current.kind === Kind.STRING) copy.block = false;
1231
+ for (const key of [
1232
+ "fields",
1233
+ "arguments",
1234
+ "interfaces"
1235
+ ]) if (Array.isArray(copy[key])) copy[key] = byName(copy[key]);
1236
+ if (current.kind === Kind.ENUM_TYPE_DEFINITION || current.kind === Kind.ENUM_TYPE_EXTENSION) copy.values = byName(current.values);
1237
+ if (current.kind === Kind.UNION_TYPE_DEFINITION || current.kind === Kind.UNION_TYPE_EXTENSION) copy.types = byName(current.types);
1238
+ return copy;
1239
+ } });
1240
+ return print(normalized);
1241
+ }
1242
+ function isScalar(def) {
1243
+ return def.kind === Kind.SCALAR_TYPE_DEFINITION || def.kind === Kind.SCALAR_TYPE_EXTENSION;
1244
+ }
1245
+ /** Type and root-field claims, without scalars or generated types. */
1246
+ function collectSubgraphClaims(typeDefs, generatedNames) {
1247
+ const types = /* @__PURE__ */ new Map();
1248
+ const claims = /* @__PURE__ */ new Map();
1249
+ for (const def of typeDefs.definitions) {
1250
+ if (!isTypeDefinitionNode(def) && !isTypeExtensionNode(def)) continue;
1251
+ if (isScalar(def)) continue;
1252
+ const node = def;
1253
+ const name = node.name.value;
1254
+ if (ROOT_TYPE_NAMES.has(name)) {
1255
+ if (!("fields" in node)) continue;
1256
+ for (const field of node.fields ?? []) {
1257
+ const key = `${name}.${field.name.value}`;
1258
+ const definition = normalizeDefinition(field);
1259
+ const previous = claims.get(key);
1260
+ claims.set(key, previous === void 0 ? definition : `${previous}\n${definition}`);
1261
+ }
1262
+ continue;
1263
+ }
1264
+ if (isTypeDefinitionNode(node) && generatedNames.has(name)) continue;
1265
+ const nodes = types.get(name) ?? [];
1266
+ nodes.push(node);
1267
+ types.set(name, nodes);
1268
+ }
1269
+ for (const [name, nodes] of types) {
1270
+ const merged = mergeTypeNodes(nodes);
1271
+ claims.set(name, merged ? normalizeDefinition(merged) : nodes.map(normalizeDefinition).sort().join("\n"));
1272
+ }
1273
+ return claims;
1274
+ }
1275
+ const EXTENSION_KINDS = {
1276
+ [Kind.OBJECT_TYPE_DEFINITION]: Kind.OBJECT_TYPE_EXTENSION,
1277
+ [Kind.INTERFACE_TYPE_DEFINITION]: Kind.INTERFACE_TYPE_EXTENSION,
1278
+ [Kind.UNION_TYPE_DEFINITION]: Kind.UNION_TYPE_EXTENSION,
1279
+ [Kind.ENUM_TYPE_DEFINITION]: Kind.ENUM_TYPE_EXTENSION,
1280
+ [Kind.INPUT_OBJECT_TYPE_DEFINITION]: Kind.INPUT_OBJECT_TYPE_EXTENSION
1281
+ };
1282
+ /** One definition plus its same-kind extensions, as a single definition. */
1283
+ function mergeTypeNodes(nodes) {
1284
+ if (nodes.length === 1) return nodes[0];
1285
+ const definitions = nodes.filter(isTypeDefinitionNode);
1286
+ if (definitions.length !== 1) return void 0;
1287
+ const [definition] = definitions;
1288
+ const extensionKind = EXTENSION_KINDS[definition.kind];
1289
+ const merged = { ...definition };
1290
+ for (const node of nodes) {
1291
+ if (node === definition) continue;
1292
+ if (node.kind !== extensionKind) return void 0;
1293
+ const members = node;
1294
+ for (const key of [
1295
+ "fields",
1296
+ "interfaces",
1297
+ "values",
1298
+ "types",
1299
+ "directives"
1300
+ ]) {
1301
+ const extra = members[key];
1302
+ if (extra) merged[key] = [...merged[key] ?? [], ...extra];
1303
+ }
1304
+ }
1305
+ return merged;
1306
+ }
1307
+ function isRootFieldClaim(claim) {
1308
+ return claim.includes(".");
1309
+ }
1310
+ /** Candidates, in priority order, that lose a claim to an earlier one. */
1311
+ function resolveClaimOwnership(candidates) {
1312
+ const owners = /* @__PURE__ */ new Map();
1313
+ const excluded = /* @__PURE__ */ new Map();
1314
+ for (const { candidate, name, claims } of candidates) {
1315
+ const conflicts = [];
1316
+ for (const [claim, definition] of claims) {
1317
+ const owned = owners.get(claim);
1318
+ if (owned && (isRootFieldClaim(claim) || owned.definition !== definition)) conflicts.push({
1319
+ claim,
1320
+ owner: owned.owner
1321
+ });
1322
+ }
1323
+ if (conflicts.length > 0) {
1324
+ excluded.set(candidate, conflicts);
1325
+ continue;
1326
+ }
1327
+ for (const [claim, definition] of claims) if (!owners.has(claim)) owners.set(claim, {
1328
+ definition,
1329
+ owner: name
1330
+ });
1331
+ }
1332
+ return excluded;
1333
+ }
1334
+ function describeOwnershipConflicts(conflicts) {
1335
+ return `claims owned by another subgraph: ${conflicts.map(({ claim, owner }) => `${claim} (owned by "${owner}")`).join(", ")}`;
1336
+ }
1337
+ //#endregion
1338
+ //#region src/graphql/subgraph-admission.ts
1339
+ /** Where a subgraph came from; a package origin is the package name. */
1340
+ const CORE_ORIGIN = Symbol("core");
1341
+ const DOCUMENT_MODEL_ORIGIN = Symbol("document-models");
1342
+ const HOST_ORIGIN = Symbol("host");
1343
+ function describeOrigin(origin) {
1344
+ if (origin === CORE_ORIGIN) return "core";
1345
+ if (origin === DOCUMENT_MODEL_ORIGIN) return "document models";
1346
+ if (origin === HOST_ORIGIN) return "the host";
1347
+ return `package ${origin}`;
1348
+ }
1349
+ function rank(origin) {
1350
+ if (origin === CORE_ORIGIN) return 3;
1351
+ if (origin === HOST_ORIGIN) return 2;
1352
+ if (origin === DOCUMENT_MODEL_ORIGIN) return 1;
1353
+ return 0;
1354
+ }
1355
+ /**
1356
+ * The server's decision on one built model: it refuses a model whose schema
1357
+ * does not build or that generates a reserved type name.
1358
+ */
1359
+ function admitDocumentModel(resolved, reserved) {
1360
+ if (resolved.schema === void 0) return {
1361
+ admitted: false,
1362
+ reason: `has an unusable schema: ${resolved.error.message}`
1363
+ };
1364
+ const { model, schema } = resolved;
1365
+ const taken = reservedTypeNamesTaken(model, reserved, schema.generated);
1366
+ if (taken.length > 0) return {
1367
+ admitted: false,
1368
+ reason: `generates reserved type names: ${taken.join(", ")}`
1369
+ };
1370
+ return {
1371
+ admitted: true,
1372
+ schema,
1373
+ ...schema.subgraphError !== void 0 && { subgraphRefusal: `has an unusable subgraph schema: ${schema.subgraphError.message}` }
1374
+ };
1375
+ }
1376
+ /** Usable models; a refused latest version refuses every version of its model. */
1377
+ function admitDocumentModels(resolved, reserved) {
1378
+ const latest = new Set(latestDocumentModelVersions(resolved.map(({ model }) => model)));
1379
+ const candidates = resolved.map((entry) => {
1380
+ const verdict = admitDocumentModel(entry, reserved);
1381
+ const refusal = !verdict.admitted ? {
1382
+ reason: verdict.reason,
1383
+ subgraphOnly: false
1384
+ } : verdict.subgraphRefusal !== void 0 ? {
1385
+ reason: verdict.subgraphRefusal,
1386
+ subgraphOnly: true
1387
+ } : void 0;
1388
+ return {
1389
+ model: entry.model,
1390
+ key: entry.key,
1391
+ schema: verdict.admitted ? verdict.schema : void 0,
1392
+ refusal
1393
+ };
1394
+ });
1395
+ const refusedModels = new Set(candidates.filter(({ model, refusal }) => refusal && latest.has(model)).map(({ model }) => model.documentModel.global.name));
1396
+ const admission = {
1397
+ admitted: [],
1398
+ schemas: /* @__PURE__ */ new Map(),
1399
+ refusals: []
1400
+ };
1401
+ for (const { model, key, schema, refusal } of candidates) {
1402
+ const everyVersion = latest.has(model);
1403
+ if (!everyVersion && refusedModels.has(model.documentModel.global.name)) continue;
1404
+ if (refusal) admission.refusals.push({
1405
+ model,
1406
+ key,
1407
+ version: documentModelVersion(model),
1408
+ everyVersion,
1409
+ ...refusal
1410
+ });
1411
+ if (schema) {
1412
+ admission.schemas.set(model, schema);
1413
+ admission.admitted.push(model);
1414
+ }
1415
+ }
1416
+ return admission;
1417
+ }
1418
+ const DOCUMENT_MODELS_TO_EXCLUDE = [];
1419
+ /** The version of a model: its module's own, else its latest specification's. */
1420
+ const documentModelVersion = (model) => model.version ?? model.documentModel.global.specifications.at(-1)?.version ?? 0;
1421
+ /**
1422
+ * The latest version of each model, by name: the only one whose own subgraph
1423
+ * the server registers.
1424
+ */
1425
+ function latestDocumentModelVersions(documentModels) {
1426
+ const latestByName = /* @__PURE__ */ new Map();
1427
+ for (const documentModel of documentModels) {
1428
+ const { name } = documentModel.documentModel.global;
1429
+ const existing = latestByName.get(name);
1430
+ if (!existing || documentModelVersion(documentModel) > documentModelVersion(existing)) latestByName.set(name, documentModel);
1431
+ }
1432
+ return Array.from(latestByName.values());
1433
+ }
1434
+ /** The admitted models that serve a subgraph of their own, with its types. */
1435
+ function documentModelSubgraphSources(admitted, schemas) {
1436
+ const sources = [];
1437
+ for (const model of latestDocumentModelVersions(admitted)) {
1438
+ if (DOCUMENT_MODELS_TO_EXCLUDE.includes(model.documentModel.global.id)) continue;
1439
+ const types = schemas.get(model)?.subgraph;
1440
+ if (types) sources.push({
1441
+ model,
1442
+ types
1443
+ });
1444
+ }
1445
+ return sources;
1446
+ }
1447
+ /** Same origin replaces, higher rank evicts, else refused; core names never move (#2972). */
1448
+ function decideAdmission(candidate, origin, holders, collisions) {
1449
+ if (origin !== CORE_ORIGIN && holders.some((holder) => holder.origin === CORE_ORIGIN)) return {
1450
+ action: "reject",
1451
+ reason: "core name"
1452
+ };
1453
+ if (holders.some(({ holder }) => holder === candidate)) return { action: "skip" };
1454
+ const rivals = holders.filter((holder) => holder.origin !== origin);
1455
+ for (const rival of rivals) if (rank(origin) <= rank(rival.origin)) return {
1456
+ action: "reject",
1457
+ reason: "rank",
1458
+ holderOrigin: rival.origin
1459
+ };
1460
+ const found = origin === CORE_ORIGIN ? [] : collisions();
1461
+ if (found.length > 0) return {
1462
+ action: "reject",
1463
+ reason: "collision",
1464
+ collisions: found
1465
+ };
1466
+ return {
1467
+ action: "add",
1468
+ replaces: holders.filter((holder) => holder.origin === origin).map(({ holder }) => holder),
1469
+ evicts: rivals.map(({ holder }) => holder)
1470
+ };
1471
+ }
1472
+ /** The order origins first registered in, and names within each. */
1473
+ var RegistrationOrder = class {
1474
+ #origins = /* @__PURE__ */ new Map();
1475
+ record(origin, name) {
1476
+ let entry = this.#origins.get(origin);
1477
+ if (!entry) {
1478
+ entry = {
1479
+ order: this.#origins.size,
1480
+ names: /* @__PURE__ */ new Map()
1481
+ };
1482
+ this.#origins.set(origin, entry);
1483
+ }
1484
+ if (!entry.names.has(name)) entry.names.set(name, entry.names.size);
1485
+ }
1486
+ of(origin, name) {
1487
+ const entry = this.#origins.get(origin);
1488
+ return [entry?.order ?? Infinity, entry?.names.get(name) ?? Infinity];
1489
+ }
1490
+ };
1491
+ /** Rank, then first registration. */
1492
+ function byClaimPriority(members, originOf, nameOf, order) {
1493
+ return Array.from(members, (member) => {
1494
+ const origin = originOf(member);
1495
+ return {
1496
+ member,
1497
+ priority: [-rank(origin), ...order.of(origin, nameOf(member))]
1498
+ };
1499
+ }).sort((a, b) => {
1500
+ const i = a.priority.findIndex((value, j) => value !== b.priority[j]);
1501
+ return i === -1 ? 0 : a.priority[i] - b.priority[i];
1502
+ }).map(({ member }) => member);
1503
+ }
1504
+ /** Members that lose a claim: claims go by byClaimPriority. */
1505
+ function supergraphClaimLosers(members, order) {
1506
+ return resolveClaimOwnership(byClaimPriority(members, (member) => member.origin, (member) => member.name, order).map((member) => ({
1507
+ candidate: member.member,
1508
+ name: member.name,
1509
+ claims: member.claims
1510
+ })));
1511
+ }
1512
+ //#endregion
1513
+ //#region src/graphql/inspection/admin-schema.ts
1514
+ const inspectionAdminTypeDefs = gql`
1515
+ """
1516
+ The levers a listed admin may pull. Only served when the host enables
1517
+ inspection-admin; every field refuses any other caller.
1518
+ """
1519
+ type InspectionAdmin {
1520
+ "Processor retry and rerun are served."
1521
+ processors: Boolean!
1522
+ "The catch-up priority can be set."
1523
+ catchUpPriority: Boolean!
1524
+ "Memory telemetry can be switched and heap snapshots written."
1525
+ memoryTelemetry: Boolean!
1526
+ "Keyframe clean-up and reclaim are served."
1527
+ keyframes: Boolean!
1528
+ }
1529
+
1530
+ "Rows and stored bytes a keyframe clean-up saw, can remove and removed."
1531
+ type InspectionKeyframeCleanupTotals {
1532
+ streams: Float!
1533
+ rows: Float!
1534
+ bytes: Float!
1535
+ removableRows: Float!
1536
+ removableBytes: Float!
1537
+ removedRows: Float!
1538
+ removedBytes: Float!
1539
+ }
1540
+
1541
+ type InspectionKeyframeCleanupType {
1542
+ documentType: String!
1543
+ "The rule in force; absent keeps every keyframe."
1544
+ keep: Float
1545
+ interval: Float!
1546
+ streams: Float!
1547
+ rows: Float!
1548
+ bytes: Float!
1549
+ removableRows: Float!
1550
+ removableBytes: Float!
1551
+ removedRows: Float!
1552
+ removedBytes: Float!
1553
+ }
1554
+
1555
+ type InspectionKeyframeCleanupReason {
1556
+ "beyond-keep or deleted-document."
1557
+ reason: String!
1558
+ rows: Float!
1559
+ bytes: Float!
1560
+ }
1561
+
1562
+ type InspectionKeyframeCleanupStream {
1563
+ documentId: String!
1564
+ documentType: String!
1565
+ scope: String!
1566
+ branch: String!
1567
+ reason: String!
1568
+ rows: Float!
1569
+ bytes: Float!
1570
+ removableRows: Float!
1571
+ removableBytes: Float!
1572
+ }
1573
+
1574
+ type InspectionKeyframeCleanupRun {
1575
+ id: String!
1576
+ dryRun: Boolean!
1577
+ "running, done, cancelled or failed."
1578
+ state: String!
1579
+ startedAtUtcMs: Float!
1580
+ finishedAtUtcMs: Float
1581
+ documentsTotal: Float!
1582
+ documentsSeen: Float!
1583
+ "The catch-up priority is at level 0, which stops the run."
1584
+ parked: Boolean!
1585
+ totals: InspectionKeyframeCleanupTotals!
1586
+ types: [InspectionKeyframeCleanupType!]!
1587
+ reasons: [InspectionKeyframeCleanupReason!]!
1588
+ topStreams: [InspectionKeyframeCleanupStream!]!
1589
+ error: String
1590
+ }
1591
+
1592
+ type InspectionKeyframeReclaim {
1593
+ "running, done, busy, failed or unsupported."
1594
+ state: String!
1595
+ startedAtUtcMs: Float!
1596
+ finishedAtUtcMs: Float
1597
+ tableBytesBefore: Float
1598
+ tableBytesAfter: Float
1599
+ durationMs: Float
1600
+ "What happened, or what to do by hand."
1601
+ message: String!
1602
+ }
1603
+
1604
+ type Query {
1605
+ inspectionAdmin: InspectionAdmin!
1606
+ "The running or latest keyframe clean-up."
1607
+ inspectionKeyframeCleanup: InspectionKeyframeCleanupRun
1608
+ "The running or latest reclaim of the Keyframe table's disk space."
1609
+ inspectionKeyframeReclaim: InspectionKeyframeReclaim
1610
+ }
1611
+
1612
+ type Mutation {
1613
+ "Clears a processor's error and replays from its cursor."
1614
+ inspectionRetryProcessor(processorId: String!): Boolean!
1615
+ """
1616
+ Replays a processor. With clear, it and the processors sharing its clear
1617
+ scope are cleared and replayed from their floor; otherwise its cursor moves
1618
+ back to fromOrdinal, between its floor and its cursor. Answers once the
1619
+ replay ends or has run for two seconds; its progress shows in the
1620
+ processor's lastOrdinal, and a later failure in its status and the log.
1621
+ """
1622
+ inspectionRerunProcessor(
1623
+ processorId: String!
1624
+ clear: Boolean!
1625
+ fromOrdinal: Float!
1626
+ ): Boolean!
1627
+ """
1628
+ Sets the pace of processor backfills: mode dynamic hands the level to the
1629
+ load controller (level must be absent); mode fixed holds level, 0-7.
1630
+ """
1631
+ inspectionSetCatchUpPriority(mode: String!, level: Int): Boolean!
1632
+ "Starts or stops memory telemetry, or changes its interval or outputs, without a restart."
1633
+ inspectionSetMemoryTelemetry(
1634
+ enabled: Boolean!
1635
+ intervalMs: Int
1636
+ outputs: [String!]
1637
+ ): Boolean!
1638
+ """
1639
+ Writes a V8 heap snapshot of the main thread and returns its path on the
1640
+ host. Blocks the server for seconds to minutes. force skips the check for
1641
+ free memory.
1642
+ """
1643
+ inspectionWriteHeapSnapshot(force: Boolean): String!
1644
+ """
1645
+ Starts a keyframe clean-up and answers at once; poll
1646
+ inspectionKeyframeCleanup. A dry run only reports. Otherwise it applies the
1647
+ configured keep and removes the keyframes of deleted documents. Refused
1648
+ while another run or a reclaim is going.
1649
+ """
1650
+ inspectionStartKeyframeCleanup(
1651
+ dryRun: Boolean!
1652
+ ): InspectionKeyframeCleanupRun!
1653
+ "Stops a running keyframe clean-up after its current statement."
1654
+ inspectionCancelKeyframeCleanup: Boolean!
1655
+ """
1656
+ Rewrites the Keyframe table to give its dead space back to the disk, once
1657
+ the store is quiet; poll inspectionKeyframeReclaim. Where the host has no
1658
+ way to do that, it answers with what to do by hand.
1659
+ """
1660
+ inspectionReclaimKeyframeSpace: InspectionKeyframeReclaim!
1661
+ }
1662
+ `;
1663
+ //#endregion
1664
+ //#region src/graphql/inspection/schema.ts
1665
+ const inspectionTypeDefs = gql`
1666
+ type ReactorStorageFacts {
1667
+ engine: String!
1668
+ persistence: String!
1669
+ durable: Boolean!
1670
+ selfHeal: Boolean!
1671
+ }
1672
+
1673
+ type InspectorAccess {
1674
+ admin: Boolean!
1675
+ sql: Boolean!
1676
+ }
1677
+
1678
+ """
1679
+ What this reactor reports about itself. access is null unless the caller is
1680
+ one of the host's admins.
1681
+ """
1682
+ type ReactorInfo {
1683
+ storage: ReactorStorageFacts!
1684
+ workflows: Boolean!
1685
+ syncChannels: [String!]!
1686
+ access: InspectorAccess
1687
+ }
1688
+
1689
+ type InspectionDocumentModel {
1690
+ documentType: String!
1691
+ name: String!
1692
+ version: Int!
1693
+ supportedVersions: [Int!]!
1694
+ }
1695
+
1696
+ type InspectionDrive {
1697
+ driveId: String!
1698
+ name: String!
1699
+ branch: String!
1700
+ collectionId: String!
1701
+ documentType: String!
1702
+ nodeCount: Int!
1703
+ fileCount: Int!
1704
+ folderCount: Int!
1705
+ otherNodeCount: Int!
1706
+ unreadableNodeCount: Int!
1707
+ icon: String
1708
+ }
1709
+
1710
+ type InspectionDrivePage {
1711
+ results: [InspectionDrive!]!
1712
+ nextCursor: String
1713
+ }
1714
+
1715
+ type InspectionDriveIntegrityRef {
1716
+ id: String!
1717
+ documentType: String!
1718
+ }
1719
+
1720
+ type InspectionDriveIntegrity {
1721
+ driveId: String!
1722
+ checkedNodeCount: Int!
1723
+ totalFileNodeCount: Int!
1724
+ """
1725
+ File nodes whose document is missing or not served to you; the two are
1726
+ reported alike so a withheld document's existence does not leak.
1727
+ """
1728
+ missingDocuments: [InspectionDriveIntegrityRef!]!
1729
+ unsupportedTypes: [InspectionDriveIntegrityRef!]!
1730
+ }
1731
+
1732
+ type InspectionAttachmentInfo {
1733
+ present: Boolean!
1734
+ storeKind: String!
1735
+ hasReplicator: Boolean!
1736
+ replicatorRunning: Boolean!
1737
+ backlogScanned: Boolean!
1738
+ refsSeen: Int!
1739
+ held: Int!
1740
+ bytesHeld: Float!
1741
+ queued: Int!
1742
+ fetching: Int!
1743
+ pendingFetches: Int!
1744
+ waiting: Int!
1745
+ notFound: Int!
1746
+ failed: Int!
1747
+ lastError: String
1748
+ }
1749
+
1750
+ """
1751
+ A queued job without its actions or operations.
1752
+ """
1753
+ type InspectionQueueJob {
1754
+ id: String!
1755
+ kind: String!
1756
+ documentId: String!
1757
+ scope: String!
1758
+ branch: String!
1759
+ status: String!
1760
+ actionCount: Int!
1761
+ operationCount: Int!
1762
+ retryCount: Int!
1763
+ }
1764
+
1765
+ type InspectionQueueState {
1766
+ isPaused: Boolean!
1767
+ totalPending: Int!
1768
+ totalExecuting: Int!
1769
+ pendingJobs: [InspectionQueueJob!]!
1770
+ executingJobs: [InspectionQueueJob!]!
1771
+ }
1772
+
1773
+ type InspectionProcessor {
1774
+ processorId: String!
1775
+ factoryId: String!
1776
+ driveId: String!
1777
+ processorIndex: Int!
1778
+ lastOrdinal: Float!
1779
+ status: String!
1780
+ lastError: String
1781
+ lastErrorTimestampUtcMs: Float
1782
+ floor: Float!
1783
+ clearable: Boolean!
1784
+ runFrom: Float!
1785
+ phase: String!
1786
+ }
1787
+
1788
+ """
1789
+ One path's numbers over one horizon. Times are wall-clock milliseconds the
1790
+ processor's queue awaited, not CPU; read time includes waiting for the store.
1791
+ slotWaitMs and pauseMs are throttling and count toward no busy time.
1792
+ """
1793
+ type InspectionProcessorTimingCounters {
1794
+ batches: Float!
1795
+ opsDelivered: Float!
1796
+ opsScanned: Float!
1797
+ opsMatched: Float!
1798
+ pages: Float!
1799
+ handlerMs: Float!
1800
+ maxBatchMs: Float!
1801
+ readMs: Float!
1802
+ lookupMs: Float!
1803
+ fillMs: Float!
1804
+ slotWaitMs: Float!
1805
+ pauseMs: Float!
1806
+ errors: Float!
1807
+ }
1808
+
1809
+ type InspectionProcessorTimingHorizon {
1810
+ live: InspectionProcessorTimingCounters!
1811
+ replay: InspectionProcessorTimingCounters!
1812
+ ordinalsAdvanced: Float!
1813
+ busyMs: Float!
1814
+ }
1815
+
1816
+ type InspectionProcessorTimingRun {
1817
+ startedAtUtcMs: Float!
1818
+ runFrom: Float!
1819
+ counters: InspectionProcessorTimingCounters!
1820
+ ordinalsAdvanced: Float!
1821
+ }
1822
+
1823
+ type InspectionProcessorTimingLastRun {
1824
+ startedAtUtcMs: Float!
1825
+ durationMs: Float!
1826
+ ordinals: Float!
1827
+ opsDelivered: Float!
1828
+ busyMs: Float!
1829
+ }
1830
+
1831
+ type InspectionProcessorTimingBatch {
1832
+ atUtcMs: Float!
1833
+ path: String!
1834
+ ops: Float!
1835
+ ms: Float!
1836
+ fromOrdinal: Float!
1837
+ toOrdinal: Float!
1838
+ }
1839
+
1840
+ type InspectionProcessorTimingDocumentType {
1841
+ documentType: String!
1842
+ ops: Float!
1843
+ handlerMs: Float!
1844
+ }
1845
+
1846
+ type InspectionProcessorQueueDepth {
1847
+ tasks: Float!
1848
+ ops: Float!
1849
+ }
1850
+
1851
+ """
1852
+ One processor's timing. The horizons are null while timing is off.
1853
+ """
1854
+ type InspectionProcessorTiming {
1855
+ processorId: String!
1856
+ name: String!
1857
+ driveLabel: String!
1858
+ factoryId: String!
1859
+ driveId: String!
1860
+ phase: String!
1861
+ lastOrdinal: Float!
1862
+ queueDepth: InspectionProcessorQueueDepth!
1863
+ ordinalsBehind: Float!
1864
+ opsPerSecond: Float!
1865
+ ordinalsPerSecond: Float!
1866
+ etaMs: Float
1867
+ sinceUtcMs: Float
1868
+ total: InspectionProcessorTimingHorizon
1869
+ window: InspectionProcessorTimingHorizon
1870
+ windowMs: Float!
1871
+ currentRun: InspectionProcessorTimingRun
1872
+ lastRun: InspectionProcessorTimingLastRun
1873
+ lastBatch: InspectionProcessorTimingBatch
1874
+ byDocumentType: [InspectionProcessorTimingDocumentType!]!
1875
+ }
1876
+
1877
+ """
1878
+ level is off, basic or detailed. Without a catch-up status, head is the
1879
+ highest cursor and headKnown is false.
1880
+ """
1881
+ type InspectionProcessorTimingReport {
1882
+ level: String!
1883
+ windowMs: Float!
1884
+ head: Float!
1885
+ headKnown: Boolean!
1886
+ processors: [InspectionProcessorTiming!]!
1887
+ }
1888
+
1889
+ """
1890
+ Memory samples correlated with operations processed. samples are newest
1891
+ last; summary holds the rates over the correlation window and is null until
1892
+ two samples exist.
1893
+ """
1894
+ type InspectionMemoryTelemetry {
1895
+ enabled: Boolean!
1896
+ intervalMs: Float!
1897
+ consoleIntervalMs: Float!
1898
+ outputs: [String!]!
1899
+ file: String
1900
+ startedAt: String
1901
+ summary: JSONObject
1902
+ samples: [JSONObject!]!
1903
+ }
1904
+
1905
+ """
1906
+ What one catch-up priority level sets. giveWay is stop (level 0: no page is
1907
+ read until the level rises), pause (pauseMs between pages), yield (one
1908
+ event-loop turn) or none.
1909
+ """
1910
+ type InspectionCatchUpLevelSettings {
1911
+ slots: Int!
1912
+ pageSize: Int!
1913
+ pauseMs: Int!
1914
+ giveWay: String!
1915
+ }
1916
+
1917
+ """
1918
+ The host's load over its last window, as the dynamic controller read it.
1919
+ """
1920
+ type InspectionCatchUpLoadSample {
1921
+ requests: Int!
1922
+ p95LatencyMs: Float!
1923
+ eventLoopDelayMs: Float!
1924
+ idleForMs: Float!
1925
+ }
1926
+
1927
+ """
1928
+ The pace of processor backfills. mode is fixed or dynamic; level is 0-7.
1929
+ sample is null until a dynamic tick has sampled the host's load.
1930
+ """
1931
+ type InspectionCatchUpPriority {
1932
+ mode: String!
1933
+ level: Int!
1934
+ settings: InspectionCatchUpLevelSettings!
1935
+ reason: String!
1936
+ sample: InspectionCatchUpLoadSample
1937
+ }
1938
+
1939
+ """
1940
+ healthy means something only when tracked; an untracked store reports false.
1941
+ """
1942
+ type InspectionStorageHealth {
1943
+ tracked: Boolean!
1944
+ healthy: Boolean!
1945
+ everRecreated: Boolean!
1946
+ recreateCount: Int!
1947
+ }
1948
+
1949
+ """
1950
+ Issues in scopes the caller may not read are left out.
1951
+ """
1952
+ type InspectionValidation {
1953
+ documentId: String!
1954
+ isConsistent: Boolean!
1955
+ keyframeIssues: [JSONObject!]!
1956
+ snapshotIssues: [JSONObject!]!
1957
+ streamOrderIssues: [JSONObject!]!
1958
+ }
1959
+
1960
+ type InspectionCursor {
1961
+ cursorType: String!
1962
+ cursorOrdinal: Float!
1963
+ lastSyncedAtUtcMs: Float
1964
+ liveAckOrdinal: Float!
1965
+ liveLatestOrdinal: Float!
1966
+ }
1967
+
1968
+ type InspectionMailboxDepths {
1969
+ inbox: Int!
1970
+ outbox: Int!
1971
+ deadLetter: Int!
1972
+ }
1973
+
1974
+ type InspectionConnectionHealth {
1975
+ snapshot: JSONObject!
1976
+ neverSucceeded: Boolean!
1977
+ stalenessMs: Float
1978
+ }
1979
+
1980
+ type InspectionRemote {
1981
+ remoteName: String!
1982
+ remoteId: String!
1983
+ inboxCursor: InspectionCursor!
1984
+ outboxCursor: InspectionCursor!
1985
+ mailboxDepths: InspectionMailboxDepths!
1986
+ connection: InspectionConnectionHealth!
1987
+ meta: JSONObject!
1988
+ }
1989
+
1990
+ """
1991
+ A dead letter without its operations.
1992
+ """
1993
+ type InspectionDeadLetter {
1994
+ id: String!
1995
+ jobId: String!
1996
+ documentId: String!
1997
+ branch: String!
1998
+ scopes: [String!]!
1999
+ errorType: String!
2000
+ errorMessage: String!
2001
+ operationCount: Int!
2002
+ }
2003
+
2004
+ type InspectionDeadLetterPage {
2005
+ remoteName: String!
2006
+ results: [InspectionDeadLetter!]!
2007
+ nextCursor: String
2008
+ }
2009
+
2010
+ """
2011
+ Reads only. info, documentModels and loadsModelsOnDemand serve every caller;
2012
+ drive and document reads are made as the caller through the reactor read
2013
+ gate; the rest need one of the host's admins.
2014
+ """
2015
+ type ReactorInspection {
2016
+ info: ReactorInfo!
2017
+ documentModels: [InspectionDocumentModel!]!
2018
+ """
2019
+ True when a document model loads the first time a document of its type
2020
+ arrives, so documentModels names only those loaded so far.
2021
+ """
2022
+ loadsModelsOnDemand: Boolean!
2023
+ drives(cursor: String, limit: Int): InspectionDrivePage!
2024
+ """
2025
+ Reads every file node's document. Throttled per caller.
2026
+ """
2027
+ driveIntegrity(driveId: String!, branch: String!): InspectionDriveIntegrity!
2028
+ attachmentInfo: InspectionAttachmentInfo!
2029
+ queueState: InspectionQueueState!
2030
+ processors: [InspectionProcessor!]!
2031
+ processorTiming: InspectionProcessorTimingReport!
2032
+ "Refused on a host without memory telemetry."
2033
+ memoryTelemetry(limit: Int, sinceIso: String): InspectionMemoryTelemetry!
2034
+ catchUpStatus: JSONObject!
2035
+ catchUpPriority: InspectionCatchUpPriority!
2036
+ storageHealth: InspectionStorageHealth!
2037
+ """
2038
+ Replays the whole document; expensive. Throttled per caller.
2039
+ """
2040
+ validateDocument(documentId: String!, branch: String): InspectionValidation!
2041
+ remotes: [InspectionRemote!]!
2042
+ remote(remoteName: String!): InspectionRemote!
2043
+ deadLetters(
2044
+ remoteName: String!
2045
+ cursor: String
2046
+ limit: Int
2047
+ ): InspectionDeadLetterPage!
2048
+ }
2049
+
2050
+ type Query {
2051
+ inspection: ReactorInspection!
2052
+ }
2053
+ `;
2054
+ //#endregion
2055
+ //#region src/graphql/reactor/schema.graphql
2056
+ var schema_default = "# 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\n# Action ids; absent when there is nothing to undo or redo\ntype UndoRedoTargets {\n undoTarget: String\n redoTarget: String\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 # The rows a base-reducer 3 undo and redo of the scope would retract now, for\n # the caller to sign a RETRACT of. A scope the caller may not read has none;\n # below base-reducer 3 there are none.\n undoRedoTargets(\n documentIdOrSlug: String!\n scope: String\n branch: String\n ): UndoRedoTargets!\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";
2057
+ //#endregion
2058
+ //#region src/graphql/system/schema.ts
2059
+ const systemTypeDefs = gql`
2060
+ type SystemInfo {
2061
+ version: String!
2062
+ gitHash: String!
2063
+ gitUrl: String
2064
+ }
2065
+
2066
+ type Query {
2067
+ system: SystemInfo!
2068
+ }
2069
+ `;
2070
+ //#endregion
2071
+ //#region src/packages/base-document-models.ts
2072
+ /** The models every host loads before any package's, by source package. */
2073
+ const baseDocumentModels = [
2074
+ ["document-drive", driveDocumentModelModule],
2075
+ ["document-model", documentModelDocumentModelModule],
2076
+ ["reactor-drive", reactorDriveDocumentModelModule],
2077
+ ["reactor-group", ReactorGroupV1]
2078
+ ];
2079
+ //#endregion
2080
+ export { getDocumentModelTypeDefs as A, sameScalarRegistry as B, createMergedSchema as C, generateDocumentModelSchema as D, findSubgraphTypeCollisions as E, typeDefinitionNames as F, documentModelSchemaSource as I, selectDocumentModelSchemaSource as L, hasOperationSchemas as M, reservedTypeNames as N, generatedTypesOf as O, reservedTypeNamesTaken as P, getDocumentModelSchemaName as R, buildSubgraphSchemaModule as S, documentModelSubgraphTypes as T, schema_default$1 as V, describeOwnershipConflicts as _, inspectionAdminTypeDefs as a, assembleSubgraphTypeDefs as b, HOST_ORIGIN as c, byClaimPriority as d, decideAdmission as f, collectSubgraphClaims as g, supergraphClaimLosers as h, inspectionTypeDefs as i, getGeneratedDocumentModelTypes as j, getDocumentModelSubgraphName as k, RegistrationOrder as l, documentModelSubgraphSources as m, systemTypeDefs as n, CORE_ORIGIN as o, describeOrigin as p, schema_default as r, DOCUMENT_MODEL_ORIGIN as s, baseDocumentModels as t, admitDocumentModels as u, DocumentModelSchemaCache as v, createSchema as w, buildDocumentModelSchema as x, SubgraphTypeCollisionError as y, EMPTY_SCALAR_REGISTRY as z };
2081
+
2082
+ //# sourceMappingURL=base-document-models-caJpqTLw.mjs.map
2083
+ //# debugId=7047ae02-c917-5a70-b56d-3b9b84ac2d2a