@powerhousedao/reactor-api 6.2.3-dev.82 → 6.2.3-dev.83

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.
@@ -1,5 +1,5 @@
1
1
 
2
- !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="926b8930-da2c-543f-89c7-59d1cbf32444")}catch(e){}}();
2
+ !function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d164cc5a-09cc-53c9-b196-24ebff89d427")}catch(e){}}();
3
3
  import { childLogger, documentModelDocumentModelModule } from "document-model";
4
4
  import { gql } from "graphql-tag";
5
5
  import { GraphQLScalarType, Kind, Lexer, Source, TokenKind, isTypeDefinitionNode, isTypeExtensionNode, parse, print, valueFromASTUntyped, visit } from "graphql";
@@ -83,8 +83,7 @@ function registeredScalarType(definition) {
83
83
  });
84
84
  }
85
85
  //#endregion
86
- //#region src/utils/create-schema.ts
87
- const logger = childLogger(["reactor-api", "create-schema"]);
86
+ //#region src/graphql/model-schema-templates.ts
88
87
  /**
89
88
  * Revision type - matches the definition in reactor/schema.graphql.
90
89
  * Used by PHDocument and document mutation results.
@@ -95,6 +94,234 @@ const RevisionType = `
95
94
  revision: Int!
96
95
  }
97
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/utils/create-schema.ts
324
+ const logger = childLogger(["reactor-api", "create-schema"]);
98
325
  /**
99
326
  * A subgraph defines a type whose name the generated document-model schema
100
327
  * owns, so one of the two definitions would be lost.
@@ -211,33 +438,6 @@ function prefixTypeNames(doc, prefix, names) {
211
438
  function stateTypeDefinitions(sdl, droppedObjectTypes = /* @__PURE__ */ new Set()) {
212
439
  return parseSdl(sdl).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)));
213
440
  }
