import { importShared } from './__federation_fn_import-BmYWUSaq.js';

function createInitializedPluginSpec(spec, implementation) {
    return { spec, implementation };
}
function createPluginSpec(name, options) {
    const { platforms, defaultInitializer } = options ?? {};
    return {
        type: 'plugin-spec',
        name,
        platforms: platforms && (Array.isArray(platforms) ? platforms : [platforms]),
        isOptional: false,
        optional() {
            return { ...this, isOptional: true };
        },
        defaultInitializer,
    };
}

function noop() { }

function isPrimitive(value) {
    return value == null || (typeof value !== 'object' && typeof value !== 'function');
}

function isTypedArray(x) {
    return ArrayBuffer.isView(x) && !(x instanceof DataView);
}

function getSymbols(object) {
    return Object.getOwnPropertySymbols(object).filter(symbol => Object.prototype.propertyIsEnumerable.call(object, symbol));
}

function cloneDeepWithImpl(valueToClone, keyToClone, objectToClone, stack = new Map(), cloneValue = undefined) {
    const cloned = cloneValue?.(valueToClone, keyToClone, objectToClone, stack);
    if (cloned != null) {
        return cloned;
    }
    if (isPrimitive(valueToClone)) {
        return valueToClone;
    }
    if (stack.has(valueToClone)) {
        return stack.get(valueToClone);
    }
    if (Array.isArray(valueToClone)) {
        const result = new Array(valueToClone.length);
        stack.set(valueToClone, result);
        for (let i = 0; i < valueToClone.length; i++) {
            result[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue);
        }
        if (Object.hasOwn(valueToClone, 'index')) {
            result.index = valueToClone.index;
        }
        if (Object.hasOwn(valueToClone, 'input')) {
            result.input = valueToClone.input;
        }
        return result;
    }
    if (valueToClone instanceof Date) {
        return new Date(valueToClone.getTime());
    }
    if (valueToClone instanceof RegExp) {
        const result = new RegExp(valueToClone.source, valueToClone.flags);
        result.lastIndex = valueToClone.lastIndex;
        return result;
    }
    if (valueToClone instanceof Map) {
        const result = new Map();
        stack.set(valueToClone, result);
        for (const [key, value] of valueToClone) {
            result.set(key, cloneDeepWithImpl(value, key, objectToClone, stack, cloneValue));
        }
        return result;
    }
    if (valueToClone instanceof Set) {
        const result = new Set();
        stack.set(valueToClone, result);
        for (const value of valueToClone) {
            result.add(cloneDeepWithImpl(value, undefined, objectToClone, stack, cloneValue));
        }
        return result;
    }
    if (typeof Buffer !== 'undefined' && Buffer.isBuffer(valueToClone)) {
        return valueToClone.subarray();
    }
    if (isTypedArray(valueToClone)) {
        const result = new (Object.getPrototypeOf(valueToClone).constructor)(valueToClone.length);
        stack.set(valueToClone, result);
        for (let i = 0; i < valueToClone.length; i++) {
            result[i] = cloneDeepWithImpl(valueToClone[i], i, objectToClone, stack, cloneValue);
        }
        return result;
    }
    if (valueToClone instanceof ArrayBuffer ||
        (typeof SharedArrayBuffer !== 'undefined' && valueToClone instanceof SharedArrayBuffer)) {
        return valueToClone.slice(0);
    }
    if (valueToClone instanceof DataView) {
        const result = new DataView(valueToClone.buffer.slice(0), valueToClone.byteOffset, valueToClone.byteLength);
        stack.set(valueToClone, result);
        copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
        return result;
    }
    if (typeof File !== 'undefined' && valueToClone instanceof File) {
        const result = new File([valueToClone], valueToClone.name, {
            type: valueToClone.type,
        });
        stack.set(valueToClone, result);
        copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
        return result;
    }
    if (valueToClone instanceof Blob) {
        const result = new Blob([valueToClone], { type: valueToClone.type });
        stack.set(valueToClone, result);
        copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
        return result;
    }
    if (valueToClone instanceof Error) {
        const result = new valueToClone.constructor();
        stack.set(valueToClone, result);
        result.message = valueToClone.message;
        result.name = valueToClone.name;
        result.stack = valueToClone.stack;
        result.cause = valueToClone.cause;
        copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
        return result;
    }
    if (typeof valueToClone === 'object' && valueToClone !== null) {
        const result = Object.create(Object.getPrototypeOf(valueToClone));
        stack.set(valueToClone, result);
        copyProperties(result, valueToClone, objectToClone, stack, cloneValue);
        return result;
    }
    return valueToClone;
}
function copyProperties(target, source, objectToClone = target, stack, cloneValue) {
    const keys = [...Object.keys(source), ...getSymbols(source)];
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const descriptor = Object.getOwnPropertyDescriptor(target, key);
        if (descriptor == null || descriptor.writable) {
            target[key] = cloneDeepWithImpl(source[key], key, objectToClone, stack, cloneValue);
        }
    }
}

function cloneDeep(obj) {
    return cloneDeepWithImpl(obj, undefined, obj, new Map(), undefined);
}

function isPlainObject(value) {
    if (!value || typeof value !== 'object') {
        return false;
    }
    const proto = Object.getPrototypeOf(value);
    const hasObjectPrototype = proto === null ||
        proto === Object.prototype ||
        Object.getPrototypeOf(proto) === null;
    if (!hasObjectPrototype) {
        return false;
    }
    return Object.prototype.toString.call(value) === '[object Object]';
}

function mapValues(object, getNewValue) {
    const result = {};
    const keys = Object.keys(object);
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        const value = object[key];
        result[key] = getNewValue(value, key, object);
    }
    return result;
}

function merge(target, source) {
    const sourceKeys = Object.keys(source);
    for (let i = 0; i < sourceKeys.length; i++) {
        const key = sourceKeys[i];
        const sourceValue = source[key];
        const targetValue = target[key];
        if (Array.isArray(sourceValue)) {
            if (Array.isArray(targetValue)) {
                target[key] = merge(targetValue, sourceValue);
            }
            else {
                target[key] = merge([], sourceValue);
            }
        }
        else if (isPlainObject(sourceValue)) {
            if (isPlainObject(targetValue)) {
                target[key] = merge(targetValue, sourceValue);
            }
            else {
                target[key] = merge({}, sourceValue);
            }
        }
        else if (targetValue === undefined || sourceValue !== undefined) {
            target[key] = sourceValue;
        }
    }
    return target;
}

function omit(obj, keys) {
    const result = { ...obj };
    for (let i = 0; i < keys.length; i++) {
        const key = keys[i];
        delete result[key];
    }
    return result;
}

function toMerged(target, source) {
    return merge(cloneDeep(target), source);
}

function getTag(value) {
    if (value == null) {
        return value === undefined ? '[object Undefined]' : '[object Null]';
    }
    return Object.prototype.toString.call(value);
}

