{"version":3,"file":"crud.mjs","names":["createCrudCommands","errors","config","defaultErrors","name","classification","commandSchema","id","zid","createResult","z","okResult","updateInput","archiveInput","createName","updateName","archiveName","operations","namedOperation","context","resolution","commands","enrichment","command","values","field","value","definition"],"sources":["../src/crud.ts"],"sourcesContent":["import { zid } from 'convex-helpers/server/zod4'\nimport { z } from 'zod'\nimport type { Value } from 'convex/values'\nimport type { GenericDataModel, GenericMutationCtx } from 'convex/server'\nimport type {\n\tAnyCommandMiddleware,\n\tApplicationCommand,\n\tAuditedOperation,\n\tCommandConstructor,\n\tSchemaOutput,\n} from './components/foundation/client'\nimport { defaultErrors, type ErrorFactory } from './errors'\n\n/**\n * The zodTable surface the factory consumes — structural, so any zodTable /\n * tenantTable return satisfies it.\n */\ntype CrudTable = {\n\ttableName: string\n\tcommandInput: z.ZodObject<Record<string, z.ZodType<Value | undefined>>>\n\tstorage: z.ZodObject<Record<string, z.ZodType<Value | undefined>>>\n}\n\ntype CrudContext = { db: Pick<GenericMutationCtx<GenericDataModel>['db'], 'insert' | 'patch'> }\n\ntype MaybePromise<Value> = Value | Promise<Value>\n\nexport type CrudConfig<Context extends CrudContext, Table extends CrudTable = CrudTable> = {\n\t/** The Foundation-bound Command class (destructured from the facade). */\n\tCommand: CommandConstructor\n\ttable: Table\n\t/** Audit aggregate type; enforced by the aggregates allowlist. */\n\taggregateType: string\n\t/** Observability/audit classification. Default 'business'. */\n\tclassification?: string\n\t/** Derives the audited actor id from the ctx (usually ctx.actor.userId). */\n\tactor: (context: Context) => string\n\t/**\n\t * Stamps server-owned fields onto creates (tenant, denormalized ids...).\n\t * REQUIRED when the table is a tenantTable — forgetting it would insert\n\t * untenanted rows; the factory fails fast at construction instead.\n\t */\n\tenrich?: (\n\t\tcontext: Context,\n\t\tcommand: SchemaOutput<Table['commandInput']>,\n\t) => MaybePromise<Partial<z.input<Table['storage']>>>\n\t/** Per-operation preconditions; run before the handlers. */\n\tguards?: {\n\t\tcreate?: (context: Context, command: never) => MaybePromise<void>\n\t\tupdate?: (context: Context, command: never) => MaybePromise<void>\n\t\tarchive?: (context: Context, command: never) => MaybePromise<void>\n\t}\n\t/** Per-operation middleware applied to all three generated operations. */\n\tmiddleware?: readonly AnyCommandMiddleware[]\n\terrors?: ErrorFactory\n}\n\n/**\n * Generates the standard create/update/archive operations from one zodTable\n * declaration, fully inside the audited command pipeline: strict command\n * inputs from `commandFields`, mandatory audit with the declared aggregate\n * type, soft delete only (archive sets `archivedAt` — no hard-delete\n * operation is generated, per kit doctrine).\n *\n * convex-helpers ships a same-named `crud` helper; it was deliberately not\n * used — it bypasses the command pipeline (no audits, no guards, and hard\n * deletes). See docs/crud.md.\n */\nexport type CrudCommands<\n\tContext extends CrudContext,\n\tTable extends CrudTable = CrudTable,\n> = ReturnType<typeof createCrudCommands<Context, Table>>\n\nexport function createCrudCommands<\n\tContext extends CrudContext,\n\tTable extends CrudTable = CrudTable,\n>(config: CrudConfig<Context, Table>) {\n\tconst errors = config.errors ?? defaultErrors\n\tconst name = config.table.tableName\n\tconst classification = config.classification ?? 'business'\n\tconst isTenantTable = 'tenant' in config.table.storage.shape\n\tif (isTenantTable && !config.enrich) {\n\t\treturn errors.throw({\n\t\t\tcode: 'CRUD_ENRICH_REQUIRED',\n\t\t\tmessage: `Table \"${name}\" is a tenantTable: createCrudCommands requires an enrich callback that stamps ctx.tenant`,\n\t\t})\n\t}\n\n\tconst commandSchema: Table['commandInput'] = config.table.commandInput\n\tconst id = zid(name)\n\tconst createResult = z.object({ id }).strict()\n\tconst okResult = z.object({ ok: z.literal(true) }).strict()\n\tconst updateInput = z.object({ id, data: commandSchema.partial().strict() }).strict()\n\tconst archiveInput = z.object({ id }).strict()\n\n\tconst createName = `${name}.create` as const\n\tconst updateName = `${name}.update` as const\n\tconst archiveName = `${name}.archive` as const\n\tconst operations = Object.assign(\n\t\t{},\n\t\tnamedOperation(createName, {\n\t\t\tcommand: commandSchema,\n\t\t\tresult: createResult,\n\t\t\tclassification,\n\t\t\taggregates: [config.aggregateType],\n\t\t\tmiddleware: config.middleware,\n\t\t\tguard: config.guards?.create,\n\t\t\taudit: (resolution: { result: z.output<typeof createResult> }, context: Context) => ({\n\t\t\t\toperation: createName,\n\t\t\t\tactorId: config.actor(context),\n\t\t\t\taggregate: { type: config.aggregateType, id: resolution.result.id },\n\t\t\t}),\n\t\t}),\n\t\tnamedOperation(updateName, {\n\t\t\tcommand: updateInput,\n\t\t\tresult: okResult,\n\t\t\tclassification,\n\t\t\taggregates: [config.aggregateType],\n\t\t\tmiddleware: config.middleware,\n\t\t\tguard: config.guards?.update,\n\t\t\taudit: (resolution: { command: z.output<typeof updateInput> }, context: Context) => ({\n\t\t\t\toperation: updateName,\n\t\t\t\tactorId: config.actor(context),\n\t\t\t\taggregate: { type: config.aggregateType, id: resolution.command.id },\n\t\t\t}),\n\t\t}),\n\t\tnamedOperation(archiveName, {\n\t\t\tcommand: archiveInput,\n\t\t\tresult: okResult,\n\t\t\tclassification,\n\t\t\taggregates: [config.aggregateType],\n\t\t\tmiddleware: config.middleware,\n\t\t\tguard: config.guards?.archive,\n\t\t\taudit: (resolution: { command: z.output<typeof archiveInput> }, context: Context) => ({\n\t\t\t\toperation: archiveName,\n\t\t\t\tactorId: config.actor(context),\n\t\t\t\taggregate: { type: config.aggregateType, id: resolution.command.id },\n\t\t\t}),\n\t\t}),\n\t)\n\tconst commands: ApplicationCommand<Context, typeof operations> = new config.Command<\n\t\tContext,\n\t\ttypeof operations\n\t>(operations)\n\tconst executeCreate = commands.exec({\n\t\toperation: createName,\n\t\thandler: async (context, command) => {\n\t\t\tconst enrichment = config.enrich ? await config.enrich(context, command) : {}\n\t\t\tconst values: Record<string, Value> = {}\n\t\t\tfor (const [field, value] of Object.entries({ ...command, ...enrichment })) {\n\t\t\t\tif (value !== undefined) values[field] = value\n\t\t\t}\n\t\t\tconst inserted = await context.db.insert(name, values)\n\t\t\treturn { id: inserted }\n\t\t},\n\t})\n\tconst executeUpdate = commands.exec({\n\t\toperation: updateName,\n\t\thandler: async (context, command) => {\n\t\t\tawait context.db.patch(command.id, command.data)\n\t\t\treturn { ok: true }\n\t\t},\n\t})\n\tconst executeArchive = commands.exec({\n\t\toperation: archiveName,\n\t\thandler: async (context, command) => {\n\t\t\tawait context.db.patch(command.id, { archivedAt: Date.now() })\n\t\t\treturn { ok: true }\n\t\t},\n\t})\n\n\treturn {\n\t\tcommands,\n\t\toperations,\n\t\texecuteCreate,\n\t\texecuteUpdate,\n\t\texecuteArchive,\n\t}\n}\n\nfunction namedOperation<Name extends string, Definition extends AuditedOperation>(\n\tname: Name,\n\tdefinition: Definition,\n) {\n\t// SAFETY: this object contains exactly the computed name and its corresponding definition.\n\treturn { [name]: definition } as NamedOperation<Name, Definition>\n}\n\ntype NamedOperation<Name extends string, Definition extends AuditedOperation> = {\n\t[Key in Name]: Definition\n}\n"],"mappings":"sHAyEA,SAAgBA,EAGd,EAAoC,CACrC,IAAMC,EAASC,EAAO,QAAUC,EAC1BC,EAAOF,EAAO,MAAM,UACpBG,EAAiBH,EAAO,gBAAkB,WAEhD,GADsB,WAAYA,EAAO,MAAM,QAAQ,OAClC,CAACA,EAAO,OAC5B,OAAOD,EAAO,MAAM,CACnB,KAAM,uBACN,QAAS,UAAUG,EAAK,0FACzB,CAAC,EAGF,IAAME,EAAuCJ,EAAO,MAAM,aACpDK,EAAKC,EAAIJ,CAAI,EACbK,EAAeC,EAAE,OAAO,CAAE,IAAG,CAAC,CAAC,CAAC,OAAO,EACvCC,EAAWD,EAAE,OAAO,CAAE,GAAIA,EAAE,QAAQ,EAAI,CAAE,CAAC,CAAC,CAAC,OAAO,EACpDE,EAAcF,EAAE,OAAO,CAAE,KAAI,KAAMJ,EAAc,QAAQ,CAAC,CAAC,OAAO,CAAE,CAAC,CAAC,CAAC,OAAO,EAC9EO,EAAeH,EAAE,OAAO,CAAE,IAAG,CAAC,CAAC,CAAC,OAAO,EAEvCI,EAAa,GAAGV,EAAK,SACrBW,EAAa,GAAGX,EAAK,SACr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