214
- /**
215
- * Prefixed operation schemas per module. The first definition of each module
216
- * carries a "Module: <Name>" description unless it has its own.
217
- */
218
- function buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema) {
219
- const names = new Set(allTypeNames);
220
- return specification?.modules.map((module) => {
221
- const definitions = module.operations.filter((op) => hasValidSchema(op.schema)).flatMap((op) => {
222
- const doc = parseSdl(op.schema ?? "");
223
- return prefixTypeNames(doc, documentName, /* @__PURE__ */ new Set([...names, ...definedTypeNames(doc, ALL_PREFIX_KINDS)])).definitions;
224
- });
225
- if (definitions.length === 0) return "";
226
- const [first, ...rest] = definitions;
227
- const header = "description" in first && !first.description ? {
228
- ...first,
229
- description: {
230
- kind: Kind.STRING,
231
- value: `Module: ${pascalCase(module.name)}`,
232
- block: true
233
- }
234
- } : first;
235
- return print({
236
- kind: Kind.DOCUMENT,
237
- definitions: [header, ...rest]
238
- });
239
- }).filter(Boolean).join("\n") ?? "";
240
- }
241
441
  const buildSubgraphSchemaModule = (documentModels, resolvers, typeDefs, options = {}) => {
242
442
  const generated = options.generated ?? getGeneratedDocumentModelTypes(documentModels, void 0, options.scalars);
243
443
  const newResolvers = {
@@ -263,9 +463,6 @@ const createSchema = (documentModels, resolvers, typeDefs, options = {}) => {
263
463
  const createMergedSchema = (modules) => {
264
464
  return buildSubgraphSchema(modules);
265
465
  };
266
- function getDocumentModelSchemaName(documentModel) {
267
- return pascalCase(documentModel.name.replaceAll("/", " "));
268
- }
269
466
  /** The name the model's own subgraph registers under. */
270
467
  function getDocumentModelSubgraphName(documentModel) {
271
468
  return kebabCase(documentModel.name);
@@ -470,7 +667,6 @@ function generatedTypesFrom(documentModels, scalars) {
470
667
  scalars
471
668
  };
472
669
  }
473
- const hasValidSchema = (schema) => !!(schema && /\b(input|type|enum|union|interface)\s+\w+/.test(schema));
474
670
  /** Whether any operation of the latest specification has a schema. */
475
671
  function hasOperationSchemas(documentModel) {
476
672
  const specification = documentModel.specifications.at(-1);
@@ -713,244 +909,87 @@ function applyGraphQLTypePrefixes(schema, prefix, externalTypeNames = []) {
713
909
  * @returns GraphQL DocumentNode
714
910
  */
715
911
  function generateDocumentModelSchema(documentModel, options = {}) {
716
- const { useNewApi = false } = options;
912
+ return generateModelSchema(storedModelProjection(documentModel, getDocumentModelSchemaName(documentModel)), options);
913
+ }
914
+ /** Reads the template inputs out of a model's stored SDL. */
915
+ function storedModelProjection(documentModel, documentName) {
717
916
  const specification = documentModel.specifications.at(-1);
718
- const documentName = getDocumentModelSchemaName(documentModel);
719
917
  const globalStateSchema = specification?.state.global.schema;
720
918
  const localStateSchema = specification?.state.local.schema;
721
- const globalStateTypeNames = extractTypeNames(globalStateSchema ?? "");
722
- const localStateTypeNames = extractTypeNames(localStateSchema ?? "");
723
- const stateTypeNames = [...globalStateTypeNames, ...localStateTypeNames];
919
+ const stateTypeNames = [...extractTypeNames(globalStateSchema ?? ""), ...extractTypeNames(localStateSchema ?? "")];
724
920
  const allOperationTypeNames = specification?.modules.flatMap((module) => module.operations.flatMap((op) => extractTypeNames(op.schema ?? ""))) ?? [];
725
921
  const allTypeNames = [.../* @__PURE__ */ new Set([...stateTypeNames, ...allOperationTypeNames])];
726
- const operationInputTypeNames = new Set(allOperationTypeNames);
727
- const prefixedStateInputTypes = applyGraphQLTypePrefixes(extractInputTypeDefinitions(globalStateSchema ?? "", operationInputTypeNames), documentName, allTypeNames);
728
- if (useNewApi) return generateNewApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema);
729
- return generateLegacyApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema);
730
- }
731
- /**
732
- * Generate legacy API schema with nested queries
733
- */
734
- function generateLegacyApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema) {
735
- const createDocumentMutation = `${documentName}_createDocument(name:String!, driveId:String): String`;
736
- const operationMutations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).map((op) => `${documentName}_${camelCase(op.name)}(
737
- driveId: String, docId: PHID, input: ${documentName}_${pascalCase(op.name)}Input): Int`)).join("\n ") ?? "";
738
- const moduleSchemas = buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema);
739
- return gql`
740
- """
741
- Queries: ${documentName} Document
742
- """
743
-
744
- type ${documentName}Queries {
745
- getDocument(docId: PHID!, driveId: PHID): ${documentName}
746
- getDocuments(driveId: String!): [${documentName}!]
747
- }
748
-
749
- type Query {
750
- ${documentName}: ${documentName}Queries
751
- }
752
-
753
- """
754
- Mutations: ${documentName}
755
- """
756
- type Mutation {
757
- ${createDocumentMutation}
758
-
759
- ${operationMutations}
760
- }
761
-
762
- ${prefixedStateInputTypes ? `"""
763
- Input Types from State Schema
764
- """
765
- ${prefixedStateInputTypes}` : ""}
766
-
767
- ${moduleSchemas}`;
922
+ const prefixedStateInputTypes = applyGraphQLTypePrefixes(extractInputTypeDefinitions(globalStateSchema ?? "", new Set(allOperationTypeNames)), documentName, allTypeNames);
923
+ const operations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).map((op) => ({
924
+ camelName: camelCase(op.name),
925
+ inputTypeName: `${documentName}_${pascalCase(op.name)}Input`
926
+ }))) ?? [];
927
+ const names = new Set(allTypeNames);
928
+ return {
929
+ documentName,
930
+ operations,
931
+ modules: specification?.modules.flatMap((module) => {
932
+ const definitions = module.operations.filter((op) => hasValidSchema(op.schema)).flatMap((op) => {
933
+ const doc = parseSdl(op.schema ?? "");
934
+ return prefixTypeNames(doc, documentName, /* @__PURE__ */ new Set([...names, ...definedTypeNames(doc, ALL_PREFIX_KINDS)])).definitions;
935
+ });
936
+ return definitions.length === 0 ? [] : [{
937
+ name: module.name,
938
+ sdl: print({
939
+ kind: Kind.DOCUMENT,
940
+ definitions
941
+ })
942
+ }];
943
+ }) ?? [],
944
+ stateInputTypes: prefixedStateInputTypes,
945
+ globalStateTypeName: documentName === "DocumentModel" ? `${documentName}_${documentName}GlobalState` : `${documentName}_${documentName}State`,
946
+ localStateTypeName: (localStateSchema ?? "").includes(`type ${documentName}LocalState`) ? `${documentName}_${documentName}LocalState` : null,
947
+ initialState: storedInitialState(specification, documentName, allTypeNames)
948
+ };
768
949
  }