const regexpTag = '[object RegExp]';
const stringTag = '[object String]';
const numberTag = '[object Number]';
const booleanTag = '[object Boolean]';
const argumentsTag = '[object Arguments]';
const symbolTag = '[object Symbol]';
const dateTag = '[object Date]';
const mapTag = '[object Map]';
const setTag = '[object Set]';
const arrayTag = '[object Array]';
const functionTag = '[object Function]';
const arrayBufferTag = '[object ArrayBuffer]';
const objectTag = '[object Object]';
const errorTag = '[object Error]';
const dataViewTag = '[object DataView]';
const uint8ArrayTag = '[object Uint8Array]';
const uint8ClampedArrayTag = '[object Uint8ClampedArray]';
const uint16ArrayTag = '[object Uint16Array]';
const uint32ArrayTag = '[object Uint32Array]';
const bigUint64ArrayTag = '[object BigUint64Array]';
const int8ArrayTag = '[object Int8Array]';
const int16ArrayTag = '[object Int16Array]';
const int32ArrayTag = '[object Int32Array]';
const bigInt64ArrayTag = '[object BigInt64Array]';
const float32ArrayTag = '[object Float32Array]';
const float64ArrayTag = '[object Float64Array]';

function eq(value, other) {
    return value === other || (Number.isNaN(value) && Number.isNaN(other));
}

function isEqualWith(a, b, areValuesEqual) {
    return isEqualWithImpl(a, b, undefined, undefined, undefined, undefined, areValuesEqual);
}
function isEqualWithImpl(a, b, property, aParent, bParent, stack, areValuesEqual) {
    const result = areValuesEqual(a, b, property, aParent, bParent, stack);
    if (result !== undefined) {
        return result;
    }
    if (typeof a === typeof b) {
        switch (typeof a) {
            case 'bigint':
            case 'string':
            case 'boolean':
            case 'symbol':
            case 'undefined': {
                return a === b;
            }
            case 'number': {
                return a === b || Object.is(a, b);
            }
            case 'function': {
                return a === b;
            }
            case 'object': {
                return areObjectsEqual(a, b, stack, areValuesEqual);
            }
        }
    }
    return areObjectsEqual(a, b, stack, areValuesEqual);
}
function areObjectsEqual(a, b, stack, areValuesEqual) {
    if (Object.is(a, b)) {
        return true;
    }
    let aTag = getTag(a);
    let bTag = getTag(b);
    if (aTag === argumentsTag) {
        aTag = objectTag;
    }
    if (bTag === argumentsTag) {
        bTag = objectTag;
    }
    if (aTag !== bTag) {
        return false;
    }
    switch (aTag) {
        case stringTag:
            return a.toString() === b.toString();
        case numberTag: {
            const x = a.valueOf();
            const y = b.valueOf();
            return eq(x, y);
        }
        case booleanTag:
        case dateTag:
        case symbolTag:
            return Object.is(a.valueOf(), b.valueOf());
        case regexpTag: {
            return a.source === b.source && a.flags === b.flags;
        }
        case functionTag: {
            return a === b;
        }
    }
    stack = stack ?? new Map();
    const aStack = stack.get(a);
    const bStack = stack.get(b);
    if (aStack != null && bStack != null) {
        return aStack === b;
    }
    stack.set(a, b);
    stack.set(b, a);
    try {
        switch (aTag) {
            case mapTag: {
                if (a.size !== b.size) {
                    return false;
                }
                for (const [key, value] of a.entries()) {
                    if (!b.has(key) || !isEqualWithImpl(value, b.get(key), key, a, b, stack, areValuesEqual)) {
                        return false;
                    }
                }
                return true;
            }
            case setTag: {
                if (a.size !== b.size) {
                    return false;
                }
                const aValues = Array.from(a.values());
                const bValues = Array.from(b.values());
                for (let i = 0; i < aValues.length; i++) {
                    const aValue = aValues[i];
                    const index = bValues.findIndex(bValue => {
                        return isEqualWithImpl(aValue, bValue, undefined, a, b, stack, areValuesEqual);
                    });
                    if (index === -1) {
                        return false;
                    }
                    bValues.splice(index, 1);
                }
                return true;
            }
            case arrayTag:
            case uint8ArrayTag:
            case uint8ClampedArrayTag:
            case uint16ArrayTag:
            case uint32ArrayTag:
            case bigUint64ArrayTag:
            case int8ArrayTag:
            case int16ArrayTag:
            case int32ArrayTag:
            case bigInt64ArrayTag:
            case float32ArrayTag:
            case float64ArrayTag: {
                if (typeof Buffer !== 'undefined' && Buffer.isBuffer(a) !== Buffer.isBuffer(b)) {
                    return false;
                }
                if (a.length !== b.length) {
                    return false;
                }
                for (let i = 0; i < a.length; i++) {
                    if (!isEqualWithImpl(a[i], b[i], i, a, b, stack, areValuesEqual)) {
                        return false;
                    }
                }
                return true;
            }
            case arrayBufferTag: {
                if (a.byteLength !== b.byteLength) {
                    return false;
                }
                return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual);
            }
            case dataViewTag: {
                if (a.byteLength !== b.byteLength || a.byteOffset !== b.byteOffset) {
                    return false;
                }
                return areObjectsEqual(new Uint8Array(a), new Uint8Array(b), stack, areValuesEqual);
            }
            case errorTag: {
                return a.name === b.name && a.message === b.message;
            }
            case objectTag: {
                const areEqualInstances = areObjectsEqual(a.constructor, b.constructor, stack, areValuesEqual) ||
                    (isPlainObject(a) && isPlainObject(b));
                if (!areEqualInstances) {
                    return false;
                }
                const aKeys = [...Object.keys(a), ...getSymbols(a)];
                const bKeys = [...Object.keys(b), ...getSymbols(b)];
                if (aKeys.length !== bKeys.length) {
                    return false;
                }
                for (let i = 0; i < aKeys.length; i++) {
                    const propKey = aKeys[i];
                    const aProp = a[propKey];
                    if (!Object.hasOwn(b, propKey)) {
                        return false;
                    }
                    const bProp = b[propKey];
                    if (!isEqualWithImpl(aProp, bProp, propKey, a, b, stack, areValuesEqual)) {
                        return false;
                    }
                }
                return true;
            }
            default: {
                return false;
            }
        }
    }
    finally {
        stack.delete(a);
        stack.delete(b);
    }
}

function isEqual(a, b) {
    return isEqualWith(a, b, noop);
}

let random = bytes => crypto.getRandomValues(new Uint8Array(bytes));
let customRandom = (alphabet, defaultSize, getRandom) => {
  let mask = (2 << Math.log2(alphabet.length - 1)) - 1;
  let step = -~((1.6 * mask * defaultSize) / alphabet.length);
  return (size = defaultSize) => {
    let id = '';
    while (true) {
      let bytes = getRandom(step);
      let j = step | 0;
      while (j--) {
        id += alphabet[bytes[j] & mask] || '';
        if (id.length >= size) return id
      }
    }
  }
};
let customAlphabet = (alphabet, size = 21) =>
  customRandom(alphabet, size | 0, random);

const NUMBERS = '0123456789';
const LOWERCASE = 'abcdefghijklmnopqrstuvwxyz';
const UPPERCASE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
/**
 * Use custom ID generator for characters that be easily selected
 */
const customNanoid = customAlphabet(`${NUMBERS}${LOWERCASE}${UPPERCASE}_`, 12);
/**
 * Generate a random key string made up of numbers, lowercase, and uppercase letters
 * @returns A random key string
 */
function randomKey(length = 12) {
    return customNanoid(length);
}

const {z: z$2} = await importShared('zod');

/**
 * Regex for validating kebab case, e.g. "my-project".
 */
