@schema-engine/actions 0.5.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- function j(){return function(n){return n}}import{createRegistry as E}from"@schema-engine/registry";var P=class{#e;constructor(e){this.#e=E("Action",e)}get kind(){return this.#e.kind}get size(){return this.#e.size}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}all(){return this.#e.all()}keys(){return this.#e.keys()}getAction(e){return this.get(e)}getActionTypes(){return[...this.keys()]}};import{Logger as $}from"@ecopages/logger";var C=new $("[@schema-engine/actions]");function I(n){return typeof n=="object"&&n!==null}function w(n){return Array.isArray(n)}function q(n,e){return e.aborted&&n instanceof Error&&n.name==="AbortError"}var S=class{constructor(e){this.registry=e}registry;async dispatch({actions:e,trigger:i,context:t,metadata:o,triggeredBy:r,signal:s}){if(!e?.length)return[];let u=o?this.mergeMetadata(t,o):t,g=[];for(let[f,T]of e.entries()){if(s?.aborted)break;let a=new AbortController,p=()=>a.abort(s?.reason);s?.addEventListener("abort",p,{once:!0});let m=async(c,y)=>{let B=this.match(c,i);if(!B.runs)return;let{registration:k}=B;if(!k){let A=`No handler registered for action type: ${c.$type}`;return C.error(A,{actionId:c.id,availableActions:this.registry.getActionTypes()}),{actionId:c.id,sequenceIndex:f,...y===void 0?{}:{groupIndex:y},status:"failed",cancellationRequested:!1,success:!1,error:A,shouldContinue:!0}}C.debug(`Executing action: ${c.id} (${c.$type})`);let l,b=!1;try{l=await k.execute({...u,config:c,trigger:i,signal:a.signal,...r?{triggeredBy:r}:{}})}catch(A){b=q(A,a.signal),l={success:!1,error:A instanceof Error?A.message:String(A),cause:A,shouldContinue:!0}}let D=a.signal.aborted;return!l.success&&l.shouldContinue===!1&&a.abort(),l.success||C.warn(`Action ${c.id} failed`,l),{...l,actionId:c.id,sequenceIndex:f,...y===void 0?{}:{groupIndex:y},status:b?"cancelled":l.success?"succeeded":"failed",cancellationRequested:D}},x;try{x=w(T)?await Promise.all(T.map(m)):[await m(T)]}finally{s?.removeEventListener("abort",p)}let R=x.filter(c=>c!==void 0);if(g.push(...R),R.some(c=>!c.success&&c.shouldContinue===!1))break}return g}hasMatching(e,i){return e.some(t=>w(t)?t.some(o=>this.match(o,i).runs):this.match(t,i).runs)}match(e,i){if(e.enabled===!1)return{runs:!1};if(e.triggers!==void 0&&!e.triggers.some(r=>r===i))return{runs:!1};let t=this.registry.getAction(e.$type);return e.triggers===void 0&&t&&!(t.metadata.defaultTriggers??[]).includes(i)?{runs:!1}:{runs:!0,registration:t}}dispatchSync(e){this.dispatch(e).catch(i=>C.error("dispatchSync failed:",i))}mergeMetadata(e,i){if(!I(e))return e;let t=e.metadata;return{...e,metadata:{...typeof t=="object"&&t!==null?t:{},...i}}}};import{safeParseStandardSchema as v}from"@schema-engine/registry";function h(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function d(n,e){return{message:e,path:n}}var M=["id","$type","enabled","triggers"];function O(n,e,i){let t=[];(typeof n.id!="string"||n.id==="")&&t.push(d([...e,"id"],"Action ID must be a non-empty string.")),n.enabled!==void 0&&typeof n.enabled!="boolean"&&t.push(d([...e,"enabled"],"enabled must be a boolean."));let{triggers:o}=n;return o===void 0?t:Array.isArray(o)?(o.forEach((r,s)=>{typeof r!="string"?t.push(d([...e,"triggers",s],"A trigger must be a string.")):i?.triggers&&!i.triggers.includes(r)&&t.push(d([...e,"triggers",s],`Unknown trigger '${r}'. Use one of: ${i.triggers.join(", ")}.`))}),t):(t.push(d([...e,"triggers"],"triggers must be an array of trigger names.")),t)}function K(n,e,i,t){if(!h(e)||typeof e.$type!="string")return{ok:!1,issues:[d([...i,"$type"],"Invalid action configuration: missing $type.")]};let o=n.getAction(e.$type);if(!o)return{ok:!1,issues:[d([...i,"$type"],`Unknown action type '${e.$type}'. Register it in the action registry.`)]};let r=O(e,i,t),s={},u={};for(let[a,p]of Object.entries(e))M.includes(a)?s[a]=p:u[a]=p;let g=v(o.schema,u);if(!g.success)return r.push(...g.error.issues.map(a=>({...a,path:[...i,...a.path??[]]}))),{ok:!1,issues:r};let{data:f}=g;return h(f)||r.push(d(i,`Invalid action configuration for '${e.$type}': the schema must return an object.`)),r.length>0||!h(f)?{ok:!1,issues:r}:{ok:!0,action:{...f,...s,id:e.id,$type:e.$type}}}function G(n,e,i){if(!Array.isArray(e))return{success:!1,issues:[d([],"Actions must be an array.")]};let t=[],o=[],r=(s,u)=>{let g=K(n,s,u,i);if(g.ok)return g.action;t.push(...g.issues)};return e.forEach((s,u)=>{if(Array.isArray(s)){if(s.length===0){t.push(d([u],"A group of actions must hold at least one action."));return}let f=s.map((T,a)=>r(T,[u,a])).filter(T=>T!==void 0);o.push(f);return}let g=r(s,[u]);g&&o.push(g)}),t.length>0?{success:!1,issues:t}:{success:!0,data:o}}export{S as ActionDispatcher,P as ActionRegistry,j as defineAction,G as parseActions};
1
+ function _(){return function(t){return t}}import{createRegistry as D}from"@schema-engine/registry";var k=class{#e;constructor(e){this.#e=D("Action",e)}get kind(){return this.#e.kind}get size(){return this.#e.size}get(e){return this.#e.get(e)}has(e){return this.#e.has(e)}all(){return this.#e.all()}keys(){return this.#e.keys()}getAction(e){return this.get(e)}getActionTypes(){return[...this.keys()]}};import{Logger as E}from"@ecopages/logger";var C=new E("[@schema-engine/actions]");function I(t){return typeof t=="object"&&t!==null}function P(t){return Array.isArray(t)}function q(t,e){return e.aborted&&t instanceof Error&&t.name==="AbortError"}var w=class{constructor(e){this.registry=e}registry;async dispatch({actions:e,trigger:n,context:i,metadata:r,triggeredBy:s,signal:f}){if(!e?.length)return[];let a=r?this.mergeMetadata(i,r):i,o=[];for(let[g,d]of e.entries()){if(f?.aborted)break;let u=new AbortController,p=()=>u.abort(f?.reason);f?.addEventListener("abort",p,{once:!0});let h=async(c,y)=>{let R=this.match(c,n);if(!R.runs)return;let{registration:B}=R;if(!B){let l=`No handler registered for action type: ${c.$type}`;return C.error(l,{actionId:c.id,availableActions:this.registry.getActionTypes()}),{actionId:c.id,sequenceIndex:g,...y===void 0?{}:{groupIndex:y},status:"failed",cancellationRequested:!1,success:!1,error:l,shouldContinue:!0}}C.debug(`Executing action: ${c.id} (${c.$type})`);let T,b=!1;try{T=await B.execute({...a,config:c,trigger:n,signal:u.signal,...s?{triggeredBy:s}:{}})}catch(l){b=q(l,u.signal),T={success:!1,error:l instanceof Error?l.message:String(l),cause:l,shouldContinue:!0}}let S=u.signal.aborted;return!T.success&&T.shouldContinue===!1&&u.abort(),T.success||C.warn(`Action ${c.id} failed`,T),{...T,actionId:c.id,sequenceIndex:g,...y===void 0?{}:{groupIndex:y},status:b?"cancelled":T.success?"succeeded":"failed",cancellationRequested:S}},m;try{m=P(d)?await Promise.all(d.map(h)):[await h(d)]}finally{f?.removeEventListener("abort",p)}let x=m.filter(c=>c!==void 0);if(o.push(...x),x.some(c=>!c.success&&c.shouldContinue===!1))break}return o}hasMatching(e,n){return e.some(i=>P(i)?i.some(r=>this.match(r,n).runs):this.match(i,n).runs)}match(e,n){if(e.enabled===!1)return{runs:!1};if(e.triggers!==void 0&&!e.triggers.some(s=>s===n))return{runs:!1};let i=this.registry.getAction(e.$type);return e.triggers===void 0&&i&&!(i.metadata.defaultTriggers??[]).includes(n)?{runs:!1}:{runs:!0,registration:i}}dispatchSync(e){this.dispatch(e).catch(n=>C.error("dispatchSync failed:",n))}mergeMetadata(e,n){if(!I(e))return e;let i=e.metadata;return{...e,metadata:{...typeof i=="object"&&i!==null?i:{},...n}}}};import{safeParseNode as v,safeParseStandardSchema as $,standardSchema as M}from"@schema-engine/registry";function O(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function A(t,e){return{message:e,path:t}}var L="Register it in the action registry.",N=["id","$type","enabled","triggers"];function j(t,e){let n=[];(typeof t.id!="string"||t.id==="")&&n.push(A(["id"],"Action ID must be a non-empty string.")),t.enabled!==void 0&&typeof t.enabled!="boolean"&&n.push(A(["enabled"],"enabled must be a boolean."));let{triggers:i}=t;return i===void 0?n:Array.isArray(i)?(i.forEach((r,s)=>{typeof r!="string"?n.push(A(["triggers",s],"A trigger must be a string.")):e?.triggers&&!e.triggers.includes(r)&&n.push(A(["triggers",s],`Unknown trigger '${r}'. Use one of: ${e.triggers.join(", ")}.`))}),n):(n.push(A(["triggers"],"triggers must be an array of trigger names.")),n)}function K(t,e,n){return M(i=>{let r=i,s=j(r,n),f={},a={};for(let[d,u]of Object.entries(r))N.includes(d)?f[d]=u:a[d]=u;let o=$(e,a);if(!o.success)return{issues:[...s,...o.error.issues]};let{data:g}=o;if(!O(g)){let d=`Invalid action configuration for '${t}': the schema must return an object.`;return{issues:[...s,A([],d)]}}return s.length>0?{issues:s}:{value:{...g,...f,id:r.id,$type:t}}})}function Y(t,e,n){if(!Array.isArray(e))return{success:!1,issues:[A([],"Actions must be an array.")]};let i={get(a){let o=t.getAction(a);return o&&{schema:K(a,o.schema,n)}},hint:n?.hint??L},r=[],s=[],f=(a,o)=>{let g=v(i,a,o);if(g.success)return g.data;r.push(...g.issues)};return e.forEach((a,o)=>{if(Array.isArray(a)){if(a.length===0){r.push(A([o],"A group of actions must hold at least one action."));return}let d=a.map((u,p)=>f(u,[o,p])).filter(u=>u!==void 0);s.push(d);return}let g=f(a,[o]);g&&s.push(g)}),r.length>0?{success:!1,issues:r}:{success:!0,data:s}}export{w as ActionDispatcher,k as ActionRegistry,_ as defineAction,Y as parseActions};
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/types.ts", "../src/registry.ts", "../src/dispatcher.ts", "../src/parse-actions.ts"],
4
- "sourcesContent": ["import type { BaseRegistration, RegistrationMetadata } from '@schema-engine/registry';\n\n/**\n * The keys every action entry carries, owned by the engine.\n *\n * @template TType - The action type identifier\n *\n * @remarks\n * {@link parseActions} checks these keys itself and hands only the rest to the registration's schema. A\n * registration's config type is this interface plus the output of its schema, which lists the action's own\n * arguments and none of these keys: `ActionConfigBase<'post'> & { endpoint: string }`.\n */\nexport interface ActionConfigBase<TType extends string = string> {\n\t/** Unique identifier for this action instance */\n\tid: string;\n\t/** Action type - references a registered action */\n\t$type: TType;\n\t/** Whether this action is enabled */\n\tenabled?: boolean;\n\t/** Custom triggers for this specific action instance */\n\ttriggers?: readonly string[];\n}\n\n/**\n * Action Runtime Context\n *\n * Context received by action handlers at execution time.\n * The dispatcher creates this runtime shape by enriching the caller-provided\n * base context with the current action config and trigger.\n *\n * @template TConfig - Action configuration type\n * @template TBaseContext - Caller-provided base context\n * @template TTrigger - Trigger/event type\n */\nexport type ActionRuntimeContext<TConfig = unknown, TBaseContext = unknown, TTrigger = string> = TBaseContext & {\n\t/** Current action configuration */\n\tconfig: TConfig;\n\t/** Trigger/event that caused this action to execute */\n\ttrigger: TTrigger;\n\t/** Action config that triggered nested execution, when applicable */\n\ttriggeredBy?: TConfig;\n\t/** Cooperative cancellation for the current action. */\n\tsignal: AbortSignal;\n};\n\n/**\n * Action Execution Result\n *\n * Standardized return type for all action handlers.\n * Provides success status, messages, data, and flow control information.\n *\n * @template TData - Type of data returned by the action\n *\n * @example Success Result\n * ```typescript\n * return {\n * success: true,\n * message: \"Action completed successfully\",\n * data: { submissionId: \"abc123\" },\n * shouldContinue: true\n * };\n * ```\n *\n * @example Error Result\n * ```typescript\n * return {\n * success: false,\n * error: \"Validation failed\",\n * shouldContinue: false,\n * };\n * ```\n */\nexport interface ActionExecutionResult<TData = unknown> {\n\t/** Whether the action executed successfully */\n\tsuccess: boolean;\n\t/** Success message to display or log */\n\tmessage?: string;\n\t/** Error message if action failed */\n\terror?: string;\n\t/** Original error thrown by the handler, when available. */\n\tcause?: unknown;\n\t/** Data returned by the action (e.g., API response) */\n\tdata?: TData;\n\t/**\n\t * Whether to continue after this action fails.\n\t *\n\t * @remarks\n\t * The dispatcher stops after a failed action only when this is `false`. Form submissions also\n\t * fail only for unsuccessful actions with `shouldContinue: false`; omitted or `true` continues.\n\t */\n\tshouldContinue?: boolean;\n}\n\n/** An action result annotated by the dispatcher for correlation with its configuration. */\nexport type ActionDispatchResult<TData = unknown> = ActionExecutionResult<TData> & {\n\tactionId: string;\n\tsequenceIndex: number;\n\tgroupIndex?: number;\n\tstatus: 'succeeded' | 'failed' | 'cancelled';\n\tcancellationRequested: boolean;\n};\n\n/** A sequence entry is either one action or a group that runs concurrently. */\nexport type ActionSequenceEntry<TConfig extends ActionConfigBase> = TConfig | readonly TConfig[];\n\ndeclare const PARSED_ACTION: unique symbol;\n\n/**\n * An action config that {@link parseActions} checked against its registration's schema.\n *\n * @remarks\n * The brand exists in the type only. {@link parseActions} is the one function that produces it, and\n * {@link ActionDispatcher.dispatch} accepts nothing else, so an action that arrived as raw JSON or an object\n * literal cannot reach a handler unchecked.\n */\nexport type ParsedAction<TConfig extends ActionConfigBase = ActionConfigBase> = TConfig & {\n\treadonly [PARSED_ACTION]: true;\n};\n\n/** The sequence {@link parseActions} returns and {@link ActionDispatcher.dispatch} runs. */\nexport type ParsedActionSequence<TConfig extends ActionConfigBase = ActionConfigBase> = readonly ActionSequenceEntry<\n\tParsedAction<TConfig>\n>[];\n\n/**\n * Action Handler Function Type\n *\n * Function signature for action handlers using the current runtime-enrichment model.\n * At execution time, the domain context is enriched with the current action config\n * and trigger before the handler is called.\n *\n * @template TConfig - The action configuration type\n * @template TContext - Domain-specific base context data\n * @template TTrigger - The trigger/event type\n * @template TData - The type of data returned by the action\n */\nexport type ActionHandler<TConfig = unknown, TContext = unknown, TTrigger = string, TData = unknown> = (\n\tcontext: ActionRuntimeContext<TConfig, TContext, TTrigger>,\n) => Promise<ActionExecutionResult<TData>> | ActionExecutionResult<TData>;\n\n/**\n * Action Metadata\n *\n * Descriptive information about an action type.\n *\n * @template TTrigger - The trigger/event type\n */\nexport interface ActionMetadata<TTrigger = string> extends RegistrationMetadata {\n\t/** Icon identifier (optional) */\n\ticon?: string;\n\t/** Default triggers that this action responds to */\n\tdefaultTriggers?: readonly TTrigger[];\n\t/** Category for grouping actions (optional) */\n\tcategory?: string;\n}\n\n/**\n * Action Registration\n *\n * Configuration object for registering actions in an action registry.\n * Used to define action behavior, validation, and metadata. The schema describes the action's own\n * arguments; {@link ActionConfigBase} keys are checked by {@link parseActions}.\n *\n * @template TConfig - Action configuration type\n * @template TBaseContext - Caller-provided base context data\n * @template TTrigger - The trigger/event type\n *\n * @example\n * ```typescript\n * import * as z from 'zod/mini';\n *\n * const logAction: ActionRegistration<LogActionConfig, AppContext, AppTrigger> = {\n * $type: 'log',\n * schema: z.object({\n * level: z.enum(['info', 'warn', 'error']),\n * message: z.string(),\n * }),\n * metadata: {\n * name: 'Log Message',\n * description: 'Logs a message to the console',\n * defaultTriggers: ['change', 'submit'],\n * },\n * execute: async (context) => {\n * console[context.config.level](context.config.message);\n * return { success: true };\n * },\n * };\n * ```\n */\nexport interface ActionRegistration<\n\tTConfig extends ActionConfigBase = ActionConfigBase,\n\tTBaseContext = unknown,\n\tTTrigger = string,\n\tTData = unknown,\n> extends BaseRegistration<TConfig, ActionMetadata<TTrigger>> {\n\t/** Unique action type identifier */\n\t$type: TConfig['$type'];\n\t/**\n\t * Action execution function.\n\t * Receives the runtime context produced by the dispatcher.\n\t */\n\texecute: ActionHandler<TConfig, TBaseContext, TTrigger, TData>;\n}\n\n/** Input for trigger-based sequential dispatch. */\nexport interface ActionDispatchInput<\n\tTConfig extends ActionConfigBase = ActionConfigBase,\n\tTBaseContext = unknown,\n\tTTrigger = string,\n> {\n\ttrigger: TTrigger;\n\tactions: ParsedActionSequence<TConfig>;\n\tcontext: TBaseContext;\n\ttriggeredBy?: TConfig;\n\tmetadata?: Record<string, unknown>;\n\t/**\n\t * Cancels the dispatch from outside.\n\t *\n\t * @remarks It is chained into the signal each action receives, and the sequence runs no further entry once it is aborted.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/**\n * Create a strongly typed action-definition helper for one domain.\n */\nexport function defineAction<TBaseContext, TTrigger = string>() {\n\treturn function <TConfig extends ActionConfigBase, TData = unknown>(\n\t\tregistration: ActionRegistration<TConfig, TBaseContext, TTrigger, TData>,\n\t): ActionRegistration<TConfig, TBaseContext, TTrigger, TData> {\n\t\treturn registration;\n\t};\n}\n", "import type { ActionRegistration } from './types';\nimport { createRegistry, type ReadOnlyRegistry } from '@schema-engine/registry';\n\n/**\n * Registry storage must be able to hold heterogeneous action config shapes.\n * `any` is used here as an existential placeholder for that internal storage boundary.\n */\ntype AnyActionRegistration<TBaseContext, TTrigger> = ActionRegistration<any, TBaseContext, TTrigger>;\n\n/**\n * Action Registry Provider\n *\n * Interface for objects that can provide action registrations.\n * This allows the ActionDispatcher to look up action handlers without\n * depending on a specific registry implementation.\n *\n * @template TContext - Domain-specific context data\n * @template TTrigger - The trigger/event type\n * @template TRegistration - The registration type (defaults to ActionRegistration)\n *\n * @example\n * ```typescript\n * class MyActionRegistry implements ActionRegistryProvider<MyContext, MyTrigger> {\n * private actions = new Map<string, ActionRegistration<any, MyContext, MyTrigger>>();\n *\n * register(action: ActionRegistration<any, MyContext, MyTrigger>): void {\n * this.actions.set(action.$type, action);\n * }\n *\n * getAction(type: string): ActionRegistration<any, MyContext, MyTrigger> | undefined {\n * return this.actions.get(type);\n * }\n *\n * getActionTypes(): string[] {\n * return Array.from(this.actions.keys());\n * }\n * }\n * ```\n */\nexport interface ActionRegistryProvider<\n\tTBaseContext = unknown,\n\tTTrigger = string,\n\tTRegistration extends AnyActionRegistration<TBaseContext, TTrigger> = AnyActionRegistration<TBaseContext, TTrigger>,\n> {\n\t/**\n\t * Get an action registration by type\n\t *\n\t * @param type - The action type identifier\n\t * @returns The action registration or undefined if not found\n\t */\n\tgetAction(type: string): TRegistration | undefined;\n\n\t/**\n\t * Get all registered action types\n\t *\n\t * @returns Array of action type identifiers\n\t */\n\tgetActionTypes(): string[];\n}\n\n/**\n * Action Registry\n *\n * Generic, domain-agnostic, read-only registry of action registrations, built\n * from a list on the shared {@link createRegistry} mechanism.\n *\n * @template TContext - Domain-specific context data\n * @template TTrigger - The trigger/event type\n *\n * @remarks\n * A later registration with the same `$type` replaces an earlier one without a\n * warning. Every winning schema must implement Standard Schema; the constructor\n * throws naming the offending `$type`. The registrations are held in a private\n * field, so the registry cannot be changed, and subclasses may add their own fields. To register actions at runtime, implement\n * {@link ActionRegistryProvider} on a `BaseRegistry` subclass instead.\n *\n * @example\n * ```typescript\n * import { ActionRegistry } from '@schema-engine/actions';\n *\n * type MyTrigger = 'submit' | 'change';\n * import { Logger } from '@ecopages/logger';\n * type MyContext = { formId: string; data: Record<string, unknown> };\n *\n * const logger = new Logger('[my-app]');\n * const registry = new ActionRegistry<MyContext, MyTrigger>([\n * {\n * $type: 'log',\n * schema: logSchema,\n * metadata: {\n * name: 'Log Action',\n * description: 'Logs data',\n * defaultTriggers: ['change'],\n * },\n * execute: async (context) => {\n * logger.info(context);\n * return { success: true };\n * },\n * },\n * ]);\n *\n * const action = registry.getAction('log');\n * ```\n */\nexport class ActionRegistry<\n\tTBaseContext = unknown,\n\tTTrigger = string,\n\tTRegistration extends AnyActionRegistration<TBaseContext, TTrigger> = AnyActionRegistration<TBaseContext, TTrigger>,\n>\n\timplements ReadOnlyRegistry<TRegistration>, ActionRegistryProvider<TBaseContext, TTrigger, TRegistration>\n{\n\treadonly #registry: ReadOnlyRegistry<TRegistration>;\n\n\tconstructor(registrations: readonly TRegistration[]) {\n\t\tthis.#registry = createRegistry('Action', registrations);\n\t}\n\n\tget kind(): string {\n\t\treturn this.#registry.kind;\n\t}\n\n\tget size(): number {\n\t\treturn this.#registry.size;\n\t}\n\n\tget(key: string): TRegistration | undefined {\n\t\treturn this.#registry.get(key);\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.#registry.has(key);\n\t}\n\n\tall(): readonly TRegistration[] {\n\t\treturn this.#registry.all();\n\t}\n\n\tkeys(): readonly string[] {\n\t\treturn this.#registry.keys();\n\t}\n\n\t/**\n\t * Get an action registration by type\n\t */\n\tgetAction(type: string): TRegistration | undefined {\n\t\treturn this.get(type);\n\t}\n\n\t/**\n\t * Get all registered action types\n\t */\n\tgetActionTypes(): string[] {\n\t\treturn [...this.keys()];\n\t}\n}\n", "import type {\n\tActionConfigBase,\n\tActionDispatchInput,\n\tActionDispatchResult,\n\tActionExecutionResult,\n\tActionSequenceEntry,\n\tParsedAction,\n\tParsedActionSequence,\n} from './types';\nimport type { ActionRegistryProvider } from './registry';\nimport { Logger } from '@ecopages/logger';\n\nconst logger = new Logger('[@schema-engine/actions]');\n\ntype MetadataContext = { metadata?: Record<string, unknown> };\n\nfunction isMetadataContext(value: unknown): value is MetadataContext {\n\treturn typeof value === 'object' && value !== null;\n}\n\nfunction isGroup<T extends ActionConfigBase>(entry: ActionSequenceEntry<T>): entry is readonly T[] {\n\treturn Array.isArray(entry);\n}\n\nfunction isCancellation(error: unknown, signal: AbortSignal): boolean {\n\treturn signal.aborted && error instanceof Error && error.name === 'AbortError';\n}\n\ntype ActionMatch<TBaseContext, TTrigger> =\n\t| { runs: false }\n\t| { runs: true; registration: ReturnType<ActionRegistryProvider<TBaseContext, TTrigger>['getAction']> };\n\n/** Dispatches actions in sequence, allowing groups to execute concurrently. */\nexport class ActionDispatcher<TBaseContext = unknown, TTrigger = string> {\n\tconstructor(private readonly registry: ActionRegistryProvider<TBaseContext, TTrigger>) {}\n\n\tasync dispatch<TConfig extends ActionConfigBase>({\n\t\tactions,\n\t\ttrigger,\n\t\tcontext,\n\t\tmetadata,\n\t\ttriggeredBy,\n\t\tsignal: outer,\n\t}: ActionDispatchInput<TConfig, TBaseContext, TTrigger>): Promise<ActionDispatchResult[]> {\n\t\tif (!actions?.length) return [];\n\t\tconst enhancedContext = metadata ? this.mergeMetadata(context, metadata) : context;\n\t\tconst results: ActionDispatchResult[] = [];\n\t\tfor (const [sequenceIndex, entry] of actions.entries()) {\n\t\t\tif (outer?.aborted) break;\n\t\t\tconst controller = new AbortController();\n\t\t\tconst abortWithOuter = () => controller.abort(outer?.reason);\n\t\t\touter?.addEventListener('abort', abortWithOuter, { once: true });\n\t\t\tconst run = async (\n\t\t\t\taction: ParsedAction<TConfig>,\n\t\t\t\tgroupIndex?: number,\n\t\t\t): Promise<ActionDispatchResult | undefined> => {\n\t\t\t\tconst match = this.match(action, trigger);\n\t\t\t\tif (!match.runs) return undefined;\n\t\t\t\tconst { registration } = match;\n\t\t\t\tif (!registration) {\n\t\t\t\t\tconst error = `No handler registered for action type: ${action.$type}`;\n\t\t\t\t\tlogger.error(error, { actionId: action.id, availableActions: this.registry.getActionTypes() });\n\t\t\t\t\treturn {\n\t\t\t\t\t\tactionId: action.id,\n\t\t\t\t\t\tsequenceIndex,\n\t\t\t\t\t\t...(groupIndex === undefined ? {} : { groupIndex }),\n\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\tcancellationRequested: false,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tshouldContinue: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlogger.debug(`Executing action: ${action.id} (${action.$type})`);\n\t\t\t\tlet result: ActionExecutionResult;\n\t\t\t\tlet cancelled = false;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await registration.execute({\n\t\t\t\t\t\t...enhancedContext,\n\t\t\t\t\t\tconfig: action,\n\t\t\t\t\t\ttrigger,\n\t\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t\t\t...(triggeredBy ? { triggeredBy } : {}),\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancelled = isCancellation(error, controller.signal);\n\t\t\t\t\tresult = {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\tshouldContinue: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst cancellationRequested = controller.signal.aborted;\n\t\t\t\tif (!result.success && result.shouldContinue === false) controller.abort();\n\t\t\t\tif (!result.success) logger.warn(`Action ${action.id} failed`, result);\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tactionId: action.id,\n\t\t\t\t\tsequenceIndex,\n\t\t\t\t\t...(groupIndex === undefined ? {} : { groupIndex }),\n\t\t\t\t\tstatus: cancelled ? 'cancelled' : result.success ? 'succeeded' : 'failed',\n\t\t\t\t\tcancellationRequested,\n\t\t\t\t};\n\t\t\t};\n\t\t\tlet groupResults: Array<ActionDispatchResult | undefined>;\n\t\t\ttry {\n\t\t\t\tgroupResults = isGroup(entry) ? await Promise.all(entry.map(run)) : [await run(entry)];\n\t\t\t} finally {\n\t\t\t\touter?.removeEventListener('abort', abortWithOuter);\n\t\t\t}\n\t\t\tconst executed = groupResults.filter((result): result is ActionDispatchResult => result !== undefined);\n\t\t\tresults.push(...executed);\n\t\t\tif (executed.some((result) => !result.success && result.shouldContinue === false)) break;\n\t\t}\n\t\treturn results;\n\t}\n\n\t/**\n\t * Whether `dispatch` would run, or report a missing handler for, at least one of the actions on this trigger.\n\t *\n\t * @remarks\n\t * Lets a caller skip building a context for a trigger no action answers. It checks the same conditions\n\t * `dispatch` does, so the two cannot disagree.\n\t */\n\thasMatching<TConfig extends ActionConfigBase>(actions: ParsedActionSequence<TConfig>, trigger: TTrigger): boolean {\n\t\treturn actions.some((entry) =>\n\t\t\tisGroup(entry) ? entry.some((action) => this.match(action, trigger).runs) : this.match(entry, trigger).runs,\n\t\t);\n\t}\n\n\t/**\n\t * @remarks\n\t * An action of an unregistered type always matches, so `dispatch` can report the missing handler. The\n\t * registration it looked up comes back so `dispatch` does not look it up again.\n\t */\n\tprivate match(action: ActionConfigBase, trigger: TTrigger): ActionMatch<TBaseContext, TTrigger> {\n\t\tif (action.enabled === false) return { runs: false };\n\t\tif (action.triggers !== undefined && !action.triggers.some((candidate) => candidate === trigger)) {\n\t\t\treturn { runs: false };\n\t\t}\n\t\tconst registration = this.registry.getAction(action.$type);\n\t\tconst implicit = action.triggers === undefined;\n\t\tif (implicit && registration && !(registration.metadata.defaultTriggers ?? []).includes(trigger)) {\n\t\t\treturn { runs: false };\n\t\t}\n\t\treturn { runs: true, registration };\n\t}\n\n\t/** @remarks Best-effort dispatch never rejects to its caller. */\n\tdispatchSync<TConfig extends ActionConfigBase>(input: ActionDispatchInput<TConfig, TBaseContext, TTrigger>): void {\n\t\tvoid this.dispatch(input).catch((error) => logger.error('dispatchSync failed:', error));\n\t}\n\n\tprivate mergeMetadata(context: TBaseContext, metadata: Record<string, unknown>): TBaseContext {\n\t\tif (!isMetadataContext(context)) return context;\n\t\tconst existingMetadata = context.metadata;\n\t\treturn {\n\t\t\t...context,\n\t\t\tmetadata: {\n\t\t\t\t...(typeof existingMetadata === 'object' && existingMetadata !== null ? existingMetadata : {}),\n\t\t\t\t...metadata,\n\t\t\t},\n\t\t};\n\t}\n}\n", "import { safeParseStandardSchema, type BaseRegistration, type StandardSchemaIssue } from '@schema-engine/registry';\nimport type { ActionConfigBase, ParsedAction, ParsedActionSequence } from './types';\n\n/** What {@link parseActions} needs of a registry: the registration of a `$type`, for its schema. */\nexport interface ActionSchemaLookup {\n\tgetAction(type: string): Pick<BaseRegistration, 'schema'> | undefined;\n}\n\n/** What a domain tells {@link parseActions} about the entries it accepts. */\nexport interface ParseActionsOptions {\n\t/**\n\t * The trigger names an entry's `triggers` may hold.\n\t *\n\t * @remarks Without it, any string is accepted, since the engine cannot know a domain's triggers.\n\t */\n\ttriggers?: readonly string[];\n}\n\n/**\n * What {@link parseActions} returns: the parsed sequence, or every issue found.\n *\n * @remarks\n * An issue is a Standard Schema issue whose `path` starts with the index of the entry, then the index inside\n * a group, then the path the schema reported (`[1, 0, 'endpoint']`). An entry that is not an action object\n * with a `$type`, and a `$type` no registration answers, are issues at `$type`. An empty group is an issue at its index.\n */\nexport type ParseActionsResult<TConfig extends ActionConfigBase = ActionConfigBase> =\n\t{ success: true; data: ParsedActionSequence<TConfig> } | { success: false; issues: StandardSchemaIssue[] };\n\ntype ParsedEntry<TConfig extends ActionConfigBase> =\n\t{ ok: true; action: ParsedAction<TConfig> } | { ok: false; issues: StandardSchemaIssue[] };\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction issueAt(path: ReadonlyArray<PropertyKey>, message: string): StandardSchemaIssue {\n\treturn { message, path };\n}\n\n/** The envelope keys the engine checks itself; a registration's schema never sees them. */\nconst BASE_KEYS = ['id', '$type', 'enabled', 'triggers'] as const;\n\nfunction checkBase(\n\tentry: Record<PropertyKey, unknown>,\n\tpath: ReadonlyArray<PropertyKey>,\n\toptions: ParseActionsOptions | undefined,\n): StandardSchemaIssue[] {\n\tconst issues: StandardSchemaIssue[] = [];\n\tif (typeof entry.id !== 'string' || entry.id === '') {\n\t\tissues.push(issueAt([...path, 'id'], 'Action ID must be a non-empty string.'));\n\t}\n\tif (entry.enabled !== undefined && typeof entry.enabled !== 'boolean') {\n\t\tissues.push(issueAt([...path, 'enabled'], 'enabled must be a boolean.'));\n\t}\n\tconst { triggers } = entry;\n\tif (triggers === undefined) return issues;\n\tif (!Array.isArray(triggers)) {\n\t\tissues.push(issueAt([...path, 'triggers'], 'triggers must be an array of trigger names.'));\n\t\treturn issues;\n\t}\n\ttriggers.forEach((trigger: unknown, index) => {\n\t\tif (typeof trigger !== 'string') {\n\t\t\tissues.push(issueAt([...path, 'triggers', index], 'A trigger must be a string.'));\n\t\t} else if (options?.triggers && !options.triggers.includes(trigger)) {\n\t\t\tissues.push(\n\t\t\t\tissueAt(\n\t\t\t\t\t[...path, 'triggers', index],\n\t\t\t\t\t`Unknown trigger '${trigger}'. Use one of: ${options.triggers.join(', ')}.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t});\n\treturn issues;\n}\n\nfunction parseEntry<TConfig extends ActionConfigBase>(\n\tregistry: ActionSchemaLookup,\n\tentry: unknown,\n\tpath: ReadonlyArray<PropertyKey>,\n\toptions: ParseActionsOptions | undefined,\n): ParsedEntry<TConfig> {\n\tif (!isRecord(entry) || typeof entry.$type !== 'string') {\n\t\treturn { ok: false, issues: [issueAt([...path, '$type'], 'Invalid action configuration: missing $type.')] };\n\t}\n\tconst registration = registry.getAction(entry.$type);\n\tif (!registration) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\tissues: [\n\t\t\t\tissueAt(\n\t\t\t\t\t[...path, '$type'],\n\t\t\t\t\t`Unknown action type '${entry.$type}'. Register it in the action registry.`,\n\t\t\t\t),\n\t\t\t],\n\t\t};\n\t}\n\tconst issues = checkBase(entry, path, options);\n\tconst base: Record<string, unknown> = {};\n\tconst own: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(entry)) {\n\t\tif ((BASE_KEYS as readonly string[]).includes(key)) base[key] = value;\n\t\telse own[key] = value;\n\t}\n\tconst result = safeParseStandardSchema(registration.schema, own);\n\tif (!result.success) {\n\t\tissues.push(...result.error.issues.map((issue) => ({ ...issue, path: [...path, ...(issue.path ?? [])] })));\n\t\treturn { ok: false, issues };\n\t}\n\tconst { data } = result;\n\tif (!isRecord(data)) {\n\t\tissues.push(\n\t\t\tissueAt(path, `Invalid action configuration for '${entry.$type}': the schema must return an object.`),\n\t\t);\n\t}\n\tif (issues.length > 0 || !isRecord(data)) return { ok: false, issues };\n\tconst action: ActionConfigBase = { ...data, ...base, id: entry.id as string, $type: entry.$type };\n\treturn { ok: true, action: action as ParsedAction<TConfig> };\n}\n\n/**\n * Check serialized actions against their registrations, and return them as {@link ParsedAction}s.\n *\n * @param registry - Where each entry's `$type` finds its registration and schema\n * @param input - The sequence as it arrived, for example the result of `JSON.parse`: entries, where an array entry is a group\n * @param options - What the domain adds, such as the trigger names it accepts\n *\n * @remarks\n * This is the only way to produce a {@link ParsedAction}, and so the only way to a call of\n * {@link ActionDispatcher.dispatch}. Every entry is checked, so a sequence with two bad entries reports both.\n *\n * The engine owns the keys every entry carries: `id` (a non-empty string), `$type` (a registered one), `enabled` and\n * `triggers`. It checks them itself, then hands the remaining keys to the registration's schema, which describes\n * the action's own arguments only. The result is those keys merged with what the schema returned, so its defaults and\n * transforms apply. `TConfig` is the caller's claim about the result; the parse itself checks the schemas, not that claim.\n *\n * @throws {Error} When a registration's schema validates asynchronously, which is a misuse of the registry.\n */\nexport function parseActions<TConfig extends ActionConfigBase = ActionConfigBase>(\n\tregistry: ActionSchemaLookup,\n\tinput: unknown,\n\toptions?: ParseActionsOptions,\n): ParseActionsResult<TConfig> {\n\tif (!Array.isArray(input)) {\n\t\treturn { success: false, issues: [issueAt([], 'Actions must be an array.')] };\n\t}\n\n\tconst issues: StandardSchemaIssue[] = [];\n\tconst sequence: Array<ParsedAction<TConfig> | Array<ParsedAction<TConfig>>> = [];\n\tconst collect = (entry: unknown, path: ReadonlyArray<PropertyKey>): ParsedAction<TConfig> | undefined => {\n\t\tconst parsed = parseEntry<TConfig>(registry, entry, path, options);\n\t\tif (parsed.ok) return parsed.action;\n\t\tissues.push(...parsed.issues);\n\t\treturn undefined;\n\t};\n\n\tinput.forEach((entry: unknown, index) => {\n\t\tif (Array.isArray(entry)) {\n\t\t\tif (entry.length === 0) {\n\t\t\t\tissues.push(issueAt([index], 'A group of actions must hold at least one action.'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst group = entry\n\t\t\t\t.map((member: unknown, memberIndex) => collect(member, [index, memberIndex]))\n\t\t\t\t.filter((action): action is ParsedAction<TConfig> => action !== undefined);\n\t\t\tsequence.push(group);\n\t\t\treturn;\n\t\t}\n\t\tconst action = collect(entry, [index]);\n\t\tif (action) sequence.push(action);\n\t});\n\n\tif (issues.length > 0) return { success: false, issues };\n\treturn { success: true, data: sequence };\n}\n"],
5
- "mappings": "AAkOO,SAASA,GAAgD,CAC/D,OAAO,SACNC,EAC6D,CAC7D,OAAOA,CACR,CACD,CCvOA,OAAS,kBAAAC,MAA6C,0BAuG/C,IAAMC,EAAN,KAMP,CACUC,GAET,YAAYC,EAAyC,CACpD,KAAKD,GAAYF,EAAe,SAAUG,CAAa,CACxD,CAEA,IAAI,MAAe,CAClB,OAAO,KAAKD,GAAU,IACvB,C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AASe,EACfR,EACAS,EACAf,EAC8B,CAC9B,GAAI,CAAC,MAAM,QAAQe,CAAK,EACvB,MAAO,CAAE,QAAS,GAAO,OAAQ,CAACrB,EAAQ,CAAC,EAAG,2BAA2B,CAAC,CAAE,EAG7E,IAAMO,EAAgC,CAAC,EACjCe,EAAwE,CAAC,EACzEC,EAAU,CAAClB,EAAgBJ,IAAwE,CACxG,IAAMuB,EAASb,EAAoBC,EAAUP,EAAOJ,EAAMK,CAAO,EACjE,GAAIkB,EAAO,GAAI,OAAOA,EAAO,OAC7BjB,EAAO,KAAK,GAAGiB,EAAO,MAAM,CAE7B,EAkBA,OAhBAH,EAAM,QAAQ,CAAChB,EAAgBK,IAAU,CACxC,GAAI,MAAM,QAAQL,CAAK,EAAG,CACzB,GAAIA,EAAM,SAAW,EAAG,CACvBE,EAAO,KAAKP,EAAQ,CAACU,CAAK,EAAG,mDAAmD,CAAC,EACjF,MACD,CACA,IAAMe,EAAQpB,EACZ,IAAI,CAACqB,EAAiBC,IAAgBJ,EAAQG,EAAQ,CAAChB,EAAOiB,CAAW,CAAC,CAAC,EAC3E,OAAQC,GAA4CA,IAAW,MAAS,EAC1EN,EAAS,KAAKG,CAAK,EACnB,MACD,CACA,IAAMG,EAASL,EAAQlB,EAAO,CAACK,CAAK,CAAC,EACjCkB,GAAQN,EAAS,KAAKM,CAAM,CACjC,CAAC,EAEGrB,EAAO,OAAS,EAAU,CAAE,QAAS,GAAO,OAAAA,CAAO,EAChD,CAAE,QAAS,GAAM,KAAMe,CAAS,CACxC",
6
- "names": ["defineAction", "registration", "createRegistry", "ActionRegistry", "#registry", "registrations", "key", "type", "Logger", "logger", "isMetadataContext", "value", "isGroup", "entry", "isCancellation", "error", "signal", "ActionDispatcher", "registry", "actions", "trigger", "context", "metadata", "triggeredBy", "outer", "enhancedContext", "results", "sequenceIndex", "controller", "abortWithOuter", "run", "action", "groupIndex", "match", "registration", "result", "cancelled", "cancellationRequested", "groupResults", "executed", "candidate", "input", "existingMetadata", "safeParseStandardSchema", "isRecord", "value", "issueAt", "path", "message", "BASE_KEYS", "checkBase", "entry", "options", "issues", "triggers", "trigger", "index", "parseEntry", "registry", "registration", "base", "own", "key", "result", "issue", "data", "parseActions", "input", "sequence", "collect", "parsed", "group", "member", "memberIndex", "action"]
4
+ "sourcesContent": ["import type { BaseRegistration, RegistrationMetadata } from '@schema-engine/registry';\n\n/**\n * The keys every action entry carries, owned by the engine.\n *\n * @template TType - The action type identifier\n *\n * @remarks\n * {@link parseActions} checks these keys itself and hands only the rest to the registration's schema. A\n * registration's config type is this interface plus the output of its schema, which lists the action's own\n * arguments and none of these keys: `ActionConfigBase<'post'> & { endpoint: string }`.\n */\nexport interface ActionConfigBase<TType extends string = string> {\n\t/** Unique identifier for this action instance */\n\tid: string;\n\t/** Action type - references a registered action */\n\t$type: TType;\n\t/** Whether this action is enabled */\n\tenabled?: boolean;\n\t/** Custom triggers for this specific action instance */\n\ttriggers?: readonly string[];\n}\n\n/**\n * Action Runtime Context\n *\n * Context received by action handlers at execution time.\n * The dispatcher creates this runtime shape by enriching the caller-provided\n * base context with the current action config and trigger.\n *\n * @template TConfig - Action configuration type\n * @template TBaseContext - Caller-provided base context\n * @template TTrigger - Trigger/event type\n */\nexport type ActionRuntimeContext<TConfig = unknown, TBaseContext = unknown, TTrigger = string> = TBaseContext & {\n\t/** Current action configuration */\n\tconfig: TConfig;\n\t/** Trigger/event that caused this action to execute */\n\ttrigger: TTrigger;\n\t/** Action config that triggered nested execution, when applicable */\n\ttriggeredBy?: TConfig;\n\t/** Cooperative cancellation for the current action. */\n\tsignal: AbortSignal;\n};\n\n/**\n * Action Execution Result\n *\n * Standardized return type for all action handlers.\n * Provides success status, messages, data, and flow control information.\n *\n * @template TData - Type of data returned by the action\n *\n * @example Success Result\n * ```typescript\n * return {\n * success: true,\n * message: \"Action completed successfully\",\n * data: { submissionId: \"abc123\" },\n * shouldContinue: true\n * };\n * ```\n *\n * @example Error Result\n * ```typescript\n * return {\n * success: false,\n * error: \"Validation failed\",\n * shouldContinue: false,\n * };\n * ```\n */\nexport interface ActionExecutionResult<TData = unknown> {\n\t/** Whether the action executed successfully */\n\tsuccess: boolean;\n\t/** Success message to display or log */\n\tmessage?: string;\n\t/** Error message if action failed */\n\terror?: string;\n\t/** Original error thrown by the handler, when available. */\n\tcause?: unknown;\n\t/** Data returned by the action (e.g., API response) */\n\tdata?: TData;\n\t/**\n\t * Whether to continue after this action fails.\n\t *\n\t * @remarks\n\t * The dispatcher stops after a failed action only when this is `false`. Form submissions also\n\t * fail only for unsuccessful actions with `shouldContinue: false`; omitted or `true` continues.\n\t */\n\tshouldContinue?: boolean;\n}\n\n/** An action result annotated by the dispatcher for correlation with its configuration. */\nexport type ActionDispatchResult<TData = unknown> = ActionExecutionResult<TData> & {\n\tactionId: string;\n\tsequenceIndex: number;\n\tgroupIndex?: number;\n\tstatus: 'succeeded' | 'failed' | 'cancelled';\n\tcancellationRequested: boolean;\n};\n\n/** A sequence entry is either one action or a group that runs concurrently. */\nexport type ActionSequenceEntry<TConfig extends ActionConfigBase> = TConfig | readonly TConfig[];\n\ndeclare const PARSED_ACTION: unique symbol;\n\n/**\n * An action config that {@link parseActions} checked against its registration's schema.\n *\n * @remarks\n * The brand exists in the type only. {@link parseActions} is the one function that produces it, and\n * {@link ActionDispatcher.dispatch} accepts nothing else, so an action that arrived as raw JSON or an object\n * literal cannot reach a handler unchecked.\n */\nexport type ParsedAction<TConfig extends ActionConfigBase = ActionConfigBase> = TConfig & {\n\treadonly [PARSED_ACTION]: true;\n};\n\n/** The sequence {@link parseActions} returns and {@link ActionDispatcher.dispatch} runs. */\nexport type ParsedActionSequence<TConfig extends ActionConfigBase = ActionConfigBase> = readonly ActionSequenceEntry<\n\tParsedAction<TConfig>\n>[];\n\n/**\n * Action Handler Function Type\n *\n * Function signature for action handlers using the current runtime-enrichment model.\n * At execution time, the domain context is enriched with the current action config\n * and trigger before the handler is called.\n *\n * @template TConfig - The action configuration type\n * @template TContext - Domain-specific base context data\n * @template TTrigger - The trigger/event type\n * @template TData - The type of data returned by the action\n */\nexport type ActionHandler<TConfig = unknown, TContext = unknown, TTrigger = string, TData = unknown> = (\n\tcontext: ActionRuntimeContext<TConfig, TContext, TTrigger>,\n) => Promise<ActionExecutionResult<TData>> | ActionExecutionResult<TData>;\n\n/**\n * Action Metadata\n *\n * Descriptive information about an action type.\n *\n * @template TTrigger - The trigger/event type\n */\nexport interface ActionMetadata<TTrigger = string> extends RegistrationMetadata {\n\t/** Icon identifier (optional) */\n\ticon?: string;\n\t/** Default triggers that this action responds to */\n\tdefaultTriggers?: readonly TTrigger[];\n\t/** Category for grouping actions (optional) */\n\tcategory?: string;\n}\n\n/**\n * Action Registration\n *\n * Configuration object for registering actions in an action registry.\n * Used to define action behavior, validation, and metadata. The schema describes the action's own\n * arguments; {@link ActionConfigBase} keys are checked by {@link parseActions}.\n *\n * @template TConfig - Action configuration type\n * @template TBaseContext - Caller-provided base context data\n * @template TTrigger - The trigger/event type\n *\n * @example\n * ```typescript\n * import * as z from 'zod/mini';\n *\n * const logAction: ActionRegistration<LogActionConfig, AppContext, AppTrigger> = {\n * $type: 'log',\n * schema: z.object({\n * level: z.enum(['info', 'warn', 'error']),\n * message: z.string(),\n * }),\n * metadata: {\n * name: 'Log Message',\n * description: 'Logs a message to the console',\n * defaultTriggers: ['change', 'submit'],\n * },\n * execute: async (context) => {\n * console[context.config.level](context.config.message);\n * return { success: true };\n * },\n * };\n * ```\n */\nexport interface ActionRegistration<\n\tTConfig extends ActionConfigBase = ActionConfigBase,\n\tTBaseContext = unknown,\n\tTTrigger = string,\n\tTData = unknown,\n> extends BaseRegistration<TConfig, ActionMetadata<TTrigger>> {\n\t/** Unique action type identifier */\n\t$type: TConfig['$type'];\n\t/**\n\t * Action execution function.\n\t * Receives the runtime context produced by the dispatcher.\n\t */\n\texecute: ActionHandler<TConfig, TBaseContext, TTrigger, TData>;\n}\n\n/** Input for trigger-based sequential dispatch. */\nexport interface ActionDispatchInput<\n\tTConfig extends ActionConfigBase = ActionConfigBase,\n\tTBaseContext = unknown,\n\tTTrigger = string,\n> {\n\ttrigger: TTrigger;\n\tactions: ParsedActionSequence<TConfig>;\n\tcontext: TBaseContext;\n\ttriggeredBy?: TConfig;\n\tmetadata?: Record<string, unknown>;\n\t/**\n\t * Cancels the dispatch from outside.\n\t *\n\t * @remarks It is chained into the signal each action receives, and the sequence runs no further entry once it is aborted.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/**\n * Create a strongly typed action-definition helper for one domain.\n */\nexport function defineAction<TBaseContext, TTrigger = string>() {\n\treturn function <TConfig extends ActionConfigBase, TData = unknown>(\n\t\tregistration: ActionRegistration<TConfig, TBaseContext, TTrigger, TData>,\n\t): ActionRegistration<TConfig, TBaseContext, TTrigger, TData> {\n\t\treturn registration;\n\t};\n}\n", "import type { ActionRegistration } from './types';\nimport { createRegistry, type ReadOnlyRegistry } from '@schema-engine/registry';\n\n/**\n * Registry storage must be able to hold heterogeneous action config shapes.\n * `any` is used here as an existential placeholder for that internal storage boundary.\n */\ntype AnyActionRegistration<TBaseContext, TTrigger> = ActionRegistration<any, TBaseContext, TTrigger>;\n\n/**\n * Action Registry Provider\n *\n * Interface for objects that can provide action registrations.\n * This allows the ActionDispatcher to look up action handlers without\n * depending on a specific registry implementation.\n *\n * @template TContext - Domain-specific context data\n * @template TTrigger - The trigger/event type\n * @template TRegistration - The registration type (defaults to ActionRegistration)\n *\n * @example\n * ```typescript\n * class MyActionRegistry implements ActionRegistryProvider<MyContext, MyTrigger> {\n * private actions = new Map<string, ActionRegistration<any, MyContext, MyTrigger>>();\n *\n * register(action: ActionRegistration<any, MyContext, MyTrigger>): void {\n * this.actions.set(action.$type, action);\n * }\n *\n * getAction(type: string): ActionRegistration<any, MyContext, MyTrigger> | undefined {\n * return this.actions.get(type);\n * }\n *\n * getActionTypes(): string[] {\n * return Array.from(this.actions.keys());\n * }\n * }\n * ```\n */\nexport interface ActionRegistryProvider<\n\tTBaseContext = unknown,\n\tTTrigger = string,\n\tTRegistration extends AnyActionRegistration<TBaseContext, TTrigger> = AnyActionRegistration<TBaseContext, TTrigger>,\n> {\n\t/**\n\t * Get an action registration by type\n\t *\n\t * @param type - The action type identifier\n\t * @returns The action registration or undefined if not found\n\t */\n\tgetAction(type: string): TRegistration | undefined;\n\n\t/**\n\t * Get all registered action types\n\t *\n\t * @returns Array of action type identifiers\n\t */\n\tgetActionTypes(): string[];\n}\n\n/**\n * Action Registry\n *\n * Generic, domain-agnostic, read-only registry of action registrations, built\n * from a list on the shared {@link createRegistry} mechanism.\n *\n * @template TContext - Domain-specific context data\n * @template TTrigger - The trigger/event type\n *\n * @remarks\n * A later registration with the same `$type` replaces an earlier one without a\n * warning. Every winning schema must implement Standard Schema; the constructor\n * throws naming the offending `$type`. The registrations are held in a private\n * field, so the registry cannot be changed, and subclasses may add their own fields. To register actions at runtime, implement\n * {@link ActionRegistryProvider} on a `BaseRegistry` subclass instead.\n *\n * @example\n * ```typescript\n * import { ActionRegistry } from '@schema-engine/actions';\n *\n * type MyTrigger = 'submit' | 'change';\n * import { Logger } from '@ecopages/logger';\n * type MyContext = { formId: string; data: Record<string, unknown> };\n *\n * const logger = new Logger('[my-app]');\n * const registry = new ActionRegistry<MyContext, MyTrigger>([\n * {\n * $type: 'log',\n * schema: logSchema,\n * metadata: {\n * name: 'Log Action',\n * description: 'Logs data',\n * defaultTriggers: ['change'],\n * },\n * execute: async (context) => {\n * logger.info(context);\n * return { success: true };\n * },\n * },\n * ]);\n *\n * const action = registry.getAction('log');\n * ```\n */\nexport class ActionRegistry<\n\tTBaseContext = unknown,\n\tTTrigger = string,\n\tTRegistration extends AnyActionRegistration<TBaseContext, TTrigger> = AnyActionRegistration<TBaseContext, TTrigger>,\n>\n\timplements ReadOnlyRegistry<TRegistration>, ActionRegistryProvider<TBaseContext, TTrigger, TRegistration>\n{\n\treadonly #registry: ReadOnlyRegistry<TRegistration>;\n\n\tconstructor(registrations: readonly TRegistration[]) {\n\t\tthis.#registry = createRegistry('Action', registrations);\n\t}\n\n\tget kind(): string {\n\t\treturn this.#registry.kind;\n\t}\n\n\tget size(): number {\n\t\treturn this.#registry.size;\n\t}\n\n\tget(key: string): TRegistration | undefined {\n\t\treturn this.#registry.get(key);\n\t}\n\n\thas(key: string): boolean {\n\t\treturn this.#registry.has(key);\n\t}\n\n\tall(): readonly TRegistration[] {\n\t\treturn this.#registry.all();\n\t}\n\n\tkeys(): readonly string[] {\n\t\treturn this.#registry.keys();\n\t}\n\n\t/**\n\t * Get an action registration by type\n\t */\n\tgetAction(type: string): TRegistration | undefined {\n\t\treturn this.get(type);\n\t}\n\n\t/**\n\t * Get all registered action types\n\t */\n\tgetActionTypes(): string[] {\n\t\treturn [...this.keys()];\n\t}\n}\n", "import type {\n\tActionConfigBase,\n\tActionDispatchInput,\n\tActionDispatchResult,\n\tActionExecutionResult,\n\tActionSequenceEntry,\n\tParsedAction,\n\tParsedActionSequence,\n} from './types';\nimport type { ActionRegistryProvider } from './registry';\nimport { Logger } from '@ecopages/logger';\n\nconst logger = new Logger('[@schema-engine/actions]');\n\ntype MetadataContext = { metadata?: Record<string, unknown> };\n\nfunction isMetadataContext(value: unknown): value is MetadataContext {\n\treturn typeof value === 'object' && value !== null;\n}\n\nfunction isGroup<T extends ActionConfigBase>(entry: ActionSequenceEntry<T>): entry is readonly T[] {\n\treturn Array.isArray(entry);\n}\n\nfunction isCancellation(error: unknown, signal: AbortSignal): boolean {\n\treturn signal.aborted && error instanceof Error && error.name === 'AbortError';\n}\n\ntype ActionMatch<TBaseContext, TTrigger> =\n\t| { runs: false }\n\t| { runs: true; registration: ReturnType<ActionRegistryProvider<TBaseContext, TTrigger>['getAction']> };\n\n/** Dispatches actions in sequence, allowing groups to execute concurrently. */\nexport class ActionDispatcher<TBaseContext = unknown, TTrigger = string> {\n\tconstructor(private readonly registry: ActionRegistryProvider<TBaseContext, TTrigger>) {}\n\n\tasync dispatch<TConfig extends ActionConfigBase>({\n\t\tactions,\n\t\ttrigger,\n\t\tcontext,\n\t\tmetadata,\n\t\ttriggeredBy,\n\t\tsignal: outer,\n\t}: ActionDispatchInput<TConfig, TBaseContext, TTrigger>): Promise<ActionDispatchResult[]> {\n\t\tif (!actions?.length) return [];\n\t\tconst enhancedContext = metadata ? this.mergeMetadata(context, metadata) : context;\n\t\tconst results: ActionDispatchResult[] = [];\n\t\tfor (const [sequenceIndex, entry] of actions.entries()) {\n\t\t\tif (outer?.aborted) break;\n\t\t\tconst controller = new AbortController();\n\t\t\tconst abortWithOuter = () => controller.abort(outer?.reason);\n\t\t\touter?.addEventListener('abort', abortWithOuter, { once: true });\n\t\t\tconst run = async (\n\t\t\t\taction: ParsedAction<TConfig>,\n\t\t\t\tgroupIndex?: number,\n\t\t\t): Promise<ActionDispatchResult | undefined> => {\n\t\t\t\tconst match = this.match(action, trigger);\n\t\t\t\tif (!match.runs) return undefined;\n\t\t\t\tconst { registration } = match;\n\t\t\t\tif (!registration) {\n\t\t\t\t\tconst error = `No handler registered for action type: ${action.$type}`;\n\t\t\t\t\tlogger.error(error, { actionId: action.id, availableActions: this.registry.getActionTypes() });\n\t\t\t\t\treturn {\n\t\t\t\t\t\tactionId: action.id,\n\t\t\t\t\t\tsequenceIndex,\n\t\t\t\t\t\t...(groupIndex === undefined ? {} : { groupIndex }),\n\t\t\t\t\t\tstatus: 'failed',\n\t\t\t\t\t\tcancellationRequested: false,\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror,\n\t\t\t\t\t\tshouldContinue: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tlogger.debug(`Executing action: ${action.id} (${action.$type})`);\n\t\t\t\tlet result: ActionExecutionResult;\n\t\t\t\tlet cancelled = false;\n\t\t\t\ttry {\n\t\t\t\t\tresult = await registration.execute({\n\t\t\t\t\t\t...enhancedContext,\n\t\t\t\t\t\tconfig: action,\n\t\t\t\t\t\ttrigger,\n\t\t\t\t\t\tsignal: controller.signal,\n\t\t\t\t\t\t...(triggeredBy ? { triggeredBy } : {}),\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\tcancelled = isCancellation(error, controller.signal);\n\t\t\t\t\tresult = {\n\t\t\t\t\t\tsuccess: false,\n\t\t\t\t\t\terror: error instanceof Error ? error.message : String(error),\n\t\t\t\t\t\tcause: error,\n\t\t\t\t\t\tshouldContinue: true,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t\tconst cancellationRequested = controller.signal.aborted;\n\t\t\t\tif (!result.success && result.shouldContinue === false) controller.abort();\n\t\t\t\tif (!result.success) logger.warn(`Action ${action.id} failed`, result);\n\t\t\t\treturn {\n\t\t\t\t\t...result,\n\t\t\t\t\tactionId: action.id,\n\t\t\t\t\tsequenceIndex,\n\t\t\t\t\t...(groupIndex === undefined ? {} : { groupIndex }),\n\t\t\t\t\tstatus: cancelled ? 'cancelled' : result.success ? 'succeeded' : 'failed',\n\t\t\t\t\tcancellationRequested,\n\t\t\t\t};\n\t\t\t};\n\t\t\tlet groupResults: Array<ActionDispatchResult | undefined>;\n\t\t\ttry {\n\t\t\t\tgroupResults = isGroup(entry) ? await Promise.all(entry.map(run)) : [await run(entry)];\n\t\t\t} finally {\n\t\t\t\touter?.removeEventListener('abort', abortWithOuter);\n\t\t\t}\n\t\t\tconst executed = groupResults.filter((result): result is ActionDispatchResult => result !== undefined);\n\t\t\tresults.push(...executed);\n\t\t\tif (executed.some((result) => !result.success && result.shouldContinue === false)) break;\n\t\t}\n\t\treturn results;\n\t}\n\n\t/**\n\t * Whether `dispatch` would run, or report a missing handler for, at least one of the actions on this trigger.\n\t *\n\t * @remarks\n\t * Lets a caller skip building a context for a trigger no action answers. It checks the same conditions\n\t * `dispatch` does, so the two cannot disagree.\n\t */\n\thasMatching<TConfig extends ActionConfigBase>(actions: ParsedActionSequence<TConfig>, trigger: TTrigger): boolean {\n\t\treturn actions.some((entry) =>\n\t\t\tisGroup(entry) ? entry.some((action) => this.match(action, trigger).runs) : this.match(entry, trigger).runs,\n\t\t);\n\t}\n\n\t/**\n\t * @remarks\n\t * An action of an unregistered type always matches, so `dispatch` can report the missing handler. The\n\t * registration it looked up comes back so `dispatch` does not look it up again.\n\t */\n\tprivate match(action: ActionConfigBase, trigger: TTrigger): ActionMatch<TBaseContext, TTrigger> {\n\t\tif (action.enabled === false) return { runs: false };\n\t\tif (action.triggers !== undefined && !action.triggers.some((candidate) => candidate === trigger)) {\n\t\t\treturn { runs: false };\n\t\t}\n\t\tconst registration = this.registry.getAction(action.$type);\n\t\tconst implicit = action.triggers === undefined;\n\t\tif (implicit && registration && !(registration.metadata.defaultTriggers ?? []).includes(trigger)) {\n\t\t\treturn { runs: false };\n\t\t}\n\t\treturn { runs: true, registration };\n\t}\n\n\t/** @remarks Best-effort dispatch never rejects to its caller. */\n\tdispatchSync<TConfig extends ActionConfigBase>(input: ActionDispatchInput<TConfig, TBaseContext, TTrigger>): void {\n\t\tvoid this.dispatch(input).catch((error) => logger.error('dispatchSync failed:', error));\n\t}\n\n\tprivate mergeMetadata(context: TBaseContext, metadata: Record<string, unknown>): TBaseContext {\n\t\tif (!isMetadataContext(context)) return context;\n\t\tconst existingMetadata = context.metadata;\n\t\treturn {\n\t\t\t...context,\n\t\t\tmetadata: {\n\t\t\t\t...(typeof existingMetadata === 'object' && existingMetadata !== null ? existingMetadata : {}),\n\t\t\t\t...metadata,\n\t\t\t},\n\t\t};\n\t}\n}\n", "import {\n\tsafeParseNode,\n\tsafeParseStandardSchema,\n\tstandardSchema,\n\ttype BaseRegistration,\n\ttype NodeLookup,\n\ttype StandardSchemaIssue,\n} from '@schema-engine/registry';\nimport type { ActionConfigBase, ParsedAction, ParsedActionSequence } from './types';\n\n/** What {@link parseActions} needs of a registry: the registration of a `$type`, for its schema. */\nexport interface ActionSchemaLookup {\n\tgetAction(type: string): Pick<BaseRegistration, 'schema'> | undefined;\n}\n\n/** What a domain tells {@link parseActions} about the entries it accepts. */\nexport interface ParseActionsOptions {\n\t/**\n\t * The trigger names an entry's `triggers` may hold.\n\t *\n\t * @remarks Without it, any string is accepted, since the engine cannot know a domain's triggers.\n\t */\n\ttriggers?: readonly string[];\n\t/**\n\t * The sentence that follows the message of an action `$type` nothing registers, naming where to register it.\n\t *\n\t * @remarks Without it, the sentence is `Register it in the action registry.`. A domain that registers actions through its own entry point says that one.\n\t */\n\thint?: NodeLookup['hint'];\n}\n\n/**\n * What {@link parseActions} returns: the parsed sequence, or every issue found.\n *\n * @remarks\n * An issue is a Standard Schema issue whose `path` starts with the index of the entry, then the index inside\n * a group, then the path the schema reported (`[1, 0, 'endpoint']`). Each entry is checked by `safeParseNode`, so its\n * issues sit where that function puts them: an entry that is not an object at the entry, and a missing or unregistered\n * `$type` at `$type`. An unregistered `$type` says where to register it ({@link ParseActionsOptions.hint}). An empty group is an issue at its index.\n */\nexport type ParseActionsResult<TConfig extends ActionConfigBase = ActionConfigBase> =\n\t{ success: true; data: ParsedActionSequence<TConfig> } | { success: false; issues: StandardSchemaIssue[] };\n\nfunction isRecord(value: unknown): value is Record<PropertyKey, unknown> {\n\treturn typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction issueAt(path: ReadonlyArray<PropertyKey>, message: string): StandardSchemaIssue {\n\treturn { message, path };\n}\n\nconst DEFAULT_HINT = 'Register it in the action registry.';\n\n/** The envelope keys the engine checks itself; a registration's schema never sees them. */\nconst BASE_KEYS = ['id', '$type', 'enabled', 'triggers'] as const;\n\nfunction checkBase(\n\tentry: Record<PropertyKey, unknown>,\n\toptions: ParseActionsOptions | undefined,\n): StandardSchemaIssue[] {\n\tconst issues: StandardSchemaIssue[] = [];\n\tif (typeof entry.id !== 'string' || entry.id === '') {\n\t\tissues.push(issueAt(['id'], 'Action ID must be a non-empty string.'));\n\t}\n\tif (entry.enabled !== undefined && typeof entry.enabled !== 'boolean') {\n\t\tissues.push(issueAt(['enabled'], 'enabled must be a boolean.'));\n\t}\n\tconst { triggers } = entry;\n\tif (triggers === undefined) return issues;\n\tif (!Array.isArray(triggers)) {\n\t\tissues.push(issueAt(['triggers'], 'triggers must be an array of trigger names.'));\n\t\treturn issues;\n\t}\n\ttriggers.forEach((trigger: unknown, index) => {\n\t\tif (typeof trigger !== 'string') {\n\t\t\tissues.push(issueAt(['triggers', index], 'A trigger must be a string.'));\n\t\t} else if (options?.triggers && !options.triggers.includes(trigger)) {\n\t\t\tissues.push(\n\t\t\t\tissueAt(\n\t\t\t\t\t['triggers', index],\n\t\t\t\t\t`Unknown trigger '${trigger}'. Use one of: ${options.triggers.join(', ')}.`,\n\t\t\t\t),\n\t\t\t);\n\t\t}\n\t});\n\treturn issues;\n}\n\n/**\n * The schema of a whole entry: the envelope keys the engine checks, then the remaining keys checked by the\n * registration's schema, merged into the parsed action.\n *\n * @remarks\n * `safeParseNode` runs it only once it has found the registration, so the entry is an object with a registered\n * `$type`. Its issues are relative to the entry; `safeParseNode` puts the entry's path in front.\n */\nfunction entrySchema(\n\ttype: string,\n\town: BaseRegistration['schema'],\n\toptions: ParseActionsOptions | undefined,\n): BaseRegistration['schema'] {\n\treturn standardSchema((value) => {\n\t\tconst entry = value as Record<PropertyKey, unknown>;\n\t\tconst issues = checkBase(entry, options);\n\t\tconst base: Record<string, unknown> = {};\n\t\tconst rest: Record<string, unknown> = {};\n\t\tfor (const [key, field] of Object.entries(entry)) {\n\t\t\tif ((BASE_KEYS as readonly string[]).includes(key)) base[key] = field;\n\t\t\telse rest[key] = field;\n\t\t}\n\t\tconst result = safeParseStandardSchema(own, rest);\n\t\tif (!result.success) return { issues: [...issues, ...result.error.issues] };\n\t\tconst { data } = result;\n\t\tif (!isRecord(data)) {\n\t\t\tconst message = `Invalid action configuration for '${type}': the schema must return an object.`;\n\t\t\treturn { issues: [...issues, issueAt([], message)] };\n\t\t}\n\t\tif (issues.length > 0) return { issues };\n\t\treturn { value: { ...data, ...base, id: entry.id, $type: type } };\n\t});\n}\n\n/**\n * Check serialized actions against their registrations, and return them as {@link ParsedAction}s.\n *\n * @param registry - Where each entry's `$type` finds its registration and schema\n * @param input - The sequence as it arrived, for example the result of `JSON.parse`: entries, where an array entry is a group\n * @param options - What the domain adds, such as the trigger names it accepts\n *\n * @remarks\n * This is the only way to produce a {@link ParsedAction}, and so the only way to a call of\n * {@link ActionDispatcher.dispatch}. Every entry is checked, so a sequence with two bad entries reports both.\n *\n * Each entry is a node, checked with `safeParseNode` from `@schema-engine/registry` like any other node. The engine\n * owns the keys every entry carries: `id` (a non-empty string), `$type` (a registered one), `enabled` and\n * `triggers`. It checks them itself, then hands the remaining keys to the registration's schema, which describes\n * the action's own arguments only. The result is those keys merged with what the schema returned, so its defaults and\n * transforms apply. `TConfig` is the caller's claim about the result; the parse itself checks the schemas, not that claim.\n *\n * @throws {Error} When a registration's schema validates asynchronously, which is a misuse of the registry.\n */\nexport function parseActions<TConfig extends ActionConfigBase = ActionConfigBase>(\n\tregistry: ActionSchemaLookup,\n\tinput: unknown,\n\toptions?: ParseActionsOptions,\n): ParseActionsResult<TConfig> {\n\tif (!Array.isArray(input)) {\n\t\treturn { success: false, issues: [issueAt([], 'Actions must be an array.')] };\n\t}\n\n\tconst entries: NodeLookup<Pick<BaseRegistration, 'schema'>> = {\n\t\tget(type) {\n\t\t\tconst registration = registry.getAction(type);\n\t\t\treturn registration && { schema: entrySchema(type, registration.schema, options) };\n\t\t},\n\t\thint: options?.hint ?? DEFAULT_HINT,\n\t};\n\tconst issues: StandardSchemaIssue[] = [];\n\tconst sequence: Array<ParsedAction<TConfig> | Array<ParsedAction<TConfig>>> = [];\n\tconst collect = (entry: unknown, path: ReadonlyArray<PropertyKey>): ParsedAction<TConfig> | undefined => {\n\t\tconst parsed = safeParseNode(entries, entry, path);\n\t\tif (parsed.success) return parsed.data as ParsedAction<TConfig>;\n\t\tissues.push(...parsed.issues);\n\t\treturn undefined;\n\t};\n\n\tinput.forEach((entry: unknown, index) => {\n\t\tif (Array.isArray(entry)) {\n\t\t\tif (entry.length === 0) {\n\t\t\t\tissues.push(issueAt([index], 'A group of actions must hold at least one action.'));\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst group = entry\n\t\t\t\t.map((member: unknown, memberIndex) => collect(member, [index, memberIndex]))\n\t\t\t\t.filter((action): action is ParsedAction<TConfig> => action !== undefined);\n\t\t\tsequence.push(group);\n\t\t\treturn;\n\t\t}\n\t\tconst action = collect(entry, [index]);\n\t\tif (action) sequence.push(action);\n\t});\n\n\tif (issues.length > 0) return { success: false, issues };\n\treturn { success: true, data: sequence };\n}\n"],
5
+ "mappings": "AAkOO,SAASA,GAAgD,CAC/D,OAAO,SACNC,EAC6D,CAC7D,OAAOA,CACR,CACD,CCvOA,OAAS,kBAAAC,MAA6C,0BAuG/C,IAAMC,EAAN,KAMP,CACUC,GAET,YAAYC,EAAyC,CACpD,KAAKD,GAAYF,EAAe,SAAUG,CAAa,CACxD,CAEA,IAAI,MAAe,CAClB,OAAO,KAAKD,GAAU,IACvB,CAEA,IAAI,MAAe,CAClB,OAAO,KAAKA,GAAU,IACvB,CAEA,IAAIE,EAAwC,CAC3C,OAAO,KAAKF,GAAU,IAAIE,CAAG,CAC9B,CAEA,IAAIA,EAAsB,CACzB,OAAO,KAAKF,GAAU,IAAIE,CAAG,CAC9B,CAEA,KAAgC,CAC/B,OAAO,KAAKF,GAAU,IAAI,CAC3B,CAEA,MAA0B,CACzB,OAAO,KAAKA,GAAU,KAAK,CAC5B,CAKA,UAAUG,EAAyC,CAClD,OAAO,KAAK,IAAIA,CAAI,CACrB,CAKA,gBAA2B,CAC1B,MAAO,CAAC,GAAG,KAAK,KAAK,CAAC,CACvB,CACD,EChJA,OAAS,UAAAC,MAAc,mBAEvB,IAAMC,EAAS,IAAID,EAAO,0BAA0B,EAIpD,SAASE,EAAkBC,EAA0C,CACpE,OAAO,OAAOA,GAAU,UAAYA,IAAU,IAC/C,CAEA,SAASC,EAAoCC,EAAsD,CAClG,OAAO,MAAM,QAAQA,CAAK,CAC3B,CAEA,SAASC,EAAeC,EAAgBC,EAA8B,CACrE,OAAOA,EAA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CAAS,CACxC",
6
+ "names": ["defineAction", "registration", "createRegistry", "ActionRegistry", "#registry", "registrations", "key", "type", "Logger", "logger", "isMetadataContext", "value", "isGroup", "entry", "isCancellation", "error", "signal", "ActionDispatcher", "registry", "actions", "trigger", "context", "metadata", "triggeredBy", "outer", "enhancedContext", "results", "sequenceIndex", "controller", "abortWithOuter", "run", "action", "groupIndex", "match", "registration", "result", "cancelled", "cancellationRequested", "groupResults", "executed", "candidate", "input", "existingMetadata", "safeParseNode", "safeParseStandardSchema", "standardSchema", "isRecord", "value", "issueAt", "path", "message", "DEFAULT_HINT", "BASE_KEYS", "checkBase", "entry", "options", "issues", "triggers", "trigger", "index", "entrySchema", "type", "own", "base", "rest", "key", "field", "result", "data", "parseActions", "registry", "input", "entries", "registration", "sequence", "collect", "parsed", "group", "member", "memberIndex", "action"]
7
7
  }
@@ -1,4 +1,4 @@
1
- import { type BaseRegistration, type StandardSchemaIssue } from '@schema-engine/registry';
1
+ import { type BaseRegistration, type NodeLookup, type StandardSchemaIssue } from '@schema-engine/registry';
2
2
  import type { ActionConfigBase, ParsedActionSequence } from './types';
3
3
  /** What {@link parseActions} needs of a registry: the registration of a `$type`, for its schema. */
4
4
  export interface ActionSchemaLookup {
@@ -12,14 +12,21 @@ export interface ParseActionsOptions {
12
12
  * @remarks Without it, any string is accepted, since the engine cannot know a domain's triggers.
13
13
  */
14
14
  triggers?: readonly string[];
15
+ /**
16
+ * The sentence that follows the message of an action `$type` nothing registers, naming where to register it.
17
+ *
18
+ * @remarks Without it, the sentence is `Register it in the action registry.`. A domain that registers actions through its own entry point says that one.
19
+ */
20
+ hint?: NodeLookup['hint'];
15
21
  }
16
22
  /**
17
23
  * What {@link parseActions} returns: the parsed sequence, or every issue found.
18
24
  *
19
25
  * @remarks
20
26
  * An issue is a Standard Schema issue whose `path` starts with the index of the entry, then the index inside
21
- * a group, then the path the schema reported (`[1, 0, 'endpoint']`). An entry that is not an action object
22
- * with a `$type`, and a `$type` no registration answers, are issues at `$type`. An empty group is an issue at its index.
27
+ * a group, then the path the schema reported (`[1, 0, 'endpoint']`). Each entry is checked by `safeParseNode`, so its
28
+ * issues sit where that function puts them: an entry that is not an object at the entry, and a missing or unregistered
29
+ * `$type` at `$type`. An unregistered `$type` says where to register it ({@link ParseActionsOptions.hint}). An empty group is an issue at its index.
23
30
  */
24
31
  export type ParseActionsResult<TConfig extends ActionConfigBase = ActionConfigBase> = {
25
32
  success: true;
@@ -39,7 +46,8 @@ export type ParseActionsResult<TConfig extends ActionConfigBase = ActionConfigBa
39
46
  * This is the only way to produce a {@link ParsedAction}, and so the only way to a call of
40
47
  * {@link ActionDispatcher.dispatch}. Every entry is checked, so a sequence with two bad entries reports both.
41
48
  *
42
- * The engine owns the keys every entry carries: `id` (a non-empty string), `$type` (a registered one), `enabled` and
49
+ * Each entry is a node, checked with `safeParseNode` from `@schema-engine/registry` like any other node. The engine
50
+ * owns the keys every entry carries: `id` (a non-empty string), `$type` (a registered one), `enabled` and
43
51
  * `triggers`. It checks them itself, then hands the remaining keys to the registration's schema, which describes
44
52
  * the action's own arguments only. The result is those keys merged with what the schema returned, so its defaults and
45
53
  * transforms apply. `TConfig` is the caller's claim about the result; the parse itself checks the schemas, not that claim.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@schema-engine/actions",
3
3
  "type": "module",
4
- "version": "0.5.0",
4
+ "version": "0.5.2",
5
5
  "description": "Registered actions that run from plain data: serializable workflows of sequential and parallel steps, checked before they run",
6
6
  "keywords": [
7
7
  "schema-engine",
@@ -43,18 +43,16 @@
43
43
  },
44
44
  "dependencies": {
45
45
  "@ecopages/logger": "^0.2.3",
46
- "@schema-engine/registry": "^0.5.0"
46
+ "@schema-engine/registry": "^0.5.2"
47
47
  },
48
48
  "devDependencies": {
49
49
  "esbuild": "^0.27.0",
50
50
  "tsc-alias": "^1.8.16",
51
- "vitest": "^4.0.13",
51
+ "typescript": "^5.9.3",
52
+ "vitest": "^5.1.1",
52
53
  "zod": "^4.0.17",
53
54
  "@schema-engine/scripts": "^0.0.0"
54
55
  },
55
- "peerDependencies": {
56
- "typescript": "^5"
57
- },
58
56
  "scripts": {
59
57
  "build:lib": "pnpm clean && pnpm build:files && pnpm build:types",
60
58
  "build:files": "node ./build.ts",
package/skill/SKILL.md CHANGED
@@ -19,7 +19,7 @@ This file is the router. It defines the concepts once; the references assume the
19
19
  ## Core concepts
20
20
 
21
21
  - **registration**: `{ $type, schema, metadata, ... }`, where `$type` is the stable key, `schema` is any Standard Schema that describes its config, and `metadata` names it. Elements, recipes, actions, validation rules and appearance axes are all registrations.
22
- - **registry**: a read-only registry, `createRegistry(kind, registrations)` from `@schema-engine/registry`, built once from a list. The last registration of a `$type` wins without a warning, which is how you replace a built-in.
22
+ - **registry**: a read-only registry, `createRegistry(kind, registrations)` from `@schema-engine/registry`, built once from a list. The last registration of a `$type` wins without a warning, which is how you replace a built-in; pass `{ duplicates: 'error' }` to make a repeat a build error instead.
23
23
  - **document**: serializable data whose every node names a registration by `$type`. It is checked against the registrations at the boundary, so what is rendered or run has passed its schema.
24
24
  - **action**: a registration with `execute` that runs on a trigger. Actions run as a sequence, an inner array is a parallel group, and a failure that sets `shouldContinue: false` stops what follows and cancels the group's siblings through their `signal`.
25
25
 
@@ -27,7 +27,7 @@ This file is the router. It defines the concepts once; the references assume the
27
27
 
28
28
  - **config**: a form is plain data, a `FormConfig` of steps holding elements, each with a `$type`, a `name`, `rules` and `constraints`. `engine.defineForm()` (typed, in TypeScript) or `engine.validateForm(unknown)` (portable JSON) checks it against the engine's registrations and returns a frozen `NormalizedFormConfig` that the engine owns.
29
29
  - **container**: the form's state, a `FormStateContainer` from `@schema-engine/forms/state-container`. It owns the nested values, errors, warnings, touched and dirty marks, field-array row ids and the validation in flight. Paths are dotted (`contacts.1.email`) and `FORM_ROOT` is the form itself. Every change is a command (`setValue`, `blur`, `reportNative`, `validate`, `submit`, `reset`, `fieldArray`), and every read is a pure selector over an immutable snapshot.
30
- - **runtime**: `createFormRuntime` is the lifecycle every renderer shares. It builds the container and owns the submission, the wizard steps and their navigation, `form_mount` and `form_change`, and every action dispatch. A renderer supplies only what an element can do, such as focus.
30
+ - **runtime**: for renderer authors, `createFormRuntime` is the lifecycle every renderer shares, and a renderer creates one for each form it draws. It builds the container and owns the submission, the wizard steps and their navigation, `form_mount` and `form_change`, and every action dispatch. A renderer supplies only what an element can do, such as focus. An app does not create one: it gives the engine and a config to a renderer.
31
31
  - **issues and the formatter**: the engine reports what is wrong as an issue (`type`, `source`, `ruleId`, `params`, `message`) and never makes up text. `formatIssue`, a function of the application, turns an issue into the words shown, and falls back to the issue's own `message`.
32
32
 
33
33
  Outcomes use one vocabulary: a check or a submission ends `passed`, `invalid` or `overtaken`. `overtaken` means an edit or a reset outran the check, so there is no verdict and nothing to show.
@@ -49,31 +49,32 @@ A symbol has one import path. `@schema-engine/forms` has these entries: `.` (the
49
49
 
50
50
  Each package ships this router as its own `skill/SKILL.md` and its references in its `skill/reference/` folder, so a reference is `node_modules/@schema-engine/<package>/skill/reference/<file>`, and any installed package has the router. Read the rows of the packages the project depends on and skip the others: a package that is not installed has no file. The deployed site serves the latest version of the router and of every reference at `/skill/`, with the references flat at `/skill/reference/<file>`.
51
51
 
52
- | To do | Package | Reference |
53
- | ---------------------------------------------------------------------------- | ------------------------------ | ------------------------------------ |
54
- | Register something, build a registry, or read a YAML document | `@schema-engine/registry` | `reference/registry.md` |
55
- | Parse, dispatch or cancel actions outside a form | `@schema-engine/actions` | `reference/actions.md` |
56
- | Build a grid, an appearance axis or a layout theme | `@schema-engine/layout` | `reference/layout.md` |
57
- | Create an engine, author a config, use the container or the runtime directly | `@schema-engine/forms` | `reference/forms.md` |
58
- | Add a rule, explain a validation result, or translate messages | `@schema-engine/forms` | `reference/forms-validation.md` |
59
- | Handle submit, server errors, CSRF or wizard steps | `@schema-engine/forms` | `reference/forms-submission.md` |
60
- | Run code on a form event, or define a form action | `@schema-engine/forms` | `reference/forms-actions.md` |
61
- | Render a form in React, or use its hooks | `@schema-engine/forms-react` | `reference/forms-react.md` |
62
- | Write or change a React field widget, and test it | `@schema-engine/forms-react` | `reference/forms-react-widgets.md` |
63
- | Render a form in Radiant, or reach the container from an element | `@schema-engine/forms-radiant` | `reference/forms-radiant.md` |
64
- | Write or change a Radiant field widget, and test it | `@schema-engine/forms-radiant` | `reference/forms-radiant-widgets.md` |
52
+ | To do | Package | Reference |
53
+ | ---------------------------------------------------------------- | ------------------------------ | ------------------------------------ |
54
+ | Register something, build a registry, or read a YAML document | `@schema-engine/registry` | `reference/registry.md` |
55
+ | Parse, dispatch or cancel actions outside a form | `@schema-engine/actions` | `reference/actions.md` |
56
+ | Build a grid, an appearance axis or a layout theme | `@schema-engine/layout` | `reference/layout.md` |
57
+ | Create an engine, author a config, or use the container directly | `@schema-engine/forms` | `reference/forms.md` |
58
+ | Add a rule, explain a validation result, or translate messages | `@schema-engine/forms` | `reference/forms-validation.md` |
59
+ | Handle submit, server errors, CSRF or wizard steps | `@schema-engine/forms` | `reference/forms-submission.md` |
60
+ | Run code on a form event, or define a form action | `@schema-engine/forms` | `reference/forms-actions.md` |
61
+ | Render a form in React, or use its hooks | `@schema-engine/forms-react` | `reference/forms-react.md` |
62
+ | Write or change a React field widget, and test it | `@schema-engine/forms-react` | `reference/forms-react-widgets.md` |
63
+ | Render a form in Radiant, or reach the container from an element | `@schema-engine/forms-radiant` | `reference/forms-radiant.md` |
64
+ | Write or change a Radiant field widget, and test it | `@schema-engine/forms-radiant` | `reference/forms-radiant-widgets.md` |
65
65
 
66
66
  ## Documentation map
67
67
 
68
68
  The full documentation is at `/docs` on the deployed site. The LLM-exported corpus is `/llms.txt` (index) and `/docs-llm/<section>/<slug>.md` (page bodies).
69
69
 
70
- | Section | Path prefix |
71
- | ------------------------------ | ---------------------------------- |
72
- | Schema Engine | `/docs/schema-engine/introduction` |
73
- | `@schema-engine/registry` | `/docs/registry/overview` |
74
- | `@schema-engine/actions` | `/docs/actions/overview` |
75
- | `@schema-engine/forms` | `/docs/forms/overview` |
76
- | `@schema-engine/forms-react` | `/docs/forms-react/overview` |
77
- | `@schema-engine/forms-radiant` | `/docs/forms-radiant/overview` |
78
- | `@schema-engine/layout` | `/docs/layout/overview` |
79
- | Examples | `/docs/examples/overview` |
70
+ | Section | Path prefix |
71
+ | ------------------------------ | ----------------------------------------- |
72
+ | Schema Engine | `/docs/schema-engine/introduction` |
73
+ | `@schema-engine/registry` | `/docs/registry/overview` |
74
+ | `@schema-engine/actions` | `/docs/actions/overview` |
75
+ | `@schema-engine/forms` | `/docs/forms/overview` |
76
+ | `@schema-engine/forms-react` | `/docs/forms-react/overview` |
77
+ | `@schema-engine/forms-radiant` | `/docs/forms-radiant/overview` |
78
+ | `@schema-engine/layout` | `/docs/layout/overview` |
79
+ | Examples | `/docs/examples/overview` |
80
+ | Renderer authors | `/docs/renderer-authors/write-a-renderer` |
@@ -59,7 +59,7 @@ A registration is `{ $type, schema, metadata, execute }`; an instance is `{ $typ
59
59
 
60
60
  ## parseActions
61
61
 
62
- `input` is the sequence as it arrived. Each entry is validated with the schema of the registration its `$type` names, and `data` holds what the schema returned, so defaults and transforms apply. Every entry is checked, so two bad entries report both. An issue's `path` is the index of the entry, the index inside a group when the entry is one, then the path the schema reported (`[1, 0, 'channel']`); an entry with no string `$type`, and a `$type` no registration answers, are issues at `$type`.
62
+ `input` is the sequence as it arrived. Each entry is validated with the schema of the registration its `$type` names, and `data` holds what the schema returned, so defaults and transforms apply. Every entry is checked, so two bad entries report both. An issue's `path` is the index of the entry, the index inside a group when the entry is one, then the path the schema reported (`[1, 0, 'channel']`); each entry is checked with `safeParseNode` of the registry, so an entry that is not an object is an issue at its own path, and one with no string `$type` or a `$type` no registration answers is an issue at `$type`.
63
63
 
64
64
  ## Sequences, groups and cancellation
65
65