@powerhousedao/powerhouse-vetra-packages 6.2.3 → 6.3.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (95) hide show
  1. package/dist/browser/document-models/index.js +1 -1
  2. package/dist/browser/documents-cxt8RRxe.js +18 -0
  3. package/dist/browser/documents-cxt8RRxe.js.map +1 -0
  4. package/dist/browser/editor-DXAJ8Mqb.js +2293 -0
  5. package/dist/browser/editor-DXAJ8Mqb.js.map +1 -0
  6. package/dist/browser/{editor-CiR6XQBO.js → editor-Dmpkd8pQ.js} +3 -3
  7. package/dist/browser/{editor-CiR6XQBO.js.map → editor-Dmpkd8pQ.js.map} +1 -1
  8. package/dist/browser/editors/document-model-editor/module.js +1 -1
  9. package/dist/browser/editors/document-model-editor/module.js.map +1 -1
  10. package/dist/browser/editors/generic-drive-explorer/index.js +4 -340
  11. package/dist/browser/editors/generic-drive-explorer/index.js.map +1 -1
  12. package/dist/browser/editors/generic-drive-explorer/module.js +1 -1
  13. package/dist/browser/folder-view-CwIU4XEe.js +237 -0
  14. package/dist/browser/folder-view-CwIU4XEe.js.map +1 -0
  15. package/dist/browser/graphql-editor-CGxwONKl.js +103 -0
  16. package/dist/browser/graphql-editor-CGxwONKl.js.map +1 -0
  17. package/dist/browser/hooks-D15NCia0.js +126 -0
  18. package/dist/browser/hooks-D15NCia0.js.map +1 -0
  19. package/dist/browser/index.js +5 -805
  20. package/dist/browser/index.js.map +1 -1
  21. package/dist/browser/json-editor--jgLEwP2.js +55 -0
  22. package/dist/browser/json-editor--jgLEwP2.js.map +1 -0
  23. package/dist/browser/schema-context-CC_WFs1x.js +73 -0
  24. package/dist/browser/schema-context-CC_WFs1x.js.map +1 -0
  25. package/dist/browser/state-schemas-DSY44MOd.js +307 -0
  26. package/dist/browser/state-schemas-DSY44MOd.js.map +1 -0
  27. package/dist/node/bundle-mjs-Cuu3DEfT.mjs +3140 -0
  28. package/dist/node/bundle-mjs-Cuu3DEfT.mjs.map +1 -0
  29. package/dist/node/{graphql-Dp4j7rmx.mjs → documents-DH2fyf7U.mjs} +32 -3
  30. package/dist/node/documents-DH2fyf7U.mjs.map +1 -0
  31. package/dist/node/{editor-96sMeumV.mjs → editor-BcvUeBW7.mjs} +2902 -2738
  32. package/dist/node/editor-BcvUeBW7.mjs.map +1 -0
  33. package/dist/node/editor-DJCghViS.mjs +983 -0
  34. package/dist/node/editor-DJCghViS.mjs.map +1 -0
  35. package/dist/node/editors/index.mjs +23 -2
  36. package/dist/node/editors/index.mjs.map +1 -0
  37. package/dist/node/{graphql-editor-CBJXEY_C.mjs → graphql-editor-u9NStKLL.mjs} +5078 -26
  38. package/dist/node/graphql-editor-u9NStKLL.mjs.map +1 -0
  39. package/dist/{browser/hooks-eQxBX7g4.js → node/hooks-BiLz75cj.mjs} +2 -2
  40. package/dist/node/{hooks-C2b46djt.mjs.map → hooks-BiLz75cj.mjs.map} +1 -1
  41. package/dist/node/index.mjs +12 -189
  42. package/dist/node/index.mjs.map +1 -1
  43. package/dist/{browser/json-editor-DfRD-pfk.js → node/json-editor-BfcrckeT.mjs} +3 -3
  44. package/dist/node/{json-editor-DaqHARBD.mjs.map → json-editor-BfcrckeT.mjs.map} +1 -1
  45. package/dist/node/{schema-context-CojjnSE6.mjs → schema-context-r0MTQnRC.mjs} +6 -4
  46. package/dist/node/schema-context-r0MTQnRC.mjs.map +1 -0
  47. package/dist/node/{state-schemas-BHuo0GPl.mjs → state-schemas-o3PZdBW2.mjs} +427 -54
  48. package/dist/node/state-schemas-o3PZdBW2.mjs.map +1 -0
  49. package/package.json +21 -19
  50. package/style.css +2 -0
  51. package/dist/browser/assets/entry-D62sYiFV.js +0 -318
  52. package/dist/browser/assets/projection-entry-BGcu_9-p.js +0 -446
  53. package/dist/browser/documents-CRzouuNR.js +0 -6067
  54. package/dist/browser/documents-CRzouuNR.js.map +0 -1
  55. package/dist/browser/editor-C7KBR_ar.js +0 -4676
  56. package/dist/browser/editor-C7KBR_ar.js.map +0 -1
  57. package/dist/browser/folder-view-DSgXN79D.js +0 -4409
  58. package/dist/browser/folder-view-DSgXN79D.js.map +0 -1
  59. package/dist/browser/graphql-editor-Cgi5UOrF.js +0 -11708
  60. package/dist/browser/graphql-editor-Cgi5UOrF.js.map +0 -1
  61. package/dist/browser/hooks-eQxBX7g4.js.map +0 -1
  62. package/dist/browser/json-editor-DfRD-pfk.js.map +0 -1
  63. package/dist/browser/parser-DtbeHA3H.js +0 -2554
  64. package/dist/browser/parser-DtbeHA3H.js.map +0 -1
  65. package/dist/browser/rolldown-runtime-DC62tzP2.js +0 -33
  66. package/dist/browser/src-CrUksCLW-B2dkRdgq.js +0 -5254
  67. package/dist/browser/src-CrUksCLW-B2dkRdgq.js.map +0 -1
  68. package/dist/browser/state-schemas-B5Bk_l1s.js +0 -696
  69. package/dist/browser/state-schemas-B5Bk_l1s.js.map +0 -1
  70. package/dist/browser/tslib.es6-Cno80yFJ.js +0 -32
  71. package/dist/browser/tslib.es6-Cno80yFJ.js.map +0 -1
  72. package/dist/node/documents-D70S9PZL.mjs +0 -17
  73. package/dist/node/documents-D70S9PZL.mjs.map +0 -1
  74. package/dist/node/editor-96sMeumV.mjs.map +0 -1
  75. package/dist/node/editor-wqvKwcO5.mjs +0 -24
  76. package/dist/node/editor-wqvKwcO5.mjs.map +0 -1
  77. package/dist/node/editors/document-model-editor/index.mjs +0 -1
  78. package/dist/node/editors/document-model-editor/module.mjs +0 -14
  79. package/dist/node/editors/document-model-editor/module.mjs.map +0 -1
  80. package/dist/node/editors/generic-drive-explorer/index.mjs +0 -461
  81. package/dist/node/editors/generic-drive-explorer/index.mjs.map +0 -1
  82. package/dist/node/editors/generic-drive-explorer/module.mjs +0 -14
  83. package/dist/node/editors/generic-drive-explorer/module.mjs.map +0 -1
  84. package/dist/node/folder-view-ktfv2Cvw.mjs +0 -4409
  85. package/dist/node/folder-view-ktfv2Cvw.mjs.map +0 -1
  86. package/dist/node/graphql-Dp4j7rmx.mjs.map +0 -1
  87. package/dist/node/graphql-editor-CBJXEY_C.mjs.map +0 -1
  88. package/dist/node/hooks-C2b46djt.mjs +0 -24593
  89. package/dist/node/json-editor-DaqHARBD.mjs +0 -153
  90. package/dist/node/schema-context-CojjnSE6.mjs.map +0 -1
  91. package/dist/node/src-CrUksCLW-TvF37aMo.mjs +0 -5935
  92. package/dist/node/src-CrUksCLW-TvF37aMo.mjs.map +0 -1
  93. package/dist/node/state-schemas-BHuo0GPl.mjs.map +0 -1
  94. package/dist/node/tslib.es6-VORZjfk3.mjs +0 -583
  95. package/dist/node/tslib.es6-VORZjfk3.mjs.map +0 -1