const KEBAB_CASE_REGEX = /^[a-z0-9-]+$/;
/**
 * Regex for validating pascal case, e.g. "MyProject".
 */
const PASCAL_CASE_REGEX = /^[A-Z][a-zA-Z0-9]*$/;
/**
 * Regex for validating camel case, e.g. "myProject".
 */
const CAMEL_CASE_REGEX = /^[a-z][a-zA-Z0-9]*$/;
/**
 * Regex for validating constant case, e.g. "MY_PROJECT".
 */
const CONSTANT_CASE_REGEX = /^[A-Z][A-Z0-9_]*$/;
const CASE_VALIDATORS = {
    /**
     * Zod validator for validating kebab case, e.g. "my-project".
     */
    KEBAB_CASE: z$2.string().regex(KEBAB_CASE_REGEX, {
        message: 'Must be kebab case (e.g. "my-project")',
    }),
    /**
     * Zod validator for validating pascal case, e.g. "MyProject".
     */
    PASCAL_CASE: z$2.string().regex(PASCAL_CASE_REGEX, {
        message: 'Must be pascal case (e.g. "MyProject")',
    }),
    /**
     * Zod validator for validating camel case, e.g. "myProject".
     */
    CAMEL_CASE: z$2.string().regex(CAMEL_CASE_REGEX, {
        message: 'Must be camel case (e.g. "myProject")',
    }),
    /**
     * Zod validator for validating constant case, e.g. "MY_PROJECT".
     */
    CONSTANT_CASE: z$2.string().regex(CONSTANT_CASE_REGEX, {
        message: 'Must be constant case (e.g. "MY_PROJECT")',
    }),
};

/**
 * Definition of an entity type.
 */
class DefinitionEntityType {
    prefix;
    name;
    parentType;
    /**
     * Creates a new entity type.
     *
     * @param name - The name of the entity type.
     * @param prefix - The prefix of the entity type to use in the ID, defaults to the name.
     * @param parentType - The type of the parent entity if any
     */
    constructor(name, prefix, parentType) {
        this.name = name;
        this.parentType = parentType;
        this.prefix = prefix ?? name.split('/').pop() ?? name;
    }
    /**
     * Generates a new ID for the entity type.
     *
     * @returns The new ID.
     */
    generateNewId() {
        return `${this.prefix}:${randomKey()}`;
    }
    idFromKey(key) {
        if (!key) {
            return undefined;
        }
        return `${this.prefix}:${key}`;
    }
    keyFromId(id) {
        return id.split(':')[1];
    }
    isId(id) {
        return id.startsWith(`${this.prefix}:`);
    }
}
function createEntityType(name, options) {
    const { parentType, prefix } = options ?? {};
    return new DefinitionEntityType(name, prefix, parentType);
}

function isDeepKey(key) {
    switch (typeof key) {
        case 'number':
        case 'symbol': {
            return false;
        }
        case 'string': {
            return key.includes('.') || key.includes('[') || key.includes(']');
        }
    }
}

function toKey(value) {
    if (Object.is(value, -0)) {
        return '-0';
    }
    return value.toString();
}

function toPath(deepKey) {
    const result = [];
    const length = deepKey.length;
    if (length === 0) {
        return result;
    }
    let index = 0;
    let key = '';
    let quoteChar = '';
    let bracket = false;
    if (deepKey.charCodeAt(0) === 46) {
        result.push('');
        index++;
    }
    while (index < length) {
        const char = deepKey[index];
        if (quoteChar) {
            if (char === '\\' && index + 1 < length) {
                index++;
                key += deepKey[index];
            }
            else if (char === quoteChar) {
                quoteChar = '';
            }
            else {
                key += char;
            }
        }
        else if (bracket) {
            if (char === '"' || char === "'") {
                quoteChar = char;
            }
            else if (char === ']') {
                bracket = false;
                result.push(key);
                key = '';
            }
            else {
                key += char;
            }
        }
        else {
            if (char === '[') {
                bracket = true;
                if (key) {
                    result.push(key);
                    key = '';
                }
            }
            else if (char === '.') {
                if (key) {
                    result.push(key);
                    key = '';
                }
            }
            else {
                key += char;
            }
        }
        index++;
    }
    if (key) {
        result.push(key);
    }
    return result;
}

function get(object, path, defaultValue) {
    if (object == null) {
        return defaultValue;
    }
    switch (typeof path) {
        case 'string': {
            const result = object[path];
            if (result === undefined) {
                if (isDeepKey(path)) {
                    return get(object, toPath(path), defaultValue);
                }
                else {
                    return defaultValue;
                }
            }
            return result;
        }
        case 'number':
        case 'symbol': {
            if (typeof path === 'number') {
                path = toKey(path);
            }
            const result = object[path];
            if (result === undefined) {
                return defaultValue;
            }
            return result;
        }
        default: {
            if (Array.isArray(path)) {
                return getWithPath(object, path, defaultValue);
            }
            if (Object.is(path?.valueOf(), -0)) {
                path = '-0';
            }
            else {
                path = String(path);
            }
            const result = object[path];
            if (result === undefined) {
                return defaultValue;
            }
            return result;
        }
    }
}
function getWithPath(object, path, defaultValue) {
    if (path.length === 0) {
        return defaultValue;
    }
    let current = object;
    for (let index = 0; index < path.length; index++) {
        if (current == null) {
            return defaultValue;
        }
        current = current[path[index]];
    }
    if (current === undefined) {
        return defaultValue;
    }
    return current;
}

function isObject(value) {
    return value !== null && (typeof value === 'object' || typeof value === 'function');
}

function isMatch(target, source) {
    if (source === target) {
        return true;
    }
    switch (typeof source) {
        case 'object': {
            if (source == null) {
                return true;
            }
            const keys = Object.keys(source);
            if (target == null) {
                return keys.length === 0;
            }
            if (Array.isArray(source)) {
                return isArrayMatch(target, source);
            }
            if (source instanceof Map) {
                return isMapMatch(target, source);
            }
            if (source instanceof Set) {
                return isSetMatch(target, source);
            }
            for (let i = 0; i < keys.length; i++) {
                const key = keys[i];
                if (!isPrimitive(target) && !(key in target)) {
                    return false;
                }
                if (source[key] === undefined && target[key] !== undefined) {
                    return false;
                }
                if (source[key] === null && target[key] !== null) {
                    return false;
                }
                if (!isMatch(target[key], source[key])) {
                    return false;
                }
            }
            return true;
        }
        case 'function': {
            if (Object.keys(source).length > 0) {
                return isMatch(target, { ...source });
            }
            return false;
        }
        default: {
            if (!isObject(target)) {
                return eq(target, source);
            }
            return !source;
        }
    }
}
function isMapMatch(target, source) {
    if (source.size === 0) {
        return true;
    }
    if (!(target instanceof Map)) {
        return false;
    }
    for (const [key, value] of source.entries()) {
        if (!isMatch(target.get(key), value)) {
            return false;
        }
    }
    return true;
}
function isArrayMatch(target, source) {
    if (source.length === 0) {
        return true;
    }
    if (!Array.isArray(target)) {
        return false;
    }
    const countedIndex = new Set();
    for (let i = 0; i < source.length; i++) {
        const sourceItem = source[i];
        const index = target.findIndex((targetItem, index) => {
            return isMatch(targetItem, sourceItem) && !countedIndex.has(index);
        });
        if (index === -1) {
            return false;
        }
        countedIndex.add(index);
    }
    return true;
}
function isSetMatch(target, source) {
    if (source.size === 0) {
        return true;
    }
    if (!(target instanceof Set)) {
        return false;
    }
    return isArrayMatch([...target], [...source]);
}

