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

/**
 * Creates a plugin spec with init and use phases.
 *
 * @example
 * ```typescript
 * const mySpec = createPluginSpec('core/my-spec', {
 *   initializer: () => {
 *     const items = new Map<string, Item>();
 *     return {
 *       init: {
 *         register: (item: Item) => items.set(item.name, item),
 *       },
 *       use: () => ({
 *         get: (name: string) => items.get(name),
 *         getAll: () => [...items.values()],
 *       }),
 *     };
 *   },
 * });
 * ```
 *
 * @param name - Unique identifier for the spec (e.g., 'core/my-spec')
 * @param options - Options including the initializer function
 * @returns A plugin spec that can be used with SpecStore
 */
function createPluginSpec(name, options) {
    const { initializer } = options;
    return {
        type: 'plugin-spec',
        name,
        initializer,
    };
}

/**
 * Plugin context module for tracking the current plugin being initialized.
 *
 * Uses a simple synchronous context that works on both Node and browser platforms.
 * This is safe because plugin initialization is synchronous and single-threaded.
 */
// Simple synchronous context - works on both Node and browser
// Safe because plugin initialization is synchronous and single-threaded
let currentPluginContext;
/**
 * Runs a function within a plugin context.
 *
 * This sets the current plugin context for the duration of the function execution,
 * allowing nested functions to access the plugin key via `getPluginContext()`.
 *
 * @param context - The plugin context to set
 * @param fn - The function to run within the context
 * @returns The result of the function
 */
function runInPluginContext(context, fn) {
    const prev = currentPluginContext;
    currentPluginContext = context;
    try {
        return fn();
    }
    finally {
        currentPluginContext = prev;
    }
}
/**
 * Gets the current plugin context if one exists.
 *
 * @returns The current plugin context, or undefined if not in a plugin context
 */
function getPluginContext() {
    return currentPluginContext;
}

const {createFieldMap} = await importShared('@baseplate-dev/utils');
/**
 * Creates a field map that automatically tracks which plugin registered each value.
 *
 * Similar to `createConfigFieldMap` in the sync package, this utility uses the
 * current plugin context to track the source of registrations. This enables
 * clear error messages when registration conflicts occur.
 *
 * @example
 * ```typescript
 * const fieldMap = createPluginFieldMap((t) => ({
 *   transformers: t.map<string, Transformer>(),
 * }));
 *
 * // When a plugin tries to overwrite a value:
 * // Error: Value for key 'myTransformer' has already been set by plugin-auth
 * //        and cannot be overwritten by plugin-storage
 * ```
 *
 * @param schemaBuilder - A function that builds the field map schema
 * @returns A field map with automatic source tracking
 */
function createPluginFieldMap(schemaBuilder) {
    return createFieldMap(schemaBuilder, {
        getDynamicSource: () => getPluginContext()?.pluginKey,
    });
}

/**
 * Creates a plugin spec backed by a FieldMap for automatic source tracking.
 *
 * @param name - Unique identifier for the spec
 * @param schemaBuilder - Function that builds the field map schema
 * @param options - Optional configuration including custom use interface
 */
function createFieldMapSpec(name, schemaBuilder, options) {
    return createPluginSpec(name, {
        initializer: () => {
            const fieldMap = createPluginFieldMap(schemaBuilder);
            return {
                init: fieldMap,
                use: () => {
                    const values = fieldMap.getValues();
                    if (options?.use) {
                        return options.use(values);
                    }
                    return values;
                },
            };
        },
    });
}

/**
 * Global registry that stores Baseplate metadata on Zod schema instances.
 *
 * Uses a plain WeakMap to avoid Zod's `$replace<Meta, S>` type substitution
 * which causes "type instantiation excessively deep" errors with complex unions.
 *
 * Stores an array of metadata per schema to support schemas that carry multiple
 * annotations (e.g. a schema that is both an `entity` and a `ref-context`).
 *
 * Used by `withEnt`, `withRef`, `withExpression`, and `refContext` to attach
 * metadata to schema nodes. The parallel schema+data walker reads this registry
 * to extract entity/reference/expression information after validation.
 */