@@ -0,0 +1,2293 @@
1
+ import { r as standardLibScalars } from "./documents-cxt8RRxe.js";
2
+ import { n as safeParseSdl, t as SchemaContextProvider } from "./schema-context-CC_WFs1x.js";
3
+ import { addModule, addOperation, addOperationError, deleteModule, deleteOperation, deleteOperationError, generateId, releaseNewVersion, setAuthorName, setAuthorWebsite, setInitialState, setModelDescription, setModelExtension, setModelId, setModelName, setModuleName, setOperationDescription, setOperationErrorName, setOperationName, setOperationSchema, setStateSchema } from "@powerhousedao/shared/document-model";
4
+ import * as React$1 from "react";
5
+ import React, { Suspense, forwardRef, lazy, useCallback, useEffect, useId, useImperativeHandle, useRef, useState } from "react";
6
+ import { ConnectSelect, DocumentToolbar, Modal, ModalButton } from "@powerhousedao/design-system/connect";
7
+ import { usePHToast, useSetPHDocumentEditorConfig } from "@powerhousedao/reactor-browser";
8
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
9
+ import { twMerge } from "tailwind-merge";
10
+ import { GraphQLError, Kind, buildASTSchema, getOperationAST, getVariableValues, parse, print, visit } from "graphql";
11
+ import { constantCase, pascalCase, sentenceCase, snakeCase } from "change-case";
12
+ import { z } from "zod";
13
+ import { zodResolver } from "@hookform/resolvers/zod";
14
+ import { Controller, FormProvider, useForm, useFormContext } from "react-hook-form";
15
+ import { Slot } from "@radix-ui/react-slot";
16
+ import * as LabelPrimitive from "@radix-ui/react-label";
17
+ import { cva } from "class-variance-authority";
18
+ //#region \0rolldown/runtime.js
19
+ var __defProp = Object.defineProperty;
20
+ var __exportAll = (all, no_symbols) => {
21
+ let target = {};
22
+ for (var name in all) __defProp(target, name, {
23
+ get: all[name],
24
+ enumerable: true
25
+ });
26
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
27
+ return target;
28
+ };
29
+ //#endregion
30
+ //#region editors/document-model-editor/constants/graphql-kinds.ts
31
+ const STRING_GQL_PRIMITIVE_NAME = "String";
32
+ const BOOLEAN_GQL_PRIMITIVE_NAME = "Boolean";
33
+ const FLOAT_GQL_PRIMITIVE_NAME = "Float";
34
+ const gqlPrimitiveNodeNamesList = [
35
+ STRING_GQL_PRIMITIVE_NAME,
36
+ BOOLEAN_GQL_PRIMITIVE_NAME,
37
+ "Int",
38
+ FLOAT_GQL_PRIMITIVE_NAME,
39
+ "ID"
40
+ ];
41
+ //#endregion
42
+ //#region editors/document-model-editor/utils/helpers.ts
43
+ function makeStateSchemaNameForScope(modelName, scope) {
44
+ const modelNamePascalCase = pascalCase(modelName);
45
+ const scopePascalCase = pascalCase(scope);
46
+ return scopePascalCase === "Global" ? `${modelNamePascalCase}State` : `${modelNamePascalCase}${scopePascalCase}State`;
47
+ }
48
+ function makeInitialSchemaDoc(modelName, scope) {
49
+ return `type ${makeStateSchemaNameForScope(modelName, scope)} {
50
+ "Add your ${scope} state fields here"
51
+ _placeholder: String
52
+ }`;
53
+ }
54
+ function makeOperationInitialDoc(name) {
55
+ return `input ${pascalCase(name)}Input {
56
+ "Add your inputs here"
57
+ _placeholder: String
58
+ }`;
59
+ }
60
+ function makeEmptyOperationSchema(operationName) {
61
+ return `input ${pascalCase(operationName)}Input {\n _empty: Boolean\n}`;
62
+ }
63
+ function isEmptyOperationSchema(schema) {
64
+ if (!schema) return false;
65
+ return /_empty:\s*Boolean/.test(schema) && !schema.replace(/_empty:\s*Boolean/, "").match(/\w+:\s*\w+/);
66
+ }
67
+ function safeParseJsonRecord(json) {
68
+ try {
69
+ return JSON.parse(json);
70
+ } catch (_error) {
71
+ return null;
72
+ }
73
+ }
74
+ function makeMinimalObjectForStateType(args) {
75
+ const { sharedSchemaDocumentNode, stateTypeDefinitionNode, existingValue } = args;
76
+ const existingValueObject = safeParseJsonRecord(existingValue);
77
+ if (!existingValueObject) return existingValue;
78
+ const stateTypeDefinitionFields = stateTypeDefinitionNode.fields;
79
+ if (!stateTypeDefinitionFields?.length) return existingValue;
80
+ const minimalObject = makeMinimalValuesForObjectFields({
81
+ schemaDocumentNode: sharedSchemaDocumentNode,
82
+ fieldDefinitionNodes: stateTypeDefinitionFields,
83
+ existingValueObject,
84
+ visitedTypes: /* @__PURE__ */ new Set([stateTypeDefinitionNode.name.value])
85
+ });
86
+ return JSON.stringify(minimalObject, null, 2);
87
+ }
88
+ function makeMinimalValuesForObjectFields(args) {
89
+ const { schemaDocumentNode, existingValueObject, fieldDefinitionNodes, visitedTypes } = args;
90
+ const newJson = {};
91
+ for (const astNode of fieldDefinitionNodes) {
92
+ const fieldName = getASTNodeName(astNode);
93
+ if (!fieldName) continue;
94
+ const minimalValue = makeMinimalValueForASTNode({
95
+ fieldName,
96
+ astNode,
97
+ schemaDocumentNode,
98
+ existingValueObject,
99
+ visitedTypes
100
+ });
101
+ newJson[astNode.name.value] = minimalValue;
102
+ }
103
+ return newJson;
104
+ }
105
+ function makeMinimalValueForASTNode(args) {
106
+ const { fieldName, astNode, schemaDocumentNode, existingValueObject, visitedTypes } = args;
107
+ const existingFieldValue = existingValueObject?.[fieldName];
108
+ let node = astNode;
109
+ if (isFieldDefinitionNode(astNode)) node = getASTNodeTypeNode(node);
110
+ const isNonNull = isNonNullNode(node);
111
+ if (isNonNull) node = getASTNodeTypeNode(node);
112
+ if (isListTypeNode(node)) return makeMinimalValueForGqlListNode(node, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes);
113
+ if (isGqlPrimitiveNode(node)) return makeMinimalValueForGQLPrimitiveNode(node, existingFieldValue, isNonNull);
114
+ const namedTypeDefinitionNode = getNamedTypeDefinitionNode(node, schemaDocumentNode);
115
+ if (isEnumTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull);
116
+ if (isScalarTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlScalar(namedTypeDefinitionNode, existingFieldValue, isNonNull);
117
+ if (isUnionTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes);
118
+ if (isObjectTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlObject(namedTypeDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
119
+ return existingFieldValue;
120
+ }
121
+ function isFieldDefinitionNode(astNodeTypeNode) {
122
+ if (!astNodeTypeNode) return false;
123
+ return astNodeTypeNode.kind === Kind.FIELD_DEFINITION;
124
+ }
125
+ function isNonNullNode(astNode) {
126
+ if (!astNode) return false;
127
+ return astNode.kind === Kind.NON_NULL_TYPE;
128
+ }
129
+ function isGqlPrimitiveNode(astNodeTypeNode) {
130
+ if (!astNodeTypeNode) return false;
131
+ const name = getASTNodeName(astNodeTypeNode);
132
+ return gqlPrimitiveNodeNamesList.includes(name);
133
+ }
134
+ function isListTypeNode(astNodeTypeNode) {
135
+ if (!astNodeTypeNode) return false;
136
+ return astNodeTypeNode.kind === Kind.LIST_TYPE;
137
+ }
138
+ function isEnumTypeDefinitionNode(definitionNode) {
139
+ if (!definitionNode) return false;
140
+ return definitionNode.kind === Kind.ENUM_TYPE_DEFINITION;
141
+ }
142
+ function isScalarTypeDefinitionNode(definitionNode) {
143
+ if (!definitionNode) return false;
144
+ return definitionNode.kind === Kind.SCALAR_TYPE_DEFINITION;
145
+ }
146
+ function isUnionTypeDefinitionNode(definitionNode) {
147
+ if (!definitionNode) return false;
148
+ return definitionNode.kind === Kind.UNION_TYPE_DEFINITION;
149
+ }
150
+ function isObjectTypeDefinitionNode(definitionNode) {
151
+ if (!definitionNode) return false;
152
+ return definitionNode.kind === Kind.OBJECT_TYPE_DEFINITION;
153
+ }
154
+ function getASTNodeName(astNode) {
155
+ if (!astNode) return null;
156
+ if (!("name" in astNode)) return null;
157
+ if (!astNode.name) return null;
158
+ if (!("value" in astNode.name)) return null;
159
+ return astNode.name.value;
160
+ }
161
+ function getASTNodeTypeNode(astNode) {
162
+ if (!astNode) return null;
163
+ if (!("type" in astNode)) return null;
164
+ return astNode.type;
165
+ }
166
+ function makeMinimalValueForGQLPrimitiveNode(primitiveTypeNode, existingFieldValue, isNonNull) {
167
+ const name = getASTNodeName(primitiveTypeNode);
168
+ if (!name) return null;
169
+ switch (name) {
170
+ case "ID":
171
+ if (z.string().safeParse(existingFieldValue).success) return existingFieldValue;
172
+ return isNonNull ? "placeholder-id" : null;
173
+ case BOOLEAN_GQL_PRIMITIVE_NAME:
174
+ if (z.boolean().safeParse(existingFieldValue).success) return existingFieldValue;
175
+ return isNonNull ? false : null;
176
+ case "Int":
177
+ if (z.number().safeParse(existingFieldValue).success) return existingFieldValue;
178
+ return isNonNull ? 0 : null;
179
+ case FLOAT_GQL_PRIMITIVE_NAME:
180
+ if (z.number().safeParse(existingFieldValue).success) return existingFieldValue;
181
+ return isNonNull ? 0 : null;
182
+ case STRING_GQL_PRIMITIVE_NAME:
183
+ if (z.string().safeParse(existingFieldValue).success) return existingFieldValue;
184
+ return isNonNull ? "" : null;
185
+ }
186
+ return isNonNull ? existingFieldValue : null;
187
+ }
188
+ function makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull) {
189
+ const enumValues = namedTypeDefinitionNode.values?.map((value) => value.name.value) ?? [];
190
+ if (typeof existingFieldValue === "string" && enumValues.includes(existingFieldValue)) return existingFieldValue;
191
+ if (isNonNull) return enumValues[0];
192
+ return null;
193
+ }
194
+ function makeMinimalValueForGqlScalar(scalarTypeDefinitionNode, existingFieldValue, isNonNull) {
195
+ if (!isNonNull && !existingFieldValue) return null;
196
+ const name = getASTNodeName(scalarTypeDefinitionNode);
197
+ if (!name) {
198
+ console.error("No name for scalar type definition node", scalarTypeDefinitionNode);
199
+ return null;
200
+ }
201
+ const scalar = standardLibScalars.get(name);
202
+ if (!scalar) return null;
203
+ if (name === "Upload") throw new Error("The editor cannot derive an initial state value for an Upload field.");
204
+ if (scalar.schema.safeParse(existingFieldValue).success) return existingFieldValue;
205
+ return isNonNull ? existingFieldValue : null;
206
+ }
207
+ function makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes) {
208
+ if (!isNonNull && !existingFieldValue) return null;
209
+ if (!namedTypeDefinitionNode.types?.length) return null;
210
+ const firstNamedTypeDefinitionNode = namedTypeDefinitionNode.types?.at(0);
211
+ if (!firstNamedTypeDefinitionNode) return null;
212
+ const firstNamedTypeObjectDefinitionNode = getNamedTypeDefinitionNode(firstNamedTypeDefinitionNode, schemaDocumentNode);
213
+ if (!isObjectTypeDefinitionNode(firstNamedTypeObjectDefinitionNode)) return null;
214
+ return makeMinimalValueForGqlObject(firstNamedTypeObjectDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
215
+ }
216
+ function makeMinimalValueForGqlListNode(listTypeNode, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes) {
217
+ if (!isNonNull && !Array.isArray(existingFieldValue)) return null;
218
+ if (isNonNull && !Array.isArray(existingFieldValue)) return [];
219
+ return existingFieldValue.map((item, index) => makeMinimalValueForASTNode({
220
+ fieldName: String(index),
221
+ astNode: listTypeNode.type,
222
+ schemaDocumentNode,
223
+ existingValueObject: { [index]: item },
224
+ visitedTypes
225
+ }));
226
+ }
227
+ function makeMinimalValueForGqlObject(objectTypeDefinitionNode, schemaDocumentNode, _existingValueObject, existingFieldValue, isNonNull, visitedTypes) {
228
+ const typeName = objectTypeDefinitionNode.name.value;
229
+ if (visitedTypes?.has(typeName)) return null;
230
+ if (!isNonNull && !existingFieldValue) return null;
231
+ const fields = objectTypeDefinitionNode.fields;
232
+ if (!fields?.length) return {};
233
+ const newVisitedTypes = new Set(visitedTypes);
234
+ newVisitedTypes.add(typeName);
235
+ return makeMinimalValuesForObjectFields({
236
+ schemaDocumentNode,
237
+ existingValueObject: existingFieldValue && typeof existingFieldValue === "object" && !Array.isArray(existingFieldValue) ? existingFieldValue : null,
238
+ fieldDefinitionNodes: fields,
239
+ visitedTypes: newVisitedTypes
240
+ });
241
+ }
242
+ function getNamedTypeDefinitionNode(astNodeTypeNode, schemaDocumentNode) {
243
+ if (!astNodeTypeNode) return null;
244
+ const name = getASTNodeName(astNodeTypeNode);
245
+ if (!name) return null;
246
+ const definitionNode = schemaDocumentNode.definitions.find((def) => "kind" in def && "name" in def && def.name?.value === name);
247
+ if (!definitionNode) return null;
248
+ return definitionNode;
249
+ }
250
+ function removeWhitespace(str) {
251
+ return str.replace(/\s+|\\n|\\t/g, "").toLowerCase();
252
+ }
253
+ function compareStringsWithoutWhitespace(str1, str2) {
254
+ if (str1 === null || str2 === null || str1 === void 0 || str2 === void 0) return false;
255
+ return removeWhitespace(str1) === removeWhitespace(str2);
256
+ }
257
+ function renameSchemaType(sdl, oldName, newName, scope) {
258
+ const typeSuffix = scope === "global" ? "State" : "LocalState";
259
+ const oldTypeName = `${pascalCase(oldName)}${typeSuffix}`;
260
+ const newTypeName = `${pascalCase(newName)}${typeSuffix}`;
261
+ const ast = safeParseSdl(sdl);
262
+ if (!ast) return sdl;
263
+ const updatedAst = visit(ast, { ObjectTypeDefinition: (node) => {
264
+ if (node.name.value === oldTypeName) return {
265
+ ...node,
266
+ name: {
267
+ ...node.name,
268
+ value: newTypeName
269
+ }
270
+ };
271
+ } });
272
+ return print(updatedAst);
273
+ }
274
+ function initializeModelSchema(modelName) {
275
+ return makeInitialSchemaDoc(modelName, "global");
276
+ }
277
+ /** The initial value the schema sync would write for a new model's schema. */
278
+ function makeInitialValueForSchema(stateSchemaSdl) {
279
+ const documentNode = parse(stateSchemaSdl);
280
+ const stateTypeDefinitionNode = documentNode.definitions.find((def) => def.kind === Kind.OBJECT_TYPE_DEFINITION);
281
+ if (!stateTypeDefinitionNode) return "{}";
282
+ return makeMinimalObjectForStateType({
283
+ sharedSchemaDocumentNode: documentNode,
284
+ stateTypeDefinitionNode,
285
+ existingValue: "{}"
286
+ });
287
+ }
288
+ function updateModelSchemaNames(params) {
289
+ const { oldName, newName, globalStateSchema, localStateSchema, setStateSchema } = params;
290
+ setStateSchema(renameSchemaType(globalStateSchema, oldName, newName, "global"), "global");
291
+ if (localStateSchema) setStateSchema(renameSchemaType(localStateSchema, oldName, newName, "local"), "local");
292
+ }
293
+ function handleModelNameChange(params) {
294
+ const { newName, globalStateSchema, setStateSchema } = params;
295
+ if (!!!globalStateSchema) {
296
+ setStateSchema(initializeModelSchema(newName), "global");
297
+ return;
298
+ }
299
+ updateModelSchemaNames(params);
300
+ }
301
+ function validateStateObject(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateValue) {
302
+ let stateObjectJson;
303
+ try {
304
+ stateObjectJson = JSON.parse(stateValue);
305
+ } catch (error) {
306
+ return [new Error("Invalid JSON object", { cause: error })];
307
+ }
308
+ const typeDefByName = indexTypeDefinitions(sharedSchemaDocumentNode);
309
+ const stateTypeName = stateTypeDefinitionNode.name.value;
310
+ if (!typeDefByName.has(stateTypeName)) return [/* @__PURE__ */ new Error(`State type "${stateTypeName}" was not found in sharedSchemaDocumentNode`)];
311
+ const inputSuffix = "Input";
312
+ const generatedInputDefs = generateInputTypesForObjectTree(stateTypeName, typeDefByName, inputSuffix);
313
+ const augmentedDoc = {
314
+ ...sharedSchemaDocumentNode,
315
+ definitions: [...sharedSchemaDocumentNode.definitions, ...generatedInputDefs]
316
+ };
317
+ let schema;
318
+ try {
319
+ schema = buildASTSchema(augmentedDoc, { assumeValidSDL: false });
320
+ } catch (e) {
321
+ return [new Error("Failed to build schema from SDL", { cause: e })];
322
+ }
323
+ const inputTypeName = `${stateTypeName}${inputSuffix}`;
324
+ const opDoc = parse(`query($v: ${inputTypeName}!) { __typename }`);
325
+ const op = getOperationAST(opDoc);
326
+ if (!op) return [/* @__PURE__ */ new Error("Failed to create validation operation AST")];
327
+ const { errors } = getVariableValues(schema, op.variableDefinitions ?? [], { v: stateObjectJson });
328
+ const recursiveTypeErrors = detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName);
329
+ const recursiveFieldNames = new Set(recursiveTypeErrors.map((e) => e.field));
330
+ const validationErrors = errors ? graphQLErrorsToStateValidationErrors(errors).filter((e) => {
331
+ if (e instanceof StateValidationError && e.kind === "NON_NULL") {
332
+ const rootField = e.path[0];
333
+ if (typeof rootField === "string" && recursiveFieldNames.has(rootField)) return false;
334
+ }
335
+ return true;
336
+ }) : [];
337
+ validationErrors.unshift(...recursiveTypeErrors);
338
+ const missingOptionalErrors = detectMissingOptionalFields(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateObjectJson);
339
+ validationErrors.push(...missingOptionalErrors);
340
+ return validationErrors;
341
+ }
342
+ /**
343
+ * Indexes object/input/enum/scalar/interface/union type definition nodes by name.
344
+ * Note: only AST definitions that have a "name" field are indexed.
345
+ */
346
+ function indexTypeDefinitions(doc) {
347
+ const map = /* @__PURE__ */ new Map();
348
+ for (const def of doc.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION || def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === Kind.ENUM_TYPE_DEFINITION || def.kind === Kind.SCALAR_TYPE_DEFINITION || def.kind === Kind.INTERFACE_TYPE_DEFINITION || def.kind === Kind.UNION_TYPE_DEFINITION || def.kind === Kind.OBJECT_TYPE_EXTENSION || def.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION || def.kind === Kind.ENUM_TYPE_EXTENSION || def.kind === Kind.INTERFACE_TYPE_EXTENSION || def.kind === Kind.UNION_TYPE_EXTENSION) {
349
+ const name = def.name.value;
350
+ if (!map.has(name)) map.set(name, def);
351
+ }
352
+ return map;
353
+ }
354
+ /**
355
+ * Generates InputObjectTypeDefinitionNode(s) for a root object type and any nested
356
+ * object types reachable via fields, converting object references to their *Input equivalents*.
357
+ */
358
+ function generateInputTypesForObjectTree(rootObjectTypeName, typeDefByName, inputSuffix) {
359
+ const generated = /* @__PURE__ */ new Map();
360
+ const visiting = /* @__PURE__ */ new Set();
361
+ const ensureInputForObject = (objectTypeName) => {
362
+ const inputName = `${objectTypeName}${inputSuffix}`;
363
+ if (generated.has(inputName)) return;
364
+ if (visiting.has(objectTypeName)) return;
365
+ visiting.add(objectTypeName);
366
+ const def = typeDefByName.get(objectTypeName);
367
+ if (!def) throw new GraphQLError(`Unknown referenced type "${objectTypeName}"`);
368
+ if (def.kind !== Kind.OBJECT_TYPE_DEFINITION && def.kind !== Kind.OBJECT_TYPE_EXTENSION) throw new GraphQLError(`Type "${objectTypeName}" is not an object type; cannot generate input from kind "${def.kind}"`);
369
+ const objDef = def;
370
+ const inputFields = objDef.fields?.map((f) => {
371
+ return {
372
+ kind: Kind.INPUT_VALUE_DEFINITION,
373
+ name: f.name,
374
+ description: f.description,
375
+ directives: [],
376
+ type: convertOutputTypeNodeToInputTypeNode(f.type, typeDefByName, inputSuffix, ensureInputForObject),
377
+ defaultValue: void 0
378
+ };
379
+ }) ?? [];
380
+ const inputDef = {
381
+ kind: Kind.INPUT_OBJECT_TYPE_DEFINITION,
382
+ name: {
383
+ kind: Kind.NAME,
384
+ value: inputName
385
+ },
386
+ description: objDef.description,
387
+ directives: [],
388
+ fields: inputFields
389
+ };
390
+ generated.set(inputName, inputDef);
391
+ visiting.delete(objectTypeName);
392
+ };
393
+ ensureInputForObject(rootObjectTypeName);
394
+ return Array.from(generated.values());
395
+ }
396
+ function convertOutputTypeNodeToInputTypeNode(typeNode, typeDefByName, inputSuffix, ensureInputForObject) {
397
+ switch (typeNode.kind) {
398
+ case Kind.NON_NULL_TYPE: return {
399
+ kind: Kind.NON_NULL_TYPE,
400
+ type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
401
+ };
402
+ case Kind.LIST_TYPE: return {
403
+ kind: Kind.LIST_TYPE,
404
+ type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
405
+ };
406
+ case Kind.NAMED_TYPE: {
407
+ const named = typeNode;
408
+ const name = named.name.value;
409
+ const def = typeDefByName.get(name);
410
+ if (def?.kind === Kind.OBJECT_TYPE_DEFINITION || def?.kind === Kind.OBJECT_TYPE_EXTENSION) {
411
+ ensureInputForObject(name);
412
+ return {
413
+ kind: Kind.NAMED_TYPE,
414
+ name: {
415
+ kind: Kind.NAME,
416
+ value: `${name}${inputSuffix}`
417
+ }
418
+ };
419
+ }
420
+ if (!def || def.kind === Kind.SCALAR_TYPE_DEFINITION || def.kind === Kind.ENUM_TYPE_DEFINITION || def.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === Kind.INPUT_OBJECT_TYPE_EXTENSION) return named;
421
+ if (def.kind === Kind.INTERFACE_TYPE_DEFINITION || def.kind === Kind.UNION_TYPE_DEFINITION) throw new GraphQLError(`Type "${name}" (${def.kind}) cannot be used in an input type`);
422
+ throw new GraphQLError(`Unsupported named type "${name}" of kind "${def.kind}"`);
423
+ }
424
+ default: throw new GraphQLError(`Unsupported TypeNode kind: ${JSON.stringify(typeNode)}`);
425
+ }
426
+ }
427
+ var StateValidationError = class extends Error {
428
+ payload;
429
+ originalMessage;
430
+ constructor(payload, originalMessage) {
431
+ super(payload.kind);
432
+ this.name = "StateValidationError";
433
+ this.payload = payload;
434
+ this.originalMessage = originalMessage;
435
+ Object.setPrototypeOf(this, new.target.prototype);
436
+ }
437
+ get kind() {
438
+ return this.payload.kind;
439
+ }
440
+ get path() {
441
+ return this.payload.path;
442
+ }
443
+ get field() {
444
+ return this.payload.field;
445
+ }
446
+ };
447
+ function extractInputPath(message) {
448
+ const match = message.match(/at\s+"([^"]+)"/);
449
+ if (!match) return [];
450
+ const parts = match[1].split(".").filter(Boolean);
451
+ return (parts[0] === "v" ? parts.slice(1) : parts).map((p) => /^\d+$/.test(p) ? Number(p) : p);
452
+ }
453
+ const RE_MISSING_REQUIRED_FIELD = /Field "([^"]+)" of required type "([^"]+)" was not provided\./;
454
+ const RE_UNKNOWN_FIELD = /Field "([^"]+)" is not defined by type "([^"]+)"\.(?: Did you mean "([^"]+)"\?)?/;
455
+ function extractMissingRequiredField(message) {
456
+ const m = message.match(RE_MISSING_REQUIRED_FIELD);
457
+ if (!m) return null;
458
+ return {
459
+ field: m[1],
460
+ expectedType: m[2]
461
+ };
462
+ }
463
+ function extractUnknownField(message) {
464
+ const m = message.match(RE_UNKNOWN_FIELD);
465
+ if (!m) return null;
466
+ return {
467
+ field: m[1],
468
+ typeName: m[2],
469
+ didYouMean: m[3]
470
+ };
471
+ }
472
+ function lastFieldFromPath(path) {
473
+ for (let i = path.length - 1; i >= 0; i--) if (typeof path[i] === "string") return path[i];
474
+ }
475
+ function extractExpectedType(message) {
476
+ let m = message.match(/Expected non-nullable type "([^"]+)"/);
477
+ if (m?.[1]) return m[1];
478
+ m = message.match(/Expected type "([^"]+)"/);
479
+ if (m?.[1]) return m[1];
480
+ m = message.match(/;\s*([_A-Za-z][_0-9A-Za-z]*)\s+cannot represent/i);
481
+ if (m?.[1]) return m[1];
482
+ }
483
+ function graphQLErrorsToStateValidationErrors(errors) {
484
+ const out = [];
485
+ for (const e of errors) {
486
+ const originalMessage = e.message;
487
+ const missing = extractMissingRequiredField(originalMessage);
488
+ if (missing) {
489
+ out.push(new StateValidationError({
490
+ kind: "MISSING",
491
+ path: [missing.field],
492
+ field: missing.field,
493
+ expectedType: missing.expectedType
494
+ }, originalMessage));
495
+ continue;
496
+ }
497
+ const unknown = extractUnknownField(originalMessage);
498
+ if (unknown) {
499
+ out.push(new StateValidationError({
500
+ kind: "UNKNOWN_FIELD",
501
+ path: [unknown.field],
502
+ field: unknown.field,
503
+ didYouMean: unknown.didYouMean
504
+ }, originalMessage));
505
+ continue;
506
+ }
507
+ const path = extractInputPath(originalMessage);
508
+ const field = lastFieldFromPath(path) ?? "value";
509
+ const expectedType = extractExpectedType(originalMessage);
510
+ if (originalMessage.includes("Expected non-nullable type") && originalMessage.includes("not to be null")) {
511
+ out.push(new StateValidationError({
512
+ kind: "NON_NULL",
513
+ path,
514
+ field,
515
+ expectedType
516
+ }, originalMessage));
517
+ continue;
518
+ }
519
+ if (originalMessage.includes("cannot represent") || originalMessage.includes("Expected type")) {
520
+ out.push(new StateValidationError({
521
+ kind: "TYPE",
522
+ path,
523
+ field,
524
+ expectedType,
525
+ details: originalMessage
526
+ }, originalMessage));
527
+ continue;
528
+ }
529
+ out.push(new StateValidationError({
530
+ kind: "TYPE",
531
+ path,
532
+ field,
533
+ details: originalMessage
534
+ }, originalMessage));
535
+ }
536
+ return out;
537
+ }
538
+ /**
539
+ * Finds all fields defined in the schema that are missing from the state object.
540
+ * Returns information about each missing field including whether it's required.
541
+ */
542
+ function findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value, basePath = []) {
543
+ let stateObjectJson;
544
+ try {
545
+ stateObjectJson = typeof value === "string" ? JSON.parse(value) : value;
546
+ } catch {
547
+ return [];
548
+ }
549
+ const typeByName = indexObjectTypes(sharedSchemaDocumentNode);
550
+ const missingFields = [];
551
+ for (const field of rootTypeNode.fields ?? []) {
552
+ const fieldName = field.name.value;
553
+ const fieldPath = [...basePath, fieldName];
554
+ const isRequired = field.type.kind === Kind.NON_NULL_TYPE;
555
+ const underlyingType = isRequired ? field.type.type : field.type;
556
+ if (!(fieldName in stateObjectJson)) {
557
+ missingFields.push({
558
+ fieldName,
559
+ path: fieldPath,
560
+ isRequired,
561
+ type: underlyingType
562
+ });
563
+ continue;
564
+ }
565
+ const namedType = unwrapNamedType(field.type);
566
+ const childType = namedType ? typeByName.get(namedType) : void 0;
567
+ if (childType && typeof stateObjectJson[fieldName] === "object" && stateObjectJson[fieldName] !== null && !Array.isArray(stateObjectJson[fieldName])) {
568
+ const nestedMissing = findMissingFields(sharedSchemaDocumentNode, childType, stateObjectJson[fieldName], fieldPath);
569
+ missingFields.push(...nestedMissing);
570
+ }
571
+ }
572
+ return missingFields;
573
+ }
574
+ /**
575
+ * Detects optional fields defined in the schema that are missing from the state object.
576
+ * Returns StateValidationError[] for each missing optional field.
577
+ */
578
+ function detectMissingOptionalFields(sharedSchemaDocumentNode, rootTypeNode, value) {
579
+ return findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value).filter((field) => !field.isRequired).map((field) => new StateValidationError({
580
+ kind: "MISSING_OPTIONAL",
581
+ path: field.path,
582
+ field: field.fieldName,
583
+ expectedType: typeNodeToString(field.type)
584
+ }));
585
+ }
586
+ /**
587
+ * Detects fields that have recursive types (types that reference themselves directly or indirectly).
588
+ * Returns a RECURSIVE_TYPE error for each field that contains a recursive type.
589
+ */
590
+ function detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName) {
591
+ const errors = [];
592
+ for (const field of stateTypeDefinitionNode.fields ?? []) {
593
+ const fieldName = field.name.value;
594
+ const namedTypeName = getNamedTypeName(field.type);
595
+ if (!namedTypeName) continue;
596
+ if (isRecursiveType(namedTypeName, typeDefByName, /* @__PURE__ */ new Set())) errors.push(new StateValidationError({
597
+ kind: "RECURSIVE_TYPE",
598
+ path: [fieldName],
599
+ field: fieldName,
600
+ typeName: namedTypeName
601
+ }));
602
+ }
603
+ return errors;
604
+ }
605
+ /**
606
+ * Gets the named type name from a TypeNode, unwrapping NonNull and List types.
607
+ */
608
+ function getNamedTypeName(typeNode) {
609
+ if (typeNode.kind === Kind.NAMED_TYPE) return typeNode.name.value;
610
+ if (typeNode.kind === Kind.NON_NULL_TYPE || typeNode.kind === Kind.LIST_TYPE) return getNamedTypeName(typeNode.type);
611
+ return null;
612
+ }
613
+ /**
614
+ * Checks if a type is recursive (references itself directly or indirectly through required fields).
615
+ */
616
+ function isRecursiveType(typeName, typeDefByName, visitedTypes) {
617
+ if (visitedTypes.has(typeName)) return true;
618
+ const typeDef = typeDefByName.get(typeName);
619
+ if (!typeDef || typeDef.kind !== Kind.OBJECT_TYPE_DEFINITION) return false;
620
+ visitedTypes.add(typeName);
621
+ for (const field of typeDef.fields ?? []) {
622
+ if (field.type.kind !== Kind.NON_NULL_TYPE) continue;
623
+ const innerType = field.type.type;
624
+ let fieldTypeName = null;
625
+ if (innerType.kind === Kind.NAMED_TYPE) fieldTypeName = innerType.name.value;
626
+ else if (innerType.kind === Kind.LIST_TYPE) fieldTypeName = getNamedTypeName(innerType);
627
+ if (fieldTypeName && isRecursiveType(fieldTypeName, typeDefByName, visitedTypes)) return true;
628
+ }
629
+ visitedTypes.delete(typeName);
630
+ return false;
631
+ }
632
+ /**
633
+ * Converts a TypeNode to its string representation (e.g., "String", "Int!", "[String]!")
634
+ */
635
+ function typeNodeToString(typeNode) {
636
+ switch (typeNode.kind) {
637
+ case Kind.NAMED_TYPE: return typeNode.name.value;
638
+ case Kind.NON_NULL_TYPE: return `${typeNodeToString(typeNode.type)}!`;
639
+ case Kind.LIST_TYPE: return `[${typeNodeToString(typeNode.type)}]`;
640
+ }
641
+ }
642
+ function indexObjectTypes(doc) {
643
+ const map = /* @__PURE__ */ new Map();
644
+ for (const def of doc.definitions) if (def.kind === Kind.OBJECT_TYPE_DEFINITION) map.set(def.name.value, def);
645
+ return map;
646
+ }
647
+ function unwrapNamedType(typeNode) {
648
+ if (typeNode.kind === Kind.NAMED_TYPE) return typeNode.name.value;
649
+ if (typeNode.kind === Kind.NON_NULL_TYPE) return unwrapNamedType(typeNode.type);
650
+ if (typeNode.kind === Kind.LIST_TYPE) return unwrapNamedType(typeNode.type);
651
+ }
652
+ //#endregion
653
+ //#region editors/document-model-editor/utils/linting.ts
654
+ function ensureDocumentContainsNodeWithNameAndType(doc, nodeName, nodeType) {
655
+ const parsedDoc = safeParseSdl(doc);
656
+ if (!parsedDoc) return true;
657
+ return parsedDoc.definitions.some((def) => {
658
+ return def.kind === Kind[nodeType] && "name" in def && def.name?.value === nodeName;
659
+ });
660
+ }
661
+ function createNodeTypeAndNameDiagnostic(doc, errorMessage) {
662
+ const parsedDoc = safeParseSdl(doc);
663
+ if (!parsedDoc) return void 0;
664
+ const firstNode = parsedDoc.definitions[0];
665
+ const nameNode = "name" in firstNode ? firstNode.name : null;
666
+ return {
667
+ from: nameNode?.loc?.start ?? firstNode.loc?.start ?? 0,
668
+ to: nameNode?.loc?.end ?? firstNode.loc?.end ?? 0,
669
+ severity: "error",
670
+ message: errorMessage
671
+ };
672
+ }
673
+ function ensureValidStateSchemaName(doc, modelName, scope) {
674
+ if (!safeParseSdl(doc)) return [];
675
+ const requiredTypeName = makeStateSchemaNameForScope(modelName, scope);
676
+ if (!ensureDocumentContainsNodeWithNameAndType(doc, requiredTypeName, "OBJECT_TYPE_DEFINITION")) return [createNodeTypeAndNameDiagnostic(doc, `${sentenceCase(scope)} state schema must be named ${requiredTypeName}`)].filter((d) => d !== void 0);
677
+ return [];
678
+ }
679
+ function ensureValidOperationSchemaInputName(doc, operationName) {
680
+ if (!doc || !safeParseSdl(doc)) return [];
681
+ const requiredTypeName = `${pascalCase(operationName)}Input`;
682
+ if (!ensureDocumentContainsNodeWithNameAndType(doc, requiredTypeName, "INPUT_OBJECT_TYPE_DEFINITION")) return [createNodeTypeAndNameDiagnostic(doc, `Operation schema must contain an input type named ${requiredTypeName}`)].filter((d) => d !== void 0);
683
+ return [];
684
+ }
685
+ //#endregion
686
+ //#region editors/document-model-editor/components/button.tsx
687
+ const Button = forwardRef((props, ref) => {
688
+ const { className, ...rest } = props;
689
+ return /* @__PURE__ */ jsx("button", {
690
+ ref,
691
+ ...rest,
692
+ className: twMerge("h-10 rounded-md border border-border bg-background px-4 py-2 text-sm font-medium whitespace-nowrap text-foreground transition-colors hover:hover-effect focus-visible:ring-2 focus-visible:ring-offset-2 focus-visible:outline-none disabled:disabled-effect", className)
693
+ });
694
+ });
695
+ //#endregion
696
+ //#region editors/document-model-editor/components/divider.tsx
697
+ function Divider({ className, size = "sm", margin = "md" }) {
698
+ function getSize() {
699
+ if (size === "sm") return "h-px";
700
+ if (size === "md") return "h-1";
701
+ return "h-1.5";
702
+ }
703
+ function getMargin() {
704
+ if (margin === "sm") return "my-4";
705
+ if (margin === "md") return "my-6";
706
+ return "my-8";
707
+ }
708
+ const sizeClass = getSize();
709
+ const marginClass = getMargin();
710
+ return /* @__PURE__ */ jsx("div", { className: twMerge("bg-secondary", sizeClass, marginClass, className) });
711
+ }
712
+ //#endregion
713
+ //#region editors/document-model-editor/schemas/inputs.ts
714
+ const isUppercase = (value) => !/\p{Ll}/u.test(value);
715
+ const isLowercase = (value) => !/\p{Lu}/u.test(value);
716
+ function createNameSchema(options = {}) {
717
+ const { required = false, allowEmpty = false, unique = [] } = options;
718
+ const baseSchema = allowEmpty ? z.string() : z.string().min(1);
719
+ const uniqueRefinement = baseSchema.refine((value) => {
720
+ if (!value && allowEmpty) return true;
721
+ return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
722
+ }, { message: "Item with this name already exists" });
723
+ if (!required) return unique.length > 0 ? z.string().optional().refine((value) => {
724
+ if (value === void 0) return true;
725
+ if (!value && allowEmpty) return true;
726
+ return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
727
+ }, { message: "Item with this name already exists" }) : z.string().optional();
728
+ return unique.length > 0 ? uniqueRefinement : baseSchema;
729
+ }
730
+ function createConstantCaseSchema(options = {}) {
731
+ return createNameSchema(options).transform((value) => value ? value.toUpperCase() : value).refine((value) => !value || isUppercase(value), { message: "Must be uppercase" });
732
+ }
733
+ function createLowercaseSnakeCaseSchema(options = {}) {
734
+ return createNameSchema(options).transform((value) => value ? value.toLowerCase() : value).refine((value) => !value || isLowercase(value), { message: "Must be lowercase" });
735
+ }
736
+ function toLowercaseSnakeCase(value, options = {}) {
737
+ return createLowercaseSnakeCaseSchema(options).parse(snakeCase(value));
738
+ }
739
+ function toConstantCase(value, options = {}) {
740
+ return createConstantCaseSchema(options).parse(constantCase(value));
741
+ }
742
+ z.object({
743
+ name: createNameSchema({ allowEmpty: true }),
744
+ website: z.union([z.url(), z.literal("")]).optional().default("")
745
+ }).default({
746
+ name: "",
747
+ website: ""
748
+ });
749
+ //#endregion
750
+ //#region editors/document-model-editor/context/form-context.ts
751
+ const FormFieldContext = React.createContext({});
752
+ const FormItemContext = React.createContext({});
753
+ //#endregion
754
+ //#region editors/document-model-editor/hooks/useFormField.ts
755
+ const useFormField = () => {
756
+ const fieldContext = React.useContext(FormFieldContext);
757
+ const itemContext = React.useContext(FormItemContext);
758
+ const { getFieldState, formState } = useFormContext();
759
+ const fieldState = getFieldState(fieldContext.name, formState);
760
+ if (!fieldContext) throw new Error("useFormField should be used within <FormField>");
761
+ const { id } = itemContext;
762
+ return {
763
+ id,
764
+ name: fieldContext.name,
765
+ formItemId: `${id}-form-item`,
766
+ formDescriptionId: `${id}-form-item-description`,
767
+ formMessageId: `${id}-form-item-message`,
768
+ ...fieldState
769
+ };
770
+ };
771
+ //#endregion
772
+ //#region editors/document-model-editor/components/label.tsx
773
+ const labelVariants = cva("text-sm leading-none font-medium peer-disabled:disabled-effect");
774
+ const Label = React$1.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(LabelPrimitive.Root, {
775
+ ref,
776
+ className: twMerge(labelVariants(), className),
777
+ ...props
778
+ }));
779
+ Label.displayName = LabelPrimitive.Root.displayName;
780
+ //#endregion
781
+ //#region editors/document-model-editor/components/form.tsx
782
+ const Form = FormProvider;
783
+ const FormField = ({ ...props }) => {
784
+ return /* @__PURE__ */ jsx(FormFieldContext.Provider, {
785
+ value: { name: props.name },
786
+ children: /* @__PURE__ */ jsx(Controller, { ...props })
787
+ });
788
+ };
789
+ const FormItem = React$1.forwardRef(({ className, ...props }, ref) => {
790
+ const id = React$1.useId();
791
+ return /* @__PURE__ */ jsx(FormItemContext.Provider, {
792
+ value: { id },
793
+ children: /* @__PURE__ */ jsx("div", {
794
+ ref,
795
+ className,
796
+ ...props
797
+ })
798
+ });
799
+ });
800
+ FormItem.displayName = "FormItem";
801
+ const FormLabel = React$1.forwardRef(({ className, ...props }, ref) => {
802
+ const { error, formItemId } = useFormField();
803
+ return /* @__PURE__ */ jsx(Label, {
804
+ ref,
805
+ className: twMerge(error && "text-destructive", className),
806
+ htmlFor: formItemId,
807
+ ...props
808
+ });
809
+ });
810
+ FormLabel.displayName = "FormLabel";
811
+ const FormControl = React$1.forwardRef(({ ...props }, ref) => {
812
+ const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
813
+ return /* @__PURE__ */ jsx(Slot, {
814
+ ref,
815
+ id: formItemId,
816
+ "aria-describedby": !error ? formDescriptionId : `${formDescriptionId} ${formMessageId}`,
817
+ "aria-invalid": !!error,
818
+ ...props
819
+ });
820
+ });
821
+ FormControl.displayName = "FormControl";
822
+ const FormDescription = React$1.forwardRef(({ className, ...props }, ref) => {
823
+ const { formDescriptionId } = useFormField();
824
+ return /* @__PURE__ */ jsx("p", {
825
+ ref,
826
+ id: formDescriptionId,
827
+ className: twMerge("text-sm text-foreground", className),
828
+ ...props
829
+ });
830
+ });
831
+ FormDescription.displayName = "FormDescription";
832
+ const FormMessage = React$1.forwardRef(({ className, children, ...props }, ref) => {
833
+ const { error, formMessageId } = useFormField();
834
+ const body = error ? String(error.message) : children;
835
+ if (!body) return null;
836
+ return /* @__PURE__ */ jsx("p", {
837
+ ref,
838
+ id: formMessageId,
839
+ className: twMerge("text-sm font-medium text-destructive", className),
840
+ ...props,
841
+ children: body
842
+ });
843
+ });
844
+ FormMessage.displayName = "FormMessage";
845
+ //#endregion
846
+ //#region editors/document-model-editor/components/text-area.tsx
847
+ const Textarea = forwardRef(({ className, ...props }, ref) => {
848
+ const textareaRef = useRef(null);
849
+ const adjustHeight = useCallback((textarea) => {
850
+ textarea.style.height = "auto";
851
+ const newHeight = Math.max(textarea.scrollHeight, textarea.offsetHeight);
852
+ textarea.style.height = `${newHeight}px`;
853
+ }, []);
854
+ const handleInput = useCallback((e) => {
855
+ adjustHeight(e.currentTarget);
856
+ }, [adjustHeight]);
857
+ React$1.useEffect(() => {
858
+ if (textareaRef.current) adjustHeight(textareaRef.current);
859
+ }, [adjustHeight]);
860
+ useImperativeHandle(ref, () => ({
861
+ focus: () => textareaRef.current?.focus(),
862
+ element: textareaRef.current
863
+ }));
864
+ return /* @__PURE__ */ jsx("textarea", {
865
+ ...props,
866
+ className: twMerge("min-h-10 w-full resize-none rounded-md border border-border bg-background px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none disabled:disabled-effect", className),
867
+ ref: textareaRef,
868
+ onInput: handleInput
869
+ });
870
+ });
871
+ Textarea.displayName = "Textarea";
872
+ //#endregion
873
+ //#region editors/document-model-editor/components/text-field.tsx
874
+ const TextField = forwardRef(({ name, value, onSubmit, label, placeholder, unique, className = "", rows = 1, focusOnMount = false, required = false, allowEmpty = false, shouldReset = false, onChange }, ref) => {
875
+ const textareaRef = useRef(null);
876
+ const id = useId();
877
+ useEffect(() => {
878
+ if (focusOnMount && textareaRef.current) textareaRef.current.focus();
879
+ }, [focusOnMount]);
880
+ const fieldSchema = z.object({ [name]: createNameSchema({
881
+ required,
882
+ allowEmpty,
883
+ unique
884
+ }) });
885
+ const form = useForm({
886
+ resolver: zodResolver(fieldSchema),
887
+ defaultValues: { [name]: value ?? "" }
888
+ });
889
+ const handleSubmit = useCallback((values) => {
890
+ const newValue = values[name];
891
+ if (newValue === void 0 || value === newValue) return;
892
+ onSubmit(newValue);
893
+ if (shouldReset) form.reset({ [name]: "" });
894
+ }, [
895
+ name,
896
+ value,
897
+ onSubmit,
898
+ form,
899
+ shouldReset
900
+ ]);
901
+ const handleBlur = useCallback(async () => {
902
+ const currentValue = form.getValues()[name] ?? "";
903
+ if (value === null || value === void 0) {
904
+ if (!currentValue || currentValue.trim() === "") return;
905
+ }
906
+ if (compareStringsWithoutWhitespace(currentValue, value ?? "")) return;
907
+ try {
908
+ await form.trigger();
909
+ if (form.formState.isValid) await form.handleSubmit(handleSubmit)();
910
+ } catch (_e) {}
911
+ }, [
912
+ form,
913
+ handleSubmit,
914
+ name,
915
+ value
916
+ ]);
917
+ const onEnterKeyDown = useCallback((e) => {
918
+ if (e.key === "Enter") {
919
+ e.preventDefault();
920
+ e.target.blur();
921
+ }
922
+ }, []);
923
+ const handleChange = useCallback((e) => {
924
+ const newValue = e.target.value;
925
+ onChange?.(newValue);
926
+ }, [onChange]);
927
+ useImperativeHandle(ref, () => ({ focus: () => textareaRef.current?.focus() }));
928
+ useEffect(() => {
929
+ form.reset({ [name]: value ?? "" });
930
+ }, [
931
+ form,
932
+ name,
933
+ value
934
+ ]);
935
+ return /* @__PURE__ */ jsx(Form, {
936
+ ...form,
937
+ children: /* @__PURE__ */ jsx(FormField, {
938
+ control: form.control,
939
+ name,
940
+ render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, {
941
+ className: "grid h-full grid-rows-[auto,1fr] gap-2 overflow-visible",
942
+ children: [
943
+ !!label && /* @__PURE__ */ jsx(FormLabel, {
944
+ htmlFor: name,
945
+ className: "text-sm font-medium text-foreground",
946
+ children: label
947
+ }),
948
+ /* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Textarea, {
949
+ ...field,
950
+ id,
951
+ name,
952
+ ref: (node) => {
953
+ if (node) {
954
+ field.ref(node.element);
955
+ textareaRef.current = node;
956
+ }
957
+ },
958
+ placeholder,
959
+ onBlur: () => void handleBlur(),
960
+ onChange: (e) => {
961
+ field.onChange(e);
962
+ handleChange(e);
963
+ },
964
+ onKeyDown: onEnterKeyDown,
965
+ rows,
966
+ className
967
+ }) }),
968
+ /* @__PURE__ */ jsx(FormMessage, {})
969
+ ]
970
+ })
971
+ })
972
+ });
973
+ });
974
+ TextField.displayName = "TextField";
975
+ z.object({
976
+ name: z.string(),
977
+ documentType: z.string(),
978
+ extension: z.string().optional().default(""),
979
+ description: z.string(),
980
+ authorName: z.string(),
981
+ authorWebsite: z.string()
982
+ });
983
+ function ModelMetadata(props) {
984
+ return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(ModelNameForm, { ...props }), /* @__PURE__ */ jsx("div", {
985
+ className: "flex h-full flex-col gap-4",
986
+ children: /* @__PURE__ */ jsxs("div", {
987
+ className: "grid flex-1 grid-cols-3 items-start gap-4",
988
+ children: [/* @__PURE__ */ jsxs("div", {
989
+ className: "col-span-2 flex h-full flex-col gap-4",
990
+ children: [/* @__PURE__ */ jsx("div", {
991
+ className: "shrink-0",
992
+ children: /* @__PURE__ */ jsx(DocumentTypeForm, { ...props })
993
+ }), /* @__PURE__ */ jsx("div", {
994
+ className: "min-h-0 flex-1",
995
+ children: /* @__PURE__ */ jsx(DescriptionForm, { ...props })
996
+ })]
997
+ }), /* @__PURE__ */ jsxs("div", {
998
+ className: "col-span-1 flex flex-col gap-4",
999
+ children: [
1000
+ /* @__PURE__ */ jsx(AuthorNameForm, { ...props }),
1001
+ /* @__PURE__ */ jsx(AuthorWebsiteForm, { ...props }),
1002
+ /* @__PURE__ */ jsx(ModelExtensionForm, { ...props })
1003
+ ]
1004
+ })]
1005
+ })
1006
+ })] });
1007
+ }
1008
+ function ModelNameForm(props) {
1009
+ const { name, globalStateSchema, localStateSchema, setModelName, setStateSchema } = props;
1010
+ const onSubmit = useCallback((newName) => {
1011
+ if (name === newName) return;
1012
+ setModelName(newName);
1013
+ if (!!!globalStateSchema) {
1014
+ const initialSchemaDoc = makeInitialSchemaDoc(newName, "global");
1015
+ setStateSchema(initialSchemaDoc, "global");
1016
+ return;
1017
+ }
1018
+ const newSchema = renameSchemaType(globalStateSchema, name, newName, "global");
1019
+ setStateSchema(newSchema, "global");
1020
+ if (localStateSchema) {
1021
+ const newLocalStateSchema = renameSchemaType(localStateSchema, name, newName, "local");
1022
+ setStateSchema(newLocalStateSchema, "local");
1023
+ }
1024
+ handleModelNameChange({
1025
+ oldName: name,
1026
+ newName,
1027
+ globalStateSchema,
1028
+ localStateSchema,
1029
+ setStateSchema
1030
+ });
1031
+ }, [
1032
+ name,
1033
+ globalStateSchema,
1034
+ localStateSchema,
1035
+ setStateSchema,
1036
+ setModelName
1037
+ ]);
1038
+ return /* @__PURE__ */ jsx(TextField, {
1039
+ name: "name",
1040
+ value: name,
1041
+ onSubmit,
1042
+ placeholder: "Model name",
1043
+ className: "border-none pl-0 text-xl font-bold text-foreground",
1044
+ required: true,
1045
+ focusOnMount: true
1046
+ });
1047
+ }
1048
+ function DocumentTypeForm(props) {
1049
+ const { documentType, setModelId } = props;
1050
+ return /* @__PURE__ */ jsx(TextField, {
1051
+ label: "Document Type *",
1052
+ name: "powerhouse/document-model",
1053
+ value: documentType,
1054
+ onSubmit: setModelId,
1055
+ placeholder: "Document Type",
1056
+ required: true
1057
+ });
1058
+ }
1059
+ function ModelExtensionForm(props) {
1060
+ const { extension, setModelExtension } = props;
1061
+ return /* @__PURE__ */ jsx(TextField, {
1062
+ name: "extension",
1063
+ value: extension,
1064
+ onSubmit: setModelExtension,
1065
+ label: "Model Extension",
1066
+ placeholder: "Example .phdm",
1067
+ allowEmpty: true
1068
+ });
1069
+ }
1070
+ function DescriptionForm(props) {
1071
+ const { description, setModelDescription } = props;
1072
+ return /* @__PURE__ */ jsx(TextField, {
1073
+ name: "description",
1074
+ label: "Model Description",
1075
+ value: description,
1076
+ onSubmit: setModelDescription,
1077
+ placeholder: "Describe your document to others",
1078
+ allowEmpty: true,
1079
+ className: "h-full"
1080
+ });
1081
+ }
1082
+ function AuthorNameForm(props) {
1083
+ const { authorName, setAuthorName } = props;
1084
+ return /* @__PURE__ */ jsx(TextField, {
1085
+ name: "authorName",
1086
+ value: authorName,
1087
+ onSubmit: setAuthorName,
1088
+ label: "Author Name",
1089
+ placeholder: "Username or organisation",
1090
+ allowEmpty: true
1091
+ });
1092
+ }
1093
+ function AuthorWebsiteForm(props) {
1094
+ const { authorWebsite, setAuthorWebsite } = props;
1095
+ return /* @__PURE__ */ jsx(TextField, {
1096
+ name: "authorWebsite",
1097
+ value: authorWebsite,
1098
+ label: "Website URL",
1099
+ onSubmit: (newAuthorWebsite) => {
1100
+ if (!!authorWebsite && !newAuthorWebsite) return;
1101
+ setAuthorWebsite(newAuthorWebsite);
1102
+ },
1103
+ placeholder: "https://www.powerhouse.inc/",
1104
+ allowEmpty: true
1105
+ });
1106
+ }
1107
+ //#endregion
1108
+ //#region editors/document-model-editor/components/module-form.tsx
1109
+ function ModuleForm({ module, onAddModule, updateModuleName, modules = [] }) {
1110
+ const isEdit = !!module;
1111
+ const moduleNames = modules.map((m) => m.name);
1112
+ const handleSubmit = async (name) => {
1113
+ const formattedName = toLowercaseSnakeCase(name);
1114
+ if (!formattedName.length) return;
1115
+ if (isEdit) {
1116
+ if (formattedName !== module.name) updateModuleName(module.id, formattedName);
1117
+ } else await onAddModule(formattedName);
1118
+ };
1119
+ return /* @__PURE__ */ jsx(TextField, {
1120
+ name: "name",
1121
+ label: isEdit ? "Module name *" : "Add module *",
1122
+ value: module?.name,
1123
+ onSubmit: (name) => void handleSubmit(name),
1124
+ placeholder: "Add module",
1125
+ unique: moduleNames,
1126
+ shouldReset: !isEdit,
1127
+ required: true
1128
+ }, module?.id ?? "new");
1129
+ }
1130
+ //#endregion
1131
+ //#region editors/document-model-editor/components/operation-form.tsx
1132
+ function OperationForm({ operation, module, focusOnMount, allOperationNames, onAddOperationAndInitialSchema, updateOperationName, deleteOperation }) {
1133
+ const isEdit = !!operation;
1134
+ const handleSubmit = async (name) => {
1135
+ if (isEdit && name === "") {
1136
+ deleteOperation(operation.id);
1137
+ return;
1138
+ }
1139
+ const formattedName = toConstantCase(name);
1140
+ if (isEdit) {
1141
+ if (formattedName !== operation.name) updateOperationName(operation.id, formattedName);
1142
+ } else await onAddOperationAndInitialSchema(module.id, formattedName);
1143
+ };
1144
+ const handleChange = (value) => {
1145
+ if (isEdit && value === "") deleteOperation(operation.id);
1146
+ };
1147
+ return /* @__PURE__ */ jsx(TextField, {
1148
+ name: "name",
1149
+ value: operation?.name,
1150
+ label: isEdit ? "Operation name *" : "Add operation *",
1151
+ onSubmit: (name) => void handleSubmit(name),
1152
+ onChange: handleChange,
1153
+ placeholder: "Add operation",
1154
+ required: !isEdit,
1155
+ allowEmpty: !isEdit,
1156
+ shouldReset: !isEdit,
1157
+ focusOnMount,
1158
+ unique: allOperationNames
1159
+ });
1160
+ }
1161
+ //#endregion
1162
+ //#region editors/document-model-editor/components/operation-description-form.tsx
1163
+ function OperationDescriptionForm({ operation, focusOnMount, setOperationDescription }) {
1164
+ const textFieldRef = useRef(null);
1165
+ useEffect(() => {
1166
+ if (focusOnMount && textFieldRef.current) textFieldRef.current.focus();
1167
+ }, [focusOnMount]);
1168
+ return /* @__PURE__ */ jsx(TextField, {
1169
+ ref: textFieldRef,
1170
+ name: "description",
1171
+ value: operation.description,
1172
+ onSubmit: (newDescription) => setOperationDescription(operation.id, newDescription),
1173
+ label: "Operation description",
1174
+ allowEmpty: true,
1175
+ placeholder: "Operation Description"
1176
+ });
1177
+ }
1178
+ //#endregion
1179
+ //#region editors/document-model-editor/components/operation-error-form.tsx
1180
+ function OperationErrorForm({ operation, error, focusOnMount, onSubmit, onAddOperationError, deleteOperationError, setOperationErrorName }) {
1181
+ const textFieldRef = useRef(null);
1182
+ const isEdit = !!error;
1183
+ const allOperationErrorNames = operation.errors.map((o) => o.name).filter((n) => n !== null);
1184
+ const handleSubmit = (name) => {
1185
+ if (isEdit && name === "") {
1186
+ deleteOperationError(error.id);
1187
+ return;
1188
+ }
1189
+ const formattedName = pascalCase(name);
1190
+ if (isEdit) setOperationErrorName(operation.id, error.id, formattedName);
1191
+ else onAddOperationError(operation.id, formattedName);
1192
+ onSubmit?.();
1193
+ };
1194
+ const handleChange = (value) => {
1195
+ if (isEdit && value === "") deleteOperationError(error.id);
1196
+ };
1197
+ return /* @__PURE__ */ jsx(TextField, {
1198
+ ref: textFieldRef,
1199
+ name: "name",
1200
+ value: error?.name,
1201
+ onSubmit: handleSubmit,
1202
+ onChange: handleChange,
1203
+ placeholder: "Add exception",
1204
+ required: !isEdit,
1205
+ allowEmpty: !isEdit,
1206
+ shouldReset: !isEdit,
1207
+ unique: allOperationErrorNames,
1208
+ focusOnMount
1209
+ });
1210
+ }
1211
+ //#endregion
1212
+ //#region editors/document-model-editor/components/operation-errors.tsx
1213
+ function OperationErrors({ operation, addOperationError, deleteOperationError, setOperationErrorName }) {
1214
+ const addErrorFormId = useId();
1215
+ const [shouldFocusAddForm, setShouldFocusAddForm] = useState(false);
1216
+ const onAddOperationError = useCallback(async (operationId, error) => {
1217
+ const errorId = await addOperationError(operationId, error);
1218
+ if (errorId) setShouldFocusAddForm(true);
1219
+ return errorId;
1220
+ }, [addOperationError, setShouldFocusAddForm]);
1221
+ const onAddOperationErrorSubmit = useCallback(() => setShouldFocusAddForm(false), [setShouldFocusAddForm]);
1222
+ return /* @__PURE__ */ jsxs("ul", {
1223
+ className: "ml-4 list-disc",
1224
+ children: [operation.errors.map((error) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
1225
+ error,
1226
+ operation,
1227
+ onAddOperationError,
1228
+ deleteOperationError,
1229
+ setOperationErrorName
1230
+ }) }, error.id)), /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
1231
+ operation,
1232
+ onAddOperationError,
1233
+ deleteOperationError,
1234
+ setOperationErrorName,
1235
+ focusOnMount: shouldFocusAddForm,
1236
+ onSubmit: onAddOperationErrorSubmit
1237
+ }, `${addErrorFormId}-${shouldFocusAddForm}`) })]
1238
+ });
1239
+ }
1240
+ //#endregion
1241
+ //#region editors/document-model-editor/components/operation.tsx
1242
+ const GraphqlEditor = lazy(() => import("./graphql-editor-CGxwONKl.js"));
1243
+ function Operation(props) {
1244
+ const { operation, module, allOperationNames, lastCreatedOperationId, onAddOperationAndInitialSchema, updateOperationName, deleteOperation, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
1245
+ const noInputRequired = isEmptyOperationSchema(operation.schema);
1246
+ const handleToggleNoInput = useCallback((checked) => toggleNoInputRequired(operation.id, checked), [operation.id, toggleNoInputRequired]);
1247
+ const handleUpdateDocument = useCallback((newDoc) => updateOperationSchema(operation.id, newDoc), [operation.id, updateOperationSchema]);
1248
+ const customLinter = useCallback((doc) => operation.name ? ensureValidOperationSchemaInputName(doc, operation.name) : [], [operation.name]);
1249
+ return /* @__PURE__ */ jsxs("div", {
1250
+ className: "mt-4 grid grid-cols-2 gap-x-12",
1251
+ style: {
1252
+ gridTemplateAreas: `
1253
+ "left editor"
1254
+ "errors editor"
1255
+ `,
1256
+ gridTemplateRows: "auto 1fr"
1257
+ },
1258
+ children: [
1259
+ /* @__PURE__ */ jsxs("div", {
1260
+ className: "flex flex-col gap-2",
1261
+ style: { gridArea: "left" },
1262
+ children: [/* @__PURE__ */ jsx(OperationForm, {
1263
+ operation,
1264
+ onAddOperationAndInitialSchema,
1265
+ updateOperationName,
1266
+ deleteOperation,
1267
+ module,
1268
+ allOperationNames
1269
+ }), /* @__PURE__ */ jsx(OperationDescriptionForm, {
1270
+ operation,
1271
+ focusOnMount: operation.id === lastCreatedOperationId,
1272
+ setOperationDescription
1273
+ })]
1274
+ }),
1275
+ /* @__PURE__ */ jsxs("div", {
1276
+ className: "relative top-8",
1277
+ style: { gridArea: "editor" },
1278
+ children: [/* @__PURE__ */ jsxs("label", {
1279
+ className: "mb-2 flex cursor-pointer items-center gap-2",
1280
+ children: [/* @__PURE__ */ jsx("input", {
1281
+ type: "checkbox",
1282
+ checked: noInputRequired,
1283
+ onChange: (e) => handleToggleNoInput(e.target.checked),
1284
+ className: "size-4 rounded-sm border-border"
1285
+ }), /* @__PURE__ */ jsx("span", {
1286
+ className: "text-sm text-foreground",
1287
+ children: "Operation with no inputs"
1288
+ })]
1289
+ }), !noInputRequired && /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(GraphqlEditor, {
1290
+ doc: operation.schema ?? "",
1291
+ updateDocumentInModel: handleUpdateDocument,
1292
+ customLinter
1293
+ }) })]
1294
+ }),
1295
+ /* @__PURE__ */ jsxs("div", {
1296
+ style: { gridArea: "errors" },
1297
+ children: [/* @__PURE__ */ jsx("h3", {
1298
+ className: "my-2 text-sm font-medium text-foreground",
1299
+ children: "Reducer Exceptions"
1300
+ }), /* @__PURE__ */ jsx(OperationErrors, {
1301
+ operation,
1302
+ addOperationError,
1303
+ deleteOperationError,
1304
+ setOperationErrorName
1305
+ })]
1306
+ })
1307
+ ]
1308
+ });
1309
+ }
1310
+ //#endregion
1311
+ //#region editors/document-model-editor/components/operations.tsx
1312
+ function Operations({ module, allOperations, shouldFocusNewOperation, updateOperationName, deleteOperation, addOperationAndInitialSchema, addOperationError, deleteOperationError, setOperationErrorName, updateOperationSchema, setOperationDescription, toggleNoInputRequired }) {
1313
+ const [lastCreatedOperationId, setLastCreatedOperationId] = useState(null);
1314
+ const addOperationFormId = useId();
1315
+ const allOperationNames = allOperations.map((o) => o.name).filter((n) => n !== null);
1316
+ const onAddOperationAndInitialSchema = useCallback(async (moduleId, name) => {
1317
+ const operationId = await addOperationAndInitialSchema(moduleId, name);
1318
+ if (operationId) setLastCreatedOperationId(operationId);
1319
+ return operationId;
1320
+ }, [addOperationAndInitialSchema, setLastCreatedOperationId]);
1321
+ return /* @__PURE__ */ jsxs("div", { children: [module.operations.map((operation) => /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Operation, {
1322
+ operation,
1323
+ module,
1324
+ lastCreatedOperationId,
1325
+ allOperationNames,
1326
+ addOperationError,
1327
+ deleteOperationError,
1328
+ setOperationErrorName,
1329
+ onAddOperationAndInitialSchema,
1330
+ updateOperationName,
1331
+ deleteOperation,
1332
+ updateOperationSchema,
1333
+ setOperationDescription,
1334
+ toggleNoInputRequired
1335
+ }) }, operation.id)), /* @__PURE__ */ jsx("div", {
1336
+ className: "mt-6 w-1/2 pr-6",
1337
+ children: /* @__PURE__ */ jsx(OperationForm, {
1338
+ onAddOperationAndInitialSchema,
1339
+ updateOperationName,
1340
+ deleteOperation,
1341
+ module,
1342
+ allOperationNames,
1343
+ focusOnMount: shouldFocusNewOperation
1344
+ }, addOperationFormId)
1345
+ })] });
1346
+ }
1347
+ //#endregion
1348
+ //#region editors/document-model-editor/components/module.tsx
1349
+ function Module(props) {
1350
+ const { module, modules, allOperations, lastCreatedModuleId, onAddModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
1351
+ return /* @__PURE__ */ jsxs("div", {
1352
+ className: "relative rounded-3xl bg-muted p-6",
1353
+ children: [/* @__PURE__ */ jsxs("div", {
1354
+ className: "mb-2 w-1/2 pr-6",
1355
+ children: [/* @__PURE__ */ jsx(ModuleForm, {
1356
+ modules,
1357
+ module,
1358
+ onAddModule,
1359
+ updateModuleName
1360
+ }), !!module && /* @__PURE__ */ jsx("button", {
1361
+ "aria-label": "Delete module",
1362
+ tabIndex: -1,
1363
+ className: "absolute top-1 right-1 p-2 text-foreground transition-colors hover:hover-effect",
1364
+ onClick: () => {
1365
+ deleteModule(module.id);
1366
+ },
1367
+ children: /* @__PURE__ */ jsx("svg", {
1368
+ className: "size-6",
1369
+ viewBox: "0 0 24 24",
1370
+ fill: "currentcolor",
1371
+ children: /* @__PURE__ */ jsx("path", {
1372
+ fillRule: "evenodd",
1373
+ clipRule: "evenodd",
1374
+ d: "M16.9993 8.51506L15.4844 7L11.9994 10.4852L8.51497 7.00057L7 8.51562L10.4844 12.0003L7.00056 15.4843L8.51552 16.9994L11.9994 13.5153L15.4838 17L16.9988 15.4849L13.5144 12.0003L16.9993 8.51506Z"
1375
+ })
1376
+ })
1377
+ })]
1378
+ }), !!module && /* @__PURE__ */ jsx(Operations, {
1379
+ module,
1380
+ allOperations,
1381
+ shouldFocusNewOperation: module.id === lastCreatedModuleId,
1382
+ updateOperationName,
1383
+ deleteOperation,
1384
+ addOperationAndInitialSchema,
1385
+ updateOperationSchema,
1386
+ setOperationDescription,
1387
+ addOperationError,
1388
+ deleteOperationError,
1389
+ setOperationErrorName,
1390
+ toggleNoInputRequired
1391
+ })]
1392
+ });
1393
+ }
1394
+ //#endregion
1395
+ //#region editors/document-model-editor/components/modules.tsx
1396
+ function Modules({ modules, allOperations, addModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired }) {
1397
+ const [lastCreatedModuleId, setLastCreatedModuleId] = useState(null);
1398
+ const focusTrapRef = useRef(null);
1399
+ const onAddModule = useCallback(async (name) => {
1400
+ const moduleId = await addModule(name);
1401
+ if (moduleId) {
1402
+ setLastCreatedModuleId(moduleId);
1403
+ focusTrapRef.current?.focus();
1404
+ }
1405
+ return moduleId;
1406
+ }, [addModule, setLastCreatedModuleId]);
1407
+ return /* @__PURE__ */ jsxs("div", {
1408
+ className: "flex flex-col gap-2",
1409
+ children: [
1410
+ modules.map((module) => /* @__PURE__ */ jsx(Module, {
1411
+ module,
1412
+ modules,
1413
+ allOperations,
1414
+ lastCreatedModuleId,
1415
+ onAddModule,
1416
+ updateModuleName,
1417
+ deleteModule,
1418
+ updateOperationName,
1419
+ deleteOperation,
1420
+ addOperationAndInitialSchema,
1421
+ updateOperationSchema,
1422
+ setOperationDescription,
1423
+ addOperationError,
1424
+ deleteOperationError,
1425
+ setOperationErrorName,
1426
+ toggleNoInputRequired
1427
+ }, module.id)),
1428
+ /* @__PURE__ */ jsx(Module, {
1429
+ modules,
1430
+ allOperations,
1431
+ lastCreatedModuleId,
1432
+ onAddModule,
1433
+ updateModuleName,
1434
+ deleteModule,
1435
+ updateOperationName,
1436
+ deleteOperation,
1437
+ addOperationAndInitialSchema,
1438
+ updateOperationSchema,
1439
+ setOperationDescription,
1440
+ addOperationError,
1441
+ deleteOperationError,
1442
+ setOperationErrorName,
1443
+ toggleNoInputRequired
1444
+ }, "add-module"),
1445
+ /* @__PURE__ */ jsx("div", {
1446
+ ref: focusTrapRef,
1447
+ tabIndex: 0,
1448
+ className: "size-0 overflow-hidden",
1449
+ "aria-hidden": "true"
1450
+ })
1451
+ ]
1452
+ });
1453
+ }
1454
+ //#endregion
1455
+ //#region editors/document-model-editor/components/version-controls.tsx
1456
+ const compactButtonStyle$1 = "min-h-0 min-w-0 flex-none rounded-lg px-6 py-1.5 text-sm whitespace-nowrap";
1457
+ function VersionControls(props) {
1458
+ const { specifications, viewedVersion, onViewVersion, onReleaseNewVersion } = props;
1459
+ const [showReleaseModal, setShowReleaseModal] = useState(false);
1460
+ const latestVersion = specifications[specifications.length - 1].version;
1461
+ const nextVersion = latestVersion + 1;
1462
+ return /* @__PURE__ */ jsxs("div", {
1463
+ className: "mb-4 flex items-center justify-between gap-4",
1464
+ children: [
1465
+ /* @__PURE__ */ jsxs("div", {
1466
+ className: "flex items-center gap-2",
1467
+ children: [/* @__PURE__ */ jsxs("span", {
1468
+ className: "rounded-md bg-muted px-2 py-0.5 font-mono text-xs text-foreground",
1469
+ "data-testid": "model-version-badge",
1470
+ children: ["Version ", viewedVersion]
1471
+ }), specifications.length >= 2 && /* @__PURE__ */ jsx("div", {
1472
+ "aria-label": "Document model version",
1473
+ "data-testid": "model-version-switcher",
1474
+ children: /* @__PURE__ */ jsx(ConnectSelect, {
1475
+ absolutePositionMenu: true,
1476
+ containerClassName: "z-10 [&_svg]:size-4",
1477
+ id: "model-version-switcher",
1478
+ itemClassName: "gap-1 px-2 py-1 font-mono text-xs leading-none [&_p:empty]:hidden",
1479
+ items: specifications.map((spec) => ({
1480
+ value: String(spec.version),
1481
+ displayValue: /* @__PURE__ */ jsx("span", {
1482
+ className: "normal-case",
1483
+ children: spec.version === latestVersion ? `v${spec.version} (latest)` : `v${spec.version} (frozen)`
1484
+ })
1485
+ })),
1486
+ listClassName: "border border-t-0 border-border shadow-md",
1487
+ menuClassName: "min-w-0 pr-1.5",
1488
+ onChange: (value) => {
1489
+ const version = Number(value);
1490
+ onViewVersion(version === latestVersion ? "latest" : version);
1491
+ },
1492
+ value: String(viewedVersion)
1493
+ })
1494
+ })]
1495
+ }),
1496
+ /* @__PURE__ */ jsx(Button, {
1497
+ className: "inline-flex h-8 items-center justify-center py-0",
1498
+ "data-testid": "release-new-version-button",
1499
+ onClick: () => setShowReleaseModal(true),
1500
+ type: "button",
1501
+ children: "Release new version"
1502
+ }),
1503
+ /* @__PURE__ */ jsx(Modal, {
1504
+ open: showReleaseModal,
1505
+ onOpenChange: (status) => {
1506
+ if (!status) setShowReleaseModal(false);
1507
+ },
1508
+ children: /* @__PURE__ */ jsxs("div", {
1509
+ className: "w-[440px] p-6",
1510
+ children: [
1511
+ /* @__PURE__ */ jsxs("div", {
1512
+ className: "pb-2 text-2xl font-bold text-foreground",
1513
+ children: ["Release version ", nextVersion]
1514
+ }),
1515
+ /* @__PURE__ */ jsxs("div", {
1516
+ className: "my-4 rounded-md bg-background p-4 text-left text-sm text-foreground",
1517
+ children: [/* @__PURE__ */ jsxs("p", { children: [
1518
+ "Version ",
1519
+ latestVersion,
1520
+ " will be frozen as-is. Version",
1521
+ " ",
1522
+ nextVersion,
1523
+ " starts as an identical copy, and all further edits apply to version ",
1524
+ nextVersion,
1525
+ "."
1526
+ ] }), /* @__PURE__ */ jsxs("p", {
1527
+ className: "mt-3",
1528
+ children: [
1529
+ "Existing version ",
1530
+ latestVersion,
1531
+ " documents will be upgradeable once you define the migration."
1532
+ ]
1533
+ })]
1534
+ }),
1535
+ /* @__PURE__ */ jsxs("div", {
1536
+ className: "mt-4 flex justify-between gap-3",
1537
+ children: [/* @__PURE__ */ jsx(ModalButton, {
1538
+ className: compactButtonStyle$1,
1539
+ onClick: () => setShowReleaseModal(false),
1540
+ variant: "cancel",
1541
+ children: "Cancel"
1542
+ }), /* @__PURE__ */ jsxs(ModalButton, {
1543
+ className: compactButtonStyle$1,
1544
+ "data-testid": "confirm-release-button",
1545
+ onClick: () => {
1546
+ setShowReleaseModal(false);
1547
+ onReleaseNewVersion();
1548
+ },
1549
+ variant: "confirm",
1550
+ children: ["Release version ", nextVersion]
1551
+ })]
1552
+ })
1553
+ ]
1554
+ })
1555
+ })
1556
+ ]
1557
+ });
1558
+ }
1559
+ function FrozenVersionBanner(props) {
1560
+ const { viewedVersion, latestVersion } = props;
1561
+ return /* @__PURE__ */ jsxs("div", {
1562
+ className: "mb-4 rounded-md border border-border bg-muted p-3 text-sm text-foreground",
1563
+ "data-testid": "frozen-version-banner",
1564
+ children: [
1565
+ "Version ",
1566
+ viewedVersion,
1567
+ " is frozen. You're viewing it read-only. Edits go to version ",
1568
+ latestVersion,
1569
+ "."
1570
+ ]
1571
+ });
1572
+ }
1573
+ //#endregion
1574
+ //#region editors/document-model-editor/components/version-advisory-modal.tsx
1575
+ const compactButtonStyle = "min-h-0 min-w-0 flex-none rounded-lg px-4 py-1.5 text-sm whitespace-nowrap";
1576
+ function FieldDiffList(props) {
1577
+ const { label, fields } = props;
1578
+ if (fields.length === 0) return null;
1579
+ return /* @__PURE__ */ jsxs("div", {
1580
+ className: "mt-3",
1581
+ children: [/* @__PURE__ */ jsx("p", {
1582
+ className: "mb-1.5",
1583
+ children: label
1584
+ }), /* @__PURE__ */ jsx("div", {
1585
+ className: "flex flex-col items-start gap-1",
1586
+ children: fields.map((field) => /* @__PURE__ */ jsx("span", {
1587
+ className: "rounded-md bg-muted px-2 py-0.5 font-mono text-xs text-foreground",
1588
+ children: field
1589
+ }, field))
1590
+ })]
1591
+ });
1592
+ }
1593
+ function VersionAdvisoryModal(props) {
1594
+ const { prompt, onReleaseFirst, onKeepEditing, onCancel } = props;
1595
+ if (!prompt) return null;
1596
+ const { version, reason, diff } = prompt;
1597
+ const nextVersion = version + 1;
1598
+ return /* @__PURE__ */ jsx(Modal, {
1599
+ open: true,
1600
+ onOpenChange: (status) => {
1601
+ if (!status) onCancel();
1602
+ },
1603
+ children: /* @__PURE__ */ jsxs("div", {
1604
+ className: "w-[440px] p-6",
1605
+ "data-testid": "version-advisory-modal",
1606
+ children: [
1607
+ /* @__PURE__ */ jsxs("div", {
1608
+ className: "pb-2 text-2xl font-bold text-foreground",
1609
+ children: [
1610
+ "Is version ",
1611
+ version,
1612
+ " of this model already in use?"
1613
+ ]
1614
+ }),
1615
+ /* @__PURE__ */ jsxs("div", {
1616
+ className: "my-4 rounded-md bg-background p-4 text-left text-sm text-foreground",
1617
+ children: [
1618
+ /* @__PURE__ */ jsxs("p", { children: [
1619
+ reason,
1620
+ " Documents that were already created with version ",
1621
+ version,
1622
+ " ",
1623
+ "may stop working correctly."
1624
+ ] }),
1625
+ diff && /* @__PURE__ */ jsxs(Fragment, { children: [
1626
+ /* @__PURE__ */ jsx(FieldDiffList, {
1627
+ fields: diff.addedFields,
1628
+ label: "New fields:"
1629
+ }),
1630
+ /* @__PURE__ */ jsx(FieldDiffList, {
1631
+ fields: diff.removedFields,
1632
+ label: "Removed fields:"
1633
+ }),
1634
+ /* @__PURE__ */ jsx(FieldDiffList, {
1635
+ fields: diff.changedFields,
1636
+ label: "Changed fields:"
1637
+ })
1638
+ ] }),
1639
+ /* @__PURE__ */ jsxs("p", {
1640
+ className: "mt-3",
1641
+ children: [
1642
+ "If others are already using version ",
1643
+ version,
1644
+ ", release version",
1645
+ " ",
1646
+ nextVersion,
1647
+ " first. Your change will go into version ",
1648
+ nextVersion,
1649
+ ", and existing documents can be updated safely."
1650
+ ]
1651
+ })
1652
+ ]
1653
+ }),
1654
+ /* @__PURE__ */ jsxs("div", {
1655
+ className: "mt-4 flex flex-col gap-2",
1656
+ children: [/* @__PURE__ */ jsx(ModalButton, {
1657
+ className: compactButtonStyle,
1658
+ "data-testid": "advisory-release-first",
1659
+ onClick: onReleaseFirst,
1660
+ variant: "confirm",
1661
+ children: `It's in use — release v${nextVersion} first`
1662
+ }), /* @__PURE__ */ jsxs(ModalButton, {
1663
+ className: compactButtonStyle,
1664
+ "data-testid": "advisory-keep-editing",
1665
+ onClick: onKeepEditing,
1666
+ variant: "cancel",
1667
+ children: ["Still in development — keep editing v", version]
1668
+ })]
1669
+ })
1670
+ ]
1671
+ })
1672
+ });
1673
+ }
1674
+ //#endregion
1675
+ //#region editors/document-model-editor/config.ts
1676
+ const editorConfig = { isExternalControlsEnabled: false };
1677
+ //#endregion
1678
+ //#region editors/document-model-editor/utils/change-classification.ts
1679
+ function isShapeTypeNode(node) {
1680
+ return node.kind === Kind.OBJECT_TYPE_DEFINITION || node.kind === Kind.INPUT_OBJECT_TYPE_DEFINITION || node.kind === Kind.ENUM_TYPE_DEFINITION;
1681
+ }
1682
+ function collectTypeFields(doc) {
1683
+ const types = /* @__PURE__ */ new Map();
1684
+ for (const definition of doc.definitions) {
1685
+ if (!isShapeTypeNode(definition)) continue;
1686
+ const fields = /* @__PURE__ */ new Map();
1687
+ if (definition.kind === Kind.ENUM_TYPE_DEFINITION) for (const value of definition.values ?? []) fields.set(value.name.value, "value");
1688
+ else for (const field of definition.fields ?? []) fields.set(field.name.value, print(field.type));
1689
+ types.set(definition.name.value, fields);
1690
+ }
1691
+ return types;
1692
+ }
1693
+ function escapeRegExp(value) {
1694
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
1695
+ }
1696
+ function replaceTypeName(printedType, oldName, newName) {
1697
+ return printedType.replace(new RegExp(`\\b${escapeRegExp(oldName)}\\b`, "g"), newName);
1698
+ }
1699
+ function typeSignature(name, fields) {
1700
+ return [...fields.entries()].map(([field, type]) => `${field}:${replaceTypeName(type, name, "__SELF__")}`).sort().join("|");
1701
+ }
1702
+ function detectTypeRenames(oldTypes, newTypes) {
1703
+ const renames = /* @__PURE__ */ new Map();
1704
+ const removed = [...oldTypes.keys()].filter((name) => !newTypes.has(name));
1705
+ const added = new Set([...newTypes.keys()].filter((name) => !oldTypes.has(name)));
1706
+ for (const oldName of removed) {
1707
+ const oldSignature = typeSignature(oldName, oldTypes.get(oldName));
1708
+ for (const newName of added) if (typeSignature(newName, newTypes.get(newName)) === oldSignature) {
1709
+ renames.set(oldName, newName);
1710
+ added.delete(newName);
1711
+ break;
1712
+ }
1713
+ }
1714
+ return renames;
1715
+ }
1716
+ function flattenFields(types, renames) {
1717
+ const fields = /* @__PURE__ */ new Map();
1718
+ for (const [typeName, typeFields] of types) {
1719
+ const resolvedTypeName = renames.get(typeName) ?? typeName;
1720
+ for (const [fieldName, printedType] of typeFields) {
1721
+ let resolvedType = printedType;
1722
+ for (const [oldName, newName] of renames) resolvedType = replaceTypeName(resolvedType, oldName, newName);
1723
+ fields.set(`${resolvedTypeName}.${fieldName}`, resolvedType);
1724
+ }
1725
+ }
1726
+ return fields;
1727
+ }
1728
+ function hasShapeChange(diff) {
1729
+ return diff.addedFields.length > 0 || diff.removedFields.length > 0 || diff.changedFields.length > 0;
1730
+ }
1731
+ function diffSdlShapes(oldSdl, newSdl) {
1732
+ const empty = {
1733
+ addedFields: [],
1734
+ removedFields: [],
1735
+ changedFields: []
1736
+ };
1737
+ let oldDoc;
1738
+ let newDoc;
1739
+ try {
1740
+ oldDoc = parse(oldSdl);
1741
+ newDoc = parse(newSdl);
1742
+ } catch {
1743
+ return empty;
1744
+ }
1745
+ const oldTypes = collectTypeFields(oldDoc);
1746
+ const newTypes = collectTypeFields(newDoc);
1747
+ const oldFields = flattenFields(oldTypes, detectTypeRenames(oldTypes, newTypes));
1748
+ const newFields = flattenFields(newTypes, /* @__PURE__ */ new Map());
1749
+ const diff = {
1750
+ addedFields: [],
1751
+ removedFields: [],
1752
+ changedFields: []
1753
+ };
1754
+ for (const [key, newType] of newFields) {
1755
+ const oldType = oldFields.get(key);
1756
+ if (oldType === void 0) diff.addedFields.push(key);
1757
+ else if (oldType !== newType) diff.changedFields.push(`${key}: ${oldType} → ${newType}`);
1758
+ }
1759
+ for (const key of oldFields.keys()) if (!newFields.has(key)) diff.removedFields.push(key);
1760
+ return diff;
1761
+ }
1762
+ const SAFE = { kind: "safe" };
1763
+ function isBlank(value) {
1764
+ return !value || !value.trim() || value.trim() === "{}";
1765
+ }
1766
+ /**
1767
+ * True for a blank SDL, or an SDL whose types contain nothing but the
1768
+ * `_placeholder` field the editor seeds new state/operation schemas with
1769
+ * (see `makeInitialSchemaDoc` / `makeOperationInitialDoc` in ./helpers.ts).
1770
+ * Replacing a placeholder-only schema with real fields is a user's first
1771
+ * edit on a brand-new model, not a version-relevant change.
1772
+ */
1773
+ function isPlaceholderOnlySchema(sdl) {
1774
+ if (isBlank(sdl)) return true;
1775
+ let doc;
1776
+ try {
1777
+ doc = parse(sdl);
1778
+ } catch {
1779
+ return false;
1780
+ }
1781
+ return [...collectTypeFields(doc).values()].every((fields) => fields.size === 0 || fields.size === 1 && fields.has("_placeholder"));
1782
+ }
1783
+ function findOperation(spec, operationId) {
1784
+ for (const module of spec.modules) {
1785
+ const operation = module.operations.find((op) => op.id === operationId);
1786
+ if (operation) return operation;
1787
+ }
1788
+ }
1789
+ function addedSinceLastRelease(operationId, previousSpec) {
1790
+ return previousSpec !== void 0 && !findOperation(previousSpec, operationId);
1791
+ }
1792
+ function classifySetStateSchema(input, latestSpec) {
1793
+ const currentSchema = input.scope === "local" ? latestSpec.state.local.schema : latestSpec.state.global.schema;
1794
+ if (isPlaceholderOnlySchema(currentSchema)) return SAFE;
1795
+ const diff = diffSdlShapes(currentSchema, input.schema);
1796
+ if (!hasShapeChange(diff)) return SAFE;
1797
+ return {
1798
+ kind: "version-relevant",
1799
+ reason: input.scope === "local" ? `You're changing the local fields that version ${latestSpec.version} documents store.` : `You're changing the fields that version ${latestSpec.version} documents store.`,
1800
+ diff
1801
+ };
1802
+ }
1803
+ /**
1804
+ * The editor pre-fills a fresh model's initial value from the placeholder
1805
+ * schema, so a value that is blank or carries only the `_placeholder` key is
1806
+ * still being initialized rather than changed.
1807
+ */
1808
+ function isPlaceholderOnlyInitialValue(value) {
1809
+ if (isBlank(value)) return true;
1810
+ let parsed;
1811
+ try {
1812
+ parsed = JSON.parse(value);
1813
+ } catch {
1814
+ return false;
1815
+ }
1816
+ if (typeof parsed !== "object" || parsed === null) return false;
1817
+ return Object.keys(parsed).every((key) => key === "_placeholder");
1818
+ }
1819
+ function classifySetInitialState(input, latestSpec) {
1820
+ const currentValue = input.scope === "local" ? latestSpec.state.local.initialValue : latestSpec.state.global.initialValue;
1821
+ if (isPlaceholderOnlyInitialValue(currentValue)) return SAFE;
1822
+ if (compareStringsWithoutWhitespace(currentValue, input.initialValue)) return SAFE;
1823
+ return {
1824
+ kind: "version-relevant",
1825
+ reason: `You're changing the starting content that version ${latestSpec.version} documents are built on.`
1826
+ };
1827
+ }
1828
+ function classifyOperationChange(action, operationId, latestSpec, previousSpec) {
1829
+ if (addedSinceLastRelease(operationId, previousSpec)) return SAFE;
1830
+ const operation = findOperation(latestSpec, operationId);
1831
+ if (!operation) return SAFE;
1832
+ const operationLabel = operation.name || "an operation";
1833
+ switch (action.type) {
1834
+ case "DELETE_OPERATION": return {
1835
+ kind: "version-relevant",
1836
+ reason: `You're removing the "${operationLabel}" operation from version ${latestSpec.version}.`
1837
+ };
1838
+ case "SET_OPERATION_NAME":
1839
+ if (isBlank(operation.name)) return SAFE;
1840
+ return {
1841
+ kind: "version-relevant",
1842
+ reason: `You're renaming the "${operationLabel}" operation in version ${latestSpec.version}.`
1843
+ };
1844
+ case "SET_OPERATION_SCHEMA": {
1845
+ if (isPlaceholderOnlySchema(operation.schema ?? "")) return SAFE;
1846
+ if (isBlank(action.input.schema)) return {
1847
+ kind: "version-relevant",
1848
+ reason: `You're changing the information that the "${operationLabel}" operation accepts in version ${latestSpec.version}.`
1849
+ };
1850
+ const diff = diffSdlShapes(operation.schema ?? "", action.input.schema ?? "");
1851
+ if (!hasShapeChange(diff)) return SAFE;
1852
+ return {
1853
+ kind: "version-relevant",
1854
+ reason: `You're changing the information that the "${operationLabel}" operation accepts in version ${latestSpec.version}.`,
1855
+ diff
1856
+ };
1857
+ }
1858
+ default: return SAFE;
1859
+ }
1860
+ }
1861
+ function classifyDeleteModule(moduleId, latestSpec, previousSpec) {
1862
+ const module = latestSpec.modules.find((candidate) => candidate.id === moduleId);
1863
+ if (!module || module.operations.length === 0) return SAFE;
1864
+ if (module.operations.every((operation) => addedSinceLastRelease(operation.id, previousSpec))) return SAFE;
1865
+ return {
1866
+ kind: "version-relevant",
1867
+ reason: `You're removing the "${module.name}" module and all of its operations from version ${latestSpec.version}.`
1868
+ };
1869
+ }
1870
+ /**
1871
+ * Classifies a document-model action as version-relevant (would break
1872
+ * documents created with the current version) or safe. `previousSpec` is the
1873
+ * last released specification, used to exempt operations added since the
1874
+ * release.
1875
+ */
1876
+ function classifyDocumentModelAction(action, latestSpec, previousSpec) {
1877
+ switch (action.type) {
1878
+ case "SET_STATE_SCHEMA": return classifySetStateSchema(action.input, latestSpec);
1879
+ case "SET_INITIAL_STATE": return classifySetInitialState(action.input, latestSpec);
1880
+ case "DELETE_OPERATION":
1881
+ case "SET_OPERATION_NAME":
1882
+ case "SET_OPERATION_SCHEMA": return classifyOperationChange(action, action.input.id, latestSpec, previousSpec);
1883
+ case "DELETE_MODULE": return classifyDeleteModule(action.input.id, latestSpec, previousSpec);
1884
+ default: return SAFE;
1885
+ }
1886
+ }
1887
+ /**
1888
+ * Pure decision core of the version advisory: given the actions about to be
1889
+ * dispatched, decide whether to dispatch immediately or prompt the user.
1890
+ */
1891
+ function decideDispatch(actions, latestSpec, previousSpec, hasSessionChoice) {
1892
+ if (hasSessionChoice) return { kind: "dispatch" };
1893
+ for (const action of actions) {
1894
+ const classification = classifyDocumentModelAction(action, latestSpec, previousSpec);
1895
+ if (classification.kind === "version-relevant") return {
1896
+ kind: "prompt",
1897
+ reason: classification.reason,
1898
+ diff: classification.diff
1899
+ };
1900
+ }
1901
+ return { kind: "dispatch" };
1902
+ }
1903
+ //#endregion
1904
+ //#region editors/document-model-editor/hooks/useVersionAdvisory.ts
1905
+ /**
1906
+ * Versions the user has confirmed as "still in development" (or that were
1907
+ * just created via an explicit release) for this browser session. Keyed by
1908
+ * `${documentId}:${version}`. Deliberately in-memory: a publisher returning
1909
+ * in a later session is asked again, which is when the reminder matters.
1910
+ */
1911
+ const sessionVersionChoices = /* @__PURE__ */ new Set();
1912
+ function useVersionAdvisory(args) {
1913
+ const { documentId, latestSpec, previousSpec, dispatch, onReleaseError } = args;
1914
+ const [prompt, setPrompt] = useState(void 0);
1915
+ const pendingRef = useRef(void 0);
1916
+ const choiceKey = `${documentId}:${latestSpec.version}`;
1917
+ const guardedDispatch = (...dispatchArgs) => {
1918
+ const [action] = dispatchArgs;
1919
+ const decision = decideDispatch((Array.isArray(action) ? action : [action]).filter((candidate) => candidate !== void 0), latestSpec, previousSpec, sessionVersionChoices.has(choiceKey));
1920
+ if (decision.kind === "dispatch") {
1921
+ dispatch(...dispatchArgs);
1922
+ return;
1923
+ }
1924
+ pendingRef.current = dispatchArgs;
1925
+ setPrompt({
1926
+ version: latestSpec.version,
1927
+ reason: decision.reason,
1928
+ diff: decision.diff
1929
+ });
1930
+ };
1931
+ const flushPending = () => {
1932
+ const pending = pendingRef.current;
1933
+ pendingRef.current = void 0;
1934
+ if (pending) dispatch(...pending);
1935
+ };
1936
+ const releaseFirst = () => {
1937
+ setPrompt(void 0);
1938
+ if (!pendingRef.current) return;
1939
+ dispatch(releaseNewVersion(), (errors) => {
1940
+ if (errors.length > 0) {
1941
+ pendingRef.current = void 0;
1942
+ onReleaseError?.(errors[0].message);
1943
+ }
1944
+ }, () => {
1945
+ if (!pendingRef.current) return;
1946
+ sessionVersionChoices.add(`${documentId}:${latestSpec.version + 1}`);
1947
+ flushPending();
1948
+ });
1949
+ };
1950
+ const keepEditing = () => {
1951
+ sessionVersionChoices.add(choiceKey);
1952
+ setPrompt(void 0);
1953
+ flushPending();
1954
+ };
1955
+ const cancelAdvisory = () => {
1956
+ pendingRef.current = void 0;
1957
+ setPrompt(void 0);
1958
+ };
1959
+ const markVersionInDevelopment = (version) => {
1960
+ sessionVersionChoices.add(`${documentId}:${version}`);
1961
+ };
1962
+ return {
1963
+ guardedDispatch,
1964
+ prompt,
1965
+ releaseFirst,
1966
+ keepEditing,
1967
+ cancelAdvisory,
1968
+ markVersionInDevelopment
1969
+ };
1970
+ }
1971
+ //#endregion
1972
+ //#region editors/document-model-editor/editor.tsx
1973
+ var editor_exports = /* @__PURE__ */ __exportAll({ default: () => Editor });
1974
+ const StateSchemas = lazy(() => import("./state-schemas-DSY44MOd.js"));
1975
+ const noopSetStateSchema = () => void 0;
1976
+ const noopSetInitialState = () => void 0;
1977
+ function Editor({ document, dispatch }) {
1978
+ useSetPHDocumentEditorConfig(editorConfig);
1979
+ const toast = usePHToast();
1980
+ const [scope, setScope] = useState("global");
1981
+ const documentNodeName = document.header.name;
1982
+ const { name: modelName, id: documentType, extension, description, author: { name: authorName, website: authorWebsite } } = document.state.global;
1983
+ const specifications = document.state.global.specifications;
1984
+ const latestSpec = specifications[specifications.length - 1];
1985
+ const previousSpec = specifications.length >= 2 ? specifications[specifications.length - 2] : void 0;
1986
+ const [viewedVersion, setViewedVersion] = useState("latest");
1987
+ const viewedSpec = viewedVersion === "latest" ? latestSpec : specifications.find((spec) => spec.version === viewedVersion) ?? latestSpec;
1988
+ const isViewingFrozenVersion = viewedSpec.version !== latestSpec.version;
1989
+ const { state: { global: { schema: globalStateSchema, initialValue: globalStateInitialValue }, local: { schema: localStateSchema, initialValue: localStateInitialValue } }, modules } = viewedSpec;
1990
+ const operations = modules.flatMap((module) => module.operations);
1991
+ const { state: { global: { schema: latestGlobalStateSchema, initialValue: latestGlobalStateInitialValue }, local: { schema: latestLocalStateSchema, initialValue: latestLocalStateInitialValue } }, modules: latestModules } = latestSpec;
1992
+ const latestOperations = latestModules.flatMap((module) => module.operations);
1993
+ const shouldSetInitialName = useRef(!modelName && !!documentNodeName && specifications.length === 1 && !latestGlobalStateSchema && latestModules.length === 0);
1994
+ useEffect(() => {
1995
+ if (!shouldSetInitialName.current || !documentNodeName) return;
1996
+ const initialSchemaDoc = initializeModelSchema(documentNodeName);
1997
+ dispatch([
1998
+ setModelName({ name: documentNodeName }),
1999
+ setStateSchema({
2000
+ schema: initialSchemaDoc,
2001
+ scope: "global"
2002
+ }),
2003
+ setInitialState({
2004
+ initialValue: makeInitialValueForSchema(initialSchemaDoc),
2005
+ scope: "global"
2006
+ })
2007
+ ]);
2008
+ shouldSetInitialName.current = false;
2009
+ }, [documentNodeName, dispatch]);
2010
+ const { guardedDispatch, prompt, releaseFirst, keepEditing, cancelAdvisory, markVersionInDevelopment } = useVersionAdvisory({
2011
+ documentId: document.header.id,
2012
+ latestSpec,
2013
+ previousSpec,
2014
+ dispatch,
2015
+ onReleaseError: (message) => {
2016
+ if (toast) toast(message, { type: "connect-warning" });
2017
+ }
2018
+ });
2019
+ const handleReleaseNewVersion = () => {
2020
+ const nextVersion = latestSpec.version + 1;
2021
+ dispatch(releaseNewVersion(), (errors) => {
2022
+ if (errors.length > 0 && toast) toast(errors[0].message, { type: "connect-warning" });
2023
+ }, () => {
2024
+ markVersionInDevelopment(nextVersion);
2025
+ setViewedVersion("latest");
2026
+ });
2027
+ };
2028
+ const operationSchemasSdl = operations.flatMap((operation) => operation.schema ?? []).join("\n");
2029
+ const handleSetModelId = (id) => {
2030
+ if (compareStringsWithoutWhitespace(id, documentType)) return;
2031
+ guardedDispatch([setModelId({ id })]);
2032
+ };
2033
+ const handleSetModelDescription = (newDescription) => {
2034
+ if (compareStringsWithoutWhitespace(newDescription, description)) return;
2035
+ guardedDispatch(setModelDescription({ description: newDescription }));
2036
+ };
2037
+ const handleSetModelExtension = (newExtension) => {
2038
+ if (compareStringsWithoutWhitespace(newExtension, extension)) return;
2039
+ guardedDispatch(setModelExtension({ extension: newExtension }));
2040
+ };
2041
+ const handleSetModelName = (newName) => {
2042
+ if (compareStringsWithoutWhitespace(newName, modelName)) return;
2043
+ guardedDispatch(setModelName({ name: newName }));
2044
+ };
2045
+ const handleSetAuthorName = (newAuthorName) => {
2046
+ if (compareStringsWithoutWhitespace(newAuthorName, authorName)) return;
2047
+ guardedDispatch(setAuthorName({ authorName: newAuthorName }));
2048
+ };
2049
+ const handleSetAuthorWebsite = (newAuthorWebsite) => {
2050
+ if (compareStringsWithoutWhitespace(newAuthorWebsite, authorWebsite ?? "")) return;
2051
+ guardedDispatch(setAuthorWebsite({ authorWebsite: newAuthorWebsite }));
2052
+ };
2053
+ const handleSetStateSchema = (newSchema, scope) => {
2054
+ if (compareStringsWithoutWhitespace(newSchema, scope === "global" ? latestGlobalStateSchema : latestLocalStateSchema)) return;
2055
+ guardedDispatch(setStateSchema({
2056
+ schema: newSchema,
2057
+ scope
2058
+ }));
2059
+ };
2060
+ const handleSetInitialState = (newInitialValue, scope) => {
2061
+ if (compareStringsWithoutWhitespace(newInitialValue, scope === "global" ? latestGlobalStateInitialValue : latestLocalStateInitialValue)) return;
2062
+ guardedDispatch(setInitialState({
2063
+ initialValue: newInitialValue,
2064
+ scope
2065
+ }));
2066
+ };
2067
+ const handleAddModule = (name) => {
2068
+ return new Promise((resolve) => {
2069
+ try {
2070
+ if (latestModules.some((module) => compareStringsWithoutWhitespace(module.name, name))) {
2071
+ resolve(void 0);
2072
+ return;
2073
+ }
2074
+ const id = generateId();
2075
+ guardedDispatch(addModule({
2076
+ id,
2077
+ name
2078
+ }));
2079
+ resolve(id);
2080
+ } catch (error) {
2081
+ console.error("Failed to add module:", error);
2082
+ resolve(void 0);
2083
+ }
2084
+ });
2085
+ };
2086
+ const handleSetModuleName = (id, name) => {
2087
+ if (latestModules.some((module) => compareStringsWithoutWhitespace(module.name, name))) return;
2088
+ guardedDispatch(setModuleName({
2089
+ id,
2090
+ name
2091
+ }));
2092
+ };
2093
+ const handleDeleteModule = (id) => {
2094
+ guardedDispatch(deleteModule({ id }));
2095
+ };
2096
+ const handleAddOperation = (moduleId, name) => {
2097
+ return new Promise((resolve) => {
2098
+ const id = generateId();
2099
+ guardedDispatch(addOperation({
2100
+ id,
2101
+ moduleId,
2102
+ name,
2103
+ scope
2104
+ }), (errors) => {
2105
+ if (errors.length > 0) {
2106
+ if (toast) toast(errors[0].message, { type: "connect-warning" });
2107
+ resolve(void 0);
2108
+ } else resolve(id);
2109
+ }, () => resolve(id));
2110
+ });
2111
+ };
2112
+ const handleSetOperationName = (id, name) => {
2113
+ guardedDispatch(setOperationName({
2114
+ id,
2115
+ name
2116
+ }), (errors) => {
2117
+ if (errors.length > 0 && toast) toast(errors[0].message, { type: "connect-warning" });
2118
+ });
2119
+ };
2120
+ const handleSetOperationSchema = (id, newSchema) => {
2121
+ const operation = latestOperations.find((operation) => operation.id === id);
2122
+ if (operation?.schema && compareStringsWithoutWhitespace(newSchema, operation.schema)) return;
2123
+ guardedDispatch(setOperationSchema({
2124
+ id,
2125
+ schema: newSchema
2126
+ }));
2127
+ };
2128
+ const handleToggleNoInputRequired = (id, noInputRequired) => {
2129
+ const operation = latestOperations.find((op) => op.id === id);
2130
+ if (!operation?.name) return;
2131
+ if (noInputRequired) guardedDispatch(setOperationSchema({
2132
+ id,
2133
+ schema: makeEmptyOperationSchema(operation.name)
2134
+ }));
2135
+ else guardedDispatch(setOperationSchema({
2136
+ id,
2137
+ schema: makeOperationInitialDoc(operation.name)
2138
+ }));
2139
+ };
2140
+ const handleSetOperationDescription = (id, newDescription) => {
2141
+ if (compareStringsWithoutWhitespace(latestOperations.find((operation) => operation.id === id)?.description ?? "", newDescription)) return;
2142
+ guardedDispatch(setOperationDescription({
2143
+ id,
2144
+ description: newDescription
2145
+ }));
2146
+ };
2147
+ const handleDeleteOperation = (id) => {
2148
+ guardedDispatch(deleteOperation({ id }));
2149
+ };
2150
+ const handleAddOperationError = (operationId, errorName) => {
2151
+ return new Promise((resolve) => {
2152
+ try {
2153
+ if ((latestOperations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) {
2154
+ resolve(void 0);
2155
+ return;
2156
+ }
2157
+ const id = generateId();
2158
+ const errorCode = pascalCase(errorName);
2159
+ guardedDispatch(addOperationError({
2160
+ id,
2161
+ operationId,
2162
+ errorName,
2163
+ errorCode
2164
+ }));
2165
+ resolve(id);
2166
+ } catch (error) {
2167
+ console.error("Failed to add operation error:", error);
2168
+ resolve(void 0);
2169
+ }
2170
+ });
2171
+ };
2172
+ const handleDeleteOperationError = (id) => {
2173
+ guardedDispatch(deleteOperationError({ id }));
2174
+ };
2175
+ const handleSetOperationErrorName = (operationId, errorId, errorName) => {
2176
+ if ((latestOperations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) return;
2177
+ guardedDispatch(setOperationErrorName({
2178
+ id: errorId,
2179
+ errorName
2180
+ }));
2181
+ };
2182
+ const addOperationAndInitialSchema = async (moduleId, name) => {
2183
+ try {
2184
+ const id = await handleAddOperation(moduleId, name);
2185
+ if (!id) return void 0;
2186
+ try {
2187
+ handleSetOperationSchema(id, makeOperationInitialDoc(name));
2188
+ return id;
2189
+ } catch (error) {
2190
+ console.error("Failed to update operation schema:", error);
2191
+ return;
2192
+ }
2193
+ } catch (error) {
2194
+ console.error("Failed to add operation and schema:", error);
2195
+ return;
2196
+ }
2197
+ };
2198
+ return /* @__PURE__ */ jsxs("main", {
2199
+ className: "min-h-dvh bg-background p-6",
2200
+ children: [
2201
+ /* @__PURE__ */ jsx(DocumentToolbar, { document }),
2202
+ /* @__PURE__ */ jsx(SchemaContextProvider, {
2203
+ globalStateSchemaSdl: globalStateSchema,
2204
+ localStateSchemaSdl: localStateSchema,
2205
+ operationSchemasSdl,
2206
+ children: /* @__PURE__ */ jsxs("div", {
2207
+ className: "mx-auto max-w-6xl px-4 pt-8",
2208
+ children: [
2209
+ /* @__PURE__ */ jsx(VersionControls, {
2210
+ specifications,
2211
+ viewedVersion: viewedSpec.version,
2212
+ onViewVersion: setViewedVersion,
2213
+ onReleaseNewVersion: handleReleaseNewVersion
2214
+ }),
2215
+ /* @__PURE__ */ jsx(ModelMetadata, {
2216
+ name: modelName,
2217
+ documentType,
2218
+ extension,
2219
+ description,
2220
+ authorName,
2221
+ authorWebsite: authorWebsite ?? "",
2222
+ globalStateSchema: latestGlobalStateSchema,
2223
+ localStateSchema: latestLocalStateSchema,
2224
+ setModelId: handleSetModelId,
2225
+ setModelDescription: handleSetModelDescription,
2226
+ setModelExtension: handleSetModelExtension,
2227
+ setModelName: handleSetModelName,
2228
+ setAuthorName: handleSetAuthorName,
2229
+ setAuthorWebsite: handleSetAuthorWebsite,
2230
+ setStateSchema: handleSetStateSchema
2231
+ }),
2232
+ /* @__PURE__ */ jsx(Divider, {}),
2233
+ isViewingFrozenVersion && /* @__PURE__ */ jsx(FrozenVersionBanner, {
2234
+ latestVersion: latestSpec.version,
2235
+ viewedVersion: viewedSpec.version
2236
+ }),
2237
+ /* @__PURE__ */ jsxs("div", {
2238
+ className: isViewingFrozenVersion ? "pointer-events-none opacity-80 select-none" : void 0,
2239
+ inert: isViewingFrozenVersion || void 0,
2240
+ children: [
2241
+ /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(StateSchemas, {
2242
+ modelName,
2243
+ globalStateSchema,
2244
+ globalStateInitialValue,
2245
+ localStateSchema,
2246
+ localStateInitialValue,
2247
+ setStateSchema: isViewingFrozenVersion ? noopSetStateSchema : handleSetStateSchema,
2248
+ setInitialState: isViewingFrozenVersion ? noopSetInitialState : handleSetInitialState,
2249
+ currentScope: scope,
2250
+ onScopeChange: setScope
2251
+ }) }),
2252
+ /* @__PURE__ */ jsx(Divider, {}),
2253
+ /* @__PURE__ */ jsxs("h3", {
2254
+ className: "mb-6 text-lg text-foreground capitalize",
2255
+ children: [scope, " Operations"]
2256
+ }),
2257
+ /* @__PURE__ */ jsx(Modules, {
2258
+ modules: modules.map((module) => ({
2259
+ ...module,
2260
+ operations: module.operations.filter((op) => op.scope === scope)
2261
+ })),
2262
+ allOperations: operations,
2263
+ addModule: handleAddModule,
2264
+ updateModuleName: handleSetModuleName,
2265
+ deleteModule: handleDeleteModule,
2266
+ updateOperationName: handleSetOperationName,
2267
+ updateOperationSchema: handleSetOperationSchema,
2268
+ setOperationDescription: handleSetOperationDescription,
2269
+ deleteOperation: handleDeleteOperation,
2270
+ addOperationError: handleAddOperationError,
2271
+ deleteOperationError: handleDeleteOperationError,
2272
+ setOperationErrorName: handleSetOperationErrorName,
2273
+ addOperationAndInitialSchema,
2274
+ toggleNoInputRequired: handleToggleNoInputRequired
2275
+ })
2276
+ ]
2277
+ })
2278
+ ]
2279
+ })
2280
+ }),
2281
+ /* @__PURE__ */ jsx(VersionAdvisoryModal, {
2282
+ prompt,
2283
+ onReleaseFirst: releaseFirst,
2284
+ onKeepEditing: keepEditing,
2285
+ onCancel: cancelAdvisory
2286
+ })
2287
+ ]
2288
+ });
2289
+ }
2290
+ //#endregion
2291
+ export { makeInitialSchemaDoc as a, validateStateObject as c, Editor as default, StateValidationError as i, Button as n, makeMinimalObjectForStateType as o, ensureValidStateSchemaName as r, makeStateSchemaNameForScope as s, editor_exports as t };
2292
+
2293
+ //# sourceMappingURL=editor-DXAJ8Mqb.js.map