const IS_UNSIGNED_INTEGER = /^(?:0|[1-9]\d*)$/;
function isIndex(value, length = Number.MAX_SAFE_INTEGER) {
    switch (typeof value) {
        case 'number': {
            return Number.isInteger(value) && value >= 0 && value < length;
        }
        case 'symbol': {
            return false;
        }
        case 'string': {
            return IS_UNSIGNED_INTEGER.test(value);
        }
    }
}

function set(obj, path, value) {
    const resolvedPath = Array.isArray(path) ? path : typeof path === 'string' ? toPath(path) : [path];
    let current = obj;
    for (let i = 0; i < resolvedPath.length - 1; i++) {
        const key = resolvedPath[i];
        const nextKey = resolvedPath[i + 1];
        if (current[key] == null) {
            current[key] = isIndex(nextKey) ? [] : {};
        }
        current = current[key];
    }
    const lastKey = resolvedPath[resolvedPath.length - 1];
    current[lastKey] = value;
    return obj;
}

class DefinitionReferenceMarker {
    value;
    reference;
    constructor(value, reference) {
        this.value = value;
        this.reference = reference;
    }
    toString() {
        return this.value ?? '';
    }
}
const REF_ANNOTATIONS_MARKER_SYMBOL = Symbol('refAnnotationsMarker');

/**
 * Creates a new ref context slot for the given entity type.
 * Each call creates a unique slot, even for the same entity type.
 *
 * @param name - A descriptive name for debugging (shows in Symbol description)
 * @param entityType - The entity type this slot will be associated with
 * @returns A new unique RefContextSlot instance
 *
 * @example
 * ```typescript
 * const modelSlot = createRefContextSlot('modelSlot', modelEntityType);
 * const anotherModelSlot = createRefContextSlot('anotherModelSlot', modelEntityType);
 *
 * // These are different slots despite same entity type
 * modelSlot.id !== anotherModelSlot.id
 * // modelSlot.id.toString() === 'Symbol(modelSlot)'
 * ```
 */
function createRefContextSlot(name, entityType) {
    return {
        entityType,
        id: Symbol(name),
    };
}
/**
 * Creates a RefContextSlotMap from a slot definition.
 * Used internally by ctx.refContext().
 *
 * @param slotDefinition - Map of slot names to entity types
 * @returns Map of slot names to RefContextSlot instances
 */
function createRefContextSlotMap(slotDefinition) {
    return Object.fromEntries(Object.entries(slotDefinition).map(([key, entityType]) => [
        key,
        createRefContextSlot(key, entityType),
    ]));
}

/**
 * Strips the DefinitionReferenceMarker from the value recursively.
 * @param value - The value to strip the DefinitionReferenceMarker from.
 * @returns The value without the DefinitionReferenceMarker.
 */
function stripRefMarkers(value) {
    if (value instanceof DefinitionReferenceMarker) {
        return value.value;
    }
    if (Array.isArray(value)) {
        return value.map(stripRefMarkers);
    }
    if (typeof value === 'object' && value !== null) {
        return Object.fromEntries(Object.entries(value).map(([key, childValue]) => [
            key,
            stripRefMarkers(childValue),
        ]));
    }
    return value;
}

const {z: z$1} = await importShared('zod');
function extendParserContextWithRefs({ transformReferences, }) {
    function modifyAnnotations(value, ctx, modifier) {
        if (value === null || value === undefined)
            return value;
        if (typeof value !== 'object') {
            ctx.addIssue({
                code: 'invalid_type',
                expected: 'object',
                message: `Entity must be an object`,
                input: value,
            });
            return value;
        }
        if (transformReferences) {
            const existingAnnotations = REF_ANNOTATIONS_MARKER_SYMBOL in value
                ? value[REF_ANNOTATIONS_MARKER_SYMBOL]
                : { entities: [], references: [], slots: [] };
            return {
                ...value,
                [REF_ANNOTATIONS_MARKER_SYMBOL]: modifier(existingAnnotations),
            };
        }
        return value;
    }
    function withRef(reference) {
        return z$1.string().transform((value) => {
            if (transformReferences && value) {
                return new DefinitionReferenceMarker(value, {
                    path: [],
                    type: reference.type,
                    onDelete: reference.onDelete,
                    parentSlot: reference.parentSlot,
                    provides: reference.provides,
                });
            }
            return value;
        });
    }
    function withEnt(schema, entity) {
        return schema.transform((value, ctx) => {
            if (value === null || value === undefined)
                return value;
            if (transformReferences) {
                if (typeof value !== 'object') {
                    ctx.addIssue({
                        code: 'invalid_type',
                        expected: 'object',
                        message: `Entity must be an object`,
                        input: value,
                    });
                    return value;
                }
                // Check if the id is valid
                const idPath = entity.idPath ?? ['id'];
                const id = get(value, idPath);
                if (typeof id !== 'string' || !id || !entity.type.isId(id)) {
                    ctx.addIssue({
                        code: 'custom',
                        message: `Unable to find string id field '${entity.idPath?.join('.') ?? 'id'}' in entity ${entity.type.name}`,
                        input: value,
                    });
                    return value;
                }
                const nameResolver = (() => {
                    if (entity.getNameResolver) {
                        return entity.getNameResolver(stripRefMarkers(value));
                    }
                    if (!('name' in value) || typeof value.name !== 'string') {
                        ctx.addIssue({
                            code: 'custom',
                            message: `Unable to find string name field in entity ${entity.type.name}`,
                            input: value,
                        });
                        return 'invalid';
                    }
                    return value.name;
                })();
                const newEntity = {
                    id,
                    idPath,
                    path: [],
                    type: entity.type,
                    nameResolver,
                    parentSlot: entity.parentSlot,
                    provides: entity.provides,
                };
                return modifyAnnotations(value, ctx, (annotations) => ({
                    ...annotations,
                    entities: [...annotations.entities, newEntity],
                }));
            }
            return value;
        });
    }
    /**
     * Creates ref context slots for use within a schema definition.
     * Slots provide type-safe context for parent-child entity relationships.
     *
     * @example
     * ```typescript
     * ctx.refContext(
     *   { modelSlot: modelEntityType },
     *   ({ modelSlot }) =>
     *     ctx.withEnt(schema, {
     *       type: modelEntityType,
     *       provides: modelSlot,
     *     }),
     * );
     * ```
     */
    function refContext(slotDefinition, schemaBuilder) {
        const slots = createRefContextSlotMap(slotDefinition);
        return schemaBuilder(slots).transform((value, ctx) => modifyAnnotations(value, ctx, (annotations) => ({
            ...annotations,
            slots: [
                ...annotations.slots,
                ...Object.values(slots).map((slot) => ({
                    path: [],
                    slot,
                })),
            ],
        })));
    }
    return {
        withRef,
        withEnt,
        refContext,
    };
}

