document-model 6.2.3-dev.91 → 6.2.3-dev.93
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/index.js.map +1 -1
- package/dist/tooling.d.mts +201 -1
- package/dist/tooling.d.mts.map +1 -1
- package/dist/tooling.mjs +2821 -70
- package/dist/tooling.mjs.map +1 -1
- package/package.json +10 -2
package/dist/tooling.mjs
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { DocumentModelGlobalStateSchema, defaultBaseState } from "@powerhousedao/shared/document-model";
|
|
3
|
+
import { existsSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
|
|
2
4
|
import { dirname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
|
|
3
5
|
import { z } from "zod";
|
|
4
|
-
import { fileURLToPath } from "node:url";
|
|
6
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
5
7
|
import { DEFAULT_AUTHORING_MODE, parseDefinitionSourcesConfig } from "@powerhousedao/shared/clis/definition-sources";
|
|
8
|
+
import { camelCase, constantCase, pascalCase } from "change-case";
|
|
6
9
|
//#region src/definition/kernel/hashes.ts
|
|
7
10
|
function rotateRight(value, shift) {
|
|
8
11
|
return (value >>> shift | value << 32 - shift) >>> 0;
|
|
@@ -374,6 +377,13 @@ var DefinitionError = class extends Error {
|
|
|
374
377
|
//#endregion
|
|
375
378
|
//#region src/scalars/types.ts
|
|
376
379
|
const SCALAR_DEFINITION = Symbol.for("powerhouse.scalar-definition");
|
|
380
|
+
/** The definition format version `value` is branded with, if it has a brand. */
|
|
381
|
+
function scalarDefinitionVersion(value) {
|
|
382
|
+
return typeof value === "object" && value !== null && SCALAR_DEFINITION in value ? value[SCALAR_DEFINITION] : void 0;
|
|
383
|
+
}
|
|
384
|
+
function isScalarDefinition(value) {
|
|
385
|
+
return scalarDefinitionVersion(value) === 1;
|
|
386
|
+
}
|
|
377
387
|
//#endregion
|
|
378
388
|
//#region src/scalars/define-catalog-scalar.ts
|
|
379
389
|
function defineCatalogScalar(input) {
|
|
@@ -759,6 +769,9 @@ function rejectionReceived(rejection) {
|
|
|
759
769
|
return "received" in rejection ? rejection.received : rejection.reason;
|
|
760
770
|
}
|
|
761
771
|
const CANONICAL_INDEX = /^(?:0|[1-9][0-9]*)$/;
|
|
772
|
+
function snapshotDataRecord(value, allowedKeys, path) {
|
|
773
|
+
return snapshotPlainObject(value, allowedKeys, path, snapshotDataValue, /* @__PURE__ */ new Set());
|
|
774
|
+
}
|
|
762
775
|
function snapshotArray(value, path) {
|
|
763
776
|
return snapshotArrayValue(value, path, (member) => ({
|
|
764
777
|
ok: true,
|
|
@@ -979,6 +992,47 @@ function dataPropertyValue(descriptor, key, path) {
|
|
|
979
992
|
value: descriptor.value
|
|
980
993
|
};
|
|
981
994
|
}
|
|
995
|
+
function snapshotDataValue(value, path, ancestors) {
|
|
996
|
+
switch (typeof value) {
|
|
997
|
+
case "string":
|
|
998
|
+
case "number":
|
|
999
|
+
case "boolean":
|
|
1000
|
+
case "bigint":
|
|
1001
|
+
case "undefined": return {
|
|
1002
|
+
ok: true,
|
|
1003
|
+
value
|
|
1004
|
+
};
|
|
1005
|
+
case "function": return {
|
|
1006
|
+
ok: false,
|
|
1007
|
+
reason: "not-data",
|
|
1008
|
+
path,
|
|
1009
|
+
received: "function"
|
|
1010
|
+
};
|
|
1011
|
+
case "symbol": return {
|
|
1012
|
+
ok: false,
|
|
1013
|
+
reason: "not-data",
|
|
1014
|
+
path,
|
|
1015
|
+
received: "symbol"
|
|
1016
|
+
};
|
|
1017
|
+
case "object": {
|
|
1018
|
+
if (value === null) return {
|
|
1019
|
+
ok: true,
|
|
1020
|
+
value
|
|
1021
|
+
};
|
|
1022
|
+
let isArray;
|
|
1023
|
+
try {
|
|
1024
|
+
isArray = Array.isArray(value);
|
|
1025
|
+
} catch {
|
|
1026
|
+
return {
|
|
1027
|
+
ok: false,
|
|
1028
|
+
reason: "inspection-failed",
|
|
1029
|
+
path
|
|
1030
|
+
};
|
|
1031
|
+
}
|
|
1032
|
+
return isArray ? snapshotArrayValue(value, path, snapshotDataValue, ancestors) : snapshotPlainObject(value, void 0, path, snapshotDataValue, ancestors);
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
982
1036
|
//#endregion
|
|
983
1037
|
//#region src/definition/kernel/diagnostic-codes.ts
|
|
984
1038
|
const kernelDiagnostics = defineDiagnosticCatalog({
|
|
@@ -995,6 +1049,183 @@ const kernelDiagnostics = defineDiagnosticCatalog({
|
|
|
995
1049
|
});
|
|
996
1050
|
//#endregion
|
|
997
1051
|
//#region src/definition/kernel/graphql-ast.ts
|
|
1052
|
+
const AST_KINDS = {
|
|
1053
|
+
object: "ObjectTypeDefinition",
|
|
1054
|
+
interface: "InterfaceTypeDefinition",
|
|
1055
|
+
enum: "EnumTypeDefinition",
|
|
1056
|
+
union: "UnionTypeDefinition",
|
|
1057
|
+
input: "InputObjectTypeDefinition"
|
|
1058
|
+
};
|
|
1059
|
+
const EXTENSION_TARGETS = {
|
|
1060
|
+
ObjectTypeExtension: "ObjectTypeDefinition",
|
|
1061
|
+
InterfaceTypeExtension: "InterfaceTypeDefinition",
|
|
1062
|
+
EnumTypeExtension: "EnumTypeDefinition",
|
|
1063
|
+
UnionTypeExtension: "UnionTypeDefinition",
|
|
1064
|
+
InputObjectTypeExtension: "InputObjectTypeDefinition"
|
|
1065
|
+
};
|
|
1066
|
+
const KIND_SPELLING = {
|
|
1067
|
+
ScalarTypeDefinition: {
|
|
1068
|
+
noun: "a scalar",
|
|
1069
|
+
keyword: "scalar"
|
|
1070
|
+
},
|
|
1071
|
+
ObjectTypeDefinition: {
|
|
1072
|
+
noun: "an object type",
|
|
1073
|
+
keyword: "type"
|
|
1074
|
+
},
|
|
1075
|
+
InterfaceTypeDefinition: {
|
|
1076
|
+
noun: "an interface",
|
|
1077
|
+
keyword: "interface"
|
|
1078
|
+
},
|
|
1079
|
+
EnumTypeDefinition: {
|
|
1080
|
+
noun: "an enum",
|
|
1081
|
+
keyword: "enum"
|
|
1082
|
+
},
|
|
1083
|
+
UnionTypeDefinition: {
|
|
1084
|
+
noun: "a union",
|
|
1085
|
+
keyword: "union"
|
|
1086
|
+
},
|
|
1087
|
+
InputObjectTypeDefinition: {
|
|
1088
|
+
noun: "an input",
|
|
1089
|
+
keyword: "input"
|
|
1090
|
+
}
|
|
1091
|
+
};
|
|
1092
|
+
const MEMBER_LISTS = [
|
|
1093
|
+
"fields",
|
|
1094
|
+
"values",
|
|
1095
|
+
"interfaces",
|
|
1096
|
+
"types"
|
|
1097
|
+
];
|
|
1098
|
+
function isNamedDefinition(node) {
|
|
1099
|
+
return Object.values(AST_KINDS).includes(node.kind);
|
|
1100
|
+
}
|
|
1101
|
+
function isNamedExtension(node) {
|
|
1102
|
+
return Object.hasOwn(EXTENSION_TARGETS, node.kind);
|
|
1103
|
+
}
|
|
1104
|
+
/**
|
|
1105
|
+
* Folds every extension into the type it extends. A repeated definition or
|
|
1106
|
+
* member keeps its first occurrence and is reported; an extension-only type
|
|
1107
|
+
* starts from its first extension.
|
|
1108
|
+
*/
|
|
1109
|
+
function foldTypeExtensions(definitions, path) {
|
|
1110
|
+
const types = /* @__PURE__ */ new Map();
|
|
1111
|
+
const redefinitions = [];
|
|
1112
|
+
const diagnostics = [];
|
|
1113
|
+
const memberPath = (index, list, name) => [
|
|
1114
|
+
...path,
|
|
1115
|
+
"definitions",
|
|
1116
|
+
index,
|
|
1117
|
+
list,
|
|
1118
|
+
name
|
|
1119
|
+
];
|
|
1120
|
+
const addMembers = (target, node, index) => {
|
|
1121
|
+
for (const list of MEMBER_LISTS) {
|
|
1122
|
+
const members = node[list];
|
|
1123
|
+
if (members === void 0) continue;
|
|
1124
|
+
for (const member of members) {
|
|
1125
|
+
const name = member.name.value;
|
|
1126
|
+
const key = `${list}:${name}`;
|
|
1127
|
+
const first = target.contributors.get(key);
|
|
1128
|
+
if (first !== void 0) {
|
|
1129
|
+
const coordinate = `${target.base.name.value}.${name}`;
|
|
1130
|
+
diagnostics.push(compatibilityDiagnostic(memberPath(index, list, name), `${coordinate} is defined more than once.`, {
|
|
1131
|
+
expected: "one definition per member",
|
|
1132
|
+
received: "a second definition",
|
|
1133
|
+
repair: `Remove the repeated ${name}; the host rejects a member defined twice.`,
|
|
1134
|
+
related: [{
|
|
1135
|
+
path: memberPath(first, list, name),
|
|
1136
|
+
message: `${coordinate} is first defined here.`
|
|
1137
|
+
}]
|
|
1138
|
+
}));
|
|
1139
|
+
continue;
|
|
1140
|
+
}
|
|
1141
|
+
target.contributors.set(key, index);
|
|
1142
|
+
target.lists[list]?.push(member);
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
};
|
|
1146
|
+
const start = (node, kind, index) => {
|
|
1147
|
+
const folding = {
|
|
1148
|
+
base: node,
|
|
1149
|
+
kind,
|
|
1150
|
+
index,
|
|
1151
|
+
contributors: /* @__PURE__ */ new Map(),
|
|
1152
|
+
lists: Object.fromEntries(MEMBER_LISTS.filter((list) => node[list] !== void 0).map((list) => [list, []])),
|
|
1153
|
+
directives: [...node.directives ?? []]
|
|
1154
|
+
};
|
|
1155
|
+
addMembers(folding, node, index);
|
|
1156
|
+
return folding;
|
|
1157
|
+
};
|
|
1158
|
+
const scalars = /* @__PURE__ */ new Set();
|
|
1159
|
+
const wrongKind = (index, name, defined, extension, extendedAs) => {
|
|
1160
|
+
diagnostics.push(compatibilityDiagnostic([
|
|
1161
|
+
...path,
|
|
1162
|
+
"definitions",
|
|
1163
|
+
index
|
|
1164
|
+
], `${name} is ${KIND_SPELLING[defined].noun}, so it cannot be extended as ${KIND_SPELLING[extendedAs].noun}.`, {
|
|
1165
|
+
expected: defined.replace("Definition", "Extension"),
|
|
1166
|
+
received: extension.kind,
|
|
1167
|
+
repair: `Extend ${name} with "extend ${KIND_SPELLING[defined].keyword}", or remove the extension; the host rejects an extension of a different kind.`
|
|
1168
|
+
}));
|
|
1169
|
+
};
|
|
1170
|
+
const foldScalarExtensions = (foldedTypes) => {
|
|
1171
|
+
definitions.forEach((node, index) => {
|
|
1172
|
+
if (node.kind !== "ScalarTypeExtension") return;
|
|
1173
|
+
const target = foldedTypes.get(node.name.value);
|
|
1174
|
+
if (target !== void 0) wrongKind(index, node.name.value, target.kind, node, "ScalarTypeDefinition");
|
|
1175
|
+
});
|
|
1176
|
+
};
|
|
1177
|
+
definitions.forEach((node, index) => {
|
|
1178
|
+
if (node.kind === "ScalarTypeDefinition") {
|
|
1179
|
+
scalars.add(node.name.value);
|
|
1180
|
+
return;
|
|
1181
|
+
}
|
|
1182
|
+
if (!isNamedDefinition(node)) return;
|
|
1183
|
+
const name = node.name.value;
|
|
1184
|
+
if (types.has(name)) {
|
|
1185
|
+
redefinitions.push({
|
|
1186
|
+
name,
|
|
1187
|
+
index
|
|
1188
|
+
});
|
|
1189
|
+
return;
|
|
1190
|
+
}
|
|
1191
|
+
types.set(name, start(node, node.kind, index));
|
|
1192
|
+
});
|
|
1193
|
+
definitions.forEach((node, index) => {
|
|
1194
|
+
if (!isNamedExtension(node)) return;
|
|
1195
|
+
const kind = EXTENSION_TARGETS[node.kind];
|
|
1196
|
+
const name = node.name.value;
|
|
1197
|
+
const target = types.get(name);
|
|
1198
|
+
if (target === void 0) {
|
|
1199
|
+
if (scalars.has(name)) {
|
|
1200
|
+
wrongKind(index, name, "ScalarTypeDefinition", node, kind);
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
1203
|
+
types.set(name, start(node, kind, index));
|
|
1204
|
+
return;
|
|
1205
|
+
}
|
|
1206
|
+
if (target.kind !== kind) {
|
|
1207
|
+
wrongKind(index, name, target.kind, node, kind);
|
|
1208
|
+
return;
|
|
1209
|
+
}
|
|
1210
|
+
target.directives.push(...node.directives);
|
|
1211
|
+
addMembers(target, node, index);
|
|
1212
|
+
});
|
|
1213
|
+
foldScalarExtensions(types);
|
|
1214
|
+
return {
|
|
1215
|
+
types: new Map([...types].map(([name, { base, kind, index, contributors, lists, directives }]) => [name, {
|
|
1216
|
+
node: {
|
|
1217
|
+
...base,
|
|
1218
|
+
kind,
|
|
1219
|
+
directives,
|
|
1220
|
+
...lists
|
|
1221
|
+
},
|
|
1222
|
+
index,
|
|
1223
|
+
contributors
|
|
1224
|
+
}])),
|
|
1225
|
+
redefinitions,
|
|
1226
|
+
diagnostics
|
|
1227
|
+
};
|
|
1228
|
+
}
|
|
998
1229
|
function compatibilityDiagnostic(path, message, detail = {}) {
|
|
999
1230
|
return kernelDiagnostics.create({
|
|
1000
1231
|
code: "PH-DEF-COMPATIBILITY-INVALID",
|
|
@@ -1169,15 +1400,15 @@ const compilerDiagnostics = defineDiagnosticCatalog({
|
|
|
1169
1400
|
}, kernelDiagnostics));
|
|
1170
1401
|
//#endregion
|
|
1171
1402
|
//#region src/definition/compiler/wire-shape.ts
|
|
1172
|
-
const BUILT_IN_SCALARS = [
|
|
1403
|
+
const BUILT_IN_SCALARS$1 = [
|
|
1173
1404
|
"ID",
|
|
1174
1405
|
"String",
|
|
1175
1406
|
"Boolean",
|
|
1176
1407
|
"Int",
|
|
1177
1408
|
"Float"
|
|
1178
1409
|
];
|
|
1179
|
-
const CATALOG_SCALARS = documentModelScalars.map(({ name }) => name);
|
|
1180
|
-
const MODEL_SCALARS = /* @__PURE__ */ new Set([...BUILT_IN_SCALARS, ...CATALOG_SCALARS]);
|
|
1410
|
+
const CATALOG_SCALARS$1 = documentModelScalars.map(({ name }) => name);
|
|
1411
|
+
const MODEL_SCALARS = /* @__PURE__ */ new Set([...BUILT_IN_SCALARS$1, ...CATALOG_SCALARS$1]);
|
|
1181
1412
|
const HOST_ONLY_SCALARS = new Set(scalarCatalog.map(({ name }) => name).filter((name) => !MODEL_SCALARS.has(name)));
|
|
1182
1413
|
const SCALAR_REPRESENTATIONS = [
|
|
1183
1414
|
"string",
|
|
@@ -1254,7 +1485,7 @@ var ShapeChecker = class {
|
|
|
1254
1485
|
return true;
|
|
1255
1486
|
}
|
|
1256
1487
|
};
|
|
1257
|
-
function typeReference(check, value, path) {
|
|
1488
|
+
function typeReference$1(check, value, path) {
|
|
1258
1489
|
const kind = value?.kind;
|
|
1259
1490
|
const node = kind === "list" ? check.record(value, [
|
|
1260
1491
|
"kind",
|
|
@@ -1267,7 +1498,7 @@ function typeReference(check, value, path) {
|
|
|
1267
1498
|
], path);
|
|
1268
1499
|
if (node === void 0) return;
|
|
1269
1500
|
if (typeof node.required !== "boolean") check.fail([...path, "required"], "A type reference records nullability.", "boolean", node.required);
|
|
1270
|
-
if (kind === "list") typeReference(check, node.item, [...path, "item"]);
|
|
1501
|
+
if (kind === "list") typeReference$1(check, node.item, [...path, "item"]);
|
|
1271
1502
|
else if (kind === "scalar") {
|
|
1272
1503
|
if (check.rejectHostOnlyScalar(node.name, [...path, "name"])) return;
|
|
1273
1504
|
if (typeof node.name !== "string" || !(MODEL_SCALARS.has(node.name) || check.packageScalars.has(node.name))) check.fail([...path, "name"], "A scalar reference names a catalog scalar, a GraphQL built-in, or a package scalar the specification declares.", [...MODEL_SCALARS, ...check.packageScalars].join(" | "), node.name);
|
|
@@ -1319,7 +1550,7 @@ function field(check, value, path, input) {
|
|
|
1319
1550
|
check.graphQLName(node.name, [...path, "name"]);
|
|
1320
1551
|
check.nullableString(node.description, [...path, "description"]);
|
|
1321
1552
|
check.nullableString(node.deprecated, [...path, "deprecated"]);
|
|
1322
|
-
typeReference(check, node.type, [...path, "type"]);
|
|
1553
|
+
typeReference$1(check, node.type, [...path, "type"]);
|
|
1323
1554
|
if (node.directives !== void 0) directiveUses(check, node.directives, [...path, "directives"]);
|
|
1324
1555
|
if (input) {
|
|
1325
1556
|
if (Object.hasOwn(node, "defaultValue")) check.json(node.defaultValue, [...path, "defaultValue"]);
|
|
@@ -1332,7 +1563,7 @@ function field(check, value, path, input) {
|
|
|
1332
1563
|
function fields(check, value, path, input) {
|
|
1333
1564
|
check.array(value, path)?.forEach((entry, index) => field(check, entry, [...path, index], input));
|
|
1334
1565
|
}
|
|
1335
|
-
function enumValue(check, value, path) {
|
|
1566
|
+
function enumValue$1(check, value, path) {
|
|
1336
1567
|
const node = check.record(value, [
|
|
1337
1568
|
"name",
|
|
1338
1569
|
"description",
|
|
@@ -1352,7 +1583,7 @@ const NAMED_TYPE_MEMBERS = {
|
|
|
1352
1583
|
input: "fields",
|
|
1353
1584
|
union: "members"
|
|
1354
1585
|
};
|
|
1355
|
-
function namedType(check, value, path) {
|
|
1586
|
+
function namedType$1(check, value, path) {
|
|
1356
1587
|
const kind = value?.kind;
|
|
1357
1588
|
if (typeof kind !== "string" || !Object.hasOwn(NAMED_TYPE_MEMBERS, kind)) return check.fail([...path, "kind"], "A named type has five kinds.", Object.keys(NAMED_TYPE_MEMBERS).join(" | "), kind);
|
|
1358
1589
|
const typed = kind;
|
|
@@ -1370,7 +1601,7 @@ function namedType(check, value, path) {
|
|
|
1370
1601
|
const members = check.array(node[member], [...path, member]);
|
|
1371
1602
|
switch (typed) {
|
|
1372
1603
|
case "enum":
|
|
1373
|
-
members?.forEach((entry, index) => enumValue(check, entry, [
|
|
1604
|
+
members?.forEach((entry, index) => enumValue$1(check, entry, [
|
|
1374
1605
|
...path,
|
|
1375
1606
|
"values",
|
|
1376
1607
|
index
|
|
@@ -1397,7 +1628,7 @@ function namedType(check, value, path) {
|
|
|
1397
1628
|
}
|
|
1398
1629
|
return check.graphQLName(node.name, [...path, "name"]);
|
|
1399
1630
|
}
|
|
1400
|
-
function examples(check, value, path, keys) {
|
|
1631
|
+
function examples$1(check, value, path, keys) {
|
|
1401
1632
|
check.array(value, path)?.forEach((entry, index) => {
|
|
1402
1633
|
const node = check.record(entry, keys, [...path, index]);
|
|
1403
1634
|
if (node === void 0) return;
|
|
@@ -1423,11 +1654,11 @@ function state(check, value, path, scope) {
|
|
|
1423
1654
|
if (canonicalJson(node.initialValue) !== "{}") check.fail([...path, "initialValue"], "An empty local state carries an exact empty object.", "{}", node.initialValue);
|
|
1424
1655
|
}
|
|
1425
1656
|
} else {
|
|
1426
|
-
typeReference(check, node.root, [...path, "root"]);
|
|
1657
|
+
typeReference$1(check, node.root, [...path, "root"]);
|
|
1427
1658
|
check.json(node.initialValue, [...path, "initialValue"]);
|
|
1428
1659
|
}
|
|
1429
1660
|
check.literal(node.unknownKeys, "preserve", [...path, "unknownKeys"]);
|
|
1430
|
-
examples(check, node.examples, [...path, "examples"], [
|
|
1661
|
+
examples$1(check, node.examples, [...path, "examples"], [
|
|
1431
1662
|
"id",
|
|
1432
1663
|
"key",
|
|
1433
1664
|
"value"
|
|
@@ -1442,7 +1673,7 @@ function state(check, value, path, scope) {
|
|
|
1442
1673
|
const schema = check.string(materialized.schema, [...materializedPath, "schema"]);
|
|
1443
1674
|
if (node.root === null && schema !== void 0 && schema !== "") check.fail([...materializedPath, "schema"], "An empty local state materializes an empty schema.", "\"\"", schema);
|
|
1444
1675
|
check.string(materialized.initialValue, [...materializedPath, "initialValue"]);
|
|
1445
|
-
examples(check, materialized.examples, [...materializedPath, "examples"], ["id", "value"]);
|
|
1676
|
+
examples$1(check, materialized.examples, [...materializedPath, "examples"], ["id", "value"]);
|
|
1446
1677
|
}
|
|
1447
1678
|
const OPERATION_KEYS = [
|
|
1448
1679
|
"id",
|
|
@@ -1489,7 +1720,7 @@ function operation(check, value, path) {
|
|
|
1489
1720
|
"input",
|
|
1490
1721
|
"kind"
|
|
1491
1722
|
], "An operation input is an input type.", "input", kind);
|
|
1492
|
-
else namedType(check, node.input, [...path, "input"]);
|
|
1723
|
+
else namedType$1(check, node.input, [...path, "input"]);
|
|
1493
1724
|
}
|
|
1494
1725
|
check.array(node.errors, [...path, "errors"])?.forEach((entry, index) => {
|
|
1495
1726
|
const at = [
|
|
@@ -1508,7 +1739,7 @@ function operation(check, value, path) {
|
|
|
1508
1739
|
"template"
|
|
1509
1740
|
]) check.nullableString(error[key], [...at, key]);
|
|
1510
1741
|
});
|
|
1511
|
-
examples(check, node.examples, [...path, "examples"], [
|
|
1742
|
+
examples$1(check, node.examples, [...path, "examples"], [
|
|
1512
1743
|
"id",
|
|
1513
1744
|
"key",
|
|
1514
1745
|
"value"
|
|
@@ -1553,7 +1784,7 @@ function scalars(check, value, path) {
|
|
|
1553
1784
|
check.literal(scalar.coercionProfile, "catalog-v1", [...at, "coercionProfile"]);
|
|
1554
1785
|
if (check.rejectHostOnlyScalar(scalar.name, [...at, "name"])) return;
|
|
1555
1786
|
if (!isPackage) {
|
|
1556
|
-
const name = check.oneOf(scalar.name, CATALOG_SCALARS, [...at, "name"]);
|
|
1787
|
+
const name = check.oneOf(scalar.name, CATALOG_SCALARS$1, [...at, "name"]);
|
|
1557
1788
|
if (name !== void 0) check.literal(scalar.implementation, `powerhouse.catalog#${name}`, [...at, "implementation"]);
|
|
1558
1789
|
return;
|
|
1559
1790
|
}
|
|
@@ -1597,7 +1828,7 @@ function specification(check, value, path) {
|
|
|
1597
1828
|
}
|
|
1598
1829
|
const declared = /* @__PURE__ */ new Set();
|
|
1599
1830
|
check.array(node.types, [...path, "types"])?.forEach((entry, index) => {
|
|
1600
|
-
const name = namedType(check, entry, [
|
|
1831
|
+
const name = namedType$1(check, entry, [
|
|
1601
1832
|
...path,
|
|
1602
1833
|
"types",
|
|
1603
1834
|
index
|
|
@@ -1986,6 +2217,25 @@ function realPathThroughExistingParent(path) {
|
|
|
1986
2217
|
}
|
|
1987
2218
|
return resolve(realpathSync.native(current), ...suffix);
|
|
1988
2219
|
}
|
|
2220
|
+
/** Where a lexically contained module really lives, unless a symlink takes it out of the package. */
|
|
2221
|
+
function realModulePath(packageRoot, packageRootIdentity, specifier) {
|
|
2222
|
+
let moduleIdentity;
|
|
2223
|
+
try {
|
|
2224
|
+
moduleIdentity = realPathThroughExistingParent(resolve(packageRoot, ...specifier.slice(2).split("/")));
|
|
2225
|
+
} catch {
|
|
2226
|
+
return {
|
|
2227
|
+
ok: false,
|
|
2228
|
+
reason: "unresolvable"
|
|
2229
|
+
};
|
|
2230
|
+
}
|
|
2231
|
+
return isWithin(packageRootIdentity, moduleIdentity) ? {
|
|
2232
|
+
ok: true,
|
|
2233
|
+
moduleIdentity
|
|
2234
|
+
} : {
|
|
2235
|
+
ok: false,
|
|
2236
|
+
reason: "outside"
|
|
2237
|
+
};
|
|
2238
|
+
}
|
|
1989
2239
|
function invalidEntry(path, message, expected, received, repair, source) {
|
|
1990
2240
|
return { diagnostic: toolingDiagnostics.create({
|
|
1991
2241
|
code: "PH-CONFIG-SOURCE-INVALID",
|
|
@@ -2024,14 +2274,9 @@ function normalizeEntry(value, position, packageRoot, packageRootIdentity) {
|
|
|
2024
2274
|
specifier,
|
|
2025
2275
|
exportPath
|
|
2026
2276
|
};
|
|
2027
|
-
const
|
|
2028
|
-
|
|
2029
|
-
|
|
2030
|
-
moduleIdentity = realPathThroughExistingParent(declaredPath);
|
|
2031
|
-
} catch {
|
|
2032
|
-
return invalidEntry(specifierPath, "The definition source path could not be resolved.", "a resolvable path inside the package root", specifier, "Fix the path, or the permissions of a directory on the way to it.", source);
|
|
2033
|
-
}
|
|
2034
|
-
if (!isWithin(packageRootIdentity, moduleIdentity)) return { diagnostic: toolingDiagnostics.create({
|
|
2277
|
+
const real = realModulePath(packageRoot, packageRootIdentity, specifier);
|
|
2278
|
+
if (!real.ok && real.reason === "unresolvable") return invalidEntry(specifierPath, "The definition source path could not be resolved.", "a resolvable path inside the package root", specifier, "Fix the path, or the permissions of a directory on the way to it.", source);
|
|
2279
|
+
if (!real.ok) return { diagnostic: toolingDiagnostics.create({
|
|
2035
2280
|
code: "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE",
|
|
2036
2281
|
source,
|
|
2037
2282
|
path: specifierPath,
|
|
@@ -2043,7 +2288,7 @@ function normalizeEntry(value, position, packageRoot, packageRootIdentity) {
|
|
|
2043
2288
|
return { source: {
|
|
2044
2289
|
source,
|
|
2045
2290
|
position,
|
|
2046
|
-
moduleIdentity
|
|
2291
|
+
moduleIdentity: real.moduleIdentity
|
|
2047
2292
|
} };
|
|
2048
2293
|
}
|
|
2049
2294
|
function duplicateDiagnostics(sources) {
|
|
@@ -2142,17 +2387,27 @@ function selectionDiagnostic(narrowed) {
|
|
|
2142
2387
|
repair: `Set this member to ${narrowed.expected}.`
|
|
2143
2388
|
});
|
|
2144
2389
|
}
|
|
2145
|
-
|
|
2390
|
+
/** The selected config file, its directory, and that directory's real path when it exists. */
|
|
2391
|
+
function packageRoots(request) {
|
|
2146
2392
|
const configFile = resolve(request.configFile ?? CONFIG_FILE_NAME);
|
|
2147
2393
|
const packageRoot = dirname(configFile);
|
|
2148
|
-
let packageRootIdentity = packageRoot;
|
|
2149
2394
|
try {
|
|
2150
|
-
|
|
2151
|
-
|
|
2152
|
-
|
|
2153
|
-
|
|
2154
|
-
|
|
2155
|
-
}
|
|
2395
|
+
return {
|
|
2396
|
+
configFile,
|
|
2397
|
+
packageRoot,
|
|
2398
|
+
packageRootIdentity: realpathSync.native(packageRoot)
|
|
2399
|
+
};
|
|
2400
|
+
} catch {
|
|
2401
|
+
return {
|
|
2402
|
+
configFile,
|
|
2403
|
+
packageRoot,
|
|
2404
|
+
packageRootIdentity: packageRoot
|
|
2405
|
+
};
|
|
2406
|
+
}
|
|
2407
|
+
}
|
|
2408
|
+
function resolveDefinitionSources(request) {
|
|
2409
|
+
const { configFile, ...roots } = packageRoots(request);
|
|
2410
|
+
const { packageRoot, packageRootIdentity } = roots;
|
|
2156
2411
|
if (request.allowMissingConfig === true && !existsSync(configFile)) return skipped(roots, "definition-sources-absent", DEFAULT_AUTHORING_MODE);
|
|
2157
2412
|
const config = readConfigObject(configFile);
|
|
2158
2413
|
if (!config.ok) return failed(roots, [toolingDiagnostics.create({
|
|
@@ -2519,6 +2774,44 @@ function selectExport(source, namespace) {
|
|
|
2519
2774
|
function sortBySource(entries) {
|
|
2520
2775
|
return [...entries].sort((left, right) => compareDefinitionSources(left.source, right.source) || compareDefinitionPaths(left.path, right.path));
|
|
2521
2776
|
}
|
|
2777
|
+
function revisionDiagnostic(revision) {
|
|
2778
|
+
return toolingDiagnostics.create({
|
|
2779
|
+
code: "PH-CONFIG-SOURCE-INVALID",
|
|
2780
|
+
path: ["packageRevision"],
|
|
2781
|
+
message: "The package revision is not a SHA-256 identifier, so no import can be bound to it.",
|
|
2782
|
+
expected: "sha256: followed by 64 lowercase hexadecimal digits",
|
|
2783
|
+
received: typeof revision === "string" ? revision : describeReceived(revision),
|
|
2784
|
+
repair: "Pass a revision digest of the package's current files."
|
|
2785
|
+
});
|
|
2786
|
+
}
|
|
2787
|
+
function refusedModule(specifier, code, message) {
|
|
2788
|
+
return {
|
|
2789
|
+
ok: false,
|
|
2790
|
+
diagnostic: toolingDiagnostics.create({
|
|
2791
|
+
code,
|
|
2792
|
+
source: { specifier },
|
|
2793
|
+
path: [],
|
|
2794
|
+
message,
|
|
2795
|
+
expected: "a './' module path whose real path stays inside the package root",
|
|
2796
|
+
received: specifier,
|
|
2797
|
+
repair: "Keep the module inside the package, and do not reach it through a symlink that leaves the package."
|
|
2798
|
+
})
|
|
2799
|
+
};
|
|
2800
|
+
}
|
|
2801
|
+
/** The selected sources' containment rules, so a module outside the package is never imported. */
|
|
2802
|
+
function containedPackageModule(request) {
|
|
2803
|
+
const { packageRoot, packageRootIdentity } = packageRoots(request);
|
|
2804
|
+
const normalized = normalizeSpecifier(request.specifier);
|
|
2805
|
+
if (!normalized.ok) return refusedModule(request.specifier, normalized.code, normalized.message);
|
|
2806
|
+
const real = realModulePath(packageRoot, packageRootIdentity, normalized.specifier);
|
|
2807
|
+
if (real.ok) return {
|
|
2808
|
+
ok: true,
|
|
2809
|
+
specifier: normalized.specifier,
|
|
2810
|
+
packageRootIdentity,
|
|
2811
|
+
moduleIdentity: real.moduleIdentity
|
|
2812
|
+
};
|
|
2813
|
+
return real.reason === "outside" ? refusedModule(request.specifier, "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE", "The package module resolves through a symlink that leaves the package root.") : refusedModule(request.specifier, "PH-CONFIG-SOURCE-INVALID", "The package module path could not be resolved.");
|
|
2814
|
+
}
|
|
2522
2815
|
function empty(resolution) {
|
|
2523
2816
|
return {
|
|
2524
2817
|
...resolution,
|
|
@@ -2552,14 +2845,7 @@ var DefinitionSourceLoader = class {
|
|
|
2552
2845
|
packageRoot: resolution.packageRoot,
|
|
2553
2846
|
sourceSet: resolution.sourceSet,
|
|
2554
2847
|
status: "failed",
|
|
2555
|
-
diagnostics: [
|
|
2556
|
-
code: "PH-CONFIG-SOURCE-INVALID",
|
|
2557
|
-
path: ["packageRevision"],
|
|
2558
|
-
message: "The package revision is not a SHA-256 identifier, so no import can be bound to it.",
|
|
2559
|
-
expected: "sha256: followed by 64 lowercase hexadecimal digits",
|
|
2560
|
-
received: typeof request.packageRevision === "string" ? request.packageRevision : describeReceived(request.packageRevision),
|
|
2561
|
-
repair: "Pass a revision digest of the package's current files."
|
|
2562
|
-
})]
|
|
2848
|
+
diagnostics: [revisionDiagnostic(request.packageRevision)]
|
|
2563
2849
|
});
|
|
2564
2850
|
await this.#retainRevision(request.packageRevision);
|
|
2565
2851
|
const namespaces = await this.#importModules(resolution, request);
|
|
@@ -2604,6 +2890,34 @@ var DefinitionSourceLoader = class {
|
|
|
2604
2890
|
upgradeManifests: sortBySource(collected.upgradeManifests)
|
|
2605
2891
|
};
|
|
2606
2892
|
}
|
|
2893
|
+
/**
|
|
2894
|
+
* @experimental Imports one package module through the same importer and
|
|
2895
|
+
* package revision as the selected sources, so a module both reach is
|
|
2896
|
+
* evaluated once. A module outside the package root is refused as an
|
|
2897
|
+
* outside source is. Experimental: tooling uses it for the project scalars
|
|
2898
|
+
* module while code-first projects are introduced.
|
|
2899
|
+
*/
|
|
2900
|
+
async importPackageModule(request) {
|
|
2901
|
+
request.signal?.throwIfAborted();
|
|
2902
|
+
if (!isSha256Digest(request.packageRevision)) return {
|
|
2903
|
+
ok: false,
|
|
2904
|
+
diagnostics: [revisionDiagnostic(request.packageRevision)]
|
|
2905
|
+
};
|
|
2906
|
+
const contained = containedPackageModule(request);
|
|
2907
|
+
if (!contained.ok) return {
|
|
2908
|
+
ok: false,
|
|
2909
|
+
diagnostics: [contained.diagnostic]
|
|
2910
|
+
};
|
|
2911
|
+
await this.#retainRevision(request.packageRevision);
|
|
2912
|
+
const imported = await this.#import(contained, request);
|
|
2913
|
+
return imported.ok ? {
|
|
2914
|
+
ok: true,
|
|
2915
|
+
namespace: imported.value
|
|
2916
|
+
} : {
|
|
2917
|
+
ok: false,
|
|
2918
|
+
diagnostics: imported.diagnostics({ specifier: request.specifier })
|
|
2919
|
+
};
|
|
2920
|
+
}
|
|
2607
2921
|
async dispose() {
|
|
2608
2922
|
const revision = this.#revision;
|
|
2609
2923
|
this.#imports.clear();
|
|
@@ -2617,39 +2931,2476 @@ var DefinitionSourceLoader = class {
|
|
|
2617
2931
|
this.#revision = revision;
|
|
2618
2932
|
if (superseded !== void 0) await this.#importer.disposeRevision?.(superseded);
|
|
2619
2933
|
}
|
|
2934
|
+
/** One evaluation per module and revision, whichever path asks first. */
|
|
2935
|
+
async #import(module, request) {
|
|
2936
|
+
const { moduleIdentity } = module;
|
|
2937
|
+
let namespace = this.#imports.get(moduleIdentity);
|
|
2938
|
+
if (namespace === void 0) {
|
|
2939
|
+
namespace = this.#importer.importModule({
|
|
2940
|
+
packageRoot: module.packageRootIdentity,
|
|
2941
|
+
specifier: module.specifier,
|
|
2942
|
+
packageRevision: request.packageRevision,
|
|
2943
|
+
...request.signal !== void 0 && { signal: request.signal }
|
|
2944
|
+
});
|
|
2945
|
+
this.#imports.set(moduleIdentity, namespace);
|
|
2946
|
+
namespace.catch(() => this.#imports.delete(moduleIdentity));
|
|
2947
|
+
}
|
|
2948
|
+
try {
|
|
2949
|
+
return {
|
|
2950
|
+
ok: true,
|
|
2951
|
+
value: namespaceSnapshot(await namespace)
|
|
2952
|
+
};
|
|
2953
|
+
} catch (error) {
|
|
2954
|
+
const missing = !existsSync(moduleIdentity);
|
|
2955
|
+
return {
|
|
2956
|
+
ok: false,
|
|
2957
|
+
diagnostics: (source) => importDiagnostics(error, source, missing)
|
|
2958
|
+
};
|
|
2959
|
+
}
|
|
2960
|
+
}
|
|
2620
2961
|
async #importModules(resolution, request) {
|
|
2621
2962
|
const results = /* @__PURE__ */ new Map();
|
|
2622
|
-
for (const
|
|
2623
|
-
const { moduleIdentity, source } = entry;
|
|
2963
|
+
for (const { moduleIdentity, source } of resolution.resolved) {
|
|
2624
2964
|
if (results.has(moduleIdentity)) continue;
|
|
2625
|
-
|
|
2626
|
-
|
|
2627
|
-
|
|
2628
|
-
|
|
2629
|
-
|
|
2630
|
-
|
|
2631
|
-
...request.signal !== void 0 && { signal: request.signal }
|
|
2632
|
-
});
|
|
2633
|
-
this.#imports.set(moduleIdentity, namespace);
|
|
2634
|
-
namespace.catch(() => this.#imports.delete(moduleIdentity));
|
|
2635
|
-
}
|
|
2636
|
-
try {
|
|
2637
|
-
results.set(moduleIdentity, {
|
|
2638
|
-
ok: true,
|
|
2639
|
-
value: namespaceSnapshot(await namespace)
|
|
2640
|
-
});
|
|
2641
|
-
} catch (error) {
|
|
2642
|
-
const missing = !existsSync(moduleIdentity);
|
|
2643
|
-
results.set(moduleIdentity, {
|
|
2644
|
-
ok: false,
|
|
2645
|
-
diagnostics: (failedSource) => importDiagnostics(error, failedSource, missing)
|
|
2646
|
-
});
|
|
2647
|
-
}
|
|
2965
|
+
const module = {
|
|
2966
|
+
specifier: source.specifier,
|
|
2967
|
+
packageRootIdentity: resolution.packageRootIdentity,
|
|
2968
|
+
moduleIdentity
|
|
2969
|
+
};
|
|
2970
|
+
results.set(moduleIdentity, await this.#import(module, request));
|
|
2648
2971
|
}
|
|
2649
2972
|
return results;
|
|
2650
2973
|
}
|
|
2651
2974
|
};
|
|
2652
2975
|
//#endregion
|
|
2653
|
-
|
|
2976
|
+
//#region src/definition/compiler/naming.ts
|
|
2977
|
+
function deriveDocumentModelNames(model, overrides = {}) {
|
|
2978
|
+
const graphQLName = overrides.graphQLName ?? pascalCase(model.name);
|
|
2979
|
+
return {
|
|
2980
|
+
documentType: overrides.documentType ?? model.id,
|
|
2981
|
+
graphQLName,
|
|
2982
|
+
globalStateRootName: overrides.globalStateRootName ?? `${graphQLName}State`,
|
|
2983
|
+
localStateRootName: overrides.localStateRootName ?? `${graphQLName}LocalState`
|
|
2984
|
+
};
|
|
2985
|
+
}
|
|
2986
|
+
const PLATFORM_ACTION_TYPES = /* @__PURE__ */ new Set([
|
|
2987
|
+
"SET_NAME",
|
|
2988
|
+
"SET_PREFERRED_EDITOR",
|
|
2989
|
+
"UNDO",
|
|
2990
|
+
"REDO",
|
|
2991
|
+
"RETRACT",
|
|
2992
|
+
"CREATE_DOCUMENT",
|
|
2993
|
+
"DELETE_DOCUMENT",
|
|
2994
|
+
"UPGRADE_DOCUMENT",
|
|
2995
|
+
"ADD_RELATIONSHIP",
|
|
2996
|
+
"REMOVE_RELATIONSHIP",
|
|
2997
|
+
"UPDATE_RELATIONSHIP",
|
|
2998
|
+
"PURGE_DOCUMENT"
|
|
2999
|
+
]);
|
|
3000
|
+
function deriveOperationErrorClassName(errorKey) {
|
|
3001
|
+
return pascalCase(errorKey);
|
|
3002
|
+
}
|
|
3003
|
+
/** The symbol spellings codegen derives from a stored schema-first name. */
|
|
3004
|
+
function deriveDocumentModelSymbolNames(name) {
|
|
3005
|
+
return {
|
|
3006
|
+
typeName: pascalCase(name),
|
|
3007
|
+
memberName: camelCase(name),
|
|
3008
|
+
constantName: constantCase(name)
|
|
3009
|
+
};
|
|
3010
|
+
}
|
|
3011
|
+
//#endregion
|
|
3012
|
+
//#region src/definition/tooling/check/diagnostic-codes.ts
|
|
3013
|
+
const checkDiagnostics = defineDiagnosticCatalog({
|
|
3014
|
+
"PH-DM-DUPLICATE-ERROR-CODE": {
|
|
3015
|
+
severity: "error",
|
|
3016
|
+
phase: "definition",
|
|
3017
|
+
meaning: "Two errors of one operation persist the same error code, so a caller cannot tell them apart"
|
|
3018
|
+
},
|
|
3019
|
+
"PH-DM-ERROR-CLASS-CONFLICT": {
|
|
3020
|
+
severity: "error",
|
|
3021
|
+
phase: "definition",
|
|
3022
|
+
meaning: "Two errors of one module generate the same error class with different codes"
|
|
3023
|
+
},
|
|
3024
|
+
"PH-PKG-SCALAR-CONFLICT": {
|
|
3025
|
+
severity: "error",
|
|
3026
|
+
phase: "package",
|
|
3027
|
+
meaning: "Two models of one package use different project scalars with one name, and a host declares each scalar once"
|
|
3028
|
+
},
|
|
3029
|
+
"PH-PKG-DEFINITION-UNREGISTERED": {
|
|
3030
|
+
severity: "error",
|
|
3031
|
+
phase: "package",
|
|
3032
|
+
meaning: "A code-first document model under the document models directory is reached by no definitionSources entry, so the package leaves it out"
|
|
3033
|
+
}
|
|
3034
|
+
}, toolingDiagnostics);
|
|
3035
|
+
//#endregion
|
|
3036
|
+
//#region src/definition/tooling/report/served-specification.ts
|
|
3037
|
+
/**
|
|
3038
|
+
* The specification an artifact serves, and its index in the history. Every
|
|
3039
|
+
* member of a family carries the whole history, so a check that read every
|
|
3040
|
+
* specification of every artifact would report one defect once per member.
|
|
3041
|
+
*/
|
|
3042
|
+
function servedSpecification(artifact) {
|
|
3043
|
+
const index = artifact.definition.specifications.findIndex(({ version }) => version === artifact.version);
|
|
3044
|
+
return index === -1 ? void 0 : {
|
|
3045
|
+
specification: artifact.definition.specifications[index],
|
|
3046
|
+
index
|
|
3047
|
+
};
|
|
3048
|
+
}
|
|
3049
|
+
function documentModelRef(artifact) {
|
|
3050
|
+
return {
|
|
3051
|
+
kind: "document-model",
|
|
3052
|
+
key: artifact.documentType,
|
|
3053
|
+
version: artifact.version
|
|
3054
|
+
};
|
|
3055
|
+
}
|
|
3056
|
+
//#endregion
|
|
3057
|
+
//#region src/definition/tooling/check/checks/duplicate-identities.ts
|
|
3058
|
+
/** Codegen's rule: an empty or absent code falls back to the class name. */
|
|
3059
|
+
function effectiveErrorCode(code, className) {
|
|
3060
|
+
return code?.trim() || className;
|
|
3061
|
+
}
|
|
3062
|
+
/**
|
|
3063
|
+
* The compiler refuses duplicate module keys, action types and creator keys,
|
|
3064
|
+
* an action type the document runtime owns, and an error class with two codes
|
|
3065
|
+
* in one module, before a code-first module exists, so for those this check fires only on a stored schema-first model.
|
|
3066
|
+
* Two errors of one operation sharing a code pass the compiler in both modes.
|
|
3067
|
+
*/
|
|
3068
|
+
function duplicates(artifact) {
|
|
3069
|
+
const served = servedSpecification(artifact);
|
|
3070
|
+
if (served === void 0) return [];
|
|
3071
|
+
const { specification, index } = served;
|
|
3072
|
+
const diagnostics = [];
|
|
3073
|
+
const report = (code, claimant, first, detail) => diagnostics.push(checkDiagnostics.create({
|
|
3074
|
+
code,
|
|
3075
|
+
source: artifact.source,
|
|
3076
|
+
definition: documentModelRef(artifact),
|
|
3077
|
+
path: claimant.path,
|
|
3078
|
+
...detail,
|
|
3079
|
+
related: [{
|
|
3080
|
+
source: artifact.source,
|
|
3081
|
+
path: first.path,
|
|
3082
|
+
message: `${first.label} claims it first.`
|
|
3083
|
+
}]
|
|
3084
|
+
}));
|
|
3085
|
+
const shared = (code, claimant, first, [kind, value], repair) => report(code, claimant, first, {
|
|
3086
|
+
message: `${claimant.label} and ${first.label} share the ${kind} ${value}.`,
|
|
3087
|
+
expected: `one declaration per ${kind}`,
|
|
3088
|
+
received: value,
|
|
3089
|
+
repair
|
|
3090
|
+
});
|
|
3091
|
+
const modules = /* @__PURE__ */ new Map();
|
|
3092
|
+
const actionTypes = /* @__PURE__ */ new Map();
|
|
3093
|
+
const operationKeys = /* @__PURE__ */ new Map();
|
|
3094
|
+
specification.modules.forEach((module, moduleIndex) => {
|
|
3095
|
+
const modulePath = [
|
|
3096
|
+
"specifications",
|
|
3097
|
+
index,
|
|
3098
|
+
"modules",
|
|
3099
|
+
moduleIndex
|
|
3100
|
+
];
|
|
3101
|
+
const moduleClaim = {
|
|
3102
|
+
path: modulePath,
|
|
3103
|
+
label: `module ${JSON.stringify(module.key)}`
|
|
3104
|
+
};
|
|
3105
|
+
const firstModule = modules.get(module.key);
|
|
3106
|
+
if (firstModule === void 0) modules.set(module.key, moduleClaim);
|
|
3107
|
+
else shared("PH-DM-DUPLICATE-NAME", moduleClaim, firstModule, ["key", module.key], "Rename one of the modules.");
|
|
3108
|
+
const errorClasses = /* @__PURE__ */ new Map();
|
|
3109
|
+
module.operations.forEach((operation, operationIndex) => {
|
|
3110
|
+
const operationPath = [
|
|
3111
|
+
...modulePath,
|
|
3112
|
+
"operations",
|
|
3113
|
+
operationIndex
|
|
3114
|
+
];
|
|
3115
|
+
const claim = {
|
|
3116
|
+
path: operationPath,
|
|
3117
|
+
label: `operation ${JSON.stringify(`${module.key}.${operation.key}`)}`
|
|
3118
|
+
};
|
|
3119
|
+
if (PLATFORM_ACTION_TYPES.has(operation.actionType)) diagnostics.push(checkDiagnostics.create({
|
|
3120
|
+
code: "PH-DM-DUPLICATE-ACTION",
|
|
3121
|
+
source: artifact.source,
|
|
3122
|
+
definition: documentModelRef(artifact),
|
|
3123
|
+
path: [...operationPath, "key"],
|
|
3124
|
+
message: `${claim.label} has action type ${operation.actionType}, which the document runtime reduces itself, so this operation's reducer would never run.`,
|
|
3125
|
+
expected: "an action type the document runtime does not own",
|
|
3126
|
+
received: operation.actionType,
|
|
3127
|
+
repair: "Rename the operation."
|
|
3128
|
+
}));
|
|
3129
|
+
const firstAction = actionTypes.get(operation.actionType);
|
|
3130
|
+
const firstKey = operationKeys.get(operation.key);
|
|
3131
|
+
if (firstAction !== void 0) shared("PH-DM-DUPLICATE-ACTION", claim, firstAction, ["action type", operation.actionType], "Rename one of the operations; a replayed history cannot tell which reducer wrote a shared action type.");
|
|
3132
|
+
else if (firstKey !== void 0) shared("PH-DM-DUPLICATE-NAME", claim, firstKey, ["creator key", operation.key], "Rename one of the operations; action creators share one namespace.");
|
|
3133
|
+
actionTypes.set(operation.actionType, firstAction ?? claim);
|
|
3134
|
+
operationKeys.set(operation.key, firstKey ?? claim);
|
|
3135
|
+
const errorKeys = /* @__PURE__ */ new Map();
|
|
3136
|
+
const errorCodes = /* @__PURE__ */ new Map();
|
|
3137
|
+
operation.errors.forEach((error, errorIndex) => {
|
|
3138
|
+
const errorClaim = {
|
|
3139
|
+
path: [
|
|
3140
|
+
...operationPath,
|
|
3141
|
+
"errors",
|
|
3142
|
+
errorIndex
|
|
3143
|
+
],
|
|
3144
|
+
label: `error ${JSON.stringify(error.key)}`
|
|
3145
|
+
};
|
|
3146
|
+
const className = deriveOperationErrorClassName(error.name ?? error.key);
|
|
3147
|
+
const code = effectiveErrorCode(error.code, className);
|
|
3148
|
+
const sameKey = errorKeys.get(error.key);
|
|
3149
|
+
const sameCode = errorCodes.get(code);
|
|
3150
|
+
const sameClass = errorClasses.get(className);
|
|
3151
|
+
if (sameKey !== void 0) shared("PH-DM-DUPLICATE-NAME", errorClaim, sameKey, ["key", error.key], "Rename one of the errors; each generates its own class.");
|
|
3152
|
+
else if (sameCode !== void 0) shared("PH-DM-DUPLICATE-ERROR-CODE", errorClaim, sameCode, ["code", code], "Give each error of the operation its own code, so a caller can tell them apart.");
|
|
3153
|
+
else if (sameClass !== void 0 && sameClass.code !== code) report("PH-DM-ERROR-CLASS-CONFLICT", errorClaim, sameClass, {
|
|
3154
|
+
message: `${errorClaim.label} of ${claim.label} gives the error class ${className} the code ${JSON.stringify(code)}, and ${sameClass.label} gives it ${JSON.stringify(sameClass.code)}.`,
|
|
3155
|
+
expected: sameClass.code,
|
|
3156
|
+
received: code,
|
|
3157
|
+
repair: `Give both ${className} errors the same code, or give one another name; a module generates one ${className} class.`
|
|
3158
|
+
});
|
|
3159
|
+
errorKeys.set(error.key, sameKey ?? errorClaim);
|
|
3160
|
+
errorCodes.set(code, sameCode ?? errorClaim);
|
|
3161
|
+
if (sameClass === void 0) errorClasses.set(className, {
|
|
3162
|
+
...errorClaim,
|
|
3163
|
+
label: `${errorClaim.label} of ${claim.label}`,
|
|
3164
|
+
code
|
|
3165
|
+
});
|
|
3166
|
+
});
|
|
3167
|
+
});
|
|
3168
|
+
});
|
|
3169
|
+
return diagnostics;
|
|
3170
|
+
}
|
|
3171
|
+
const duplicateIdentitiesCheck = {
|
|
3172
|
+
name: "duplicate-identities",
|
|
3173
|
+
run: ({ artifacts }) => artifacts.flatMap(duplicates)
|
|
3174
|
+
};
|
|
3175
|
+
//#endregion
|
|
3176
|
+
//#region src/definition/tooling/graphql/parse-schema.ts
|
|
3177
|
+
let graphql;
|
|
3178
|
+
/**
|
|
3179
|
+
* `graphql` is an optional peer: only tooling that reads SDL needs it, and a
|
|
3180
|
+
* package that imports document-model at runtime must not pay for it.
|
|
3181
|
+
*/
|
|
3182
|
+
function loadGraphQL() {
|
|
3183
|
+
if (graphql !== void 0) return graphql;
|
|
3184
|
+
const require = createRequire(import.meta.url);
|
|
3185
|
+
let loaded;
|
|
3186
|
+
let validation;
|
|
3187
|
+
try {
|
|
3188
|
+
loaded = require("graphql");
|
|
3189
|
+
validation = require("graphql/validation/validate.js");
|
|
3190
|
+
} catch (error) {
|
|
3191
|
+
throw new Error("Reading GraphQL SDL needs the optional peer dependency graphql@^16. Install it in the package that runs this tool.", { cause: error });
|
|
3192
|
+
}
|
|
3193
|
+
if (loaded === null || typeof loaded !== "object" || typeof loaded.parse !== "function" || typeof loaded.buildASTSchema !== "function" || typeof validation.validateSDL !== "function") throw new Error("The installed graphql package does not export parse, buildASTSchema and validateSDL; install graphql@^16.");
|
|
3194
|
+
graphql = {
|
|
3195
|
+
...loaded,
|
|
3196
|
+
validateSDL: validation.validateSDL
|
|
3197
|
+
};
|
|
3198
|
+
return graphql;
|
|
3199
|
+
}
|
|
3200
|
+
function withoutLocations(node) {
|
|
3201
|
+
if (Array.isArray(node)) return node.map(withoutLocations);
|
|
3202
|
+
if (node === null || typeof node !== "object") return node;
|
|
3203
|
+
return Object.fromEntries(Object.entries(node).filter(([key, value]) => key !== "loc" && value !== void 0).map(([key, value]) => [key, withoutLocations(value)]));
|
|
3204
|
+
}
|
|
3205
|
+
const EMPTY_DOCUMENT = {
|
|
3206
|
+
kind: "Document",
|
|
3207
|
+
definitions: []
|
|
3208
|
+
};
|
|
3209
|
+
/** Parses one stored SDL segment. A missing `graphql` peer throws; bad SDL does not. */
|
|
3210
|
+
function parseSchema(sdl) {
|
|
3211
|
+
if (sdl.trim() === "") return {
|
|
3212
|
+
ok: true,
|
|
3213
|
+
document: EMPTY_DOCUMENT
|
|
3214
|
+
};
|
|
3215
|
+
const { parse } = loadGraphQL();
|
|
3216
|
+
try {
|
|
3217
|
+
return {
|
|
3218
|
+
ok: true,
|
|
3219
|
+
document: withoutLocations(parse(sdl, { noLocation: true }))
|
|
3220
|
+
};
|
|
3221
|
+
} catch (error) {
|
|
3222
|
+
return {
|
|
3223
|
+
ok: false,
|
|
3224
|
+
message: error instanceof Error ? error.message : String(error)
|
|
3225
|
+
};
|
|
3226
|
+
}
|
|
3227
|
+
}
|
|
3228
|
+
//#endregion
|
|
3229
|
+
//#region src/definition/tooling/check/checks/graphql-schema.ts
|
|
3230
|
+
/** The first graphql-js message pattern that matches picks the code. */
|
|
3231
|
+
const ERROR_CODES = [
|
|
3232
|
+
{
|
|
3233
|
+
pattern: /^(?:Interface field |Object field \S+ includes required argument |Type \S+ (?:must only implement|cannot implement|can only implement|must implement) )/,
|
|
3234
|
+
code: "PH-DM-INTERFACE-INVALID",
|
|
3235
|
+
repair: "Give the type every field, argument and ancestor interface its interfaces declare, with compatible types."
|
|
3236
|
+
},
|
|
3237
|
+
{
|
|
3238
|
+
pattern: / must be (?:Input|Output) Type but got: /,
|
|
3239
|
+
code: "PH-DM-TYPE-POSITION-INVALID",
|
|
3240
|
+
repair: "Reference input types only from input fields and arguments, and output types only from output fields."
|
|
3241
|
+
},
|
|
3242
|
+
{
|
|
3243
|
+
pattern: / within itself through a series of non-null fields: /,
|
|
3244
|
+
code: "PH-DM-INPUT-CYCLE",
|
|
3245
|
+
repair: "Make one input field on the cycle nullable or a list."
|
|
3246
|
+
}
|
|
3247
|
+
];
|
|
3248
|
+
const OTHER_ERROR = {
|
|
3249
|
+
code: "PH-DEF-COMPATIBILITY-INVALID",
|
|
3250
|
+
repair: "Correct the stored schema so graphql-js builds it; codegen and hosts build the same schema."
|
|
3251
|
+
};
|
|
3252
|
+
/** A model's schema has no operations, so graphql-js has no Query root to require. */
|
|
3253
|
+
const NO_QUERY_ROOT = "Query root type must be provided.";
|
|
3254
|
+
/**
|
|
3255
|
+
* The SDL rules graphql-js applies, minus the directive rules: a stored
|
|
3256
|
+
* schema carries directive uses such as `@equals` without declaring them,
|
|
3257
|
+
* and codegen and hosts read them as annotations.
|
|
3258
|
+
*/
|
|
3259
|
+
function sdlRules(graphql) {
|
|
3260
|
+
return [
|
|
3261
|
+
graphql.LoneSchemaDefinitionRule,
|
|
3262
|
+
graphql.UniqueOperationTypesRule,
|
|
3263
|
+
graphql.UniqueTypeNamesRule,
|
|
3264
|
+
graphql.UniqueEnumValueNamesRule,
|
|
3265
|
+
graphql.UniqueFieldDefinitionNamesRule,
|
|
3266
|
+
graphql.UniqueArgumentDefinitionNamesRule,
|
|
3267
|
+
graphql.UniqueDirectiveNamesRule,
|
|
3268
|
+
graphql.KnownTypeNamesRule,
|
|
3269
|
+
graphql.PossibleTypeExtensionsRule,
|
|
3270
|
+
graphql.UniqueArgumentNamesRule,
|
|
3271
|
+
graphql.UniqueInputFieldNamesRule
|
|
3272
|
+
];
|
|
3273
|
+
}
|
|
3274
|
+
const NAMED_DEFINITION = /^(?:Scalar|Object|Interface|InputObject|Enum|Union)TypeDefinition$/;
|
|
3275
|
+
/**
|
|
3276
|
+
* Hosts keep the first definition of a repeated type name and codegen merges
|
|
3277
|
+
* the repeats, so a repeat is not an error here. Catalog and project scalars
|
|
3278
|
+
* the document uses without declaring become stub declarations, and a type
|
|
3279
|
+
* the document only extends gets an empty base to extend.
|
|
3280
|
+
*/
|
|
3281
|
+
function validationDocument(nodes, specification) {
|
|
3282
|
+
const defined = /* @__PURE__ */ new Set();
|
|
3283
|
+
const definitions = nodes.filter((node) => {
|
|
3284
|
+
if (!NAMED_DEFINITION.test(node.kind) || node.name === void 0) return true;
|
|
3285
|
+
if (defined.has(node.name.value)) return false;
|
|
3286
|
+
defined.add(node.name.value);
|
|
3287
|
+
return true;
|
|
3288
|
+
});
|
|
3289
|
+
const define = (kind, value) => {
|
|
3290
|
+
if (defined.has(value)) return;
|
|
3291
|
+
defined.add(value);
|
|
3292
|
+
definitions.push({
|
|
3293
|
+
kind,
|
|
3294
|
+
name: {
|
|
3295
|
+
kind: "Name",
|
|
3296
|
+
value
|
|
3297
|
+
},
|
|
3298
|
+
directives: [],
|
|
3299
|
+
interfaces: [],
|
|
3300
|
+
fields: [],
|
|
3301
|
+
values: [],
|
|
3302
|
+
types: []
|
|
3303
|
+
});
|
|
3304
|
+
};
|
|
3305
|
+
for (const name of [...scalarCatalog.map((scalar) => scalar.name), ...specification.scalars.map((scalar) => scalar.name)]) define("ScalarTypeDefinition", name);
|
|
3306
|
+
for (const node of nodes) if (node.kind.endsWith("TypeExtension") && node.name !== void 0) define(node.kind.replace(/Extension$/, "Definition"), node.name.value);
|
|
3307
|
+
return {
|
|
3308
|
+
kind: "Document",
|
|
3309
|
+
definitions
|
|
3310
|
+
};
|
|
3311
|
+
}
|
|
3312
|
+
/**
|
|
3313
|
+
* Maps every object inside each top-level node to that node's owner. A
|
|
3314
|
+
* type's first definition points at its structured type; any other node
|
|
3315
|
+
* points at its place in the retained document.
|
|
3316
|
+
*/
|
|
3317
|
+
function ownersByNode(nodes, specification, index) {
|
|
3318
|
+
const typeIndex = new Map(specification.types.map((type, position) => [type.name, position]));
|
|
3319
|
+
const firstDefinitions = /* @__PURE__ */ new Set();
|
|
3320
|
+
const owners = /* @__PURE__ */ new Map();
|
|
3321
|
+
nodes.forEach((node, nodeIndex) => {
|
|
3322
|
+
const name = node.name?.value;
|
|
3323
|
+
const position = name === void 0 ? void 0 : typeIndex.get(name);
|
|
3324
|
+
const first = name !== void 0 && NAMED_DEFINITION.test(node.kind) && !firstDefinitions.has(name);
|
|
3325
|
+
if (first) firstDefinitions.add(name);
|
|
3326
|
+
const owner = {
|
|
3327
|
+
name,
|
|
3328
|
+
implements: (node.interfaces ?? []).map((entry) => entry.name.value),
|
|
3329
|
+
path: first && position !== void 0 ? [
|
|
3330
|
+
"specifications",
|
|
3331
|
+
index,
|
|
3332
|
+
"types",
|
|
3333
|
+
position
|
|
3334
|
+
] : [
|
|
3335
|
+
"specifications",
|
|
3336
|
+
index,
|
|
3337
|
+
"graphQLCompatibility",
|
|
3338
|
+
"document",
|
|
3339
|
+
"definitions",
|
|
3340
|
+
nodeIndex
|
|
3341
|
+
]
|
|
3342
|
+
};
|
|
3343
|
+
const visit = (value) => {
|
|
3344
|
+
if (value === null || typeof value !== "object") return;
|
|
3345
|
+
owners.set(value, owner);
|
|
3346
|
+
for (const child of Object.values(value)) visit(child);
|
|
3347
|
+
};
|
|
3348
|
+
visit(node);
|
|
3349
|
+
});
|
|
3350
|
+
return owners;
|
|
3351
|
+
}
|
|
3352
|
+
/**
|
|
3353
|
+
* The owner of an error's last node, except that an interface error belongs
|
|
3354
|
+
* to the type that implements another owner of the error, which graphql-js
|
|
3355
|
+
* may list before or after the interface's own nodes.
|
|
3356
|
+
*/
|
|
3357
|
+
function ownerOf(error, owners) {
|
|
3358
|
+
const candidates = (error.nodes ?? []).flatMap((node) => owners.get(node) ?? []);
|
|
3359
|
+
const names = new Set(candidates.map(({ name }) => name));
|
|
3360
|
+
return candidates.findLast((owner) => owner.implements.some((name) => names.has(name))) ?? candidates.at(-1);
|
|
3361
|
+
}
|
|
3362
|
+
function checkArtifact$1(artifact) {
|
|
3363
|
+
const served = servedSpecification(artifact);
|
|
3364
|
+
const retained = served?.specification.graphQLCompatibility;
|
|
3365
|
+
if (served === void 0 || retained === void 0 || retained === null) return [];
|
|
3366
|
+
const { specification, index } = served;
|
|
3367
|
+
const graphql = loadGraphQL();
|
|
3368
|
+
const nodes = retained.document.definitions;
|
|
3369
|
+
const document = validationDocument(nodes, specification);
|
|
3370
|
+
let errors = graphql.validateSDL(document, void 0, sdlRules(graphql));
|
|
3371
|
+
if (errors.length === 0) errors = graphql.validateSchema(graphql.buildASTSchema(document, { assumeValidSDL: true })).filter(({ message }) => message !== NO_QUERY_ROOT);
|
|
3372
|
+
const owners = ownersByNode(nodes, specification, index);
|
|
3373
|
+
return errors.map((error) => {
|
|
3374
|
+
const { code, repair } = ERROR_CODES.find(({ pattern }) => pattern.test(error.message)) ?? OTHER_ERROR;
|
|
3375
|
+
return checkDiagnostics.create({
|
|
3376
|
+
code,
|
|
3377
|
+
source: artifact.source,
|
|
3378
|
+
definition: documentModelRef(artifact),
|
|
3379
|
+
path: ownerOf(error, owners)?.path ?? [
|
|
3380
|
+
"specifications",
|
|
3381
|
+
index,
|
|
3382
|
+
"graphQLCompatibility"
|
|
3383
|
+
],
|
|
3384
|
+
message: error.message,
|
|
3385
|
+
repair
|
|
3386
|
+
});
|
|
3387
|
+
});
|
|
3388
|
+
}
|
|
3389
|
+
/**
|
|
3390
|
+
* The compiler validates every type it declares. A retained GraphQL document
|
|
3391
|
+
* is the schema codegen and hosts build, so graphql-js validates it as they
|
|
3392
|
+
* would.
|
|
3393
|
+
*/
|
|
3394
|
+
const graphqlSchemaCheck = {
|
|
3395
|
+
name: "graphql-schema",
|
|
3396
|
+
run: ({ artifacts }) => artifacts.flatMap(checkArtifact$1)
|
|
3397
|
+
};
|
|
3398
|
+
//#endregion
|
|
3399
|
+
//#region src/definition/tooling/report/logical-collisions.ts
|
|
3400
|
+
/**
|
|
3401
|
+
* A host registers one module per `documentType@version`. The loader already
|
|
3402
|
+
* reports two selected sources that claim one, so a claimant is reported here
|
|
3403
|
+
* only when it or the anchor comes from outside the selection.
|
|
3404
|
+
*/
|
|
3405
|
+
function logicalCollisionDiagnostics(sourceSet, [anchor, ...claimants]) {
|
|
3406
|
+
const selected = new Set(sourceSet.sources.map(({ specifier }) => specifier));
|
|
3407
|
+
const isSelected = (artifact) => selected.has(artifact.source.specifier);
|
|
3408
|
+
const key = `${anchor.documentType}@${anchor.version}`;
|
|
3409
|
+
return claimants.filter((claimant) => !(isSelected(claimant) && isSelected(anchor))).map((claimant) => toolingDiagnostics.create({
|
|
3410
|
+
code: "PH-PKG-LOGICAL-COLLISION",
|
|
3411
|
+
source: claimant.source,
|
|
3412
|
+
definition: documentModelRef(claimant),
|
|
3413
|
+
path: [],
|
|
3414
|
+
message: `Two sources claim ${key}, and a host registers one module per document type and version.`,
|
|
3415
|
+
expected: `one source for ${key}`,
|
|
3416
|
+
received: `${anchor.source.specifier} and ${claimant.source.specifier}`,
|
|
3417
|
+
repair: "Keep one of the two models, or give one of them another document type.",
|
|
3418
|
+
related: [{
|
|
3419
|
+
source: anchor.source,
|
|
3420
|
+
path: [],
|
|
3421
|
+
message: `This source also claims ${key}.`
|
|
3422
|
+
}]
|
|
3423
|
+
}));
|
|
3424
|
+
}
|
|
3425
|
+
//#endregion
|
|
3426
|
+
//#region src/definition/tooling/check/checks/logical-collisions.ts
|
|
3427
|
+
const logicalCollisionsCheck = {
|
|
3428
|
+
name: "logical-collisions",
|
|
3429
|
+
run: ({ sourceSet, artifacts }) => {
|
|
3430
|
+
const groups = /* @__PURE__ */ new Map();
|
|
3431
|
+
for (const artifact of artifacts) {
|
|
3432
|
+
const key = `${artifact.documentType}@${artifact.version}`;
|
|
3433
|
+
groups.set(key, [...groups.get(key) ?? [], artifact]);
|
|
3434
|
+
}
|
|
3435
|
+
return [...groups.values()].flatMap((group) => logicalCollisionDiagnostics(sourceSet, group));
|
|
3436
|
+
}
|
|
3437
|
+
};
|
|
3438
|
+
//#endregion
|
|
3439
|
+
//#region src/definition/tooling/check/checks/package-scalar-names.ts
|
|
3440
|
+
/**
|
|
3441
|
+
* A host serves every model of a package and declares each scalar once, so
|
|
3442
|
+
* two package scalars that share a name but not a definition collide there.
|
|
3443
|
+
* The compiler sees one model at a time and cannot catch this.
|
|
3444
|
+
*/
|
|
3445
|
+
const packageScalarNamesCheck = {
|
|
3446
|
+
name: "package-scalar-names",
|
|
3447
|
+
run: ({ artifacts }) => {
|
|
3448
|
+
const first = /* @__PURE__ */ new Map();
|
|
3449
|
+
const diagnostics = [];
|
|
3450
|
+
for (const artifact of artifacts) {
|
|
3451
|
+
const served = servedSpecification(artifact);
|
|
3452
|
+
if (served === void 0) continue;
|
|
3453
|
+
served.specification.scalars.forEach((scalar, scalarIndex) => {
|
|
3454
|
+
if (!("definition" in scalar)) return;
|
|
3455
|
+
const use = {
|
|
3456
|
+
digest: canonicalDigest(scalar.definition),
|
|
3457
|
+
source: artifact.source,
|
|
3458
|
+
path: [
|
|
3459
|
+
"specifications",
|
|
3460
|
+
served.index,
|
|
3461
|
+
"scalars",
|
|
3462
|
+
scalarIndex
|
|
3463
|
+
]
|
|
3464
|
+
};
|
|
3465
|
+
const known = first.get(scalar.name);
|
|
3466
|
+
if (known === void 0) {
|
|
3467
|
+
first.set(scalar.name, use);
|
|
3468
|
+
return;
|
|
3469
|
+
}
|
|
3470
|
+
if (known.digest === use.digest) return;
|
|
3471
|
+
diagnostics.push(checkDiagnostics.create({
|
|
3472
|
+
code: "PH-PKG-SCALAR-CONFLICT",
|
|
3473
|
+
source: use.source,
|
|
3474
|
+
definition: {
|
|
3475
|
+
kind: "scalar",
|
|
3476
|
+
key: scalar.name
|
|
3477
|
+
},
|
|
3478
|
+
path: use.path,
|
|
3479
|
+
message: `Two different package scalars are named ${scalar.name}.`,
|
|
3480
|
+
expected: "one definition per package scalar name",
|
|
3481
|
+
received: scalar.name,
|
|
3482
|
+
repair: `Declare ${scalar.name} once with defineScalar in scalars/index.ts and import it everywhere it is used.`,
|
|
3483
|
+
related: [{
|
|
3484
|
+
source: known.source,
|
|
3485
|
+
path: known.path,
|
|
3486
|
+
message: `The other ${scalar.name} is used here.`
|
|
3487
|
+
}]
|
|
3488
|
+
}));
|
|
3489
|
+
});
|
|
3490
|
+
}
|
|
3491
|
+
return diagnostics;
|
|
3492
|
+
}
|
|
3493
|
+
};
|
|
3494
|
+
//#endregion
|
|
3495
|
+
//#region src/definition/compiler/segments.ts
|
|
3496
|
+
function referencedNames(definition) {
|
|
3497
|
+
const names = [];
|
|
3498
|
+
const visit = (reference) => {
|
|
3499
|
+
if (reference.kind === "list") {
|
|
3500
|
+
visit(reference.item);
|
|
3501
|
+
return;
|
|
3502
|
+
}
|
|
3503
|
+
if (reference.kind === "named") names.push(reference.name);
|
|
3504
|
+
};
|
|
3505
|
+
switch (definition.kind) {
|
|
3506
|
+
case "enum": return names;
|
|
3507
|
+
case "union": return definition.members;
|
|
3508
|
+
case "input":
|
|
3509
|
+
definition.fields.forEach((field) => visit(field.type));
|
|
3510
|
+
return names;
|
|
3511
|
+
case "object":
|
|
3512
|
+
case "interface":
|
|
3513
|
+
names.push(...definition.implements ?? []);
|
|
3514
|
+
for (const field of definition.fields) {
|
|
3515
|
+
field.args?.forEach((argument) => visit(argument.type));
|
|
3516
|
+
visit(field.type);
|
|
3517
|
+
}
|
|
3518
|
+
return names;
|
|
3519
|
+
}
|
|
3520
|
+
}
|
|
3521
|
+
function reachableFrom(rootName, index) {
|
|
3522
|
+
const reached = /* @__PURE__ */ new Set();
|
|
3523
|
+
if (rootName === null) return reached;
|
|
3524
|
+
const queue = [rootName];
|
|
3525
|
+
while (queue.length > 0) {
|
|
3526
|
+
const name = queue.pop();
|
|
3527
|
+
if (reached.has(name)) continue;
|
|
3528
|
+
const definition = index.get(name);
|
|
3529
|
+
if (definition === void 0) continue;
|
|
3530
|
+
reached.add(name);
|
|
3531
|
+
queue.push(...referencedNames(definition));
|
|
3532
|
+
}
|
|
3533
|
+
return reached;
|
|
3534
|
+
}
|
|
3535
|
+
function assignStoredSegments(input) {
|
|
3536
|
+
const stateIndex = new Map(input.types.map((definition) => [definition.name, definition]));
|
|
3537
|
+
const globalReach = reachableFrom(input.globalRoot, stateIndex);
|
|
3538
|
+
const localReach = reachableFrom(input.localRoot, stateIndex);
|
|
3539
|
+
const operationIndex = new Map(stateIndex);
|
|
3540
|
+
for (const operation of input.operations) if (operation.input !== null) operationIndex.set(operation.input.name, operation.input);
|
|
3541
|
+
const claimed = /* @__PURE__ */ new Set();
|
|
3542
|
+
const operations = /* @__PURE__ */ new Map();
|
|
3543
|
+
for (const operation of input.operations) {
|
|
3544
|
+
if (operation.input === null) continue;
|
|
3545
|
+
claimed.add(operation.input.name);
|
|
3546
|
+
const reached = reachableFrom(operation.input.name, operationIndex);
|
|
3547
|
+
const supporting = input.types.filter((definition) => definition.kind === "input" && reached.has(definition.name) && !claimed.has(definition.name));
|
|
3548
|
+
for (const definition of supporting) claimed.add(definition.name);
|
|
3549
|
+
operations.set(operation.key, [operation.input, ...supporting]);
|
|
3550
|
+
}
|
|
3551
|
+
const local = input.types.filter((definition) => definition.kind !== "input" && localReach.has(definition.name) && !globalReach.has(definition.name));
|
|
3552
|
+
const localDeclared = new Set(local.map((definition) => definition.name));
|
|
3553
|
+
return {
|
|
3554
|
+
global: input.types.filter((definition) => !localDeclared.has(definition.name) && !claimed.has(definition.name)),
|
|
3555
|
+
local,
|
|
3556
|
+
operations
|
|
3557
|
+
};
|
|
3558
|
+
}
|
|
3559
|
+
//#endregion
|
|
3560
|
+
//#region src/definition/tooling/graphql/ast-to-structured.ts
|
|
3561
|
+
/** graphql-js's reason for a bare `@deprecated`. */
|
|
3562
|
+
const DEFAULT_DEPRECATION_REASON = "No longer supported";
|
|
3563
|
+
const NAMED_TYPE_NODE = /^(?:Object|Interface|InputObject|Enum|Union)Type(?:Definition|Extension)$/;
|
|
3564
|
+
function description(node) {
|
|
3565
|
+
return node === void 0 ? null : node.value;
|
|
3566
|
+
}
|
|
3567
|
+
function constValue(node) {
|
|
3568
|
+
switch (node.kind) {
|
|
3569
|
+
case "IntValue":
|
|
3570
|
+
case "FloatValue": return Number(node.value);
|
|
3571
|
+
case "StringValue":
|
|
3572
|
+
case "EnumValue":
|
|
3573
|
+
case "BooleanValue": return node.value;
|
|
3574
|
+
case "NullValue": return null;
|
|
3575
|
+
case "ListValue": return node.values.map(constValue);
|
|
3576
|
+
case "ObjectValue": return Object.fromEntries(node.fields.map((field) => [field.name.value, constValue(field.value)]));
|
|
3577
|
+
}
|
|
3578
|
+
}
|
|
3579
|
+
function typeReference(node, declared, required = false) {
|
|
3580
|
+
switch (node.kind) {
|
|
3581
|
+
case "NonNullType": return typeReference(node.type, declared, true);
|
|
3582
|
+
case "ListType": return {
|
|
3583
|
+
kind: "list",
|
|
3584
|
+
required,
|
|
3585
|
+
item: typeReference(node.type, declared)
|
|
3586
|
+
};
|
|
3587
|
+
case "NamedType": return {
|
|
3588
|
+
kind: declared.has(node.name.value) ? "named" : "scalar",
|
|
3589
|
+
name: node.name.value,
|
|
3590
|
+
required
|
|
3591
|
+
};
|
|
3592
|
+
}
|
|
3593
|
+
}
|
|
3594
|
+
function directives(nodes) {
|
|
3595
|
+
const index = nodes.findIndex((node) => node.name.value === "deprecated" && node.arguments.every((argument) => argument.name.value === "reason" && argument.value.kind === "StringValue"));
|
|
3596
|
+
const reason = nodes[index]?.arguments[0]?.value;
|
|
3597
|
+
const rest = nodes.filter((_, position) => position !== index);
|
|
3598
|
+
return {
|
|
3599
|
+
deprecated: index === -1 ? null : reason?.value ?? DEFAULT_DEPRECATION_REASON,
|
|
3600
|
+
...rest.length > 0 && { uses: rest.map((node) => ({
|
|
3601
|
+
name: node.name.value,
|
|
3602
|
+
arguments: node.arguments.map((argument) => ({
|
|
3603
|
+
name: argument.name.value,
|
|
3604
|
+
value: constValue(argument.value)
|
|
3605
|
+
}))
|
|
3606
|
+
})) }
|
|
3607
|
+
};
|
|
3608
|
+
}
|
|
3609
|
+
function inputField(node, declared) {
|
|
3610
|
+
const { deprecated, uses } = directives(node.directives);
|
|
3611
|
+
return {
|
|
3612
|
+
key: node.name.value,
|
|
3613
|
+
name: node.name.value,
|
|
3614
|
+
description: description(node.description),
|
|
3615
|
+
deprecated,
|
|
3616
|
+
type: typeReference(node.type, declared),
|
|
3617
|
+
...node.defaultValue !== void 0 && { defaultValue: constValue(node.defaultValue) },
|
|
3618
|
+
...uses !== void 0 && { directives: uses }
|
|
3619
|
+
};
|
|
3620
|
+
}
|
|
3621
|
+
function outputField(node, declared) {
|
|
3622
|
+
const { deprecated, uses } = directives(node.directives);
|
|
3623
|
+
return {
|
|
3624
|
+
key: node.name.value,
|
|
3625
|
+
name: node.name.value,
|
|
3626
|
+
description: description(node.description),
|
|
3627
|
+
deprecated,
|
|
3628
|
+
...node.arguments.length > 0 && { args: node.arguments.map((argument) => inputField(argument, declared)) },
|
|
3629
|
+
type: typeReference(node.type, declared),
|
|
3630
|
+
...uses !== void 0 && { directives: uses }
|
|
3631
|
+
};
|
|
3632
|
+
}
|
|
3633
|
+
function enumValue(node) {
|
|
3634
|
+
const { deprecated, uses } = directives(node.directives);
|
|
3635
|
+
return {
|
|
3636
|
+
name: node.name.value,
|
|
3637
|
+
description: description(node.description),
|
|
3638
|
+
deprecated,
|
|
3639
|
+
...uses !== void 0 && { directives: uses }
|
|
3640
|
+
};
|
|
3641
|
+
}
|
|
3642
|
+
function namedType(node, declared) {
|
|
3643
|
+
switch (node.kind) {
|
|
3644
|
+
case "ObjectTypeDefinition":
|
|
3645
|
+
case "InterfaceTypeDefinition": return {
|
|
3646
|
+
kind: node.kind === "ObjectTypeDefinition" ? "object" : "interface",
|
|
3647
|
+
name: node.name.value,
|
|
3648
|
+
description: description(node.description),
|
|
3649
|
+
...node.interfaces.length > 0 && { implements: node.interfaces.map((entry) => entry.name.value) },
|
|
3650
|
+
fields: node.fields.map((field) => outputField(field, declared))
|
|
3651
|
+
};
|
|
3652
|
+
case "InputObjectTypeDefinition": return {
|
|
3653
|
+
kind: "input",
|
|
3654
|
+
name: node.name.value,
|
|
3655
|
+
description: description(node.description),
|
|
3656
|
+
unknownKeys: "preserve",
|
|
3657
|
+
fields: node.fields.map((field) => inputField(field, declared))
|
|
3658
|
+
};
|
|
3659
|
+
case "EnumTypeDefinition": return {
|
|
3660
|
+
kind: "enum",
|
|
3661
|
+
name: node.name.value,
|
|
3662
|
+
description: description(node.description),
|
|
3663
|
+
values: node.values.map(enumValue)
|
|
3664
|
+
};
|
|
3665
|
+
case "UnionTypeDefinition": return {
|
|
3666
|
+
kind: "union",
|
|
3667
|
+
name: node.name.value,
|
|
3668
|
+
description: description(node.description),
|
|
3669
|
+
members: node.types.map((member) => member.name.value)
|
|
3670
|
+
};
|
|
3671
|
+
}
|
|
3672
|
+
}
|
|
3673
|
+
/** Names of the object, interface, input, enum and union types the nodes define or extend. */
|
|
3674
|
+
function declaredTypeNames(definitions) {
|
|
3675
|
+
const declared = /* @__PURE__ */ new Set();
|
|
3676
|
+
for (const node of definitions) if (NAMED_TYPE_NODE.test(node.kind) && "name" in node) declared.add(node.name.value);
|
|
3677
|
+
return declared;
|
|
3678
|
+
}
|
|
3679
|
+
/**
|
|
3680
|
+
* Every object, interface, input, enum and union type the nodes define or
|
|
3681
|
+
* extend, with each extension folded into its type: defined types in
|
|
3682
|
+
* document order, then types the nodes only extend. A repeated definition or
|
|
3683
|
+
* member keeps its first occurrence; graphql-js validation reports the
|
|
3684
|
+
* repeat. A reference to a name in `declared` is a named type; any other
|
|
3685
|
+
* reference is a scalar.
|
|
3686
|
+
*/
|
|
3687
|
+
function structuredTypes(definitions, declared = declaredTypeNames(definitions)) {
|
|
3688
|
+
return [...foldTypeExtensions(definitions, []).types.values()].map(({ node }) => namedType(node, declared));
|
|
3689
|
+
}
|
|
3690
|
+
function namedTypeName(node) {
|
|
3691
|
+
return node.kind === "NamedType" ? node.name.value : namedTypeName(node.type);
|
|
3692
|
+
}
|
|
3693
|
+
/**
|
|
3694
|
+
* The type name every field and field argument of the nodes refers to,
|
|
3695
|
+
* extensions included, in document order and with repeats.
|
|
3696
|
+
*/
|
|
3697
|
+
function referencedTypeNames(definitions) {
|
|
3698
|
+
const names = [];
|
|
3699
|
+
for (const node of definitions) {
|
|
3700
|
+
if (!("fields" in node)) continue;
|
|
3701
|
+
for (const field of node.fields) {
|
|
3702
|
+
names.push(namedTypeName(field.type));
|
|
3703
|
+
for (const argument of "arguments" in field ? field.arguments : []) names.push(namedTypeName(argument.type));
|
|
3704
|
+
}
|
|
3705
|
+
}
|
|
3706
|
+
return names;
|
|
3707
|
+
}
|
|
3708
|
+
//#endregion
|
|
3709
|
+
//#region src/definition/tooling/check/stored-specification.ts
|
|
3710
|
+
function record(value, path) {
|
|
3711
|
+
const snapshot = snapshotRecord(value, void 0, path);
|
|
3712
|
+
return snapshot.ok ? snapshot : {
|
|
3713
|
+
ok: false,
|
|
3714
|
+
path: snapshot.path,
|
|
3715
|
+
expected: "a plain record",
|
|
3716
|
+
received: rejectionReceived(snapshot)
|
|
3717
|
+
};
|
|
3718
|
+
}
|
|
3719
|
+
function array(value, path) {
|
|
3720
|
+
const snapshot = snapshotArray(value, path);
|
|
3721
|
+
return snapshot.ok ? snapshot : {
|
|
3722
|
+
ok: false,
|
|
3723
|
+
path: snapshot.path,
|
|
3724
|
+
expected: "an array",
|
|
3725
|
+
received: rejectionReceived(snapshot)
|
|
3726
|
+
};
|
|
3727
|
+
}
|
|
3728
|
+
function text(value, path) {
|
|
3729
|
+
return typeof value === "string" ? {
|
|
3730
|
+
ok: true,
|
|
3731
|
+
value
|
|
3732
|
+
} : {
|
|
3733
|
+
ok: false,
|
|
3734
|
+
path,
|
|
3735
|
+
expected: "a string",
|
|
3736
|
+
received: describeReceived(value)
|
|
3737
|
+
};
|
|
3738
|
+
}
|
|
3739
|
+
function readServedStoredSpecification(value, path) {
|
|
3740
|
+
const specification = record(value, path);
|
|
3741
|
+
if (!specification.ok) return specification;
|
|
3742
|
+
const state = record(specification.value.state, [...path, "state"]);
|
|
3743
|
+
if (!state.ok) return state;
|
|
3744
|
+
const initialValues = {};
|
|
3745
|
+
const segments = [];
|
|
3746
|
+
for (const scope of ["global", "local"]) {
|
|
3747
|
+
const at = [
|
|
3748
|
+
...path,
|
|
3749
|
+
"state",
|
|
3750
|
+
scope
|
|
3751
|
+
];
|
|
3752
|
+
const stored = record(state.value[scope], at);
|
|
3753
|
+
if (!stored.ok) return stored;
|
|
3754
|
+
const schema = text(stored.value.schema, [...at, "schema"]);
|
|
3755
|
+
if (!schema.ok) return schema;
|
|
3756
|
+
const initialValue = text(stored.value.initialValue, [...at, "initialValue"]);
|
|
3757
|
+
if (!initialValue.ok) return initialValue;
|
|
3758
|
+
initialValues[scope] = initialValue.value;
|
|
3759
|
+
segments.push({
|
|
3760
|
+
path: [...at, "schema"],
|
|
3761
|
+
schema: schema.value,
|
|
3762
|
+
of: { scope }
|
|
3763
|
+
});
|
|
3764
|
+
}
|
|
3765
|
+
const modules = array(specification.value.modules, [...path, "modules"]);
|
|
3766
|
+
if (!modules.ok) return modules;
|
|
3767
|
+
for (const [moduleIndex, entry] of modules.value.entries()) {
|
|
3768
|
+
const at = [
|
|
3769
|
+
...path,
|
|
3770
|
+
"modules",
|
|
3771
|
+
moduleIndex
|
|
3772
|
+
];
|
|
3773
|
+
const module = record(entry, at);
|
|
3774
|
+
if (!module.ok) return module;
|
|
3775
|
+
const operations = array(module.value.operations, [...at, "operations"]);
|
|
3776
|
+
if (!operations.ok) return operations;
|
|
3777
|
+
for (const [operationIndex, member] of operations.value.entries()) {
|
|
3778
|
+
const operationPath = [
|
|
3779
|
+
...at,
|
|
3780
|
+
"operations",
|
|
3781
|
+
operationIndex
|
|
3782
|
+
];
|
|
3783
|
+
const operation = record(member, operationPath);
|
|
3784
|
+
if (!operation.ok) return operation;
|
|
3785
|
+
if (operation.value.schema === null) continue;
|
|
3786
|
+
const schema = text(operation.value.schema, [...operationPath, "schema"]);
|
|
3787
|
+
if (!schema.ok) return schema;
|
|
3788
|
+
segments.push({
|
|
3789
|
+
path: [...operationPath, "schema"],
|
|
3790
|
+
schema: schema.value,
|
|
3791
|
+
of: {
|
|
3792
|
+
module: moduleIndex,
|
|
3793
|
+
operation: operationIndex
|
|
3794
|
+
}
|
|
3795
|
+
});
|
|
3796
|
+
}
|
|
3797
|
+
}
|
|
3798
|
+
return {
|
|
3799
|
+
ok: true,
|
|
3800
|
+
value: {
|
|
3801
|
+
path,
|
|
3802
|
+
initialValues,
|
|
3803
|
+
segments
|
|
3804
|
+
}
|
|
3805
|
+
};
|
|
3806
|
+
}
|
|
3807
|
+
function storedHistory(artifact) {
|
|
3808
|
+
const documentModel = record(artifact.documentModel, ["documentModel"]);
|
|
3809
|
+
const global = documentModel.ok ? record(documentModel.value.global, ["documentModel", "global"]) : documentModel;
|
|
3810
|
+
if (!global.ok) return global;
|
|
3811
|
+
const path = [
|
|
3812
|
+
"documentModel",
|
|
3813
|
+
"global",
|
|
3814
|
+
"specifications"
|
|
3815
|
+
];
|
|
3816
|
+
const specifications = array(global.value.specifications, path);
|
|
3817
|
+
if (!specifications.ok) return specifications;
|
|
3818
|
+
const versions = [];
|
|
3819
|
+
let served;
|
|
3820
|
+
let servedIndex = -1;
|
|
3821
|
+
for (const [index, entry] of specifications.value.entries()) {
|
|
3822
|
+
const specification = record(entry, [...path, index]);
|
|
3823
|
+
if (!specification.ok) return specification;
|
|
3824
|
+
const { version } = specification.value;
|
|
3825
|
+
if (typeof version !== "number") return {
|
|
3826
|
+
ok: false,
|
|
3827
|
+
path: [
|
|
3828
|
+
...path,
|
|
3829
|
+
index,
|
|
3830
|
+
"version"
|
|
3831
|
+
],
|
|
3832
|
+
expected: "a version number",
|
|
3833
|
+
received: describeReceived(version)
|
|
3834
|
+
};
|
|
3835
|
+
versions.push(version);
|
|
3836
|
+
if (version === artifact.version && servedIndex === -1) {
|
|
3837
|
+
served = entry;
|
|
3838
|
+
servedIndex = index;
|
|
3839
|
+
}
|
|
3840
|
+
}
|
|
3841
|
+
if (servedIndex === -1) return {
|
|
3842
|
+
ok: true,
|
|
3843
|
+
value: {
|
|
3844
|
+
path,
|
|
3845
|
+
versions,
|
|
3846
|
+
served: void 0
|
|
3847
|
+
}
|
|
3848
|
+
};
|
|
3849
|
+
const specification = readServedStoredSpecification(served, [...path, servedIndex]);
|
|
3850
|
+
return specification.ok ? {
|
|
3851
|
+
ok: true,
|
|
3852
|
+
value: {
|
|
3853
|
+
path,
|
|
3854
|
+
versions,
|
|
3855
|
+
served: specification.value
|
|
3856
|
+
}
|
|
3857
|
+
} : specification;
|
|
3858
|
+
}
|
|
3859
|
+
/**
|
|
3860
|
+
* Reads the stored model an artifact serves without trusting its shape: a
|
|
3861
|
+
* module assembled by hand can carry anything there. Every check that reads
|
|
3862
|
+
* stored strings goes through this, so each reports one malformed member the
|
|
3863
|
+
* same way and the report keeps it once.
|
|
3864
|
+
*/
|
|
3865
|
+
function readStoredModel(artifact) {
|
|
3866
|
+
const read = storedHistory(artifact);
|
|
3867
|
+
if (read.ok) return {
|
|
3868
|
+
ok: true,
|
|
3869
|
+
...read.value
|
|
3870
|
+
};
|
|
3871
|
+
return {
|
|
3872
|
+
ok: false,
|
|
3873
|
+
diagnostic: checkDiagnostics.create({
|
|
3874
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
3875
|
+
source: artifact.source,
|
|
3876
|
+
definition: documentModelRef(artifact),
|
|
3877
|
+
path: read.path,
|
|
3878
|
+
message: "The stored document model this source serves is malformed, so hosts and codegen cannot read it.",
|
|
3879
|
+
expected: read.expected,
|
|
3880
|
+
received: read.received,
|
|
3881
|
+
repair: "Export the module materialize returned, or save the model again from the document model editor; the stored model is not edited by hand."
|
|
3882
|
+
})
|
|
3883
|
+
};
|
|
3884
|
+
}
|
|
3885
|
+
//#endregion
|
|
3886
|
+
//#region src/definition/tooling/check/checks/retained-serialization.ts
|
|
3887
|
+
/**
|
|
3888
|
+
* SDL cannot spell an input without fields, a field key apart from its name,
|
|
3889
|
+
* or a member order that means nothing, so those are not compared.
|
|
3890
|
+
*/
|
|
3891
|
+
function comparable(type) {
|
|
3892
|
+
if (type.kind === "enum") return canonicalJson(type);
|
|
3893
|
+
if (type.kind === "union") return canonicalJson({
|
|
3894
|
+
...type,
|
|
3895
|
+
members: [...type.members].sort(compareCodeUnits)
|
|
3896
|
+
});
|
|
3897
|
+
const fields = type.fields.map((field) => {
|
|
3898
|
+
const { key: _key, ...rest } = field;
|
|
3899
|
+
return "args" in field && field.args !== void 0 ? {
|
|
3900
|
+
...rest,
|
|
3901
|
+
args: field.args.map(({ key: _argKey, ...arg }) => arg)
|
|
3902
|
+
} : rest;
|
|
3903
|
+
});
|
|
3904
|
+
const [only] = fields;
|
|
3905
|
+
const emptyMarker = type.kind === "input" && fields.length === 1 && only.name === "_empty" && only.type.kind === "scalar" && only.type.name === "Boolean" && !only.type.required;
|
|
3906
|
+
return canonicalJson({
|
|
3907
|
+
...type,
|
|
3908
|
+
..."implements" in type && type.implements !== void 0 && { implements: [...type.implements].sort(compareCodeUnits) },
|
|
3909
|
+
fields: emptyMarker ? [] : fields
|
|
3910
|
+
});
|
|
3911
|
+
}
|
|
3912
|
+
function differs(stored, declared) {
|
|
3913
|
+
return comparable(stored) !== comparable(declared);
|
|
3914
|
+
}
|
|
3915
|
+
/** The canonical printer owns each segment, so every segment holds exactly its printed types. */
|
|
3916
|
+
function compareCanonical(report, segment, stored) {
|
|
3917
|
+
const expected = segment.printed.map(({ name }) => name);
|
|
3918
|
+
const received = stored.map(({ name }) => name);
|
|
3919
|
+
const missing = expected.find((name) => !received.includes(name));
|
|
3920
|
+
const surplus = received.find((name) => !expected.includes(name));
|
|
3921
|
+
if (missing !== void 0 || surplus !== void 0) {
|
|
3922
|
+
report(segment.path, missing !== void 0 ? `The stored schema segment does not declare ${missing}.` : `The stored schema segment declares ${surplus}, which the definition places elsewhere or not at all.`, expected.join(", "), received.join(", "));
|
|
3923
|
+
return;
|
|
3924
|
+
}
|
|
3925
|
+
for (const declared of segment.printed) {
|
|
3926
|
+
const copy = stored.find(({ name }) => name === declared.name);
|
|
3927
|
+
if (copy === void 0 || !differs(copy, declared)) continue;
|
|
3928
|
+
report([...segment.path, declared.name], `The stored schema segment describes ${declared.name} differently than the definition.`, canonicalJson(declared), canonicalJson(copy));
|
|
3929
|
+
}
|
|
3930
|
+
}
|
|
3931
|
+
/**
|
|
3932
|
+
* A schema-first model keeps its own split, and a segment may extend a type
|
|
3933
|
+
* another declares, so the union of segments is folded and compared.
|
|
3934
|
+
*/
|
|
3935
|
+
function compareExplicit(report, path, segments, declaration) {
|
|
3936
|
+
const types = structuredTypes(segments.flatMap(({ definitions }) => definitions), new Set(declaration.keys()));
|
|
3937
|
+
const segmentOf = (name) => segments.find(({ definitions }) => declaredTypeNames(definitions).has(name))?.segment.path ?? path;
|
|
3938
|
+
const seen = /* @__PURE__ */ new Set();
|
|
3939
|
+
for (const type of types) {
|
|
3940
|
+
seen.add(type.name);
|
|
3941
|
+
const declared = declaration.get(type.name);
|
|
3942
|
+
if (declared === void 0) report(segmentOf(type.name), `The stored schema segment declares ${type.name}, which the definition does not describe.`, [...declaration.keys()].join(", "), type.name);
|
|
3943
|
+
else if (differs(type, declared)) report([...segmentOf(type.name), type.name], `The stored schema segment describes ${type.name} differently than the definition.`, canonicalJson(declared), canonicalJson(type));
|
|
3944
|
+
}
|
|
3945
|
+
for (const name of declaration.keys()) {
|
|
3946
|
+
if (seen.has(name)) continue;
|
|
3947
|
+
report(path, `No stored schema segment declares ${name}.`, name, [...seen].join(", "));
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
3950
|
+
function checkArtifact(artifact) {
|
|
3951
|
+
const served = servedSpecification(artifact);
|
|
3952
|
+
if (served === void 0) return [];
|
|
3953
|
+
const { specification, index } = served;
|
|
3954
|
+
const at = ["specifications", index];
|
|
3955
|
+
const diagnostics = [];
|
|
3956
|
+
const report = (path, message, expected, received) => diagnostics.push(checkDiagnostics.create({
|
|
3957
|
+
code: "PH-DEF-COMPATIBILITY-INVALID",
|
|
3958
|
+
source: artifact.source,
|
|
3959
|
+
definition: documentModelRef(artifact),
|
|
3960
|
+
path,
|
|
3961
|
+
message,
|
|
3962
|
+
expected,
|
|
3963
|
+
received,
|
|
3964
|
+
repair: "Export the module materialize returned, or save the model again from the document model editor; a stored string that describes another structure is a definition error."
|
|
3965
|
+
}));
|
|
3966
|
+
const operations = specification.modules.flatMap((module) => module.operations.map((operation) => ({
|
|
3967
|
+
key: `${module.key}/${operation.key}`,
|
|
3968
|
+
input: operation.input
|
|
3969
|
+
})));
|
|
3970
|
+
const printed = assignStoredSegments({
|
|
3971
|
+
types: specification.types,
|
|
3972
|
+
globalRoot: specification.state.global.root.name,
|
|
3973
|
+
localRoot: specification.state.local.root?.name ?? null,
|
|
3974
|
+
operations
|
|
3975
|
+
});
|
|
3976
|
+
const declaration = new Map([...specification.types, ...operations.flatMap(({ input }) => input === null ? [] : [input])].map((type) => [type.name, type]));
|
|
3977
|
+
const stored = readStoredModel(artifact);
|
|
3978
|
+
if (!stored.ok) diagnostics.push(stored.diagnostic);
|
|
3979
|
+
const storedSpecification = stored.ok ? stored.served : void 0;
|
|
3980
|
+
const canonical = artifact.definition.compatibility.serialization === "canonical-v1";
|
|
3981
|
+
const missing = /* @__PURE__ */ new Map();
|
|
3982
|
+
specification.modules.forEach((module, moduleIndex) => module.operations.forEach((operation, operationIndex) => {
|
|
3983
|
+
if (canonical || operation.input !== null) missing.set(`${moduleIndex}/${operationIndex}`, `${module.key}.${operation.key}`);
|
|
3984
|
+
}));
|
|
3985
|
+
const segments = [];
|
|
3986
|
+
for (const { path, schema, of } of storedSpecification?.segments ?? []) {
|
|
3987
|
+
if ("scope" in of) {
|
|
3988
|
+
segments.push({
|
|
3989
|
+
path,
|
|
3990
|
+
stored: schema,
|
|
3991
|
+
printed: printed[of.scope]
|
|
3992
|
+
});
|
|
3993
|
+
continue;
|
|
3994
|
+
}
|
|
3995
|
+
const module = specification.modules.at(of.module);
|
|
3996
|
+
const operation = module?.operations.at(of.operation);
|
|
3997
|
+
if (module === void 0 || operation === void 0) {
|
|
3998
|
+
report(path, "The stored schema segment belongs to an operation the definition does not declare.", "a segment of a declared operation", schema);
|
|
3999
|
+
continue;
|
|
4000
|
+
}
|
|
4001
|
+
missing.delete(`${of.module}/${of.operation}`);
|
|
4002
|
+
segments.push({
|
|
4003
|
+
path,
|
|
4004
|
+
stored: schema,
|
|
4005
|
+
printed: printed.operations.get(`${module.key}/${operation.key}`) ?? (operation.input === null ? [] : [operation.input])
|
|
4006
|
+
});
|
|
4007
|
+
}
|
|
4008
|
+
if (storedSpecification !== void 0) for (const operation of missing.values()) report(storedSpecification.path, `The stored model has no schema segment for operation ${operation}.`, `a schema segment for ${operation}`, "absent");
|
|
4009
|
+
const parsed = segments.flatMap((segment) => {
|
|
4010
|
+
const result = parseSchema(segment.stored);
|
|
4011
|
+
if (result.ok) return [{
|
|
4012
|
+
segment,
|
|
4013
|
+
definitions: result.document.definitions
|
|
4014
|
+
}];
|
|
4015
|
+
report(segment.path, `The stored schema segment is not GraphQL SDL: ${result.message}`, "GraphQL SDL", segment.stored);
|
|
4016
|
+
return [];
|
|
4017
|
+
});
|
|
4018
|
+
if (canonical) {
|
|
4019
|
+
const declared = new Set(declaration.keys());
|
|
4020
|
+
for (const { segment, definitions } of parsed) compareCanonical(report, segment, structuredTypes(definitions, declared));
|
|
4021
|
+
} else if (storedSpecification !== void 0 && parsed.length === segments.length) compareExplicit(report, storedSpecification.path, parsed, declaration);
|
|
4022
|
+
for (const scope of ["global", "local"]) {
|
|
4023
|
+
const state = specification.state[scope];
|
|
4024
|
+
const text = state.materialized.initialValue;
|
|
4025
|
+
if (text.trim() === "") continue;
|
|
4026
|
+
let value;
|
|
4027
|
+
try {
|
|
4028
|
+
value = JSON.parse(text);
|
|
4029
|
+
} catch {
|
|
4030
|
+
value = void 0;
|
|
4031
|
+
}
|
|
4032
|
+
const received = value === void 0 ? text : canonicalJson(value);
|
|
4033
|
+
if (received === canonicalJson(state.initialValue)) continue;
|
|
4034
|
+
report([
|
|
4035
|
+
...at,
|
|
4036
|
+
"state",
|
|
4037
|
+
scope,
|
|
4038
|
+
"initialValue"
|
|
4039
|
+
], `The stored ${scope} initial value describes a different value than the definition.`, canonicalJson(state.initialValue), received);
|
|
4040
|
+
}
|
|
4041
|
+
return diagnostics;
|
|
4042
|
+
}
|
|
4043
|
+
/**
|
|
4044
|
+
* Hosts and codegen read the stored SDL strings; the definition carries the
|
|
4045
|
+
* structure. Every segment is checked: for a canonical model the strings are
|
|
4046
|
+
* the printer's output, so a mismatch is a forged module or a compiler defect.
|
|
4047
|
+
*/
|
|
4048
|
+
const retainedSerializationCheck = {
|
|
4049
|
+
name: "retained-serialization",
|
|
4050
|
+
run: ({ artifacts }) => artifacts.flatMap(checkArtifact)
|
|
4051
|
+
};
|
|
4052
|
+
//#endregion
|
|
4053
|
+
//#region src/definition/tooling/check/checks/stored-materialization.ts
|
|
4054
|
+
/**
|
|
4055
|
+
* Hosts read the stored model; consumers of the definition read the
|
|
4056
|
+
* structure. A module assembled by hand can make the two disagree.
|
|
4057
|
+
*/
|
|
4058
|
+
const storedMaterializationCheck = {
|
|
4059
|
+
name: "stored-materialization",
|
|
4060
|
+
run: ({ artifacts }) => artifacts.flatMap((artifact) => {
|
|
4061
|
+
const stored = readStoredModel(artifact);
|
|
4062
|
+
if (!stored.ok) return [stored.diagnostic];
|
|
4063
|
+
const storedVersions = canonicalJson(stored.versions);
|
|
4064
|
+
const declaredVersions = canonicalJson(artifact.definition.specifications.map(({ version }) => version));
|
|
4065
|
+
const at = {
|
|
4066
|
+
source: artifact.source,
|
|
4067
|
+
definition: documentModelRef(artifact)
|
|
4068
|
+
};
|
|
4069
|
+
if (storedVersions !== declaredVersions) return [checkDiagnostics.create({
|
|
4070
|
+
...at,
|
|
4071
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
4072
|
+
path: stored.path,
|
|
4073
|
+
message: "The stored specification history and the structured definition cover different versions.",
|
|
4074
|
+
expected: declaredVersions,
|
|
4075
|
+
received: storedVersions,
|
|
4076
|
+
repair: "Export the module materialize returned; do not assemble the stored model or its definition by hand."
|
|
4077
|
+
})];
|
|
4078
|
+
const served = servedSpecification(artifact);
|
|
4079
|
+
if (served === void 0 || stored.served === void 0) return [];
|
|
4080
|
+
const { path, initialValues } = stored.served;
|
|
4081
|
+
return ["global", "local"].flatMap((scope) => {
|
|
4082
|
+
const expected = served.specification.state[scope].materialized.initialValue;
|
|
4083
|
+
const received = initialValues[scope];
|
|
4084
|
+
if (received === expected) return [];
|
|
4085
|
+
return [checkDiagnostics.create({
|
|
4086
|
+
...at,
|
|
4087
|
+
code: "PH-DM-INITIAL-VALUE-INVALID",
|
|
4088
|
+
path: [
|
|
4089
|
+
...path,
|
|
4090
|
+
"state",
|
|
4091
|
+
scope,
|
|
4092
|
+
"initialValue"
|
|
4093
|
+
],
|
|
4094
|
+
message: `The stored ${scope} initial value is not the one the definition materializes.`,
|
|
4095
|
+
expected,
|
|
4096
|
+
received,
|
|
4097
|
+
repair: "Export the module materialize returned; a stored initial value is not an independent setting."
|
|
4098
|
+
})];
|
|
4099
|
+
});
|
|
4100
|
+
})
|
|
4101
|
+
};
|
|
4102
|
+
//#endregion
|
|
4103
|
+
//#region src/definition/tooling/check/checks/unregistered-definitions.ts
|
|
4104
|
+
/** Turns each declaration the project scan found unregistered into one diagnostic. */
|
|
4105
|
+
const unregisteredDefinitionsCheck = {
|
|
4106
|
+
name: "unregistered-definitions",
|
|
4107
|
+
run: ({ unregistered }) => unregistered.map(({ unit, specifier }) => {
|
|
4108
|
+
const entry = `{ "specifier": "${specifier}" }`;
|
|
4109
|
+
return checkDiagnostics.create({
|
|
4110
|
+
code: "PH-PKG-DEFINITION-UNREGISTERED",
|
|
4111
|
+
source: { specifier },
|
|
4112
|
+
path: [],
|
|
4113
|
+
message: `${unit} declares a code-first document model that no definitionSources entry reaches, so the package leaves it out.`,
|
|
4114
|
+
expected: `a definitionSources entry that reaches ${specifier}`,
|
|
4115
|
+
received: "no entry",
|
|
4116
|
+
repair: `Add ${entry} to definitionSources.entries in powerhouse.config.json. If definitionSources is absent or schema-first, set it to { "formatVersion": 1, "mode": "code-first", "entries": [${entry}] }; schema-first models keep generating from their stored files.`
|
|
4117
|
+
});
|
|
4118
|
+
})
|
|
4119
|
+
};
|
|
4120
|
+
//#endregion
|
|
4121
|
+
//#region src/definition/tooling/report/status.ts
|
|
4122
|
+
/** These phases mean the tool could not read the package, not that a model is wrong. */
|
|
4123
|
+
const FAILURE_PHASES = /* @__PURE__ */ new Set(["configuration", "import"]);
|
|
4124
|
+
/** Drops exact repeats and orders the rest independently of input order. */
|
|
4125
|
+
function sortedUniqueDiagnostics(diagnostics) {
|
|
4126
|
+
const unique = /* @__PURE__ */ new Map();
|
|
4127
|
+
for (const diagnostic of diagnostics) unique.set(canonicalJson(diagnostic), diagnostic);
|
|
4128
|
+
return [...unique].sort(([leftKey, left], [rightKey, right]) => compareDefinitionDiagnostics(left, right) || compareCodeUnits(leftKey, rightKey)).map(([, diagnostic]) => diagnostic);
|
|
4129
|
+
}
|
|
4130
|
+
function definitionStatus(input) {
|
|
4131
|
+
const errors = input.diagnostics.filter(({ severity }) => severity === "error");
|
|
4132
|
+
if (errors.some(({ phase }) => FAILURE_PHASES.has(phase))) return "failed";
|
|
4133
|
+
if (errors.length > 0) return "invalid";
|
|
4134
|
+
if (input.skipReason !== void 0 && input.definitions.length === 0 && input.diagnostics.length === 0) return "skipped";
|
|
4135
|
+
return "ok";
|
|
4136
|
+
}
|
|
4137
|
+
function compareArtifacts(left, right) {
|
|
4138
|
+
return compareCodeUnits(left.documentType, right.documentType) || left.version - right.version || compareCodeUnits(left.source.specifier, right.source.specifier) || compareCodeUnits(canonicalJson(left.source.exportPath ?? []), canonicalJson(right.source.exportPath ?? []));
|
|
4139
|
+
}
|
|
4140
|
+
/** The artifact order, extended to every kind of inventory entry. */
|
|
4141
|
+
function compareInventoryEntries(left, right) {
|
|
4142
|
+
return compareCodeUnits(left.key, right.key) || (left.version ?? 0) - (right.version ?? 0) || compareCodeUnits(left.source.specifier, right.source.specifier) || compareCodeUnits(canonicalJson(left.source.exportPath ?? []), canonicalJson(right.source.exportPath ?? [])) || compareCodeUnits(left.kind, right.kind);
|
|
4143
|
+
}
|
|
4144
|
+
/** Builds the stored check report. Profile is `edit`: release checks come later. */
|
|
4145
|
+
function definitionCheckReport(input) {
|
|
4146
|
+
const diagnostics = sortedUniqueDiagnostics(input.diagnostics);
|
|
4147
|
+
const definitions = [...input.artifacts.map((artifact) => ({
|
|
4148
|
+
kind: "document-model",
|
|
4149
|
+
key: artifact.documentType,
|
|
4150
|
+
version: artifact.version,
|
|
4151
|
+
digest: artifact.digest,
|
|
4152
|
+
source: artifact.source
|
|
4153
|
+
})), ...input.definitions].sort(compareInventoryEntries);
|
|
4154
|
+
const status = definitionStatus({
|
|
4155
|
+
...input.skipReason !== void 0 && { skipReason: input.skipReason },
|
|
4156
|
+
definitions,
|
|
4157
|
+
diagnostics
|
|
4158
|
+
});
|
|
4159
|
+
const errors = diagnostics.filter(({ severity }) => severity === "error").length;
|
|
4160
|
+
const common = {
|
|
4161
|
+
kind: "powerhouse.definition-check",
|
|
4162
|
+
formatVersion: 1,
|
|
4163
|
+
profile: "edit",
|
|
4164
|
+
sourceSet: input.sourceSet,
|
|
4165
|
+
definitions,
|
|
4166
|
+
diagnostics,
|
|
4167
|
+
summary: {
|
|
4168
|
+
errors,
|
|
4169
|
+
warnings: diagnostics.length - errors
|
|
4170
|
+
}
|
|
4171
|
+
};
|
|
4172
|
+
if (status === "skipped") return {
|
|
4173
|
+
...common,
|
|
4174
|
+
status,
|
|
4175
|
+
skipReason: input.skipReason
|
|
4176
|
+
};
|
|
4177
|
+
return {
|
|
4178
|
+
...common,
|
|
4179
|
+
status
|
|
4180
|
+
};
|
|
4181
|
+
}
|
|
4182
|
+
//#endregion
|
|
4183
|
+
//#region src/definition/tooling/check/check-project-definitions.ts
|
|
4184
|
+
/**
|
|
4185
|
+
* The checks `ph model check` runs on document models. A later layer adds its
|
|
4186
|
+
* own with `[...documentModelChecks, ...theirs]`.
|
|
4187
|
+
*/
|
|
4188
|
+
const documentModelChecks = Object.freeze([
|
|
4189
|
+
storedMaterializationCheck,
|
|
4190
|
+
duplicateIdentitiesCheck,
|
|
4191
|
+
packageScalarNamesCheck,
|
|
4192
|
+
logicalCollisionsCheck,
|
|
4193
|
+
graphqlSchemaCheck,
|
|
4194
|
+
retainedSerializationCheck,
|
|
4195
|
+
unregisteredDefinitionsCheck
|
|
4196
|
+
]);
|
|
4197
|
+
/** Moves a check's normalized paths to where each source's author edits them. */
|
|
4198
|
+
function relocated(diagnostic, relocations) {
|
|
4199
|
+
const at = (source, path) => (source === void 0 ? void 0 : relocations.get(source.specifier))?.(path) ?? path;
|
|
4200
|
+
return {
|
|
4201
|
+
...diagnostic,
|
|
4202
|
+
path: at(diagnostic.source, diagnostic.path),
|
|
4203
|
+
...diagnostic.related !== void 0 && { related: diagnostic.related.map((location) => ({
|
|
4204
|
+
...location,
|
|
4205
|
+
path: at(location.source, location.path)
|
|
4206
|
+
})) }
|
|
4207
|
+
};
|
|
4208
|
+
}
|
|
4209
|
+
/**
|
|
4210
|
+
* @experimental Runs every check over a loaded project and builds the stored
|
|
4211
|
+
* check report with the project's load diagnostics. `definitions` adds
|
|
4212
|
+
* inventory entries a caller checked itself. Experimental while code-first
|
|
4213
|
+
* projects are introduced.
|
|
4214
|
+
*/
|
|
4215
|
+
async function checkProjectDefinitions(project, options = {}) {
|
|
4216
|
+
const relocations = project.relocations ?? /* @__PURE__ */ new Map();
|
|
4217
|
+
const diagnostics = [...project.diagnostics];
|
|
4218
|
+
for (const check of options.checks ?? documentModelChecks) for (const diagnostic of await check.run(project)) diagnostics.push(relocated(diagnostic, relocations));
|
|
4219
|
+
return definitionCheckReport({
|
|
4220
|
+
sourceSet: project.sourceSet,
|
|
4221
|
+
...project.skipReason !== void 0 && { skipReason: project.skipReason },
|
|
4222
|
+
artifacts: project.artifacts,
|
|
4223
|
+
definitions: options.definitions ?? [],
|
|
4224
|
+
diagnostics
|
|
4225
|
+
});
|
|
4226
|
+
}
|
|
4227
|
+
//#endregion
|
|
4228
|
+
//#region src/definition/tooling/inspect/diagnostic-codes.ts
|
|
4229
|
+
const inspectDiagnostics = defineDiagnosticCatalog({ "PH-INSPECT-SELECTION-UNKNOWN": {
|
|
4230
|
+
severity: "error",
|
|
4231
|
+
phase: "configuration",
|
|
4232
|
+
meaning: "The selected document type and version is not served by any model of the package"
|
|
4233
|
+
} }, toolingDiagnostics);
|
|
4234
|
+
//#endregion
|
|
4235
|
+
//#region src/definition/tooling/inspect/inspect-project-definitions.ts
|
|
4236
|
+
/** Keeps the capped `expected` text from cutting a key in half. */
|
|
4237
|
+
const MAX_LISTED = 20;
|
|
4238
|
+
function inspection(artifact) {
|
|
4239
|
+
const served = servedSpecification(artifact);
|
|
4240
|
+
if (served === void 0) return void 0;
|
|
4241
|
+
const { specification } = served;
|
|
4242
|
+
return {
|
|
4243
|
+
version: artifact.version,
|
|
4244
|
+
source: artifact.source,
|
|
4245
|
+
scopes: {
|
|
4246
|
+
global: specification.state.global.root.name,
|
|
4247
|
+
local: specification.state.local.root?.name ?? null
|
|
4248
|
+
},
|
|
4249
|
+
modules: specification.modules.map((module) => ({
|
|
4250
|
+
key: module.key,
|
|
4251
|
+
name: module.name,
|
|
4252
|
+
operations: module.operations.map((operation) => ({
|
|
4253
|
+
key: operation.key,
|
|
4254
|
+
name: operation.name,
|
|
4255
|
+
actionType: operation.actionType,
|
|
4256
|
+
scope: operation.scope,
|
|
4257
|
+
input: operation.input?.name ?? null,
|
|
4258
|
+
errors: operation.errors.map(({ key, code }) => ({
|
|
4259
|
+
key,
|
|
4260
|
+
code
|
|
4261
|
+
}))
|
|
4262
|
+
}))
|
|
4263
|
+
})),
|
|
4264
|
+
scalars: specification.scalars.map(({ name, implementation }) => ({
|
|
4265
|
+
name,
|
|
4266
|
+
implementation
|
|
4267
|
+
})),
|
|
4268
|
+
types: specification.types.map(({ name }) => name)
|
|
4269
|
+
};
|
|
4270
|
+
}
|
|
4271
|
+
/** Artifacts that carry one definition, and so one digest, form one family. */
|
|
4272
|
+
function families(artifacts) {
|
|
4273
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
4274
|
+
for (const artifact of artifacts) {
|
|
4275
|
+
const version = inspection(artifact);
|
|
4276
|
+
if (version === void 0) continue;
|
|
4277
|
+
const family = grouped.get(artifact.digest);
|
|
4278
|
+
if (family === void 0) grouped.set(artifact.digest, {
|
|
4279
|
+
first: artifact,
|
|
4280
|
+
versions: [version]
|
|
4281
|
+
});
|
|
4282
|
+
else family.versions.push(version);
|
|
4283
|
+
}
|
|
4284
|
+
return [...grouped.values()].map(({ first, versions }) => ({
|
|
4285
|
+
documentType: first.documentType,
|
|
4286
|
+
name: first.definition.model.name,
|
|
4287
|
+
extension: first.definition.model.extension,
|
|
4288
|
+
digest: first.digest,
|
|
4289
|
+
compatibility: first.definition.compatibility,
|
|
4290
|
+
versions
|
|
4291
|
+
}));
|
|
4292
|
+
}
|
|
4293
|
+
function unknownSelection(selection, artifacts) {
|
|
4294
|
+
const available = [...new Set(artifacts.map(({ documentType, version }) => `${documentType}@${version}`))];
|
|
4295
|
+
const listed = available.length <= MAX_LISTED ? available.join(", ") : `${available.slice(0, MAX_LISTED).join(", ")}, and ${available.length - MAX_LISTED} more`;
|
|
4296
|
+
const selected = `${selection.documentType}@${selection.version}`;
|
|
4297
|
+
return inspectDiagnostics.create({
|
|
4298
|
+
code: "PH-INSPECT-SELECTION-UNKNOWN",
|
|
4299
|
+
path: ["selection"],
|
|
4300
|
+
message: `No model of this package serves ${selected}.`,
|
|
4301
|
+
expected: available.length === 0 ? "a package with a model" : listed,
|
|
4302
|
+
received: selected,
|
|
4303
|
+
repair: available.length === 0 ? "Add a document model to the package, or register its code-first source in definitionSources." : `Inspect one of: ${listed}.`
|
|
4304
|
+
});
|
|
4305
|
+
}
|
|
4306
|
+
/**
|
|
4307
|
+
* @experimental Describes the loaded models without running checks. With a
|
|
4308
|
+
* selection it answers for that model only, and adds its full definition
|
|
4309
|
+
* when exactly one model serves it. Experimental while code-first projects
|
|
4310
|
+
* are introduced.
|
|
4311
|
+
*/
|
|
4312
|
+
function inspectProjectDefinitions(project, options = {}) {
|
|
4313
|
+
const artifacts = [...project.artifacts].sort(compareArtifacts);
|
|
4314
|
+
const { selection } = options;
|
|
4315
|
+
const selected = selection === void 0 ? artifacts : artifacts.filter(({ documentType, version }) => documentType === selection.documentType && version === selection.version);
|
|
4316
|
+
const diagnostics = sortedUniqueDiagnostics([...project.diagnostics, ...selection === void 0 ? [] : selected.length === 0 ? [unknownSelection(selection, artifacts)] : logicalCollisionDiagnostics(project.sourceSet, selected)]);
|
|
4317
|
+
return {
|
|
4318
|
+
kind: "powerhouse.definition-inspection",
|
|
4319
|
+
formatVersion: 1,
|
|
4320
|
+
status: definitionStatus({
|
|
4321
|
+
...project.skipReason !== void 0 && { skipReason: project.skipReason },
|
|
4322
|
+
definitions: artifacts,
|
|
4323
|
+
diagnostics
|
|
4324
|
+
}),
|
|
4325
|
+
sourceSet: project.sourceSet,
|
|
4326
|
+
families: families(selected),
|
|
4327
|
+
diagnostics,
|
|
4328
|
+
...selection !== void 0 && selected.length === 1 && { definition: selected[0].definition }
|
|
4329
|
+
};
|
|
4330
|
+
}
|
|
4331
|
+
//#endregion
|
|
4332
|
+
//#region src/definition/tooling/schema-first/project-scalars.ts
|
|
4333
|
+
/** Where codegen reads a package's `defineScalar` exports from. */
|
|
4334
|
+
const PROJECT_SCALARS_SPECIFIER = "./scalars/index.ts";
|
|
4335
|
+
/** The scalars `scalars/index.ts` exports, imported like the selected sources. */
|
|
4336
|
+
async function loadProjectScalars(request) {
|
|
4337
|
+
const { loader, packageRoot, configFile, packageRevision, signal } = request;
|
|
4338
|
+
if (!existsSync(join(packageRoot, "scalars", "index.ts"))) return {
|
|
4339
|
+
definitions: [],
|
|
4340
|
+
diagnostics: []
|
|
4341
|
+
};
|
|
4342
|
+
const imported = await loader.importPackageModule({
|
|
4343
|
+
configFile,
|
|
4344
|
+
packageRevision,
|
|
4345
|
+
...signal !== void 0 && { signal },
|
|
4346
|
+
specifier: PROJECT_SCALARS_SPECIFIER
|
|
4347
|
+
});
|
|
4348
|
+
if (!imported.ok) return {
|
|
4349
|
+
definitions: [],
|
|
4350
|
+
diagnostics: imported.diagnostics
|
|
4351
|
+
};
|
|
4352
|
+
return {
|
|
4353
|
+
definitions: Object.entries(imported.namespace).flatMap(([exportName, value]) => isScalarDefinition(value) && value.name === exportName ? [value] : []).sort((left, right) => compareCodeUnits(left.name, right.name)),
|
|
4354
|
+
diagnostics: []
|
|
4355
|
+
};
|
|
4356
|
+
}
|
|
4357
|
+
//#endregion
|
|
4358
|
+
//#region src/definition/compiler/stored-scalar.ts
|
|
4359
|
+
function storedScalarDefinition(definition) {
|
|
4360
|
+
return {
|
|
4361
|
+
kind: "powerhouse.scalar",
|
|
4362
|
+
formatVersion: 1,
|
|
4363
|
+
name: definition.name,
|
|
4364
|
+
representation: definition.representation ?? "json",
|
|
4365
|
+
description: definition.description ?? "",
|
|
4366
|
+
coercion: { source: definition.coercion === void 0 ? "derived" : "explicit" },
|
|
4367
|
+
coercionProfile: "catalog-v1"
|
|
4368
|
+
};
|
|
4369
|
+
}
|
|
4370
|
+
function scalarReferences(catalogScalars, packageScalars) {
|
|
4371
|
+
const catalog = documentModelScalars.map(({ name }) => name).filter((name) => catalogScalars.has(name)).map((name) => ({
|
|
4372
|
+
name,
|
|
4373
|
+
implementation: `powerhouse.catalog#${name}`,
|
|
4374
|
+
coercionProfile: "catalog-v1"
|
|
4375
|
+
}));
|
|
4376
|
+
const declared = [...packageScalars].sort(([left], [right]) => compareCodeUnits(left, right)).map(([name, definition]) => ({
|
|
4377
|
+
name,
|
|
4378
|
+
implementation: `package#${name}`,
|
|
4379
|
+
coercionProfile: "catalog-v1",
|
|
4380
|
+
definition: storedScalarDefinition(definition)
|
|
4381
|
+
}));
|
|
4382
|
+
return [...catalog, ...declared];
|
|
4383
|
+
}
|
|
4384
|
+
//#endregion
|
|
4385
|
+
//#region src/definition/tooling/schema-first/schema-first-document-model-module-adapter.ts
|
|
4386
|
+
const EXAMPLE_KEY_PREFIX = "schema-first-id:";
|
|
4387
|
+
function producesRuntimeSymbol(name) {
|
|
4388
|
+
if (typeof name !== "string" || name.trim() === "") return false;
|
|
4389
|
+
const { typeName, memberName, constantName } = deriveDocumentModelSymbolNames(name);
|
|
4390
|
+
return typeName !== "" && memberName !== "" && constantName !== "";
|
|
4391
|
+
}
|
|
4392
|
+
function blocked(collector, kind, value, path) {
|
|
4393
|
+
const received = typeof value === "string" ? JSON.stringify(value) : String(value);
|
|
4394
|
+
collector.add({
|
|
4395
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
4396
|
+
path,
|
|
4397
|
+
message: `The stored ${kind} name ${received} never produced a runtime symbol, so there is no generated ${kind} to describe.`,
|
|
4398
|
+
expected: "a name with at least one letter or digit",
|
|
4399
|
+
received,
|
|
4400
|
+
repair: `Name the ${kind} in the document model editor and generate again.`
|
|
4401
|
+
});
|
|
4402
|
+
}
|
|
4403
|
+
function examples(stored) {
|
|
4404
|
+
return stored.map(({ id, value }) => ({
|
|
4405
|
+
id,
|
|
4406
|
+
key: `${EXAMPLE_KEY_PREFIX}${id}`,
|
|
4407
|
+
value
|
|
4408
|
+
}));
|
|
4409
|
+
}
|
|
4410
|
+
function parseInitialValue(collector, stored, path, emptyIsObject) {
|
|
4411
|
+
if (emptyIsObject && stored.trim() === "") return {};
|
|
4412
|
+
let parsed;
|
|
4413
|
+
try {
|
|
4414
|
+
parsed = JSON.parse(stored);
|
|
4415
|
+
} catch {
|
|
4416
|
+
parsed = void 0;
|
|
4417
|
+
}
|
|
4418
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) return parsed;
|
|
4419
|
+
collector.add({
|
|
4420
|
+
code: "PH-DM-INITIAL-VALUE-INVALID",
|
|
4421
|
+
path,
|
|
4422
|
+
message: "The stored initial value does not parse to a JSON object, so it cannot be the value its state root holds.",
|
|
4423
|
+
expected: "a JSON object, encoded once",
|
|
4424
|
+
received: stored,
|
|
4425
|
+
repair: "Store the scope's initial value as a JSON object."
|
|
4426
|
+
});
|
|
4427
|
+
}
|
|
4428
|
+
function emptyInputProjection(input) {
|
|
4429
|
+
const [only] = input.fields;
|
|
4430
|
+
return input.fields.length === 1 && only.name === "_empty" && only.type.kind === "scalar" && only.type.name === "Boolean" && !only.type.required ? {
|
|
4431
|
+
...input,
|
|
4432
|
+
fields: []
|
|
4433
|
+
} : input;
|
|
4434
|
+
}
|
|
4435
|
+
function modelScalarReferences(definitions, scalars) {
|
|
4436
|
+
const used = new Set(referencedTypeNames(definitions));
|
|
4437
|
+
return scalarReferences(used, new Map(scalars.filter(({ name }) => used.has(name)).map((definition) => [definition.name, definition])));
|
|
4438
|
+
}
|
|
4439
|
+
function normalizeOperation(collector, operation, typesByName, path) {
|
|
4440
|
+
if (!producesRuntimeSymbol(operation.name)) return blocked(collector, "operation", operation.name, [...path, "name"]);
|
|
4441
|
+
if (operation.scope !== "global" && operation.scope !== "local") {
|
|
4442
|
+
collector.add({
|
|
4443
|
+
code: "PH-DM-SCOPE-UNSUPPORTED",
|
|
4444
|
+
path: [...path, "scope"],
|
|
4445
|
+
message: `Operation ${JSON.stringify(operation.name)} is stored in scope ${JSON.stringify(operation.scope)}, which a V1 definition cannot record.`,
|
|
4446
|
+
expected: "global | local",
|
|
4447
|
+
received: String(operation.scope),
|
|
4448
|
+
repair: "Store the operation in the global or local scope."
|
|
4449
|
+
});
|
|
4450
|
+
return;
|
|
4451
|
+
}
|
|
4452
|
+
const names = deriveDocumentModelSymbolNames(operation.name);
|
|
4453
|
+
const inputName = `${names.typeName}Input`;
|
|
4454
|
+
const hasSchema = operation.schema !== null && operation.schema.trim() !== "";
|
|
4455
|
+
const declared = hasSchema ? typesByName.get(inputName) : void 0;
|
|
4456
|
+
if (hasSchema && declared?.kind !== "input") {
|
|
4457
|
+
collector.add({
|
|
4458
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
4459
|
+
path: [...path, "schema"],
|
|
4460
|
+
message: `The stored schema of operation ${JSON.stringify(operation.name)} declares no input type ${inputName}, which codegen and the host read its input from.`,
|
|
4461
|
+
expected: `input ${inputName} { ... }`,
|
|
4462
|
+
received: declared === void 0 ? "absent" : declared.kind,
|
|
4463
|
+
repair: `Declare input ${inputName} in the operation's schema.`
|
|
4464
|
+
});
|
|
4465
|
+
return;
|
|
4466
|
+
}
|
|
4467
|
+
const errors = operation.errors.map((error, index) => producesRuntimeSymbol(error.name) ? {
|
|
4468
|
+
id: error.id,
|
|
4469
|
+
key: deriveDocumentModelSymbolNames(error.name).typeName,
|
|
4470
|
+
code: error.code,
|
|
4471
|
+
name: error.name,
|
|
4472
|
+
description: error.description,
|
|
4473
|
+
template: error.template
|
|
4474
|
+
} : blocked(collector, "error", error.name, [
|
|
4475
|
+
...path,
|
|
4476
|
+
"errors",
|
|
4477
|
+
index,
|
|
4478
|
+
"name"
|
|
4479
|
+
]));
|
|
4480
|
+
if (errors.includes(void 0)) return void 0;
|
|
4481
|
+
return {
|
|
4482
|
+
id: operation.id,
|
|
4483
|
+
key: names.memberName,
|
|
4484
|
+
name: operation.name,
|
|
4485
|
+
description: operation.description,
|
|
4486
|
+
actionType: names.constantName,
|
|
4487
|
+
creatorKey: names.memberName,
|
|
4488
|
+
scope: operation.scope,
|
|
4489
|
+
input: declared?.kind === "input" ? emptyInputProjection(declared) : null,
|
|
4490
|
+
errors,
|
|
4491
|
+
examples: examples(operation.examples),
|
|
4492
|
+
template: operation.template,
|
|
4493
|
+
reducer: operation.reducer
|
|
4494
|
+
};
|
|
4495
|
+
}
|
|
4496
|
+
function rootState(collector, stored, root, path, scope) {
|
|
4497
|
+
const initialValue = parseInitialValue(collector, stored.initialValue, [...path, "initialValue"], scope === "local");
|
|
4498
|
+
if (initialValue === void 0) return void 0;
|
|
4499
|
+
const materialized = {
|
|
4500
|
+
initialValue: stored.initialValue,
|
|
4501
|
+
examples: stored.examples.map(({ id, value }) => ({
|
|
4502
|
+
id,
|
|
4503
|
+
value
|
|
4504
|
+
}))
|
|
4505
|
+
};
|
|
4506
|
+
return root === null ? {
|
|
4507
|
+
root: null,
|
|
4508
|
+
initialValue: {},
|
|
4509
|
+
examples: examples(stored.examples),
|
|
4510
|
+
unknownKeys: "preserve",
|
|
4511
|
+
materialized: {
|
|
4512
|
+
...materialized,
|
|
4513
|
+
schema: ""
|
|
4514
|
+
}
|
|
4515
|
+
} : {
|
|
4516
|
+
root: {
|
|
4517
|
+
kind: "named",
|
|
4518
|
+
name: root,
|
|
4519
|
+
required: true
|
|
4520
|
+
},
|
|
4521
|
+
initialValue,
|
|
4522
|
+
examples: examples(stored.examples),
|
|
4523
|
+
unknownKeys: "preserve",
|
|
4524
|
+
materialized: {
|
|
4525
|
+
...materialized,
|
|
4526
|
+
schema: stored.schema
|
|
4527
|
+
}
|
|
4528
|
+
};
|
|
4529
|
+
}
|
|
4530
|
+
const BUILT_IN_SCALARS = /* @__PURE__ */ new Set([
|
|
4531
|
+
"ID",
|
|
4532
|
+
"String",
|
|
4533
|
+
"Boolean",
|
|
4534
|
+
"Int",
|
|
4535
|
+
"Float"
|
|
4536
|
+
]);
|
|
4537
|
+
const CATALOG_SCALARS = new Set(scalarCatalog.map(({ name }) => name));
|
|
4538
|
+
/**
|
|
4539
|
+
* Codegen imports every scalar a stored schema declares or uses from
|
|
4540
|
+
* scalars/index.ts unless it is built in or in the catalog. A missing export
|
|
4541
|
+
* would otherwise surface later as an error that never names it.
|
|
4542
|
+
*/
|
|
4543
|
+
function knownScalars(collector, segments, declared, scalars) {
|
|
4544
|
+
const project = new Set(scalars.map(({ name }) => name));
|
|
4545
|
+
const reported = /* @__PURE__ */ new Set();
|
|
4546
|
+
for (const segment of segments) {
|
|
4547
|
+
const names = [...referencedTypeNames(segment.definitions).filter((name) => !declared.has(name)).map((name) => ({
|
|
4548
|
+
name,
|
|
4549
|
+
verb: "uses"
|
|
4550
|
+
})), ...segment.definitions.flatMap((node) => node.kind === "ScalarTypeDefinition" ? [{
|
|
4551
|
+
name: node.name.value,
|
|
4552
|
+
verb: "declares"
|
|
4553
|
+
}] : [])];
|
|
4554
|
+
for (const { name, verb } of names) {
|
|
4555
|
+
if (BUILT_IN_SCALARS.has(name) || CATALOG_SCALARS.has(name) || project.has(name) || reported.has(name)) continue;
|
|
4556
|
+
reported.add(name);
|
|
4557
|
+
collector.add({
|
|
4558
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
4559
|
+
path: segment.path,
|
|
4560
|
+
message: `The stored schema ${verb} scalar ${name}, which is not a GraphQL built-in, a catalog scalar, or a project scalar exported from scalars/index.ts.`,
|
|
4561
|
+
expected: "a scalar defined with defineScalar in scalars/index.ts",
|
|
4562
|
+
received: name,
|
|
4563
|
+
repair: `Export ${name} from scalars/index.ts with defineScalar, or use a catalog scalar.`
|
|
4564
|
+
});
|
|
4565
|
+
}
|
|
4566
|
+
}
|
|
4567
|
+
return reported.size === 0;
|
|
4568
|
+
}
|
|
4569
|
+
/** A specification's stored SDL strings, in the order its retained document concatenates them. */
|
|
4570
|
+
function storedSchemaSegments(specification, path) {
|
|
4571
|
+
return [
|
|
4572
|
+
{
|
|
4573
|
+
schema: specification.state.global.schema,
|
|
4574
|
+
path: [
|
|
4575
|
+
...path,
|
|
4576
|
+
"state",
|
|
4577
|
+
"global",
|
|
4578
|
+
"schema"
|
|
4579
|
+
]
|
|
4580
|
+
},
|
|
4581
|
+
{
|
|
4582
|
+
schema: specification.state.local.schema,
|
|
4583
|
+
path: [
|
|
4584
|
+
...path,
|
|
4585
|
+
"state",
|
|
4586
|
+
"local",
|
|
4587
|
+
"schema"
|
|
4588
|
+
]
|
|
4589
|
+
},
|
|
4590
|
+
...specification.modules.flatMap((module, moduleIndex) => module.operations.map((operation, operationIndex) => ({
|
|
4591
|
+
schema: operation.schema ?? "",
|
|
4592
|
+
path: [
|
|
4593
|
+
...path,
|
|
4594
|
+
"modules",
|
|
4595
|
+
moduleIndex,
|
|
4596
|
+
"operations",
|
|
4597
|
+
operationIndex,
|
|
4598
|
+
"schema"
|
|
4599
|
+
]
|
|
4600
|
+
})))
|
|
4601
|
+
];
|
|
4602
|
+
}
|
|
4603
|
+
function normalizeSpecification(collector, specification, roots, path, scalars) {
|
|
4604
|
+
const segments = storedSchemaSegments(specification, path);
|
|
4605
|
+
const parsedSegments = [];
|
|
4606
|
+
for (const segment of segments) {
|
|
4607
|
+
const parsed = parseSchema(segment.schema);
|
|
4608
|
+
if (!parsed.ok) {
|
|
4609
|
+
collector.add({
|
|
4610
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
4611
|
+
path: segment.path,
|
|
4612
|
+
message: `The stored schema is not GraphQL SDL: ${parsed.message}`,
|
|
4613
|
+
expected: "GraphQL SDL",
|
|
4614
|
+
received: segment.schema,
|
|
4615
|
+
repair: "Fix the schema in the document model editor."
|
|
4616
|
+
});
|
|
4617
|
+
return;
|
|
4618
|
+
}
|
|
4619
|
+
parsedSegments.push({
|
|
4620
|
+
path: segment.path,
|
|
4621
|
+
definitions: parsed.document.definitions
|
|
4622
|
+
});
|
|
4623
|
+
}
|
|
4624
|
+
const definitions = parsedSegments.flatMap((segment) => segment.definitions);
|
|
4625
|
+
const declared = declaredTypeNames(definitions);
|
|
4626
|
+
if (!knownScalars(collector, parsedSegments, declared, scalars)) return;
|
|
4627
|
+
const allTypes = structuredTypes(definitions, declared);
|
|
4628
|
+
const typesByName = new Map(allTypes.map((type) => [type.name, type]));
|
|
4629
|
+
const hasLocalRoot = specification.state.local.schema.trim() !== "";
|
|
4630
|
+
for (const scope of ["global", "local"]) {
|
|
4631
|
+
if (scope === "local" && !hasLocalRoot) continue;
|
|
4632
|
+
if (typesByName.get(roots[scope])?.kind !== "object") {
|
|
4633
|
+
collector.add({
|
|
4634
|
+
code: "PH-DM-STATE-ROOT-INVALID",
|
|
4635
|
+
path: [
|
|
4636
|
+
...path,
|
|
4637
|
+
"state",
|
|
4638
|
+
scope,
|
|
4639
|
+
"schema"
|
|
4640
|
+
],
|
|
4641
|
+
message: `The stored ${scope} state schema declares no object type named ${roots[scope]}.`,
|
|
4642
|
+
expected: `type ${roots[scope]} { ... }`,
|
|
4643
|
+
received: [...typesByName.keys()].join(", "),
|
|
4644
|
+
repair: `Name the ${scope} state root after the model; every consumer resolves it by that name.`
|
|
4645
|
+
});
|
|
4646
|
+
return;
|
|
4647
|
+
}
|
|
4648
|
+
}
|
|
4649
|
+
const modules = [];
|
|
4650
|
+
for (const [moduleIndex, module] of specification.modules.entries()) {
|
|
4651
|
+
const modulePath = [
|
|
4652
|
+
...path,
|
|
4653
|
+
"modules",
|
|
4654
|
+
moduleIndex
|
|
4655
|
+
];
|
|
4656
|
+
if (!producesRuntimeSymbol(module.name)) return blocked(collector, "module", module.name, [...modulePath, "name"]);
|
|
4657
|
+
const operations = module.operations.map((operation, operationIndex) => normalizeOperation(collector, operation, typesByName, [
|
|
4658
|
+
...modulePath,
|
|
4659
|
+
"operations",
|
|
4660
|
+
operationIndex
|
|
4661
|
+
]));
|
|
4662
|
+
if (operations.includes(void 0)) return void 0;
|
|
4663
|
+
modules.push({
|
|
4664
|
+
id: module.id,
|
|
4665
|
+
key: deriveDocumentModelSymbolNames(module.name).memberName,
|
|
4666
|
+
name: module.name,
|
|
4667
|
+
description: module.description,
|
|
4668
|
+
operations
|
|
4669
|
+
});
|
|
4670
|
+
}
|
|
4671
|
+
const global = rootState(collector, specification.state.global, roots.global, [
|
|
4672
|
+
...path,
|
|
4673
|
+
"state",
|
|
4674
|
+
"global"
|
|
4675
|
+
], "global");
|
|
4676
|
+
const local = rootState(collector, specification.state.local, hasLocalRoot ? roots.local : null, [
|
|
4677
|
+
...path,
|
|
4678
|
+
"state",
|
|
4679
|
+
"local"
|
|
4680
|
+
], "local");
|
|
4681
|
+
if (global === void 0 || global.root === null || local === void 0) return;
|
|
4682
|
+
const inputs = new Set(modules.flatMap((module) => module.operations.flatMap((operation) => operation.input === null ? [] : [operation.input.name])));
|
|
4683
|
+
return {
|
|
4684
|
+
version: specification.version,
|
|
4685
|
+
scalars: modelScalarReferences(definitions, scalars),
|
|
4686
|
+
graphQLCompatibility: {
|
|
4687
|
+
kind: "graphql-ast-v1",
|
|
4688
|
+
document: {
|
|
4689
|
+
kind: "Document",
|
|
4690
|
+
definitions
|
|
4691
|
+
},
|
|
4692
|
+
preserveDefinitionOrder: true
|
|
4693
|
+
},
|
|
4694
|
+
types: allTypes.filter((type) => !inputs.has(type.name)),
|
|
4695
|
+
state: {
|
|
4696
|
+
global,
|
|
4697
|
+
local
|
|
4698
|
+
},
|
|
4699
|
+
modules,
|
|
4700
|
+
changeLog: [...specification.changeLog]
|
|
4701
|
+
};
|
|
4702
|
+
}
|
|
4703
|
+
function storedModel(collector, value, options) {
|
|
4704
|
+
const root = snapshotRecord(value, void 0, []);
|
|
4705
|
+
const module = root.ok && root.value.documentModel !== void 0 ? root.value : void 0;
|
|
4706
|
+
const documentModel = module === void 0 ? value : module.documentModel;
|
|
4707
|
+
const path = module === void 0 ? [] : ["documentModel"];
|
|
4708
|
+
const state = snapshotRecord(documentModel, void 0, path);
|
|
4709
|
+
const global = state.ok ? snapshotDataRecord(state.value.global, void 0, [...path, "global"]) : state;
|
|
4710
|
+
if (!global.ok) {
|
|
4711
|
+
collector.add({
|
|
4712
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
4713
|
+
path: global.path,
|
|
4714
|
+
message: `This export is neither a generated document-model module nor its stored state (${global.reason}).`,
|
|
4715
|
+
expected: "a module with documentModel.global, or a DocumentModelPHState",
|
|
4716
|
+
received: rejectionReceived(global),
|
|
4717
|
+
repair: "Pass the module ph generate produced, or its documentModel."
|
|
4718
|
+
});
|
|
4719
|
+
return;
|
|
4720
|
+
}
|
|
4721
|
+
const parsed = DocumentModelGlobalStateSchema().safeParse(global.value);
|
|
4722
|
+
if (!parsed.success) {
|
|
4723
|
+
for (const issue of parsed.error.issues) collector.add({
|
|
4724
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
4725
|
+
path: [
|
|
4726
|
+
...path,
|
|
4727
|
+
"global",
|
|
4728
|
+
...issue.path.map((segment) => typeof segment === "symbol" ? String(segment) : segment)
|
|
4729
|
+
],
|
|
4730
|
+
message: issue.message,
|
|
4731
|
+
expected: "a stored document model matching DocumentModelGlobalState",
|
|
4732
|
+
received: "a malformed stored model",
|
|
4733
|
+
repair: "Pass the module ph generate produced, or its stored documentModel."
|
|
4734
|
+
});
|
|
4735
|
+
return;
|
|
4736
|
+
}
|
|
4737
|
+
const declared = options.version ?? module?.version ?? 1;
|
|
4738
|
+
if (typeof declared !== "number" || !Number.isSafeInteger(declared) || declared <= 0) {
|
|
4739
|
+
collector.add({
|
|
4740
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
4741
|
+
path: ["version"],
|
|
4742
|
+
message: "A module's registry version is a positive safe integer.",
|
|
4743
|
+
expected: "a positive safe integer",
|
|
4744
|
+
received: typeof declared === "number" ? String(declared) : describeReceived(declared),
|
|
4745
|
+
repair: "Pass the version this module registers."
|
|
4746
|
+
});
|
|
4747
|
+
return;
|
|
4748
|
+
}
|
|
4749
|
+
return {
|
|
4750
|
+
global: parsed.data,
|
|
4751
|
+
documentModel,
|
|
4752
|
+
version: declared
|
|
4753
|
+
};
|
|
4754
|
+
}
|
|
4755
|
+
/**
|
|
4756
|
+
* @experimental Normalizes one generated schema-first module, or one stored
|
|
4757
|
+
* `DocumentModelPHState`, into the V1 wire shape. A model it cannot
|
|
4758
|
+
* normalize is reported in `diagnostics`; the stored members it trusts are
|
|
4759
|
+
* the ones `ph generate` writes. Experimental: it exists so code-first and
|
|
4760
|
+
* schema-first models can be read through one shape while code-first
|
|
4761
|
+
* projects are introduced.
|
|
4762
|
+
*/
|
|
4763
|
+
function adaptSchemaFirstDocumentModelModule(value, source, options = {}) {
|
|
4764
|
+
const probe = new DefinitionDiagnosticCollector(toolingDiagnostics);
|
|
4765
|
+
const stored = storedModel(probe, value, options);
|
|
4766
|
+
if (stored === void 0) return {
|
|
4767
|
+
artifacts: [],
|
|
4768
|
+
upgradeManifest: null,
|
|
4769
|
+
diagnostics: probe.diagnostics
|
|
4770
|
+
};
|
|
4771
|
+
const { global, version } = stored;
|
|
4772
|
+
const collector = new DefinitionDiagnosticCollector(toolingDiagnostics, {
|
|
4773
|
+
kind: "document-model",
|
|
4774
|
+
key: global.id,
|
|
4775
|
+
version
|
|
4776
|
+
});
|
|
4777
|
+
const failed = () => ({
|
|
4778
|
+
artifacts: [],
|
|
4779
|
+
upgradeManifest: null,
|
|
4780
|
+
diagnostics: collector.diagnostics
|
|
4781
|
+
});
|
|
4782
|
+
const names = deriveDocumentModelNames({
|
|
4783
|
+
id: global.id,
|
|
4784
|
+
name: global.name
|
|
4785
|
+
});
|
|
4786
|
+
const specifications = global.specifications.map((specification, index) => normalizeSpecification(collector, specification, {
|
|
4787
|
+
global: names.globalStateRootName,
|
|
4788
|
+
local: names.localStateRootName
|
|
4789
|
+
}, ["specifications", index], options.scalars ?? []));
|
|
4790
|
+
if (specifications.includes(void 0)) return failed();
|
|
4791
|
+
const definition = {
|
|
4792
|
+
kind: "powerhouse.document-model",
|
|
4793
|
+
formatVersion: 1,
|
|
4794
|
+
compatibility: {
|
|
4795
|
+
identity: "explicit-schema-first",
|
|
4796
|
+
scalarCoercion: "catalog-v1",
|
|
4797
|
+
serialization: "explicit-schema-first"
|
|
4798
|
+
},
|
|
4799
|
+
model: {
|
|
4800
|
+
documentType: global.id,
|
|
4801
|
+
graphQLName: names.graphQLName,
|
|
4802
|
+
name: global.name,
|
|
4803
|
+
description: global.description,
|
|
4804
|
+
extension: global.extension,
|
|
4805
|
+
author: {
|
|
4806
|
+
name: global.author.name,
|
|
4807
|
+
website: global.author.website
|
|
4808
|
+
}
|
|
4809
|
+
},
|
|
4810
|
+
specifications
|
|
4811
|
+
};
|
|
4812
|
+
const shape = checkDocumentModelDefinitionShape(definition);
|
|
4813
|
+
collector.merge(shape);
|
|
4814
|
+
if (shape.length > 0) return failed();
|
|
4815
|
+
if (!definition.specifications.some((entry) => entry.version === version)) {
|
|
4816
|
+
collector.add({
|
|
4817
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
4818
|
+
path: ["specifications"],
|
|
4819
|
+
message: `The stored history carries no version ${version}, which is the version this module serves.`,
|
|
4820
|
+
expected: `a specification for version ${version}`,
|
|
4821
|
+
received: definition.specifications.map((entry) => String(entry.version)).join(", "),
|
|
4822
|
+
repair: "Pass the version this module registers, or the module that serves a stored version."
|
|
4823
|
+
});
|
|
4824
|
+
return failed();
|
|
4825
|
+
}
|
|
4826
|
+
return {
|
|
4827
|
+
artifacts: [{
|
|
4828
|
+
kind: "powerhouse.document-model-artifact",
|
|
4829
|
+
source,
|
|
4830
|
+
documentType: global.id,
|
|
4831
|
+
version,
|
|
4832
|
+
definition,
|
|
4833
|
+
digest: canonicalDigest(definition),
|
|
4834
|
+
documentModel: stored.documentModel
|
|
4835
|
+
}],
|
|
4836
|
+
upgradeManifest: null,
|
|
4837
|
+
diagnostics: collector.diagnostics
|
|
4838
|
+
};
|
|
4839
|
+
}
|
|
4840
|
+
//#endregion
|
|
4841
|
+
//#region src/definition/tooling/schema-first/stored-locations.ts
|
|
4842
|
+
function segmentDeclarations(specification, path) {
|
|
4843
|
+
const nodes = [];
|
|
4844
|
+
const defined = /* @__PURE__ */ new Map();
|
|
4845
|
+
const extended = /* @__PURE__ */ new Map();
|
|
4846
|
+
for (const segment of storedSchemaSegments(specification, path)) {
|
|
4847
|
+
const parsed = parseSchema(segment.schema);
|
|
4848
|
+
if (!parsed.ok) continue;
|
|
4849
|
+
for (const node of parsed.document.definitions) {
|
|
4850
|
+
nodes.push(segment.path);
|
|
4851
|
+
const name = "name" in node ? node.name.value : void 0;
|
|
4852
|
+
if (name === void 0) continue;
|
|
4853
|
+
const first = node.kind.endsWith("Extension") ? extended : defined;
|
|
4854
|
+
if (!first.has(name)) first.set(name, segment.path);
|
|
4855
|
+
}
|
|
4856
|
+
}
|
|
4857
|
+
return {
|
|
4858
|
+
nodes,
|
|
4859
|
+
types: new Map([...extended, ...defined])
|
|
4860
|
+
};
|
|
4861
|
+
}
|
|
4862
|
+
/**
|
|
4863
|
+
* A schema-first author edits the stored file, which is the served global
|
|
4864
|
+
* state, and declares types in its SDL segments rather than as structured
|
|
4865
|
+
* types. Served paths lose their `documentModel/global` prefix; a type, a
|
|
4866
|
+
* scalar or a retained document node points at the segment that declares it.
|
|
4867
|
+
* Every result is cut back to the deepest member the stored file has, so no
|
|
4868
|
+
* location names a normalized-only member or reaches inside an SDL string.
|
|
4869
|
+
*/
|
|
4870
|
+
function storedModelRelocation(artifact) {
|
|
4871
|
+
const stored = artifact.documentModel.global.specifications;
|
|
4872
|
+
const declarations = /* @__PURE__ */ new Map();
|
|
4873
|
+
const declared = (index) => {
|
|
4874
|
+
let found = declarations.get(index);
|
|
4875
|
+
if (found === void 0) {
|
|
4876
|
+
found = segmentDeclarations(stored[index], ["specifications", index]);
|
|
4877
|
+
declarations.set(index, found);
|
|
4878
|
+
}
|
|
4879
|
+
return found;
|
|
4880
|
+
};
|
|
4881
|
+
const relocate = (path) => {
|
|
4882
|
+
if (path[0] === "documentModel" && path[1] === "global") return path.slice(2);
|
|
4883
|
+
const [root, index, member, ...rest] = path;
|
|
4884
|
+
if (root !== "specifications" || typeof index !== "number" || stored.at(index) === void 0) return path;
|
|
4885
|
+
const specification = ["specifications", index];
|
|
4886
|
+
if (member === "types") {
|
|
4887
|
+
const name = typeof rest[0] === "number" ? artifact.definition.specifications.at(index)?.types.at(rest[0])?.name : void 0;
|
|
4888
|
+
return (name === void 0 ? void 0 : declared(index).types.get(name)) ?? specification;
|
|
4889
|
+
}
|
|
4890
|
+
if (member === "scalars") {
|
|
4891
|
+
const name = typeof rest[0] === "number" ? artifact.definition.specifications.at(index)?.scalars.at(rest[0])?.name : void 0;
|
|
4892
|
+
return (name === void 0 ? void 0 : declared(index).types.get(name)) ?? specification;
|
|
4893
|
+
}
|
|
4894
|
+
if (member === "graphQLCompatibility") {
|
|
4895
|
+
const [document, definitions, node] = rest;
|
|
4896
|
+
return (document === "document" && definitions === "definitions" && typeof node === "number" ? declared(index).nodes.at(node) : void 0) ?? specification;
|
|
4897
|
+
}
|
|
4898
|
+
return path;
|
|
4899
|
+
};
|
|
4900
|
+
return (path) => storedPrefix(artifact.documentModel.global, relocate(path));
|
|
4901
|
+
}
|
|
4902
|
+
function storedPrefix(stored, path) {
|
|
4903
|
+
let value = stored;
|
|
4904
|
+
let depth = 0;
|
|
4905
|
+
for (const segment of path) {
|
|
4906
|
+
if (typeof value !== "object" || value === null) break;
|
|
4907
|
+
if (!Object.hasOwn(value, segment)) break;
|
|
4908
|
+
value = value[segment];
|
|
4909
|
+
depth += 1;
|
|
4910
|
+
}
|
|
4911
|
+
return path.slice(0, depth);
|
|
4912
|
+
}
|
|
4913
|
+
//#endregion
|
|
4914
|
+
//#region src/definition/tooling/schema-first/stored-models.ts
|
|
4915
|
+
function unreadable(packageRoot, path, what, error) {
|
|
4916
|
+
return toolingDiagnostics.create({
|
|
4917
|
+
code: "PH-IMPORT-FAILED",
|
|
4918
|
+
source: { specifier: packageSpecifier(packageRoot, path) },
|
|
4919
|
+
path: [],
|
|
4920
|
+
message: `The ${what} could not be read, so the stored models in it are not checked.`,
|
|
4921
|
+
expected: `a readable ${what}`,
|
|
4922
|
+
received: describeThrown(error),
|
|
4923
|
+
repair: "Fix the permissions of the path."
|
|
4924
|
+
});
|
|
4925
|
+
}
|
|
4926
|
+
function outsidePackage(specifier) {
|
|
4927
|
+
return toolingDiagnostics.create({
|
|
4928
|
+
code: "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE",
|
|
4929
|
+
source: { specifier },
|
|
4930
|
+
path: [],
|
|
4931
|
+
message: "The stored document model resolves through a symlink that leaves the package root, so it is not this package's model.",
|
|
4932
|
+
expected: "a real path contained by the package root",
|
|
4933
|
+
received: specifier,
|
|
4934
|
+
repair: "Replace the symlink with a model file that really lives in this package."
|
|
4935
|
+
});
|
|
4936
|
+
}
|
|
4937
|
+
/**
|
|
4938
|
+
* A missing models directory holds no models; any other read failure is
|
|
4939
|
+
* reported. A symlinked model directory or file counts when its real path
|
|
4940
|
+
* stays in the package.
|
|
4941
|
+
*/
|
|
4942
|
+
function storedModelFiles(packageRoot, documentModelsDir) {
|
|
4943
|
+
let names;
|
|
4944
|
+
let packageRootIdentity;
|
|
4945
|
+
try {
|
|
4946
|
+
packageRootIdentity = realpathSync.native(packageRoot);
|
|
4947
|
+
names = readdirSync(documentModelsDir).sort(compareCodeUnits);
|
|
4948
|
+
} catch (error) {
|
|
4949
|
+
return {
|
|
4950
|
+
files: [],
|
|
4951
|
+
diagnostics: error.code === "ENOENT" ? [] : [unreadable(packageRoot, documentModelsDir, "document models directory", error)]
|
|
4952
|
+
};
|
|
4953
|
+
}
|
|
4954
|
+
const files = [];
|
|
4955
|
+
const diagnostics = [];
|
|
4956
|
+
for (const name of names) {
|
|
4957
|
+
const directory = join(documentModelsDir, name);
|
|
4958
|
+
const file = join(directory, `${name}.json`);
|
|
4959
|
+
let real;
|
|
4960
|
+
try {
|
|
4961
|
+
if (!statSync(directory, { throwIfNoEntry: false })?.isDirectory() || !statSync(file, { throwIfNoEntry: false })?.isFile()) continue;
|
|
4962
|
+
real = realpathSync.native(file);
|
|
4963
|
+
} catch (error) {
|
|
4964
|
+
diagnostics.push(unreadable(packageRoot, directory, "document model directory", error));
|
|
4965
|
+
continue;
|
|
4966
|
+
}
|
|
4967
|
+
if (isWithin(packageRootIdentity, real)) files.push(file);
|
|
4968
|
+
else diagnostics.push(outsidePackage(packageSpecifier(packageRoot, file)));
|
|
4969
|
+
}
|
|
4970
|
+
return {
|
|
4971
|
+
files,
|
|
4972
|
+
diagnostics
|
|
4973
|
+
};
|
|
4974
|
+
}
|
|
4975
|
+
function packageSpecifier(packageRoot, file) {
|
|
4976
|
+
return `./${relative(packageRoot, file).split(sep).join("/")}`;
|
|
4977
|
+
}
|
|
4978
|
+
function storedVersion(value) {
|
|
4979
|
+
const specifications = value?.specifications;
|
|
4980
|
+
if (!Array.isArray(specifications)) return void 0;
|
|
4981
|
+
const version = specifications.at(-1)?.version;
|
|
4982
|
+
return typeof version === "number" ? version : void 0;
|
|
4983
|
+
}
|
|
4984
|
+
function adaptStoredModelFile(file, source, scalars) {
|
|
4985
|
+
let text;
|
|
4986
|
+
try {
|
|
4987
|
+
text = readFileSync(file, "utf8");
|
|
4988
|
+
} catch (error) {
|
|
4989
|
+
return {
|
|
4990
|
+
artifacts: [],
|
|
4991
|
+
diagnostics: [toolingDiagnostics.create({
|
|
4992
|
+
code: "PH-IMPORT-FAILED",
|
|
4993
|
+
source,
|
|
4994
|
+
path: [],
|
|
4995
|
+
message: "The stored document model file could not be read.",
|
|
4996
|
+
expected: "a readable JSON file",
|
|
4997
|
+
received: describeThrown(error),
|
|
4998
|
+
repair: "Fix the file's permissions."
|
|
4999
|
+
})]
|
|
5000
|
+
};
|
|
5001
|
+
}
|
|
5002
|
+
let stored;
|
|
5003
|
+
try {
|
|
5004
|
+
stored = JSON.parse(text);
|
|
5005
|
+
} catch (error) {
|
|
5006
|
+
return {
|
|
5007
|
+
artifacts: [],
|
|
5008
|
+
diagnostics: [toolingDiagnostics.create({
|
|
5009
|
+
code: "PH-DM-DECLARATION-INVALID",
|
|
5010
|
+
source,
|
|
5011
|
+
path: [],
|
|
5012
|
+
message: "The stored document model is not JSON.",
|
|
5013
|
+
expected: "the JSON the document model editor saves",
|
|
5014
|
+
received: describeThrown(error),
|
|
5015
|
+
repair: "Repair the JSON, or save the model again from the document model editor."
|
|
5016
|
+
})]
|
|
5017
|
+
};
|
|
5018
|
+
}
|
|
5019
|
+
const version = storedVersion(stored);
|
|
5020
|
+
const result = adaptSchemaFirstDocumentModelModule({
|
|
5021
|
+
...defaultBaseState(),
|
|
5022
|
+
global: stored,
|
|
5023
|
+
local: {}
|
|
5024
|
+
}, source, {
|
|
5025
|
+
scalars,
|
|
5026
|
+
...version !== void 0 && { version }
|
|
5027
|
+
});
|
|
5028
|
+
const artifact = result.artifacts.at(0);
|
|
5029
|
+
return {
|
|
5030
|
+
artifacts: artifact === void 0 ? [] : artifact.definition.specifications.map((specification) => ({
|
|
5031
|
+
...artifact,
|
|
5032
|
+
version: specification.version
|
|
5033
|
+
})),
|
|
5034
|
+
...artifact !== void 0 && { relocation: storedModelRelocation(artifact) },
|
|
5035
|
+
diagnostics: result.diagnostics.map((diagnostic) => ({
|
|
5036
|
+
...diagnostic,
|
|
5037
|
+
source,
|
|
5038
|
+
path: diagnostic.path[0] === "global" ? diagnostic.path.slice(1) : diagnostic.path
|
|
5039
|
+
}))
|
|
5040
|
+
};
|
|
5041
|
+
}
|
|
5042
|
+
/**
|
|
5043
|
+
* Normalizes every `<documentModelsDir>/<name>/<name>.json` a schema-first
|
|
5044
|
+
* package stores, with the project scalars `scalars/index.ts` exports. A
|
|
5045
|
+
* directory or file that cannot be read, or a file that cannot be adapted,
|
|
5046
|
+
* is a diagnostic.
|
|
5047
|
+
*/
|
|
5048
|
+
const readStoredDocumentModels = async (input) => {
|
|
5049
|
+
const { packageRoot, documentModelsDir } = input;
|
|
5050
|
+
if (documentModelsDir === void 0) return {
|
|
5051
|
+
artifacts: [],
|
|
5052
|
+
diagnostics: [],
|
|
5053
|
+
relocations: /* @__PURE__ */ new Map()
|
|
5054
|
+
};
|
|
5055
|
+
const { files, diagnostics } = storedModelFiles(packageRoot, documentModelsDir);
|
|
5056
|
+
if (files.length === 0) return {
|
|
5057
|
+
artifacts: [],
|
|
5058
|
+
diagnostics,
|
|
5059
|
+
relocations: /* @__PURE__ */ new Map()
|
|
5060
|
+
};
|
|
5061
|
+
const scalars = await loadProjectScalars(input);
|
|
5062
|
+
const relocations = /* @__PURE__ */ new Map();
|
|
5063
|
+
const results = files.map((file) => {
|
|
5064
|
+
const specifier = packageSpecifier(packageRoot, file);
|
|
5065
|
+
const result = adaptStoredModelFile(file, { specifier }, scalars.definitions);
|
|
5066
|
+
if (result.relocation !== void 0) relocations.set(specifier, result.relocation);
|
|
5067
|
+
return result;
|
|
5068
|
+
});
|
|
5069
|
+
return {
|
|
5070
|
+
artifacts: results.flatMap((result) => result.artifacts),
|
|
5071
|
+
diagnostics: [
|
|
5072
|
+
...diagnostics,
|
|
5073
|
+
...scalars.diagnostics,
|
|
5074
|
+
...results.flatMap((result) => result.diagnostics)
|
|
5075
|
+
],
|
|
5076
|
+
relocations
|
|
5077
|
+
};
|
|
5078
|
+
};
|
|
5079
|
+
//#endregion
|
|
5080
|
+
//#region src/definition/tooling/project/unregistered-definitions.ts
|
|
5081
|
+
const DECLARATION = {
|
|
5082
|
+
module: /^document-model(?:\/|$)/,
|
|
5083
|
+
factory: "defineDocumentModel(?:Family)?"
|
|
5084
|
+
};
|
|
5085
|
+
const NAMED_IMPORT = /\bimport\s*\{([^}]*)\}\s*from\s*"#(\d+)"/g;
|
|
5086
|
+
const NAMESPACE_IMPORT = /\bimport\s*\*\s*as\s+([\w$]+)\s*from\s*"#(\d+)"/g;
|
|
5087
|
+
function startsRegExp(code) {
|
|
5088
|
+
const before = code.slice(-64).trimEnd();
|
|
5089
|
+
return before === "" || /[(,=:[!&|?{};+\-*%<>~^}]$/.test(before) || /(?:^|[^\w$])(?:return|typeof|case|do|else|in|of|new|delete|void|throw|yield|await)$/.test(before);
|
|
5090
|
+
}
|
|
5091
|
+
function readCodeAndStrings(file) {
|
|
5092
|
+
let text;
|
|
5093
|
+
try {
|
|
5094
|
+
text = readFileSync(file, "utf8");
|
|
5095
|
+
} catch {
|
|
5096
|
+
return {
|
|
5097
|
+
code: "",
|
|
5098
|
+
strings: []
|
|
5099
|
+
};
|
|
5100
|
+
}
|
|
5101
|
+
let code = "";
|
|
5102
|
+
const strings = [];
|
|
5103
|
+
const literal = (contents) => {
|
|
5104
|
+
code += `"#${strings.length}"`;
|
|
5105
|
+
strings.push(contents);
|
|
5106
|
+
};
|
|
5107
|
+
let braces = 0;
|
|
5108
|
+
const templates = [];
|
|
5109
|
+
let i = 0;
|
|
5110
|
+
const skipQuoted = (end) => {
|
|
5111
|
+
while (i < text.length && !end(i)) i += text[i] === "\\" ? 2 : 1;
|
|
5112
|
+
};
|
|
5113
|
+
while (i < text.length) {
|
|
5114
|
+
const char = text[i];
|
|
5115
|
+
if (char === "/" && text[i + 1] === "/") {
|
|
5116
|
+
i = text.indexOf("\n", i);
|
|
5117
|
+
if (i === -1) i = text.length;
|
|
5118
|
+
} else if (char === "/" && text[i + 1] === "*") {
|
|
5119
|
+
const end = text.indexOf("*/", i + 2);
|
|
5120
|
+
i = end === -1 ? text.length : end + 2;
|
|
5121
|
+
code += " ";
|
|
5122
|
+
} else if (char === "/" && startsRegExp(code)) {
|
|
5123
|
+
i += 1;
|
|
5124
|
+
let inClass = false;
|
|
5125
|
+
while (i < text.length && text[i] !== "\n") {
|
|
5126
|
+
if (text[i] === "\\") i += 1;
|
|
5127
|
+
else if (text[i] === "[") inClass = true;
|
|
5128
|
+
else if (text[i] === "]") inClass = false;
|
|
5129
|
+
else if (text[i] === "/" && !inClass) break;
|
|
5130
|
+
i += 1;
|
|
5131
|
+
}
|
|
5132
|
+
i += 1;
|
|
5133
|
+
while (/[a-z]/.test(text[i] ?? "")) i += 1;
|
|
5134
|
+
code += " ";
|
|
5135
|
+
} else if (char === "\"" || char === "'") {
|
|
5136
|
+
const start = i += 1;
|
|
5137
|
+
skipQuoted((at) => text[at] === char || text[at] === "\n");
|
|
5138
|
+
literal(text.slice(start, i));
|
|
5139
|
+
i += 1;
|
|
5140
|
+
} else if (char === "`" || char === "}" && templates.at(-1) === braces) {
|
|
5141
|
+
const whole = char === "`";
|
|
5142
|
+
if (!whole) templates.pop();
|
|
5143
|
+
const start = i += 1;
|
|
5144
|
+
skipQuoted((at) => text[at] === "`" || text[at] === "$" && text[at + 1] === "{");
|
|
5145
|
+
const closed = text[i] === "`";
|
|
5146
|
+
literal(whole && closed ? text.slice(start, i) : "");
|
|
5147
|
+
if (closed) i += 1;
|
|
5148
|
+
else {
|
|
5149
|
+
templates.push(braces);
|
|
5150
|
+
i += 2;
|
|
5151
|
+
}
|
|
5152
|
+
} else {
|
|
5153
|
+
if (char === "{") braces += 1;
|
|
5154
|
+
if (char === "}") braces -= 1;
|
|
5155
|
+
code += char;
|
|
5156
|
+
i += 1;
|
|
5157
|
+
}
|
|
5158
|
+
}
|
|
5159
|
+
return {
|
|
5160
|
+
code,
|
|
5161
|
+
strings
|
|
5162
|
+
};
|
|
5163
|
+
}
|
|
5164
|
+
/** `type as e` imports a value named `type`. */
|
|
5165
|
+
function valueBindings(clause) {
|
|
5166
|
+
return clause.split(",").map((part) => part.trim()).filter((part) => part !== "" && !/^type\s+(?!as\b)/.test(part)).map((part) => {
|
|
5167
|
+
const [imported, local = imported] = part.split(/\s+as\s+/);
|
|
5168
|
+
return {
|
|
5169
|
+
imported,
|
|
5170
|
+
local
|
|
5171
|
+
};
|
|
5172
|
+
});
|
|
5173
|
+
}
|
|
5174
|
+
function isSourceFile(name) {
|
|
5175
|
+
return /\.m?tsx?$/.test(name) && !/\.d\.m?ts$/.test(name);
|
|
5176
|
+
}
|
|
5177
|
+
function isTestFile(name) {
|
|
5178
|
+
return /\.(?:test|spec)\.m?tsx?$/.test(name);
|
|
5179
|
+
}
|
|
5180
|
+
/**
|
|
5181
|
+
* Sorted, with symlinks followed. An entry that cannot be read, or whose real
|
|
5182
|
+
* path leaves the package, is not the package's and is skipped.
|
|
5183
|
+
*/
|
|
5184
|
+
function packageEntries(path, packageRootIdentity) {
|
|
5185
|
+
let names;
|
|
5186
|
+
try {
|
|
5187
|
+
names = readdirSync(path);
|
|
5188
|
+
} catch {
|
|
5189
|
+
return [];
|
|
5190
|
+
}
|
|
5191
|
+
return names.filter((name) => name !== "node_modules" && !name.startsWith(".")).sort(compareCodeUnits).flatMap((name) => {
|
|
5192
|
+
const child = join(path, name);
|
|
5193
|
+
try {
|
|
5194
|
+
const real = realpathSync.native(child);
|
|
5195
|
+
if (!isWithin(packageRootIdentity, real)) return [];
|
|
5196
|
+
return [{
|
|
5197
|
+
name,
|
|
5198
|
+
path: child,
|
|
5199
|
+
real,
|
|
5200
|
+
isDirectory: statSync(real).isDirectory()
|
|
5201
|
+
}];
|
|
5202
|
+
} catch {
|
|
5203
|
+
return [];
|
|
5204
|
+
}
|
|
5205
|
+
});
|
|
5206
|
+
}
|
|
5207
|
+
/** `visited` holds real directories, so a symlink cycle ends. */
|
|
5208
|
+
function sourceFilesUnder(directory, packageRootIdentity, visited) {
|
|
5209
|
+
if (visited.has(directory.real)) return [];
|
|
5210
|
+
visited.add(directory.real);
|
|
5211
|
+
return packageEntries(directory.path, packageRootIdentity).flatMap((entry) => {
|
|
5212
|
+
if (entry.isDirectory) return entry.name === "__tests__" ? [] : sourceFilesUnder(entry, packageRootIdentity, visited);
|
|
5213
|
+
return isSourceFile(entry.name) && !isTestFile(entry.name) ? [entry] : [];
|
|
5214
|
+
});
|
|
5215
|
+
}
|
|
5216
|
+
function declares(file) {
|
|
5217
|
+
const { module, factory } = DECLARATION;
|
|
5218
|
+
const { code, strings } = readCodeAndStrings(file);
|
|
5219
|
+
const isFactory = new RegExp(`^${factory}$`);
|
|
5220
|
+
return [...[...code.matchAll(NAMED_IMPORT)].filter(([, , index]) => module.test(strings[Number(index)])).flatMap(([, clause]) => valueBindings(clause).filter(({ imported }) => isFactory.test(imported)).map(({ local }) => escapeRegExp(local))), ...[...code.matchAll(NAMESPACE_IMPORT)].filter(([, , index]) => module.test(strings[Number(index)])).map(([, namespace]) => `${escapeRegExp(namespace)}\\s*\\.\\s*${factory}`)].some((callee) => new RegExp(`(?<![\\w$.])${callee}\\s*(?:<[^;()]*>\\s*)?\\(`).test(code));
|
|
5221
|
+
}
|
|
5222
|
+
function escapeRegExp(name) {
|
|
5223
|
+
return name.replaceAll("$", "\\$");
|
|
5224
|
+
}
|
|
5225
|
+
function packagePath(root, path) {
|
|
5226
|
+
return `./${relative(root, path).split(sep).join("/")}`;
|
|
5227
|
+
}
|
|
5228
|
+
function realPathOrSelf(path) {
|
|
5229
|
+
try {
|
|
5230
|
+
return realpathSync.native(path);
|
|
5231
|
+
} catch {
|
|
5232
|
+
return path;
|
|
5233
|
+
}
|
|
5234
|
+
}
|
|
5235
|
+
/** The suggested specifier is the folder's `index.ts` when it declares, else the first declaring file. */
|
|
5236
|
+
function modelUnit(packageRoot, packageRootIdentity, directory) {
|
|
5237
|
+
const declaring = sourceFilesUnder(directory, packageRootIdentity, /* @__PURE__ */ new Set()).filter(({ real }) => declares(real));
|
|
5238
|
+
const index = join(directory.path, "index.ts");
|
|
5239
|
+
const suggested = declaring.find(({ path }) => path === index) ?? declaring.at(0);
|
|
5240
|
+
if (suggested === void 0) return void 0;
|
|
5241
|
+
return {
|
|
5242
|
+
kind: "document-model",
|
|
5243
|
+
unit: `${packagePath(packageRoot, directory.path)}/`,
|
|
5244
|
+
specifier: packagePath(packageRoot, suggested.path),
|
|
5245
|
+
declaring: declaring.map(({ real }) => real)
|
|
5246
|
+
};
|
|
5247
|
+
}
|
|
5248
|
+
/**
|
|
5249
|
+
* Each `<documentModelsDir>/<name>/` whose sources declare a code-first model
|
|
5250
|
+
* that no selected source's import reached. A selected source that did not
|
|
5251
|
+
* import reaches files no one can name, so the scan then reports nothing.
|
|
5252
|
+
*/
|
|
5253
|
+
function findUnregisteredDefinitions(request) {
|
|
5254
|
+
const { packageRoot, documentModelsDir, sources, importedFiles } = request;
|
|
5255
|
+
const imported = sources.map(({ specifier }) => importedFiles(specifier));
|
|
5256
|
+
if (imported.some((files) => files.length === 0)) return [];
|
|
5257
|
+
const reached = new Set(imported.flat().map(realPathOrSelf));
|
|
5258
|
+
const packageRootIdentity = realPathOrSelf(packageRoot);
|
|
5259
|
+
return packageEntries(documentModelsDir, packageRootIdentity).flatMap((entry) => entry.isDirectory ? modelUnit(packageRoot, packageRootIdentity, entry) ?? [] : []).filter((unit) => !unit.declaring.some((file) => reached.has(file))).map(({ kind, unit, specifier }) => ({
|
|
5260
|
+
kind,
|
|
5261
|
+
unit,
|
|
5262
|
+
specifier
|
|
5263
|
+
}));
|
|
5264
|
+
}
|
|
5265
|
+
//#endregion
|
|
5266
|
+
//#region src/definition/tooling/project/project-definitions.ts
|
|
5267
|
+
const DEFAULT_DOCUMENT_MODELS_DIR = "./document-models";
|
|
5268
|
+
/** Code-first sources are authored in normalized coordinates, so they need no relocation. */
|
|
5269
|
+
const adaptSelectedModules = ({ loaded }) => {
|
|
5270
|
+
const results = loaded.documentModels.map(({ value, source }) => {
|
|
5271
|
+
const result = adaptCodeFirstDocumentModelSource(value, source);
|
|
5272
|
+
return {
|
|
5273
|
+
artifacts: result.artifacts,
|
|
5274
|
+
diagnostics: result.diagnostics.map((diagnostic) => diagnostic.source === void 0 ? {
|
|
5275
|
+
...diagnostic,
|
|
5276
|
+
source
|
|
5277
|
+
} : diagnostic)
|
|
5278
|
+
};
|
|
5279
|
+
});
|
|
5280
|
+
return {
|
|
5281
|
+
artifacts: results.flatMap(({ artifacts }) => artifacts),
|
|
5282
|
+
diagnostics: results.flatMap(({ diagnostics }) => diagnostics),
|
|
5283
|
+
relocations: /* @__PURE__ */ new Map()
|
|
5284
|
+
};
|
|
5285
|
+
};
|
|
5286
|
+
/** The readers a project loads with unless a caller passes its own; the one place an authoring mode is named. */
|
|
5287
|
+
const defaultDefinitionProducers = Object.freeze([adaptSelectedModules, readStoredDocumentModels]);
|
|
5288
|
+
/** A path that cannot be inspected is left to the readers, which report it. */
|
|
5289
|
+
function namesNonDirectory(path) {
|
|
5290
|
+
try {
|
|
5291
|
+
return statSync(path, { throwIfNoEntry: false })?.isDirectory() === false;
|
|
5292
|
+
} catch {
|
|
5293
|
+
return false;
|
|
5294
|
+
}
|
|
5295
|
+
}
|
|
5296
|
+
/** The configured models directory, or why it cannot be scanned. */
|
|
5297
|
+
function documentModelsDirectory(packageRoot, configFile) {
|
|
5298
|
+
const config = readConfigObject(resolve(configFile));
|
|
5299
|
+
if (!config.ok) return { diagnostics: [] };
|
|
5300
|
+
const configured = config.value.documentModelsDir ?? DEFAULT_DOCUMENT_MODELS_DIR;
|
|
5301
|
+
if (typeof configured !== "string" || configured.trim() === "") return { diagnostics: [toolingDiagnostics.create({
|
|
5302
|
+
code: "PH-CONFIG-SOURCE-INVALID",
|
|
5303
|
+
path: ["documentModelsDir"],
|
|
5304
|
+
message: "documentModelsDir is not a directory path.",
|
|
5305
|
+
expected: "a package-relative path such as ./document-models",
|
|
5306
|
+
received: JSON.stringify(configured),
|
|
5307
|
+
repair: "Set documentModelsDir to a package-relative directory, or remove it to use ./document-models."
|
|
5308
|
+
})] };
|
|
5309
|
+
const path = resolve(packageRoot, configured);
|
|
5310
|
+
let inside = isWithin(packageRoot, path);
|
|
5311
|
+
try {
|
|
5312
|
+
inside &&= isWithin(realpathSync.native(packageRoot), realPathThroughExistingParent(path));
|
|
5313
|
+
} catch {
|
|
5314
|
+
inside = false;
|
|
5315
|
+
}
|
|
5316
|
+
if (!inside) return { diagnostics: [toolingDiagnostics.create({
|
|
5317
|
+
code: "PH-CONFIG-SOURCE-OUTSIDE-PACKAGE",
|
|
5318
|
+
path: ["documentModelsDir"],
|
|
5319
|
+
message: "documentModelsDir leaves the package root, so its models are not this package's.",
|
|
5320
|
+
expected: "a directory inside the package",
|
|
5321
|
+
received: configured,
|
|
5322
|
+
repair: "Point documentModelsDir at a directory inside the package."
|
|
5323
|
+
})] };
|
|
5324
|
+
if (namesNonDirectory(path)) return { diagnostics: [toolingDiagnostics.create({
|
|
5325
|
+
code: "PH-CONFIG-SOURCE-INVALID",
|
|
5326
|
+
path: ["documentModelsDir"],
|
|
5327
|
+
message: "documentModelsDir names a file, not a directory.",
|
|
5328
|
+
expected: "a package-relative directory such as ./document-models",
|
|
5329
|
+
received: configured,
|
|
5330
|
+
repair: "Point documentModelsDir at the directory that holds the models, or remove it to use ./document-models."
|
|
5331
|
+
})] };
|
|
5332
|
+
return {
|
|
5333
|
+
path,
|
|
5334
|
+
diagnostics: []
|
|
5335
|
+
};
|
|
5336
|
+
}
|
|
5337
|
+
/** Tool and Node messages can quote the machine path a package lives at. */
|
|
5338
|
+
function packageRelative(diagnostics, packageRoot) {
|
|
5339
|
+
let real = packageRoot;
|
|
5340
|
+
try {
|
|
5341
|
+
real = realpathSync.native(packageRoot);
|
|
5342
|
+
} catch {}
|
|
5343
|
+
const roots = [.../* @__PURE__ */ new Set([packageRoot, real])].sort((left, right) => right.length - left.length).flatMap((root) => [pathToFileURL(root).href, root]);
|
|
5344
|
+
const rewrite = (text) => roots.reduce((result, root) => result.replaceAll(root, "."), text);
|
|
5345
|
+
return diagnostics.map((diagnostic) => ({
|
|
5346
|
+
...diagnostic,
|
|
5347
|
+
message: rewrite(diagnostic.message),
|
|
5348
|
+
repair: rewrite(diagnostic.repair),
|
|
5349
|
+
...diagnostic.expected !== void 0 && { expected: rewrite(diagnostic.expected) },
|
|
5350
|
+
...diagnostic.received !== void 0 && { received: rewrite(diagnostic.received) },
|
|
5351
|
+
...diagnostic.related !== void 0 && { related: diagnostic.related.map((location) => ({
|
|
5352
|
+
...location,
|
|
5353
|
+
message: rewrite(location.message)
|
|
5354
|
+
})) }
|
|
5355
|
+
}));
|
|
5356
|
+
}
|
|
5357
|
+
/**
|
|
5358
|
+
* @experimental Loads the selected code-first sources and the package's stored
|
|
5359
|
+
* schema-first models, and scans for code-first declarations no source
|
|
5360
|
+
* reaches. Artifacts and diagnostics are sorted and package relative.
|
|
5361
|
+
* `producers` replaces the default readers. `importedFiles` names the
|
|
5362
|
+
* absolute paths of every module the loader's import of a selected
|
|
5363
|
+
* specifier evaluated, so reach follows whatever the importer resolved.
|
|
5364
|
+
* Experimental while code-first projects are introduced.
|
|
5365
|
+
*/
|
|
5366
|
+
async function loadProjectDefinitions(request) {
|
|
5367
|
+
const { loader, producers = defaultDefinitionProducers, importedFiles, ...load } = request;
|
|
5368
|
+
const loaded = await loader.normalizeDefinitionSources(load);
|
|
5369
|
+
request.signal?.throwIfAborted();
|
|
5370
|
+
const { packageRoot } = loaded;
|
|
5371
|
+
const directory = documentModelsDirectory(packageRoot, request.configFile);
|
|
5372
|
+
const modelsDir = directory.path;
|
|
5373
|
+
const input = {
|
|
5374
|
+
...load,
|
|
5375
|
+
loader,
|
|
5376
|
+
packageRoot,
|
|
5377
|
+
loaded,
|
|
5378
|
+
...modelsDir !== void 0 && { documentModelsDir: modelsDir }
|
|
5379
|
+
};
|
|
5380
|
+
const produced = [];
|
|
5381
|
+
for (const producer of producers) produced.push(await producer(input));
|
|
5382
|
+
request.signal?.throwIfAborted();
|
|
5383
|
+
const selectionKnown = !loaded.diagnostics.some(({ phase, severity }) => phase === "configuration" && severity === "error");
|
|
5384
|
+
return {
|
|
5385
|
+
packageRoot,
|
|
5386
|
+
sourceSet: loaded.sourceSet,
|
|
5387
|
+
...loaded.status === "skipped" && { skipReason: loaded.skipReason },
|
|
5388
|
+
artifacts: produced.flatMap(({ artifacts }) => artifacts).sort(compareArtifacts),
|
|
5389
|
+
relocations: new Map(produced.flatMap(({ relocations }) => [...relocations])),
|
|
5390
|
+
diagnostics: sortedUniqueDiagnostics(packageRelative([
|
|
5391
|
+
...loaded.diagnostics,
|
|
5392
|
+
...directory.diagnostics,
|
|
5393
|
+
...produced.flatMap(({ diagnostics }) => diagnostics)
|
|
5394
|
+
], packageRoot)),
|
|
5395
|
+
unregistered: selectionKnown && modelsDir !== void 0 ? findUnregisteredDefinitions({
|
|
5396
|
+
packageRoot,
|
|
5397
|
+
documentModelsDir: modelsDir,
|
|
5398
|
+
sources: loaded.sourceSet.sources,
|
|
5399
|
+
importedFiles
|
|
5400
|
+
}) : []
|
|
5401
|
+
};
|
|
5402
|
+
}
|
|
5403
|
+
//#endregion
|
|
5404
|
+
export { DefinitionSourceLoader, adaptCodeFirstDocumentModelSource, checkProjectDefinitions, formatDefinitionDiagnostic, inspectProjectDefinitions, loadProjectDefinitions, resolveDefinitionSelection };
|
|
2654
5405
|
|
|
2655
5406
|
//# sourceMappingURL=tooling.mjs.map
|