import { _ as string, f as lazy, g as record, i as sentenceCase, l as array, m as number, r as pascalCase, s as _null, u as boolean, v as union } from "./dist-fA4EItr0.mjs";
import { t as require_graphql } from "./graphql-DskHmkMe.mjs";
import { a as customScalars } from "./documents-BFBPmyw1.mjs";
import { n as safeParseSdl } from "./schema-context-CX5ml_9t.mjs";
//#region ../../node_modules/.pnpm/@powerhousedao+document-engineering@1.40.5_@types+express@4.17.25_@types+react-dom@19.2_75e28b6ec666f63b132a491ff3a6fdf7/node_modules/@powerhousedao/document-engineering/dist/src/scalars/graphql/utils.js
const SerializableSchema = lazy(() => union([
	string(),
	number(),
	boolean(),
	_null(),
	array(SerializableSchema),
	record(string(), SerializableSchema)
]));
function getPHCustomScalarByTypeName(name) {
	return Object.values(customScalars).find((scalar) => scalar.config.name === name) ?? null;
}
//#endregion
//#region editors/document-model-editor/constants/graphql-kinds.ts
const STRING_GQL_PRIMITIVE_NAME = "String";
const BOOLEAN_GQL_PRIMITIVE_NAME = "Boolean";
const FLOAT_GQL_PRIMITIVE_NAME = "Float";
const gqlPrimitiveNodeNamesList = [
	STRING_GQL_PRIMITIVE_NAME,
	BOOLEAN_GQL_PRIMITIVE_NAME,
	"Int",
	FLOAT_GQL_PRIMITIVE_NAME,
	"ID"
];
//#endregion
//#region editors/document-model-editor/utils/helpers.ts
var import_graphql = require_graphql();
function makeStateSchemaNameForScope(modelName, scope) {
	const modelNamePascalCase = pascalCase(modelName);
	const scopePascalCase = pascalCase(scope);
	return scopePascalCase === "Global" ? `${modelNamePascalCase}State` : `${modelNamePascalCase}${scopePascalCase}State`;
}
function makeInitialSchemaDoc(modelName, scope) {
	return `type ${makeStateSchemaNameForScope(modelName, scope)} {
  "Add your ${scope} state fields here"
  _placeholder: String
}`;
}
function makeOperationInitialDoc(name) {
	return `input ${pascalCase(name)}Input {
  "Add your inputs here"
  _placeholder: String
}`;
}
function makeEmptyOperationSchema(operationName) {
	return `input ${pascalCase(operationName)}Input {\n  _empty: Boolean\n}`;
}
function isEmptyOperationSchema(schema) {
	if (!schema) return false;
	return /_empty:\s*Boolean/.test(schema) && !schema.replace(/_empty:\s*Boolean/, "").match(/\w+:\s*\w+/);
}
function safeParseJsonRecord(json) {
	try {
		return JSON.parse(json);
	} catch (_error) {
		return null;
	}
}
function makeMinimalObjectForStateType(args) {
	const { sharedSchemaDocumentNode, stateTypeDefinitionNode, existingValue } = args;
	const existingValueObject = safeParseJsonRecord(existingValue);
	if (!existingValueObject) return existingValue;
	const stateTypeDefinitionFields = stateTypeDefinitionNode.fields;
	if (!stateTypeDefinitionFields?.length) return existingValue;
	const minimalObject = makeMinimalValuesForObjectFields({
		schemaDocumentNode: sharedSchemaDocumentNode,
		fieldDefinitionNodes: stateTypeDefinitionFields,
		existingValueObject,
		visitedTypes: new Set([stateTypeDefinitionNode.name.value])
	});
	return JSON.stringify(minimalObject, null, 2);
}
function makeMinimalValuesForObjectFields(args) {
	const { schemaDocumentNode, existingValueObject, fieldDefinitionNodes, visitedTypes } = args;
	const newJson = {};
	for (const astNode of fieldDefinitionNodes) {
		const fieldName = getASTNodeName(astNode);
		if (!fieldName) continue;
		const minimalValue = makeMinimalValueForASTNode({
			fieldName,
			astNode,
			schemaDocumentNode,
			existingValueObject,
			visitedTypes
		});
		newJson[astNode.name.value] = minimalValue;
	}
	return newJson;
}
function makeMinimalValueForASTNode(args) {
	const { fieldName, astNode, schemaDocumentNode, existingValueObject, visitedTypes } = args;
	const existingFieldValue = existingValueObject?.[fieldName];
	let node = astNode;
	if (isFieldDefinitionNode(astNode)) node = getASTNodeTypeNode(node);
	const isNonNull = isNonNullNode(node);
	if (isNonNull) node = getASTNodeTypeNode(node);
	if (isListTypeNode(node)) return makeMinimalValueForGqlListNode(node, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes);
	if (isGqlPrimitiveNode(node)) return makeMinimalValueForGQLPrimitiveNode(node, existingFieldValue, isNonNull);
	const namedTypeDefinitionNode = getNamedTypeDefinitionNode(node, schemaDocumentNode);
	if (isEnumTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull);
	if (isScalarTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlScalar(namedTypeDefinitionNode, existingFieldValue, isNonNull);
	if (isUnionTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes);
	if (isObjectTypeDefinitionNode(namedTypeDefinitionNode)) return makeMinimalValueForGqlObject(namedTypeDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
	return existingFieldValue;
}
function isFieldDefinitionNode(astNodeTypeNode) {
	if (!astNodeTypeNode) return false;
	return astNodeTypeNode.kind === import_graphql.Kind.FIELD_DEFINITION;
}
function isNonNullNode(astNode) {
	if (!astNode) return false;
	return astNode.kind === import_graphql.Kind.NON_NULL_TYPE;
}
function isGqlPrimitiveNode(astNodeTypeNode) {
	if (!astNodeTypeNode) return false;
	const name = getASTNodeName(astNodeTypeNode);
	return gqlPrimitiveNodeNamesList.includes(name);
}
function isListTypeNode(astNodeTypeNode) {
	if (!astNodeTypeNode) return false;
	return astNodeTypeNode.kind === import_graphql.Kind.LIST_TYPE;
}
function isEnumTypeDefinitionNode(definitionNode) {
	if (!definitionNode) return false;
	return definitionNode.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION;
}
function isScalarTypeDefinitionNode(definitionNode) {
	if (!definitionNode) return false;
	return definitionNode.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION;
}
function isUnionTypeDefinitionNode(definitionNode) {
	if (!definitionNode) return false;
	return definitionNode.kind === import_graphql.Kind.UNION_TYPE_DEFINITION;
}
function isObjectTypeDefinitionNode(definitionNode) {
	if (!definitionNode) return false;
	return definitionNode.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION;
}
function getASTNodeName(astNode) {
	if (!astNode) return null;
	if (!("name" in astNode)) return null;
	if (!astNode.name) return null;
	if (!("value" in astNode.name)) return null;
	return astNode.name.value;
}
function getASTNodeTypeNode(astNode) {
	if (!astNode) return null;
	if (!("type" in astNode)) return null;
	return astNode.type;
}
function makeMinimalValueForGQLPrimitiveNode(primitiveTypeNode, existingFieldValue, isNonNull) {
	const name = getASTNodeName(primitiveTypeNode);
	if (!name) return null;
	switch (name) {
		case "ID":
			if (string().safeParse(existingFieldValue).success) return existingFieldValue;
			return isNonNull ? "placeholder-id" : null;
		case BOOLEAN_GQL_PRIMITIVE_NAME:
			if (boolean().safeParse(existingFieldValue).success) return existingFieldValue;
			return isNonNull ? false : null;
		case "Int":
			if (number().safeParse(existingFieldValue).success) return existingFieldValue;
			return isNonNull ? 0 : null;
		case FLOAT_GQL_PRIMITIVE_NAME:
			if (number().safeParse(existingFieldValue).success) return existingFieldValue;
			return isNonNull ? 0 : null;
		case STRING_GQL_PRIMITIVE_NAME:
			if (string().safeParse(existingFieldValue).success) return existingFieldValue;
			return isNonNull ? "" : null;
	}
	return isNonNull ? existingFieldValue : null;
}
function makeMinimalValueForGqlEnum(namedTypeDefinitionNode, existingFieldValue, isNonNull) {
	const enumValues = namedTypeDefinitionNode.values?.map((value) => value.name.value) ?? [];
	if (typeof existingFieldValue === "string" && enumValues.includes(existingFieldValue)) return existingFieldValue;
	if (isNonNull) return enumValues[0];
	return null;
}
function makeMinimalValueForGqlScalar(scalarTypeDefinitionNode, existingFieldValue, isNonNull) {
	if (!isNonNull && !existingFieldValue) return null;
	const name = getASTNodeName(scalarTypeDefinitionNode);
	if (!name) {
		console.error("No name for scalar type definition node", scalarTypeDefinitionNode);
		return null;
	}
	const scalar = getPHCustomScalarByTypeName(name);
	if (!scalar) return null;
	if (scalar.schema.safeParse(existingFieldValue).success) return existingFieldValue;
	if (!isNonNull) return null;
	const minimalValue = scalar.getDefaultValue?.();
	if (minimalValue) return minimalValue;
	return existingFieldValue;
}
function makeMinimalValueForGqlUnion(namedTypeDefinitionNode, existingFieldValue, schemaDocumentNode, existingValueObject, isNonNull, visitedTypes) {
	if (!isNonNull && !existingFieldValue) return null;
	if (!namedTypeDefinitionNode.types?.length) return null;
	const firstNamedTypeDefinitionNode = namedTypeDefinitionNode.types?.at(0);
	if (!firstNamedTypeDefinitionNode) return null;
	const firstNamedTypeObjectDefinitionNode = getNamedTypeDefinitionNode(firstNamedTypeDefinitionNode, schemaDocumentNode);
	if (!isObjectTypeDefinitionNode(firstNamedTypeObjectDefinitionNode)) return null;
	return makeMinimalValueForGqlObject(firstNamedTypeObjectDefinitionNode, schemaDocumentNode, existingValueObject, existingFieldValue, isNonNull, visitedTypes);
}
function makeMinimalValueForGqlListNode(listTypeNode, existingFieldValue, isNonNull, schemaDocumentNode, visitedTypes) {
	if (!isNonNull && !Array.isArray(existingFieldValue)) return null;
	if (isNonNull && !Array.isArray(existingFieldValue)) return [];
	return existingFieldValue.map((item, index) => makeMinimalValueForASTNode({
		fieldName: String(index),
		astNode: listTypeNode.type,
		schemaDocumentNode,
		existingValueObject: { [index]: item },
		visitedTypes
	}));
}
function makeMinimalValueForGqlObject(objectTypeDefinitionNode, schemaDocumentNode, _existingValueObject, existingFieldValue, isNonNull, visitedTypes) {
	const typeName = objectTypeDefinitionNode.name.value;
	if (visitedTypes?.has(typeName)) return null;
	if (!isNonNull && !existingFieldValue) return null;
	const fields = objectTypeDefinitionNode.fields;
	if (!fields?.length) return {};
	const newVisitedTypes = new Set(visitedTypes);
	newVisitedTypes.add(typeName);
	return makeMinimalValuesForObjectFields({
		schemaDocumentNode,
		existingValueObject: existingFieldValue && typeof existingFieldValue === "object" && !Array.isArray(existingFieldValue) ? existingFieldValue : null,
		fieldDefinitionNodes: fields,
		visitedTypes: newVisitedTypes
	});
}
function getNamedTypeDefinitionNode(astNodeTypeNode, schemaDocumentNode) {
	if (!astNodeTypeNode) return null;
	const name = getASTNodeName(astNodeTypeNode);
	if (!name) return null;
	const definitionNode = schemaDocumentNode.definitions.find((def) => "kind" in def && "name" in def && def.name?.value === name);
	if (!definitionNode) return null;
	return definitionNode;
}
function removeWhitespace(str) {
	return str.replace(/\s+|\\n|\\t/g, "").toLowerCase();
}
function compareStringsWithoutWhitespace(str1, str2) {
	if (str1 === null || str2 === null || str1 === void 0 || str2 === void 0) return false;
	return removeWhitespace(str1) === removeWhitespace(str2);
}
function renameSchemaType(sdl, oldName, newName, scope) {
	const typeSuffix = scope === "global" ? "State" : "LocalState";
	const oldTypeName = `${pascalCase(oldName)}${typeSuffix}`;
	const newTypeName = `${pascalCase(newName)}${typeSuffix}`;
	const ast = safeParseSdl(sdl);
	if (!ast) return sdl;
	return (0, import_graphql.print)((0, import_graphql.visit)(ast, { ObjectTypeDefinition: (node) => {
		if (node.name.value === oldTypeName) return {
			...node,
			name: {
				...node.name,
				value: newTypeName
			}
		};
	} }));
}
function initializeModelSchema(modelName) {
	return makeInitialSchemaDoc(modelName, "global");
}
function updateModelSchemaNames(params) {
	const { oldName, newName, globalStateSchema, localStateSchema, setStateSchema } = params;
	setStateSchema(renameSchemaType(globalStateSchema, oldName, newName, "global"), "global");
	if (localStateSchema) setStateSchema(renameSchemaType(localStateSchema, oldName, newName, "local"), "local");
}
function handleModelNameChange(params) {
	const { newName, globalStateSchema, setStateSchema } = params;
	if (!!!globalStateSchema) {
		setStateSchema(initializeModelSchema(newName), "global");
		return;
	}
	updateModelSchemaNames(params);
}
function validateStateObject(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateValue) {
	let stateObjectJson;
	try {
		stateObjectJson = JSON.parse(stateValue);
	} catch (error) {
		return [new Error("Invalid JSON object", { cause: error })];
	}
	const typeDefByName = indexTypeDefinitions(sharedSchemaDocumentNode);
	const stateTypeName = stateTypeDefinitionNode.name.value;
	if (!typeDefByName.has(stateTypeName)) return [/* @__PURE__ */ new Error(`State type "${stateTypeName}" was not found in sharedSchemaDocumentNode`)];
	const inputSuffix = "Input";
	const generatedInputDefs = generateInputTypesForObjectTree(stateTypeName, typeDefByName, inputSuffix);
	const augmentedDoc = {
		...sharedSchemaDocumentNode,
		definitions: [...sharedSchemaDocumentNode.definitions, ...generatedInputDefs]
	};
	let schema;
	try {
		schema = (0, import_graphql.buildASTSchema)(augmentedDoc, { assumeValidSDL: false });
	} catch (e) {
		return [new Error("Failed to build schema from SDL", { cause: e })];
	}
	const op = (0, import_graphql.getOperationAST)((0, import_graphql.parse)(`query($v: ${`${stateTypeName}${inputSuffix}`}!) { __typename }`));
	if (!op) return [/* @__PURE__ */ new Error("Failed to create validation operation AST")];
	const { errors } = (0, import_graphql.getVariableValues)(schema, op.variableDefinitions ?? [], { v: stateObjectJson });
	const recursiveTypeErrors = detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName);
	const recursiveFieldNames = new Set(recursiveTypeErrors.map((e) => e.field));
	const validationErrors = errors ? graphQLErrorsToStateValidationErrors(errors).filter((e) => {
		if (e instanceof StateValidationError && e.kind === "NON_NULL") {
			const rootField = e.path[0];
			if (typeof rootField === "string" && recursiveFieldNames.has(rootField)) return false;
		}
		return true;
	}) : [];
	validationErrors.unshift(...recursiveTypeErrors);
	const missingOptionalErrors = detectMissingOptionalFields(sharedSchemaDocumentNode, stateTypeDefinitionNode, stateObjectJson);
	validationErrors.push(...missingOptionalErrors);
	return validationErrors;
}
/**
* Indexes object/input/enum/scalar/interface/union type definition nodes by name.
* Note: only AST definitions that have a "name" field are indexed.
*/
function indexTypeDefinitions(doc) {
	const map = /* @__PURE__ */ new Map();
	for (const def of doc.definitions) if (def.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION || def.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION || def.kind === import_graphql.Kind.INTERFACE_TYPE_DEFINITION || def.kind === import_graphql.Kind.UNION_TYPE_DEFINITION || def.kind === import_graphql.Kind.OBJECT_TYPE_EXTENSION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION || def.kind === import_graphql.Kind.ENUM_TYPE_EXTENSION || def.kind === import_graphql.Kind.INTERFACE_TYPE_EXTENSION || def.kind === import_graphql.Kind.UNION_TYPE_EXTENSION) {
		const name = def.name.value;
		if (!map.has(name)) map.set(name, def);
	}
	return map;
}
/**
* Generates InputObjectTypeDefinitionNode(s) for a root object type and any nested
* object types reachable via fields, converting object references to their *Input equivalents*.
*/
function generateInputTypesForObjectTree(rootObjectTypeName, typeDefByName, inputSuffix) {
	const generated = /* @__PURE__ */ new Map();
	const visiting = /* @__PURE__ */ new Set();
	const ensureInputForObject = (objectTypeName) => {
		const inputName = `${objectTypeName}${inputSuffix}`;
		if (generated.has(inputName)) return;
		if (visiting.has(objectTypeName)) return;
		visiting.add(objectTypeName);
		const def = typeDefByName.get(objectTypeName);
		if (!def) throw new import_graphql.GraphQLError(`Unknown referenced type "${objectTypeName}"`);
		if (def.kind !== import_graphql.Kind.OBJECT_TYPE_DEFINITION && def.kind !== import_graphql.Kind.OBJECT_TYPE_EXTENSION) throw new import_graphql.GraphQLError(`Type "${objectTypeName}" is not an object type; cannot generate input from kind "${def.kind}"`);
		const objDef = def;
		const inputFields = objDef.fields?.map((f) => {
			return {
				kind: import_graphql.Kind.INPUT_VALUE_DEFINITION,
				name: f.name,
				description: f.description,
				directives: [],
				type: convertOutputTypeNodeToInputTypeNode(f.type, typeDefByName, inputSuffix, ensureInputForObject),
				defaultValue: void 0
			};
		}) ?? [];
		const inputDef = {
			kind: import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION,
			name: {
				kind: import_graphql.Kind.NAME,
				value: inputName
			},
			description: objDef.description,
			directives: [],
			fields: inputFields
		};
		generated.set(inputName, inputDef);
		visiting.delete(objectTypeName);
	};
	ensureInputForObject(rootObjectTypeName);
	return Array.from(generated.values());
}
function convertOutputTypeNodeToInputTypeNode(typeNode, typeDefByName, inputSuffix, ensureInputForObject) {
	switch (typeNode.kind) {
		case import_graphql.Kind.NON_NULL_TYPE: return {
			kind: import_graphql.Kind.NON_NULL_TYPE,
			type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
		};
		case import_graphql.Kind.LIST_TYPE: return {
			kind: import_graphql.Kind.LIST_TYPE,
			type: convertOutputTypeNodeToInputTypeNode(typeNode.type, typeDefByName, inputSuffix, ensureInputForObject)
		};
		case import_graphql.Kind.NAMED_TYPE: {
			const named = typeNode;
			const name = named.name.value;
			const def = typeDefByName.get(name);
			if (def?.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION || def?.kind === import_graphql.Kind.OBJECT_TYPE_EXTENSION) {
				ensureInputForObject(name);
				return {
					kind: import_graphql.Kind.NAMED_TYPE,
					name: {
						kind: import_graphql.Kind.NAME,
						value: `${name}${inputSuffix}`
					}
				};
			}
			if (!def || def.kind === import_graphql.Kind.SCALAR_TYPE_DEFINITION || def.kind === import_graphql.Kind.ENUM_TYPE_DEFINITION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_DEFINITION || def.kind === import_graphql.Kind.INPUT_OBJECT_TYPE_EXTENSION) return named;
			if (def.kind === import_graphql.Kind.INTERFACE_TYPE_DEFINITION || def.kind === import_graphql.Kind.UNION_TYPE_DEFINITION) throw new import_graphql.GraphQLError(`Type "${name}" (${def.kind}) cannot be used in an input type`);
			throw new import_graphql.GraphQLError(`Unsupported named type "${name}" of kind "${def.kind}"`);
		}
		default: throw new import_graphql.GraphQLError(`Unsupported TypeNode kind: ${JSON.stringify(typeNode)}`);
	}
}
var StateValidationError = class extends Error {
	payload;
	originalMessage;
	constructor(payload, originalMessage) {
		super(payload.kind);
		this.name = "StateValidationError";
		this.payload = payload;
		this.originalMessage = originalMessage;
		Object.setPrototypeOf(this, new.target.prototype);
	}
	get kind() {
		return this.payload.kind;
	}
	get path() {
		return this.payload.path;
	}
	get field() {
		return this.payload.field;
	}
};
function extractInputPath(message) {
	const match = message.match(/at\s+"([^"]+)"/);
	if (!match) return [];
	const parts = match[1].split(".").filter(Boolean);
	return (parts[0] === "v" ? parts.slice(1) : parts).map((p) => /^\d+$/.test(p) ? Number(p) : p);
}
const RE_MISSING_REQUIRED_FIELD = /Field "([^"]+)" of required type "([^"]+)" was not provided\./;
const RE_UNKNOWN_FIELD = /Field "([^"]+)" is not defined by type "([^"]+)"\.(?: Did you mean "([^"]+)"\?)?/;
function extractMissingRequiredField(message) {
	const m = message.match(RE_MISSING_REQUIRED_FIELD);
	if (!m) return null;
	return {
		field: m[1],
		expectedType: m[2]
	};
}
function extractUnknownField(message) {
	const m = message.match(RE_UNKNOWN_FIELD);
	if (!m) return null;
	return {
		field: m[1],
		typeName: m[2],
		didYouMean: m[3]
	};
}
function lastFieldFromPath(path) {
	for (let i = path.length - 1; i >= 0; i--) if (typeof path[i] === "string") return path[i];
}
function extractExpectedType(message) {
	let m = message.match(/Expected non-nullable type "([^"]+)"/);
	if (m?.[1]) return m[1];
	m = message.match(/Expected type "([^"]+)"/);
	if (m?.[1]) return m[1];
	m = message.match(/;\s*([_A-Za-z][_0-9A-Za-z]*)\s+cannot represent/i);
	if (m?.[1]) return m[1];
}
function graphQLErrorsToStateValidationErrors(errors) {
	const out = [];
	for (const e of errors) {
		const originalMessage = e.message;
		const missing = extractMissingRequiredField(originalMessage);
		if (missing) {
			out.push(new StateValidationError({
				kind: "MISSING",
				path: [missing.field],
				field: missing.field,
				expectedType: missing.expectedType
			}, originalMessage));
			continue;
		}
		const unknown = extractUnknownField(originalMessage);
		if (unknown) {
			out.push(new StateValidationError({
				kind: "UNKNOWN_FIELD",
				path: [unknown.field],
				field: unknown.field,
				didYouMean: unknown.didYouMean
			}, originalMessage));
			continue;
		}
		const path = extractInputPath(originalMessage);
		const field = lastFieldFromPath(path) ?? "value";
		const expectedType = extractExpectedType(originalMessage);
		if (originalMessage.includes("Expected non-nullable type") && originalMessage.includes("not to be null")) {
			out.push(new StateValidationError({
				kind: "NON_NULL",
				path,
				field,
				expectedType
			}, originalMessage));
			continue;
		}
		if (originalMessage.includes("cannot represent") || originalMessage.includes("Expected type")) {
			out.push(new StateValidationError({
				kind: "TYPE",
				path,
				field,
				expectedType,
				details: originalMessage
			}, originalMessage));
			continue;
		}
		out.push(new StateValidationError({
			kind: "TYPE",
			path,
			field,
			details: originalMessage
		}, originalMessage));
	}
	return out;
}
/**
* Finds all fields defined in the schema that are missing from the state object.
* Returns information about each missing field including whether it's required.
*/
function findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value, basePath = []) {
	let stateObjectJson;
	try {
		stateObjectJson = typeof value === "string" ? JSON.parse(value) : value;
	} catch {
		return [];
	}
	const typeByName = indexObjectTypes(sharedSchemaDocumentNode);
	const missingFields = [];
	for (const field of rootTypeNode.fields ?? []) {
		const fieldName = field.name.value;
		const fieldPath = [...basePath, fieldName];
		const isRequired = field.type.kind === import_graphql.Kind.NON_NULL_TYPE;
		const underlyingType = isRequired ? field.type.type : field.type;
		if (!(fieldName in stateObjectJson)) {
			missingFields.push({
				fieldName,
				path: fieldPath,
				isRequired,
				type: underlyingType
			});
			continue;
		}
		const namedType = unwrapNamedType(field.type);
		const childType = namedType ? typeByName.get(namedType) : void 0;
		if (childType && typeof stateObjectJson[fieldName] === "object" && stateObjectJson[fieldName] !== null && !Array.isArray(stateObjectJson[fieldName])) {
			const nestedMissing = findMissingFields(sharedSchemaDocumentNode, childType, stateObjectJson[fieldName], fieldPath);
			missingFields.push(...nestedMissing);
		}
	}
	return missingFields;
}
/**
* Detects optional fields defined in the schema that are missing from the state object.
* Returns StateValidationError[] for each missing optional field.
*/
function detectMissingOptionalFields(sharedSchemaDocumentNode, rootTypeNode, value) {
	return findMissingFields(sharedSchemaDocumentNode, rootTypeNode, value).filter((field) => !field.isRequired).map((field) => new StateValidationError({
		kind: "MISSING_OPTIONAL",
		path: field.path,
		field: field.fieldName,
		expectedType: typeNodeToString(field.type)
	}));
}
/**
* Detects fields that have recursive types (types that reference themselves directly or indirectly).
* Returns a RECURSIVE_TYPE error for each field that contains a recursive type.
*/
function detectRecursiveTypes(stateTypeDefinitionNode, typeDefByName) {
	const errors = [];
	for (const field of stateTypeDefinitionNode.fields ?? []) {
		const fieldName = field.name.value;
		const namedTypeName = getNamedTypeName(field.type);
		if (!namedTypeName) continue;
		if (isRecursiveType(namedTypeName, typeDefByName, /* @__PURE__ */ new Set())) errors.push(new StateValidationError({
			kind: "RECURSIVE_TYPE",
			path: [fieldName],
			field: fieldName,
			typeName: namedTypeName
		}));
	}
	return errors;
}
/**
* Gets the named type name from a TypeNode, unwrapping NonNull and List types.
*/
function getNamedTypeName(typeNode) {
	if (typeNode.kind === import_graphql.Kind.NAMED_TYPE) return typeNode.name.value;
	if (typeNode.kind === import_graphql.Kind.NON_NULL_TYPE || typeNode.kind === import_graphql.Kind.LIST_TYPE) return getNamedTypeName(typeNode.type);
	return null;
}
/**
* Checks if a type is recursive (references itself directly or indirectly through required fields).
*/
function isRecursiveType(typeName, typeDefByName, visitedTypes) {
	if (visitedTypes.has(typeName)) return true;
	const typeDef = typeDefByName.get(typeName);
	if (!typeDef || typeDef.kind !== import_graphql.Kind.OBJECT_TYPE_DEFINITION) return false;
	visitedTypes.add(typeName);
	for (const field of typeDef.fields ?? []) {
		if (field.type.kind !== import_graphql.Kind.NON_NULL_TYPE) continue;
		const innerType = field.type.type;
		let fieldTypeName = null;
		if (innerType.kind === import_graphql.Kind.NAMED_TYPE) fieldTypeName = innerType.name.value;
		else if (innerType.kind === import_graphql.Kind.LIST_TYPE) fieldTypeName = getNamedTypeName(innerType);
		if (fieldTypeName && isRecursiveType(fieldTypeName, typeDefByName, visitedTypes)) return true;
	}
	visitedTypes.delete(typeName);
	return false;
}
/**
* Converts a TypeNode to its string representation (e.g., "String", "Int!", "[String]!")
*/
function typeNodeToString(typeNode) {
	switch (typeNode.kind) {
		case import_graphql.Kind.NAMED_TYPE: return typeNode.name.value;
		case import_graphql.Kind.NON_NULL_TYPE: return `${typeNodeToString(typeNode.type)}!`;
		case import_graphql.Kind.LIST_TYPE: return `[${typeNodeToString(typeNode.type)}]`;
	}
}
function indexObjectTypes(doc) {
	const map = /* @__PURE__ */ new Map();
	for (const def of doc.definitions) if (def.kind === import_graphql.Kind.OBJECT_TYPE_DEFINITION) map.set(def.name.value, def);
	return map;
}
function unwrapNamedType(typeNode) {
	if (typeNode.kind === import_graphql.Kind.NAMED_TYPE) return typeNode.name.value;
	if (typeNode.kind === import_graphql.Kind.NON_NULL_TYPE) return unwrapNamedType(typeNode.type);
	if (typeNode.kind === import_graphql.Kind.LIST_TYPE) return unwrapNamedType(typeNode.type);
}
//#endregion
//#region editors/document-model-editor/utils/linting.ts
function ensureDocumentContainsNodeWithNameAndType(doc, nodeName, nodeType) {
	const parsedDoc = safeParseSdl(doc);
	if (!parsedDoc) return true;
	return parsedDoc.definitions.some((def) => {
		return def.kind === import_graphql.Kind[nodeType] && "name" in def && def.name?.value === nodeName;
	});
}
function createNodeTypeAndNameDiagnostic(doc, errorMessage) {
	const parsedDoc = safeParseSdl(doc);
	if (!parsedDoc) return void 0;
	const firstNode = parsedDoc.definitions[0];
	const nameNode = "name" in firstNode ? firstNode.name : null;
	return {
		from: nameNode?.loc?.start ?? firstNode.loc?.start ?? 0,
		to: nameNode?.loc?.end ?? firstNode.loc?.end ?? 0,
		severity: "error",
		message: errorMessage
	};
}
function ensureValidStateSchemaName(doc, modelName, scope) {
	if (!safeParseSdl(doc)) return [];
	const requiredTypeName = makeStateSchemaNameForScope(modelName, scope);
	if (!ensureDocumentContainsNodeWithNameAndType(doc, requiredTypeName, "OBJECT_TYPE_DEFINITION")) return [createNodeTypeAndNameDiagnostic(doc, `${sentenceCase(scope)} state schema must be named ${requiredTypeName}`)].filter((d) => d !== void 0);
	return [];
}
function ensureValidOperationSchemaInputName(doc, operationName) {
	if (!doc || !safeParseSdl(doc)) return [];
	const requiredTypeName = `${pascalCase(operationName)}Input`;
	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);
	return [];
}
//#endregion
export { handleModelNameChange as a, makeEmptyOperationSchema as c, makeOperationInitialDoc as d, makeStateSchemaNameForScope as f, compareStringsWithoutWhitespace as i, makeInitialSchemaDoc as l, validateStateObject as m, ensureValidStateSchemaName as n, initializeModelSchema as o, renameSchemaType as p, StateValidationError as r, isEmptyOperationSchema as s, ensureValidOperationSchemaInputName as t, makeMinimalObjectForStateType as u };

//# sourceMappingURL=linting-Dx50GuLN.mjs.map