function isEmpty(value) {
    if (value === undefined || value === null) {
        return true;
    }
    if (Array.isArray(value)) {
        return value.length === 0;
    }
    if (typeof value === 'object' &&
        Object.getPrototypeOf(value) === Object.prototype) {
        return Object.values(value).every((val) => val === undefined);
    }
    if (typeof value === 'string') {
        return value === '';
    }
    return false;
}
/**
 * Extends the parser context with default value handling functionality.
 *
 * @param options - The schema creator options containing the defaultMode
 * @returns An object containing the withDefault method
 */
function extendParserContextWithDefaults(options) {
    const mode = options.defaultMode ?? 'populate';
    return {
        withDefault: function withDefault(schema, defaultValue) {
            switch (mode) {
                case 'populate': {
                    return schema.prefault(defaultValue).optional();
                }
                case 'strip': {
                    // Use transform to remove values matching defaults after validation
                    return schema
                        .transform((value) => {
                        if (value === defaultValue)
                            return undefined;
                        if (isEmpty(value)) {
                            return undefined;
                        }
                        return value;
                    })
                        .optional();
                }
                case 'preserve': {
                    // Return schema with .optional() added
                    return schema.transform((x) => x).optional();
                }
            }
        },
    };
}

function createDefinitionSchemaParserContext(options) {
    return {
        ...options,
        ...extendParserContextWithRefs(options),
        ...extendParserContextWithDefaults(options),
    };
}
function definitionSchema(creator) {
    return (context) => creator(context);
}
/**
 * Creates a schema that requires slots to be passed from parent schemas.
 * Used when a schema needs to reference entities from a parent context.
 *
 * @example
 * ```typescript
 * // Child schema requiring modelSlot from parent
 * export const createModelScalarFieldSchema = definitionSchemaWithSlots(
 *   { modelSlot: modelEntityType },
 *   (ctx, { modelSlot }) =>
 *     ctx.withEnt(schema, {
 *       type: modelScalarFieldEntityType,
 *       parentSlot: modelSlot,
 *     }),
 * );
 *
 * // Called from parent:
 * createModelScalarFieldSchema(ctx, { modelSlot: parentModelSlot })
 * ```
 */
function definitionSchemaWithSlots(slotDefinition, creator) {
    const creatorWithSlots = (context, slots) => creator(context, slots);
    creatorWithSlots.slotDefinition = slotDefinition;
    return creatorWithSlots;
}
/**
 * Wraps a schema creator that requires slots with placeholder slots,
 * producing a simple schema creator that can be used for validation-only
 * contexts (e.g., React Hook Form).
 *
 * The placeholder slots allow the schema to parse without actual parent context,
 * which is useful when you only need schema validation without ref extraction.
 *
 * @example
 * ```typescript
 * // Schema that normally requires modelSlot from parent
 * const createModelScalarFieldSchema = definitionSchemaWithSlots(
 *   { modelSlot: modelEntityType },
 *   (ctx, { modelSlot }) => ctx.withEnt(schema, { parentSlot: modelSlot }),
 * );
 *
 * // For React Hook Form validation, wrap with placeholder slots
 * const fieldSchema = withPlaceholderSlots(createModelScalarFieldSchema);
 * const zodSchema = fieldSchema(ctx); // No slots needed
 * ```
 */
function withPlaceholderSlots(schemaCreator) {
    return (ctx) => {
        const placeholderSlots = createRefContextSlotMap(schemaCreator.slotDefinition);
        return schemaCreator(ctx, placeholderSlots);
    };
}

const {z} = await importShared('zod');
const featureEntityType = createEntityType('feature');
const featureNameSchema = CASE_VALIDATORS.KEBAB_CASE;
const createFeatureSchema = definitionSchema((ctx) => ctx.withEnt(z.object({
    id: z.string(),
    name: z
        .string()
        .min(1)
        .refine((name) => name
        .split('/')
        .every((part) => featureNameSchema.safeParse(part).success), {
        message: 'Feature name must be lowercase and contain only letters, numbers, and dashes',
    }),
    parentRef: ctx
        .withRef({
        type: featureEntityType,
        onDelete: 'DELETE_PARENT',
    })
        .optional(),
}), { type: featureEntityType }));
const createFeaturesSchema = definitionSchema((ctx) => z.array(createFeatureSchema(ctx)).default([]));

const modelEntityType = createEntityType('model');
const modelScalarFieldEntityType = createEntityType('model-scalar-field', {
    parentType: modelEntityType,
});
const modelLocalRelationEntityType = createEntityType('model-local-relation', { parentType: modelEntityType });
const modelForeignRelationEntityType = createEntityType('model-foreign-relation', { parentType: modelEntityType });
const modelUniqueConstraintEntityType = createEntityType('model-unique-constraint', { parentType: modelEntityType });
const modelTransformerEntityType = createEntityType('model-transformer', { parentType: modelEntityType });
const modelEnumEntityType = createEntityType('model-enum');
const modelEnumValueEntityType = createEntityType('model-enum-value', {
    parentType: modelEnumEntityType,
});

function getRootFeatures(projectDefinition) {
    return projectDefinition.features.filter((f) => !f.parentRef);
}
function getFeatureById(projectDefinition, featureId) {
    return projectDefinition.features.find((f) => f.id === featureId);
}
function getFeatureByIdOrThrow(projectDefinition, featureId) {
    const feature = getFeatureById(projectDefinition, featureId);
    if (!feature) {
        throw new Error(`Could not find feature with ID ${featureId}`);
    }
    return feature;
}
function getFeatureChildren(projectDefinition, featureId) {
    return projectDefinition.features.filter((f) => f.parentRef === featureId);
}
function getFeatureName(featureConfig) {
    return featureConfig.name.split('/').pop() ?? '';
}
function getFeatureNameById(projectDefinition, featureId) {
    const feature = getFeatureByIdOrThrow(projectDefinition, featureId);
    return getFeatureName(feature);
}
function getFeaturePathById(projectDefinition, featureId) {
    const feature = getFeatureByIdOrThrow(projectDefinition, featureId);
    return feature.name;
}
function validateFeatureName(name) {
    const nameParts = name.split('/');
    return nameParts.every((part) => featureNameSchema.safeParse(part).success);
}
function ensureFeatureByNameRecursively(projectDefinition, nameOrId) {
    if (featureEntityType.isId(nameOrId)) {
        return nameOrId;
    }
    const nameParts = nameOrId.split('/');
    let lastName = '';
    let parentRef = undefined;
    for (const part of nameParts) {
        const feature = projectDefinition.features.find((f) => f.name === part && f.parentRef === parentRef);
        const name = [lastName, part].filter(Boolean).join('/');
        if (feature) {
            parentRef = feature.id;
        }
        else {
            const newFeature = {
                id: featureEntityType.generateNewId(),
                name,
                parentRef,
            };
            projectDefinition.features.push(newFeature);
            parentRef = newFeature.id;
        }
        lastName = name;
    }
    if (!parentRef) {
        throw new Error('Failed to create feature');
    }
    return parentRef;
}
function getFeatureByName(projectDefinition, name) {
    return projectDefinition.features.find((f) => f.name === name);
}
function getFeatureIdByNameOrDefault(projectDefinition, name) {
    return getFeatureByName(projectDefinition, name)?.id ?? name;
}
const FeatureUtils = {
    getRootFeatures,
    getFeatureById,
    getFeatureByIdOrThrow,
    getFeatureChildren,
    getFeatureName,
    getFeatureNameById,
    getFeaturePathById,
    validateFeatureName,
    ensureFeatureByNameRecursively,
    getFeatureByName,
    getFeatureIdByNameOrDefault,
};

