@powerhousedao/powerhouse-vetra-packages 6.2.3-dev.8 → 6.2.3-dev.80

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 (115) hide show
  1. package/dist/browser/document-models/index.js +2 -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-6T4WF2og.js → editor-DXAJ8Mqb.js} +761 -277
  5. package/dist/browser/editor-DXAJ8Mqb.js.map +1 -0
  6. package/dist/browser/{editor-DHysndk4.js → editor-Dmpkd8pQ.js} +4 -5
  7. package/dist/browser/{editor-DHysndk4.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 -324
  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/editors/generic-drive-explorer/module.js.map +1 -1
  14. package/dist/browser/{folder-view-DTewe8q8.js → folder-view-CwIU4XEe.js} +17 -12
  15. package/dist/browser/folder-view-CwIU4XEe.js.map +1 -0
  16. package/dist/browser/graphql-editor-CGxwONKl.js +103 -0
  17. package/dist/browser/graphql-editor-CGxwONKl.js.map +1 -0
  18. package/dist/browser/hooks-D15NCia0.js +126 -0
  19. package/dist/browser/hooks-D15NCia0.js.map +1 -0
  20. package/dist/browser/index.js +6 -703
  21. package/dist/browser/index.js.map +1 -1
  22. package/dist/browser/json-editor--jgLEwP2.js +55 -0
  23. package/dist/browser/json-editor--jgLEwP2.js.map +1 -0
  24. package/dist/browser/{schema-context-ZyeclQwy.js → schema-context-CC_WFs1x.js} +10 -6
  25. package/dist/browser/schema-context-CC_WFs1x.js.map +1 -0
  26. package/dist/browser/{state-schemas-CpcWN_Qo.js → state-schemas-DSY44MOd.js} +28 -19
  27. package/dist/browser/state-schemas-DSY44MOd.js.map +1 -0
  28. package/dist/{browser/dist-BAJ5nRDl.js → node/bundle-mjs-Cuu3DEfT.mjs} +1251 -822
  29. package/dist/node/bundle-mjs-Cuu3DEfT.mjs.map +1 -0
  30. package/dist/node/document-models/index.mjs +2 -1
  31. package/dist/node/{graphql-BfAoPeWM.mjs → documents-CNInCxpO.mjs} +66 -50
  32. package/dist/node/documents-CNInCxpO.mjs.map +1 -0
  33. package/dist/node/editor-C54qhQLX.mjs +4762 -0
  34. package/dist/node/editor-C54qhQLX.mjs.map +1 -0
  35. package/dist/node/{editor-DPv5LEug.mjs → editor-NwTlNx8z.mjs} +4 -5
  36. package/dist/node/{editor-DPv5LEug.mjs.map → editor-NwTlNx8z.mjs.map} +1 -1
  37. package/dist/node/editors/document-model-editor/module.mjs +1 -1
  38. package/dist/node/editors/document-model-editor/module.mjs.map +1 -1
  39. package/dist/node/editors/generic-drive-explorer/index.mjs +26 -21
  40. package/dist/node/editors/generic-drive-explorer/index.mjs.map +1 -1
  41. package/dist/node/editors/generic-drive-explorer/module.mjs +1 -1
  42. package/dist/node/editors/generic-drive-explorer/module.mjs.map +1 -1
  43. package/dist/node/folder-view-CkCNU8A_.mjs +966 -0
  44. package/dist/node/folder-view-CkCNU8A_.mjs.map +1 -0
  45. package/dist/node/{graphql-editor-D0CHQeCL.mjs → graphql-editor--ZZPvvGh.mjs} +5130 -63
  46. package/dist/node/graphql-editor--ZZPvvGh.mjs.map +1 -0
  47. package/dist/node/{hooks-D0DcS3MV.mjs → hooks-DI7akiay.mjs} +824 -444
  48. package/dist/node/{hooks-D0DcS3MV.mjs.map → hooks-DI7akiay.mjs.map} +1 -1
  49. package/dist/node/index.mjs +45 -97
  50. package/dist/node/index.mjs.map +1 -1
  51. package/dist/{browser/json-editor-xI_oaxyT.js → node/json-editor-gYEyOVXY.mjs} +8 -9
  52. package/dist/node/{json-editor-Ckaem6ky.mjs.map → json-editor-gYEyOVXY.mjs.map} +1 -1
  53. package/dist/node/rolldown-runtime-Bl3dcgcQ.mjs +16 -0
  54. package/dist/node/{schema-context-DL8jhi_d.mjs → schema-context-DTb0xqgJ.mjs} +9 -6
  55. package/dist/node/schema-context-DTb0xqgJ.mjs.map +1 -0
  56. package/dist/node/state-schemas-Ciq9kway.mjs +1071 -0
  57. package/dist/node/state-schemas-Ciq9kway.mjs.map +1 -0
  58. package/package.json +26 -23
  59. package/style.css +2 -0
  60. package/dist/browser/assets/entry-DSBtQnit.js +0 -314
  61. package/dist/browser/assets/projection-entry-Bem3exmO.js +0 -404
  62. package/dist/browser/button-CuO8Gh3v.js +0 -696
  63. package/dist/browser/button-CuO8Gh3v.js.map +0 -1
  64. package/dist/browser/connect-5NZDVmbb.js +0 -14328
  65. package/dist/browser/connect-5NZDVmbb.js.map +0 -1
  66. package/dist/browser/dist-1yB-AuT-.js +0 -4641
  67. package/dist/browser/dist-1yB-AuT-.js.map +0 -1
  68. package/dist/browser/dist-B4FWbuEM.js +0 -4148
  69. package/dist/browser/dist-B4FWbuEM.js.map +0 -1
  70. package/dist/browser/dist-BAJ5nRDl.js.map +0 -1
  71. package/dist/browser/document-drive-CrvzV1D4.js +0 -8319
  72. package/dist/browser/document-drive-CrvzV1D4.js.map +0 -1
  73. package/dist/browser/documents-J_l59mSV.js +0 -6188
  74. package/dist/browser/documents-J_l59mSV.js.map +0 -1
  75. package/dist/browser/editor-6T4WF2og.js.map +0 -1
  76. package/dist/browser/folder-view-DTewe8q8.js.map +0 -1
  77. package/dist/browser/graphql-editor-C2EtXqb9.js +0 -11698
  78. package/dist/browser/graphql-editor-C2EtXqb9.js.map +0 -1
  79. package/dist/browser/hooks-KKcNp2X0.js +0 -24213
  80. package/dist/browser/hooks-KKcNp2X0.js.map +0 -1
  81. package/dist/browser/json-editor-xI_oaxyT.js.map +0 -1
  82. package/dist/browser/lib-CPkPeg_u.js +0 -209
  83. package/dist/browser/lib-CPkPeg_u.js.map +0 -1
  84. package/dist/browser/parser-CkF6Qt8V.js +0 -2553
  85. package/dist/browser/parser-CkF6Qt8V.js.map +0 -1
  86. package/dist/browser/printer-CEYr4JOg.js +0 -604
  87. package/dist/browser/printer-CEYr4JOg.js.map +0 -1
  88. package/dist/browser/schema-context-ZyeclQwy.js.map +0 -1
  89. package/dist/browser/state-schemas-CpcWN_Qo.js.map +0 -1
  90. package/dist/node/button-Da7CxMn7.mjs +0 -678
  91. package/dist/node/button-Da7CxMn7.mjs.map +0 -1
  92. package/dist/node/connect-cjzsd2cR.mjs +0 -15022
  93. package/dist/node/connect-cjzsd2cR.mjs.map +0 -1
  94. package/dist/node/dist-C30J_pcg.mjs +0 -4649
  95. package/dist/node/dist-C30J_pcg.mjs.map +0 -1
  96. package/dist/node/dist-CzYOpeXN.mjs +0 -2711
  97. package/dist/node/dist-CzYOpeXN.mjs.map +0 -1
  98. package/dist/node/dist-DT7jI9ol.mjs +0 -4148
  99. package/dist/node/dist-DT7jI9ol.mjs.map +0 -1
  100. package/dist/node/document-drive-BByBwg-I.mjs +0 -8336
  101. package/dist/node/document-drive-BByBwg-I.mjs.map +0 -1
  102. package/dist/node/documents-DCf53bzO.mjs +0 -747
  103. package/dist/node/documents-DCf53bzO.mjs.map +0 -1
  104. package/dist/node/editor-B4vhYrmV.mjs +0 -1809
  105. package/dist/node/editor-B4vhYrmV.mjs.map +0 -1
  106. package/dist/node/folder-view-BhackcXO.mjs +0 -232
  107. package/dist/node/folder-view-BhackcXO.mjs.map +0 -1
  108. package/dist/node/graphql-BfAoPeWM.mjs.map +0 -1
  109. package/dist/node/graphql-editor-D0CHQeCL.mjs.map +0 -1
  110. package/dist/node/json-editor-Ckaem6ky.mjs +0 -154
  111. package/dist/node/main-BhH_ajBM.mjs +0 -745
  112. package/dist/node/main-BhH_ajBM.mjs.map +0 -1
  113. package/dist/node/schema-context-DL8jhi_d.mjs.map +0 -1
  114. package/dist/node/state-schemas-B1SNl8Ob.mjs +0 -299
  115. package/dist/node/state-schemas-B1SNl8Ob.mjs.map +0 -1
@@ -0,0 +1,4762 @@
1
+ import { n as __exportAll } from "./rolldown-runtime-Bl3dcgcQ.mjs";
2
+ import { t as twMerge } from "./bundle-mjs-Cuu3DEfT.mjs";
3
+ import { o as require_graphql, r as standardLibScalars } from "./documents-CNInCxpO.mjs";
4
+ import { n as safeParseSdl, t as SchemaContextProvider } from "./schema-context-DTb0xqgJ.mjs";
5
+ 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";
6
+ import { z } from "zod";
7
+ import * as React$1 from "react";
8
+ import React, { Suspense, forwardRef, lazy, useCallback, useEffect, useId, useImperativeHandle, useRef, useState } from "react";
9
+ import { ConnectSelect, DocumentToolbar, Modal, ModalButton } from "@powerhousedao/design-system/connect";
10
+ import { usePHToast, useSetPHDocumentEditorConfig } from "@powerhousedao/reactor-browser";
11
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
12
+ import "react-dom";
13
+ import * as n from "zod/v4/core";
14
+ //#region ../../node_modules/.pnpm/change-case@5.4.4/node_modules/change-case/dist/index.js
15
+ const SPLIT_LOWER_UPPER_RE = /([\p{Ll}\d])(\p{Lu})/gu;
16
+ const SPLIT_UPPER_UPPER_RE = /(\p{Lu})([\p{Lu}][\p{Ll}])/gu;
17
+ const SPLIT_SEPARATE_NUMBER_RE = /(\d)\p{Ll}|(\p{L})\d/u;
18
+ const DEFAULT_STRIP_REGEXP = /[^\p{L}\d]+/giu;
19
+ const SPLIT_REPLACE_VALUE = "$1\0$2";
20
+ const DEFAULT_PREFIX_SUFFIX_CHARACTERS = "";
21
+ /**
22
+ * Split any cased input strings into an array of words.
23
+ */
24
+ function split(value) {
25
+ let result = value.trim();
26
+ result = result.replace(SPLIT_LOWER_UPPER_RE, SPLIT_REPLACE_VALUE).replace(SPLIT_UPPER_UPPER_RE, SPLIT_REPLACE_VALUE);
27
+ result = result.replace(DEFAULT_STRIP_REGEXP, "\0");
28
+ let start = 0;
29
+ let end = result.length;
30
+ while (result.charAt(start) === "\0") start++;
31
+ if (start === end) return [];
32
+ while (result.charAt(end - 1) === "\0") end--;
33
+ return result.slice(start, end).split(/\0/g);
34
+ }
35
+ /**
36
+ * Split the input string into an array of words, separating numbers.
37
+ */
38
+ function splitSeparateNumbers(value) {
39
+ const words = split(value);
40
+ for (let i = 0; i < words.length; i++) {
41
+ const word = words[i];
42
+ const match = SPLIT_SEPARATE_NUMBER_RE.exec(word);
43
+ if (match) {
44
+ const offset = match.index + (match[1] ?? match[2]).length;
45
+ words.splice(i, 1, word.slice(0, offset), word.slice(offset));
46
+ }
47
+ }
48
+ return words;
49
+ }
50
+ /**
51
+ * Convert a string to space separated lower case (`foo bar`).
52
+ */
53
+ function noCase(input, options) {
54
+ const [prefix, words, suffix] = splitPrefixSuffix(input, options);
55
+ return prefix + words.map(lowerFactory(options?.locale)).join(options?.delimiter ?? " ") + suffix;
56
+ }
57
+ /**
58
+ * Convert a string to pascal case (`FooBar`).
59
+ */
60
+ function pascalCase(input, options) {
61
+ const [prefix, words, suffix] = splitPrefixSuffix(input, options);
62
+ const lower = lowerFactory(options?.locale);
63
+ const upper = upperFactory(options?.locale);
64
+ const transform = options?.mergeAmbiguousCharacters ? capitalCaseTransformFactory(lower, upper) : pascalCaseTransformFactory(lower, upper);
65
+ return prefix + words.map(transform).join(options?.delimiter ?? "") + suffix;
66
+ }
67
+ /**
68
+ * Convert a string to constant case (`FOO_BAR`).
69
+ */
70
+ function constantCase(input, options) {
71
+ const [prefix, words, suffix] = splitPrefixSuffix(input, options);
72
+ return prefix + words.map(upperFactory(options?.locale)).join(options?.delimiter ?? "_") + suffix;
73
+ }
74
+ /**
75
+ * Convert a string to path case (`Foo bar`).
76
+ */
77
+ function sentenceCase(input, options) {
78
+ const [prefix, words, suffix] = splitPrefixSuffix(input, options);
79
+ const lower = lowerFactory(options?.locale);
80
+ const transform = capitalCaseTransformFactory(lower, upperFactory(options?.locale));
81
+ return prefix + words.map((word, index) => {
82
+ if (index === 0) return transform(word);
83
+ return lower(word);
84
+ }).join(options?.delimiter ?? " ") + suffix;
85
+ }
86
+ /**
87
+ * Convert a string to snake case (`foo_bar`).
88
+ */
89
+ function snakeCase(input, options) {
90
+ return noCase(input, {
91
+ delimiter: "_",
92
+ ...options
93
+ });
94
+ }
95
+ function lowerFactory(locale) {
96
+ return locale === false ? (input) => input.toLowerCase() : (input) => input.toLocaleLowerCase(locale);
97
+ }
98
+ function upperFactory(locale) {
99
+ return locale === false ? (input) => input.toUpperCase() : (input) => input.toLocaleUpperCase(locale);
100
+ }
101
+ function capitalCaseTransformFactory(lower, upper) {
102
+ return (word) => `${upper(word[0])}${lower(word.slice(1))}`;
103
+ }
104
+ function pascalCaseTransformFactory(lower, upper) {
105
+ return (word, index) => {
106
+ const char0 = word[0];
107
+ return (index > 0 && char0 >= "0" && char0 <= "9" ? "_" + char0 : upper(char0)) + lower(word.slice(1));
108
+ };
109
+ }
110
+ function splitPrefixSuffix(input, options = {}) {
111
+ const splitFn = options.split ?? (options.separateNumbers ? splitSeparateNumbers : split);
112
+ const prefixCharacters = options.prefixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;
113
+ const suffixCharacters = options.suffixCharacters ?? DEFAULT_PREFIX_SUFFIX_CHARACTERS;
114
+ let prefixIndex = 0;
115
+ let suffixIndex = input.length;
116
+ while (prefixIndex < input.length) {
117
+ const char = input.charAt(prefixIndex);
118
+ if (!prefixCharacters.includes(char)) break;
119
+ prefixIndex++;
120
+ }
121
+ while (suffixIndex > prefixIndex) {
122
+ const index = suffixIndex - 1;
123
+ const char = input.charAt(index);
124
+ if (!suffixCharacters.includes(char)) break;
125
+ suffixIndex = index;
126
+ }
127
+ return [
128
+ input.slice(0, prefixIndex),
129
+ splitFn(input.slice(prefixIndex, suffixIndex)),
130
+ input.slice(suffixIndex)
131
+ ];
132
+ }
133
+ //#endregion
134
+ //#region editors/document-model-editor/constants/graphql-kinds.ts
135
+ var import_graphql = require_graphql();
136
+ const STRING_GQL_PRIMITIVE_NAME = "String";
137
+ const BOOLEAN_GQL_PRIMITIVE_NAME = "Boolean";
138
+ const FLOAT_GQL_PRIMITIVE_NAME = "Float";
139
+ const gqlPrimitiveNodeNamesList = [
140
+ STRING_GQL_PRIMITIVE_NAME,
141
+ BOOLEAN_GQL_PRIMITIVE_NAME,
142
+ "Int",
143
+ FLOAT_GQL_PRIMITIVE_NAME,
144
+ "ID"
145
+ ];
146
+ //#endregion
147
+ //#region editors/document-model-editor/utils/helpers.ts
148
+ function makeStateSchemaNameForScope(modelName, scope) {
149
+ const modelNamePascalCase = pascalCase(modelName);
150
+ const scopePascalCase = pascalCase(scope);
151
+ return scopePascalCase === "Global" ? `${modelNamePascalCase}State` : `${modelNamePascalCase}${scopePascalCase}State`;
152
+ }
153
+ function makeInitialSchemaDoc(modelName, scope) {
154
+ return `type ${makeStateSchemaNameForScope(modelName, scope)} {
155
+ "Add your ${scope} state fields here"
156
+ _placeholder: String
157
+ }`;
158
+ }
159
+ function makeOperationInitialDoc(name) {
160
+ return `input ${pascalCase(name)}Input {
161
+ "Add your inputs here"
162
+ _placeholder: String
163
+ }`;
164
+ }
165
+ function makeEmptyOperationSchema(operationName) {
166
+ return `input ${pascalCase(operationName)}Input {\n _empty: Boolean\n}`;
167
+ }
168
+ function isEmptyOperationSchema(schema) {
169
+ if (!schema) return false;
170
+ return /_empty:\s*Boolean/.test(schema) && !schema.replace(/_empty:\s*Boolean/, "").match(/\w+:\s*\w+/);
171
+ }
172
+ function safeParseJsonRecord(json) {
173
+ try {
174
+ return JSON.parse(json);
175
+ } catch (_error) {
176
+ return null;
177
+ }
178
+ }
179
+ function makeMinimalObjectForStateType(args) {
180
+ const { sharedSchemaDocumentNode, stateTypeDefinitionNode, existingValue } = args;
181
+ const existingValueObject = safeParseJsonRecord(existingValue);
182
+ if (!existingValueObject) return existingValue;
183
+ const stateTypeDefinitionFields = stateTypeDefinitionNode.fields;
184
+ if (!stateTypeDefinitionFields?.length) return existingValue;
185
+ const minimalObject = makeMinimalValuesForObjectFields({
186
+ schemaDocumentNode: sharedSchemaDocumentNode,
187
+ fieldDefinitionNodes: stateTypeDefinitionFields,
188
+ existingValueObject,
189
+ visitedTypes: /* @__PURE__ */ new Set([stateTypeDefinitionNode.name.value])
190
+ });
191
+ return JSON.stringify(minimalObject, null, 2);
192
+ }
193
+ function makeMinimalValuesForObjectFields(args) {
194
+ const { schemaDocumentNode, existingValueObject, fieldDefinitionNodes, visitedTypes } = args;
195
+ const newJson = {};
196
+ for (const astNode of fieldDefinitionNodes) {
197
+ const fieldName = getASTNodeName(astNode);
198
+ if (!fieldName) continue;
199
+ const minimalValue = makeMinimalValueForASTNode({
200
+ fieldName,
201
+ astNode,
202
+ schemaDocumentNode,
203
+ existingValueObject,
204
+ visitedTypes
205
+ });
206
+ newJson[astNode.name.value] = minimalValue;
207
+ }
208
+ return newJson;
209
+ }
210
+ function makeMinimalValueForASTNode(args) {
211
+ const { fieldName, astNode, schemaDocumentNode, existingValueObject, visitedTypes } = args;
212
+ const existingFieldValue = existingValueObject?.[fieldName];
213
+ let node = astNode;
214
+ if (isFieldDefinitionNode(astNode)) node = getASTNodeTypeNode(node);
215
+ const isNonNull = isNonNullNode(node);
216
+ if (isNonNull) node = getASTNodeTypeNode(node);
217
+ if (isListTypeNode(node)) return makeMinimalValueForGqlListNode(node, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes);
218
+ if (isGqlPrimitiveNode(node)) return makeMinimalValueForGQLPrimitiveNode(node, existingFieldValue, isNonNull);
219
+ const namedTypeDefinitionNode = getNamedTypeDefinitionNode(node, schemaDocumentNode);
220
+ if (isEnumTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull);
221
+ if (isScalarTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlScalar(namedTypeDefinitionNode, existingFieldValue, isNonNull);
222
+ if (isUnionTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes);
223
+ if (isObjectTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlObject(namedTypeDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
224
+ return existingFieldValue;
225
+ }
226
+ function isFieldDefinitionNode(astNodeTypeNode) {
227
+ if (!astNodeTypeNode) return false;
228
+ return astNodeTypeNode.kind === import_graphql.Kind.FIELD_DEFINITION;
229
+ }
230
+ function isNonNullNode(astNode) {
231
+ if (!astNode) return false;
232
+ return astNode.kind === import_graphql.Kind.NON_NULL_TYPE;
233
+ }
234
+ function isGqlPrimitiveNode(astNodeTypeNode) {
235
+ if (!astNodeTypeNode) return false;
236
+ const name = getASTNodeName(astNodeTypeNode);
237
+ return gqlPrimitiveNodeNamesList.includes(name);
238
+ }
239
+ function isListTypeNode(astNodeTypeNode) {
240
+ if (!astNodeTypeNode) return false;
241
+ return astNodeTypeNode.kind === import_graphql.Kind.LIST_TYPE;
242
+ }
243
+ function isEnumTypeDefinitionNode(definitionNode) {
244
+ if (!definitionNode) return false;
245
+ return definitionNode.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION;
246
+ }
247
+ function isScalarTypeDefinitionNode(definitionNode) {
248
+ if (!definitionNode) return false;
249
+ return definitionNode.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION;
250
+ }
251
+ function isUnionTypeDefinitionNode(definitionNode) {
252
+ if (!definitionNode) return false;
253
+ return definitionNode.kind === import_graphql.Kind.UNION_TYPE_DEFINITION;
254
+ }
255
+ function isObjectTypeDefinitionNode(definitionNode) {
256
+ if (!definitionNode) return false;
257
+ return definitionNode.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION;
258
+ }
259
+ function getASTNodeName(astNode) {
260
+ if (!astNode) return null;
261
+ if (!("name" in astNode)) return null;
262
+ if (!astNode.name) return null;
263
+ if (!("value" in astNode.name)) return null;
264
+ return astNode.name.value;
265
+ }
266
+ function getASTNodeTypeNode(astNode) {
267
+ if (!astNode) return null;
268
+ if (!("type" in astNode)) return null;
269
+ return astNode.type;
270
+ }
271
+ function makeMinimalValueForGQLPrimitiveNode(primitiveTypeNode, existingFieldValue, isNonNull) {
272
+ const name = getASTNodeName(primitiveTypeNode);
273
+ if (!name) return null;
274
+ switch (name) {
275
+ case "ID":
276
+ if (z.string().safeParse(existingFieldValue).success) return existingFieldValue;
277
+ return isNonNull ? "placeholder-id" : null;
278
+ case BOOLEAN_GQL_PRIMITIVE_NAME:
279
+ if (z.boolean().safeParse(existingFieldValue).success) return existingFieldValue;
280
+ return isNonNull ? false : null;
281
+ case "Int":
282
+ if (z.number().safeParse(existingFieldValue).success) return existingFieldValue;
283
+ return isNonNull ? 0 : null;
284
+ case FLOAT_GQL_PRIMITIVE_NAME:
285
+ if (z.number().safeParse(existingFieldValue).success) return existingFieldValue;
286
+ return isNonNull ? 0 : null;
287
+ case STRING_GQL_PRIMITIVE_NAME:
288
+ if (z.string().safeParse(existingFieldValue).success) return existingFieldValue;
289
+ return isNonNull ? "" : null;
290
+ }
291
+ return isNonNull ? existingFieldValue : null;
292
+ }
293
+ function makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull) {
294
+ const enumValues = namedTypeDefinitionNode.values?.map((value) => value.name.value) ?? [];
295
+ if (typeof existingFieldValue === "string" && enumValues.includes(existingFieldValue)) return existingFieldValue;
296
+ if (isNonNull) return enumValues[0];
297
+ return null;
298
+ }
299
+ function makeMinimalValueForGqlScalar(scalarTypeDefinitionNode, existingFieldValue, isNonNull) {
300
+ if (!isNonNull && !existingFieldValue) return null;
301
+ const name = getASTNodeName(scalarTypeDefinitionNode);
302
+ if (!name) {
303
+ console.error("No name for scalar type definition node", scalarTypeDefinitionNode);
304
+ return null;
305
+ }
306
+ const scalar = standardLibScalars.get(name);
307
+ if (!scalar) return null;
308
+ if (name === "Upload") throw new Error("The editor cannot derive an initial state value for an Upload field.");
309
+ if (scalar.schema.safeParse(existingFieldValue).success) return existingFieldValue;
310
+ return isNonNull ? existingFieldValue : null;
311
+ }
312
+ function makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes) {
313
+ if (!isNonNull && !existingFieldValue) return null;
314
+ if (!namedTypeDefinitionNode.types?.length) return null;
315
+ const firstNamedTypeDefinitionNode = namedTypeDefinitionNode.types?.at(0);
316
+ if (!firstNamedTypeDefinitionNode) return null;
317
+ const firstNamedTypeObjectDefinitionNode = getNamedTypeDefinitionNode(firstNamedTypeDefinitionNode, schemaDocumentNode);
318
+ if (!isObjectTypeDefinitionNode(firstNamedTypeObjectDefinitionNode)) return null;
319
+ return makeMinimalValueForGqlObject(firstNamedTypeObjectDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
320
+ }
321
+ function makeMinimalValueForGqlListNode(listTypeNode, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes) {
322
+ if (!isNonNull && !Array.isArray(existingFieldValue)) return null;
323
+ if (isNonNull && !Array.isArray(existingFieldValue)) return [];
324
+ return existingFieldValue.map((item, index) => makeMinimalValueForASTNode({
325
+ fieldName: String(index),
326
+ astNode: listTypeNode.type,
327
+ schemaDocumentNode,
328
+ existingValueObject: { [index]: item },
329
+ visitedTypes
330
+ }));
331
+ }
332
+ function makeMinimalValueForGqlObject(objectTypeDefinitionNode, schemaDocumentNode, _existingValueObject, existingFieldValue, isNonNull, visitedTypes) {
333
+ const typeName = objectTypeDefinitionNode.name.value;
334
+ if (visitedTypes?.has(typeName)) return null;
335
+ if (!isNonNull && !existingFieldValue) return null;
336
+ const fields = objectTypeDefinitionNode.fields;
337
+ if (!fields?.length) return {};
338
+ const newVisitedTypes = new Set(visitedTypes);
339
+ newVisitedTypes.add(typeName);
340
+ return makeMinimalValuesForObjectFields({
341
+ schemaDocumentNode,
342
+ existingValueObject: existingFieldValue && typeof existingFieldValue === "object" && !Array.isArray(existingFieldValue) ? existingFieldValue : null,
343
+ fieldDefinitionNodes: fields,
344
+ visitedTypes: newVisitedTypes
345
+ });
346
+ }
347
+ function getNamedTypeDefinitionNode(astNodeTypeNode, schemaDocumentNode) {
348
+ if (!astNodeTypeNode) return null;
349
+ const name = getASTNodeName(astNodeTypeNode);
350
+ if (!name) return null;
351
+ const definitionNode = schemaDocumentNode.definitions.find((def) => "kind" in def && "name" in def && def.name?.value === name);
352
+ if (!definitionNode) return null;
353
+ return definitionNode;
354
+ }
355
+ function removeWhitespace(str) {
356
+ return str.replace(/\s+|\\n|\\t/g, "").toLowerCase();
357
+ }
358
+ function compareStringsWithoutWhitespace(str1, str2) {
359
+ if (str1 === null || str2 === null || str1 === void 0 || str2 === void 0) return false;
360
+ return removeWhitespace(str1) === removeWhitespace(str2);
361
+ }
362
+ function renameSchemaType(sdl, oldName, newName, scope) {
363
+ const typeSuffix = scope === "global" ? "State" : "LocalState";
364
+ const oldTypeName = `${pascalCase(oldName)}${typeSuffix}`;
365
+ const newTypeName = `${pascalCase(newName)}${typeSuffix}`;
366
+ const ast = safeParseSdl(sdl);
367
+ if (!ast) return sdl;
368
+ const updatedAst = (0, import_graphql.visit)(ast, { ObjectTypeDefinition: (node) => {
369
+ if (node.name.value === oldTypeName) return {
370
+ ...node,
371
+ name: {
372
+ ...node.name,
373
+ value: newTypeName
374
+ }
375
+ };
376
+ } });
377
+ return (0, import_graphql.print)(updatedAst);
378
+ }
379
+ function initializeModelSchema(modelName) {
380
+ return makeInitialSchemaDoc(modelName, "global");
381
+ }
382
+ /** The initial value the schema sync would write for a new model's schema. */
383
+ function makeInitialValueForSchema(stateSchemaSdl) {
384
+ const documentNode = (0, import_graphql.parse)(stateSchemaSdl);
385
+ const stateTypeDefinitionNode = documentNode.definitions.find((def) => def.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION);
386
+ if (!stateTypeDefinitionNode) return "{}";
387
+ return makeMinimalObjectForStateType({
388
+ sharedSchemaDocumentNode: documentNode,
389
+ stateTypeDefinitionNode,
390
+ existingValue: "{}"
391
+ });
392
+ }
393
+ function updateModelSchemaNames(params) {
394
+ const { oldName, newName, globalStateSchema, localStateSchema, setStateSchema } = params;
395
+ setStateSchema(renameSchemaType(globalStateSchema, oldName, newName, "global"), "global");
396
+ if (localStateSchema) setStateSchema(renameSchemaType(localStateSchema, oldName, newName, "local"), "local");
397
+ }
398
+ function handleModelNameChange(params) {
399
+ const { newName, globalStateSchema, setStateSchema } = params;
400
+ if (!!!globalStateSchema) {
401
+ setStateSchema(initializeModelSchema(newName), "global");
402
+ return;
403
+ }
404
+ updateModelSchemaNames(params);
405
+ }
406
+ function validateStateObject(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateValue) {
407
+ let stateObjectJson;
408
+ try {
409
+ stateObjectJson = JSON.parse(stateValue);
410
+ } catch (error) {
411
+ return [new Error("Invalid JSON object", { cause: error })];
412
+ }
413
+ const typeDefByName = indexTypeDefinitions(sharedSchemaDocumentNode);
414
+ const stateTypeName = stateTypeDefinitionNode.name.value;
415
+ if (!typeDefByName.has(stateTypeName)) return [/* @__PURE__ */ new Error(`State type "${stateTypeName}" was not found in sharedSchemaDocumentNode`)];
416
+ const inputSuffix = "Input";
417
+ const generatedInputDefs = generateInputTypesForObjectTree(stateTypeName, typeDefByName, inputSuffix);
418
+ const augmentedDoc = {
419
+ ...sharedSchemaDocumentNode,
420
+ definitions: [...sharedSchemaDocumentNode.definitions, ...generatedInputDefs]
421
+ };
422
+ let schema;
423
+ try {
424
+ schema = (0, import_graphql.buildASTSchema)(augmentedDoc, { assumeValidSDL: false });
425
+ } catch (e) {
426
+ return [new Error("Failed to build schema from SDL", { cause: e })];
427
+ }
428
+ const inputTypeName = `${stateTypeName}${inputSuffix}`;
429
+ const opDoc = (0, import_graphql.parse)(`query($v: ${inputTypeName}!) { __typename }`);
430
+ const op = (0, import_graphql.getOperationAST)(opDoc);
431
+ if (!op) return [/* @__PURE__ */ new Error("Failed to create validation operation AST")];
432
+ const { errors } = (0, import_graphql.getVariableValues)(schema, op.variableDefinitions ?? [], { v: stateObjectJson });
433
+ const recursiveTypeErrors = detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName);
434
+ const recursiveFieldNames = new Set(recursiveTypeErrors.map((e) => e.field));
435
+ const validationErrors = errors ? graphQLErrorsToStateValidationErrors(errors).filter((e) => {
436
+ if (e instanceof StateValidationError && e.kind === "NON_NULL") {
437
+ const rootField = e.path[0];
438
+ if (typeof rootField === "string" && recursiveFieldNames.has(rootField)) return false;
439
+ }
440
+ return true;
441
+ }) : [];
442
+ validationErrors.unshift(...recursiveTypeErrors);
443
+ const missingOptionalErrors = detectMissingOptionalFields(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateObjectJson);
444
+ validationErrors.push(...missingOptionalErrors);
445
+ return validationErrors;
446
+ }
447
+ /**
448
+ * Indexes object/input/enum/scalar/interface/union type definition nodes by name.
449
+ * Note: only AST definitions that have a "name" field are indexed.
450
+ */
451
+ function indexTypeDefinitions(doc) {
452
+ const map = /* @__PURE__ */ new Map();
453
+ for (const def of doc.definitions) if (def.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION || def.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION || def.kind === import_graphql.Kind.INTERFACE_TYPE_DEFINITION || def.kind === import_graphql.Kind.UNION_TYPE_DEFINITION || def.kind === import_graphql.Kind.OBJECT_TYPE_EXTENSION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION || def.kind === import_graphql.Kind.ENUM_TYPE_EXTENSION || def.kind === import_graphql.Kind.INTERFACE_TYPE_EXTENSION || def.kind === import_graphql.Kind.UNION_TYPE_EXTENSION) {
454
+ const name = def.name.value;
455
+ if (!map.has(name)) map.set(name, def);
456
+ }
457
+ return map;
458
+ }
459
+ /**
460
+ * Generates InputObjectTypeDefinitionNode(s) for a root object type and any nested
461
+ * object types reachable via fields, converting object references to their *Input equivalents*.
462
+ */
463
+ function generateInputTypesForObjectTree(rootObjectTypeName, typeDefByName, inputSuffix) {
464
+ const generated = /* @__PURE__ */ new Map();
465
+ const visiting = /* @__PURE__ */ new Set();
466
+ const ensureInputForObject = (objectTypeName) => {
467
+ const inputName = `${objectTypeName}${inputSuffix}`;
468
+ if (generated.has(inputName)) return;
469
+ if (visiting.has(objectTypeName)) return;
470
+ visiting.add(objectTypeName);
471
+ const def = typeDefByName.get(objectTypeName);
472
+ if (!def) throw new import_graphql.GraphQLError(`Unknown referenced type "${objectTypeName}"`);
473
+ if (def.kind !== import_graphql.Kind.OBJECT_TYPE_DEFINITION && def.kind !== import_graphql.Kind.OBJECT_TYPE_EXTENSION) throw new import_graphql.GraphQLError(`Type "${objectTypeName}" is not an object type; cannot generate input from kind "${def.kind}"`);
474
+ const objDef = def;
475
+ const inputFields = objDef.fields?.map((f) => {
476
+ return {
477
+ kind: import_graphql.Kind.INPUT_VALUE_DEFINITION,
478
+ name: f.name,
479
+ description: f.description,
480
+ directives: [],
481
+ type: convertOutputTypeNodeToInputTypeNode(f.type, typeDefByName, inputSuffix, ensureInputForObject),
482
+ defaultValue: void 0
483
+ };
484
+ }) ?? [];
485
+ const inputDef = {
486
+ kind: import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION,
487
+ name: {
488
+ kind: import_graphql.Kind.NAME,
489
+ value: inputName
490
+ },
491
+ description: objDef.description,
492
+ directives: [],
493
+ fields: inputFields
494
+ };
495
+ generated.set(inputName, inputDef);
496
+ visiting.delete(objectTypeName);
497
+ };
498
+ ensureInputForObject(rootObjectTypeName);
499
+ return Array.from(generated.values());
500
+ }
501
+ function convertOutputTypeNodeToInputTypeNode(typeNode, typeDefByName, inputSuffix, ensureInputForObject) {
502
+ switch (typeNode.kind) {
503
+ case import_graphql.Kind.NON_NULL_TYPE: return {
504
+ kind: import_graphql.Kind.NON_NULL_TYPE,
505
+ type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
506
+ };
507
+ case import_graphql.Kind.LIST_TYPE: return {
508
+ kind: import_graphql.Kind.LIST_TYPE,
509
+ type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
510
+ };
511
+ case import_graphql.Kind.NAMED_TYPE: {
512
+ const named = typeNode;
513
+ const name = named.name.value;
514
+ const def = typeDefByName.get(name);
515
+ if (def?.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || def?.kind === import_graphql.Kind.OBJECT_TYPE_EXTENSION) {
516
+ ensureInputForObject(name);
517
+ return {
518
+ kind: import_graphql.Kind.NAMED_TYPE,
519
+ name: {
520
+ kind: import_graphql.Kind.NAME,
521
+ value: `${name}${inputSuffix}`
522
+ }
523
+ };
524
+ }
525
+ if (!def || def.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION || def.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) return named;
526
+ if (def.kind === import_graphql.Kind.INTERFACE_TYPE_DEFINITION || def.kind === import_graphql.Kind.UNION_TYPE_DEFINITION) throw new import_graphql.GraphQLError(`Type "${name}" (${def.kind}) cannot be used in an input type`);
527
+ throw new import_graphql.GraphQLError(`Unsupported named type "${name}" of kind "${def.kind}"`);
528
+ }
529
+ default: throw new import_graphql.GraphQLError(`Unsupported TypeNode kind: ${JSON.stringify(typeNode)}`);
530
+ }
531
+ }
532
+ var StateValidationError = class extends Error {
533
+ payload;
534
+ originalMessage;
535
+ constructor(payload, originalMessage) {
536
+ super(payload.kind);
537
+ this.name = "StateValidationError";
538
+ this.payload = payload;
539
+ this.originalMessage = originalMessage;
540
+ Object.setPrototypeOf(this, new.target.prototype);
541
+ }
542
+ get kind() {
543
+ return this.payload.kind;
544
+ }
545
+ get path() {
546
+ return this.payload.path;
547
+ }
548
+ get field() {
549
+ return this.payload.field;
550
+ }
551
+ };
552
+ function extractInputPath(message) {
553
+ const match = message.match(/at\s+"([^"]+)"/);
554
+ if (!match) return [];
555
+ const parts = match[1].split(".").filter(Boolean);
556
+ return (parts[0] === "v" ? parts.slice(1) : parts).map((p) => /^\d+$/.test(p) ? Number(p) : p);
557
+ }
558
+ const RE_MISSING_REQUIRED_FIELD = /Field "([^"]+)" of required type "([^"]+)" was not provided\./;
559
+ const RE_UNKNOWN_FIELD = /Field "([^"]+)" is not defined by type "([^"]+)"\.(?: Did you mean "([^"]+)"\?)?/;
560
+ function extractMissingRequiredField(message) {
561
+ const m = message.match(RE_MISSING_REQUIRED_FIELD);
562
+ if (!m) return null;
563
+ return {
564
+ field: m[1],
565
+ expectedType: m[2]
566
+ };
567
+ }
568
+ function extractUnknownField(message) {
569
+ const m = message.match(RE_UNKNOWN_FIELD);
570
+ if (!m) return null;
571
+ return {
572
+ field: m[1],
573
+ typeName: m[2],
574
+ didYouMean: m[3]
575
+ };
576
+ }
577
+ function lastFieldFromPath(path) {
578
+ for (let i = path.length - 1; i >= 0; i--) if (typeof path[i] === "string") return path[i];
579
+ }
580
+ function extractExpectedType(message) {
581
+ let m = message.match(/Expected non-nullable type "([^"]+)"/);
582
+ if (m?.[1]) return m[1];
583
+ m = message.match(/Expected type "([^"]+)"/);
584
+ if (m?.[1]) return m[1];
585
+ m = message.match(/;\s*([_A-Za-z][_0-9A-Za-z]*)\s+cannot represent/i);
586
+ if (m?.[1]) return m[1];
587
+ }
588
+ function graphQLErrorsToStateValidationErrors(errors) {
589
+ const out = [];
590
+ for (const e of errors) {
591
+ const originalMessage = e.message;
592
+ const missing = extractMissingRequiredField(originalMessage);
593
+ if (missing) {
594
+ out.push(new StateValidationError({
595
+ kind: "MISSING",
596
+ path: [missing.field],
597
+ field: missing.field,
598
+ expectedType: missing.expectedType
599
+ }, originalMessage));
600
+ continue;
601
+ }
602
+ const unknown = extractUnknownField(originalMessage);
603
+ if (unknown) {
604
+ out.push(new StateValidationError({
605
+ kind: "UNKNOWN_FIELD",
606
+ path: [unknown.field],
607
+ field: unknown.field,
608
+ didYouMean: unknown.didYouMean
609
+ }, originalMessage));
610
+ continue;
611
+ }
612
+ const path = extractInputPath(originalMessage);
613
+ const field = lastFieldFromPath(path) ?? "value";
614
+ const expectedType = extractExpectedType(originalMessage);
615
+ if (originalMessage.includes("Expected non-nullable type") && originalMessage.includes("not to be null")) {
616
+ out.push(new StateValidationError({
617
+ kind: "NON_NULL",
618
+ path,
619
+ field,
620
+ expectedType
621
+ }, originalMessage));
622
+ continue;
623
+ }
624
+ if (originalMessage.includes("cannot represent") || originalMessage.includes("Expected type")) {
625
+ out.push(new StateValidationError({
626
+ kind: "TYPE",
627
+ path,
628
+ field,
629
+ expectedType,
630
+ details: originalMessage
631
+ }, originalMessage));
632
+ continue;
633
+ }
634
+ out.push(new StateValidationError({
635
+ kind: "TYPE",
636
+ path,
637
+ field,
638
+ details: originalMessage
639
+ }, originalMessage));
640
+ }
641
+ return out;
642
+ }
643
+ /**
644
+ * Finds all fields defined in the schema that are missing from the state object.
645
+ * Returns information about each missing field including whether it's required.
646
+ */
647
+ function findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value, basePath = []) {
648
+ let stateObjectJson;
649
+ try {
650
+ stateObjectJson = typeof value === "string" ? JSON.parse(value) : value;
651
+ } catch {
652
+ return [];
653
+ }
654
+ const typeByName = indexObjectTypes(sharedSchemaDocumentNode);
655
+ const missingFields = [];
656
+ for (const field of rootTypeNode.fields ?? []) {
657
+ const fieldName = field.name.value;
658
+ const fieldPath = [...basePath, fieldName];
659
+ const isRequired = field.type.kind === import_graphql.Kind.NON_NULL_TYPE;
660
+ const underlyingType = isRequired ? field.type.type : field.type;
661
+ if (!(fieldName in stateObjectJson)) {
662
+ missingFields.push({
663
+ fieldName,
664
+ path: fieldPath,
665
+ isRequired,
666
+ type: underlyingType
667
+ });
668
+ continue;
669
+ }
670
+ const namedType = unwrapNamedType(field.type);
671
+ const childType = namedType ? typeByName.get(namedType) : void 0;
672
+ if (childType && typeof stateObjectJson[fieldName] === "object" && stateObjectJson[fieldName] !== null && !Array.isArray(stateObjectJson[fieldName])) {
673
+ const nestedMissing = findMissingFields(sharedSchemaDocumentNode, childType, stateObjectJson[fieldName], fieldPath);
674
+ missingFields.push(...nestedMissing);
675
+ }
676
+ }
677
+ return missingFields;
678
+ }
679
+ /**
680
+ * Detects optional fields defined in the schema that are missing from the state object.
681
+ * Returns StateValidationError[] for each missing optional field.
682
+ */
683
+ function detectMissingOptionalFields(sharedSchemaDocumentNode, rootTypeNode, value) {
684
+ return findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value).filter((field) => !field.isRequired).map((field) => new StateValidationError({
685
+ kind: "MISSING_OPTIONAL",
686
+ path: field.path,
687
+ field: field.fieldName,
688
+ expectedType: typeNodeToString(field.type)
689
+ }));
690
+ }
691
+ /**
692
+ * Detects fields that have recursive types (types that reference themselves directly or indirectly).
693
+ * Returns a RECURSIVE_TYPE error for each field that contains a recursive type.
694
+ */
695
+ function detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName) {
696
+ const errors = [];
697
+ for (const field of stateTypeDefinitionNode.fields ?? []) {
698
+ const fieldName = field.name.value;
699
+ const namedTypeName = getNamedTypeName(field.type);
700
+ if (!namedTypeName) continue;
701
+ if (isRecursiveType(namedTypeName, typeDefByName, /* @__PURE__ */ new Set())) errors.push(new StateValidationError({
702
+ kind: "RECURSIVE_TYPE",
703
+ path: [fieldName],
704
+ field: fieldName,
705
+ typeName: namedTypeName
706
+ }));
707
+ }
708
+ return errors;
709
+ }
710
+ /**
711
+ * Gets the named type name from a TypeNode, unwrapping NonNull and List types.
712
+ */
713
+ function getNamedTypeName(typeNode) {
714
+ if (typeNode.kind === import_graphql.Kind.NAMED_TYPE) return typeNode.name.value;
715
+ if (typeNode.kind === import_graphql.Kind.NON_NULL_TYPE || typeNode.kind === import_graphql.Kind.LIST_TYPE) return getNamedTypeName(typeNode.type);
716
+ return null;
717
+ }
718
+ /**
719
+ * Checks if a type is recursive (references itself directly or indirectly through required fields).
720
+ */
721
+ function isRecursiveType(typeName, typeDefByName, visitedTypes) {
722
+ if (visitedTypes.has(typeName)) return true;
723
+ const typeDef = typeDefByName.get(typeName);
724
+ if (!typeDef || typeDef.kind !== import_graphql.Kind.OBJECT_TYPE_DEFINITION) return false;
725
+ visitedTypes.add(typeName);
726
+ for (const field of typeDef.fields ?? []) {
727
+ if (field.type.kind !== import_graphql.Kind.NON_NULL_TYPE) continue;
728
+ const innerType = field.type.type;
729
+ let fieldTypeName = null;
730
+ if (innerType.kind === import_graphql.Kind.NAMED_TYPE) fieldTypeName = innerType.name.value;
731
+ else if (innerType.kind === import_graphql.Kind.LIST_TYPE) fieldTypeName = getNamedTypeName(innerType);
732
+ if (fieldTypeName && isRecursiveType(fieldTypeName, typeDefByName, visitedTypes)) return true;
733
+ }
734
+ visitedTypes.delete(typeName);
735
+ return false;
736
+ }
737
+ /**
738
+ * Converts a TypeNode to its string representation (e.g., "String", "Int!", "[String]!")
739
+ */
740
+ function typeNodeToString(typeNode) {
741
+ switch (typeNode.kind) {
742
+ case import_graphql.Kind.NAMED_TYPE: return typeNode.name.value;
743
+ case import_graphql.Kind.NON_NULL_TYPE: return `${typeNodeToString(typeNode.type)}!`;
744
+ case import_graphql.Kind.LIST_TYPE: return `[${typeNodeToString(typeNode.type)}]`;
745
+ }
746
+ }
747
+ function indexObjectTypes(doc) {
748
+ const map = /* @__PURE__ */ new Map();
749
+ for (const def of doc.definitions) if (def.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION) map.set(def.name.value, def);
750
+ return map;
751
+ }
752
+ function unwrapNamedType(typeNode) {
753
+ if (typeNode.kind === import_graphql.Kind.NAMED_TYPE) return typeNode.name.value;
754
+ if (typeNode.kind === import_graphql.Kind.NON_NULL_TYPE) return unwrapNamedType(typeNode.type);
755
+ if (typeNode.kind === import_graphql.Kind.LIST_TYPE) return unwrapNamedType(typeNode.type);
756
+ }
757
+ //#endregion
758
+ //#region editors/document-model-editor/utils/linting.ts
759
+ function ensureDocumentContainsNodeWithNameAndType(doc, nodeName, nodeType) {
760
+ const parsedDoc = safeParseSdl(doc);
761
+ if (!parsedDoc) return true;
762
+ return parsedDoc.definitions.some((def) => {
763
+ return def.kind === import_graphql.Kind[nodeType] && "name" in def && def.name?.value === nodeName;
764
+ });
765
+ }
766
+ function createNodeTypeAndNameDiagnostic(doc, errorMessage) {
767
+ const parsedDoc = safeParseSdl(doc);
768
+ if (!parsedDoc) return void 0;
769
+ const firstNode = parsedDoc.definitions[0];
770
+ const nameNode = "name" in firstNode ? firstNode.name : null;
771
+ return {
772
+ from: nameNode?.loc?.start ?? firstNode.loc?.start ?? 0,
773
+ to: nameNode?.loc?.end ?? firstNode.loc?.end ?? 0,
774
+ severity: "error",
775
+ message: errorMessage
776
+ };
777
+ }
778
+ function ensureValidStateSchemaName(doc, modelName, scope) {
779
+ if (!safeParseSdl(doc)) return [];
780
+ const requiredTypeName = makeStateSchemaNameForScope(modelName, scope);
781
+ if (!ensureDocumentContainsNodeWithNameAndType(doc, requiredTypeName, "OBJECT_TYPE_DEFINITION")) return [createNodeTypeAndNameDiagnostic(doc, `${sentenceCase(scope)} state schema must be named ${requiredTypeName}`)].filter((d) => d !== void 0);
782
+ return [];
783
+ }
784
+ function ensureValidOperationSchemaInputName(doc, operationName) {
785
+ if (!doc || !safeParseSdl(doc)) return [];
786
+ const requiredTypeName = `${pascalCase(operationName)}Input`;
787
+ 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);
788
+ return [];
789
+ }
790
+ //#endregion
791
+ //#region editors/document-model-editor/components/button.tsx
792
+ const Button = forwardRef((props, ref) => {
793
+ const { className, ...rest } = props;
794
+ return /* @__PURE__ */ jsx("button", {
795
+ ref,
796
+ ...rest,
797
+ 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)
798
+ });
799
+ });
800
+ //#endregion
801
+ //#region ../../node_modules/.pnpm/@radix-ui+react-compose-refs@1.1.2_@types+react@19.2.14_react@19.2.6/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
802
+ function setRef$1(ref, value) {
803
+ if (typeof ref === "function") return ref(value);
804
+ else if (ref !== null && ref !== void 0) ref.current = value;
805
+ }
806
+ function composeRefs$1(...refs) {
807
+ return (node) => {
808
+ let hasCleanup = false;
809
+ const cleanups = refs.map((ref) => {
810
+ const cleanup = setRef$1(ref, node);
811
+ if (!hasCleanup && typeof cleanup == "function") hasCleanup = true;
812
+ return cleanup;
813
+ });
814
+ if (hasCleanup) return () => {
815
+ for (let i = 0; i < cleanups.length; i++) {
816
+ const cleanup = cleanups[i];
817
+ if (typeof cleanup == "function") cleanup();
818
+ else setRef$1(refs[i], null);
819
+ }
820
+ };
821
+ };
822
+ }
823
+ function useComposedRefs$1(...refs) {
824
+ return React$1.useCallback(composeRefs$1(...refs), refs);
825
+ }
826
+ //#endregion
827
+ //#region editors/document-model-editor/components/divider.tsx
828
+ function Divider({ className, size = "sm", margin = "md" }) {
829
+ function getSize() {
830
+ if (size === "sm") return "h-px";
831
+ if (size === "md") return "h-1";
832
+ return "h-1.5";
833
+ }
834
+ function getMargin() {
835
+ if (margin === "sm") return "my-4";
836
+ if (margin === "md") return "my-6";
837
+ return "my-8";
838
+ }
839
+ const sizeClass = getSize();
840
+ const marginClass = getMargin();
841
+ return /* @__PURE__ */ jsx("div", { className: twMerge("bg-secondary", sizeClass, marginClass, className) });
842
+ }
843
+ //#endregion
844
+ //#region ../../node_modules/.pnpm/react-hook-form@7.71.2_react@19.2.6/node_modules/react-hook-form/dist/index.esm.mjs
845
+ var isCheckBoxInput = (element) => element.type === "checkbox";
846
+ var isDateObject = (value) => value instanceof Date;
847
+ var isNullOrUndefined = (value) => value == null;
848
+ const isObjectType = (value) => typeof value === "object";
849
+ var isObject = (value) => !isNullOrUndefined(value) && !Array.isArray(value) && isObjectType(value) && !isDateObject(value);
850
+ var getEventValue = (event) => isObject(event) && event.target ? isCheckBoxInput(event.target) ? event.target.checked : event.target.value : event;
851
+ var getNodeParentName = (name) => name.substring(0, name.search(/\.\d+(\.|$)/)) || name;
852
+ var isNameInFieldArray = (names, name) => names.has(getNodeParentName(name));
853
+ var isPlainObject = (tempObject) => {
854
+ const prototypeCopy = tempObject.constructor && tempObject.constructor.prototype;
855
+ return isObject(prototypeCopy) && prototypeCopy.hasOwnProperty("isPrototypeOf");
856
+ };
857
+ var isWeb = typeof window !== "undefined" && typeof window.HTMLElement !== "undefined" && typeof document !== "undefined";
858
+ function cloneObject(data) {
859
+ if (data instanceof Date) return new Date(data);
860
+ const isFileListInstance = typeof FileList !== "undefined" && data instanceof FileList;
861
+ if (isWeb && (data instanceof Blob || isFileListInstance)) return data;
862
+ const isArray = Array.isArray(data);
863
+ if (!isArray && !(isObject(data) && isPlainObject(data))) return data;
864
+ const copy = isArray ? [] : Object.create(Object.getPrototypeOf(data));
865
+ for (const key in data) if (Object.prototype.hasOwnProperty.call(data, key)) copy[key] = cloneObject(data[key]);
866
+ return copy;
867
+ }
868
+ var isKey = (value) => /^\w*$/.test(value);
869
+ var isUndefined = (val) => val === void 0;
870
+ var compact = (value) => Array.isArray(value) ? value.filter(Boolean) : [];
871
+ var stringToPath = (input) => compact(input.replace(/["|']|\]/g, "").split(/\.|\[/));
872
+ var get = (object, path, defaultValue) => {
873
+ if (!path || !isObject(object)) return defaultValue;
874
+ const result = (isKey(path) ? [path] : stringToPath(path)).reduce((result, key) => isNullOrUndefined(result) ? result : result[key], object);
875
+ return isUndefined(result) || result === object ? isUndefined(object[path]) ? defaultValue : object[path] : result;
876
+ };
877
+ var isBoolean = (value) => typeof value === "boolean";
878
+ var isFunction = (value) => typeof value === "function";
879
+ var set = (object, path, value) => {
880
+ let index = -1;
881
+ const tempPath = isKey(path) ? [path] : stringToPath(path);
882
+ const length = tempPath.length;
883
+ const lastIndex = length - 1;
884
+ while (++index < length) {
885
+ const key = tempPath[index];
886
+ let newValue = value;
887
+ if (index !== lastIndex) {
888
+ const objValue = object[key];
889
+ newValue = isObject(objValue) || Array.isArray(objValue) ? objValue : !isNaN(+tempPath[index + 1]) ? [] : {};
890
+ }
891
+ if (key === "__proto__" || key === "constructor" || key === "prototype") return;
892
+ object[key] = newValue;
893
+ object = object[key];
894
+ }
895
+ };
896
+ const EVENTS = {
897
+ BLUR: "blur",
898
+ FOCUS_OUT: "focusout",
899
+ CHANGE: "change"
900
+ };
901
+ const VALIDATION_MODE = {
902
+ onBlur: "onBlur",
903
+ onChange: "onChange",
904
+ onSubmit: "onSubmit",
905
+ onTouched: "onTouched",
906
+ all: "all"
907
+ };
908
+ const INPUT_VALIDATION_RULES = {
909
+ max: "max",
910
+ min: "min",
911
+ maxLength: "maxLength",
912
+ minLength: "minLength",
913
+ pattern: "pattern",
914
+ required: "required",
915
+ validate: "validate"
916
+ };
917
+ /**
918
+ * Separate context for `control` to prevent unnecessary rerenders.
919
+ * Internal hooks that only need control use this instead of full form context.
920
+ */
921
+ const HookFormControlContext = React.createContext(null);
922
+ HookFormControlContext.displayName = "HookFormControlContext";
923
+ /**
924
+ * @internal Internal hook to access only control from context.
925
+ */
926
+ const useFormControlContext = () => React.useContext(HookFormControlContext);
927
+ var getProxyFormState = (formState, control, localProxyFormState, isRoot = true) => {
928
+ const result = { defaultValues: control._defaultValues };
929
+ for (const key in formState) Object.defineProperty(result, key, { get: () => {
930
+ const _key = key;
931
+ if (control._proxyFormState[_key] !== VALIDATION_MODE.all) control._proxyFormState[_key] = !isRoot || VALIDATION_MODE.all;
932
+ localProxyFormState && (localProxyFormState[_key] = true);
933
+ return formState[_key];
934
+ } });
935
+ return result;
936
+ };
937
+ const useIsomorphicLayoutEffect = typeof window !== "undefined" ? React.useLayoutEffect : React.useEffect;
938
+ /**
939
+ * This custom hook allows you to subscribe to each form state, and isolate the re-render at the custom hook level. It has its scope in terms of form state subscription, so it would not affect other useFormState and useForm. Using this hook can reduce the re-render impact on large and complex form application.
940
+ *
941
+ * @remarks
942
+ * [API](https://react-hook-form.com/docs/useformstate) • [Demo](https://codesandbox.io/s/useformstate-75xly)
943
+ *
944
+ * @param props - include options on specify fields to subscribe. {@link UseFormStateReturn}
945
+ *
946
+ * @example
947
+ * ```tsx
948
+ * function App() {
949
+ * const { register, handleSubmit, control } = useForm({
950
+ * defaultValues: {
951
+ * firstName: "firstName"
952
+ * }});
953
+ * const { dirtyFields } = useFormState({
954
+ * control
955
+ * });
956
+ * const onSubmit = (data) => console.log(data);
957
+ *
958
+ * return (
959
+ * <form onSubmit={handleSubmit(onSubmit)}>
960
+ * <input {...register("firstName")} placeholder="First Name" />
961
+ * {dirtyFields.firstName && <p>Field is dirty.</p>}
962
+ * <input type="submit" />
963
+ * </form>
964
+ * );
965
+ * }
966
+ * ```
967
+ */
968
+ function useFormState(props) {
969
+ const formControl = useFormControlContext();
970
+ const { control = formControl, disabled, name, exact } = props || {};
971
+ const [formState, updateFormState] = React.useState(control._formState);
972
+ const _localProxyFormState = React.useRef({
973
+ isDirty: false,
974
+ isLoading: false,
975
+ dirtyFields: false,
976
+ touchedFields: false,
977
+ validatingFields: false,
978
+ isValidating: false,
979
+ isValid: false,
980
+ errors: false
981
+ });
982
+ useIsomorphicLayoutEffect(() => control._subscribe({
983
+ name,
984
+ formState: _localProxyFormState.current,
985
+ exact,
986
+ callback: (formState) => {
987
+ !disabled && updateFormState({
988
+ ...control._formState,
989
+ ...formState
990
+ });
991
+ }
992
+ }), [
993
+ name,
994
+ disabled,
995
+ exact
996
+ ]);
997
+ React.useEffect(() => {
998
+ _localProxyFormState.current.isValid && control._setValid(true);
999
+ }, [control]);
1000
+ return React.useMemo(() => getProxyFormState(formState, control, _localProxyFormState.current, false), [formState, control]);
1001
+ }
1002
+ var isString = (value) => typeof value === "string";
1003
+ var generateWatchOutput = (names, _names, formValues, isGlobal, defaultValue) => {
1004
+ if (isString(names)) {
1005
+ isGlobal && _names.watch.add(names);
1006
+ return get(formValues, names, defaultValue);
1007
+ }
1008
+ if (Array.isArray(names)) return names.map((fieldName) => (isGlobal && _names.watch.add(fieldName), get(formValues, fieldName)));
1009
+ isGlobal && (_names.watchAll = true);
1010
+ return formValues;
1011
+ };
1012
+ var isPrimitive = (value) => isNullOrUndefined(value) || !isObjectType(value);
1013
+ function deepEqual(object1, object2, _internal_visited = /* @__PURE__ */ new WeakSet()) {
1014
+ if (isPrimitive(object1) || isPrimitive(object2)) return Object.is(object1, object2);
1015
+ if (isDateObject(object1) && isDateObject(object2)) return Object.is(object1.getTime(), object2.getTime());
1016
+ const keys1 = Object.keys(object1);
1017
+ const keys2 = Object.keys(object2);
1018
+ if (keys1.length !== keys2.length) return false;
1019
+ if (_internal_visited.has(object1) || _internal_visited.has(object2)) return true;
1020
+ _internal_visited.add(object1);
1021
+ _internal_visited.add(object2);
1022
+ for (const key of keys1) {
1023
+ const val1 = object1[key];
1024
+ if (!keys2.includes(key)) return false;
1025
+ if (key !== "ref") {
1026
+ const val2 = object2[key];
1027
+ if (isDateObject(val1) && isDateObject(val2) || isObject(val1) && isObject(val2) || Array.isArray(val1) && Array.isArray(val2) ? !deepEqual(val1, val2, _internal_visited) : !Object.is(val1, val2)) return false;
1028
+ }
1029
+ }
1030
+ return true;
1031
+ }
1032
+ /**
1033
+ * Custom hook to subscribe to field change and isolate re-rendering at the component level.
1034
+ *
1035
+ * @remarks
1036
+ *
1037
+ * [API](https://react-hook-form.com/docs/usewatch) • [Demo](https://codesandbox.io/s/react-hook-form-v7-ts-usewatch-h9i5e)
1038
+ *
1039
+ * @example
1040
+ * ```tsx
1041
+ * const { control } = useForm();
1042
+ * const values = useWatch({
1043
+ * name: "fieldName"
1044
+ * control,
1045
+ * })
1046
+ * ```
1047
+ */
1048
+ function useWatch(props) {
1049
+ const formControl = useFormControlContext();
1050
+ const { control = formControl, name, defaultValue, disabled, exact, compute } = props || {};
1051
+ const _defaultValue = React.useRef(defaultValue);
1052
+ const _compute = React.useRef(compute);
1053
+ const _computeFormValues = React.useRef(void 0);
1054
+ const _prevControl = React.useRef(control);
1055
+ const _prevName = React.useRef(name);
1056
+ _compute.current = compute;
1057
+ const [value, updateValue] = React.useState(() => {
1058
+ const defaultValue = control._getWatch(name, _defaultValue.current);
1059
+ return _compute.current ? _compute.current(defaultValue) : defaultValue;
1060
+ });
1061
+ const getCurrentOutput = React.useCallback((values) => {
1062
+ const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current);
1063
+ return _compute.current ? _compute.current(formValues) : formValues;
1064
+ }, [
1065
+ control._formValues,
1066
+ control._names,
1067
+ name
1068
+ ]);
1069
+ const refreshValue = React.useCallback((values) => {
1070
+ if (!disabled) {
1071
+ const formValues = generateWatchOutput(name, control._names, values || control._formValues, false, _defaultValue.current);
1072
+ if (_compute.current) {
1073
+ const computedFormValues = _compute.current(formValues);
1074
+ if (!deepEqual(computedFormValues, _computeFormValues.current)) {
1075
+ updateValue(computedFormValues);
1076
+ _computeFormValues.current = computedFormValues;
1077
+ }
1078
+ } else updateValue(formValues);
1079
+ }
1080
+ }, [
1081
+ control._formValues,
1082
+ control._names,
1083
+ disabled,
1084
+ name
1085
+ ]);
1086
+ useIsomorphicLayoutEffect(() => {
1087
+ if (_prevControl.current !== control || !deepEqual(_prevName.current, name)) {
1088
+ _prevControl.current = control;
1089
+ _prevName.current = name;
1090
+ refreshValue();
1091
+ }
1092
+ return control._subscribe({
1093
+ name,
1094
+ formState: { values: true },
1095
+ exact,
1096
+ callback: (formState) => {
1097
+ refreshValue(formState.values);
1098
+ }
1099
+ });
1100
+ }, [
1101
+ control,
1102
+ exact,
1103
+ name,
1104
+ refreshValue
1105
+ ]);
1106
+ React.useEffect(() => control._removeUnmounted());
1107
+ const controlChanged = _prevControl.current !== control;
1108
+ const prevName = _prevName.current;
1109
+ const computedOutput = React.useMemo(() => {
1110
+ if (disabled) return null;
1111
+ const nameChanged = !controlChanged && !deepEqual(prevName, name);
1112
+ return controlChanged || nameChanged ? getCurrentOutput() : null;
1113
+ }, [
1114
+ disabled,
1115
+ controlChanged,
1116
+ name,
1117
+ prevName,
1118
+ getCurrentOutput
1119
+ ]);
1120
+ return computedOutput !== null ? computedOutput : value;
1121
+ }
1122
+ /**
1123
+ * Custom hook to work with controlled component, this function provide you with both form and field level state. Re-render is isolated at the hook level.
1124
+ *
1125
+ * @remarks
1126
+ * [API](https://react-hook-form.com/docs/usecontroller) • [Demo](https://codesandbox.io/s/usecontroller-0o8px)
1127
+ *
1128
+ * @param props - the path name to the form field value, and validation rules.
1129
+ *
1130
+ * @returns field properties, field and form state. {@link UseControllerReturn}
1131
+ *
1132
+ * @example
1133
+ * ```tsx
1134
+ * function Input(props) {
1135
+ * const { field, fieldState, formState } = useController(props);
1136
+ * return (
1137
+ * <div>
1138
+ * <input {...field} placeholder={props.name} />
1139
+ * <p>{fieldState.isTouched && "Touched"}</p>
1140
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
1141
+ * </div>
1142
+ * );
1143
+ * }
1144
+ * ```
1145
+ */
1146
+ function useController(props) {
1147
+ const formControl = useFormControlContext();
1148
+ const { name, disabled, control = formControl, shouldUnregister, defaultValue, exact = true } = props;
1149
+ const isArrayField = isNameInFieldArray(control._names.array, name);
1150
+ const value = useWatch({
1151
+ control,
1152
+ name,
1153
+ defaultValue: React.useMemo(() => get(control._formValues, name, get(control._defaultValues, name, defaultValue)), [
1154
+ control,
1155
+ name,
1156
+ defaultValue
1157
+ ]),
1158
+ exact
1159
+ });
1160
+ const formState = useFormState({
1161
+ control,
1162
+ name,
1163
+ exact
1164
+ });
1165
+ const _props = React.useRef(props);
1166
+ const _previousNameRef = React.useRef(void 0);
1167
+ const _registerProps = React.useRef(control.register(name, {
1168
+ ...props.rules,
1169
+ value,
1170
+ ...isBoolean(props.disabled) ? { disabled: props.disabled } : {}
1171
+ }));
1172
+ _props.current = props;
1173
+ const fieldState = React.useMemo(() => Object.defineProperties({}, {
1174
+ invalid: {
1175
+ enumerable: true,
1176
+ get: () => !!get(formState.errors, name)
1177
+ },
1178
+ isDirty: {
1179
+ enumerable: true,
1180
+ get: () => !!get(formState.dirtyFields, name)
1181
+ },
1182
+ isTouched: {
1183
+ enumerable: true,
1184
+ get: () => !!get(formState.touchedFields, name)
1185
+ },
1186
+ isValidating: {
1187
+ enumerable: true,
1188
+ get: () => !!get(formState.validatingFields, name)
1189
+ },
1190
+ error: {
1191
+ enumerable: true,
1192
+ get: () => get(formState.errors, name)
1193
+ }
1194
+ }), [formState, name]);
1195
+ const onChange = React.useCallback((event) => _registerProps.current.onChange({
1196
+ target: {
1197
+ value: getEventValue(event),
1198
+ name
1199
+ },
1200
+ type: EVENTS.CHANGE
1201
+ }), [name]);
1202
+ const onBlur = React.useCallback(() => _registerProps.current.onBlur({
1203
+ target: {
1204
+ value: get(control._formValues, name),
1205
+ name
1206
+ },
1207
+ type: EVENTS.BLUR
1208
+ }), [name, control._formValues]);
1209
+ const ref = React.useCallback((elm) => {
1210
+ const field = get(control._fields, name);
1211
+ if (field && field._f && elm) field._f.ref = {
1212
+ focus: () => isFunction(elm.focus) && elm.focus(),
1213
+ select: () => isFunction(elm.select) && elm.select(),
1214
+ setCustomValidity: (message) => isFunction(elm.setCustomValidity) && elm.setCustomValidity(message),
1215
+ reportValidity: () => isFunction(elm.reportValidity) && elm.reportValidity()
1216
+ };
1217
+ }, [control._fields, name]);
1218
+ const field = React.useMemo(() => ({
1219
+ name,
1220
+ value,
1221
+ ...isBoolean(disabled) || formState.disabled ? { disabled: formState.disabled || disabled } : {},
1222
+ onChange,
1223
+ onBlur,
1224
+ ref
1225
+ }), [
1226
+ name,
1227
+ disabled,
1228
+ formState.disabled,
1229
+ onChange,
1230
+ onBlur,
1231
+ ref,
1232
+ value
1233
+ ]);
1234
+ React.useEffect(() => {
1235
+ const _shouldUnregisterField = control._options.shouldUnregister || shouldUnregister;
1236
+ const previousName = _previousNameRef.current;
1237
+ if (previousName && previousName !== name && !isArrayField) control.unregister(previousName);
1238
+ control.register(name, {
1239
+ ..._props.current.rules,
1240
+ ...isBoolean(_props.current.disabled) ? { disabled: _props.current.disabled } : {}
1241
+ });
1242
+ const updateMounted = (name, value) => {
1243
+ const field = get(control._fields, name);
1244
+ if (field && field._f) field._f.mount = value;
1245
+ };
1246
+ updateMounted(name, true);
1247
+ if (_shouldUnregisterField) {
1248
+ const value = cloneObject(get(control._options.defaultValues, name, _props.current.defaultValue));
1249
+ set(control._defaultValues, name, value);
1250
+ if (isUndefined(get(control._formValues, name))) set(control._formValues, name, value);
1251
+ }
1252
+ !isArrayField && control.register(name);
1253
+ _previousNameRef.current = name;
1254
+ return () => {
1255
+ (isArrayField ? _shouldUnregisterField && !control._state.action : _shouldUnregisterField) ? control.unregister(name) : updateMounted(name, false);
1256
+ };
1257
+ }, [
1258
+ name,
1259
+ control,
1260
+ isArrayField,
1261
+ shouldUnregister
1262
+ ]);
1263
+ React.useEffect(() => {
1264
+ control._setDisabledField({
1265
+ disabled,
1266
+ name
1267
+ });
1268
+ }, [
1269
+ disabled,
1270
+ name,
1271
+ control
1272
+ ]);
1273
+ return React.useMemo(() => ({
1274
+ field,
1275
+ formState,
1276
+ fieldState
1277
+ }), [
1278
+ field,
1279
+ formState,
1280
+ fieldState
1281
+ ]);
1282
+ }
1283
+ /**
1284
+ * Component based on `useController` hook to work with controlled component.
1285
+ *
1286
+ * @remarks
1287
+ * [API](https://react-hook-form.com/docs/usecontroller/controller) • [Demo](https://codesandbox.io/s/react-hook-form-v6-controller-ts-jwyzw) • [Video](https://www.youtube.com/watch?v=N2UNk_UCVyA)
1288
+ *
1289
+ * @param props - the path name to the form field value, and validation rules.
1290
+ *
1291
+ * @returns provide field handler functions, field and form state.
1292
+ *
1293
+ * @example
1294
+ * ```tsx
1295
+ * function App() {
1296
+ * const { control } = useForm<FormValues>({
1297
+ * defaultValues: {
1298
+ * test: ""
1299
+ * }
1300
+ * });
1301
+ *
1302
+ * return (
1303
+ * <form>
1304
+ * <Controller
1305
+ * control={control}
1306
+ * name="test"
1307
+ * render={({ field: { onChange, onBlur, value, ref }, formState, fieldState }) => (
1308
+ * <>
1309
+ * <input
1310
+ * onChange={onChange} // send value to hook form
1311
+ * onBlur={onBlur} // notify when input is touched
1312
+ * value={value} // return updated value
1313
+ * ref={ref} // set ref for focus management
1314
+ * />
1315
+ * <p>{formState.isSubmitted ? "submitted" : ""}</p>
1316
+ * <p>{fieldState.isTouched ? "touched" : ""}</p>
1317
+ * </>
1318
+ * )}
1319
+ * />
1320
+ * </form>
1321
+ * );
1322
+ * }
1323
+ * ```
1324
+ */
1325
+ const Controller = (props) => props.render(useController(props));
1326
+ const HookFormContext = React.createContext(null);
1327
+ HookFormContext.displayName = "HookFormContext";
1328
+ /**
1329
+ * This custom hook allows you to access the form context. useFormContext is intended to be used in deeply nested structures, where it would become inconvenient to pass the context as a prop. To be used with {@link FormProvider}.
1330
+ *
1331
+ * @remarks
1332
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
1333
+ *
1334
+ * @returns return all useForm methods
1335
+ *
1336
+ * @example
1337
+ * ```tsx
1338
+ * function App() {
1339
+ * const methods = useForm();
1340
+ * const onSubmit = data => console.log(data);
1341
+ *
1342
+ * return (
1343
+ * <FormProvider {...methods} >
1344
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
1345
+ * <NestedInput />
1346
+ * <input type="submit" />
1347
+ * </form>
1348
+ * </FormProvider>
1349
+ * );
1350
+ * }
1351
+ *
1352
+ * function NestedInput() {
1353
+ * const { register } = useFormContext(); // retrieve all hook methods
1354
+ * return <input {...register("test")} />;
1355
+ * }
1356
+ * ```
1357
+ */
1358
+ const useFormContext = () => React.useContext(HookFormContext);
1359
+ /**
1360
+ * A provider component that propagates the `useForm` methods to all children components via [React Context](https://react.dev/reference/react/useContext) API. To be used with {@link useFormContext}.
1361
+ *
1362
+ * @remarks
1363
+ * [API](https://react-hook-form.com/docs/useformcontext) • [Demo](https://codesandbox.io/s/react-hook-form-v7-form-context-ytudi)
1364
+ *
1365
+ * @param props - all useForm methods
1366
+ *
1367
+ * @example
1368
+ * ```tsx
1369
+ * function App() {
1370
+ * const methods = useForm();
1371
+ * const onSubmit = data => console.log(data);
1372
+ *
1373
+ * return (
1374
+ * <FormProvider {...methods} >
1375
+ * <form onSubmit={methods.handleSubmit(onSubmit)}>
1376
+ * <NestedInput />
1377
+ * <input type="submit" />
1378
+ * </form>
1379
+ * </FormProvider>
1380
+ * );
1381
+ * }
1382
+ *
1383
+ * function NestedInput() {
1384
+ * const { register } = useFormContext(); // retrieve all hook methods
1385
+ * return <input {...register("test")} />;
1386
+ * }
1387
+ * ```
1388
+ */
1389
+ const FormProvider = (props) => {
1390
+ const { children, watch, getValues, getFieldState, setError, clearErrors, setValue, trigger, formState, resetField, reset, handleSubmit, unregister, control, register, setFocus, subscribe } = props;
1391
+ return React.createElement(HookFormContext.Provider, { value: React.useMemo(() => ({
1392
+ watch,
1393
+ getValues,
1394
+ getFieldState,
1395
+ setError,
1396
+ clearErrors,
1397
+ setValue,
1398
+ trigger,
1399
+ formState,
1400
+ resetField,
1401
+ reset,
1402
+ handleSubmit,
1403
+ unregister,
1404
+ control,
1405
+ register,
1406
+ setFocus,
1407
+ subscribe
1408
+ }), [
1409
+ clearErrors,
1410
+ control,
1411
+ formState,
1412
+ getFieldState,
1413
+ getValues,
1414
+ handleSubmit,
1415
+ register,
1416
+ reset,
1417
+ resetField,
1418
+ setError,
1419
+ setFocus,
1420
+ setValue,
1421
+ subscribe,
1422
+ trigger,
1423
+ unregister,
1424
+ watch
1425
+ ]) }, React.createElement(HookFormControlContext.Provider, { value: control }, children));
1426
+ };
1427
+ var appendErrors = (name, validateAllFieldCriteria, errors, type, message) => validateAllFieldCriteria ? {
1428
+ ...errors[name],
1429
+ types: {
1430
+ ...errors[name] && errors[name].types ? errors[name].types : {},
1431
+ [type]: message || true
1432
+ }
1433
+ } : {};
1434
+ var convertToArrayPayload = (value) => Array.isArray(value) ? value : [value];
1435
+ var createSubject = () => {
1436
+ let _observers = [];
1437
+ const next = (value) => {
1438
+ for (const observer of _observers) observer.next && observer.next(value);
1439
+ };
1440
+ const subscribe = (observer) => {
1441
+ _observers.push(observer);
1442
+ return { unsubscribe: () => {
1443
+ _observers = _observers.filter((o) => o !== observer);
1444
+ } };
1445
+ };
1446
+ const unsubscribe = () => {
1447
+ _observers = [];
1448
+ };
1449
+ return {
1450
+ get observers() {
1451
+ return _observers;
1452
+ },
1453
+ next,
1454
+ subscribe,
1455
+ unsubscribe
1456
+ };
1457
+ };
1458
+ function extractFormValues(fieldsState, formValues) {
1459
+ const values = {};
1460
+ for (const key in fieldsState) if (fieldsState.hasOwnProperty(key)) {
1461
+ const fieldState = fieldsState[key];
1462
+ const fieldValue = formValues[key];
1463
+ if (fieldState && isObject(fieldState) && fieldValue) {
1464
+ const nestedFieldsState = extractFormValues(fieldState, fieldValue);
1465
+ if (isObject(nestedFieldsState)) values[key] = nestedFieldsState;
1466
+ } else if (fieldsState[key]) values[key] = fieldValue;
1467
+ }
1468
+ return values;
1469
+ }
1470
+ var isEmptyObject = (value) => isObject(value) && !Object.keys(value).length;
1471
+ var isFileInput = (element) => element.type === "file";
1472
+ var isHTMLElement = (value) => {
1473
+ if (!isWeb) return false;
1474
+ const owner = value ? value.ownerDocument : 0;
1475
+ return value instanceof (owner && owner.defaultView ? owner.defaultView.HTMLElement : HTMLElement);
1476
+ };
1477
+ var isMultipleSelect = (element) => element.type === `select-multiple`;
1478
+ var isRadioInput = (element) => element.type === "radio";
1479
+ var isRadioOrCheckbox = (ref) => isRadioInput(ref) || isCheckBoxInput(ref);
1480
+ var live = (ref) => isHTMLElement(ref) && ref.isConnected;
1481
+ function baseGet(object, updatePath) {
1482
+ const length = updatePath.slice(0, -1).length;
1483
+ let index = 0;
1484
+ while (index < length) object = isUndefined(object) ? index++ : object[updatePath[index++]];
1485
+ return object;
1486
+ }
1487
+ function isEmptyArray(obj) {
1488
+ for (const key in obj) if (obj.hasOwnProperty(key) && !isUndefined(obj[key])) return false;
1489
+ return true;
1490
+ }
1491
+ function unset(object, path) {
1492
+ const paths = Array.isArray(path) ? path : isKey(path) ? [path] : stringToPath(path);
1493
+ const childObject = paths.length === 1 ? object : baseGet(object, paths);
1494
+ const index = paths.length - 1;
1495
+ const key = paths[index];
1496
+ if (childObject) delete childObject[key];
1497
+ if (index !== 0 && (isObject(childObject) && isEmptyObject(childObject) || Array.isArray(childObject) && isEmptyArray(childObject))) unset(object, paths.slice(0, -1));
1498
+ return object;
1499
+ }
1500
+ var objectHasFunction = (data) => {
1501
+ for (const key in data) if (isFunction(data[key])) return true;
1502
+ return false;
1503
+ };
1504
+ function isTraversable(value) {
1505
+ return Array.isArray(value) || isObject(value) && !objectHasFunction(value);
1506
+ }
1507
+ function markFieldsDirty(data, fields = {}) {
1508
+ for (const key in data) {
1509
+ const value = data[key];
1510
+ if (isTraversable(value)) {
1511
+ fields[key] = Array.isArray(value) ? [] : {};
1512
+ markFieldsDirty(value, fields[key]);
1513
+ } else if (!isUndefined(value)) fields[key] = true;
1514
+ }
1515
+ return fields;
1516
+ }
1517
+ function getDirtyFields(data, formValues, dirtyFieldsFromValues) {
1518
+ if (!dirtyFieldsFromValues) dirtyFieldsFromValues = markFieldsDirty(formValues);
1519
+ for (const key in data) {
1520
+ const value = data[key];
1521
+ if (isTraversable(value)) {
1522
+ if (isUndefined(formValues) || isPrimitive(dirtyFieldsFromValues[key])) dirtyFieldsFromValues[key] = markFieldsDirty(value, Array.isArray(value) ? [] : {});
1523
+ else getDirtyFields(value, isNullOrUndefined(formValues) ? {} : formValues[key], dirtyFieldsFromValues[key]);
1524
+ } else {
1525
+ const formValue = formValues[key];
1526
+ dirtyFieldsFromValues[key] = !deepEqual(value, formValue);
1527
+ }
1528
+ }
1529
+ return dirtyFieldsFromValues;
1530
+ }
1531
+ const defaultResult = {
1532
+ value: false,
1533
+ isValid: false
1534
+ };
1535
+ const validResult = {
1536
+ value: true,
1537
+ isValid: true
1538
+ };
1539
+ var getCheckboxValue = (options) => {
1540
+ if (Array.isArray(options)) {
1541
+ if (options.length > 1) {
1542
+ const values = options.filter((option) => option && option.checked && !option.disabled).map((option) => option.value);
1543
+ return {
1544
+ value: values,
1545
+ isValid: !!values.length
1546
+ };
1547
+ }
1548
+ return options[0].checked && !options[0].disabled ? options[0].attributes && !isUndefined(options[0].attributes.value) ? isUndefined(options[0].value) || options[0].value === "" ? validResult : {
1549
+ value: options[0].value,
1550
+ isValid: true
1551
+ } : validResult : defaultResult;
1552
+ }
1553
+ return defaultResult;
1554
+ };
1555
+ var getFieldValueAs = (value, { valueAsNumber, valueAsDate, setValueAs }) => isUndefined(value) ? value : valueAsNumber ? value === "" ? NaN : value ? +value : value : valueAsDate && isString(value) ? new Date(value) : setValueAs ? setValueAs(value) : value;
1556
+ const defaultReturn = {
1557
+ isValid: false,
1558
+ value: null
1559
+ };
1560
+ var getRadioValue = (options) => Array.isArray(options) ? options.reduce((previous, option) => option && option.checked && !option.disabled ? {
1561
+ isValid: true,
1562
+ value: option.value
1563
+ } : previous, defaultReturn) : defaultReturn;
1564
+ function getFieldValue(_f) {
1565
+ const ref = _f.ref;
1566
+ if (isFileInput(ref)) return ref.files;
1567
+ if (isRadioInput(ref)) return getRadioValue(_f.refs).value;
1568
+ if (isMultipleSelect(ref)) return [...ref.selectedOptions].map(({ value }) => value);
1569
+ if (isCheckBoxInput(ref)) return getCheckboxValue(_f.refs).value;
1570
+ return getFieldValueAs(isUndefined(ref.value) ? _f.ref.value : ref.value, _f);
1571
+ }
1572
+ var getResolverOptions = (fieldsNames, _fields, criteriaMode, shouldUseNativeValidation) => {
1573
+ const fields = {};
1574
+ for (const name of fieldsNames) {
1575
+ const field = get(_fields, name);
1576
+ field && set(fields, name, field._f);
1577
+ }
1578
+ return {
1579
+ criteriaMode,
1580
+ names: [...fieldsNames],
1581
+ fields,
1582
+ shouldUseNativeValidation
1583
+ };
1584
+ };
1585
+ var isRegex = (value) => value instanceof RegExp;
1586
+ var getRuleValue = (rule) => isUndefined(rule) ? rule : isRegex(rule) ? rule.source : isObject(rule) ? isRegex(rule.value) ? rule.value.source : rule.value : rule;
1587
+ var getValidationModes = (mode) => ({
1588
+ isOnSubmit: !mode || mode === VALIDATION_MODE.onSubmit,
1589
+ isOnBlur: mode === VALIDATION_MODE.onBlur,
1590
+ isOnChange: mode === VALIDATION_MODE.onChange,
1591
+ isOnAll: mode === VALIDATION_MODE.all,
1592
+ isOnTouch: mode === VALIDATION_MODE.onTouched
1593
+ });
1594
+ const ASYNC_FUNCTION = "AsyncFunction";
1595
+ var hasPromiseValidation = (fieldReference) => !!fieldReference && !!fieldReference.validate && !!(isFunction(fieldReference.validate) && fieldReference.validate.constructor.name === ASYNC_FUNCTION || isObject(fieldReference.validate) && Object.values(fieldReference.validate).find((validateFunction) => validateFunction.constructor.name === ASYNC_FUNCTION));
1596
+ var hasValidation = (options) => options.mount && (options.required || options.min || options.max || options.maxLength || options.minLength || options.pattern || options.validate);
1597
+ var isWatched = (name, _names, isBlurEvent) => !isBlurEvent && (_names.watchAll || _names.watch.has(name) || [..._names.watch].some((watchName) => name.startsWith(watchName) && /^\.\w+/.test(name.slice(watchName.length))));
1598
+ const iterateFieldsByAction = (fields, action, fieldsNames, abortEarly) => {
1599
+ for (const key of fieldsNames || Object.keys(fields)) {
1600
+ const field = get(fields, key);
1601
+ if (field) {
1602
+ const { _f, ...currentField } = field;
1603
+ if (_f) {
1604
+ if (_f.refs && _f.refs[0] && action(_f.refs[0], key) && !abortEarly) return true;
1605
+ else if (_f.ref && action(_f.ref, _f.name) && !abortEarly) return true;
1606
+ else if (iterateFieldsByAction(currentField, action)) break;
1607
+ } else if (isObject(currentField)) {
1608
+ if (iterateFieldsByAction(currentField, action)) break;
1609
+ }
1610
+ }
1611
+ }
1612
+ };
1613
+ function schemaErrorLookup(errors, _fields, name) {
1614
+ const error = get(errors, name);
1615
+ if (error || isKey(name)) return {
1616
+ error,
1617
+ name
1618
+ };
1619
+ const names = name.split(".");
1620
+ while (names.length) {
1621
+ const fieldName = names.join(".");
1622
+ const field = get(_fields, fieldName);
1623
+ const foundError = get(errors, fieldName);
1624
+ if (field && !Array.isArray(field) && name !== fieldName) return { name };
1625
+ if (foundError && foundError.type) return {
1626
+ name: fieldName,
1627
+ error: foundError
1628
+ };
1629
+ if (foundError && foundError.root && foundError.root.type) return {
1630
+ name: `${fieldName}.root`,
1631
+ error: foundError.root
1632
+ };
1633
+ names.pop();
1634
+ }
1635
+ return { name };
1636
+ }
1637
+ var shouldRenderFormState = (formStateData, _proxyFormState, updateFormState, isRoot) => {
1638
+ updateFormState(formStateData);
1639
+ const { name, ...formState } = formStateData;
1640
+ return isEmptyObject(formState) || Object.keys(formState).length >= Object.keys(_proxyFormState).length || Object.keys(formState).find((key) => _proxyFormState[key] === (!isRoot || VALIDATION_MODE.all));
1641
+ };
1642
+ var shouldSubscribeByName = (name, signalName, exact) => !name || !signalName || name === signalName || convertToArrayPayload(name).some((currentName) => currentName && (exact ? currentName === signalName : currentName.startsWith(signalName) || signalName.startsWith(currentName)));
1643
+ var skipValidation = (isBlurEvent, isTouched, isSubmitted, reValidateMode, mode) => {
1644
+ if (mode.isOnAll) return false;
1645
+ else if (!isSubmitted && mode.isOnTouch) return !(isTouched || isBlurEvent);
1646
+ else if (isSubmitted ? reValidateMode.isOnBlur : mode.isOnBlur) return !isBlurEvent;
1647
+ else if (isSubmitted ? reValidateMode.isOnChange : mode.isOnChange) return isBlurEvent;
1648
+ return true;
1649
+ };
1650
+ var unsetEmptyArray = (ref, name) => !compact(get(ref, name)).length && unset(ref, name);
1651
+ var updateFieldArrayRootError = (errors, error, name) => {
1652
+ const fieldArrayErrors = convertToArrayPayload(get(errors, name));
1653
+ set(fieldArrayErrors, "root", error[name]);
1654
+ set(errors, name, fieldArrayErrors);
1655
+ return errors;
1656
+ };
1657
+ function getValidateError(result, ref, type = "validate") {
1658
+ if (isString(result) || Array.isArray(result) && result.every(isString) || isBoolean(result) && !result) return {
1659
+ type,
1660
+ message: isString(result) ? result : "",
1661
+ ref
1662
+ };
1663
+ }
1664
+ var getValueAndMessage = (validationData) => isObject(validationData) && !isRegex(validationData) ? validationData : {
1665
+ value: validationData,
1666
+ message: ""
1667
+ };
1668
+ var validateField = async (field, disabledFieldNames, formValues, validateAllFieldCriteria, shouldUseNativeValidation, isFieldArray) => {
1669
+ const { ref, refs, required, maxLength, minLength, min, max, pattern, validate, name, valueAsNumber, mount } = field._f;
1670
+ const inputValue = get(formValues, name);
1671
+ if (!mount || disabledFieldNames.has(name)) return {};
1672
+ const inputRef = refs ? refs[0] : ref;
1673
+ const setCustomValidity = (message) => {
1674
+ if (shouldUseNativeValidation && inputRef.reportValidity) {
1675
+ inputRef.setCustomValidity(isBoolean(message) ? "" : message || "");
1676
+ inputRef.reportValidity();
1677
+ }
1678
+ };
1679
+ const error = {};
1680
+ const isRadio = isRadioInput(ref);
1681
+ const isCheckBox = isCheckBoxInput(ref);
1682
+ const isRadioOrCheckbox = isRadio || isCheckBox;
1683
+ const isEmpty = (valueAsNumber || isFileInput(ref)) && isUndefined(ref.value) && isUndefined(inputValue) || isHTMLElement(ref) && ref.value === "" || inputValue === "" || Array.isArray(inputValue) && !inputValue.length;
1684
+ const appendErrorsCurry = appendErrors.bind(null, name, validateAllFieldCriteria, error);
1685
+ const getMinMaxMessage = (exceedMax, maxLengthMessage, minLengthMessage, maxType = INPUT_VALIDATION_RULES.maxLength, minType = INPUT_VALIDATION_RULES.minLength) => {
1686
+ const message = exceedMax ? maxLengthMessage : minLengthMessage;
1687
+ error[name] = {
1688
+ type: exceedMax ? maxType : minType,
1689
+ message,
1690
+ ref,
1691
+ ...appendErrorsCurry(exceedMax ? maxType : minType, message)
1692
+ };
1693
+ };
1694
+ if (isFieldArray ? !Array.isArray(inputValue) || !inputValue.length : required && (!isRadioOrCheckbox && (isEmpty || isNullOrUndefined(inputValue)) || isBoolean(inputValue) && !inputValue || isCheckBox && !getCheckboxValue(refs).isValid || isRadio && !getRadioValue(refs).isValid)) {
1695
+ const { value, message } = isString(required) ? {
1696
+ value: !!required,
1697
+ message: required
1698
+ } : getValueAndMessage(required);
1699
+ if (value) {
1700
+ error[name] = {
1701
+ type: INPUT_VALIDATION_RULES.required,
1702
+ message,
1703
+ ref: inputRef,
1704
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.required, message)
1705
+ };
1706
+ if (!validateAllFieldCriteria) {
1707
+ setCustomValidity(message);
1708
+ return error;
1709
+ }
1710
+ }
1711
+ }
1712
+ if (!isEmpty && (!isNullOrUndefined(min) || !isNullOrUndefined(max))) {
1713
+ let exceedMax;
1714
+ let exceedMin;
1715
+ const maxOutput = getValueAndMessage(max);
1716
+ const minOutput = getValueAndMessage(min);
1717
+ if (!isNullOrUndefined(inputValue) && !isNaN(inputValue)) {
1718
+ const valueNumber = ref.valueAsNumber || (inputValue ? +inputValue : inputValue);
1719
+ if (!isNullOrUndefined(maxOutput.value)) exceedMax = valueNumber > maxOutput.value;
1720
+ if (!isNullOrUndefined(minOutput.value)) exceedMin = valueNumber < minOutput.value;
1721
+ } else {
1722
+ const valueDate = ref.valueAsDate || new Date(inputValue);
1723
+ const convertTimeToDate = (time) => /* @__PURE__ */ new Date((/* @__PURE__ */ new Date()).toDateString() + " " + time);
1724
+ const isTime = ref.type == "time";
1725
+ const isWeek = ref.type == "week";
1726
+ if (isString(maxOutput.value) && inputValue) exceedMax = isTime ? convertTimeToDate(inputValue) > convertTimeToDate(maxOutput.value) : isWeek ? inputValue > maxOutput.value : valueDate > new Date(maxOutput.value);
1727
+ if (isString(minOutput.value) && inputValue) exceedMin = isTime ? convertTimeToDate(inputValue) < convertTimeToDate(minOutput.value) : isWeek ? inputValue < minOutput.value : valueDate < new Date(minOutput.value);
1728
+ }
1729
+ if (exceedMax || exceedMin) {
1730
+ getMinMaxMessage(!!exceedMax, maxOutput.message, minOutput.message, INPUT_VALIDATION_RULES.max, INPUT_VALIDATION_RULES.min);
1731
+ if (!validateAllFieldCriteria) {
1732
+ setCustomValidity(error[name].message);
1733
+ return error;
1734
+ }
1735
+ }
1736
+ }
1737
+ if ((maxLength || minLength) && !isEmpty && (isString(inputValue) || isFieldArray && Array.isArray(inputValue))) {
1738
+ const maxLengthOutput = getValueAndMessage(maxLength);
1739
+ const minLengthOutput = getValueAndMessage(minLength);
1740
+ const exceedMax = !isNullOrUndefined(maxLengthOutput.value) && inputValue.length > +maxLengthOutput.value;
1741
+ const exceedMin = !isNullOrUndefined(minLengthOutput.value) && inputValue.length < +minLengthOutput.value;
1742
+ if (exceedMax || exceedMin) {
1743
+ getMinMaxMessage(exceedMax, maxLengthOutput.message, minLengthOutput.message);
1744
+ if (!validateAllFieldCriteria) {
1745
+ setCustomValidity(error[name].message);
1746
+ return error;
1747
+ }
1748
+ }
1749
+ }
1750
+ if (pattern && !isEmpty && isString(inputValue)) {
1751
+ const { value: patternValue, message } = getValueAndMessage(pattern);
1752
+ if (isRegex(patternValue) && !inputValue.match(patternValue)) {
1753
+ error[name] = {
1754
+ type: INPUT_VALIDATION_RULES.pattern,
1755
+ message,
1756
+ ref,
1757
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.pattern, message)
1758
+ };
1759
+ if (!validateAllFieldCriteria) {
1760
+ setCustomValidity(message);
1761
+ return error;
1762
+ }
1763
+ }
1764
+ }
1765
+ if (validate) {
1766
+ if (isFunction(validate)) {
1767
+ const validateError = getValidateError(await validate(inputValue, formValues), inputRef);
1768
+ if (validateError) {
1769
+ error[name] = {
1770
+ ...validateError,
1771
+ ...appendErrorsCurry(INPUT_VALIDATION_RULES.validate, validateError.message)
1772
+ };
1773
+ if (!validateAllFieldCriteria) {
1774
+ setCustomValidity(validateError.message);
1775
+ return error;
1776
+ }
1777
+ }
1778
+ } else if (isObject(validate)) {
1779
+ let validationResult = {};
1780
+ for (const key in validate) {
1781
+ if (!isEmptyObject(validationResult) && !validateAllFieldCriteria) break;
1782
+ const validateError = getValidateError(await validate[key](inputValue, formValues), inputRef, key);
1783
+ if (validateError) {
1784
+ validationResult = {
1785
+ ...validateError,
1786
+ ...appendErrorsCurry(key, validateError.message)
1787
+ };
1788
+ setCustomValidity(validateError.message);
1789
+ if (validateAllFieldCriteria) error[name] = validationResult;
1790
+ }
1791
+ }
1792
+ if (!isEmptyObject(validationResult)) {
1793
+ error[name] = {
1794
+ ref: inputRef,
1795
+ ...validationResult
1796
+ };
1797
+ if (!validateAllFieldCriteria) return error;
1798
+ }
1799
+ }
1800
+ }
1801
+ setCustomValidity(true);
1802
+ return error;
1803
+ };
1804
+ const defaultOptions = {
1805
+ mode: VALIDATION_MODE.onSubmit,
1806
+ reValidateMode: VALIDATION_MODE.onChange,
1807
+ shouldFocusError: true
1808
+ };
1809
+ function createFormControl(props = {}) {
1810
+ let _options = {
1811
+ ...defaultOptions,
1812
+ ...props
1813
+ };
1814
+ let _formState = {
1815
+ submitCount: 0,
1816
+ isDirty: false,
1817
+ isReady: false,
1818
+ isLoading: isFunction(_options.defaultValues),
1819
+ isValidating: false,
1820
+ isSubmitted: false,
1821
+ isSubmitting: false,
1822
+ isSubmitSuccessful: false,
1823
+ isValid: false,
1824
+ touchedFields: {},
1825
+ dirtyFields: {},
1826
+ validatingFields: {},
1827
+ errors: _options.errors || {},
1828
+ disabled: _options.disabled || false
1829
+ };
1830
+ let _fields = {};
1831
+ let _defaultValues = isObject(_options.defaultValues) || isObject(_options.values) ? cloneObject(_options.defaultValues || _options.values) || {} : {};
1832
+ let _formValues = _options.shouldUnregister ? {} : cloneObject(_defaultValues);
1833
+ let _state = {
1834
+ action: false,
1835
+ mount: false,
1836
+ watch: false,
1837
+ keepIsValid: false
1838
+ };
1839
+ let _names = {
1840
+ mount: /* @__PURE__ */ new Set(),
1841
+ disabled: /* @__PURE__ */ new Set(),
1842
+ unMount: /* @__PURE__ */ new Set(),
1843
+ array: /* @__PURE__ */ new Set(),
1844
+ watch: /* @__PURE__ */ new Set()
1845
+ };
1846
+ let delayErrorCallback;
1847
+ let timer = 0;
1848
+ const defaultProxyFormState = {
1849
+ isDirty: false,
1850
+ dirtyFields: false,
1851
+ validatingFields: false,
1852
+ touchedFields: false,
1853
+ isValidating: false,
1854
+ isValid: false,
1855
+ errors: false
1856
+ };
1857
+ const _proxyFormState = { ...defaultProxyFormState };
1858
+ let _proxySubscribeFormState = { ..._proxyFormState };
1859
+ const _subjects = {
1860
+ array: createSubject(),
1861
+ state: createSubject()
1862
+ };
1863
+ const shouldDisplayAllAssociatedErrors = _options.criteriaMode === VALIDATION_MODE.all;
1864
+ const debounce = (callback) => (wait) => {
1865
+ clearTimeout(timer);
1866
+ timer = setTimeout(callback, wait);
1867
+ };
1868
+ const _setValid = async (shouldUpdateValid) => {
1869
+ if (_state.keepIsValid) return;
1870
+ if (!_options.disabled && (_proxyFormState.isValid || _proxySubscribeFormState.isValid || shouldUpdateValid)) {
1871
+ let isValid;
1872
+ if (_options.resolver) {
1873
+ isValid = isEmptyObject((await _runSchema()).errors);
1874
+ _updateIsValidating();
1875
+ } else isValid = await executeBuiltInValidation(_fields, true);
1876
+ if (isValid !== _formState.isValid) _subjects.state.next({ isValid });
1877
+ }
1878
+ };
1879
+ const _updateIsValidating = (names, isValidating) => {
1880
+ if (!_options.disabled && (_proxyFormState.isValidating || _proxyFormState.validatingFields || _proxySubscribeFormState.isValidating || _proxySubscribeFormState.validatingFields)) {
1881
+ (names || Array.from(_names.mount)).forEach((name) => {
1882
+ if (name) isValidating ? set(_formState.validatingFields, name, isValidating) : unset(_formState.validatingFields, name);
1883
+ });
1884
+ _subjects.state.next({
1885
+ validatingFields: _formState.validatingFields,
1886
+ isValidating: !isEmptyObject(_formState.validatingFields)
1887
+ });
1888
+ }
1889
+ };
1890
+ const _setFieldArray = (name, values = [], method, args, shouldSetValues = true, shouldUpdateFieldsAndState = true) => {
1891
+ if (args && method && !_options.disabled) {
1892
+ _state.action = true;
1893
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_fields, name))) {
1894
+ const fieldValues = method(get(_fields, name), args.argA, args.argB);
1895
+ shouldSetValues && set(_fields, name, fieldValues);
1896
+ }
1897
+ if (shouldUpdateFieldsAndState && Array.isArray(get(_formState.errors, name))) {
1898
+ const errors = method(get(_formState.errors, name), args.argA, args.argB);
1899
+ shouldSetValues && set(_formState.errors, name, errors);
1900
+ unsetEmptyArray(_formState.errors, name);
1901
+ }
1902
+ if ((_proxyFormState.touchedFields || _proxySubscribeFormState.touchedFields) && shouldUpdateFieldsAndState && Array.isArray(get(_formState.touchedFields, name))) {
1903
+ const touchedFields = method(get(_formState.touchedFields, name), args.argA, args.argB);
1904
+ shouldSetValues && set(_formState.touchedFields, name, touchedFields);
1905
+ }
1906
+ if (_proxyFormState.dirtyFields || _proxySubscribeFormState.dirtyFields) _formState.dirtyFields = getDirtyFields(_defaultValues, _formValues);
1907
+ _subjects.state.next({
1908
+ name,
1909
+ isDirty: _getDirty(name, values),
1910
+ dirtyFields: _formState.dirtyFields,
1911
+ errors: _formState.errors,
1912
+ isValid: _formState.isValid
1913
+ });
1914
+ } else set(_formValues, name, values);
1915
+ };
1916
+ const updateErrors = (name, error) => {
1917
+ set(_formState.errors, name, error);
1918
+ _subjects.state.next({ errors: _formState.errors });
1919
+ };
1920
+ const _setErrors = (errors) => {
1921
+ _formState.errors = errors;
1922
+ _subjects.state.next({
1923
+ errors: _formState.errors,
1924
+ isValid: false
1925
+ });
1926
+ };
1927
+ const updateValidAndValue = (name, shouldSkipSetValueAs, value, ref) => {
1928
+ const field = get(_fields, name);
1929
+ if (field) {
1930
+ const defaultValue = get(_formValues, name, isUndefined(value) ? get(_defaultValues, name) : value);
1931
+ isUndefined(defaultValue) || ref && ref.defaultChecked || shouldSkipSetValueAs ? set(_formValues, name, shouldSkipSetValueAs ? defaultValue : getFieldValue(field._f)) : setFieldValue(name, defaultValue);
1932
+ _state.mount && !_state.action && _setValid();
1933
+ }
1934
+ };
1935
+ const updateTouchAndDirty = (name, fieldValue, isBlurEvent, shouldDirty, shouldRender) => {
1936
+ let shouldUpdateField = false;
1937
+ let isPreviousDirty = false;
1938
+ const output = { name };
1939
+ if (!_options.disabled) {
1940
+ if (!isBlurEvent || shouldDirty) {
1941
+ if (_proxyFormState.isDirty || _proxySubscribeFormState.isDirty) {
1942
+ isPreviousDirty = _formState.isDirty;
1943
+ _formState.isDirty = output.isDirty = _getDirty();
1944
+ shouldUpdateField = isPreviousDirty !== output.isDirty;
1945
+ }
1946
+ const isCurrentFieldPristine = deepEqual(get(_defaultValues, name), fieldValue);
1947
+ isPreviousDirty = !!get(_formState.dirtyFields, name);
1948
+ isCurrentFieldPristine ? unset(_formState.dirtyFields, name) : set(_formState.dirtyFields, name, true);
1949
+ output.dirtyFields = _formState.dirtyFields;
1950
+ shouldUpdateField = shouldUpdateField || (_proxyFormState.dirtyFields || _proxySubscribeFormState.dirtyFields) && isPreviousDirty !== !isCurrentFieldPristine;
1951
+ }
1952
+ if (isBlurEvent) {
1953
+ const isPreviousFieldTouched = get(_formState.touchedFields, name);
1954
+ if (!isPreviousFieldTouched) {
1955
+ set(_formState.touchedFields, name, isBlurEvent);
1956
+ output.touchedFields = _formState.touchedFields;
1957
+ shouldUpdateField = shouldUpdateField || (_proxyFormState.touchedFields || _proxySubscribeFormState.touchedFields) && isPreviousFieldTouched !== isBlurEvent;
1958
+ }
1959
+ }
1960
+ shouldUpdateField && shouldRender && _subjects.state.next(output);
1961
+ }
1962
+ return shouldUpdateField ? output : {};
1963
+ };
1964
+ const shouldRenderByError = (name, isValid, error, fieldState) => {
1965
+ const previousFieldError = get(_formState.errors, name);
1966
+ const shouldUpdateValid = (_proxyFormState.isValid || _proxySubscribeFormState.isValid) && isBoolean(isValid) && _formState.isValid !== isValid;
1967
+ if (_options.delayError && error) {
1968
+ delayErrorCallback = debounce(() => updateErrors(name, error));
1969
+ delayErrorCallback(_options.delayError);
1970
+ } else {
1971
+ clearTimeout(timer);
1972
+ delayErrorCallback = null;
1973
+ error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
1974
+ }
1975
+ if ((error ? !deepEqual(previousFieldError, error) : previousFieldError) || !isEmptyObject(fieldState) || shouldUpdateValid) {
1976
+ const updatedFormState = {
1977
+ ...fieldState,
1978
+ ...shouldUpdateValid && isBoolean(isValid) ? { isValid } : {},
1979
+ errors: _formState.errors,
1980
+ name
1981
+ };
1982
+ _formState = {
1983
+ ..._formState,
1984
+ ...updatedFormState
1985
+ };
1986
+ _subjects.state.next(updatedFormState);
1987
+ }
1988
+ };
1989
+ const _runSchema = async (name) => {
1990
+ _updateIsValidating(name, true);
1991
+ return await _options.resolver(_formValues, _options.context, getResolverOptions(name || _names.mount, _fields, _options.criteriaMode, _options.shouldUseNativeValidation));
1992
+ };
1993
+ const executeSchemaAndUpdateState = async (names) => {
1994
+ const { errors } = await _runSchema(names);
1995
+ _updateIsValidating(names);
1996
+ if (names) for (const name of names) {
1997
+ const error = get(errors, name);
1998
+ error ? set(_formState.errors, name, error) : unset(_formState.errors, name);
1999
+ }
2000
+ else _formState.errors = errors;
2001
+ return errors;
2002
+ };
2003
+ const executeBuiltInValidation = async (fields, shouldOnlyCheckValid, context = { valid: true }) => {
2004
+ for (const name in fields) {
2005
+ const field = fields[name];
2006
+ if (field) {
2007
+ const { _f, ...fieldValue } = field;
2008
+ if (_f) {
2009
+ const isFieldArrayRoot = _names.array.has(_f.name);
2010
+ const isPromiseFunction = field._f && hasPromiseValidation(field._f);
2011
+ if (isPromiseFunction && _proxyFormState.validatingFields) _updateIsValidating([_f.name], true);
2012
+ const fieldError = await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation && !shouldOnlyCheckValid, isFieldArrayRoot);
2013
+ if (isPromiseFunction && _proxyFormState.validatingFields) _updateIsValidating([_f.name]);
2014
+ if (fieldError[_f.name]) {
2015
+ context.valid = false;
2016
+ if (shouldOnlyCheckValid || props.shouldUseNativeValidation) break;
2017
+ }
2018
+ !shouldOnlyCheckValid && (get(fieldError, _f.name) ? isFieldArrayRoot ? updateFieldArrayRootError(_formState.errors, fieldError, _f.name) : set(_formState.errors, _f.name, fieldError[_f.name]) : unset(_formState.errors, _f.name));
2019
+ }
2020
+ !isEmptyObject(fieldValue) && await executeBuiltInValidation(fieldValue, shouldOnlyCheckValid, context);
2021
+ }
2022
+ }
2023
+ return context.valid;
2024
+ };
2025
+ const _removeUnmounted = () => {
2026
+ for (const name of _names.unMount) {
2027
+ const field = get(_fields, name);
2028
+ field && (field._f.refs ? field._f.refs.every((ref) => !live(ref)) : !live(field._f.ref)) && unregister(name);
2029
+ }
2030
+ _names.unMount = /* @__PURE__ */ new Set();
2031
+ };
2032
+ const _getDirty = (name, data) => !_options.disabled && (name && data && set(_formValues, name, data), !deepEqual(getValues(), _defaultValues));
2033
+ const _getWatch = (names, defaultValue, isGlobal) => generateWatchOutput(names, _names, { ..._state.mount ? _formValues : isUndefined(defaultValue) ? _defaultValues : isString(names) ? { [names]: defaultValue } : defaultValue }, isGlobal, defaultValue);
2034
+ const _getFieldArray = (name) => compact(get(_state.mount ? _formValues : _defaultValues, name, _options.shouldUnregister ? get(_defaultValues, name, []) : []));
2035
+ const setFieldValue = (name, value, options = {}) => {
2036
+ const field = get(_fields, name);
2037
+ let fieldValue = value;
2038
+ if (field) {
2039
+ const fieldReference = field._f;
2040
+ if (fieldReference) {
2041
+ !fieldReference.disabled && set(_formValues, name, getFieldValueAs(value, fieldReference));
2042
+ fieldValue = isHTMLElement(fieldReference.ref) && isNullOrUndefined(value) ? "" : value;
2043
+ if (isMultipleSelect(fieldReference.ref)) [...fieldReference.ref.options].forEach((optionRef) => optionRef.selected = fieldValue.includes(optionRef.value));
2044
+ else if (fieldReference.refs) {
2045
+ if (isCheckBoxInput(fieldReference.ref)) fieldReference.refs.forEach((checkboxRef) => {
2046
+ if (!checkboxRef.defaultChecked || !checkboxRef.disabled) {
2047
+ if (Array.isArray(fieldValue)) checkboxRef.checked = !!fieldValue.find((data) => data === checkboxRef.value);
2048
+ else checkboxRef.checked = fieldValue === checkboxRef.value || !!fieldValue;
2049
+ }
2050
+ });
2051
+ else fieldReference.refs.forEach((radioRef) => radioRef.checked = radioRef.value === fieldValue);
2052
+ } else if (isFileInput(fieldReference.ref)) fieldReference.ref.value = "";
2053
+ else {
2054
+ fieldReference.ref.value = fieldValue;
2055
+ if (!fieldReference.ref.type) _subjects.state.next({
2056
+ name,
2057
+ values: cloneObject(_formValues)
2058
+ });
2059
+ }
2060
+ }
2061
+ }
2062
+ (options.shouldDirty || options.shouldTouch) && updateTouchAndDirty(name, fieldValue, options.shouldTouch, options.shouldDirty, true);
2063
+ options.shouldValidate && trigger(name);
2064
+ };
2065
+ const setValues = (name, value, options) => {
2066
+ for (const fieldKey in value) {
2067
+ if (!value.hasOwnProperty(fieldKey)) return;
2068
+ const fieldValue = value[fieldKey];
2069
+ const fieldName = name + "." + fieldKey;
2070
+ const field = get(_fields, fieldName);
2071
+ (_names.array.has(name) || isObject(fieldValue) || field && !field._f) && !isDateObject(fieldValue) ? setValues(fieldName, fieldValue, options) : setFieldValue(fieldName, fieldValue, options);
2072
+ }
2073
+ };
2074
+ const setValue = (name, value, options = {}) => {
2075
+ const field = get(_fields, name);
2076
+ const isFieldArray = _names.array.has(name);
2077
+ const cloneValue = cloneObject(value);
2078
+ set(_formValues, name, cloneValue);
2079
+ if (isFieldArray) {
2080
+ _subjects.array.next({
2081
+ name,
2082
+ values: cloneObject(_formValues)
2083
+ });
2084
+ if ((_proxyFormState.isDirty || _proxyFormState.dirtyFields || _proxySubscribeFormState.isDirty || _proxySubscribeFormState.dirtyFields) && options.shouldDirty) _subjects.state.next({
2085
+ name,
2086
+ dirtyFields: getDirtyFields(_defaultValues, _formValues),
2087
+ isDirty: _getDirty(name, cloneValue)
2088
+ });
2089
+ } else field && !field._f && !isNullOrUndefined(cloneValue) ? setValues(name, cloneValue, options) : setFieldValue(name, cloneValue, options);
2090
+ if (isWatched(name, _names)) _subjects.state.next({
2091
+ ..._formState,
2092
+ name,
2093
+ values: cloneObject(_formValues)
2094
+ });
2095
+ else _subjects.state.next({
2096
+ name: _state.mount ? name : void 0,
2097
+ values: cloneObject(_formValues)
2098
+ });
2099
+ };
2100
+ const onChange = async (event) => {
2101
+ _state.mount = true;
2102
+ const target = event.target;
2103
+ let name = target.name;
2104
+ let isFieldValueUpdated = true;
2105
+ const field = get(_fields, name);
2106
+ const _updateIsFieldValueUpdated = (fieldValue) => {
2107
+ isFieldValueUpdated = Number.isNaN(fieldValue) || isDateObject(fieldValue) && isNaN(fieldValue.getTime()) || deepEqual(fieldValue, get(_formValues, name, fieldValue));
2108
+ };
2109
+ const validationModeBeforeSubmit = getValidationModes(_options.mode);
2110
+ const validationModeAfterSubmit = getValidationModes(_options.reValidateMode);
2111
+ if (field) {
2112
+ let error;
2113
+ let isValid;
2114
+ const fieldValue = target.type ? getFieldValue(field._f) : getEventValue(event);
2115
+ const isBlurEvent = event.type === EVENTS.BLUR || event.type === EVENTS.FOCUS_OUT;
2116
+ const shouldSkipValidation = !hasValidation(field._f) && !_options.resolver && !get(_formState.errors, name) && !field._f.deps || skipValidation(isBlurEvent, get(_formState.touchedFields, name), _formState.isSubmitted, validationModeAfterSubmit, validationModeBeforeSubmit);
2117
+ const watched = isWatched(name, _names, isBlurEvent);
2118
+ set(_formValues, name, fieldValue);
2119
+ if (isBlurEvent) {
2120
+ if (!target || !target.readOnly) {
2121
+ field._f.onBlur && field._f.onBlur(event);
2122
+ delayErrorCallback && delayErrorCallback(0);
2123
+ }
2124
+ } else if (field._f.onChange) field._f.onChange(event);
2125
+ const fieldState = updateTouchAndDirty(name, fieldValue, isBlurEvent);
2126
+ const shouldRender = !isEmptyObject(fieldState) || watched;
2127
+ !isBlurEvent && _subjects.state.next({
2128
+ name,
2129
+ type: event.type,
2130
+ values: cloneObject(_formValues)
2131
+ });
2132
+ if (shouldSkipValidation) {
2133
+ if (_proxyFormState.isValid || _proxySubscribeFormState.isValid) {
2134
+ if (_options.mode === "onBlur") {
2135
+ if (isBlurEvent) _setValid();
2136
+ } else if (!isBlurEvent) _setValid();
2137
+ }
2138
+ return shouldRender && _subjects.state.next({
2139
+ name,
2140
+ ...watched ? {} : fieldState
2141
+ });
2142
+ }
2143
+ !isBlurEvent && watched && _subjects.state.next({ ..._formState });
2144
+ if (_options.resolver) {
2145
+ const { errors } = await _runSchema([name]);
2146
+ _updateIsValidating([name]);
2147
+ _updateIsFieldValueUpdated(fieldValue);
2148
+ if (isFieldValueUpdated) {
2149
+ const previousErrorLookupResult = schemaErrorLookup(_formState.errors, _fields, name);
2150
+ const errorLookupResult = schemaErrorLookup(errors, _fields, previousErrorLookupResult.name || name);
2151
+ error = errorLookupResult.error;
2152
+ name = errorLookupResult.name;
2153
+ isValid = isEmptyObject(errors);
2154
+ }
2155
+ } else {
2156
+ _updateIsValidating([name], true);
2157
+ error = (await validateField(field, _names.disabled, _formValues, shouldDisplayAllAssociatedErrors, _options.shouldUseNativeValidation))[name];
2158
+ _updateIsValidating([name]);
2159
+ _updateIsFieldValueUpdated(fieldValue);
2160
+ if (isFieldValueUpdated) {
2161
+ if (error) isValid = false;
2162
+ else if (_proxyFormState.isValid || _proxySubscribeFormState.isValid) isValid = await executeBuiltInValidation(_fields, true);
2163
+ }
2164
+ }
2165
+ if (isFieldValueUpdated) {
2166
+ field._f.deps && (!Array.isArray(field._f.deps) || field._f.deps.length > 0) && trigger(field._f.deps);
2167
+ shouldRenderByError(name, isValid, error, fieldState);
2168
+ }
2169
+ }
2170
+ };
2171
+ const _focusInput = (ref, key) => {
2172
+ if (get(_formState.errors, key) && ref.focus) {
2173
+ ref.focus();
2174
+ return 1;
2175
+ }
2176
+ };
2177
+ const trigger = async (name, options = {}) => {
2178
+ let isValid;
2179
+ let validationResult;
2180
+ const fieldNames = convertToArrayPayload(name);
2181
+ if (_options.resolver) {
2182
+ const errors = await executeSchemaAndUpdateState(isUndefined(name) ? name : fieldNames);
2183
+ isValid = isEmptyObject(errors);
2184
+ validationResult = name ? !fieldNames.some((name) => get(errors, name)) : isValid;
2185
+ } else if (name) {
2186
+ validationResult = (await Promise.all(fieldNames.map(async (fieldName) => {
2187
+ const field = get(_fields, fieldName);
2188
+ return await executeBuiltInValidation(field && field._f ? { [fieldName]: field } : field);
2189
+ }))).every(Boolean);
2190
+ (validationResult || _formState.isValid) && _setValid();
2191
+ } else validationResult = isValid = await executeBuiltInValidation(_fields);
2192
+ _subjects.state.next({
2193
+ ...!isString(name) || (_proxyFormState.isValid || _proxySubscribeFormState.isValid) && isValid !== _formState.isValid ? {} : { name },
2194
+ ..._options.resolver || !name ? { isValid } : {},
2195
+ errors: _formState.errors
2196
+ });
2197
+ options.shouldFocus && !validationResult && iterateFieldsByAction(_fields, _focusInput, name ? fieldNames : _names.mount);
2198
+ return validationResult;
2199
+ };
2200
+ const getValues = (fieldNames, config) => {
2201
+ let values = { ..._state.mount ? _formValues : _defaultValues };
2202
+ if (config) values = extractFormValues(config.dirtyFields ? _formState.dirtyFields : _formState.touchedFields, values);
2203
+ return isUndefined(fieldNames) ? values : isString(fieldNames) ? get(values, fieldNames) : fieldNames.map((name) => get(values, name));
2204
+ };
2205
+ const getFieldState = (name, formState) => ({
2206
+ invalid: !!get((formState || _formState).errors, name),
2207
+ isDirty: !!get((formState || _formState).dirtyFields, name),
2208
+ error: get((formState || _formState).errors, name),
2209
+ isValidating: !!get(_formState.validatingFields, name),
2210
+ isTouched: !!get((formState || _formState).touchedFields, name)
2211
+ });
2212
+ const clearErrors = (name) => {
2213
+ const names = name ? convertToArrayPayload(name) : void 0;
2214
+ names === null || names === void 0 || names.forEach((inputName) => unset(_formState.errors, inputName));
2215
+ if (names) names.forEach((inputName) => {
2216
+ _subjects.state.next({
2217
+ name: inputName,
2218
+ errors: _formState.errors
2219
+ });
2220
+ });
2221
+ else _subjects.state.next({ errors: {} });
2222
+ };
2223
+ const setError = (name, error, options) => {
2224
+ const ref = (get(_fields, name, { _f: {} })._f || {}).ref;
2225
+ const { ref: currentRef, message, type, ...restOfErrorTree } = get(_formState.errors, name) || {};
2226
+ set(_formState.errors, name, {
2227
+ ...restOfErrorTree,
2228
+ ...error,
2229
+ ref
2230
+ });
2231
+ _subjects.state.next({
2232
+ name,
2233
+ errors: _formState.errors,
2234
+ isValid: false
2235
+ });
2236
+ options && options.shouldFocus && ref && ref.focus && ref.focus();
2237
+ };
2238
+ const watch = (name, defaultValue) => isFunction(name) ? _subjects.state.subscribe({ next: (payload) => "values" in payload && name(_getWatch(void 0, defaultValue), payload) }) : _getWatch(name, defaultValue, true);
2239
+ const _subscribe = (props) => _subjects.state.subscribe({ next: (formState) => {
2240
+ if (shouldSubscribeByName(props.name, formState.name, props.exact) && shouldRenderFormState(formState, props.formState || _proxyFormState, _setFormState, props.reRenderRoot)) props.callback({
2241
+ values: { ..._formValues },
2242
+ ..._formState,
2243
+ ...formState,
2244
+ defaultValues: _defaultValues
2245
+ });
2246
+ } }).unsubscribe;
2247
+ const subscribe = (props) => {
2248
+ _state.mount = true;
2249
+ _proxySubscribeFormState = {
2250
+ ..._proxySubscribeFormState,
2251
+ ...props.formState
2252
+ };
2253
+ return _subscribe({
2254
+ ...props,
2255
+ formState: {
2256
+ ...defaultProxyFormState,
2257
+ ...props.formState
2258
+ }
2259
+ });
2260
+ };
2261
+ const unregister = (name, options = {}) => {
2262
+ for (const fieldName of name ? convertToArrayPayload(name) : _names.mount) {
2263
+ _names.mount.delete(fieldName);
2264
+ _names.array.delete(fieldName);
2265
+ if (!options.keepValue) {
2266
+ unset(_fields, fieldName);
2267
+ unset(_formValues, fieldName);
2268
+ }
2269
+ !options.keepError && unset(_formState.errors, fieldName);
2270
+ !options.keepDirty && unset(_formState.dirtyFields, fieldName);
2271
+ !options.keepTouched && unset(_formState.touchedFields, fieldName);
2272
+ !options.keepIsValidating && unset(_formState.validatingFields, fieldName);
2273
+ !_options.shouldUnregister && !options.keepDefaultValue && unset(_defaultValues, fieldName);
2274
+ }
2275
+ _subjects.state.next({ values: cloneObject(_formValues) });
2276
+ _subjects.state.next({
2277
+ ..._formState,
2278
+ ...!options.keepDirty ? {} : { isDirty: _getDirty() }
2279
+ });
2280
+ !options.keepIsValid && _setValid();
2281
+ };
2282
+ const _setDisabledField = ({ disabled, name }) => {
2283
+ if (isBoolean(disabled) && _state.mount || !!disabled || _names.disabled.has(name)) {
2284
+ const disabledStateChanged = _names.disabled.has(name) !== !!disabled;
2285
+ disabled ? _names.disabled.add(name) : _names.disabled.delete(name);
2286
+ disabledStateChanged && _state.mount && !_state.action && _setValid();
2287
+ }
2288
+ };
2289
+ const register = (name, options = {}) => {
2290
+ let field = get(_fields, name);
2291
+ const disabledIsDefined = isBoolean(options.disabled) || isBoolean(_options.disabled);
2292
+ set(_fields, name, {
2293
+ ...field || {},
2294
+ _f: {
2295
+ ...field && field._f ? field._f : { ref: { name } },
2296
+ name,
2297
+ mount: true,
2298
+ ...options
2299
+ }
2300
+ });
2301
+ _names.mount.add(name);
2302
+ if (field) _setDisabledField({
2303
+ disabled: isBoolean(options.disabled) ? options.disabled : _options.disabled,
2304
+ name
2305
+ });
2306
+ else updateValidAndValue(name, true, options.value);
2307
+ return {
2308
+ ...disabledIsDefined ? { disabled: options.disabled || _options.disabled } : {},
2309
+ ..._options.progressive ? {
2310
+ required: !!options.required,
2311
+ min: getRuleValue(options.min),
2312
+ max: getRuleValue(options.max),
2313
+ minLength: getRuleValue(options.minLength),
2314
+ maxLength: getRuleValue(options.maxLength),
2315
+ pattern: getRuleValue(options.pattern)
2316
+ } : {},
2317
+ name,
2318
+ onChange,
2319
+ onBlur: onChange,
2320
+ ref: (ref) => {
2321
+ if (ref) {
2322
+ register(name, options);
2323
+ field = get(_fields, name);
2324
+ const fieldRef = isUndefined(ref.value) ? ref.querySelectorAll ? ref.querySelectorAll("input,select,textarea")[0] || ref : ref : ref;
2325
+ const radioOrCheckbox = isRadioOrCheckbox(fieldRef);
2326
+ const refs = field._f.refs || [];
2327
+ if (radioOrCheckbox ? refs.find((option) => option === fieldRef) : fieldRef === field._f.ref) return;
2328
+ set(_fields, name, { _f: {
2329
+ ...field._f,
2330
+ ...radioOrCheckbox ? {
2331
+ refs: [
2332
+ ...refs.filter(live),
2333
+ fieldRef,
2334
+ ...Array.isArray(get(_defaultValues, name)) ? [{}] : []
2335
+ ],
2336
+ ref: {
2337
+ type: fieldRef.type,
2338
+ name
2339
+ }
2340
+ } : { ref: fieldRef }
2341
+ } });
2342
+ updateValidAndValue(name, false, void 0, fieldRef);
2343
+ } else {
2344
+ field = get(_fields, name, {});
2345
+ if (field._f) field._f.mount = false;
2346
+ (_options.shouldUnregister || options.shouldUnregister) && !(isNameInFieldArray(_names.array, name) && _state.action) && _names.unMount.add(name);
2347
+ }
2348
+ }
2349
+ };
2350
+ };
2351
+ const _focusError = () => _options.shouldFocusError && iterateFieldsByAction(_fields, _focusInput, _names.mount);
2352
+ const _disableForm = (disabled) => {
2353
+ if (isBoolean(disabled)) {
2354
+ _subjects.state.next({ disabled });
2355
+ iterateFieldsByAction(_fields, (ref, name) => {
2356
+ const currentField = get(_fields, name);
2357
+ if (currentField) {
2358
+ ref.disabled = currentField._f.disabled || disabled;
2359
+ if (Array.isArray(currentField._f.refs)) currentField._f.refs.forEach((inputRef) => {
2360
+ inputRef.disabled = currentField._f.disabled || disabled;
2361
+ });
2362
+ }
2363
+ }, 0, false);
2364
+ }
2365
+ };
2366
+ const handleSubmit = (onValid, onInvalid) => async (e) => {
2367
+ let onValidError = void 0;
2368
+ if (e) {
2369
+ e.preventDefault && e.preventDefault();
2370
+ e.persist && e.persist();
2371
+ }
2372
+ let fieldValues = cloneObject(_formValues);
2373
+ _subjects.state.next({ isSubmitting: true });
2374
+ if (_options.resolver) {
2375
+ const { errors, values } = await _runSchema();
2376
+ _updateIsValidating();
2377
+ _formState.errors = errors;
2378
+ fieldValues = cloneObject(values);
2379
+ } else await executeBuiltInValidation(_fields);
2380
+ if (_names.disabled.size) for (const name of _names.disabled) unset(fieldValues, name);
2381
+ unset(_formState.errors, "root");
2382
+ if (isEmptyObject(_formState.errors)) {
2383
+ _subjects.state.next({ errors: {} });
2384
+ try {
2385
+ await onValid(fieldValues, e);
2386
+ } catch (error) {
2387
+ onValidError = error;
2388
+ }
2389
+ } else {
2390
+ if (onInvalid) await onInvalid({ ..._formState.errors }, e);
2391
+ _focusError();
2392
+ setTimeout(_focusError);
2393
+ }
2394
+ _subjects.state.next({
2395
+ isSubmitted: true,
2396
+ isSubmitting: false,
2397
+ isSubmitSuccessful: isEmptyObject(_formState.errors) && !onValidError,
2398
+ submitCount: _formState.submitCount + 1,
2399
+ errors: _formState.errors
2400
+ });
2401
+ if (onValidError) throw onValidError;
2402
+ };
2403
+ const resetField = (name, options = {}) => {
2404
+ if (get(_fields, name)) {
2405
+ if (isUndefined(options.defaultValue)) setValue(name, cloneObject(get(_defaultValues, name)));
2406
+ else {
2407
+ setValue(name, options.defaultValue);
2408
+ set(_defaultValues, name, cloneObject(options.defaultValue));
2409
+ }
2410
+ if (!options.keepTouched) unset(_formState.touchedFields, name);
2411
+ if (!options.keepDirty) {
2412
+ unset(_formState.dirtyFields, name);
2413
+ _formState.isDirty = options.defaultValue ? _getDirty(name, cloneObject(get(_defaultValues, name))) : _getDirty();
2414
+ }
2415
+ if (!options.keepError) {
2416
+ unset(_formState.errors, name);
2417
+ _proxyFormState.isValid && _setValid();
2418
+ }
2419
+ _subjects.state.next({ ..._formState });
2420
+ }
2421
+ };
2422
+ const _reset = (formValues, keepStateOptions = {}) => {
2423
+ const updatedValues = formValues ? cloneObject(formValues) : _defaultValues;
2424
+ const cloneUpdatedValues = cloneObject(updatedValues);
2425
+ const isEmptyResetValues = isEmptyObject(formValues);
2426
+ const values = isEmptyResetValues ? _defaultValues : cloneUpdatedValues;
2427
+ if (!keepStateOptions.keepDefaultValues) _defaultValues = updatedValues;
2428
+ if (!keepStateOptions.keepValues) {
2429
+ if (keepStateOptions.keepDirtyValues) {
2430
+ const fieldsToCheck = /* @__PURE__ */ new Set([..._names.mount, ...Object.keys(getDirtyFields(_defaultValues, _formValues))]);
2431
+ for (const fieldName of Array.from(fieldsToCheck)) {
2432
+ const isDirty = get(_formState.dirtyFields, fieldName);
2433
+ const existingValue = get(_formValues, fieldName);
2434
+ const newValue = get(values, fieldName);
2435
+ if (isDirty && !isUndefined(existingValue)) set(values, fieldName, existingValue);
2436
+ else if (!isDirty && !isUndefined(newValue)) setValue(fieldName, newValue);
2437
+ }
2438
+ } else {
2439
+ if (isWeb && isUndefined(formValues)) for (const name of _names.mount) {
2440
+ const field = get(_fields, name);
2441
+ if (field && field._f) {
2442
+ const fieldReference = Array.isArray(field._f.refs) ? field._f.refs[0] : field._f.ref;
2443
+ if (isHTMLElement(fieldReference)) {
2444
+ const form = fieldReference.closest("form");
2445
+ if (form) {
2446
+ form.reset();
2447
+ break;
2448
+ }
2449
+ }
2450
+ }
2451
+ }
2452
+ if (keepStateOptions.keepFieldsRef) for (const fieldName of _names.mount) setValue(fieldName, get(values, fieldName));
2453
+ else _fields = {};
2454
+ }
2455
+ _formValues = _options.shouldUnregister ? keepStateOptions.keepDefaultValues ? cloneObject(_defaultValues) : {} : cloneObject(values);
2456
+ _subjects.array.next({ values: { ...values } });
2457
+ _subjects.state.next({ values: { ...values } });
2458
+ }
2459
+ _names = {
2460
+ mount: keepStateOptions.keepDirtyValues ? _names.mount : /* @__PURE__ */ new Set(),
2461
+ unMount: /* @__PURE__ */ new Set(),
2462
+ array: /* @__PURE__ */ new Set(),
2463
+ disabled: /* @__PURE__ */ new Set(),
2464
+ watch: /* @__PURE__ */ new Set(),
2465
+ watchAll: false,
2466
+ focus: ""
2467
+ };
2468
+ _state.mount = !_proxyFormState.isValid || !!keepStateOptions.keepIsValid || !!keepStateOptions.keepDirtyValues || !_options.shouldUnregister && !isEmptyObject(values);
2469
+ _state.watch = !!_options.shouldUnregister;
2470
+ _state.keepIsValid = !!keepStateOptions.keepIsValid;
2471
+ _state.action = false;
2472
+ if (!keepStateOptions.keepErrors) _formState.errors = {};
2473
+ _subjects.state.next({
2474
+ submitCount: keepStateOptions.keepSubmitCount ? _formState.submitCount : 0,
2475
+ isDirty: isEmptyResetValues ? false : keepStateOptions.keepDirty ? _formState.isDirty : !!(keepStateOptions.keepDefaultValues && !deepEqual(formValues, _defaultValues)),
2476
+ isSubmitted: keepStateOptions.keepIsSubmitted ? _formState.isSubmitted : false,
2477
+ dirtyFields: isEmptyResetValues ? {} : keepStateOptions.keepDirtyValues ? keepStateOptions.keepDefaultValues && _formValues ? getDirtyFields(_defaultValues, _formValues) : _formState.dirtyFields : keepStateOptions.keepDefaultValues && formValues ? getDirtyFields(_defaultValues, formValues) : keepStateOptions.keepDirty ? _formState.dirtyFields : {},
2478
+ touchedFields: keepStateOptions.keepTouched ? _formState.touchedFields : {},
2479
+ errors: keepStateOptions.keepErrors ? _formState.errors : {},
2480
+ isSubmitSuccessful: keepStateOptions.keepIsSubmitSuccessful ? _formState.isSubmitSuccessful : false,
2481
+ isSubmitting: false,
2482
+ defaultValues: _defaultValues
2483
+ });
2484
+ };
2485
+ const reset = (formValues, keepStateOptions) => _reset(isFunction(formValues) ? formValues(_formValues) : formValues, {
2486
+ ..._options.resetOptions,
2487
+ ...keepStateOptions
2488
+ });
2489
+ const setFocus = (name, options = {}) => {
2490
+ const field = get(_fields, name);
2491
+ const fieldReference = field && field._f;
2492
+ if (fieldReference) {
2493
+ const fieldRef = fieldReference.refs ? fieldReference.refs[0] : fieldReference.ref;
2494
+ if (fieldRef.focus) setTimeout(() => {
2495
+ fieldRef.focus();
2496
+ options.shouldSelect && isFunction(fieldRef.select) && fieldRef.select();
2497
+ });
2498
+ }
2499
+ };
2500
+ const _setFormState = (updatedFormState) => {
2501
+ _formState = {
2502
+ ..._formState,
2503
+ ...updatedFormState
2504
+ };
2505
+ };
2506
+ const _resetDefaultValues = () => isFunction(_options.defaultValues) && _options.defaultValues().then((values) => {
2507
+ reset(values, _options.resetOptions);
2508
+ _subjects.state.next({ isLoading: false });
2509
+ });
2510
+ const methods = {
2511
+ control: {
2512
+ register,
2513
+ unregister,
2514
+ getFieldState,
2515
+ handleSubmit,
2516
+ setError,
2517
+ _subscribe,
2518
+ _runSchema,
2519
+ _updateIsValidating,
2520
+ _focusError,
2521
+ _getWatch,
2522
+ _getDirty,
2523
+ _setValid,
2524
+ _setFieldArray,
2525
+ _setDisabledField,
2526
+ _setErrors,
2527
+ _getFieldArray,
2528
+ _reset,
2529
+ _resetDefaultValues,
2530
+ _removeUnmounted,
2531
+ _disableForm,
2532
+ _subjects,
2533
+ _proxyFormState,
2534
+ get _fields() {
2535
+ return _fields;
2536
+ },
2537
+ get _formValues() {
2538
+ return _formValues;
2539
+ },
2540
+ get _state() {
2541
+ return _state;
2542
+ },
2543
+ set _state(value) {
2544
+ _state = value;
2545
+ },
2546
+ get _defaultValues() {
2547
+ return _defaultValues;
2548
+ },
2549
+ get _names() {
2550
+ return _names;
2551
+ },
2552
+ set _names(value) {
2553
+ _names = value;
2554
+ },
2555
+ get _formState() {
2556
+ return _formState;
2557
+ },
2558
+ get _options() {
2559
+ return _options;
2560
+ },
2561
+ set _options(value) {
2562
+ _options = {
2563
+ ..._options,
2564
+ ...value
2565
+ };
2566
+ }
2567
+ },
2568
+ subscribe,
2569
+ trigger,
2570
+ register,
2571
+ handleSubmit,
2572
+ watch,
2573
+ setValue,
2574
+ getValues,
2575
+ reset,
2576
+ resetField,
2577
+ clearErrors,
2578
+ unregister,
2579
+ setError,
2580
+ setFocus,
2581
+ getFieldState
2582
+ };
2583
+ return {
2584
+ ...methods,
2585
+ formControl: methods
2586
+ };
2587
+ }
2588
+ /**
2589
+ * Custom hook to manage the entire form.
2590
+ *
2591
+ * @remarks
2592
+ * [API](https://react-hook-form.com/docs/useform) • [Demo](https://codesandbox.io/s/react-hook-form-get-started-ts-5ksmm) • [Video](https://www.youtube.com/watch?v=RkXv4AXXC_4)
2593
+ *
2594
+ * @param props - form configuration and validation parameters.
2595
+ *
2596
+ * @returns methods - individual functions to manage the form state. {@link UseFormReturn}
2597
+ *
2598
+ * @example
2599
+ * ```tsx
2600
+ * function App() {
2601
+ * const { register, handleSubmit, watch, formState: { errors } } = useForm();
2602
+ * const onSubmit = data => console.log(data);
2603
+ *
2604
+ * console.log(watch("example"));
2605
+ *
2606
+ * return (
2607
+ * <form onSubmit={handleSubmit(onSubmit)}>
2608
+ * <input defaultValue="test" {...register("example")} />
2609
+ * <input {...register("exampleRequired", { required: true })} />
2610
+ * {errors.exampleRequired && <span>This field is required</span>}
2611
+ * <button>Submit</button>
2612
+ * </form>
2613
+ * );
2614
+ * }
2615
+ * ```
2616
+ */
2617
+ function useForm(props = {}) {
2618
+ const _formControl = React.useRef(void 0);
2619
+ const _values = React.useRef(void 0);
2620
+ const [formState, updateFormState] = React.useState({
2621
+ isDirty: false,
2622
+ isValidating: false,
2623
+ isLoading: isFunction(props.defaultValues),
2624
+ isSubmitted: false,
2625
+ isSubmitting: false,
2626
+ isSubmitSuccessful: false,
2627
+ isValid: false,
2628
+ submitCount: 0,
2629
+ dirtyFields: {},
2630
+ touchedFields: {},
2631
+ validatingFields: {},
2632
+ errors: props.errors || {},
2633
+ disabled: props.disabled || false,
2634
+ isReady: false,
2635
+ defaultValues: isFunction(props.defaultValues) ? void 0 : props.defaultValues
2636
+ });
2637
+ if (!_formControl.current) {
2638
+ if (props.formControl) {
2639
+ _formControl.current = {
2640
+ ...props.formControl,
2641
+ formState
2642
+ };
2643
+ if (props.defaultValues && !isFunction(props.defaultValues)) props.formControl.reset(props.defaultValues, props.resetOptions);
2644
+ } else {
2645
+ const { formControl, ...rest } = createFormControl(props);
2646
+ _formControl.current = {
2647
+ ...rest,
2648
+ formState
2649
+ };
2650
+ }
2651
+ }
2652
+ const control = _formControl.current.control;
2653
+ control._options = props;
2654
+ useIsomorphicLayoutEffect(() => {
2655
+ const sub = control._subscribe({
2656
+ formState: control._proxyFormState,
2657
+ callback: () => updateFormState({ ...control._formState }),
2658
+ reRenderRoot: true
2659
+ });
2660
+ updateFormState((data) => ({
2661
+ ...data,
2662
+ isReady: true
2663
+ }));
2664
+ control._formState.isReady = true;
2665
+ return sub;
2666
+ }, [control]);
2667
+ React.useEffect(() => control._disableForm(props.disabled), [control, props.disabled]);
2668
+ React.useEffect(() => {
2669
+ if (props.mode) control._options.mode = props.mode;
2670
+ if (props.reValidateMode) control._options.reValidateMode = props.reValidateMode;
2671
+ }, [
2672
+ control,
2673
+ props.mode,
2674
+ props.reValidateMode
2675
+ ]);
2676
+ React.useEffect(() => {
2677
+ if (props.errors) {
2678
+ control._setErrors(props.errors);
2679
+ control._focusError();
2680
+ }
2681
+ }, [control, props.errors]);
2682
+ React.useEffect(() => {
2683
+ props.shouldUnregister && control._subjects.state.next({ values: control._getWatch() });
2684
+ }, [control, props.shouldUnregister]);
2685
+ React.useEffect(() => {
2686
+ if (control._proxyFormState.isDirty) {
2687
+ const isDirty = control._getDirty();
2688
+ if (isDirty !== formState.isDirty) control._subjects.state.next({ isDirty });
2689
+ }
2690
+ }, [control, formState.isDirty]);
2691
+ React.useEffect(() => {
2692
+ var _a;
2693
+ if (props.values && !deepEqual(props.values, _values.current)) {
2694
+ control._reset(props.values, {
2695
+ keepFieldsRef: true,
2696
+ ...control._options.resetOptions
2697
+ });
2698
+ if (!((_a = control._options.resetOptions) === null || _a === void 0 ? void 0 : _a.keepIsValid)) control._setValid();
2699
+ _values.current = props.values;
2700
+ updateFormState((state) => ({ ...state }));
2701
+ } else control._resetDefaultValues();
2702
+ }, [control, props.values]);
2703
+ React.useEffect(() => {
2704
+ if (!control._state.mount) {
2705
+ control._setValid();
2706
+ control._state.mount = true;
2707
+ }
2708
+ if (control._state.watch) {
2709
+ control._state.watch = false;
2710
+ control._subjects.state.next({ ...control._formState });
2711
+ }
2712
+ control._removeUnmounted();
2713
+ });
2714
+ _formControl.current.formState = React.useMemo(() => getProxyFormState(formState, control), [control, formState]);
2715
+ return _formControl.current;
2716
+ }
2717
+ //#endregion
2718
+ //#region ../../node_modules/.pnpm/@hookform+resolvers@5.2.2_react-hook-form@7.71.2_react@19.2.6_/node_modules/@hookform/resolvers/dist/resolvers.mjs
2719
+ const r$1 = (t, r, o) => {
2720
+ if (t && "reportValidity" in t) {
2721
+ const s = get(o, r);
2722
+ t.setCustomValidity(s && s.message || ""), t.reportValidity();
2723
+ }
2724
+ };
2725
+ const o = (e, t) => {
2726
+ for (const o in t.fields) {
2727
+ const s = t.fields[o];
2728
+ s && s.ref && "reportValidity" in s.ref ? r$1(s.ref, o, e) : s && s.refs && s.refs.forEach((t) => r$1(t, o, e));
2729
+ }
2730
+ };
2731
+ const s$1 = (r, s) => {
2732
+ s.shouldUseNativeValidation && o(r, s);
2733
+ const n = {};
2734
+ for (const o in r) {
2735
+ const f = get(s.fields, o), c = Object.assign(r[o] || {}, { ref: f && f.ref });
2736
+ if (i$1(s.names || Object.keys(r), o)) {
2737
+ const r = Object.assign({}, get(n, o));
2738
+ set(r, "root", c), set(n, o, r);
2739
+ } else set(n, o, c);
2740
+ }
2741
+ return n;
2742
+ };
2743
+ const i$1 = (e, t) => {
2744
+ const r = n$1(t);
2745
+ return e.some((e) => n$1(e).match(`^${r}\\.\\d+`));
2746
+ };
2747
+ function n$1(e) {
2748
+ return e.replace(/\]|\[/g, "");
2749
+ }
2750
+ //#endregion
2751
+ //#region ../../node_modules/.pnpm/@hookform+resolvers@5.2.2_react-hook-form@7.71.2_react@19.2.6_/node_modules/@hookform/resolvers/zod/dist/zod.mjs
2752
+ function t(r, e) {
2753
+ try {
2754
+ var o = r();
2755
+ } catch (r) {
2756
+ return e(r);
2757
+ }
2758
+ return o && o.then ? o.then(void 0, e) : o;
2759
+ }
2760
+ function s(r, e) {
2761
+ for (var n = {}; r.length;) {
2762
+ var t = r[0], s = t.code, i = t.message, a = t.path.join(".");
2763
+ if (!n[a]) if ("unionErrors" in t) {
2764
+ var u = t.unionErrors[0].errors[0];
2765
+ n[a] = {
2766
+ message: u.message,
2767
+ type: u.code
2768
+ };
2769
+ } else n[a] = {
2770
+ message: i,
2771
+ type: s
2772
+ };
2773
+ if ("unionErrors" in t && t.unionErrors.forEach(function(e) {
2774
+ return e.errors.forEach(function(e) {
2775
+ return r.push(e);
2776
+ });
2777
+ }), e) {
2778
+ var c = n[a].types, f = c && c[t.code];
2779
+ n[a] = appendErrors(a, e, n, s, f ? [].concat(f, t.message) : t.message);
2780
+ }
2781
+ r.shift();
2782
+ }
2783
+ return n;
2784
+ }
2785
+ function i(r, e) {
2786
+ for (var n = {}; r.length;) {
2787
+ var t = r[0], s = t.code, i = t.message, a = t.path.join(".");
2788
+ if (!n[a]) if ("invalid_union" === t.code && t.errors.length > 0) {
2789
+ var u = t.errors[0][0];
2790
+ n[a] = {
2791
+ message: u.message,
2792
+ type: u.code
2793
+ };
2794
+ } else n[a] = {
2795
+ message: i,
2796
+ type: s
2797
+ };
2798
+ if ("invalid_union" === t.code && t.errors.forEach(function(e) {
2799
+ return e.forEach(function(e) {
2800
+ return r.push(e);
2801
+ });
2802
+ }), e) {
2803
+ var c = n[a].types, f = c && c[t.code];
2804
+ n[a] = appendErrors(a, e, n, s, f ? [].concat(f, t.message) : t.message);
2805
+ }
2806
+ r.shift();
2807
+ }
2808
+ return n;
2809
+ }
2810
+ function a(o$1, a, u) {
2811
+ if (void 0 === u && (u = {}), function(r) {
2812
+ return "_def" in r && "object" == typeof r._def && "typeName" in r._def;
2813
+ }(o$1)) return function(n, i, c) {
2814
+ try {
2815
+ return Promise.resolve(t(function() {
2816
+ return Promise.resolve(o$1["sync" === u.mode ? "parse" : "parseAsync"](n, a)).then(function(e) {
2817
+ return c.shouldUseNativeValidation && o({}, c), {
2818
+ errors: {},
2819
+ values: u.raw ? Object.assign({}, n) : e
2820
+ };
2821
+ });
2822
+ }, function(r) {
2823
+ if (function(r) {
2824
+ return Array.isArray(null == r ? void 0 : r.issues);
2825
+ }(r)) return {
2826
+ values: {},
2827
+ errors: s$1(s(r.errors, !c.shouldUseNativeValidation && "all" === c.criteriaMode), c)
2828
+ };
2829
+ throw r;
2830
+ }));
2831
+ } catch (r) {
2832
+ return Promise.reject(r);
2833
+ }
2834
+ };
2835
+ if (function(r) {
2836
+ return "_zod" in r && "object" == typeof r._zod;
2837
+ }(o$1)) return function(s, c, f) {
2838
+ try {
2839
+ return Promise.resolve(t(function() {
2840
+ return Promise.resolve(("sync" === u.mode ? n.parse : n.parseAsync)(o$1, s, a)).then(function(e) {
2841
+ return f.shouldUseNativeValidation && o({}, f), {
2842
+ errors: {},
2843
+ values: u.raw ? Object.assign({}, s) : e
2844
+ };
2845
+ });
2846
+ }, function(r) {
2847
+ if (function(r) {
2848
+ return r instanceof n.$ZodError;
2849
+ }(r)) return {
2850
+ values: {},
2851
+ errors: s$1(i(r.issues, !f.shouldUseNativeValidation && "all" === f.criteriaMode), f)
2852
+ };
2853
+ throw r;
2854
+ }));
2855
+ } catch (r) {
2856
+ return Promise.reject(r);
2857
+ }
2858
+ };
2859
+ throw new Error("Invalid input: not a Zod schema");
2860
+ }
2861
+ //#endregion
2862
+ //#region editors/document-model-editor/schemas/inputs.ts
2863
+ const isUppercase = (value) => !/\p{Ll}/u.test(value);
2864
+ const isLowercase = (value) => !/\p{Lu}/u.test(value);
2865
+ function createNameSchema(options = {}) {
2866
+ const { required = false, allowEmpty = false, unique = [] } = options;
2867
+ const baseSchema = allowEmpty ? z.string() : z.string().min(1);
2868
+ const uniqueRefinement = baseSchema.refine((value) => {
2869
+ if (!value && allowEmpty) return true;
2870
+ return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
2871
+ }, { message: "Item with this name already exists" });
2872
+ if (!required) return unique.length > 0 ? z.string().optional().refine((value) => {
2873
+ if (value === void 0) return true;
2874
+ if (!value && allowEmpty) return true;
2875
+ return !unique.map((n) => n.toLowerCase()).includes(value.replace(/^\s+|\s+$/g, "_").toLowerCase());
2876
+ }, { message: "Item with this name already exists" }) : z.string().optional();
2877
+ return unique.length > 0 ? uniqueRefinement : baseSchema;
2878
+ }
2879
+ function createConstantCaseSchema(options = {}) {
2880
+ return createNameSchema(options).transform((value) => value ? value.toUpperCase() : value).refine((value) => !value || isUppercase(value), { message: "Must be uppercase" });
2881
+ }
2882
+ function createLowercaseSnakeCaseSchema(options = {}) {
2883
+ return createNameSchema(options).transform((value) => value ? value.toLowerCase() : value).refine((value) => !value || isLowercase(value), { message: "Must be lowercase" });
2884
+ }
2885
+ function toLowercaseSnakeCase(value, options = {}) {
2886
+ return createLowercaseSnakeCaseSchema(options).parse(snakeCase(value));
2887
+ }
2888
+ function toConstantCase(value, options = {}) {
2889
+ return createConstantCaseSchema(options).parse(constantCase(value));
2890
+ }
2891
+ z.object({
2892
+ name: createNameSchema({ allowEmpty: true }),
2893
+ website: z.union([z.url(), z.literal("")]).optional().default("")
2894
+ }).default({
2895
+ name: "",
2896
+ website: ""
2897
+ });
2898
+ //#endregion
2899
+ //#region ../../node_modules/.pnpm/@radix-ui+react-compose-refs@1.1.3_@types+react@19.2.14_react@19.2.6/node_modules/@radix-ui/react-compose-refs/dist/index.mjs
2900
+ function setRef(ref, value) {
2901
+ if (typeof ref === "function") return ref(value);
2902
+ else if (ref !== null && ref !== void 0) ref.current = value;
2903
+ }
2904
+ function composeRefs(...refs) {
2905
+ return (node) => {
2906
+ let hasCleanup = false;
2907
+ const cleanups = refs.map((ref) => {
2908
+ const cleanup = setRef(ref, node);
2909
+ if (!hasCleanup && typeof cleanup == "function") hasCleanup = true;
2910
+ return cleanup;
2911
+ });
2912
+ if (hasCleanup) return () => {
2913
+ for (let i = 0; i < cleanups.length; i++) {
2914
+ const cleanup = cleanups[i];
2915
+ if (typeof cleanup == "function") cleanup();
2916
+ else setRef(refs[i], null);
2917
+ }
2918
+ };
2919
+ };
2920
+ }
2921
+ function useComposedRefs(...refs) {
2922
+ return React$1.useCallback(composeRefs(...refs), refs);
2923
+ }
2924
+ //#endregion
2925
+ //#region ../../node_modules/.pnpm/@radix-ui+react-slot@1.3.0_@types+react@19.2.14_react@19.2.6/node_modules/@radix-ui/react-slot/dist/index.mjs
2926
+ // @__NO_SIDE_EFFECTS__
2927
+ function createSlot$1(ownerName) {
2928
+ const Slot2 = React$1.forwardRef((props, forwardedRef) => {
2929
+ let { children, ...slotProps } = props;
2930
+ let slottableElement = null;
2931
+ let hasSlottable = false;
2932
+ const newChildren = [];
2933
+ if (isLazyComponent$1(children) && typeof use$1 === "function") children = use$1(children._payload);
2934
+ React$1.Children.forEach(children, (maybeSlottable) => {
2935
+ if (isSlottable$1(maybeSlottable)) {
2936
+ hasSlottable = true;
2937
+ const slottable = maybeSlottable;
2938
+ let child = "child" in slottable.props ? slottable.props.child : slottable.props.children;
2939
+ if (isLazyComponent$1(child) && typeof use$1 === "function") child = use$1(child._payload);
2940
+ slottableElement = getSlottableElementFromSlottable(slottable, child);
2941
+ newChildren.push(slottableElement?.props?.children);
2942
+ } else newChildren.push(maybeSlottable);
2943
+ });
2944
+ if (slottableElement) slottableElement = React$1.cloneElement(slottableElement, void 0, newChildren);
2945
+ else if (!hasSlottable && React$1.Children.count(children) === 1 && React$1.isValidElement(children)) slottableElement = children;
2946
+ const slottableElementRef = slottableElement ? getElementRef$1(slottableElement) : void 0;
2947
+ const composedRef = useComposedRefs(forwardedRef, slottableElementRef);
2948
+ if (!slottableElement) {
2949
+ if (children || children === 0) throw new Error(hasSlottable ? createSlottableError(ownerName) : createSlotError(ownerName));
2950
+ return children;
2951
+ }
2952
+ const mergedProps = mergeProps$1(slotProps, slottableElement.props ?? {});
2953
+ if (slottableElement.type !== React$1.Fragment) mergedProps.ref = forwardedRef ? composedRef : slottableElementRef;
2954
+ return React$1.cloneElement(slottableElement, mergedProps);
2955
+ });
2956
+ Slot2.displayName = `${ownerName}.Slot`;
2957
+ return Slot2;
2958
+ }
2959
+ var Slot = /* @__PURE__ */ createSlot$1("Slot");
2960
+ var SLOTTABLE_IDENTIFIER$1 = Symbol.for("radix.slottable");
2961
+ var getSlottableElementFromSlottable = (slottable, child) => {
2962
+ if ("child" in slottable.props) {
2963
+ const child2 = slottable.props.child;
2964
+ if (!React$1.isValidElement(child2)) return null;
2965
+ return React$1.cloneElement(child2, void 0, slottable.props.children(child2.props.children));
2966
+ }
2967
+ return React$1.isValidElement(child) ? child : null;
2968
+ };
2969
+ function mergeProps$1(slotProps, childProps) {
2970
+ const overrideProps = { ...childProps };
2971
+ for (const propName in childProps) {
2972
+ const slotPropValue = slotProps[propName];
2973
+ const childPropValue = childProps[propName];
2974
+ if (/^on[A-Z]/.test(propName)) {
2975
+ if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => {
2976
+ const result = childPropValue(...args);
2977
+ slotPropValue(...args);
2978
+ return result;
2979
+ };
2980
+ else if (slotPropValue) overrideProps[propName] = slotPropValue;
2981
+ } else if (propName === "style") overrideProps[propName] = {
2982
+ ...slotPropValue,
2983
+ ...childPropValue
2984
+ };
2985
+ else if (propName === "className") overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
2986
+ }
2987
+ return {
2988
+ ...slotProps,
2989
+ ...overrideProps
2990
+ };
2991
+ }
2992
+ function getElementRef$1(element) {
2993
+ let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
2994
+ let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
2995
+ if (mayWarn) return element.ref;
2996
+ getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
2997
+ mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
2998
+ if (mayWarn) return element.props.ref;
2999
+ return element.props.ref || element.ref;
3000
+ }
3001
+ function isSlottable$1(child) {
3002
+ return React$1.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER$1;
3003
+ }
3004
+ var REACT_LAZY_TYPE$1 = Symbol.for("react.lazy");
3005
+ function isLazyComponent$1(element) {
3006
+ return element != null && typeof element === "object" && "$$typeof" in element && element.$$typeof === REACT_LAZY_TYPE$1 && "_payload" in element && isPromiseLike$1(element._payload);
3007
+ }
3008
+ function isPromiseLike$1(value) {
3009
+ return typeof value === "object" && value !== null && "then" in value;
3010
+ }
3011
+ var createSlotError = (ownerName) => {
3012
+ return `${ownerName} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`;
3013
+ };
3014
+ var createSlottableError = (ownerName) => {
3015
+ return `${ownerName} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`;
3016
+ };
3017
+ var use$1 = React$1[" use ".trim().toString()];
3018
+ //#endregion
3019
+ //#region editors/document-model-editor/context/form-context.ts
3020
+ const FormFieldContext = React.createContext({});
3021
+ const FormItemContext = React.createContext({});
3022
+ //#endregion
3023
+ //#region editors/document-model-editor/hooks/useFormField.ts
3024
+ const useFormField = () => {
3025
+ const fieldContext = React.useContext(FormFieldContext);
3026
+ const itemContext = React.useContext(FormItemContext);
3027
+ const { getFieldState, formState } = useFormContext();
3028
+ const fieldState = getFieldState(fieldContext.name, formState);
3029
+ if (!fieldContext) throw new Error("useFormField should be used within <FormField>");
3030
+ const { id } = itemContext;
3031
+ return {
3032
+ id,
3033
+ name: fieldContext.name,
3034
+ formItemId: `${id}-form-item`,
3035
+ formDescriptionId: `${id}-form-item-description`,
3036
+ formMessageId: `${id}-form-item-message`,
3037
+ ...fieldState
3038
+ };
3039
+ };
3040
+ //#endregion
3041
+ //#region ../../node_modules/.pnpm/@radix-ui+react-slot@1.2.4_@types+react@19.2.14_react@19.2.6/node_modules/@radix-ui/react-slot/dist/index.mjs
3042
+ var REACT_LAZY_TYPE = Symbol.for("react.lazy");
3043
+ var use = React$1[" use ".trim().toString()];
3044
+ function isPromiseLike(value) {
3045
+ return typeof value === "object" && value !== null && "then" in value;
3046
+ }
3047
+ function isLazyComponent(element) {
3048
+ return element != null && typeof element === "object" && "$$typeof" in element && element.$$typeof === REACT_LAZY_TYPE && "_payload" in element && isPromiseLike(element._payload);
3049
+ }
3050
+ // @__NO_SIDE_EFFECTS__
3051
+ function createSlot(ownerName) {
3052
+ const SlotClone = /* @__PURE__ */ createSlotClone(ownerName);
3053
+ const Slot2 = React$1.forwardRef((props, forwardedRef) => {
3054
+ let { children, ...slotProps } = props;
3055
+ if (isLazyComponent(children) && typeof use === "function") children = use(children._payload);
3056
+ const childrenArray = React$1.Children.toArray(children);
3057
+ const slottable = childrenArray.find(isSlottable);
3058
+ if (slottable) {
3059
+ const newElement = slottable.props.children;
3060
+ const newChildren = childrenArray.map((child) => {
3061
+ if (child === slottable) {
3062
+ if (React$1.Children.count(newElement) > 1) return React$1.Children.only(null);
3063
+ return React$1.isValidElement(newElement) ? newElement.props.children : null;
3064
+ } else return child;
3065
+ });
3066
+ return /* @__PURE__ */ jsx(SlotClone, {
3067
+ ...slotProps,
3068
+ ref: forwardedRef,
3069
+ children: React$1.isValidElement(newElement) ? React$1.cloneElement(newElement, void 0, newChildren) : null
3070
+ });
3071
+ }
3072
+ return /* @__PURE__ */ jsx(SlotClone, {
3073
+ ...slotProps,
3074
+ ref: forwardedRef,
3075
+ children
3076
+ });
3077
+ });
3078
+ Slot2.displayName = `${ownerName}.Slot`;
3079
+ return Slot2;
3080
+ }
3081
+ // @__NO_SIDE_EFFECTS__
3082
+ function createSlotClone(ownerName) {
3083
+ const SlotClone = React$1.forwardRef((props, forwardedRef) => {
3084
+ let { children, ...slotProps } = props;
3085
+ if (isLazyComponent(children) && typeof use === "function") children = use(children._payload);
3086
+ if (React$1.isValidElement(children)) {
3087
+ const childrenRef = getElementRef(children);
3088
+ const props2 = mergeProps(slotProps, children.props);
3089
+ if (children.type !== React$1.Fragment) props2.ref = forwardedRef ? composeRefs$1(forwardedRef, childrenRef) : childrenRef;
3090
+ return React$1.cloneElement(children, props2);
3091
+ }
3092
+ return React$1.Children.count(children) > 1 ? React$1.Children.only(null) : null;
3093
+ });
3094
+ SlotClone.displayName = `${ownerName}.SlotClone`;
3095
+ return SlotClone;
3096
+ }
3097
+ var SLOTTABLE_IDENTIFIER = Symbol("radix.slottable");
3098
+ function isSlottable(child) {
3099
+ return React$1.isValidElement(child) && typeof child.type === "function" && "__radixId" in child.type && child.type.__radixId === SLOTTABLE_IDENTIFIER;
3100
+ }
3101
+ function mergeProps(slotProps, childProps) {
3102
+ const overrideProps = { ...childProps };
3103
+ for (const propName in childProps) {
3104
+ const slotPropValue = slotProps[propName];
3105
+ const childPropValue = childProps[propName];
3106
+ if (/^on[A-Z]/.test(propName)) {
3107
+ if (slotPropValue && childPropValue) overrideProps[propName] = (...args) => {
3108
+ const result = childPropValue(...args);
3109
+ slotPropValue(...args);
3110
+ return result;
3111
+ };
3112
+ else if (slotPropValue) overrideProps[propName] = slotPropValue;
3113
+ } else if (propName === "style") overrideProps[propName] = {
3114
+ ...slotPropValue,
3115
+ ...childPropValue
3116
+ };
3117
+ else if (propName === "className") overrideProps[propName] = [slotPropValue, childPropValue].filter(Boolean).join(" ");
3118
+ }
3119
+ return {
3120
+ ...slotProps,
3121
+ ...overrideProps
3122
+ };
3123
+ }
3124
+ function getElementRef(element) {
3125
+ let getter = Object.getOwnPropertyDescriptor(element.props, "ref")?.get;
3126
+ let mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
3127
+ if (mayWarn) return element.ref;
3128
+ getter = Object.getOwnPropertyDescriptor(element, "ref")?.get;
3129
+ mayWarn = getter && "isReactWarning" in getter && getter.isReactWarning;
3130
+ if (mayWarn) return element.props.ref;
3131
+ return element.props.ref || element.ref;
3132
+ }
3133
+ //#endregion
3134
+ //#region ../../node_modules/.pnpm/@radix-ui+react-primitive@2.1.4_@types+react-dom@19.2.3_@types+react@19.2.14__@types+re_c8c8fd2647f03197dbf56370d7498033/node_modules/@radix-ui/react-primitive/dist/index.mjs
3135
+ var Primitive = [
3136
+ "a",
3137
+ "button",
3138
+ "div",
3139
+ "form",
3140
+ "h2",
3141
+ "h3",
3142
+ "img",
3143
+ "input",
3144
+ "label",
3145
+ "li",
3146
+ "nav",
3147
+ "ol",
3148
+ "p",
3149
+ "select",
3150
+ "span",
3151
+ "svg",
3152
+ "ul"
3153
+ ].reduce((primitive, node) => {
3154
+ const Slot = /* @__PURE__ */ createSlot(`Primitive.${node}`);
3155
+ const Node = React$1.forwardRef((props, forwardedRef) => {
3156
+ const { asChild, ...primitiveProps } = props;
3157
+ const Comp = asChild ? Slot : node;
3158
+ if (typeof window !== "undefined") window[Symbol.for("radix-ui")] = true;
3159
+ return /* @__PURE__ */ jsx(Comp, {
3160
+ ...primitiveProps,
3161
+ ref: forwardedRef
3162
+ });
3163
+ });
3164
+ Node.displayName = `Primitive.${node}`;
3165
+ return {
3166
+ ...primitive,
3167
+ [node]: Node
3168
+ };
3169
+ }, {});
3170
+ //#endregion
3171
+ //#region ../../node_modules/.pnpm/@radix-ui+react-label@2.1.8_@types+react-dom@19.2.3_@types+react@19.2.14__@types+react@_8d35ec453e0b59eefe06771bb1432577/node_modules/@radix-ui/react-label/dist/index.mjs
3172
+ var NAME = "Label";
3173
+ var Label$1 = React$1.forwardRef((props, forwardedRef) => {
3174
+ return /* @__PURE__ */ jsx(Primitive.label, {
3175
+ ...props,
3176
+ ref: forwardedRef,
3177
+ onMouseDown: (event) => {
3178
+ if (event.target.closest("button, input, select, textarea")) return;
3179
+ props.onMouseDown?.(event);
3180
+ if (!event.defaultPrevented && event.detail > 1) event.preventDefault();
3181
+ }
3182
+ });
3183
+ });
3184
+ Label$1.displayName = NAME;
3185
+ var Root = Label$1;
3186
+ //#endregion
3187
+ //#region ../../node_modules/.pnpm/clsx@2.0.0/node_modules/clsx/dist/clsx.mjs
3188
+ function r(e) {
3189
+ var t, f, n = "";
3190
+ if ("string" == typeof e || "number" == typeof e) n += e;
3191
+ else if ("object" == typeof e) if (Array.isArray(e)) for (t = 0; t < e.length; t++) e[t] && (f = r(e[t])) && (n && (n += " "), n += f);
3192
+ else for (t in e) e[t] && (n && (n += " "), n += t);
3193
+ return n;
3194
+ }
3195
+ function clsx() {
3196
+ for (var e, t, f = 0, n = ""; f < arguments.length;) (e = arguments[f++]) && (t = r(e)) && (n && (n += " "), n += t);
3197
+ return n;
3198
+ }
3199
+ //#endregion
3200
+ //#region ../../node_modules/.pnpm/class-variance-authority@0.7.0/node_modules/class-variance-authority/dist/index.mjs
3201
+ const falsyToString = (value) => typeof value === "boolean" ? "".concat(value) : value === 0 ? "0" : value;
3202
+ const cx = clsx;
3203
+ const cva = (base, config) => {
3204
+ return (props) => {
3205
+ var ref;
3206
+ if ((config === null || config === void 0 ? void 0 : config.variants) == null) return cx(base, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
3207
+ const { variants, defaultVariants } = config;
3208
+ const getVariantClassNames = Object.keys(variants).map((variant) => {
3209
+ const variantProp = props === null || props === void 0 ? void 0 : props[variant];
3210
+ const defaultVariantProp = defaultVariants === null || defaultVariants === void 0 ? void 0 : defaultVariants[variant];
3211
+ if (variantProp === null) return null;
3212
+ const variantKey = falsyToString(variantProp) || falsyToString(defaultVariantProp);
3213
+ return variants[variant][variantKey];
3214
+ });
3215
+ const propsWithoutUndefined = props && Object.entries(props).reduce((acc, param) => {
3216
+ let [key, value] = param;
3217
+ if (value === void 0) return acc;
3218
+ acc[key] = value;
3219
+ return acc;
3220
+ }, {});
3221
+ const getCompoundVariantClassNames = config === null || config === void 0 ? void 0 : (ref = config.compoundVariants) === null || ref === void 0 ? void 0 : ref.reduce((acc, param1) => {
3222
+ let { class: cvClass, className: cvClassName, ...compoundVariantOptions } = param1;
3223
+ return Object.entries(compoundVariantOptions).every((param) => {
3224
+ let [key, value] = param;
3225
+ return Array.isArray(value) ? value.includes({
3226
+ ...defaultVariants,
3227
+ ...propsWithoutUndefined
3228
+ }[key]) : {
3229
+ ...defaultVariants,
3230
+ ...propsWithoutUndefined
3231
+ }[key] === value;
3232
+ }) ? [
3233
+ ...acc,
3234
+ cvClass,
3235
+ cvClassName
3236
+ ] : acc;
3237
+ }, []);
3238
+ return cx(base, getVariantClassNames, getCompoundVariantClassNames, props === null || props === void 0 ? void 0 : props.class, props === null || props === void 0 ? void 0 : props.className);
3239
+ };
3240
+ };
3241
+ //#endregion
3242
+ //#region editors/document-model-editor/components/label.tsx
3243
+ const labelVariants = cva("text-sm leading-none font-medium peer-disabled:disabled-effect");
3244
+ const Label = React$1.forwardRef(({ className, ...props }, ref) => /* @__PURE__ */ jsx(Root, {
3245
+ ref,
3246
+ className: twMerge(labelVariants(), className),
3247
+ ...props
3248
+ }));
3249
+ Label.displayName = Root.displayName;
3250
+ //#endregion
3251
+ //#region editors/document-model-editor/components/form.tsx
3252
+ const Form = FormProvider;
3253
+ const FormField = ({ ...props }) => {
3254
+ return /* @__PURE__ */ jsx(FormFieldContext.Provider, {
3255
+ value: { name: props.name },
3256
+ children: /* @__PURE__ */ jsx(Controller, { ...props })
3257
+ });
3258
+ };
3259
+ const FormItem = React$1.forwardRef(({ className, ...props }, ref) => {
3260
+ const id = React$1.useId();
3261
+ return /* @__PURE__ */ jsx(FormItemContext.Provider, {
3262
+ value: { id },
3263
+ children: /* @__PURE__ */ jsx("div", {
3264
+ ref,
3265
+ className,
3266
+ ...props
3267
+ })
3268
+ });
3269
+ });
3270
+ FormItem.displayName = "FormItem";
3271
+ const FormLabel = React$1.forwardRef(({ className, ...props }, ref) => {
3272
+ const { error, formItemId } = useFormField();
3273
+ return /* @__PURE__ */ jsx(Label, {
3274
+ ref,
3275
+ className: twMerge(error && "text-destructive", className),
3276
+ htmlFor: formItemId,
3277
+ ...props
3278
+ });
3279
+ });
3280
+ FormLabel.displayName = "FormLabel";
3281
+ const FormControl = React$1.forwardRef(({ ...props }, ref) => {
3282
+ const { error, formItemId, formDescriptionId, formMessageId } = useFormField();
3283
+ return /* @__PURE__ */ jsx(Slot, {
3284
+ ref,
3285
+ id: formItemId,
3286
+ "aria-describedby": !error ? formDescriptionId : `${formDescriptionId} ${formMessageId}`,
3287
+ "aria-invalid": !!error,
3288
+ ...props
3289
+ });
3290
+ });
3291
+ FormControl.displayName = "FormControl";
3292
+ const FormDescription = React$1.forwardRef(({ className, ...props }, ref) => {
3293
+ const { formDescriptionId } = useFormField();
3294
+ return /* @__PURE__ */ jsx("p", {
3295
+ ref,
3296
+ id: formDescriptionId,
3297
+ className: twMerge("text-sm text-foreground", className),
3298
+ ...props
3299
+ });
3300
+ });
3301
+ FormDescription.displayName = "FormDescription";
3302
+ const FormMessage = React$1.forwardRef(({ className, children, ...props }, ref) => {
3303
+ const { error, formMessageId } = useFormField();
3304
+ const body = error ? String(error.message) : children;
3305
+ if (!body) return null;
3306
+ return /* @__PURE__ */ jsx("p", {
3307
+ ref,
3308
+ id: formMessageId,
3309
+ className: twMerge("text-sm font-medium text-destructive", className),
3310
+ ...props,
3311
+ children: body
3312
+ });
3313
+ });
3314
+ FormMessage.displayName = "FormMessage";
3315
+ //#endregion
3316
+ //#region editors/document-model-editor/components/text-area.tsx
3317
+ const Textarea = forwardRef(({ className, ...props }, ref) => {
3318
+ const textareaRef = useRef(null);
3319
+ const adjustHeight = useCallback((textarea) => {
3320
+ textarea.style.height = "auto";
3321
+ const newHeight = Math.max(textarea.scrollHeight, textarea.offsetHeight);
3322
+ textarea.style.height = `${newHeight}px`;
3323
+ }, []);
3324
+ const handleInput = useCallback((e) => {
3325
+ adjustHeight(e.currentTarget);
3326
+ }, [adjustHeight]);
3327
+ React$1.useEffect(() => {
3328
+ if (textareaRef.current) adjustHeight(textareaRef.current);
3329
+ }, [adjustHeight]);
3330
+ useImperativeHandle(ref, () => ({
3331
+ focus: () => textareaRef.current?.focus(),
3332
+ element: textareaRef.current
3333
+ }));
3334
+ return /* @__PURE__ */ jsx("textarea", {
3335
+ ...props,
3336
+ 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),
3337
+ ref: textareaRef,
3338
+ onInput: handleInput
3339
+ });
3340
+ });
3341
+ Textarea.displayName = "Textarea";
3342
+ //#endregion
3343
+ //#region editors/document-model-editor/components/text-field.tsx
3344
+ const TextField = forwardRef(({ name, value, onSubmit, label, placeholder, unique, className = "", rows = 1, focusOnMount = false, required = false, allowEmpty = false, shouldReset = false, onChange }, ref) => {
3345
+ const textareaRef = useRef(null);
3346
+ const id = useId();
3347
+ useEffect(() => {
3348
+ if (focusOnMount && textareaRef.current) textareaRef.current.focus();
3349
+ }, [focusOnMount]);
3350
+ const form = useForm({
3351
+ resolver: a(z.object({ [name]: createNameSchema({
3352
+ required,
3353
+ allowEmpty,
3354
+ unique
3355
+ }) })),
3356
+ defaultValues: { [name]: value ?? "" }
3357
+ });
3358
+ const handleSubmit = useCallback((values) => {
3359
+ const newValue = values[name];
3360
+ if (newValue === void 0 || value === newValue) return;
3361
+ onSubmit(newValue);
3362
+ if (shouldReset) form.reset({ [name]: "" });
3363
+ }, [
3364
+ name,
3365
+ value,
3366
+ onSubmit,
3367
+ form,
3368
+ shouldReset
3369
+ ]);
3370
+ const handleBlur = useCallback(async () => {
3371
+ const currentValue = form.getValues()[name] ?? "";
3372
+ if (value === null || value === void 0) {
3373
+ if (!currentValue || currentValue.trim() === "") return;
3374
+ }
3375
+ if (compareStringsWithoutWhitespace(currentValue, value ?? "")) return;
3376
+ try {
3377
+ await form.trigger();
3378
+ if (form.formState.isValid) await form.handleSubmit(handleSubmit)();
3379
+ } catch (_e) {}
3380
+ }, [
3381
+ form,
3382
+ handleSubmit,
3383
+ name,
3384
+ value
3385
+ ]);
3386
+ const onEnterKeyDown = useCallback((e) => {
3387
+ if (e.key === "Enter") {
3388
+ e.preventDefault();
3389
+ e.target.blur();
3390
+ }
3391
+ }, []);
3392
+ const handleChange = useCallback((e) => {
3393
+ const newValue = e.target.value;
3394
+ onChange?.(newValue);
3395
+ }, [onChange]);
3396
+ useImperativeHandle(ref, () => ({ focus: () => textareaRef.current?.focus() }));
3397
+ useEffect(() => {
3398
+ form.reset({ [name]: value ?? "" });
3399
+ }, [
3400
+ form,
3401
+ name,
3402
+ value
3403
+ ]);
3404
+ return /* @__PURE__ */ jsx(Form, {
3405
+ ...form,
3406
+ children: /* @__PURE__ */ jsx(FormField, {
3407
+ control: form.control,
3408
+ name,
3409
+ render: ({ field }) => /* @__PURE__ */ jsxs(FormItem, {
3410
+ className: "grid h-full grid-rows-[auto,1fr] gap-2 overflow-visible",
3411
+ children: [
3412
+ !!label && /* @__PURE__ */ jsx(FormLabel, {
3413
+ htmlFor: name,
3414
+ className: "text-sm font-medium text-foreground",
3415
+ children: label
3416
+ }),
3417
+ /* @__PURE__ */ jsx(FormControl, { children: /* @__PURE__ */ jsx(Textarea, {
3418
+ ...field,
3419
+ id,
3420
+ name,
3421
+ ref: (node) => {
3422
+ if (node) {
3423
+ field.ref(node.element);
3424
+ textareaRef.current = node;
3425
+ }
3426
+ },
3427
+ placeholder,
3428
+ onBlur: () => void handleBlur(),
3429
+ onChange: (e) => {
3430
+ field.onChange(e);
3431
+ handleChange(e);
3432
+ },
3433
+ onKeyDown: onEnterKeyDown,
3434
+ rows,
3435
+ className
3436
+ }) }),
3437
+ /* @__PURE__ */ jsx(FormMessage, {})
3438
+ ]
3439
+ })
3440
+ })
3441
+ });
3442
+ });
3443
+ TextField.displayName = "TextField";
3444
+ z.object({
3445
+ name: z.string(),
3446
+ documentType: z.string(),
3447
+ extension: z.string().optional().default(""),
3448
+ description: z.string(),
3449
+ authorName: z.string(),
3450
+ authorWebsite: z.string()
3451
+ });
3452
+ function ModelMetadata(props) {
3453
+ return /* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx(ModelNameForm, { ...props }), /* @__PURE__ */ jsx("div", {
3454
+ className: "flex h-full flex-col gap-4",
3455
+ children: /* @__PURE__ */ jsxs("div", {
3456
+ className: "grid flex-1 grid-cols-3 items-start gap-4",
3457
+ children: [/* @__PURE__ */ jsxs("div", {
3458
+ className: "col-span-2 flex h-full flex-col gap-4",
3459
+ children: [/* @__PURE__ */ jsx("div", {
3460
+ className: "shrink-0",
3461
+ children: /* @__PURE__ */ jsx(DocumentTypeForm, { ...props })
3462
+ }), /* @__PURE__ */ jsx("div", {
3463
+ className: "min-h-0 flex-1",
3464
+ children: /* @__PURE__ */ jsx(DescriptionForm, { ...props })
3465
+ })]
3466
+ }), /* @__PURE__ */ jsxs("div", {
3467
+ className: "col-span-1 flex flex-col gap-4",
3468
+ children: [
3469
+ /* @__PURE__ */ jsx(AuthorNameForm, { ...props }),
3470
+ /* @__PURE__ */ jsx(AuthorWebsiteForm, { ...props }),
3471
+ /* @__PURE__ */ jsx(ModelExtensionForm, { ...props })
3472
+ ]
3473
+ })]
3474
+ })
3475
+ })] });
3476
+ }
3477
+ function ModelNameForm(props) {
3478
+ const { name, globalStateSchema, localStateSchema, setModelName, setStateSchema } = props;
3479
+ const onSubmit = useCallback((newName) => {
3480
+ if (name === newName) return;
3481
+ setModelName(newName);
3482
+ if (!!!globalStateSchema) {
3483
+ const initialSchemaDoc = makeInitialSchemaDoc(newName, "global");
3484
+ setStateSchema(initialSchemaDoc, "global");
3485
+ return;
3486
+ }
3487
+ const newSchema = renameSchemaType(globalStateSchema, name, newName, "global");
3488
+ setStateSchema(newSchema, "global");
3489
+ if (localStateSchema) {
3490
+ const newLocalStateSchema = renameSchemaType(localStateSchema, name, newName, "local");
3491
+ setStateSchema(newLocalStateSchema, "local");
3492
+ }
3493
+ handleModelNameChange({
3494
+ oldName: name,
3495
+ newName,
3496
+ globalStateSchema,
3497
+ localStateSchema,
3498
+ setStateSchema
3499
+ });
3500
+ }, [
3501
+ name,
3502
+ globalStateSchema,
3503
+ localStateSchema,
3504
+ setStateSchema,
3505
+ setModelName
3506
+ ]);
3507
+ return /* @__PURE__ */ jsx(TextField, {
3508
+ name: "name",
3509
+ value: name,
3510
+ onSubmit,
3511
+ placeholder: "Model name",
3512
+ className: "border-none pl-0 text-xl font-bold text-foreground",
3513
+ required: true,
3514
+ focusOnMount: true
3515
+ });
3516
+ }
3517
+ function DocumentTypeForm(props) {
3518
+ const { documentType, setModelId } = props;
3519
+ return /* @__PURE__ */ jsx(TextField, {
3520
+ label: "Document Type *",
3521
+ name: "powerhouse/document-model",
3522
+ value: documentType,
3523
+ onSubmit: setModelId,
3524
+ placeholder: "Document Type",
3525
+ required: true
3526
+ });
3527
+ }
3528
+ function ModelExtensionForm(props) {
3529
+ const { extension, setModelExtension } = props;
3530
+ return /* @__PURE__ */ jsx(TextField, {
3531
+ name: "extension",
3532
+ value: extension,
3533
+ onSubmit: setModelExtension,
3534
+ label: "Model Extension",
3535
+ placeholder: "Example .phdm",
3536
+ allowEmpty: true
3537
+ });
3538
+ }
3539
+ function DescriptionForm(props) {
3540
+ const { description, setModelDescription } = props;
3541
+ return /* @__PURE__ */ jsx(TextField, {
3542
+ name: "description",
3543
+ label: "Model Description",
3544
+ value: description,
3545
+ onSubmit: setModelDescription,
3546
+ placeholder: "Describe your document to others",
3547
+ allowEmpty: true,
3548
+ className: "h-full"
3549
+ });
3550
+ }
3551
+ function AuthorNameForm(props) {
3552
+ const { authorName, setAuthorName } = props;
3553
+ return /* @__PURE__ */ jsx(TextField, {
3554
+ name: "authorName",
3555
+ value: authorName,
3556
+ onSubmit: setAuthorName,
3557
+ label: "Author Name",
3558
+ placeholder: "Username or organisation",
3559
+ allowEmpty: true
3560
+ });
3561
+ }
3562
+ function AuthorWebsiteForm(props) {
3563
+ const { authorWebsite, setAuthorWebsite } = props;
3564
+ return /* @__PURE__ */ jsx(TextField, {
3565
+ name: "authorWebsite",
3566
+ value: authorWebsite,
3567
+ label: "Website URL",
3568
+ onSubmit: (newAuthorWebsite) => {
3569
+ if (!!authorWebsite && !newAuthorWebsite) return;
3570
+ setAuthorWebsite(newAuthorWebsite);
3571
+ },
3572
+ placeholder: "https://www.powerhouse.inc/",
3573
+ allowEmpty: true
3574
+ });
3575
+ }
3576
+ //#endregion
3577
+ //#region editors/document-model-editor/components/module-form.tsx
3578
+ function ModuleForm({ module, onAddModule, updateModuleName, modules = [] }) {
3579
+ const isEdit = !!module;
3580
+ const moduleNames = modules.map((m) => m.name);
3581
+ const handleSubmit = async (name) => {
3582
+ const formattedName = toLowercaseSnakeCase(name);
3583
+ if (!formattedName.length) return;
3584
+ if (isEdit) {
3585
+ if (formattedName !== module.name) updateModuleName(module.id, formattedName);
3586
+ } else await onAddModule(formattedName);
3587
+ };
3588
+ return /* @__PURE__ */ jsx(TextField, {
3589
+ name: "name",
3590
+ label: isEdit ? "Module name *" : "Add module *",
3591
+ value: module?.name,
3592
+ onSubmit: (name) => void handleSubmit(name),
3593
+ placeholder: "Add module",
3594
+ unique: moduleNames,
3595
+ shouldReset: !isEdit,
3596
+ required: true
3597
+ }, module?.id ?? "new");
3598
+ }
3599
+ //#endregion
3600
+ //#region editors/document-model-editor/components/operation-form.tsx
3601
+ function OperationForm({ operation, module, focusOnMount, allOperationNames, onAddOperationAndInitialSchema, updateOperationName, deleteOperation }) {
3602
+ const isEdit = !!operation;
3603
+ const handleSubmit = async (name) => {
3604
+ if (isEdit && name === "") {
3605
+ deleteOperation(operation.id);
3606
+ return;
3607
+ }
3608
+ const formattedName = toConstantCase(name);
3609
+ if (isEdit) {
3610
+ if (formattedName !== operation.name) updateOperationName(operation.id, formattedName);
3611
+ } else await onAddOperationAndInitialSchema(module.id, formattedName);
3612
+ };
3613
+ const handleChange = (value) => {
3614
+ if (isEdit && value === "") deleteOperation(operation.id);
3615
+ };
3616
+ return /* @__PURE__ */ jsx(TextField, {
3617
+ name: "name",
3618
+ value: operation?.name,
3619
+ label: isEdit ? "Operation name *" : "Add operation *",
3620
+ onSubmit: (name) => void handleSubmit(name),
3621
+ onChange: handleChange,
3622
+ placeholder: "Add operation",
3623
+ required: !isEdit,
3624
+ allowEmpty: !isEdit,
3625
+ shouldReset: !isEdit,
3626
+ focusOnMount,
3627
+ unique: allOperationNames
3628
+ });
3629
+ }
3630
+ //#endregion
3631
+ //#region editors/document-model-editor/components/operation-description-form.tsx
3632
+ function OperationDescriptionForm({ operation, focusOnMount, setOperationDescription }) {
3633
+ const textFieldRef = useRef(null);
3634
+ useEffect(() => {
3635
+ if (focusOnMount && textFieldRef.current) textFieldRef.current.focus();
3636
+ }, [focusOnMount]);
3637
+ return /* @__PURE__ */ jsx(TextField, {
3638
+ ref: textFieldRef,
3639
+ name: "description",
3640
+ value: operation.description,
3641
+ onSubmit: (newDescription) => setOperationDescription(operation.id, newDescription),
3642
+ label: "Operation description",
3643
+ allowEmpty: true,
3644
+ placeholder: "Operation Description"
3645
+ });
3646
+ }
3647
+ //#endregion
3648
+ //#region editors/document-model-editor/components/operation-error-form.tsx
3649
+ function OperationErrorForm({ operation, error, focusOnMount, onSubmit, onAddOperationError, deleteOperationError, setOperationErrorName }) {
3650
+ const textFieldRef = useRef(null);
3651
+ const isEdit = !!error;
3652
+ const allOperationErrorNames = operation.errors.map((o) => o.name).filter((n) => n !== null);
3653
+ const handleSubmit = (name) => {
3654
+ if (isEdit && name === "") {
3655
+ deleteOperationError(error.id);
3656
+ return;
3657
+ }
3658
+ const formattedName = pascalCase(name);
3659
+ if (isEdit) setOperationErrorName(operation.id, error.id, formattedName);
3660
+ else onAddOperationError(operation.id, formattedName);
3661
+ onSubmit?.();
3662
+ };
3663
+ const handleChange = (value) => {
3664
+ if (isEdit && value === "") deleteOperationError(error.id);
3665
+ };
3666
+ return /* @__PURE__ */ jsx(TextField, {
3667
+ ref: textFieldRef,
3668
+ name: "name",
3669
+ value: error?.name,
3670
+ onSubmit: handleSubmit,
3671
+ onChange: handleChange,
3672
+ placeholder: "Add exception",
3673
+ required: !isEdit,
3674
+ allowEmpty: !isEdit,
3675
+ shouldReset: !isEdit,
3676
+ unique: allOperationErrorNames,
3677
+ focusOnMount
3678
+ });
3679
+ }
3680
+ //#endregion
3681
+ //#region editors/document-model-editor/components/operation-errors.tsx
3682
+ function OperationErrors({ operation, addOperationError, deleteOperationError, setOperationErrorName }) {
3683
+ const addErrorFormId = useId();
3684
+ const [shouldFocusAddForm, setShouldFocusAddForm] = useState(false);
3685
+ const onAddOperationError = useCallback(async (operationId, error) => {
3686
+ const errorId = await addOperationError(operationId, error);
3687
+ if (errorId) setShouldFocusAddForm(true);
3688
+ return errorId;
3689
+ }, [addOperationError, setShouldFocusAddForm]);
3690
+ const onAddOperationErrorSubmit = useCallback(() => setShouldFocusAddForm(false), [setShouldFocusAddForm]);
3691
+ return /* @__PURE__ */ jsxs("ul", {
3692
+ className: "ml-4 list-disc",
3693
+ children: [operation.errors.map((error) => /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
3694
+ error,
3695
+ operation,
3696
+ onAddOperationError,
3697
+ deleteOperationError,
3698
+ setOperationErrorName
3699
+ }) }, error.id)), /* @__PURE__ */ jsx("li", { children: /* @__PURE__ */ jsx(OperationErrorForm, {
3700
+ operation,
3701
+ onAddOperationError,
3702
+ deleteOperationError,
3703
+ setOperationErrorName,
3704
+ focusOnMount: shouldFocusAddForm,
3705
+ onSubmit: onAddOperationErrorSubmit
3706
+ }, `${addErrorFormId}-${shouldFocusAddForm}`) })]
3707
+ });
3708
+ }
3709
+ //#endregion
3710
+ //#region editors/document-model-editor/components/operation.tsx
3711
+ const GraphqlEditor = lazy(() => import("./graphql-editor--ZZPvvGh.mjs"));
3712
+ function Operation(props) {
3713
+ const { operation, module, allOperationNames, lastCreatedOperationId, onAddOperationAndInitialSchema, updateOperationName, deleteOperation, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
3714
+ const noInputRequired = isEmptyOperationSchema(operation.schema);
3715
+ const handleToggleNoInput = useCallback((checked) => toggleNoInputRequired(operation.id, checked), [operation.id, toggleNoInputRequired]);
3716
+ const handleUpdateDocument = useCallback((newDoc) => updateOperationSchema(operation.id, newDoc), [operation.id, updateOperationSchema]);
3717
+ const customLinter = useCallback((doc) => operation.name ? ensureValidOperationSchemaInputName(doc, operation.name) : [], [operation.name]);
3718
+ return /* @__PURE__ */ jsxs("div", {
3719
+ className: "mt-4 grid grid-cols-2 gap-x-12",
3720
+ style: {
3721
+ gridTemplateAreas: `
3722
+ "left editor"
3723
+ "errors editor"
3724
+ `,
3725
+ gridTemplateRows: "auto 1fr"
3726
+ },
3727
+ children: [
3728
+ /* @__PURE__ */ jsxs("div", {
3729
+ className: "flex flex-col gap-2",
3730
+ style: { gridArea: "left" },
3731
+ children: [/* @__PURE__ */ jsx(OperationForm, {
3732
+ operation,
3733
+ onAddOperationAndInitialSchema,
3734
+ updateOperationName,
3735
+ deleteOperation,
3736
+ module,
3737
+ allOperationNames
3738
+ }), /* @__PURE__ */ jsx(OperationDescriptionForm, {
3739
+ operation,
3740
+ focusOnMount: operation.id === lastCreatedOperationId,
3741
+ setOperationDescription
3742
+ })]
3743
+ }),
3744
+ /* @__PURE__ */ jsxs("div", {
3745
+ className: "relative top-8",
3746
+ style: { gridArea: "editor" },
3747
+ children: [/* @__PURE__ */ jsxs("label", {
3748
+ className: "mb-2 flex cursor-pointer items-center gap-2",
3749
+ children: [/* @__PURE__ */ jsx("input", {
3750
+ type: "checkbox",
3751
+ checked: noInputRequired,
3752
+ onChange: (e) => handleToggleNoInput(e.target.checked),
3753
+ className: "size-4 rounded-sm border-border"
3754
+ }), /* @__PURE__ */ jsx("span", {
3755
+ className: "text-sm text-foreground",
3756
+ children: "Operation with no inputs"
3757
+ })]
3758
+ }), !noInputRequired && /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(GraphqlEditor, {
3759
+ doc: operation.schema ?? "",
3760
+ updateDocumentInModel: handleUpdateDocument,
3761
+ customLinter
3762
+ }) })]
3763
+ }),
3764
+ /* @__PURE__ */ jsxs("div", {
3765
+ style: { gridArea: "errors" },
3766
+ children: [/* @__PURE__ */ jsx("h3", {
3767
+ className: "my-2 text-sm font-medium text-foreground",
3768
+ children: "Reducer Exceptions"
3769
+ }), /* @__PURE__ */ jsx(OperationErrors, {
3770
+ operation,
3771
+ addOperationError,
3772
+ deleteOperationError,
3773
+ setOperationErrorName
3774
+ })]
3775
+ })
3776
+ ]
3777
+ });
3778
+ }
3779
+ //#endregion
3780
+ //#region editors/document-model-editor/components/operations.tsx
3781
+ function Operations({ module, allOperations, shouldFocusNewOperation, updateOperationName, deleteOperation, addOperationAndInitialSchema, addOperationError, deleteOperationError, setOperationErrorName, updateOperationSchema, setOperationDescription, toggleNoInputRequired }) {
3782
+ const [lastCreatedOperationId, setLastCreatedOperationId] = useState(null);
3783
+ const addOperationFormId = useId();
3784
+ const allOperationNames = allOperations.map((o) => o.name).filter((n) => n !== null);
3785
+ const onAddOperationAndInitialSchema = useCallback(async (moduleId, name) => {
3786
+ const operationId = await addOperationAndInitialSchema(moduleId, name);
3787
+ if (operationId) setLastCreatedOperationId(operationId);
3788
+ return operationId;
3789
+ }, [addOperationAndInitialSchema, setLastCreatedOperationId]);
3790
+ return /* @__PURE__ */ jsxs("div", { children: [module.operations.map((operation) => /* @__PURE__ */ jsx("div", { children: /* @__PURE__ */ jsx(Operation, {
3791
+ operation,
3792
+ module,
3793
+ lastCreatedOperationId,
3794
+ allOperationNames,
3795
+ addOperationError,
3796
+ deleteOperationError,
3797
+ setOperationErrorName,
3798
+ onAddOperationAndInitialSchema,
3799
+ updateOperationName,
3800
+ deleteOperation,
3801
+ updateOperationSchema,
3802
+ setOperationDescription,
3803
+ toggleNoInputRequired
3804
+ }) }, operation.id)), /* @__PURE__ */ jsx("div", {
3805
+ className: "mt-6 w-1/2 pr-6",
3806
+ children: /* @__PURE__ */ jsx(OperationForm, {
3807
+ onAddOperationAndInitialSchema,
3808
+ updateOperationName,
3809
+ deleteOperation,
3810
+ module,
3811
+ allOperationNames,
3812
+ focusOnMount: shouldFocusNewOperation
3813
+ }, addOperationFormId)
3814
+ })] });
3815
+ }
3816
+ //#endregion
3817
+ //#region editors/document-model-editor/components/module.tsx
3818
+ function Module(props) {
3819
+ const { module, modules, allOperations, lastCreatedModuleId, onAddModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired } = props;
3820
+ return /* @__PURE__ */ jsxs("div", {
3821
+ className: "relative rounded-3xl bg-muted p-6",
3822
+ children: [/* @__PURE__ */ jsxs("div", {
3823
+ className: "mb-2 w-1/2 pr-6",
3824
+ children: [/* @__PURE__ */ jsx(ModuleForm, {
3825
+ modules,
3826
+ module,
3827
+ onAddModule,
3828
+ updateModuleName
3829
+ }), !!module && /* @__PURE__ */ jsx("button", {
3830
+ "aria-label": "Delete module",
3831
+ tabIndex: -1,
3832
+ className: "absolute top-1 right-1 p-2 text-foreground transition-colors hover:hover-effect",
3833
+ onClick: () => {
3834
+ deleteModule(module.id);
3835
+ },
3836
+ children: /* @__PURE__ */ jsx("svg", {
3837
+ className: "size-6",
3838
+ viewBox: "0 0 24 24",
3839
+ fill: "currentcolor",
3840
+ children: /* @__PURE__ */ jsx("path", {
3841
+ fillRule: "evenodd",
3842
+ clipRule: "evenodd",
3843
+ 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"
3844
+ })
3845
+ })
3846
+ })]
3847
+ }), !!module && /* @__PURE__ */ jsx(Operations, {
3848
+ module,
3849
+ allOperations,
3850
+ shouldFocusNewOperation: module.id === lastCreatedModuleId,
3851
+ updateOperationName,
3852
+ deleteOperation,
3853
+ addOperationAndInitialSchema,
3854
+ updateOperationSchema,
3855
+ setOperationDescription,
3856
+ addOperationError,
3857
+ deleteOperationError,
3858
+ setOperationErrorName,
3859
+ toggleNoInputRequired
3860
+ })]
3861
+ });
3862
+ }
3863
+ //#endregion
3864
+ //#region editors/document-model-editor/components/modules.tsx
3865
+ function Modules({ modules, allOperations, addModule, updateModuleName, deleteModule, updateOperationName, deleteOperation, addOperationAndInitialSchema, updateOperationSchema, setOperationDescription, addOperationError, deleteOperationError, setOperationErrorName, toggleNoInputRequired }) {
3866
+ const [lastCreatedModuleId, setLastCreatedModuleId] = useState(null);
3867
+ const focusTrapRef = useRef(null);
3868
+ const onAddModule = useCallback(async (name) => {
3869
+ const moduleId = await addModule(name);
3870
+ if (moduleId) {
3871
+ setLastCreatedModuleId(moduleId);
3872
+ focusTrapRef.current?.focus();
3873
+ }
3874
+ return moduleId;
3875
+ }, [addModule, setLastCreatedModuleId]);
3876
+ return /* @__PURE__ */ jsxs("div", {
3877
+ className: "flex flex-col gap-2",
3878
+ children: [
3879
+ modules.map((module) => /* @__PURE__ */ jsx(Module, {
3880
+ module,
3881
+ modules,
3882
+ allOperations,
3883
+ lastCreatedModuleId,
3884
+ onAddModule,
3885
+ updateModuleName,
3886
+ deleteModule,
3887
+ updateOperationName,
3888
+ deleteOperation,
3889
+ addOperationAndInitialSchema,
3890
+ updateOperationSchema,
3891
+ setOperationDescription,
3892
+ addOperationError,
3893
+ deleteOperationError,
3894
+ setOperationErrorName,
3895
+ toggleNoInputRequired
3896
+ }, module.id)),
3897
+ /* @__PURE__ */ jsx(Module, {
3898
+ modules,
3899
+ allOperations,
3900
+ lastCreatedModuleId,
3901
+ onAddModule,
3902
+ updateModuleName,
3903
+ deleteModule,
3904
+ updateOperationName,
3905
+ deleteOperation,
3906
+ addOperationAndInitialSchema,
3907
+ updateOperationSchema,
3908
+ setOperationDescription,
3909
+ addOperationError,
3910
+ deleteOperationError,
3911
+ setOperationErrorName,
3912
+ toggleNoInputRequired
3913
+ }, "add-module"),
3914
+ /* @__PURE__ */ jsx("div", {
3915
+ ref: focusTrapRef,
3916
+ tabIndex: 0,
3917
+ className: "size-0 overflow-hidden",
3918
+ "aria-hidden": "true"
3919
+ })
3920
+ ]
3921
+ });
3922
+ }
3923
+ //#endregion
3924
+ //#region editors/document-model-editor/components/version-controls.tsx
3925
+ const compactButtonStyle$1 = "min-h-0 min-w-0 flex-none rounded-lg px-6 py-1.5 text-sm whitespace-nowrap";
3926
+ function VersionControls(props) {
3927
+ const { specifications, viewedVersion, onViewVersion, onReleaseNewVersion } = props;
3928
+ const [showReleaseModal, setShowReleaseModal] = useState(false);
3929
+ const latestVersion = specifications[specifications.length - 1].version;
3930
+ const nextVersion = latestVersion + 1;
3931
+ return /* @__PURE__ */ jsxs("div", {
3932
+ className: "mb-4 flex items-center justify-between gap-4",
3933
+ children: [
3934
+ /* @__PURE__ */ jsxs("div", {
3935
+ className: "flex items-center gap-2",
3936
+ children: [/* @__PURE__ */ jsxs("span", {
3937
+ className: "rounded-md bg-muted px-2 py-0.5 font-mono text-xs text-foreground",
3938
+ "data-testid": "model-version-badge",
3939
+ children: ["Version ", viewedVersion]
3940
+ }), specifications.length >= 2 && /* @__PURE__ */ jsx("div", {
3941
+ "aria-label": "Document model version",
3942
+ "data-testid": "model-version-switcher",
3943
+ children: /* @__PURE__ */ jsx(ConnectSelect, {
3944
+ absolutePositionMenu: true,
3945
+ containerClassName: "z-10 [&_svg]:size-4",
3946
+ id: "model-version-switcher",
3947
+ itemClassName: "gap-1 px-2 py-1 font-mono text-xs leading-none [&_p:empty]:hidden",
3948
+ items: specifications.map((spec) => ({
3949
+ value: String(spec.version),
3950
+ displayValue: /* @__PURE__ */ jsx("span", {
3951
+ className: "normal-case",
3952
+ children: spec.version === latestVersion ? `v${spec.version} (latest)` : `v${spec.version} (frozen)`
3953
+ })
3954
+ })),
3955
+ listClassName: "border border-t-0 border-border shadow-md",
3956
+ menuClassName: "min-w-0 pr-1.5",
3957
+ onChange: (value) => {
3958
+ const version = Number(value);
3959
+ onViewVersion(version === latestVersion ? "latest" : version);
3960
+ },
3961
+ value: String(viewedVersion)
3962
+ })
3963
+ })]
3964
+ }),
3965
+ /* @__PURE__ */ jsx(Button, {
3966
+ className: "inline-flex h-8 items-center justify-center py-0",
3967
+ "data-testid": "release-new-version-button",
3968
+ onClick: () => setShowReleaseModal(true),
3969
+ type: "button",
3970
+ children: "Release new version"
3971
+ }),
3972
+ /* @__PURE__ */ jsx(Modal, {
3973
+ open: showReleaseModal,
3974
+ onOpenChange: (status) => {
3975
+ if (!status) setShowReleaseModal(false);
3976
+ },
3977
+ children: /* @__PURE__ */ jsxs("div", {
3978
+ className: "w-[440px] p-6",
3979
+ children: [
3980
+ /* @__PURE__ */ jsxs("div", {
3981
+ className: "pb-2 text-2xl font-bold text-foreground",
3982
+ children: ["Release version ", nextVersion]
3983
+ }),
3984
+ /* @__PURE__ */ jsxs("div", {
3985
+ className: "my-4 rounded-md bg-background p-4 text-left text-sm text-foreground",
3986
+ children: [/* @__PURE__ */ jsxs("p", { children: [
3987
+ "Version ",
3988
+ latestVersion,
3989
+ " will be frozen as-is. Version",
3990
+ " ",
3991
+ nextVersion,
3992
+ " starts as an identical copy, and all further edits apply to version ",
3993
+ nextVersion,
3994
+ "."
3995
+ ] }), /* @__PURE__ */ jsxs("p", {
3996
+ className: "mt-3",
3997
+ children: [
3998
+ "Existing version ",
3999
+ latestVersion,
4000
+ " documents will be upgradeable once you define the migration."
4001
+ ]
4002
+ })]
4003
+ }),
4004
+ /* @__PURE__ */ jsxs("div", {
4005
+ className: "mt-4 flex justify-between gap-3",
4006
+ children: [/* @__PURE__ */ jsx(ModalButton, {
4007
+ className: compactButtonStyle$1,
4008
+ onClick: () => setShowReleaseModal(false),
4009
+ variant: "cancel",
4010
+ children: "Cancel"
4011
+ }), /* @__PURE__ */ jsxs(ModalButton, {
4012
+ className: compactButtonStyle$1,
4013
+ "data-testid": "confirm-release-button",
4014
+ onClick: () => {
4015
+ setShowReleaseModal(false);
4016
+ onReleaseNewVersion();
4017
+ },
4018
+ variant: "confirm",
4019
+ children: ["Release version ", nextVersion]
4020
+ })]
4021
+ })
4022
+ ]
4023
+ })
4024
+ })
4025
+ ]
4026
+ });
4027
+ }
4028
+ function FrozenVersionBanner(props) {
4029
+ const { viewedVersion, latestVersion } = props;
4030
+ return /* @__PURE__ */ jsxs("div", {
4031
+ className: "mb-4 rounded-md border border-border bg-muted p-3 text-sm text-foreground",
4032
+ "data-testid": "frozen-version-banner",
4033
+ children: [
4034
+ "Version ",
4035
+ viewedVersion,
4036
+ " is frozen. You're viewing it read-only. Edits go to version ",
4037
+ latestVersion,
4038
+ "."
4039
+ ]
4040
+ });
4041
+ }
4042
+ //#endregion
4043
+ //#region editors/document-model-editor/components/version-advisory-modal.tsx
4044
+ const compactButtonStyle = "min-h-0 min-w-0 flex-none rounded-lg px-4 py-1.5 text-sm whitespace-nowrap";
4045
+ function FieldDiffList(props) {
4046
+ const { label, fields } = props;
4047
+ if (fields.length === 0) return null;
4048
+ return /* @__PURE__ */ jsxs("div", {
4049
+ className: "mt-3",
4050
+ children: [/* @__PURE__ */ jsx("p", {
4051
+ className: "mb-1.5",
4052
+ children: label
4053
+ }), /* @__PURE__ */ jsx("div", {
4054
+ className: "flex flex-col items-start gap-1",
4055
+ children: fields.map((field) => /* @__PURE__ */ jsx("span", {
4056
+ className: "rounded-md bg-muted px-2 py-0.5 font-mono text-xs text-foreground",
4057
+ children: field
4058
+ }, field))
4059
+ })]
4060
+ });
4061
+ }
4062
+ function VersionAdvisoryModal(props) {
4063
+ const { prompt, onReleaseFirst, onKeepEditing, onCancel } = props;
4064
+ if (!prompt) return null;
4065
+ const { version, reason, diff } = prompt;
4066
+ const nextVersion = version + 1;
4067
+ return /* @__PURE__ */ jsx(Modal, {
4068
+ open: true,
4069
+ onOpenChange: (status) => {
4070
+ if (!status) onCancel();
4071
+ },
4072
+ children: /* @__PURE__ */ jsxs("div", {
4073
+ className: "w-[440px] p-6",
4074
+ "data-testid": "version-advisory-modal",
4075
+ children: [
4076
+ /* @__PURE__ */ jsxs("div", {
4077
+ className: "pb-2 text-2xl font-bold text-foreground",
4078
+ children: [
4079
+ "Is version ",
4080
+ version,
4081
+ " of this model already in use?"
4082
+ ]
4083
+ }),
4084
+ /* @__PURE__ */ jsxs("div", {
4085
+ className: "my-4 rounded-md bg-background p-4 text-left text-sm text-foreground",
4086
+ children: [
4087
+ /* @__PURE__ */ jsxs("p", { children: [
4088
+ reason,
4089
+ " Documents that were already created with version ",
4090
+ version,
4091
+ " ",
4092
+ "may stop working correctly."
4093
+ ] }),
4094
+ diff && /* @__PURE__ */ jsxs(Fragment, { children: [
4095
+ /* @__PURE__ */ jsx(FieldDiffList, {
4096
+ fields: diff.addedFields,
4097
+ label: "New fields:"
4098
+ }),
4099
+ /* @__PURE__ */ jsx(FieldDiffList, {
4100
+ fields: diff.removedFields,
4101
+ label: "Removed fields:"
4102
+ }),
4103
+ /* @__PURE__ */ jsx(FieldDiffList, {
4104
+ fields: diff.changedFields,
4105
+ label: "Changed fields:"
4106
+ })
4107
+ ] }),
4108
+ /* @__PURE__ */ jsxs("p", {
4109
+ className: "mt-3",
4110
+ children: [
4111
+ "If others are already using version ",
4112
+ version,
4113
+ ", release version",
4114
+ " ",
4115
+ nextVersion,
4116
+ " first. Your change will go into version ",
4117
+ nextVersion,
4118
+ ", and existing documents can be updated safely."
4119
+ ]
4120
+ })
4121
+ ]
4122
+ }),
4123
+ /* @__PURE__ */ jsxs("div", {
4124
+ className: "mt-4 flex flex-col gap-2",
4125
+ children: [/* @__PURE__ */ jsx(ModalButton, {
4126
+ className: compactButtonStyle,
4127
+ "data-testid": "advisory-release-first",
4128
+ onClick: onReleaseFirst,
4129
+ variant: "confirm",
4130
+ children: `It's in use — release v${nextVersion} first`
4131
+ }), /* @__PURE__ */ jsxs(ModalButton, {
4132
+ className: compactButtonStyle,
4133
+ "data-testid": "advisory-keep-editing",
4134
+ onClick: onKeepEditing,
4135
+ variant: "cancel",
4136
+ children: ["Still in development — keep editing v", version]
4137
+ })]
4138
+ })
4139
+ ]
4140
+ })
4141
+ });
4142
+ }
4143
+ //#endregion
4144
+ //#region editors/document-model-editor/config.ts
4145
+ const editorConfig = { isExternalControlsEnabled: false };
4146
+ //#endregion
4147
+ //#region editors/document-model-editor/utils/change-classification.ts
4148
+ function isShapeTypeNode(node) {
4149
+ return node.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || node.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || node.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION;
4150
+ }
4151
+ function collectTypeFields(doc) {
4152
+ const types = /* @__PURE__ */ new Map();
4153
+ for (const definition of doc.definitions) {
4154
+ if (!isShapeTypeNode(definition)) continue;
4155
+ const fields = /* @__PURE__ */ new Map();
4156
+ if (definition.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION) for (const value of definition.values ?? []) fields.set(value.name.value, "value");
4157
+ else for (const field of definition.fields ?? []) fields.set(field.name.value, (0, import_graphql.print)(field.type));
4158
+ types.set(definition.name.value, fields);
4159
+ }
4160
+ return types;
4161
+ }
4162
+ function escapeRegExp(value) {
4163
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4164
+ }
4165
+ function replaceTypeName(printedType, oldName, newName) {
4166
+ return printedType.replace(new RegExp(`\\b${escapeRegExp(oldName)}\\b`, "g"), newName);
4167
+ }
4168
+ function typeSignature(name, fields) {
4169
+ return [...fields.entries()].map(([field, type]) => `${field}:${replaceTypeName(type, name, "__SELF__")}`).sort().join("|");
4170
+ }
4171
+ function detectTypeRenames(oldTypes, newTypes) {
4172
+ const renames = /* @__PURE__ */ new Map();
4173
+ const removed = [...oldTypes.keys()].filter((name) => !newTypes.has(name));
4174
+ const added = new Set([...newTypes.keys()].filter((name) => !oldTypes.has(name)));
4175
+ for (const oldName of removed) {
4176
+ const oldSignature = typeSignature(oldName, oldTypes.get(oldName));
4177
+ for (const newName of added) if (typeSignature(newName, newTypes.get(newName)) === oldSignature) {
4178
+ renames.set(oldName, newName);
4179
+ added.delete(newName);
4180
+ break;
4181
+ }
4182
+ }
4183
+ return renames;
4184
+ }
4185
+ function flattenFields(types, renames) {
4186
+ const fields = /* @__PURE__ */ new Map();
4187
+ for (const [typeName, typeFields] of types) {
4188
+ const resolvedTypeName = renames.get(typeName) ?? typeName;
4189
+ for (const [fieldName, printedType] of typeFields) {
4190
+ let resolvedType = printedType;
4191
+ for (const [oldName, newName] of renames) resolvedType = replaceTypeName(resolvedType, oldName, newName);
4192
+ fields.set(`${resolvedTypeName}.${fieldName}`, resolvedType);
4193
+ }
4194
+ }
4195
+ return fields;
4196
+ }
4197
+ function hasShapeChange(diff) {
4198
+ return diff.addedFields.length > 0 || diff.removedFields.length > 0 || diff.changedFields.length > 0;
4199
+ }
4200
+ function diffSdlShapes(oldSdl, newSdl) {
4201
+ const empty = {
4202
+ addedFields: [],
4203
+ removedFields: [],
4204
+ changedFields: []
4205
+ };
4206
+ let oldDoc;
4207
+ let newDoc;
4208
+ try {
4209
+ oldDoc = (0, import_graphql.parse)(oldSdl);
4210
+ newDoc = (0, import_graphql.parse)(newSdl);
4211
+ } catch {
4212
+ return empty;
4213
+ }
4214
+ const oldTypes = collectTypeFields(oldDoc);
4215
+ const newTypes = collectTypeFields(newDoc);
4216
+ const oldFields = flattenFields(oldTypes, detectTypeRenames(oldTypes, newTypes));
4217
+ const newFields = flattenFields(newTypes, /* @__PURE__ */ new Map());
4218
+ const diff = {
4219
+ addedFields: [],
4220
+ removedFields: [],
4221
+ changedFields: []
4222
+ };
4223
+ for (const [key, newType] of newFields) {
4224
+ const oldType = oldFields.get(key);
4225
+ if (oldType === void 0) diff.addedFields.push(key);
4226
+ else if (oldType !== newType) diff.changedFields.push(`${key}: ${oldType} → ${newType}`);
4227
+ }
4228
+ for (const key of oldFields.keys()) if (!newFields.has(key)) diff.removedFields.push(key);
4229
+ return diff;
4230
+ }
4231
+ const SAFE = { kind: "safe" };
4232
+ function isBlank(value) {
4233
+ return !value || !value.trim() || value.trim() === "{}";
4234
+ }
4235
+ /**
4236
+ * True for a blank SDL, or an SDL whose types contain nothing but the
4237
+ * `_placeholder` field the editor seeds new state/operation schemas with
4238
+ * (see `makeInitialSchemaDoc` / `makeOperationInitialDoc` in ./helpers.ts).
4239
+ * Replacing a placeholder-only schema with real fields is a user's first
4240
+ * edit on a brand-new model, not a version-relevant change.
4241
+ */
4242
+ function isPlaceholderOnlySchema(sdl) {
4243
+ if (isBlank(sdl)) return true;
4244
+ let doc;
4245
+ try {
4246
+ doc = (0, import_graphql.parse)(sdl);
4247
+ } catch {
4248
+ return false;
4249
+ }
4250
+ return [...collectTypeFields(doc).values()].every((fields) => fields.size === 0 || fields.size === 1 && fields.has("_placeholder"));
4251
+ }
4252
+ function findOperation(spec, operationId) {
4253
+ for (const module of spec.modules) {
4254
+ const operation = module.operations.find((op) => op.id === operationId);
4255
+ if (operation) return operation;
4256
+ }
4257
+ }
4258
+ function addedSinceLastRelease(operationId, previousSpec) {
4259
+ return previousSpec !== void 0 && !findOperation(previousSpec, operationId);
4260
+ }
4261
+ function classifySetStateSchema(input, latestSpec) {
4262
+ const currentSchema = input.scope === "local" ? latestSpec.state.local.schema : latestSpec.state.global.schema;
4263
+ if (isPlaceholderOnlySchema(currentSchema)) return SAFE;
4264
+ const diff = diffSdlShapes(currentSchema, input.schema);
4265
+ if (!hasShapeChange(diff)) return SAFE;
4266
+ return {
4267
+ kind: "version-relevant",
4268
+ 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.`,
4269
+ diff
4270
+ };
4271
+ }
4272
+ /**
4273
+ * The editor pre-fills a fresh model's initial value from the placeholder
4274
+ * schema, so a value that is blank or carries only the `_placeholder` key is
4275
+ * still being initialized rather than changed.
4276
+ */
4277
+ function isPlaceholderOnlyInitialValue(value) {
4278
+ if (isBlank(value)) return true;
4279
+ let parsed;
4280
+ try {
4281
+ parsed = JSON.parse(value);
4282
+ } catch {
4283
+ return false;
4284
+ }
4285
+ if (typeof parsed !== "object" || parsed === null) return false;
4286
+ return Object.keys(parsed).every((key) => key === "_placeholder");
4287
+ }
4288
+ function classifySetInitialState(input, latestSpec) {
4289
+ const currentValue = input.scope === "local" ? latestSpec.state.local.initialValue : latestSpec.state.global.initialValue;
4290
+ if (isPlaceholderOnlyInitialValue(currentValue)) return SAFE;
4291
+ if (compareStringsWithoutWhitespace(currentValue, input.initialValue)) return SAFE;
4292
+ return {
4293
+ kind: "version-relevant",
4294
+ reason: `You're changing the starting content that version ${latestSpec.version} documents are built on.`
4295
+ };
4296
+ }
4297
+ function classifyOperationChange(action, operationId, latestSpec, previousSpec) {
4298
+ if (addedSinceLastRelease(operationId, previousSpec)) return SAFE;
4299
+ const operation = findOperation(latestSpec, operationId);
4300
+ if (!operation) return SAFE;
4301
+ const operationLabel = operation.name || "an operation";
4302
+ switch (action.type) {
4303
+ case "DELETE_OPERATION": return {
4304
+ kind: "version-relevant",
4305
+ reason: `You're removing the "${operationLabel}" operation from version ${latestSpec.version}.`
4306
+ };
4307
+ case "SET_OPERATION_NAME":
4308
+ if (isBlank(operation.name)) return SAFE;
4309
+ return {
4310
+ kind: "version-relevant",
4311
+ reason: `You're renaming the "${operationLabel}" operation in version ${latestSpec.version}.`
4312
+ };
4313
+ case "SET_OPERATION_SCHEMA": {
4314
+ if (isPlaceholderOnlySchema(operation.schema ?? "")) return SAFE;
4315
+ if (isBlank(action.input.schema)) return {
4316
+ kind: "version-relevant",
4317
+ reason: `You're changing the information that the "${operationLabel}" operation accepts in version ${latestSpec.version}.`
4318
+ };
4319
+ const diff = diffSdlShapes(operation.schema ?? "", action.input.schema ?? "");
4320
+ if (!hasShapeChange(diff)) return SAFE;
4321
+ return {
4322
+ kind: "version-relevant",
4323
+ reason: `You're changing the information that the "${operationLabel}" operation accepts in version ${latestSpec.version}.`,
4324
+ diff
4325
+ };
4326
+ }
4327
+ default: return SAFE;
4328
+ }
4329
+ }
4330
+ function classifyDeleteModule(moduleId, latestSpec, previousSpec) {
4331
+ const module = latestSpec.modules.find((candidate) => candidate.id === moduleId);
4332
+ if (!module || module.operations.length === 0) return SAFE;
4333
+ if (module.operations.every((operation) => addedSinceLastRelease(operation.id, previousSpec))) return SAFE;
4334
+ return {
4335
+ kind: "version-relevant",
4336
+ reason: `You're removing the "${module.name}" module and all of its operations from version ${latestSpec.version}.`
4337
+ };
4338
+ }
4339
+ /**
4340
+ * Classifies a document-model action as version-relevant (would break
4341
+ * documents created with the current version) or safe. `previousSpec` is the
4342
+ * last released specification, used to exempt operations added since the
4343
+ * release.
4344
+ */
4345
+ function classifyDocumentModelAction(action, latestSpec, previousSpec) {
4346
+ switch (action.type) {
4347
+ case "SET_STATE_SCHEMA": return classifySetStateSchema(action.input, latestSpec);
4348
+ case "SET_INITIAL_STATE": return classifySetInitialState(action.input, latestSpec);
4349
+ case "DELETE_OPERATION":
4350
+ case "SET_OPERATION_NAME":
4351
+ case "SET_OPERATION_SCHEMA": return classifyOperationChange(action, action.input.id, latestSpec, previousSpec);
4352
+ case "DELETE_MODULE": return classifyDeleteModule(action.input.id, latestSpec, previousSpec);
4353
+ default: return SAFE;
4354
+ }
4355
+ }
4356
+ /**
4357
+ * Pure decision core of the version advisory: given the actions about to be
4358
+ * dispatched, decide whether to dispatch immediately or prompt the user.
4359
+ */
4360
+ function decideDispatch(actions, latestSpec, previousSpec, hasSessionChoice) {
4361
+ if (hasSessionChoice) return { kind: "dispatch" };
4362
+ for (const action of actions) {
4363
+ const classification = classifyDocumentModelAction(action, latestSpec, previousSpec);
4364
+ if (classification.kind === "version-relevant") return {
4365
+ kind: "prompt",
4366
+ reason: classification.reason,
4367
+ diff: classification.diff
4368
+ };
4369
+ }
4370
+ return { kind: "dispatch" };
4371
+ }
4372
+ //#endregion
4373
+ //#region editors/document-model-editor/hooks/useVersionAdvisory.ts
4374
+ /**
4375
+ * Versions the user has confirmed as "still in development" (or that were
4376
+ * just created via an explicit release) for this browser session. Keyed by
4377
+ * `${documentId}:${version}`. Deliberately in-memory: a publisher returning
4378
+ * in a later session is asked again, which is when the reminder matters.
4379
+ */
4380
+ const sessionVersionChoices = /* @__PURE__ */ new Set();
4381
+ function useVersionAdvisory(args) {
4382
+ const { documentId, latestSpec, previousSpec, dispatch, onReleaseError } = args;
4383
+ const [prompt, setPrompt] = useState(void 0);
4384
+ const pendingRef = useRef(void 0);
4385
+ const choiceKey = `${documentId}:${latestSpec.version}`;
4386
+ const guardedDispatch = (...dispatchArgs) => {
4387
+ const [action] = dispatchArgs;
4388
+ const decision = decideDispatch((Array.isArray(action) ? action : [action]).filter((candidate) => candidate !== void 0), latestSpec, previousSpec, sessionVersionChoices.has(choiceKey));
4389
+ if (decision.kind === "dispatch") {
4390
+ dispatch(...dispatchArgs);
4391
+ return;
4392
+ }
4393
+ pendingRef.current = dispatchArgs;
4394
+ setPrompt({
4395
+ version: latestSpec.version,
4396
+ reason: decision.reason,
4397
+ diff: decision.diff
4398
+ });
4399
+ };
4400
+ const flushPending = () => {
4401
+ const pending = pendingRef.current;
4402
+ pendingRef.current = void 0;
4403
+ if (pending) dispatch(...pending);
4404
+ };
4405
+ const releaseFirst = () => {
4406
+ setPrompt(void 0);
4407
+ if (!pendingRef.current) return;
4408
+ dispatch(releaseNewVersion(), (errors) => {
4409
+ if (errors.length > 0) {
4410
+ pendingRef.current = void 0;
4411
+ onReleaseError?.(errors[0].message);
4412
+ }
4413
+ }, () => {
4414
+ if (!pendingRef.current) return;
4415
+ sessionVersionChoices.add(`${documentId}:${latestSpec.version + 1}`);
4416
+ flushPending();
4417
+ });
4418
+ };
4419
+ const keepEditing = () => {
4420
+ sessionVersionChoices.add(choiceKey);
4421
+ setPrompt(void 0);
4422
+ flushPending();
4423
+ };
4424
+ const cancelAdvisory = () => {
4425
+ pendingRef.current = void 0;
4426
+ setPrompt(void 0);
4427
+ };
4428
+ const markVersionInDevelopment = (version) => {
4429
+ sessionVersionChoices.add(`${documentId}:${version}`);
4430
+ };
4431
+ return {
4432
+ guardedDispatch,
4433
+ prompt,
4434
+ releaseFirst,
4435
+ keepEditing,
4436
+ cancelAdvisory,
4437
+ markVersionInDevelopment
4438
+ };
4439
+ }
4440
+ //#endregion
4441
+ //#region editors/document-model-editor/editor.tsx
4442
+ var editor_exports = /* @__PURE__ */ __exportAll({ default: () => Editor });
4443
+ const StateSchemas = lazy(() => import("./state-schemas-Ciq9kway.mjs"));
4444
+ const noopSetStateSchema = () => void 0;
4445
+ const noopSetInitialState = () => void 0;
4446
+ function Editor({ document, dispatch }) {
4447
+ useSetPHDocumentEditorConfig(editorConfig);
4448
+ const toast = usePHToast();
4449
+ const [scope, setScope] = useState("global");
4450
+ const documentNodeName = document.header.name;
4451
+ const { name: modelName, id: documentType, extension, description, author: { name: authorName, website: authorWebsite } } = document.state.global;
4452
+ const specifications = document.state.global.specifications;
4453
+ const latestSpec = specifications[specifications.length - 1];
4454
+ const previousSpec = specifications.length >= 2 ? specifications[specifications.length - 2] : void 0;
4455
+ const [viewedVersion, setViewedVersion] = useState("latest");
4456
+ const viewedSpec = viewedVersion === "latest" ? latestSpec : specifications.find((spec) => spec.version === viewedVersion) ?? latestSpec;
4457
+ const isViewingFrozenVersion = viewedSpec.version !== latestSpec.version;
4458
+ const { state: { global: { schema: globalStateSchema, initialValue: globalStateInitialValue }, local: { schema: localStateSchema, initialValue: localStateInitialValue } }, modules } = viewedSpec;
4459
+ const operations = modules.flatMap((module) => module.operations);
4460
+ const { state: { global: { schema: latestGlobalStateSchema, initialValue: latestGlobalStateInitialValue }, local: { schema: latestLocalStateSchema, initialValue: latestLocalStateInitialValue } }, modules: latestModules } = latestSpec;
4461
+ const latestOperations = latestModules.flatMap((module) => module.operations);
4462
+ const shouldSetInitialName = useRef(!modelName && !!documentNodeName && specifications.length === 1 && !latestGlobalStateSchema && latestModules.length === 0);
4463
+ useEffect(() => {
4464
+ if (!shouldSetInitialName.current || !documentNodeName) return;
4465
+ const initialSchemaDoc = initializeModelSchema(documentNodeName);
4466
+ dispatch([
4467
+ setModelName({ name: documentNodeName }),
4468
+ setStateSchema({
4469
+ schema: initialSchemaDoc,
4470
+ scope: "global"
4471
+ }),
4472
+ setInitialState({
4473
+ initialValue: makeInitialValueForSchema(initialSchemaDoc),
4474
+ scope: "global"
4475
+ })
4476
+ ]);
4477
+ shouldSetInitialName.current = false;
4478
+ }, [documentNodeName, dispatch]);
4479
+ const { guardedDispatch, prompt, releaseFirst, keepEditing, cancelAdvisory, markVersionInDevelopment } = useVersionAdvisory({
4480
+ documentId: document.header.id,
4481
+ latestSpec,
4482
+ previousSpec,
4483
+ dispatch,
4484
+ onReleaseError: (message) => {
4485
+ if (toast) toast(message, { type: "connect-warning" });
4486
+ }
4487
+ });
4488
+ const handleReleaseNewVersion = () => {
4489
+ const nextVersion = latestSpec.version + 1;
4490
+ dispatch(releaseNewVersion(), (errors) => {
4491
+ if (errors.length > 0 && toast) toast(errors[0].message, { type: "connect-warning" });
4492
+ }, () => {
4493
+ markVersionInDevelopment(nextVersion);
4494
+ setViewedVersion("latest");
4495
+ });
4496
+ };
4497
+ const operationSchemasSdl = operations.flatMap((operation) => operation.schema ?? []).join("\n");
4498
+ const handleSetModelId = (id) => {
4499
+ if (compareStringsWithoutWhitespace(id, documentType)) return;
4500
+ guardedDispatch([setModelId({ id })]);
4501
+ };
4502
+ const handleSetModelDescription = (newDescription) => {
4503
+ if (compareStringsWithoutWhitespace(newDescription, description)) return;
4504
+ guardedDispatch(setModelDescription({ description: newDescription }));
4505
+ };
4506
+ const handleSetModelExtension = (newExtension) => {
4507
+ if (compareStringsWithoutWhitespace(newExtension, extension)) return;
4508
+ guardedDispatch(setModelExtension({ extension: newExtension }));
4509
+ };
4510
+ const handleSetModelName = (newName) => {
4511
+ if (compareStringsWithoutWhitespace(newName, modelName)) return;
4512
+ guardedDispatch(setModelName({ name: newName }));
4513
+ };
4514
+ const handleSetAuthorName = (newAuthorName) => {
4515
+ if (compareStringsWithoutWhitespace(newAuthorName, authorName)) return;
4516
+ guardedDispatch(setAuthorName({ authorName: newAuthorName }));
4517
+ };
4518
+ const handleSetAuthorWebsite = (newAuthorWebsite) => {
4519
+ if (compareStringsWithoutWhitespace(newAuthorWebsite, authorWebsite ?? "")) return;
4520
+ guardedDispatch(setAuthorWebsite({ authorWebsite: newAuthorWebsite }));
4521
+ };
4522
+ const handleSetStateSchema = (newSchema, scope) => {
4523
+ if (compareStringsWithoutWhitespace(newSchema, scope === "global" ? latestGlobalStateSchema : latestLocalStateSchema)) return;
4524
+ guardedDispatch(setStateSchema({
4525
+ schema: newSchema,
4526
+ scope
4527
+ }));
4528
+ };
4529
+ const handleSetInitialState = (newInitialValue, scope) => {
4530
+ if (compareStringsWithoutWhitespace(newInitialValue, scope === "global" ? latestGlobalStateInitialValue : latestLocalStateInitialValue)) return;
4531
+ guardedDispatch(setInitialState({
4532
+ initialValue: newInitialValue,
4533
+ scope
4534
+ }));
4535
+ };
4536
+ const handleAddModule = (name) => {
4537
+ return new Promise((resolve) => {
4538
+ try {
4539
+ if (latestModules.some((module) => compareStringsWithoutWhitespace(module.name, name))) {
4540
+ resolve(void 0);
4541
+ return;
4542
+ }
4543
+ const id = generateId();
4544
+ guardedDispatch(addModule({
4545
+ id,
4546
+ name
4547
+ }));
4548
+ resolve(id);
4549
+ } catch (error) {
4550
+ console.error("Failed to add module:", error);
4551
+ resolve(void 0);
4552
+ }
4553
+ });
4554
+ };
4555
+ const handleSetModuleName = (id, name) => {
4556
+ if (latestModules.some((module) => compareStringsWithoutWhitespace(module.name, name))) return;
4557
+ guardedDispatch(setModuleName({
4558
+ id,
4559
+ name
4560
+ }));
4561
+ };
4562
+ const handleDeleteModule = (id) => {
4563
+ guardedDispatch(deleteModule({ id }));
4564
+ };
4565
+ const handleAddOperation = (moduleId, name) => {
4566
+ return new Promise((resolve) => {
4567
+ const id = generateId();
4568
+ guardedDispatch(addOperation({
4569
+ id,
4570
+ moduleId,
4571
+ name,
4572
+ scope
4573
+ }), (errors) => {
4574
+ if (errors.length > 0) {
4575
+ if (toast) toast(errors[0].message, { type: "connect-warning" });
4576
+ resolve(void 0);
4577
+ } else resolve(id);
4578
+ }, () => resolve(id));
4579
+ });
4580
+ };
4581
+ const handleSetOperationName = (id, name) => {
4582
+ guardedDispatch(setOperationName({
4583
+ id,
4584
+ name
4585
+ }), (errors) => {
4586
+ if (errors.length > 0 && toast) toast(errors[0].message, { type: "connect-warning" });
4587
+ });
4588
+ };
4589
+ const handleSetOperationSchema = (id, newSchema) => {
4590
+ const operation = latestOperations.find((operation) => operation.id === id);
4591
+ if (operation?.schema && compareStringsWithoutWhitespace(newSchema, operation.schema)) return;
4592
+ guardedDispatch(setOperationSchema({
4593
+ id,
4594
+ schema: newSchema
4595
+ }));
4596
+ };
4597
+ const handleToggleNoInputRequired = (id, noInputRequired) => {
4598
+ const operation = latestOperations.find((op) => op.id === id);
4599
+ if (!operation?.name) return;
4600
+ if (noInputRequired) guardedDispatch(setOperationSchema({
4601
+ id,
4602
+ schema: makeEmptyOperationSchema(operation.name)
4603
+ }));
4604
+ else guardedDispatch(setOperationSchema({
4605
+ id,
4606
+ schema: makeOperationInitialDoc(operation.name)
4607
+ }));
4608
+ };
4609
+ const handleSetOperationDescription = (id, newDescription) => {
4610
+ if (compareStringsWithoutWhitespace(latestOperations.find((operation) => operation.id === id)?.description ?? "", newDescription)) return;
4611
+ guardedDispatch(setOperationDescription({
4612
+ id,
4613
+ description: newDescription
4614
+ }));
4615
+ };
4616
+ const handleDeleteOperation = (id) => {
4617
+ guardedDispatch(deleteOperation({ id }));
4618
+ };
4619
+ const handleAddOperationError = (operationId, errorName) => {
4620
+ return new Promise((resolve) => {
4621
+ try {
4622
+ if ((latestOperations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) {
4623
+ resolve(void 0);
4624
+ return;
4625
+ }
4626
+ const id = generateId();
4627
+ const errorCode = pascalCase(errorName);
4628
+ guardedDispatch(addOperationError({
4629
+ id,
4630
+ operationId,
4631
+ errorName,
4632
+ errorCode
4633
+ }));
4634
+ resolve(id);
4635
+ } catch (error) {
4636
+ console.error("Failed to add operation error:", error);
4637
+ resolve(void 0);
4638
+ }
4639
+ });
4640
+ };
4641
+ const handleDeleteOperationError = (id) => {
4642
+ guardedDispatch(deleteOperationError({ id }));
4643
+ };
4644
+ const handleSetOperationErrorName = (operationId, errorId, errorName) => {
4645
+ if ((latestOperations.find((operation) => operation.id === operationId)?.errors.map((error) => error.name).filter(Boolean) ?? []).some((name) => compareStringsWithoutWhitespace(name, errorName))) return;
4646
+ guardedDispatch(setOperationErrorName({
4647
+ id: errorId,
4648
+ errorName
4649
+ }));
4650
+ };
4651
+ const addOperationAndInitialSchema = async (moduleId, name) => {
4652
+ try {
4653
+ const id = await handleAddOperation(moduleId, name);
4654
+ if (!id) return void 0;
4655
+ try {
4656
+ handleSetOperationSchema(id, makeOperationInitialDoc(name));
4657
+ return id;
4658
+ } catch (error) {
4659
+ console.error("Failed to update operation schema:", error);
4660
+ return;
4661
+ }
4662
+ } catch (error) {
4663
+ console.error("Failed to add operation and schema:", error);
4664
+ return;
4665
+ }
4666
+ };
4667
+ return /* @__PURE__ */ jsxs("main", {
4668
+ className: "min-h-dvh bg-background p-6",
4669
+ children: [
4670
+ /* @__PURE__ */ jsx(DocumentToolbar, { document }),
4671
+ /* @__PURE__ */ jsx(SchemaContextProvider, {
4672
+ globalStateSchemaSdl: globalStateSchema,
4673
+ localStateSchemaSdl: localStateSchema,
4674
+ operationSchemasSdl,
4675
+ children: /* @__PURE__ */ jsxs("div", {
4676
+ className: "mx-auto max-w-6xl px-4 pt-8",
4677
+ children: [
4678
+ /* @__PURE__ */ jsx(VersionControls, {
4679
+ specifications,
4680
+ viewedVersion: viewedSpec.version,
4681
+ onViewVersion: setViewedVersion,
4682
+ onReleaseNewVersion: handleReleaseNewVersion
4683
+ }),
4684
+ /* @__PURE__ */ jsx(ModelMetadata, {
4685
+ name: modelName,
4686
+ documentType,
4687
+ extension,
4688
+ description,
4689
+ authorName,
4690
+ authorWebsite: authorWebsite ?? "",
4691
+ globalStateSchema: latestGlobalStateSchema,
4692
+ localStateSchema: latestLocalStateSchema,
4693
+ setModelId: handleSetModelId,
4694
+ setModelDescription: handleSetModelDescription,
4695
+ setModelExtension: handleSetModelExtension,
4696
+ setModelName: handleSetModelName,
4697
+ setAuthorName: handleSetAuthorName,
4698
+ setAuthorWebsite: handleSetAuthorWebsite,
4699
+ setStateSchema: handleSetStateSchema
4700
+ }),
4701
+ /* @__PURE__ */ jsx(Divider, {}),
4702
+ isViewingFrozenVersion && /* @__PURE__ */ jsx(FrozenVersionBanner, {
4703
+ latestVersion: latestSpec.version,
4704
+ viewedVersion: viewedSpec.version
4705
+ }),
4706
+ /* @__PURE__ */ jsxs("div", {
4707
+ className: isViewingFrozenVersion ? "pointer-events-none opacity-80 select-none" : void 0,
4708
+ inert: isViewingFrozenVersion || void 0,
4709
+ children: [
4710
+ /* @__PURE__ */ jsx(Suspense, { children: /* @__PURE__ */ jsx(StateSchemas, {
4711
+ modelName,
4712
+ globalStateSchema,
4713
+ globalStateInitialValue,
4714
+ localStateSchema,
4715
+ localStateInitialValue,
4716
+ setStateSchema: isViewingFrozenVersion ? noopSetStateSchema : handleSetStateSchema,
4717
+ setInitialState: isViewingFrozenVersion ? noopSetInitialState : handleSetInitialState,
4718
+ currentScope: scope,
4719
+ onScopeChange: setScope
4720
+ }) }),
4721
+ /* @__PURE__ */ jsx(Divider, {}),
4722
+ /* @__PURE__ */ jsxs("h3", {
4723
+ className: "mb-6 text-lg text-foreground capitalize",
4724
+ children: [scope, " Operations"]
4725
+ }),
4726
+ /* @__PURE__ */ jsx(Modules, {
4727
+ modules: modules.map((module) => ({
4728
+ ...module,
4729
+ operations: module.operations.filter((op) => op.scope === scope)
4730
+ })),
4731
+ allOperations: operations,
4732
+ addModule: handleAddModule,
4733
+ updateModuleName: handleSetModuleName,
4734
+ deleteModule: handleDeleteModule,
4735
+ updateOperationName: handleSetOperationName,
4736
+ updateOperationSchema: handleSetOperationSchema,
4737
+ setOperationDescription: handleSetOperationDescription,
4738
+ deleteOperation: handleDeleteOperation,
4739
+ addOperationError: handleAddOperationError,
4740
+ deleteOperationError: handleDeleteOperationError,
4741
+ setOperationErrorName: handleSetOperationErrorName,
4742
+ addOperationAndInitialSchema,
4743
+ toggleNoInputRequired: handleToggleNoInputRequired
4744
+ })
4745
+ ]
4746
+ })
4747
+ ]
4748
+ })
4749
+ }),
4750
+ /* @__PURE__ */ jsx(VersionAdvisoryModal, {
4751
+ prompt,
4752
+ onReleaseFirst: releaseFirst,
4753
+ onKeepEditing: keepEditing,
4754
+ onCancel: cancelAdvisory
4755
+ })
4756
+ ]
4757
+ });
4758
+ }
4759
+ //#endregion
4760
+ export { ensureValidStateSchemaName as a, makeMinimalObjectForStateType as c, Editor as default, Button as i, makeStateSchemaNameForScope as l, composeRefs$1 as n, StateValidationError as o, useComposedRefs$1 as r, makeInitialSchemaDoc as s, editor_exports as t, validateStateObject as u };
4761
+
4762
+ //# sourceMappingURL=editor-C54qhQLX.mjs.map