const definitionRefRegistry = (() => {
    const map = new WeakMap();
    return {
        add(schema, meta) {
            const existing = map.get(schema);
            if (existing) {
                if ((meta.kind === 'entity' || meta.kind === 'reference') &&
                    existing.some((e) => e.kind === meta.kind && e.type === meta.type)) {
                    throw new Error(`Duplicate definition ref metadata kind "${meta.kind}" for type "${meta.type.name}" on the same schema instance. ` +
                        `This usually means a shared/module-level schema was passed to withEnt/withRef multiple times. ` +
                        `Create a fresh schema instance instead.`);
                }
                existing.push(meta);
            }
            else {
                map.set(schema, [meta]);
            }
        },
        getAll(schema) {
            return map.get(schema) ?? [];
        },
        has(schema) {
            return map.has(schema);
        },
    };
})();

/**
 * 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),
    ]));
}

const {z: z$1} = await importShared('zod');
/**
 * Creates a string schema annotated as a reference to another entity.
 *
 * Can be used standalone:
 * ```typescript
 * withRef({ type: modelEnumEntityType, onDelete: 'RESTRICT' })
 * ```
 *
 * Or on the parser context:
 * ```typescript
 * ctx.withRef({ type: modelEnumEntityType, onDelete: 'RESTRICT' })
 * ```
 */
function withRef(reference) {
    const schema = z$1.string().min(1);
    definitionRefRegistry.add(schema, {
        kind: 'reference',
        type: reference.type,
        onDelete: reference.onDelete,
        parentSlot: reference.parentSlot,
        provides: reference.provides,
    });
    return schema;
}
/**
 * Creates a schema decorator that marks a schema as defining an entity.
 *
 * Can be used with `.apply()`:
 * ```typescript
 * schema.apply(withEnt({ type: modelEntityType, provides: modelSlot }))
 * ```
 *
 * Or via the parser context (2-arg legacy form):
 * ```typescript
 * ctx.withEnt(schema, { type: modelEntityType, provides: modelSlot })
 * ```
 *
 * @param entity - The entity definition input
 * @returns A function that decorates a schema with entity metadata
 */
function withEnt(entity) {
    return (schema) => {
        const idPath = entity.idPath ?? ['id'];
        definitionRefRegistry.add(schema, {
            kind: 'entity',
            type: entity.type,
            idPath,
            getNameResolver: entity.getNameResolver,
            parentSlot: entity.parentSlot,
            provides: entity.provides,
        });
        return schema;
    };
}
/**
 * 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);
    const schema = schemaBuilder(slots);
    definitionRefRegistry.add(schema, {
        kind: 'ref-context',
        slots: Object.values(slots),
    });
    return schema;
}
/**
 * Wraps a value with a ref expression parser for deferred validation.
 * The parser handles all parsing, validation, and rename handling.
 *
 * If the parser declares required slots (via TRequiredSlots), they must be
 * provided as the second argument. TypeScript enforces this at compile time.
 *
 * The parser's `createSchema()` method is called to get a fresh schema
 * instance per call site, allowing per-call metadata to be registered
 * independently in the Baseplate registry.
 *
 * @example
 * ```typescript
 * // Parser without required slots
 * const expressionSchema = ctx.withExpression(simpleParser);
 *
 * // Parser with required slots (TypeScript enforces the second argument)
 * ctx.refContext(
 *   { modelSlot: modelEntityType },
 *   ({ modelSlot }) =>
 *     z.object({
 *       condition: ctx.withExpression(authorizerParser, { model: modelSlot }),
 *     })
 * );
 * ```
 */