function byId(projectDefinition, id) {
    return projectDefinition.models.find((m) => m.id === id);
}
function byIdOrThrow(projectDefinition, id) {
    const model = byId(projectDefinition, id);
    if (!model) {
        throw new Error(`Could not find model with ID ${id}`);
    }
    return model;
}
function byName(projectDefinition, name) {
    return projectDefinition.models.find((m) => m.name === name);
}
function byNameOrThrow(projectDefinition, name) {
    const model = byName(projectDefinition, name);
    if (!model) {
        throw new Error(`Could not find model with name ${name}`);
    }
    return model;
}
function getScalarFieldById(model, id) {
    const field = model.model.fields.find((f) => f.id === id);
    if (!field) {
        throw new Error(`Could not find field with ID ${id}`);
    }
    return field;
}
function getRelationsToModel(projectDefinition, modelId) {
    return projectDefinition.models.flatMap((m) => m.model.relations
        ?.filter((r) => r.modelRef === modelId)
        .map((r) => ({ model: m, relation: r })) ?? []);
}
function getModelsForFeature(projectDefinition, featureId) {
    return projectDefinition.models.filter((m) => m.featureRef === featureId);
}
function getModelIdFields(model) {
    return model.model.primaryKeyFieldRefs;
}
function hasService(model) {
    return (!!model.service.create.enabled ||
        !!model.service.update.enabled ||
        !!model.service.delete.enabled ||
        model.service.transformers.length > 0);
}
function validateModelName(name) {
    return PASCAL_CASE_REGEX.test(name);
}
/**
 * Returns the ID of a model by name, or the name if no model is found.
 * @param projectDefinition - The project definition.
 * @param name - The name of the model.
 * @returns The ID of the model, or the name if no model is found.
 */
function getModelIdByNameOrDefault(projectDefinition, name) {
    return projectDefinition.models.find((m) => m.name === name)?.id ?? name;
}
const ModelUtils = {
    byId,
    byIdOrThrow,
    byName,
    byNameOrThrow,
    getScalarFieldById,
    getRelationsToModel,
    getModelsForFeature,
    getModelIdFields,
    hasService,
    validateModelName,
    getModelIdByNameOrDefault,
};

/**
 * Allows diffing of arbitrary JSON objects.
 */
class DefinitionDiffField {
    /**
     * The name of the field to be presented to the user.
     */
    name;
    constructor(name) {
        this.name = name;
    }
}
/**
 * A field that is an array of objects with a unique key.
 */
class DefinitionDiffKeyedArrayField extends DefinitionDiffField {
    getKey;
    options;
    constructor(name, getKey, options = {}) {
        super(name);
        this.getKey = getKey;
        this.options = options;
    }
    diff(current, desired) {
        const currentValue = current ?? [];
        const desiredValue = desired ?? [];
        if (!Array.isArray(currentValue) || !Array.isArray(desiredValue)) {
            throw new TypeError('Current and desired must be arrays');
        }
        const ops = [];
        const { allowRemove, ignoreFields = ['id'] } = this.options;
        const currentByKey = new Map(currentValue.map((item) => [this.getKey(item), item]));
        const desiredByKey = new Map(desiredValue.map((item) => [this.getKey(item), item]));
        for (const [key, desiredItem] of desiredByKey) {
            const currentItem = currentByKey.get(key);
            if (!currentItem) {
                ops.push({ type: 'add', key, item: desiredItem });
                continue;
            }
            if (!isMatch(omit(currentItem, ignoreFields), omit(desiredItem, ignoreFields))) {
                ops.push({ type: 'update', key, item: desiredItem });
            }
        }
        if (allowRemove) {
            for (const [key, currentItem] of currentByKey) {
                if (!desiredByKey.has(key)) {
                    ops.push({ type: 'remove', key, item: currentItem });
                }
            }
        }
        return ops;
    }
    apply(current, diff) {
        const patch = diff;
        const currentValue = current ?? [];
        if (!Array.isArray(currentValue)) {
            throw new TypeError('Current must be array');
        }
        const items = [...currentValue];
        for (const { type, key, item } of patch) {
            const index = items.findIndex((i) => this.getKey(i) === key);
            switch (type) {
                case 'add': {
                    items.push(item);
                    break;
                }
                case 'update': {
                    if (index === -1) {
                        throw new Error(`Cannot apply patch. Item with key "${key}" not found.`);
                    }
                    // Preserve existing id if present.
                    items[index] = toMerged(items[index], item);
                    break;
                }
                case 'remove': {
                    if (index !== -1) {
                        items.splice(index, 1);
                    }
                    break;
                }
            }
        }
        return items;
    }
    getActionVerb(isNew) {
        return isNew ? 'created' : 'added or updated';
    }
}
/**
 * A field that is a replacement for the entire object or array.
 */
class DefinitionDiffReplacementField extends DefinitionDiffField {
    diff(current, desired) {
        if (desired === undefined) {
            return [];
        }
        if (!isMatch(current, desired)) {
            return [{ type: 'update', key: '*', item: desired }];
        }
        return [];
    }
    apply(current, diff) {
        if (diff.length === 0)
            return current;
        return diff[0].item;
    }
    getActionVerb(isNew) {
        return isNew ? 'set' : 'replaced';
    }
}
/**
 * A field that ensures an array contains certain values.
 * This field type only adds items, never removes them.
 */
class DefinitionDiffArrayIncludesField extends DefinitionDiffField {
    getKey;
    constructor(name, getKey) {
        super(name);
        this.getKey = getKey;
    }
    diff(current, desired) {
        const currentValue = current ?? [];
        const desiredValue = desired ?? [];
        if (!Array.isArray(currentValue) || !Array.isArray(desiredValue)) {
            throw new TypeError('Current and desired must be arrays');
        }
        const ops = [];
        const currentSet = new Set(this.getKey ? currentValue.map(this.getKey) : currentValue);
        for (const item of desiredValue) {
            const key = this.getKey ? this.getKey(item) : String(item);
            if (!currentSet.has(key)) {
                ops.push({ type: 'add', key, item });
            }
        }
        return ops;
    }
    apply(current, diff) {
        const currentValue = (current ?? []);
        if (!Array.isArray(currentValue)) {
            throw new TypeError('Current must be array');
        }
        const items = [...currentValue];
        for (const { type, item } of diff) {
            if (type === 'add') {
                items.push(item);
            }
        }
        return items;
    }
    getActionVerb(isNew) {
        return isNew ? 'created' : 'added';
    }
}
function createDefinitionDiffConfig(config) {
    return config;
}
/**
 * Creates a diff between two objects.
 */
function createDefinitionDiff(current, desired, configuration) {
    const ops = mapValues(configuration, (field, key) => {
        if (!field)
            return [];
        return field.diff(get(current, key), get(desired, key));
    });
    if (Object.values(ops).every((ops) => ops.length === 0)) {
        return undefined;
    }
    return ops;
}
/**
 * Applies a diff to an object.
 */
function applyDefinitionDiff(current, diff, configuration) {
    const clonedCurrent = cloneDeep(current);
    for (const [key, ops] of Object.entries(diff)) {
        if (!ops)
            continue;
        const field = configuration[key];
        const currentValue = get(clonedCurrent, key);
        set(clonedCurrent, key, field.apply(currentValue, ops));
    }
    return clonedCurrent;
}

