@powerhousedao/powerhouse-vetra-packages 6.2.3-dev.5 → 6.2.3-dev.50

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