function withExpression(parser, slots) {
    // createSchema() returns a fresh instance per call, allowing per-call
    // metadata to be registered without conflicting across call sites.
    const schema = parser.createSchema();
    definitionRefRegistry.add(schema, {
        kind: 'expression',
        parser,
        slots,
    });
    return schema;
}
function extendParserContextWithRefs() {
    return {
        withRef,
        // Legacy 2-arg API that delegates to the standalone withEnt decorator.
        // Uses a cast because the standalone accepts DefinitionEntityInput<unknown, ...>
        // while this 2-arg form infers the full z.output<TType> for type-safe idPath.
        withEnt(schema, entity) {
            return schema.apply(withEnt(entity));
        },
        refContext,
        withExpression,
    };
}

/**
 * Registry that stores default-value metadata on Zod schema instances.
 *
 * Uses a WeakMap to avoid interfering with Zod's type system.
 * Annotated by `withDefault()`; read by `cleanDefaultValues()`.
 */
const definitionDefaultRegistry = (() => {
    const map = new WeakMap();
    return {
        set(schema, meta) {
            map.set(schema, meta);
        },
        get(schema) {
            return map.get(schema);
        },
    };
})();

/**
 * Creates a schema decorator that applies a default value.
 *
 * Uses `prefault` to ensure defaults are populated during Zod parse, and
 * registers the default value in the registry so `cleanDefaultValues()` can
 * strip matching values during serialization.
 *
 * Can be used standalone with `.apply()`:
 * ```typescript
 * z.boolean().apply(withDefault(false))
 * ```
 *
 * @param defaultValue - The default value to apply
 * @returns A function that decorates a schema with the default value
 */
function withDefault(defaultValue) {
    return (schema) => {
        const result = schema.prefault(defaultValue);
        definitionDefaultRegistry.set(result, { defaultValue });
        return result;
    };
}
/**
 * Extends the parser context with default value handling functionality.
 *
 * @returns An object containing the withDefault method
 */
function extendParserContextWithDefaults() {
    return {
        withDefault: (schema, defaultValue) => withDefault(defaultValue)(schema),
    };
}

const contextCache = new WeakMap();
function createDefinitionSchemaParserContext(options) {
    const cached = contextCache.get(options.plugins);
    if (cached)
        return cached;
    const context = {
        ...options,
        ...extendParserContextWithRefs(),
        ...extendParserContextWithDefaults(),
    };
    contextCache.set(options.plugins, context);
    return context;
}
function definitionSchema(creator) {
    const cache = new WeakMap();
    return (context) => {
        const cached = cache.get(context);
        if (cached)
            return cached;
        const result = creator(context);
        cache.set(context, result);
        return result;
    };
}
/**
 * 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 {randomKey} = await importShared('@baseplate-dev/utils');

/**
 * 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);
}

const {CASE_VALIDATORS} = await importShared('@baseplate-dev/utils');

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([]));

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,
};

const {PASCAL_CASE_REGEX} = await importShared('@baseplate-dev/utils');

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;
}
function getPrimaryKeyFields(model) {
    const primaryKeyFields = model.model.primaryKeyFieldRefs;
    return primaryKeyFields.map((id) => getScalarFieldById(model, id));
}
const ModelUtils = {
    byId,
    byIdOrThrow,
    byName,
    byNameOrThrow,
    getScalarFieldById,
    getRelationsToModel,
    getModelsForFeature,
    getModelIdFields,
    hasService,
    validateModelName,
    getModelIdByNameOrDefault,
    getPrimaryKeyFields,
};

export { DefinitionEntityType as D, FeatureUtils as F, ModelUtils as M, createEntityType as a, definitionRefRegistry as b, createFieldMapSpec as c, definitionSchemaWithSlots as d, definitionDefaultRegistry as e, definitionSchema as f, featureEntityType as g, createFeaturesSchema as h, createDefinitionSchemaParserContext as i, createFeatureSchema as j, createPluginFieldMap as k, createPluginSpec as l, createRefContextSlot as m, createRefContextSlotMap as n, featureNameSchema as o, getPluginContext as p, withEnt as q, runInPluginContext as r, withPlaceholderSlots as s, withRef as t, withDefault as w };
//# sourceMappingURL=model-utils-BfcjfzCn.js.map
