@powerhousedao/reactor-api 6.2.3-dev.93 → 6.2.3-dev.95
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{base-document-models-CNHrVpOU.mjs → base-document-models-CCYv5XxL.mjs} +518 -302
- package/dist/base-document-models-CCYv5XxL.mjs.map +1 -0
- package/dist/{create-schema-ClPWjRPY.d.mts → create-schema-DJzlm_Fz.d.mts} +16 -12
- package/dist/create-schema-DJzlm_Fz.d.mts.map +1 -0
- package/dist/index.d.mts +78 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +131 -36
- package/dist/index.mjs.map +1 -1
- package/dist/{package-subgraph-check-DdZLhOHW.mjs → package-subgraph-check-DPlf58ps.mjs} +4 -4
- package/dist/{package-subgraph-check-DdZLhOHW.mjs.map → package-subgraph-check-DPlf58ps.mjs.map} +1 -1
- package/dist/src/graphql/subgraph-types.d.mts +1 -1
- package/dist/src/graphql/subgraph-types.mjs +1 -1
- package/dist/src/packages/vite-loader.d.mts +1 -1
- package/dist/src/packages/vite-loader.d.mts.map +1 -1
- package/dist/src/packages/vite-loader.mjs +17 -10
- package/dist/src/packages/vite-loader.mjs.map +1 -1
- package/dist/{subgraph-extraction-DioqM_Dc.mjs → subgraph-extraction-C_hFvSaS.mjs} +9 -4
- package/dist/{subgraph-extraction-DioqM_Dc.mjs.map → subgraph-extraction-C_hFvSaS.mjs.map} +1 -1
- package/dist/{types-PXB1ctpi.d.mts → types-Bz_xjf8j.d.mts} +8 -2
- package/dist/types-Bz_xjf8j.d.mts.map +1 -0
- package/package.json +13 -13
- package/dist/base-document-models-CNHrVpOU.mjs.map +0 -1
- package/dist/create-schema-ClPWjRPY.d.mts.map +0 -1
- package/dist/types-PXB1ctpi.d.mts.map +0 -1
|
@@ -1,15 +1,15 @@
|
|
|
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]="
|
|
3
|
-
import { childLogger, documentModelDocumentModelModule } from "document-model";
|
|
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]="392c1b84-7a7a-5715-91f3-f9595a6367d3")}catch(e){}}();
|
|
3
|
+
import { childLogger, documentModelDocumentModelModule, inspectDocumentModelDefinition, projectDocumentModelGraphQL } 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";
|
|
6
6
|
import { createHash } from "node:crypto";
|
|
7
7
|
import { scalarCatalog } from "document-model/scalars";
|
|
8
|
+
import { camelCase, kebabCase, pascalCase } from "change-case";
|
|
8
9
|
import { GraphQLJSON, GraphQLJSONObject } from "graphql-type-json";
|
|
9
10
|
import { inspect, isDeepStrictEqual } from "node:util";
|
|
10
11
|
import { z } from "zod";
|
|
11
12
|
import { buildSubgraphSchema } from "@apollo/subgraph";
|
|
12
|
-
import { camelCase, kebabCase, pascalCase } from "change-case";
|
|
13
13
|
import { reactorDriveDocumentModelModule } from "@powerhousedao/reactor-drive";
|
|
14
14
|
import { ReactorGroupV1 } from "@powerhousedao/reactor-group";
|
|
15
15
|
import { driveDocumentModelModule } from "@powerhousedao/shared/document-drive";
|
|
@@ -320,59 +320,7 @@ function generateNewApiSchema(projection) {
|
|
|
320
320
|
${printModuleSchemas(projection.modules)}`;
|
|
321
321
|
}
|
|
322
322
|
//#endregion
|
|
323
|
-
//#region src/
|
|
324
|
-
const logger = childLogger(["reactor-api", "create-schema"]);
|
|
325
|
-
/**
|
|
326
|
-
* A subgraph defines a type whose name the generated document-model schema
|
|
327
|
-
* owns, so one of the two definitions would be lost.
|
|
328
|
-
*/
|
|
329
|
-
var SubgraphTypeCollisionError = class extends Error {
|
|
330
|
-
typeNames;
|
|
331
|
-
constructor(typeNames) {
|
|
332
|
-
super(`Subgraph defines types reserved by the document-model schema: ${typeNames.join(", ")}`);
|
|
333
|
-
this.name = "SubgraphTypeCollisionError";
|
|
334
|
-
this.typeNames = typeNames;
|
|
335
|
-
}
|
|
336
|
-
};
|
|
337
|
-
/**
|
|
338
|
-
* Type-system definition kinds that GraphQL requires to be uniquely named.
|
|
339
|
-
* A subgraph SDL with two definitions sharing a name fails federation
|
|
340
|
-
* composition ("There can be only one type named X"), which is fatal to the
|
|
341
|
-
* whole gateway. We dedupe these by name; field/operation/extension nodes are
|
|
342
|
-
* left untouched.
|
|
343
|
-
*/
|
|
344
|
-
const TYPE_DEFINITION_KINDS = /* @__PURE__ */ new Set([
|
|
345
|
-
Kind.OBJECT_TYPE_DEFINITION,
|
|
346
|
-
Kind.ENUM_TYPE_DEFINITION,
|
|
347
|
-
Kind.INPUT_OBJECT_TYPE_DEFINITION,
|
|
348
|
-
Kind.INTERFACE_TYPE_DEFINITION,
|
|
349
|
-
Kind.UNION_TYPE_DEFINITION,
|
|
350
|
-
Kind.SCALAR_TYPE_DEFINITION
|
|
351
|
-
]);
|
|
352
|
-
/**
|
|
353
|
-
* Drop duplicate type-system definitions by name, keeping the first occurrence.
|
|
354
|
-
* Deduping is by name across ALL kinds (a `type` and an `enum` sharing a name
|
|
355
|
-
* collide in GraphQL too), so the first definition of a given name wins
|
|
356
|
-
* regardless of kind. State types are emitted before operation types, so
|
|
357
|
-
* keep-first preserves the authoritative state definition. This heals a document
|
|
358
|
-
* model that defines the same name twice (global+local, state+operation, or
|
|
359
|
-
* twice in one scope) so the assembled subgraph SDL composes instead of crashing
|
|
360
|
-
* the gateway (Sentry #917).
|
|
361
|
-
*/
|
|
362
|
-
const dedupeTypeDefinitions = (definitions, seen = /* @__PURE__ */ new Set()) => definitions.filter((def) => {
|
|
363
|
-
const name = typeDefinitionName(def);
|
|
364
|
-
if (name === void 0) return true;
|
|
365
|
-
if (seen.has(name)) {
|
|
366
|
-
logger.debug(`Dropping duplicate type definition: ${name}`);
|
|
367
|
-
return false;
|
|
368
|
-
}
|
|
369
|
-
seen.add(name);
|
|
370
|
-
return true;
|
|
371
|
-
});
|
|
372
|
-
function typeDefinitionName(def) {
|
|
373
|
-
if (!TYPE_DEFINITION_KINDS.has(def.kind)) return void 0;
|
|
374
|
-
return def.name?.value;
|
|
375
|
-
}
|
|
323
|
+
//#region src/graphql/document-model-schema/schema-ast.ts
|
|
376
324
|
const EMPTY_DOCUMENT = {
|
|
377
325
|
kind: Kind.DOCUMENT,
|
|
378
326
|
definitions: []
|
|
@@ -435,8 +383,498 @@ function prefixTypeNames(doc, prefix, names) {
|
|
|
435
383
|
} });
|
|
436
384
|
}
|
|
437
385
|
/** State schema definitions without inputs, `DateTime` or the given object types. */
|
|
438
|
-
function
|
|
439
|
-
return
|
|
386
|
+
function stateDefinitions(doc, droppedObjectTypes = /* @__PURE__ */ new Set()) {
|
|
387
|
+
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)));
|
|
388
|
+
}
|
|
389
|
+
/** The state types and the document type a model adds to the generated schema. */
|
|
390
|
+
function generatedModelDefinitions(dmSchemaName, global, local) {
|
|
391
|
+
const stateDoc = {
|
|
392
|
+
kind: Kind.DOCUMENT,
|
|
393
|
+
definitions: [...stateDefinitions(global), ...stateDefinitions(local, LOCAL_STATE_STUBS)]
|
|
394
|
+
};
|
|
395
|
+
const prefixed = prefixTypeNames(stateDoc, dmSchemaName, new Set(definedTypeNames(stateDoc, STATE_PREFIX_KINDS)));
|
|
396
|
+
const documentType = parseSdl(`
|
|
397
|
+
type ${dmSchemaName} implements IDocument {
|
|
398
|
+
id: String!
|
|
399
|
+
name: String!
|
|
400
|
+
documentType: String!
|
|
401
|
+
operations(skip: Int, first: Int): [Operation!]!
|
|
402
|
+
revision: Int!
|
|
403
|
+
createdAtUtcIso: DateTime!
|
|
404
|
+
lastModifiedAtUtcIso: DateTime!
|
|
405
|
+
${dmSchemaName !== "DocumentModel" ? `initialState: ${dmSchemaName}_${dmSchemaName}State!` : ""}
|
|
406
|
+
${dmSchemaName !== "DocumentModel" ? `state: ${dmSchemaName}_${dmSchemaName}State!` : ""}
|
|
407
|
+
stateJSON: JSONObject
|
|
408
|
+
}`);
|
|
409
|
+
return [...prefixed.definitions, ...documentType.definitions];
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* Print the input type definitions of a schema document.
|
|
413
|
+
* @param excludeTypeNames - Input type names to leave out
|
|
414
|
+
*/
|
|
415
|
+
function printInputTypeDefinitions(doc, excludeTypeNames = /* @__PURE__ */ new Set()) {
|
|
416
|
+
const definitions = doc.definitions.filter((def) => def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION && !excludeTypeNames.has(def.name.value));
|
|
417
|
+
if (definitions.length === 0) return "";
|
|
418
|
+
return print({
|
|
419
|
+
kind: Kind.DOCUMENT,
|
|
420
|
+
definitions
|
|
421
|
+
});
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Apply type prefixes to GraphQL schema to namespace types and avoid collisions.
|
|
425
|
+
* Inlined from @powerhousedao/common/utils to avoid ES module import issues.
|
|
426
|
+
* @param {string} schema - GraphQL schema string
|
|
427
|
+
* @param {string} prefix - Prefix to apply to type names
|
|
428
|
+
* @param {string[]} externalTypeNames - Type names from other schemas to also prefix
|
|
429
|
+
* @returns {string} Schema with prefixed types
|
|
430
|
+
*/
|
|
431
|
+
function applyGraphQLTypePrefixes(schema, prefix, externalTypeNames = []) {
|
|
432
|
+
if (!schema || !schema.trim()) return schema;
|
|
433
|
+
const doc = parseSdl(schema);
|
|
434
|
+
const names = /* @__PURE__ */ new Set([...definedTypeNames(doc, ALL_PREFIX_KINDS), ...externalTypeNames]);
|
|
435
|
+
if (names.size === 0) return schema;
|
|
436
|
+
return print(prefixTypeNames(doc, prefix, names));
|
|
437
|
+
}
|
|
438
|
+
function printModuleOperations(operations, documentName, names) {
|
|
439
|
+
const definitions = operations.flatMap((doc) => {
|
|
440
|
+
return prefixTypeNames(doc, documentName, /* @__PURE__ */ new Set([...names, ...definedTypeNames(doc, ALL_PREFIX_KINDS)])).definitions;
|
|
441
|
+
});
|
|
442
|
+
return definitions.length === 0 ? null : print({
|
|
443
|
+
kind: Kind.DOCUMENT,
|
|
444
|
+
definitions
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
function globalStateTypeName(documentName) {
|
|
448
|
+
return documentName === "DocumentModel" ? `${documentName}_${documentName}GlobalState` : `${documentName}_${documentName}State`;
|
|
449
|
+
}
|
|
450
|
+
/**
|
|
451
|
+
* Extract the root state type name from a scope's GraphQL schema.
|
|
452
|
+
* Uses the naming convention: {DocumentName}State for global,
|
|
453
|
+
* {DocumentName}{PascalScope}State for other scopes (e.g., DocumentDriveLocalState).
|
|
454
|
+
* Falls back to the last ObjectTypeDefinition (root types are conventionally last).
|
|
455
|
+
*/
|
|
456
|
+
function rootTypeName(ast, documentName, scopeName) {
|
|
457
|
+
const candidates = [`${documentName}${scopeName === "global" ? "" : pascalCase(scopeName)}State`, `${documentName}${pascalCase(scopeName)}State`];
|
|
458
|
+
let lastObjectType = null;
|
|
459
|
+
for (const def of ast.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) {
|
|
460
|
+
if (candidates.includes(def.name.value)) return def.name.value;
|
|
461
|
+
lastObjectType = def.name.value;
|
|
462
|
+
}
|
|
463
|
+
return lastObjectType;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Convert a GraphQL output type AST node to an optional input type string.
|
|
467
|
+
* Strips non-null markers and converts object type references to Input suffix.
|
|
468
|
+
*/
|
|
469
|
+
function convertTypeNodeToInput(typeNode, objectNames, unionNames, interfaceNames) {
|
|
470
|
+
if (typeNode.kind === Kind.NON_NULL_TYPE && typeNode.type) return convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames);
|
|
471
|
+
if (typeNode.kind === Kind.LIST_TYPE && typeNode.type) return `[${convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames)}]`;
|
|
472
|
+
if (typeNode.kind === Kind.NAMED_TYPE && typeNode.name) {
|
|
473
|
+
const name = typeNode.name.value;
|
|
474
|
+
if (objectNames.has(name)) return `${name}Input`;
|
|
475
|
+
if (unionNames.has(name) || interfaceNames.has(name)) return "JSONObject";
|
|
476
|
+
return name;
|
|
477
|
+
}
|
|
478
|
+
return "JSONObject";
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Generate GraphQL input type definitions from a state schema document.
|
|
482
|
+
* Converts output type definitions to input types with all fields optional.
|
|
483
|
+
* - Object type references get Input suffix
|
|
484
|
+
* - Union/interface references become JSONObject
|
|
485
|
+
* - Enums and scalars remain unchanged
|
|
486
|
+
*/
|
|
487
|
+
function stateInputTypes(ast, excludeTypeNames) {
|
|
488
|
+
const enumNames = /* @__PURE__ */ new Set();
|
|
489
|
+
const unionNames = /* @__PURE__ */ new Set();
|
|
490
|
+
const interfaceNames = /* @__PURE__ */ new Set();
|
|
491
|
+
const objectNames = /* @__PURE__ */ new Set();
|
|
492
|
+
const existingInputNames = /* @__PURE__ */ new Set();
|
|
493
|
+
for (const def of ast.definitions) switch (def.kind) {
|
|
494
|
+
case Kind.ENUM_TYPE_DEFINITION:
|
|
495
|
+
enumNames.add(def.name.value);
|
|
496
|
+
break;
|
|
497
|
+
case Kind.UNION_TYPE_DEFINITION:
|
|
498
|
+
unionNames.add(def.name.value);
|
|
499
|
+
break;
|
|
500
|
+
case Kind.INTERFACE_TYPE_DEFINITION:
|
|
501
|
+
interfaceNames.add(def.name.value);
|
|
502
|
+
break;
|
|
503
|
+
case Kind.OBJECT_TYPE_DEFINITION:
|
|
504
|
+
objectNames.add(def.name.value);
|
|
505
|
+
break;
|
|
506
|
+
case Kind.INPUT_OBJECT_TYPE_DEFINITION: existingInputNames.add(def.name.value);
|
|
507
|
+
}
|
|
508
|
+
const inputTypes = [];
|
|
509
|
+
for (const def of ast.definitions) {
|
|
510
|
+
if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;
|
|
511
|
+
const inputName = `${def.name.value}Input`;
|
|
512
|
+
if (existingInputNames.has(inputName)) continue;
|
|
513
|
+
if (excludeTypeNames?.has(inputName)) continue;
|
|
514
|
+
const fields = def.fields ?? [];
|
|
515
|
+
if (fields.length === 0) continue;
|
|
516
|
+
const inputFields = fields.map((field) => {
|
|
517
|
+
return ` ${field.name.value}: ${convertTypeNodeToInput(field.type, objectNames, unionNames, interfaceNames)}`;
|
|
518
|
+
});
|
|
519
|
+
inputTypes.push(`input ${def.name.value}Input {\n${inputFields.join("\n")}\n}`);
|
|
520
|
+
}
|
|
521
|
+
return inputTypes.join("\n\n");
|
|
522
|
+
}
|
|
523
|
+
function scopeInitialState(ast, documentName, scopeName, allTypeNames) {
|
|
524
|
+
const rootName = rootTypeName(ast, documentName, scopeName);
|
|
525
|
+
if (!rootName) return { type: "JSONObject" };
|
|
526
|
+
const scopeInputTypes = stateInputTypes(ast, new Set(allTypeNames));
|
|
527
|
+
if (!scopeInputTypes) return { type: "JSONObject" };
|
|
528
|
+
return {
|
|
529
|
+
type: `${documentName}_${rootName}Input`,
|
|
530
|
+
inputTypes: applyGraphQLTypePrefixes(scopeInputTypes, documentName, allTypeNames)
|
|
531
|
+
};
|
|
532
|
+
}
|
|
533
|
+
//#endregion
|
|
534
|
+
//#region src/graphql/document-model-schema/model-projection.ts
|
|
535
|
+
function buildModelProjection(documentName, documents) {
|
|
536
|
+
const allTypeNames = [.../* @__PURE__ */ new Set([...documents.stateTypeNames, ...documents.operationTypeNames])];
|
|
537
|
+
const names = new Set(allTypeNames);
|
|
538
|
+
const modules = documents.modules.flatMap(({ name, operations }) => {
|
|
539
|
+
const sdl = printModuleOperations(operations, documentName, names);
|
|
540
|
+
return sdl === null ? [] : [{
|
|
541
|
+
name,
|
|
542
|
+
sdl
|
|
543
|
+
}];
|
|
544
|
+
});
|
|
545
|
+
const scopes = documents.scopes.map(({ name, document }) => document === null ? {
|
|
546
|
+
name,
|
|
547
|
+
type: "JSONObject"
|
|
548
|
+
} : {
|
|
549
|
+
name,
|
|
550
|
+
...scopeInitialState(document, documentName, name, allTypeNames)
|
|
551
|
+
});
|
|
552
|
+
return {
|
|
553
|
+
documentName,
|
|
554
|
+
operations: documents.operations,
|
|
555
|
+
modules,
|
|
556
|
+
stateInputTypes: applyGraphQLTypePrefixes(printInputTypeDefinitions(documents.global, new Set(documents.operationTypeNames)), documentName, allTypeNames),
|
|
557
|
+
globalStateTypeName: globalStateTypeName(documentName),
|
|
558
|
+
localStateTypeName: documents.hasLocalRoot ? `${documentName}_${documentName}LocalState` : null,
|
|
559
|
+
initialState: {
|
|
560
|
+
inputTypes: scopes.flatMap(({ inputTypes }) => inputTypes ?? []).join("\n\n"),
|
|
561
|
+
scopes: scopes.map(({ name, type }) => ({
|
|
562
|
+
name,
|
|
563
|
+
type
|
|
564
|
+
}))
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
//#endregion
|
|
569
|
+
//#region src/graphql/document-model-schema/stored-projection.ts
|
|
570
|
+
const logger$2 = childLogger(["reactor-api", "create-schema"]);
|
|
571
|
+
/**
|
|
572
|
+
* Reads a model's schema out of its latest stored specification's SDL, on
|
|
573
|
+
* every call. Malformed SDL fails, or falls back, where it always has.
|
|
574
|
+
*/
|
|
575
|
+
function storedSchemaSource(global) {
|
|
576
|
+
return {
|
|
577
|
+
packageScalars: [],
|
|
578
|
+
hasOperationSchemas: () => {
|
|
579
|
+
const specification = global.specifications.at(-1);
|
|
580
|
+
if (!specification) return false;
|
|
581
|
+
return specification.modules.some((module) => module.operations.some((op) => hasValidSchema(op.schema)));
|
|
582
|
+
},
|
|
583
|
+
modelDefinitions: () => {
|
|
584
|
+
const dmSchemaName = getDocumentModelSchemaName(global);
|
|
585
|
+
const latestSpec = global.specifications.at(-1);
|
|
586
|
+
const globalSchema = latestSpec?.state.global.schema ?? "";
|
|
587
|
+
const localSchema = latestSpec?.state.local.schema ?? "";
|
|
588
|
+
return generatedModelDefinitions(dmSchemaName, parseSdl(globalSchema), parseSdl(localSchema));
|
|
589
|
+
},
|
|
590
|
+
modelProjection: () => {
|
|
591
|
+
const documentName = getDocumentModelSchemaName(global);
|
|
592
|
+
return buildModelProjection(documentName, storedDocuments(global.specifications.at(-1), documentName));
|
|
593
|
+
},
|
|
594
|
+
stateDefinitions: () => {
|
|
595
|
+
const specification = global.specifications.at(-1);
|
|
596
|
+
if (!specification) return [];
|
|
597
|
+
const fullSchema = `${specification.state.global.schema ?? ""}\n${specification.state.local.schema ?? ""}`;
|
|
598
|
+
if (!fullSchema.trim()) return [];
|
|
599
|
+
try {
|
|
600
|
+
return parse(fullSchema).definitions;
|
|
601
|
+
} catch {
|
|
602
|
+
return [];
|
|
603
|
+
}
|
|
604
|
+
},
|
|
605
|
+
mutationOperations: () => global.specifications.at(-1)?.modules.flatMap((module) => module.operations.filter((op) => op.name)).map((op) => ({
|
|
606
|
+
camelName: camelCase(op.name),
|
|
607
|
+
storedName: op.name,
|
|
608
|
+
creatorKey: camelCase(op.name)
|
|
609
|
+
})) ?? []
|
|
610
|
+
};
|
|
611
|
+
}
|
|
612
|
+
/**
|
|
613
|
+
* Type names a schema defines. Unparseable schemas yield no names.
|
|
614
|
+
*/
|
|
615
|
+
function extractTypeNames(schema) {
|
|
616
|
+
try {
|
|
617
|
+
return definedTypeNames(parseSdl(schema), ALL_PREFIX_KINDS);
|
|
618
|
+
} catch (error) {
|
|
619
|
+
logger$2.debug(`Skipping unparseable schema: ${String(error)}`);
|
|
620
|
+
return [];
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
/**
|
|
624
|
+
* The template documents of a stored specification. Type names skip
|
|
625
|
+
* unparseable schemas; the global state and served operation schemas must
|
|
626
|
+
* parse; a scope schema that does not parse strictly is served as `JSONObject`.
|
|
627
|
+
*/
|
|
628
|
+
function storedDocuments(specification, documentName) {
|
|
629
|
+
const globalStateSchema = specification?.state.global.schema;
|
|
630
|
+
const localStateSchema = specification?.state.local.schema;
|
|
631
|
+
const stateTypeNames = [...extractTypeNames(globalStateSchema ?? ""), ...extractTypeNames(localStateSchema ?? "")];
|
|
632
|
+
const operationTypeNames = specification?.modules.flatMap((module) => module.operations.flatMap((op) => extractTypeNames(op.schema ?? ""))) ?? [];
|
|
633
|
+
const global = parseSdl(globalStateSchema ?? "");
|
|
634
|
+
const operations = specification?.modules.flatMap((module) => module.operations.filter((op) => op.name && hasValidSchema(op.schema)).map((op) => ({
|
|
635
|
+
camelName: camelCase(op.name),
|
|
636
|
+
inputTypeName: `${documentName}_${pascalCase(op.name)}Input`
|
|
637
|
+
}))) ?? [];
|
|
638
|
+
return {
|
|
639
|
+
global,
|
|
640
|
+
stateTypeNames,
|
|
641
|
+
operationTypeNames,
|
|
642
|
+
modules: specification?.modules.map((module) => ({
|
|
643
|
+
name: module.name,
|
|
644
|
+
operations: module.operations.filter((op) => hasValidSchema(op.schema)).map((op) => parseSdl(op.schema ?? ""))
|
|
645
|
+
})) ?? [],
|
|
646
|
+
operations,
|
|
647
|
+
hasLocalRoot: (localStateSchema ?? "").includes(`type ${documentName}LocalState`),
|
|
648
|
+
scopes: storedScopes(specification)
|
|
649
|
+
};
|
|
650
|
+
}
|
|
651
|
+
function storedScopes(specification) {
|
|
652
|
+
if (!specification) return [];
|
|
653
|
+
return Object.entries(specification.state).map(([name, scopeState]) => {
|
|
654
|
+
const schema = scopeState.schema ?? "";
|
|
655
|
+
if (!hasValidSchema(schema)) return {
|
|
656
|
+
name,
|
|
657
|
+
document: null
|
|
658
|
+
};
|
|
659
|
+
try {
|
|
660
|
+
return {
|
|
661
|
+
name,
|
|
662
|
+
document: parse(schema)
|
|
663
|
+
};
|
|
664
|
+
} catch {
|
|
665
|
+
return {
|
|
666
|
+
name,
|
|
667
|
+
document: null
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
});
|
|
671
|
+
}
|
|
672
|
+
//#endregion
|
|
673
|
+
//#region src/graphql/document-model-schema/structured-projection.ts
|
|
674
|
+
const documentOf = (segment) => segment === null ? EMPTY_DOCUMENT : segment.document;
|
|
675
|
+
const inputOf = (operation) => operation.input;
|
|
676
|
+
function once(compute) {
|
|
677
|
+
let cached;
|
|
678
|
+
return () => (cached ??= { value: compute() }).value;
|
|
679
|
+
}
|
|
680
|
+
/**
|
|
681
|
+
* Adapts a definition's GraphQL projection. Each value is derived on first use
|
|
682
|
+
* and kept, since the projection is an immutable snapshot.
|
|
683
|
+
*/
|
|
684
|
+
function structuredSchemaSource(projection, global) {
|
|
685
|
+
const name = getDocumentModelSchemaName(global);
|
|
686
|
+
const documentName = () => name;
|
|
687
|
+
const globalDocument = documentOf(projection.global);
|
|
688
|
+
const localDocument = documentOf(projection.local);
|
|
689
|
+
const mutationOperations = once(() => projection.modules.flatMap((module) => module.operations.flatMap((operation) => {
|
|
690
|
+
const input = inputOf(operation)?.definitions[0];
|
|
691
|
+
if (input?.kind !== Kind.INPUT_OBJECT_TYPE_DEFINITION) return [];
|
|
692
|
+
return [{
|
|
693
|
+
camelName: camelCase(operation.name),
|
|
694
|
+
inputTypeName: `${documentName()}_${input.name.value}`,
|
|
695
|
+
storedName: operation.name,
|
|
696
|
+
creatorKey: operation.creatorKey
|
|
697
|
+
}];
|
|
698
|
+
})));
|
|
699
|
+
return {
|
|
700
|
+
packageScalars: projection.packageScalars,
|
|
701
|
+
mutationOperations,
|
|
702
|
+
hasOperationSchemas: once(() => projection.modules.some((module) => module.operations.some((op) => op.input !== null))),
|
|
703
|
+
modelDefinitions: once(() => generatedModelDefinitions(documentName(), globalDocument, localDocument)),
|
|
704
|
+
stateDefinitions: once(() => [...globalDocument.definitions, ...localDocument.definitions]),
|
|
705
|
+
modelProjection: once(() => {
|
|
706
|
+
const name = documentName();
|
|
707
|
+
const operationInputs = projection.modules.map((module) => module.operations.flatMap((operation) => inputOf(operation) ?? []));
|
|
708
|
+
const localRoot = `${name}LocalState`;
|
|
709
|
+
return buildModelProjection(name, {
|
|
710
|
+
global: globalDocument,
|
|
711
|
+
stateTypeNames: [...definedTypeNames(globalDocument, ALL_PREFIX_KINDS), ...definedTypeNames(localDocument, ALL_PREFIX_KINDS)],
|
|
712
|
+
operationTypeNames: operationInputs.flat().flatMap((input) => definedTypeNames(input, ALL_PREFIX_KINDS)),
|
|
713
|
+
modules: projection.modules.map((module, index) => ({
|
|
714
|
+
name: module.name,
|
|
715
|
+
operations: operationInputs[index] ?? []
|
|
716
|
+
})),
|
|
717
|
+
operations: mutationOperations(),
|
|
718
|
+
hasLocalRoot: localDocument.definitions.some((def) => def.kind === Kind.OBJECT_TYPE_DEFINITION && def.name.value === localRoot),
|
|
719
|
+
scopes: [{
|
|
720
|
+
name: "global",
|
|
721
|
+
document: globalDocument
|
|
722
|
+
}, {
|
|
723
|
+
name: "local",
|
|
724
|
+
document: projection.local === null ? null : localDocument
|
|
725
|
+
}]
|
|
726
|
+
});
|
|
727
|
+
})
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
//#endregion
|
|
731
|
+
//#region src/graphql/document-model-schema/source.ts
|
|
732
|
+
const logger$1 = childLogger(["reactor-api", "document-model-schema"]);
|
|
733
|
+
const logged = /* @__PURE__ */ new Set();
|
|
734
|
+
function warnOnce(documentType, reason, detail) {
|
|
735
|
+
const key = `${documentType}\n${reason}`;
|
|
736
|
+
if (logged.has(key)) return;
|
|
737
|
+
logged.add(key);
|
|
738
|
+
logger$1.warn("Serving document model @documentType from its stored model: its definition is @reason: @detail", documentType, reason, detail);
|
|
739
|
+
}
|
|
740
|
+
const projected = /* @__PURE__ */ new WeakMap();
|
|
741
|
+
function project(inspection) {
|
|
742
|
+
let entry = projected.get(inspection.specification);
|
|
743
|
+
if (entry === void 0) {
|
|
744
|
+
try {
|
|
745
|
+
entry = {
|
|
746
|
+
projection: projectDocumentModelGraphQL(inspection.definition, inspection.specification),
|
|
747
|
+
sources: /* @__PURE__ */ new Map()
|
|
748
|
+
};
|
|
749
|
+
} catch (error) {
|
|
750
|
+
entry = { error };
|
|
751
|
+
}
|
|
752
|
+
projected.set(inspection.specification, entry);
|
|
753
|
+
}
|
|
754
|
+
return entry;
|
|
755
|
+
}
|
|
756
|
+
const snapshotDigests = /* @__PURE__ */ new WeakMap();
|
|
757
|
+
/**
|
|
758
|
+
* The cache-key part a model's definition adds: a digest of the inspected
|
|
759
|
+
* snapshot when the schema is built from it, else `null`, so a model served
|
|
760
|
+
* from its stored SDL keeps main's key. Inspection is memoized per definition
|
|
761
|
+
* object, so this runs once per loaded definition.
|
|
762
|
+
*/
|
|
763
|
+
function structuredDefinitionDigest(model) {
|
|
764
|
+
let inspection;
|
|
765
|
+
try {
|
|
766
|
+
inspection = inspectDocumentModelDefinition(model);
|
|
767
|
+
} catch {
|
|
768
|
+
return null;
|
|
769
|
+
}
|
|
770
|
+
if (inspection.kind !== "structured") return null;
|
|
771
|
+
let digest = snapshotDigests.get(inspection.definition);
|
|
772
|
+
if (digest === void 0) {
|
|
773
|
+
digest = createHash("sha256").update(JSON.stringify(inspection.definition)).digest("base64");
|
|
774
|
+
snapshotDigests.set(inspection.definition, digest);
|
|
775
|
+
}
|
|
776
|
+
return digest;
|
|
777
|
+
}
|
|
778
|
+
/**
|
|
779
|
+
* The one place a host selects how a document model's schema is built: from
|
|
780
|
+
* its structured definition when it carries a valid, matching one, else from
|
|
781
|
+
* its stored SDL. Logs nothing; `fallback` says why a definition is not served.
|
|
782
|
+
*/
|
|
783
|
+
function selectDocumentModelSchemaSource(model) {
|
|
784
|
+
const { global } = model.documentModel;
|
|
785
|
+
let inspection;
|
|
786
|
+
try {
|
|
787
|
+
inspection = inspectDocumentModelDefinition(model);
|
|
788
|
+
} catch (error) {
|
|
789
|
+
return {
|
|
790
|
+
source: storedSchemaSource(global),
|
|
791
|
+
fallback: {
|
|
792
|
+
reason: "unreadable",
|
|
793
|
+
error
|
|
794
|
+
}
|
|
795
|
+
};
|
|
796
|
+
}
|
|
797
|
+
if (inspection.kind === "stored") return {
|
|
798
|
+
source: storedSchemaSource(global),
|
|
799
|
+
...(inspection.reason === "invalid" || inspection.reason === "mismatch") && { fallback: {
|
|
800
|
+
reason: inspection.reason,
|
|
801
|
+
diagnostics: inspection.diagnostics
|
|
802
|
+
} }
|
|
803
|
+
};
|
|
804
|
+
const entry = project(inspection);
|
|
805
|
+
if ("error" in entry) return {
|
|
806
|
+
source: storedSchemaSource(global),
|
|
807
|
+
fallback: {
|
|
808
|
+
reason: "unreadable",
|
|
809
|
+
error: entry.error
|
|
810
|
+
}
|
|
811
|
+
};
|
|
812
|
+
let source = entry.sources.get(global.name);
|
|
813
|
+
if (source === void 0) {
|
|
814
|
+
source = structuredSchemaSource(entry.projection, global);
|
|
815
|
+
entry.sources.set(global.name, source);
|
|
816
|
+
}
|
|
817
|
+
return { source };
|
|
818
|
+
}
|
|
819
|
+
/** {@link selectDocumentModelSchemaSource}, logging a fallback once per document type and reason. */
|
|
820
|
+
function documentModelSchemaSource(model) {
|
|
821
|
+
const { source, fallback } = selectDocumentModelSchemaSource(model);
|
|
822
|
+
if (fallback !== void 0) warnOnce(model.documentModel.global.id, fallback.reason, "diagnostics" in fallback ? fallback.diagnostics : fallback.error);
|
|
823
|
+
return source;
|
|
824
|
+
}
|
|
825
|
+
//#endregion
|
|
826
|
+
//#region src/utils/create-schema.ts
|
|
827
|
+
const logger = childLogger(["reactor-api", "create-schema"]);
|
|
828
|
+
/**
|
|
829
|
+
* A subgraph defines a type whose name the generated document-model schema
|
|
830
|
+
* owns, so one of the two definitions would be lost.
|
|
831
|
+
*/
|
|
832
|
+
var SubgraphTypeCollisionError = class extends Error {
|
|
833
|
+
typeNames;
|
|
834
|
+
constructor(typeNames) {
|
|
835
|
+
super(`Subgraph defines types reserved by the document-model schema: ${typeNames.join(", ")}`);
|
|
836
|
+
this.name = "SubgraphTypeCollisionError";
|
|
837
|
+
this.typeNames = typeNames;
|
|
838
|
+
}
|
|
839
|
+
};
|
|
840
|
+
/**
|
|
841
|
+
* Type-system definition kinds that GraphQL requires to be uniquely named.
|
|
842
|
+
* A subgraph SDL with two definitions sharing a name fails federation
|
|
843
|
+
* composition ("There can be only one type named X"), which is fatal to the
|
|
844
|
+
* whole gateway. We dedupe these by name; field/operation/extension nodes are
|
|
845
|
+
* left untouched.
|
|
846
|
+
*/
|
|
847
|
+
const TYPE_DEFINITION_KINDS = /* @__PURE__ */ new Set([
|
|
848
|
+
Kind.OBJECT_TYPE_DEFINITION,
|
|
849
|
+
Kind.ENUM_TYPE_DEFINITION,
|
|
850
|
+
Kind.INPUT_OBJECT_TYPE_DEFINITION,
|
|
851
|
+
Kind.INTERFACE_TYPE_DEFINITION,
|
|
852
|
+
Kind.UNION_TYPE_DEFINITION,
|
|
853
|
+
Kind.SCALAR_TYPE_DEFINITION
|
|
854
|
+
]);
|
|
855
|
+
/**
|
|
856
|
+
* Drop duplicate type-system definitions by name, keeping the first occurrence.
|
|
857
|
+
* Deduping is by name across ALL kinds (a `type` and an `enum` sharing a name
|
|
858
|
+
* collide in GraphQL too), so the first definition of a given name wins
|
|
859
|
+
* regardless of kind. State types are emitted before operation types, so
|
|
860
|
+
* keep-first preserves the authoritative state definition. This heals a document
|
|
861
|
+
* model that defines the same name twice (global+local, state+operation, or
|
|
862
|
+
* twice in one scope) so the assembled subgraph SDL composes instead of crashing
|
|
863
|
+
* the gateway (Sentry #917).
|
|
864
|
+
*/
|
|
865
|
+
const dedupeTypeDefinitions = (definitions, seen = /* @__PURE__ */ new Set()) => definitions.filter((def) => {
|
|
866
|
+
const name = typeDefinitionName(def);
|
|
867
|
+
if (name === void 0) return true;
|
|
868
|
+
if (seen.has(name)) {
|
|
869
|
+
logger.debug(`Dropping duplicate type definition: ${name}`);
|
|
870
|
+
return false;
|
|
871
|
+
}
|
|
872
|
+
seen.add(name);
|
|
873
|
+
return true;
|
|
874
|
+
});
|
|
875
|
+
function typeDefinitionName(def) {
|
|
876
|
+
if (!TYPE_DEFINITION_KINDS.has(def.kind)) return void 0;
|
|
877
|
+
return def.name?.value;
|
|
440
878
|
}
|
|
441
879
|
const buildSubgraphSchemaModule = (documentModels, resolvers, typeDefs, options = {}) => {
|
|
442
880
|
const generated = options.generated ?? getGeneratedDocumentModelTypes(documentModels, void 0, options.scalars);
|
|
@@ -479,30 +917,10 @@ function typeDefinitionNames(doc) {
|
|
|
479
917
|
}
|
|
480
918
|
/** The definitions `documentModel` adds to the generated schema. */
|
|
481
919
|
function documentModelDefinitions(documentModel) {
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
const definitions = [...stateTypeDefinitions(globalSchema), ...stateTypeDefinitions(localSchema, LOCAL_STATE_STUBS)];
|
|
487
|
-
const stateDoc = {
|
|
488
|
-
kind: Kind.DOCUMENT,
|
|
489
|
-
definitions
|
|
490
|
-
};
|
|
491
|
-
const prefixed = prefixTypeNames(stateDoc, dmSchemaName, new Set(definedTypeNames(stateDoc, STATE_PREFIX_KINDS)));
|
|
492
|
-
const documentType = parseSdl(`
|
|
493
|
-
type ${dmSchemaName} implements IDocument {
|
|
494
|
-
id: String!
|
|
495
|
-
name: String!
|
|
496
|
-
documentType: String!
|
|
497
|
-
operations(skip: Int, first: Int): [Operation!]!
|
|
498
|
-
revision: Int!
|
|
499
|
-
createdAtUtcIso: DateTime!
|
|
500
|
-
lastModifiedAtUtcIso: DateTime!
|
|
501
|
-
${dmSchemaName !== "DocumentModel" ? `initialState: ${dmSchemaName}_${dmSchemaName}State!` : ""}
|
|
502
|
-
${dmSchemaName !== "DocumentModel" ? `state: ${dmSchemaName}_${dmSchemaName}State!` : ""}
|
|
503
|
-
stateJSON: JSONObject
|
|
504
|
-
}`);
|
|
505
|
-
return [...prefixed.definitions, ...documentType.definitions];
|
|
920
|
+
return documentModelSchemaSource(documentModel).modelDefinitions();
|
|
921
|
+
}
|
|
922
|
+
function sourceOf(documentModel) {
|
|
923
|
+
return "documentModel" in documentModel ? documentModel : { documentModel: { global: documentModel } };
|
|
506
924
|
}
|
|
507
925
|
function addScalarFlags(definitions, into) {
|
|
508
926
|
for (const def of definitions) {
|
|
@@ -533,7 +951,7 @@ function reservedTypeNames(coreTypeDefs) {
|
|
|
533
951
|
* The reserved names `documentModel`'s generated types take. A scalar may
|
|
534
952
|
* repeat a reserved scalar: the duplicate is dropped on assembly.
|
|
535
953
|
*/
|
|
536
|
-
function reservedTypeNamesTaken(documentModel, reserved, definitions = documentModelDefinitions(documentModel
|
|
954
|
+
function reservedTypeNamesTaken(documentModel, reserved, definitions = documentModelDefinitions(documentModel)) {
|
|
537
955
|
const generated = addScalarFlags(definitions, /* @__PURE__ */ new Map());
|
|
538
956
|
return Array.from(generated).filter(([name, scalar]) => reserved.has(name) && !(scalar && reserved.get(name))).map(([name]) => name);
|
|
539
957
|
}
|
|
@@ -636,25 +1054,25 @@ const GENERATED_TAIL = gql`
|
|
|
636
1054
|
*/
|
|
637
1055
|
function getGeneratedDocumentModelTypes(documentModels, schemas, scalars = EMPTY_SCALAR_REGISTRY) {
|
|
638
1056
|
return generatedTypesFrom(documentModels.map((model) => ({
|
|
639
|
-
|
|
1057
|
+
model,
|
|
640
1058
|
generated: schemas?.get(model)?.generated
|
|
641
1059
|
})), scalars);
|
|
642
1060
|
}
|
|
643
1061
|
/** {@link getGeneratedDocumentModelTypes} from the models' global states. */
|
|
644
1062
|
function generatedTypesOf(documentModels) {
|
|
645
|
-
return generatedTypesFrom(documentModels.map((global) => ({ global })), EMPTY_SCALAR_REGISTRY);
|
|
1063
|
+
return generatedTypesFrom(documentModels.map((global) => ({ model: sourceOf(global) })), EMPTY_SCALAR_REGISTRY);
|
|
646
1064
|
}
|
|
647
1065
|
function generatedTypesFrom(documentModels, scalars) {
|
|
648
1066
|
const modelDefinitions = [];
|
|
649
1067
|
const addedDocumentModels = /* @__PURE__ */ new Set();
|
|
650
|
-
documentModels.forEach(({
|
|
651
|
-
const dmSchemaName = getDocumentModelSchemaName(global);
|
|
1068
|
+
documentModels.forEach(({ model, generated }) => {
|
|
1069
|
+
const dmSchemaName = getDocumentModelSchemaName(model.documentModel.global);
|
|
652
1070
|
if (addedDocumentModels.has(dmSchemaName)) {
|
|
653
1071
|
logger.debug(`Skipping document model with duplicate name: ${dmSchemaName}`);
|
|
654
1072
|
return;
|
|
655
1073
|
}
|
|
656
1074
|
addedDocumentModels.add(dmSchemaName);
|
|
657
|
-
modelDefinitions.push(...generated ?? documentModelDefinitions(
|
|
1075
|
+
modelDefinitions.push(...generated ?? documentModelDefinitions(model));
|
|
658
1076
|
});
|
|
659
1077
|
const definitions = dedupeTypeDefinitions([
|
|
660
1078
|
...generatedHead(scalars),
|
|
@@ -669,9 +1087,7 @@ function generatedTypesFrom(documentModels, scalars) {
|
|
|
669
1087
|
}
|
|
670
1088
|
/** Whether any operation of the latest specification has a schema. */
|
|
671
1089
|
function hasOperationSchemas(documentModel) {
|
|
672
|
-
|
|
673
|
-
if (!specification) return false;
|
|
674
|
-
return specification.modules.some((module) => module.operations.some((op) => hasValidSchema(op.schema)));
|
|
1090
|
+
return documentModelSchemaSource(sourceOf(documentModel)).hasOperationSchemas();
|
|
675
1091
|
}
|
|
676
1092
|
/** The types of a document model's own subgraph. */
|
|
677
1093
|
function documentModelSubgraphTypes(documentModel) {
|
|
@@ -688,13 +1104,13 @@ function checkBuilds(documentModel, generated, subgraph) {
|
|
|
688
1104
|
}
|
|
689
1105
|
/** Throws when the generated types every subgraph carries do not build. */
|
|
690
1106
|
function buildDocumentModelSchema(documentModel, options = {}) {
|
|
691
|
-
const generated = documentModelDefinitions(documentModel
|
|
692
|
-
if (options.subgraph === false || !hasOperationSchemas(documentModel
|
|
1107
|
+
const generated = documentModelDefinitions(documentModel);
|
|
1108
|
+
if (options.subgraph === false || !hasOperationSchemas(documentModel)) {
|
|
693
1109
|
checkBuilds(documentModel, generated);
|
|
694
1110
|
return { generated };
|
|
695
1111
|
}
|
|
696
1112
|
try {
|
|
697
|
-
const subgraph = documentModelSubgraphTypes(documentModel
|
|
1113
|
+
const subgraph = documentModelSubgraphTypes(documentModel);
|
|
698
1114
|
checkBuilds(documentModel, generated, subgraph);
|
|
699
1115
|
return {
|
|
700
1116
|
generated,
|
|
@@ -711,7 +1127,10 @@ function buildDocumentModelSchema(documentModel, options = {}) {
|
|
|
711
1127
|
/** Hash of everything {@link buildDocumentModelSchema} reads. */
|
|
712
1128
|
function schemaSourceKey(documentModel) {
|
|
713
1129
|
const { name, specifications } = documentModel.documentModel.global;
|
|
714
|
-
|
|
1130
|
+
const hash = createHash("sha256").update(JSON.stringify([name, specifications.at(-1)]));
|
|
1131
|
+
const definition = structuredDefinitionDigest(documentModel);
|
|
1132
|
+
if (definition !== null) hash.update(definition);
|
|
1133
|
+
return hash.digest("base64");
|
|
715
1134
|
}
|
|
716
1135
|
/** Schemas and failures by source hash, for the last resolve's models only. */
|
|
717
1136
|
var DocumentModelSchemaCache = class {
|
|
@@ -779,129 +1198,6 @@ function assembleSubgraphTypeDefs(generated, typeDefs, ownTypeNames) {
|
|
|
779
1198
|
};
|
|
780
1199
|
}
|
|
781
1200
|
/**
|
|
782
|
-
* Extract the names of types defined in a GraphQL schema.
|
|
783
|
-
* Unparseable schemas yield no names.
|
|
784
|
-
*/
|
|
785
|
-
function extractTypeNames(schema) {
|
|
786
|
-
try {
|
|
787
|
-
return definedTypeNames(parseSdl(schema), ALL_PREFIX_KINDS);
|
|
788
|
-
} catch (error) {
|
|
789
|
-
logger.debug(`Skipping unparseable schema: ${String(error)}`);
|
|
790
|
-
return [];
|
|
791
|
-
}
|
|
792
|
-
}
|
|
793
|
-
/**
|
|
794
|
-
* Print the input type definitions of a GraphQL schema.
|
|
795
|
-
* @param excludeTypeNames - Input type names to leave out
|
|
796
|
-
*/
|
|
797
|
-
function extractInputTypeDefinitions(schema, excludeTypeNames = /* @__PURE__ */ new Set()) {
|
|
798
|
-
const definitions = parseSdl(schema).definitions.filter((def) => def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION && !excludeTypeNames.has(def.name.value));
|
|
799
|
-
if (definitions.length === 0) return "";
|
|
800
|
-
return print({
|
|
801
|
-
kind: Kind.DOCUMENT,
|
|
802
|
-
definitions
|
|
803
|
-
});
|
|
804
|
-
}
|
|
805
|
-
/**
|
|
806
|
-
* Extract the root state type name from a scope's GraphQL schema.
|
|
807
|
-
* Uses the naming convention: {DocumentName}State for global,
|
|
808
|
-
* {DocumentName}{PascalScope}State for other scopes (e.g., DocumentDriveLocalState).
|
|
809
|
-
* Falls back to the last ObjectTypeDefinition (root types are conventionally last).
|
|
810
|
-
*/
|
|
811
|
-
function extractRootTypeName(schema, documentName, scopeName) {
|
|
812
|
-
try {
|
|
813
|
-
const ast = parse(schema);
|
|
814
|
-
const candidates = [`${documentName}${scopeName === "global" ? "" : pascalCase(scopeName)}State`, `${documentName}${pascalCase(scopeName)}State`];
|
|
815
|
-
let lastObjectType = null;
|
|
816
|
-
for (const def of ast.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) {
|
|
817
|
-
if (candidates.includes(def.name.value)) return def.name.value;
|
|
818
|
-
lastObjectType = def.name.value;
|
|
819
|
-
}
|
|
820
|
-
return lastObjectType;
|
|
821
|
-
} catch {}
|
|
822
|
-
return null;
|
|
823
|
-
}
|
|
824
|
-
/**
|
|
825
|
-
* Convert a GraphQL output type AST node to an optional input type string.
|
|
826
|
-
* Strips non-null markers and converts object type references to Input suffix.
|
|
827
|
-
*/
|
|
828
|
-
function convertTypeNodeToInput(typeNode, objectNames, unionNames, interfaceNames) {
|
|
829
|
-
if (typeNode.kind === Kind.NON_NULL_TYPE && typeNode.type) return convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames);
|
|
830
|
-
if (typeNode.kind === Kind.LIST_TYPE && typeNode.type) return `[${convertTypeNodeToInput(typeNode.type, objectNames, unionNames, interfaceNames)}]`;
|
|
831
|
-
if (typeNode.kind === Kind.NAMED_TYPE && typeNode.name) {
|
|
832
|
-
const name = typeNode.name.value;
|
|
833
|
-
if (objectNames.has(name)) return `${name}Input`;
|
|
834
|
-
if (unionNames.has(name) || interfaceNames.has(name)) return "JSONObject";
|
|
835
|
-
return name;
|
|
836
|
-
}
|
|
837
|
-
return "JSONObject";
|
|
838
|
-
}
|
|
839
|
-
/**
|
|
840
|
-
* Generate GraphQL input type definitions from a state schema string.
|
|
841
|
-
* Converts output type definitions to input types with all fields optional.
|
|
842
|
-
* - Object type references get Input suffix
|
|
843
|
-
* - Union/interface references become JSONObject
|
|
844
|
-
* - Enums and scalars remain unchanged
|
|
845
|
-
*/
|
|
846
|
-
function generateStateInputTypes(stateSchema, excludeTypeNames) {
|
|
847
|
-
if (!stateSchema || !stateSchema.trim()) return "";
|
|
848
|
-
let ast;
|
|
849
|
-
try {
|
|
850
|
-
ast = parse(stateSchema);
|
|
851
|
-
} catch {
|
|
852
|
-
return "";
|
|
853
|
-
}
|
|
854
|
-
const enumNames = /* @__PURE__ */ new Set();
|
|
855
|
-
const unionNames = /* @__PURE__ */ new Set();
|
|
856
|
-
const interfaceNames = /* @__PURE__ */ new Set();
|
|
857
|
-
const objectNames = /* @__PURE__ */ new Set();
|
|
858
|
-
const existingInputNames = /* @__PURE__ */ new Set();
|
|
859
|
-
for (const def of ast.definitions) switch (def.kind) {
|
|
860
|
-
case Kind.ENUM_TYPE_DEFINITION:
|
|
861
|
-
enumNames.add(def.name.value);
|
|
862
|
-
break;
|
|
863
|
-
case Kind.UNION_TYPE_DEFINITION:
|
|
864
|
-
unionNames.add(def.name.value);
|
|
865
|
-
break;
|
|
866
|
-
case Kind.INTERFACE_TYPE_DEFINITION:
|
|
867
|
-
interfaceNames.add(def.name.value);
|
|
868
|
-
break;
|
|
869
|
-
case Kind.OBJECT_TYPE_DEFINITION:
|
|
870
|
-
objectNames.add(def.name.value);
|
|
871
|
-
break;
|
|
872
|
-
case Kind.INPUT_OBJECT_TYPE_DEFINITION: existingInputNames.add(def.name.value);
|
|
873
|
-
}
|
|
874
|
-
const inputTypes = [];
|
|
875
|
-
for (const def of ast.definitions) {
|
|
876
|
-
if (def.kind !== Kind.OBJECT_TYPE_DEFINITION) continue;
|
|
877
|
-
const inputName = `${def.name.value}Input`;
|
|
878
|
-
if (existingInputNames.has(inputName)) continue;
|
|
879
|
-
if (excludeTypeNames?.has(inputName)) continue;
|
|
880
|
-
const fields = def.fields ?? [];
|
|
881
|
-
if (fields.length === 0) continue;
|
|
882
|
-
const inputFields = fields.map((field) => {
|
|
883
|
-
return ` ${field.name.value}: ${convertTypeNodeToInput(field.type, objectNames, unionNames, interfaceNames)}`;
|
|
884
|
-
});
|
|
885
|
-
inputTypes.push(`input ${def.name.value}Input {\n${inputFields.join("\n")}\n}`);
|
|
886
|
-
}
|
|
887
|
-
return inputTypes.join("\n\n");
|
|
888
|
-
}
|
|
889
|
-
/**
|
|
890
|
-
* Apply type prefixes to GraphQL schema to namespace types and avoid collisions.
|
|
891
|
-
* Inlined from @powerhousedao/common/utils to avoid ES module import issues.
|
|
892
|
-
* @param {string} schema - GraphQL schema string
|
|
893
|
-
* @param {string} prefix - Prefix to apply to type names
|
|
894
|
-
* @param {string[]} externalTypeNames - Type names from other schemas to also prefix
|
|
895
|
-
* @returns {string} Schema with prefixed types
|
|
896
|
-
*/
|
|
897
|
-
function applyGraphQLTypePrefixes(schema, prefix, externalTypeNames = []) {
|
|
898
|
-
if (!schema || !schema.trim()) return schema;
|
|
899
|
-
const doc = parseSdl(schema);
|
|
900
|
-
const names = /* @__PURE__ */ new Set([...definedTypeNames(doc, ALL_PREFIX_KINDS), ...externalTypeNames]);
|
|
901
|
-
if (names.size === 0) return schema;
|
|
902
|
-
return print(prefixTypeNames(doc, prefix, names));
|
|
903
|
-
}
|
|
904
|
-
/**
|
|
905
1201
|
* Generate a GraphQL schema for a document model.
|
|
906
1202
|
*
|
|
907
1203
|
* @param documentModel - The document model global state
|
|
@@ -909,87 +1205,7 @@ function applyGraphQLTypePrefixes(schema, prefix, externalTypeNames = []) {
|
|
|
909
1205
|
* @returns GraphQL DocumentNode
|
|
910
1206
|
*/
|
|
911
1207
|
function generateDocumentModelSchema(documentModel, options = {}) {
|
|
912
|
-
return generateModelSchema(
|
|
913
|
-
}
|
|
914
|
-
/** Reads the template inputs out of a model's stored SDL. */
|
|
915
|
-
function storedModelProjection(documentModel, documentName) {
|
|
916
|
-
const specification = documentModel.specifications.at(-1);
|
|
917
|
-
const globalStateSchema = specification?.state.global.schema;
|
|
918
|
-
const localStateSchema = specification?.state.local.schema;
|
|
919
|
-
const stateTypeNames = [...extractTypeNames(globalStateSchema ?? ""), ...extractTypeNames(localStateSchema ?? "")];
|
|
920
|
-
const allOperationTypeNames = specification?.modules.flatMap((module) => module.operations.flatMap((op) => extractTypeNames(op.schema ?? ""))) ?? [];
|
|
921
|
-
const allTypeNames = [.../* @__PURE__ */ new Set([...stateTypeNames, ...allOperationTypeNames])];
|
|
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
|
-
};
|
|
949
|
-
}
|
|
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;
|
|
974
|
-
}
|
|
975
|
-
const scopeInputTypes = generateStateInputTypes(schema, new Set(allTypeNames));
|
|
976
|
-
if (!scopeInputTypes) {
|
|
977
|
-
scopes.push({
|
|
978
|
-
name: scopeName,
|
|
979
|
-
type: "JSONObject"
|
|
980
|
-
});
|
|
981
|
-
continue;
|
|
982
|
-
}
|
|
983
|
-
scopes.push({
|
|
984
|
-
name: scopeName,
|
|
985
|
-
type: `${documentName}_${rootTypeName}Input`
|
|
986
|
-
});
|
|
987
|
-
generatedInputTypeParts.push(applyGraphQLTypePrefixes(scopeInputTypes, documentName, allTypeNames));
|
|
988
|
-
}
|
|
989
|
-
return {
|
|
990
|
-
inputTypes: generatedInputTypeParts.join("\n\n"),
|
|
991
|
-
scopes
|
|
992
|
-
};
|
|
1208
|
+
return generateModelSchema(documentModelSchemaSource(sourceOf(documentModel)).modelProjection(), options);
|
|
993
1209
|
}
|
|
994
1210
|
//#endregion
|
|
995
1211
|
//#region src/graphql/subgraph-type-ownership.ts
|
|
@@ -1855,7 +2071,7 @@ const baseDocumentModels = [
|
|
|
1855
2071
|
["reactor-group", ReactorGroupV1]
|
|
1856
2072
|
];
|
|
1857
2073
|
//#endregion
|
|
1858
|
-
export { getDocumentModelTypeDefs as A, createMergedSchema as C, generateDocumentModelSchema as D, findSubgraphTypeCollisions as E, typeDefinitionNames as F,
|
|
2074
|
+
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 };
|
|
1859
2075
|
|
|
1860
|
-
//# sourceMappingURL=base-document-models-
|
|
1861
|
-
//# debugId=
|
|
2076
|
+
//# sourceMappingURL=base-document-models-CCYv5XxL.mjs.map
|
|
2077
|
+
//# debugId=392c1b84-7a7a-5715-91f3-f9595a6367d3
|