769
- /**
770
- * Generate new API schema with flat queries, typed state, and async mutations.
771
- * Note: State schema types are NOT included here because they are already defined
772
- * in getDocumentModelTypeDefs() which is used during schema composition.
773
- * Including them here would cause duplicate type definitions.
774
- */
775
- function generateNewApiSchema(documentName, specification, prefixedStateInputTypes, allTypeNames, hasValidSchema) {
776
- const stateType = `${documentName}_FullState!`;
777
- const sharedBaseTypes = `
778
- """Hash configuration for document state"""
779
- type ${documentName}_PHHashConfig {
780
- algorithm: String!
781
- encoding: String!
782
- }
783
-
784
- """Document scope state (same for all document types)"""
785
- type ${documentName}_PHDocumentScopeState {
786
- version: Int!
787
- hash: ${documentName}_PHHashConfig!
788
- isDeleted: Boolean
789
- deletedAtUtcIso: String
790
- deletedBy: String
791
- deletionReason: String
792
- }
793
- `;
794
- const hasLocalStateType = (specification?.state.local.schema ?? "").includes(`type ${documentName}LocalState`);
795
- const fullStateType = `
796
- """Full state with all scopes for ${documentName}"""
797
- type ${documentName}_FullState {
798
- auth: JSONObject!
799
- document: ${documentName}_PHDocumentScopeState!
800
- global: ${documentName === "DocumentModel" ? `${documentName}_${documentName}GlobalState!` : `${documentName}_${documentName}State!`}
801
- local: ${!hasLocalStateType ? "JSONObject!" : `${documentName}_${documentName}LocalState!`}
802
- }
803
- `;
804
- const commonInputTypes = `
805
- input ${documentName}_ViewFilterInput {
806
- branch: String
807
- scopes: [String!]
808
- }
809
-
810
- input ${documentName}_PagingInput {
811
- limit: Int
812
- offset: Int
813
- cursor: String
814
- }
815
-
816
- input ${documentName}_SearchFilterInput {
817
- parentId: String
818
- identifiers: [String!] @deprecated(reason: "Ignored. Filter by parentId.")
819
- }
820
- `;
821
- const revisionType = RevisionType;
822
- const resultTypes = `
823
- """
824
- Mutation result type for ${documentName} operations with typed state.
825
- Matches ReactorSubgraph PHDocument pattern with revisionsList.
826
- """
827
- type ${documentName}MutationResult {
828
- id: String!
829
- slug: String
830
- preferredEditor: String
831
- name: String!
832
- documentType: String!
833
- state: ${stateType}
834
- revisionsList: [Revision!]!
835
- createdAtUtcIso: DateTime!
836
- lastModifiedAtUtcIso: DateTime!
837
- }
838
-
839
- """
840
- Document with children for ${documentName}
841
- """
842
- type ${documentName}_DocumentWithChildren {
843
- document: ${documentName}MutationResult!
844
- childIds: [String!]!
845
- }
846
-
847
- """
848
- Paginated result type for ${documentName} documents
849
- """
850
- type ${documentName}_DocumentResultPage {
851
- items: [${documentName}MutationResult!]!
852
- hasNextPage: Boolean!
853
- hasPreviousPage: Boolean!
854
- cursor: String
855
- }
856
- `;
857
- const queries = `
858
- type ${documentName}Queries {
859
- """Get a specific ${documentName} document by identifier"""
860
- document(idOrSlug: String, identifier: String @deprecated(reason: "Use idOrSlug."), view: ${documentName}_ViewFilterInput): ${documentName}_DocumentWithChildren
861
-
862
- """Get all ${documentName} documents (paged)"""
863
- documents(paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
864
-
865
- """Find ${documentName} documents by search criteria"""
866
- findDocuments(search: ${documentName}_SearchFilterInput, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
867
-
868
- """Get outgoing relationships of a ${documentName} document"""
869
- documentOutgoingRelationships(sourceIdOrSlug: String, sourceIdentifier: String @deprecated(reason: "Use sourceIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
870
-
871
- """Get incoming relationships to a ${documentName} document"""
872
- documentIncomingRelationships(targetIdOrSlug: String, targetIdentifier: String @deprecated(reason: "Use targetIdOrSlug."), relationshipType: String!, view: ${documentName}_ViewFilterInput, paging: ${documentName}_PagingInput): ${documentName}_DocumentResultPage!
873
- }
874
- `;
875
- let initialStateInputSchema = "";
876
- if (specification) {
877
- const scopeFields = [];
878
- const generatedInputTypeParts = [];
879
- for (const [scopeName, scopeState] of Object.entries(specification.state)) {
880
- const schema = scopeState.schema ?? "";
881
- if (hasValidSchema(schema)) {
882
- const rootTypeName = extractRootTypeName(schema, documentName, scopeName);
883
- if (!rootTypeName) {
884
- scopeFields.push(` ${scopeName}: JSONObject`);
885
- continue;
886
- }
887
- const scopeInputTypes = generateStateInputTypes(schema, new Set(allTypeNames));
888
- if (!scopeInputTypes) {
889
- scopeFields.push(` ${scopeName}: JSONObject`);
890
- continue;
891
- }
892
- const prefixedScopeInputTypes = applyGraphQLTypePrefixes(scopeInputTypes, documentName, allTypeNames);
893
- scopeFields.push(` ${scopeName}: ${documentName}_${rootTypeName}Input`);
894
- generatedInputTypeParts.push(prefixedScopeInputTypes);
895
- } else scopeFields.push(` ${scopeName}: JSONObject`);
950
+ /** The new API's initial-state argument, read out of the stored scope SDL. */
951
+ function storedInitialState(specification, documentName, allTypeNames) {
952
+ const scopes = [];
953
+ const generatedInputTypeParts = [];
954
+ if (!specification) return {
955
+ inputTypes: "",
956
+ scopes
957
+ };
958
+ for (const [scopeName, scopeState] of Object.entries(specification.state)) {
959
+ const schema = scopeState.schema ?? "";
960
+ if (!hasValidSchema(schema)) {
961
+ scopes.push({
962
+ name: scopeName,
963
+ type: "JSONObject"
964
+ });
965
+ continue;
966
+ }
967
+ const rootTypeName = extractRootTypeName(schema, documentName, scopeName);
968
+ if (!rootTypeName) {
969
+ scopes.push({
970
+ name: scopeName,
971
+ type: "JSONObject"
972
+ });
973
+ continue;
896
974
  }
897
- if (scopeFields.length > 0) {
898
- const inputTypeDefs = generatedInputTypeParts.join("\n\n");
899
- const wrapper = `input ${documentName}_InitialStateInput {\n${scopeFields.join("\n")}\n}`;
900
- initialStateInputSchema = inputTypeDefs ? `${inputTypeDefs}\n\n${wrapper}` : wrapper;
975
+ const scopeInputTypes = generateStateInputTypes(schema, new Set(allTypeNames));
976
+ if (!scopeInputTypes) {
977
+ scopes.push({
978
+ name: scopeName,
979
+ type: "JSONObject"
980
+ });
981
+ continue;
901
982
  }
983
+ scopes.push({
984
+ name: scopeName,
985
+ type: `${documentName}_${rootTypeName}Input`
986
+ });
987
+ generatedInputTypeParts.push(applyGraphQLTypePrefixes(scopeInputTypes, documentName, allTypeNames));
902
988
  }
903
- 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!`;
904
- const createEmptyDocumentMutation = `createEmptyDocument(parentIdOrSlug: String, parentIdentifier: String @deprecated(reason: "Use parentIdOrSlug.")): ${documentName}MutationResult!`;
905
- const operationMutations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).flatMap((op) => [`${camelCase(op.name)}(documentIdOrSlug: String, docId: PHID @deprecated(reason: "Use documentIdOrSlug."), input: ${documentName}_${pascalCase(op.name)}Input!): ${documentName}MutationResult!`, `${camelCase(op.name)}Async(documentIdOrSlug: String, docId: PHID @deprecated(reason: "Use documentIdOrSlug."), input: ${documentName}_${pascalCase(op.name)}Input!): String!`])).join("\n ") ?? "";
906
- const moduleSchemas = buildModuleSchemas(specification, documentName, allTypeNames, hasValidSchema);
907
- return gql`
908
- ${catalogScalarSdl}
909
-
910
- ${revisionType}
911
-
912
- ${sharedBaseTypes}
913
-
914
- ${fullStateType}
915
-
916
- ${commonInputTypes}
917
-
918
- ${resultTypes}
919
-
920
- """
921
- Queries: ${documentName} Document
922
- """
923
- ${queries}
924
-
925
- """
926
- Mutations: ${documentName}
927
- """
928
- type ${documentName}Mutations {
929
- ${createDocumentMutation}
930
- ${createEmptyDocumentMutation}
931
-
932
- ${operationMutations}
933
- }
934
-
935
- type Query {
936
- ${documentName}: ${documentName}Queries!
937
- }
938
-
939
- type Mutation {
940
- ${documentName}: ${documentName}Mutations!
941
- }
942
-
943
- ${prefixedStateInputTypes ? `"""
944
- Input Types from State Schema
945
- """
946
- ${prefixedStateInputTypes}` : ""}
947
-
948
- ${initialStateInputSchema ? `"""
949
- Input Types for Initial State
950
- """
951
- ${initialStateInputSchema}` : ""}
952
-
953
- ${moduleSchemas}`;
989
+ return {
990
+ inputTypes: generatedInputTypeParts.join("\n\n"),
991
+ scopes
992
+ };
954
993
  }
955
994
  //#endregion
956
995
  //#region src/graphql/subgraph-type-ownership.ts
@@ -1091,47 +1130,46 @@ function rank(origin) {
1091
1130
  if (origin === DOCUMENT_MODEL_ORIGIN) return 1;
1092
1131
  return 0;
1093
1132
  }
1133
+ /**
1134
+ * The server's decision on one built model: it refuses a model whose schema
1135
+ * does not build or that generates a reserved type name.
1136
+ */
1137
+ function admitDocumentModel(resolved, reserved) {
1138
+ if (resolved.schema === void 0) return {
1139
+ admitted: false,
1140
+ reason: `has an unusable schema: ${resolved.error.message}`
1141
+ };
1142
+ const { model, schema } = resolved;
1143
+ const taken = reservedTypeNamesTaken(model, reserved, schema.generated);
1144
+ if (taken.length > 0) return {
1145
+ admitted: false,
1146
+ reason: `generates reserved type names: ${taken.join(", ")}`
1147
+ };
1148
+ return {
1149
+ admitted: true,
1150
+ schema,
1151
+ ...schema.subgraphError !== void 0 && { subgraphRefusal: `has an unusable subgraph schema: ${schema.subgraphError.message}` }
1152
+ };
1153
+ }
1094
1154
  /** Usable models; a refused latest version refuses every version of its model. */
1095
1155
  function admitDocumentModels(resolved, reserved) {
1096
- const latest = new Set(filterLatestDocumentModelVersions(resolved.map(({ model }) => model)));
1097
- const candidates = [];
1098
- for (const { model, key, schema, error } of resolved) {
1099
- if (!schema) {
1100
- const reason = `has an unusable schema: ${error.message}`;
1101
- candidates.push({
1102
- model,
1103
- key,
1104
- refusal: {
1105
- reason,
1106
- subgraphOnly: false
1107
- }
1108
- });
1109
- continue;
1110
- }
1111
- const taken = reservedTypeNamesTaken(model, reserved, schema.generated);
1112
- if (taken.length > 0) {
1113
- const reason = `generates reserved type names: ${taken.join(", ")}`;
1114
- candidates.push({
1115
- model,
1116
- key,
1117
- refusal: {
1118
- reason,
1119
- subgraphOnly: false
1120
- }
1121
- });
1122
- continue;
1123
- }
1124
- const refusal = schema.subgraphError && {
1125
- reason: `has an unusable subgraph schema: ${schema.subgraphError.message}`,
1156
+ const latest = new Set(latestDocumentModelVersions(resolved.map(({ model }) => model)));
1157
+ const candidates = resolved.map((entry) => {
1158
+ const verdict = admitDocumentModel(entry, reserved);
1159
+ const refusal = !verdict.admitted ? {
1160
+ reason: verdict.reason,
1161
+ subgraphOnly: false
1162
+ } : verdict.subgraphRefusal !== void 0 ? {
1163
+ reason: verdict.subgraphRefusal,
1126
1164
  subgraphOnly: true
1127
- };
1128
- candidates.push({
1129
- model,
1130
- key,
1131
- schema,
1165
+ } : void 0;
1166
+ return {
1167
+ model: entry.model,
1168
+ key: entry.key,
1169
+ schema: verdict.admitted ? verdict.schema : void 0,
1132
1170
  refusal
1133
- });
1134
- }
1171
+ };
1172
+ });
1135
1173
  const refusedModels = new Set(candidates.filter(({ model, refusal }) => refusal && latest.has(model)).map(({ model }) => model.documentModel.global.name));
1136
1174
  const admission = {
1137
1175
  admitted: [],
@@ -1144,7 +1182,7 @@ function admitDocumentModels(resolved, reserved) {
1144
1182
  if (refusal) admission.refusals.push({
1145
1183
  model,
1146
1184
  key,
1147
- version: specVersion(model),
1185
+ version: documentModelVersion(model),
1148
1186
  everyVersion,
1149
1187
  ...refusal
1150
1188
  });
@@ -1156,21 +1194,25 @@ function admitDocumentModels(resolved, reserved) {
1156
1194
  return admission;
1157
1195
  }
1158
1196
  const DOCUMENT_MODELS_TO_EXCLUDE = [];
1159
- const specVersion = (model) => model.documentModel.global.specifications.at(-1)?.version ?? 0;
1160
- /** The latest version of each document model. */
1161
- function filterLatestDocumentModelVersions(documentModels) {
1197
+ /** The version of a model: its latest specification's. */
1198
+ const documentModelVersion = (model) => model.documentModel.global.specifications.at(-1)?.version ?? 0;
1199
+ /**
1200
+ * The latest version of each model, by name: the only one whose own subgraph
1201
+ * the server registers.
1202
+ */
1203
+ function latestDocumentModelVersions(documentModels) {
1162
1204
  const latestByName = /* @__PURE__ */ new Map();
1163
1205
  for (const documentModel of documentModels) {
1164
- const name = documentModel.documentModel.global.name;
1206
+ const { name } = documentModel.documentModel.global;
1165
1207
  const existing = latestByName.get(name);
1166
- if (!existing || specVersion(documentModel) > specVersion(existing)) latestByName.set(name, documentModel);
1208
+ if (!existing || documentModelVersion(documentModel) > documentModelVersion(existing)) latestByName.set(name, documentModel);
1167
1209
  }
1168
1210
  return Array.from(latestByName.values());
1169
1211
  }
1170
1212
  /** The admitted models that serve a subgraph of their own, with its types. */
1171
1213
  function documentModelSubgraphSources(admitted, schemas) {
1172
1214
  const sources = [];
1173
- for (const model of filterLatestDocumentModelVersions(admitted)) {
1215
+ for (const model of latestDocumentModelVersions(admitted)) {
1174
1216
  if (DOCUMENT_MODELS_TO_EXCLUDE.includes(model.documentModel.global.id)) continue;
1175
1217
  const types = schemas.get(model)?.subgraph;
1176
1218
  if (types) sources.push({
@@ -1582,7 +1624,7 @@ const baseDocumentModels = [
1582
1624
  ["reactor-group", ReactorGroupV1]
1583
1625
  ];
1584
1626
  //#endregion
1585
- export { getDocumentModelSubgraphName as A, createMergedSchema as C, generateDocumentModelSchema as D, findSubgraphTypeCollisions as E, reservedTypeNamesTaken as F, typeDefinitionNames as I, EMPTY_SCALAR_REGISTRY as L, getGeneratedDocumentModelTypes as M, hasOperationSchemas as N, generatedTypesOf as O, reservedTypeNames as P, sameScalarRegistry as R, buildSubgraphSchemaModule as S, documentModelSubgraphTypes as T, 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, getDocumentModelTypeDefs as j, getDocumentModelSchemaName 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, schema_default$1 as z };
1627
+ export { getDocumentModelTypeDefs as A, createMergedSchema as C, generateDocumentModelSchema as D, findSubgraphTypeCollisions as E, typeDefinitionNames as F, getDocumentModelSchemaName as I, EMPTY_SCALAR_REGISTRY as L, hasOperationSchemas as M, reservedTypeNames as N, generatedTypesOf as O, reservedTypeNamesTaken as P, sameScalarRegistry as R, buildSubgraphSchemaModule as S, documentModelSubgraphTypes as T, 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, schema_default$1 as z };
1586
1628
 
1587
- //# sourceMappingURL=base-document-models-sJ25SjR4.mjs.map
1588
- //# debugId=926b8930-da2c-543f-89c7-59d1cbf32444
1629
+ //# sourceMappingURL=base-document-models-DZfYOd9M.mjs.map
1630
+ //# debugId=d164cc5a-09cc-53c9-b196-24ebff89d427