/**
 * Computes a unique key for a unique constraint by sorting its field refs.
 *
 * @param constraint - Unique constraint input.
 * @returns A key string.
 */
function getUniqueConstraintKey(constraint) {
    const fields = constraint.fields.map((f) => f.fieldRef).sort();
    return fields.join('|');
}
const modelMergerDefinitionDiffConfig = createDefinitionDiffConfig({
    'model.fields': new DefinitionDiffKeyedArrayField('fields', (f) => f.name),
    'model.relations': new DefinitionDiffKeyedArrayField('relations', (r) => r.name),
    'model.uniqueConstraints': new DefinitionDiffKeyedArrayField('unique constraints', (c) => getUniqueConstraintKey(c)),
    'model.primaryKeyFieldRefs': new DefinitionDiffReplacementField('primary key fields'),
    'graphql.objectType.enabled': new DefinitionDiffReplacementField('GraphQL object type enabled'),
    'graphql.objectType.fields': new DefinitionDiffArrayIncludesField('GraphQL object type fields'),
    'graphql.objectType.localRelations': new DefinitionDiffArrayIncludesField('GraphQL object type local relations'),
    'graphql.objectType.foreignRelations': new DefinitionDiffArrayIncludesField('GraphQL object type foreign relations'),
});
/**
 * Serializes a model merger model input such that all IDs are replaced with
 * names.
 *
 * @param input - The model merger model input.
 * @param definitionContainer - The definition container.
 * @returns The serialized model merger model input.
 */
function serializeModelMergerModelInput(input, definitionContainer, siblingModels) {
    const siblingModelIds = new Map(siblingModels.map((m) => [m.id, m.name]));
    const siblingModelFieldIdMap = new Map([
        ...input.model.fields.map((f) => [f.id, f.name]),
        ...siblingModels.flatMap((m) => m.model.fields.map((f) => [f.id, f.name])),
    ]);
    const siblingModelRelationIdMap = new Map([
        ...(input.model.relations ?? []).map((r) => [r.id, r.name]),
        ...siblingModels.flatMap((m) => (m.model.relations ?? []).map((r) => [r.id, r.name])),
        ...(input.model.relations ?? []).map((r) => [r.foreignId, r.foreignRelationName]),
        ...siblingModels.flatMap((m) => (m.model.relations ?? []).map((r) => [r.foreignId, r.foreignRelationName])),
    ]);
    const modelFromId = (id) => siblingModelIds.get(id) ?? definitionContainer.nameFromId(id);
    const fieldNameFromId = (id) => siblingModelFieldIdMap.get(id) ?? definitionContainer.nameFromId(id);
    const relationNameFromId = (id) => siblingModelRelationIdMap.get(id) ?? definitionContainer.nameFromId(id);
    return {
        ...input,
        model: {
            ...input.model,
            relations: input.model.relations?.map((r) => ({
                ...r,
                modelRef: modelFromId(r.modelRef),
                references: r.references.map((reference) => ({
                    ...reference,
                    localRef: fieldNameFromId(reference.localRef),
                    foreignRef: fieldNameFromId(reference.foreignRef),
                })),
            })),
            uniqueConstraints: input.model.uniqueConstraints?.map((c) => ({
                ...c,
                fields: c.fields.map((f) => ({
                    ...f,
                    fieldRef: fieldNameFromId(f.fieldRef),
                })),
            })),
            primaryKeyFieldRefs: input.model.primaryKeyFieldRefs.map(fieldNameFromId),
        },
        graphql: {
            ...input.graphql,
            objectType: {
                ...input.graphql?.objectType,
                fields: input.graphql?.objectType?.fields?.map(fieldNameFromId) ?? [],
                localRelations: input.graphql?.objectType?.localRelations?.map(relationNameFromId) ??
                    [],
                foreignRelations: input.graphql?.objectType?.foreignRelations?.map(relationNameFromId) ?? [],
            },
        },
    };
}
/**
 * Attaches IDs to the model merger model input.
 *
 * @param input - The model merger model input.
 * @returns The model merger model input with IDs attached.
 */
function attachIdsToModelMergerModelInput(input) {
    return {
        ...input,
        model: {
            ...input.model,
            fields: input.model.fields.map((f) => ({
                ...f,
                id: f.id ?? modelScalarFieldEntityType.generateNewId(),
            })),
            relations: input.model.relations?.map((r) => ({
                ...r,
                id: r.id ?? modelLocalRelationEntityType.generateNewId(),
                foreignId: r.foreignId ?? modelForeignRelationEntityType.generateNewId(),
            })),
            uniqueConstraints: input.model.uniqueConstraints?.map((c) => ({
                ...c,
                id: c.id ?? modelUniqueConstraintEntityType.generateNewId(),
            })),
        },
    };
}
/**
 * Deserializes a model merger model input converting all names to IDs.
 *
 * @param input - The model merger model input.
 * @param resolveForeignFieldRef - A function that resolves the foreign field ref.
 * @returns The deserialized model merger model input.
 */
function deserializeModelMergerModelInput(input, resolveForeignFieldRef, resolveForeignRelationRef, resolveModelRef) {
    const inputWithIds = attachIdsToModelMergerModelInput(input);
    const resolveLocalFieldName = (name) => {
        const field = inputWithIds.model.fields.find((f) => f.name === name);
        if (!field) {
            throw new Error(`Field ${name} not found`);
        }
        return field.id;
    };
    const resolveLocalRelationName = (name) => {
        const relation = inputWithIds.model.relations?.find((r) => r.name === name);
        if (!relation) {
            throw new Error(`Relation ${name} not found`);
        }
        return relation.id;
    };
    return {
        ...inputWithIds,
        model: {
            ...inputWithIds.model,
            relations: inputWithIds.model.relations?.map((relation) => ({
                ...relation,
                modelRef: resolveModelRef(relation.modelRef),
                references: relation.references.map((reference) => ({
                    ...reference,
                    localRef: resolveLocalFieldName(reference.localRef),
                    foreignRef: resolveForeignFieldRef(relation.modelRef, reference.foreignRef),
                })),
            })),
            uniqueConstraints: inputWithIds.model.uniqueConstraints?.map((constraint) => ({
                ...constraint,
                fields: constraint.fields.map((field) => ({
                    ...field,
                    fieldRef: resolveLocalFieldName(field.fieldRef),
                })),
            })),
            primaryKeyFieldRefs: inputWithIds.model.primaryKeyFieldRefs.map((fieldRef) => resolveLocalFieldName(fieldRef)),
        },
        graphql: {
            ...inputWithIds.graphql,
            objectType: {
                ...inputWithIds.graphql?.objectType,
                fields: inputWithIds.graphql?.objectType?.fields?.map((fieldRef) => resolveLocalFieldName(fieldRef)) ?? [],
                localRelations: inputWithIds.graphql?.objectType?.localRelations?.map((relationRef) => resolveLocalRelationName(relationRef)) ?? [],
                foreignRelations: inputWithIds.graphql?.objectType?.foreignRelations?.map((relationRef) => resolveForeignRelationRef(relationRef)) ?? [],
            },
        },
    };
}
/**
 * Creates a new blank model config input from a name and feature ref.
 *
 * @param name - The name of the model.
 * @param featureRef - The feature ref of the model.
 * @returns The new model config input.
 */
function createNewModelConfigInput(name, featureRef, id) {
    return {
        id,
        name,
        featureRef,
        model: {
            fields: [],
            primaryKeyFieldRefs: [],
        },
    };
}
/**
 * Diff the model definition.
 *
 * @param current - The current model definition or a new model to be created.
 * @param desired - The desired model definition.
 * @param definitionContainer - Project definition container.
 * @param options - Diff options.
 * @returns A diff output or undefined if there are no differences.
 */
function createModelMergerResult(current, desired, definitionContainer, { siblingModels = [] } = {}) {
    const currentModel = current ??
        createNewModelConfigInput(desired.name, desired.featureRef, modelEntityType.generateNewId());
    // resolves all the names of the current model config input
    const resolvedCurrent = serializeModelMergerModelInput(currentModel, definitionContainer, siblingModels);
    const diff = createDefinitionDiff(resolvedCurrent, desired, modelMergerDefinitionDiffConfig);
    if (!diff) {
        return undefined;
    }
    return {
        isNewModel: !current,
        id: currentModel.id,
        name: currentModel.name,
        featureRef: currentModel.featureRef,
        changes: diff,
    };
}
function doesModelMergerResultsHaveChanges(results) {
    return Object.values(results).some((result) => result?.changes);
}
/**
 * Creates a model merger result for a set of models.
 *
 * @param current - A map of model IDs
 * @param desired - The desired model definition.
 * @param definitionContainer - Project definition container.
 * @param options - Diff options.
 * @returns A model merger result for a set of models.
 */
function createModelMergerResults(current, desired, definitionContainer, { siblingModels = [] } = {}) {
    return mapValues(desired, (desired, key) => createModelMergerResult(current[key] && modelEntityType.isId(current[key])
        ? ModelUtils.byIdOrThrow(definitionContainer.definition, current[key])
        : ModelUtils.byName(definitionContainer.definition, current[key] ?? ''), desired, definitionContainer, {
        siblingModels,
    }));
}
function applyModelMergerDiff(model, diff, definitionContainer, siblingModels = []) {
    const resolvedCurrent = serializeModelMergerModelInput(model, definitionContainer, siblingModels);
    const patchedCurrent = applyDefinitionDiff(resolvedCurrent, diff, modelMergerDefinitionDiffConfig);
    return {
        ...model,
        ...deserializeModelMergerModelInput(patchedCurrent, (modelId, fieldName) => {
            const siblingModel = siblingModels.find((m) => m.id === modelId || m.name === modelId);
            if (siblingModel) {
                const field = siblingModel.model.fields.find((f) => f.name === fieldName);
                if (!field) {
                    throw new Error(`Field ${fieldName} not found in sibling model ${modelId}`);
                }
                return field.id;
            }
            const model = ModelUtils.byName(definitionContainer.definition, modelId) ??
                ModelUtils.byIdOrThrow(definitionContainer.definition, modelId);
            const field = model.model.fields.find((f) => f.name === fieldName);
            if (!field) {
                throw new Error(`Field ${fieldName} not found in model ${model.name}`);
            }
            return field.id;
        }, (relationName) => {
            // Search sibling model first
            let relationId;
            for (const siblingModel of siblingModels) {
                const relation = siblingModel.model.relations?.find((r) => r.foreignRelationName === relationName);
                if (relation) {
                    relationId = relation.foreignId;
                    break;
                }
            }
            if (relationId) {
                return relationId;
            }
            const relations = ModelUtils.getRelationsToModel(definitionContainer.definition, model.id);
            const relation = relations.find((r) => r.relation.foreignRelationName === relationName &&
                r.relation.modelRef === model.id);
            if (!relation) {
                throw new Error(`Relation ${relationName} not found in model ${model.name}`);
            }
            return relation.relation.foreignId;
        }, (modelRef) => {
            const siblingModel = siblingModels.find((m) => m.id === modelRef || m.name === modelRef);
            if (siblingModel) {
                return siblingModel.id;
            }
            const model = ModelUtils.byName(definitionContainer.definition, modelRef) ??
                ModelUtils.byIdOrThrow(definitionContainer.definition, modelRef);
            return model.id;
        }),
    };
}
function applyModelMergerResultInPlace(draftConfig, currentModel, result, definitionContainer, { siblingModels = [] } = {}) {
    const newModel = applyModelMergerDiff(currentModel, result.changes, definitionContainer, siblingModels);
    if (result.isNewModel) {
        draftConfig.models.push(newModel);
    }
    else {
        const index = draftConfig.models.findIndex((m) => m.id === result.id);
        if (index === -1) {
            throw new Error(`Model ${result.id} not found`);
        }
        draftConfig.models[index] = newModel;
    }
    return newModel.id;
}
function createAndApplyModelMergerResults(draftConfig, current, desired, definitionContainer, { siblingModels = [] } = {}) {
    const results = createModelMergerResults(current, desired, definitionContainer, { siblingModels });
    const newModels = [];
    const resultIds = {};
    // Apply model mergers in order
    for (const [key, result] of Object.entries(results)) {
        if (result) {
            const model = result.isNewModel
                ? createNewModelConfigInput(result.name, result.featureRef, result.id)
                : ModelUtils.byIdOrThrow(definitionContainer.definition, result.id);
            applyModelMergerResultInPlace(draftConfig, model, result, definitionContainer, {
                siblingModels: newModels,
            });
            const newModel = draftConfig.models.find((m) => m.id === result.id);
            if (newModel) {
                newModels.push(newModel);
            }
            resultIds[key] = model.id;
        }
        else {
            resultIds[key] = desired[key].name;
        }
    }
    return resultIds;
}

export { withPlaceholderSlots as A, featureNameSchema as B, CASE_VALIDATORS as C, DefinitionReferenceMarker as D, createFeatureSchema as E, FeatureUtils as F, modelMergerDefinitionDiffConfig as G, createModelMergerResult as H, doesModelMergerResultsHaveChanges as I, createModelMergerResults as J, applyModelMergerDiff as K, applyModelMergerResultInPlace as L, ModelUtils as M, createAndApplyModelMergerResults as N, DefinitionDiffKeyedArrayField as O, DefinitionDiffReplacementField as P, DefinitionDiffArrayIncludesField as Q, REF_ANNOTATIONS_MARKER_SYMBOL as R, createDefinitionDiffConfig as S, createDefinitionDiff as T, applyDefinitionDiff as U, createEntityType as a, createDefinitionSchemaParserContext as b, createPluginSpec as c, definitionSchemaWithSlots as d, set as e, definitionSchema as f, get as g, modelForeignRelationEntityType as h, isEqual as i, modelLocalRelationEntityType as j, modelScalarFieldEntityType as k, modelEntityType as l, mapValues as m, modelTransformerEntityType as n, modelEnumValueEntityType as o, modelEnumEntityType as p, featureEntityType as q, modelUniqueConstraintEntityType as r, stripRefMarkers as s, createFeaturesSchema as t, omit as u, cloneDeep as v, createInitializedPluginSpec as w, createRefContextSlot as x, createRefContextSlotMap as y, DefinitionEntityType as z };
//# sourceMappingURL=model-merger-Br7ZV97w.js.map
