ts-rules-composer 1.3.0 → 1.5.0
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/README.md +149 -221
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +79 -39
- package/dist/index.d.ts +79 -39
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/mermaid.cjs +3 -0
- package/dist/mermaid.cjs.map +1 -0
- package/dist/mermaid.d.cts +11 -0
- package/dist/mermaid.d.ts +11 -0
- package/dist/mermaid.js +3 -0
- package/dist/mermaid.js.map +1 -0
- package/dist/rule-C3RlYflY.d.cts +37 -0
- package/dist/rule-C3RlYflY.d.ts +37 -0
- package/dist/to-graph-Dd9xksGt.js +2 -0
- package/dist/to-graph-Dd9xksGt.js.map +1 -0
- package/dist/to-graph-Dilv6lBr.cjs +2 -0
- package/dist/to-graph-Dilv6lBr.cjs.map +1 -0
- package/package.json +11 -1
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { t as Rule } from "./rule-C3RlYflY.js";
|
|
2
|
+
/**
|
|
3
|
+
* Renders a rule as Mermaid flowchart source, without running it.
|
|
4
|
+
*
|
|
5
|
+
* Skeleton: draws leaf rules and `pipeRules` sequences only.
|
|
6
|
+
*
|
|
7
|
+
* @example
|
|
8
|
+
* const text = toMermaid(pipeRules([hasItems, withinLimit]));
|
|
9
|
+
*/
|
|
10
|
+
export declare const toMermaid: <TInput, TError, TContext>(rule: Rule<TInput, TError, TContext>) => string;
|
|
11
|
+
//# sourceMappingURL=mermaid.d.ts.map
|
package/dist/mermaid.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import{t as e}from"./to-graph-Dd9xksGt.js";const t=e=>e.replace(/[^A-Za-z0-9_]/g,`_`),n=e=>e.replace(/[^\p{L}\p{N} _.,:/-]/gu,e=>`#${e.codePointAt(0)};`),r=(e,t)=>` ${e}["${n(t)}"]`,i=e=>{let n=t(e.id);if(e.kind===`sequence`&&e.steps.length>0){let t=e.steps.map(i);return{nodes:t.flatMap(e=>e.nodes),edges:[...t.flatMap(e=>e.edges),...t.slice(1).map((e,n)=>` ${t[n].exit} --> ${e.entry}`)],entry:t[0].entry,exit:t[t.length-1].exit}}let a=e.kind===`rule`?e.label:e.kind;return{nodes:[r(n,a)],edges:[],entry:n,exit:n}},a=t=>{let n=i(e(t).root);return[`flowchart TD`,` input([input])`,...n.nodes,` passed([passed])`,` input --> ${n.entry}`,...n.edges,` ${n.exit} --> passed`].join(`
|
|
2
|
+
`)};export{a as toMermaid};
|
|
3
|
+
//# sourceMappingURL=mermaid.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mermaid.js","names":["toGraph","mermaidId","id","escapeLabel","label","char","box","render","node","parts","part","i","toMermaid","body","rule"],"sources":["../src/lib/mermaid/to-mermaid.ts"],"sourcesContent":["import type { GraphNode } from \"../graph/node\";\nimport { toGraph } from \"../graph/to-graph\";\nimport type { Rule } from \"../types\";\n\ntype Fragment = {\n nodes: string[];\n edges: string[];\n entry: string;\n exit: string;\n};\n\nconst mermaidId = (id: string) => id.replace(/[^A-Za-z0-9_]/g, \"_\");\n\n/**\n * Labels come from function names and `named()` strings, so they are\n * untrusted. Everything except letters, digits, spaces and a few plain\n * punctuation marks becomes a numeric entity (`#40;`). That covers quotes,\n * brackets, `%` (directives), `#`, `;` and every kind of line break, so a label\n * can never leave its quoted string or start a statement of its own.\n */\nconst escapeLabel = (label: string) =>\n label.replace(/[^\\p{L}\\p{N} _.,:/-]/gu, (char) => `#${char.codePointAt(0)};`);\n\nconst box = (id: string, label: string) => ` ${id}[\"${escapeLabel(label)}\"]`;\n\nconst render = (node: GraphNode): Fragment => {\n const id = mermaidId(node.id);\n\n if (node.kind === \"sequence\" && node.steps.length > 0) {\n const parts = node.steps.map(render);\n return {\n nodes: parts.flatMap((part) => part.nodes),\n edges: [\n ...parts.flatMap((part) => part.edges),\n ...parts\n .slice(1)\n .map((part, i) => ` ${parts[i].exit} --> ${part.entry}`),\n ],\n entry: parts[0].entry,\n exit: parts[parts.length - 1].exit,\n };\n }\n\n // Leaves and kinds the skeleton cannot draw yet render as a single box.\n const label = node.kind === \"rule\" ? node.label : node.kind;\n return { nodes: [box(id, label)], edges: [], entry: id, exit: id };\n};\n\n/**\n * Renders a rule as Mermaid flowchart source, without running it.\n *\n * Skeleton: draws leaf rules and `pipeRules` sequences only.\n *\n * @example\n * const text = toMermaid(pipeRules([hasItems, withinLimit]));\n */\nexport const toMermaid = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): string => {\n const body = render(toGraph(rule).root);\n return [\n \"flowchart TD\",\n \" input([input])\",\n ...body.nodes,\n \" passed([passed])\",\n ` input --> ${body.entry}`,\n ...body.edges,\n ` ${body.exit} --> passed`,\n ].join(\"\\n\");\n};\n"],"mappings":"A,2CAWA,MAAMC,EAAa,GAAeC,EAAG,QAAQ,iBAAkB,GAAG,EAS5DC,EAAe,GACnBC,EAAM,QAAQ,yBAA2B,GAAS,IAAIC,EAAK,YAAY,CAAC,EAAE,EAAE,EAExEC,GAAO,EAAY,IAAkB,KAAKJ,EAAG,IAAIC,EAAYC,CAAK,EAAE,IAEpEG,EAAU,GAA8B,CAC5C,IAAML,EAAKD,EAAUO,EAAK,EAAE,EAE5B,GAAIA,EAAK,OAAS,YAAcA,EAAK,MAAM,OAAS,EAAG,CACrD,IAAMC,EAAQD,EAAK,MAAM,IAAID,CAAM,EACnC,MAAO,CACL,MAAOE,EAAM,QAAS,GAASC,EAAK,KAAK,EACzC,MAAO,CACL,GAAGD,EAAM,QAAS,GAASC,EAAK,KAAK,EACrC,GAAGD,EACA,MAAM,CAAC,CAAC,CACR,KAAK,EAAM,IAAM,KAAKA,EAAME,EAAE,CAAC,KAAK,OAAOD,EAAK,OAAO,CAC5D,EACA,MAAOD,EAAM,EAAE,CAAC,MAChB,KAAMA,EAAMA,EAAM,OAAS,EAAE,CAAC,IAChC,CACF,CAGA,IAAML,EAAQI,EAAK,OAAS,OAASA,EAAK,MAAQA,EAAK,KACvD,MAAO,CAAE,MAAO,CAACF,EAAIJ,EAAIE,CAAK,CAAC,EAAG,MAAO,CAAC,EAAG,MAAOF,EAAI,KAAMA,CAAG,CACnE,EAUaU,EACX,GACW,CACX,IAAMC,EAAON,EAAOP,EAAQc,CAAI,CAAC,CAAC,IAAI,EACtC,MAAO,CACL,eACA,mBACA,GAAGD,EAAK,MACR,qBACA,eAAeA,EAAK,QACpB,GAAGA,EAAK,MACR,KAAKA,EAAK,KAAK,YACjB,CAAC,CAAC,KAAK;CAAI,CACb,E"}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Represents the result of a rule evaluation.
|
|
3
|
+
* @template TError - The type of the error (defaults to string)
|
|
4
|
+
* @example
|
|
5
|
+
* // Passed result
|
|
6
|
+
* const passed: RuleResult = { status: "passed" };
|
|
7
|
+
*
|
|
8
|
+
* // Failed result
|
|
9
|
+
* const failed: RuleResult = {
|
|
10
|
+
* status: "failed",
|
|
11
|
+
* error: "Validation failed"
|
|
12
|
+
* };
|
|
13
|
+
*/
|
|
14
|
+
type RuleResult<TError = string> = {
|
|
15
|
+
readonly status: "passed";
|
|
16
|
+
} | {
|
|
17
|
+
readonly status: "failed";
|
|
18
|
+
readonly error: TError;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* A function that validates an input and returns a RuleResult.
|
|
22
|
+
* @template TInput - The type of the input to validate
|
|
23
|
+
* @template TError - The type of the error (defaults to string)
|
|
24
|
+
* @template TContext - The type of the context object (optional)
|
|
25
|
+
* @param input - The input value to validate
|
|
26
|
+
* @param context - Optional context object that can be used during validation
|
|
27
|
+
* @returns Either a Promise of RuleResult or RuleResult directly
|
|
28
|
+
* @example
|
|
29
|
+
* const isEven: Rule<number> = (input) => {
|
|
30
|
+
* return input % 2 === 0
|
|
31
|
+
* ? { status: "passed" }
|
|
32
|
+
* : { status: "failed", error: "Number must be even" };
|
|
33
|
+
* };
|
|
34
|
+
*/
|
|
35
|
+
type Rule<TInput, TError = string, TContext = unknown> = (input: TInput, context?: TContext) => Promise<RuleResult<TError>> | RuleResult<TError>;
|
|
36
|
+
export { RuleResult as n, Rule as t };
|
|
37
|
+
//# sourceMappingURL=rule-C3RlYflY.d.cts.map
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Represents the result of a rule evaluation.
|
|
3
|
+
* @template TError - The type of the error (defaults to string)
|
|
4
|
+
* @example
|
|
5
|
+
* // Passed result
|
|
6
|
+
* const passed: RuleResult = { status: "passed" };
|
|
7
|
+
*
|
|
8
|
+
* // Failed result
|
|
9
|
+
* const failed: RuleResult = {
|
|
10
|
+
* status: "failed",
|
|
11
|
+
* error: "Validation failed"
|
|
12
|
+
* };
|
|
13
|
+
*/
|
|
14
|
+
type RuleResult<TError = string> = {
|
|
15
|
+
readonly status: "passed";
|
|
16
|
+
} | {
|
|
17
|
+
readonly status: "failed";
|
|
18
|
+
readonly error: TError;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* A function that validates an input and returns a RuleResult.
|
|
22
|
+
* @template TInput - The type of the input to validate
|
|
23
|
+
* @template TError - The type of the error (defaults to string)
|
|
24
|
+
* @template TContext - The type of the context object (optional)
|
|
25
|
+
* @param input - The input value to validate
|
|
26
|
+
* @param context - Optional context object that can be used during validation
|
|
27
|
+
* @returns Either a Promise of RuleResult or RuleResult directly
|
|
28
|
+
* @example
|
|
29
|
+
* const isEven: Rule<number> = (input) => {
|
|
30
|
+
* return input % 2 === 0
|
|
31
|
+
* ? { status: "passed" }
|
|
32
|
+
* : { status: "failed", error: "Number must be even" };
|
|
33
|
+
* };
|
|
34
|
+
*/
|
|
35
|
+
type Rule<TInput, TError = string, TContext = unknown> = (input: TInput, context?: TContext) => Promise<RuleResult<TError>> | RuleResult<TError>;
|
|
36
|
+
export { RuleResult as n, Rule as t };
|
|
37
|
+
//# sourceMappingURL=rule-C3RlYflY.d.ts.map
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=Symbol.for(`ts-rules-composer.node`),t=(t,n)=>(Object.defineProperty(t,e,{value:n,enumerable:!1,writable:!1,configurable:!0}),t),n=t=>typeof t==`function`&&Object.hasOwn(t,e)?t[e]:void 0,r=e=>{let{name:t}=e;return t===``||t===`anonymous`||t.startsWith(`bound `)?void 0:t},i=()=>{let e=0,t=(t,n)=>n??r(t)??`rule #${++e}`,i=(e,r)=>{let o=n(e);if(!o||o.kind===`rule`)return{id:r,kind:`rule`,label:t(e,o?.label),...o?.params?{params:o.params}:{}};switch(o.kind){case`sequence`:return{id:r,kind:`sequence`,via:o.via,steps:o.steps.map((e,t)=>i(e,`${r}.steps.${t}`))};case`branch`:return{id:r,kind:`branch`,test:t(o.test,a(o.test)),...o.ifTrue?{ifTrue:i(o.ifTrue,`${r}.ifTrue`)}:{},...o.ifFalse?{ifFalse:i(o.ifFalse,`${r}.ifFalse`)}:{}}}};return i},a=e=>{let t=n(e);return t?.kind===`rule`?t.label:void 0},o=e=>({version:1,root:i()(e,`root`)});export{t as n,o as t};
|
|
2
|
+
//# sourceMappingURL=to-graph-Dd9xksGt.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"to-graph-Dd9xksGt.js","names":["NODE_KEY","attachNode","fn","node","readNode","usableName","name","createBuilder","unlabelled","labelOf","explicit","build","raw","step","id","index","readLabel","toGraph","rule"],"sources":["../src/lib/graph/node.ts","../src/lib/graph/labels.ts","../src/lib/graph/to-graph.ts"],"sourcesContent":["/**\n * Graph node primitives.\n *\n * This module must not import from `combinators/` or `helpers/`: combinators\n * import it, and `helpers/` and `combinators/` already depend on each other.\n */\n\n/** Any function a combinator may hold as a child (rule, predicate, accessor). */\nexport type Fn = (...args: never[]) => unknown;\n\n/**\n * Structure recorded by a combinator at construction time. Children are the\n * original functions passed in (before any safety wrapping), so they can be\n * inspected later. Internal: the public, JSON-safe form is {@link GraphNode}.\n */\nexport type RawNode =\n | {\n /** A rule given an explicit label by `named`. */\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n kind: \"sequence\";\n /** Steps in execution order (`composeRules` runs its array reversed). */\n steps: Fn[];\n via: \"pipeRules\" | \"composeRules\";\n }\n | {\n kind: \"branch\";\n /**\n * `when` has only `ifTrue`, `unless` only `ifFalse`, `ifElse` both. A\n * missing side passes. (Not named `then`/`else`: an object with a\n * `then` key is treated as a promise by `await`.)\n */\n test: Fn;\n ifTrue?: Fn;\n ifFalse?: Fn;\n };\n\n/** Public, JSON-serializable graph. Built by `toGraph`. */\nexport type GraphNode =\n | {\n id: string;\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n id: string;\n kind: \"sequence\";\n via: \"pipeRules\" | \"composeRules\";\n steps: GraphNode[];\n }\n | {\n id: string;\n kind: \"branch\";\n test: string;\n ifTrue?: GraphNode;\n ifFalse?: GraphNode;\n };\n\nexport type RuleGraph = { version: 1; root: GraphNode };\n\n/**\n * Registry symbol, so ESM and CJS copies of the package (or several copies of\n * one version) read each other's metadata.\n */\nexport const NODE_KEY: unique symbol = Symbol.for(\n \"ts-rules-composer.node\",\n) as never;\n\ntype WithNode = { [NODE_KEY]?: RawNode };\n\n/**\n * Records `node` on `fn` and returns the same function. The property is\n * non-enumerable, so spreading, `Object.keys` and `JSON.stringify` are\n * unaffected. A later call replaces an earlier one.\n */\nexport const attachNode = <F extends Fn>(fn: F, node: RawNode): F => {\n Object.defineProperty(fn, NODE_KEY, {\n value: node,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n return fn;\n};\n\n/** Returns the node recorded on `fn`, or `undefined` for plain functions. */\nexport const readNode = (fn: unknown): RawNode | undefined =>\n typeof fn === \"function\" && Object.hasOwn(fn, NODE_KEY)\n ? (fn as WithNode)[NODE_KEY]\n : undefined;\n","/**\n * The function's own name, unless it carries no information: empty,\n * \"anonymous\", or the \"bound x\" name given by `Function.prototype.bind`.\n */\nexport const usableName = (fn: { name: string }): string | undefined => {\n const { name } = fn;\n return name === \"\" || name === \"anonymous\" || name.startsWith(\"bound \")\n ? undefined\n : name;\n};\n","import type { Rule } from \"../types\";\nimport { usableName } from \"./labels\";\nimport { type Fn, type GraphNode, type RuleGraph, readNode } from \"./node\";\n\n/**\n * Builds the public graph. Unlabelled functions get `rule #n`, numbered in\n * depth-first order (a branch's predicate before its sides) so that the same\n * pipeline always yields the same labels.\n */\nconst createBuilder = () => {\n let unlabelled = 0;\n const labelOf = (fn: Fn, explicit?: string) =>\n explicit ?? usableName(fn) ?? `rule #${++unlabelled}`;\n\n const build = (fn: Fn, id: string): GraphNode => {\n const raw = readNode(fn);\n\n // Any function without a recorded structure is a leaf rule.\n if (!raw || raw.kind === \"rule\") {\n return {\n id,\n kind: \"rule\",\n label: labelOf(fn, raw?.label),\n ...(raw?.params ? { params: raw.params } : {}),\n };\n }\n\n switch (raw.kind) {\n case \"sequence\":\n return {\n id,\n kind: \"sequence\",\n via: raw.via,\n steps: raw.steps.map((step, index) =>\n build(step, `${id}.steps.${index}`),\n ),\n };\n case \"branch\": {\n const test = labelOf(raw.test, readLabel(raw.test));\n return {\n id,\n kind: \"branch\",\n test,\n ...(raw.ifTrue ? { ifTrue: build(raw.ifTrue, `${id}.ifTrue`) } : {}),\n ...(raw.ifFalse\n ? { ifFalse: build(raw.ifFalse, `${id}.ifFalse`) }\n : {}),\n };\n }\n }\n };\n\n return build;\n};\n\nconst readLabel = (fn: Fn) => {\n const raw = readNode(fn);\n return raw?.kind === \"rule\" ? raw.label : undefined;\n};\n\n/**\n * Describes a rule as a JSON-serializable graph, without running it.\n *\n * Rules built with this package's combinators are described structurally; any\n * other function (including your own wrappers) is a single leaf rule.\n *\n * @example\n * const graph = toGraph(pipeRules([hasItems, withinLimit]));\n * // { version: 1, root: { kind: \"sequence\", steps: [...] } }\n * @caveats\n * - Nothing is executed: rules, predicates and accessors are never called.\n * - Anonymous functions are labelled `rule #n`; use `named` for a real name.\n */\nexport const toGraph = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): RuleGraph => ({ version: 1, root: createBuilder()(rule, \"root\") });\n"],"mappings":"AAoEA,MAAaA,EAA0B,OAAO,IAC5C,wBACF,EASaC,GAA4B,EAAO,KAC9C,OAAO,eAAeC,EAAIF,EAAU,CAClC,MAAOG,EACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACMD,GAIIE,EAAY,GACvB,OAAOF,GAAO,YAAc,OAAO,OAAOA,EAAIF,CAAQ,EACjDE,EAAgBF,GACjB,IAAA,GCzFOK,EAAc,GAA6C,CACtE,GAAM,CAAE,QAASH,EACjB,OAAOI,IAAS,IAAMA,IAAS,aAAeA,EAAK,WAAW,QAAQ,EAClE,IAAA,GACAA,CACN,ECAMC,MAAsB,CAC1B,IAAIC,EAAa,EACXC,GAAW,EAAQ,IACvBC,GAAYL,EAAWH,CAAE,GAAK,SAAS,EAAEM,IAErCG,GAAS,EAAQ,IAA0B,CAC/C,IAAMC,EAAMR,EAASF,CAAE,EAGvB,GAAI,CAACU,GAAOA,EAAI,OAAS,OACvB,MAAO,CACL,KACA,KAAM,OACN,MAAOH,EAAQP,EAAIU,GAAK,KAAK,EAC7B,GAAIA,GAAK,OAAS,CAAE,OAAQA,EAAI,MAAO,EAAI,CAAC,CAC9C,EAGF,OAAQA,EAAI,KAAZ,CACE,IAAK,WACH,MAAO,CACL,KACA,KAAM,WACN,IAAKA,EAAI,IACT,MAAOA,EAAI,MAAM,KAAK,EAAM,IAC1BD,EAAME,EAAM,GAAGC,EAAG,SAASC,GAAO,CACpC,CACF,EACF,IAAK,SAEH,MAAO,CACL,KACA,KAAM,SACN,KAJWN,EAAQG,EAAI,KAAMI,EAAUJ,EAAI,IAAI,CAI5C,EACH,GAAIA,EAAI,OAAS,CAAE,OAAQD,EAAMC,EAAI,OAAQ,GAAGE,EAAG,QAAQ,CAAE,EAAI,CAAC,EAClE,GAAIF,EAAI,QACJ,CAAE,QAASD,EAAMC,EAAI,QAAS,GAAGE,EAAG,SAAS,CAAE,EAC/C,CAAC,CACP,CAEJ,CACF,EAEA,OAAOH,CACT,EAEMK,EAAa,GAAW,CAC5B,IAAMJ,EAAMR,EAASF,CAAE,EACvB,OAAOU,GAAK,OAAS,OAASA,EAAI,MAAQ,IAAA,EAC5C,EAeaK,EACX,IACe,CAAE,QAAS,EAAG,KAAMV,EAAc,CAAC,CAACW,EAAM,MAAM,CAAE,G"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
const e=Symbol.for(`ts-rules-composer.node`),t=(t,n)=>(Object.defineProperty(t,e,{value:n,enumerable:!1,writable:!1,configurable:!0}),t),n=t=>typeof t==`function`&&Object.hasOwn(t,e)?t[e]:void 0,r=e=>{let{name:t}=e;return t===``||t===`anonymous`||t.startsWith(`bound `)?void 0:t},i=()=>{let e=0,t=(t,n)=>n??r(t)??`rule #${++e}`,i=(e,r)=>{let o=n(e);if(!o||o.kind===`rule`)return{id:r,kind:`rule`,label:t(e,o?.label),...o?.params?{params:o.params}:{}};switch(o.kind){case`sequence`:return{id:r,kind:`sequence`,via:o.via,steps:o.steps.map((e,t)=>i(e,`${r}.steps.${t}`))};case`branch`:return{id:r,kind:`branch`,test:t(o.test,a(o.test)),...o.ifTrue?{ifTrue:i(o.ifTrue,`${r}.ifTrue`)}:{},...o.ifFalse?{ifFalse:i(o.ifFalse,`${r}.ifFalse`)}:{}}}};return i},a=e=>{let t=n(e);return t?.kind===`rule`?t.label:void 0},o=e=>({version:1,root:i()(e,`root`)});Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
|
|
2
|
+
//# sourceMappingURL=to-graph-Dilv6lBr.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"to-graph-Dilv6lBr.cjs","names":["NODE_KEY","attachNode","fn","node","readNode","usableName","name","createBuilder","unlabelled","labelOf","explicit","build","raw","step","id","index","readLabel","toGraph","rule"],"sources":["../src/lib/graph/node.ts","../src/lib/graph/labels.ts","../src/lib/graph/to-graph.ts"],"sourcesContent":["/**\n * Graph node primitives.\n *\n * This module must not import from `combinators/` or `helpers/`: combinators\n * import it, and `helpers/` and `combinators/` already depend on each other.\n */\n\n/** Any function a combinator may hold as a child (rule, predicate, accessor). */\nexport type Fn = (...args: never[]) => unknown;\n\n/**\n * Structure recorded by a combinator at construction time. Children are the\n * original functions passed in (before any safety wrapping), so they can be\n * inspected later. Internal: the public, JSON-safe form is {@link GraphNode}.\n */\nexport type RawNode =\n | {\n /** A rule given an explicit label by `named`. */\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n kind: \"sequence\";\n /** Steps in execution order (`composeRules` runs its array reversed). */\n steps: Fn[];\n via: \"pipeRules\" | \"composeRules\";\n }\n | {\n kind: \"branch\";\n /**\n * `when` has only `ifTrue`, `unless` only `ifFalse`, `ifElse` both. A\n * missing side passes. (Not named `then`/`else`: an object with a\n * `then` key is treated as a promise by `await`.)\n */\n test: Fn;\n ifTrue?: Fn;\n ifFalse?: Fn;\n };\n\n/** Public, JSON-serializable graph. Built by `toGraph`. */\nexport type GraphNode =\n | {\n id: string;\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n id: string;\n kind: \"sequence\";\n via: \"pipeRules\" | \"composeRules\";\n steps: GraphNode[];\n }\n | {\n id: string;\n kind: \"branch\";\n test: string;\n ifTrue?: GraphNode;\n ifFalse?: GraphNode;\n };\n\nexport type RuleGraph = { version: 1; root: GraphNode };\n\n/**\n * Registry symbol, so ESM and CJS copies of the package (or several copies of\n * one version) read each other's metadata.\n */\nexport const NODE_KEY: unique symbol = Symbol.for(\n \"ts-rules-composer.node\",\n) as never;\n\ntype WithNode = { [NODE_KEY]?: RawNode };\n\n/**\n * Records `node` on `fn` and returns the same function. The property is\n * non-enumerable, so spreading, `Object.keys` and `JSON.stringify` are\n * unaffected. A later call replaces an earlier one.\n */\nexport const attachNode = <F extends Fn>(fn: F, node: RawNode): F => {\n Object.defineProperty(fn, NODE_KEY, {\n value: node,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n return fn;\n};\n\n/** Returns the node recorded on `fn`, or `undefined` for plain functions. */\nexport const readNode = (fn: unknown): RawNode | undefined =>\n typeof fn === \"function\" && Object.hasOwn(fn, NODE_KEY)\n ? (fn as WithNode)[NODE_KEY]\n : undefined;\n","/**\n * The function's own name, unless it carries no information: empty,\n * \"anonymous\", or the \"bound x\" name given by `Function.prototype.bind`.\n */\nexport const usableName = (fn: { name: string }): string | undefined => {\n const { name } = fn;\n return name === \"\" || name === \"anonymous\" || name.startsWith(\"bound \")\n ? undefined\n : name;\n};\n","import type { Rule } from \"../types\";\nimport { usableName } from \"./labels\";\nimport { type Fn, type GraphNode, type RuleGraph, readNode } from \"./node\";\n\n/**\n * Builds the public graph. Unlabelled functions get `rule #n`, numbered in\n * depth-first order (a branch's predicate before its sides) so that the same\n * pipeline always yields the same labels.\n */\nconst createBuilder = () => {\n let unlabelled = 0;\n const labelOf = (fn: Fn, explicit?: string) =>\n explicit ?? usableName(fn) ?? `rule #${++unlabelled}`;\n\n const build = (fn: Fn, id: string): GraphNode => {\n const raw = readNode(fn);\n\n // Any function without a recorded structure is a leaf rule.\n if (!raw || raw.kind === \"rule\") {\n return {\n id,\n kind: \"rule\",\n label: labelOf(fn, raw?.label),\n ...(raw?.params ? { params: raw.params } : {}),\n };\n }\n\n switch (raw.kind) {\n case \"sequence\":\n return {\n id,\n kind: \"sequence\",\n via: raw.via,\n steps: raw.steps.map((step, index) =>\n build(step, `${id}.steps.${index}`),\n ),\n };\n case \"branch\": {\n const test = labelOf(raw.test, readLabel(raw.test));\n return {\n id,\n kind: \"branch\",\n test,\n ...(raw.ifTrue ? { ifTrue: build(raw.ifTrue, `${id}.ifTrue`) } : {}),\n ...(raw.ifFalse\n ? { ifFalse: build(raw.ifFalse, `${id}.ifFalse`) }\n : {}),\n };\n }\n }\n };\n\n return build;\n};\n\nconst readLabel = (fn: Fn) => {\n const raw = readNode(fn);\n return raw?.kind === \"rule\" ? raw.label : undefined;\n};\n\n/**\n * Describes a rule as a JSON-serializable graph, without running it.\n *\n * Rules built with this package's combinators are described structurally; any\n * other function (including your own wrappers) is a single leaf rule.\n *\n * @example\n * const graph = toGraph(pipeRules([hasItems, withinLimit]));\n * // { version: 1, root: { kind: \"sequence\", steps: [...] } }\n * @caveats\n * - Nothing is executed: rules, predicates and accessors are never called.\n * - Anonymous functions are labelled `rule #n`; use `named` for a real name.\n */\nexport const toGraph = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): RuleGraph => ({ version: 1, root: createBuilder()(rule, \"root\") });\n"],"mappings":"AAoEA,MAAaA,EAA0B,OAAO,IAC5C,wBACF,EASaC,GAA4B,EAAO,KAC9C,OAAO,eAAeC,EAAIF,EAAU,CAClC,MAAOG,EACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACMD,GAIIE,EAAY,GACvB,OAAOF,GAAO,YAAc,OAAO,OAAOA,EAAIF,CAAQ,EACjDE,EAAgBF,GACjB,IAAA,GCzFOK,EAAc,GAA6C,CACtE,GAAM,CAAE,QAASH,EACjB,OAAOI,IAAS,IAAMA,IAAS,aAAeA,EAAK,WAAW,QAAQ,EAClE,IAAA,GACAA,CACN,ECAMC,MAAsB,CAC1B,IAAIC,EAAa,EACXC,GAAW,EAAQ,IACvBC,GAAYL,EAAWH,CAAE,GAAK,SAAS,EAAEM,IAErCG,GAAS,EAAQ,IAA0B,CAC/C,IAAMC,EAAMR,EAASF,CAAE,EAGvB,GAAI,CAACU,GAAOA,EAAI,OAAS,OACvB,MAAO,CACL,KACA,KAAM,OACN,MAAOH,EAAQP,EAAIU,GAAK,KAAK,EAC7B,GAAIA,GAAK,OAAS,CAAE,OAAQA,EAAI,MAAO,EAAI,CAAC,CAC9C,EAGF,OAAQA,EAAI,KAAZ,CACE,IAAK,WACH,MAAO,CACL,KACA,KAAM,WACN,IAAKA,EAAI,IACT,MAAOA,EAAI,MAAM,KAAK,EAAM,IAC1BD,EAAME,EAAM,GAAGC,EAAG,SAASC,GAAO,CACpC,CACF,EACF,IAAK,SAEH,MAAO,CACL,KACA,KAAM,SACN,KAJWN,EAAQG,EAAI,KAAMI,EAAUJ,EAAI,IAAI,CAI5C,EACH,GAAIA,EAAI,OAAS,CAAE,OAAQD,EAAMC,EAAI,OAAQ,GAAGE,EAAG,QAAQ,CAAE,EAAI,CAAC,EAClE,GAAIF,EAAI,QACJ,CAAE,QAASD,EAAMC,EAAI,QAAS,GAAGE,EAAG,SAAS,CAAE,EAC/C,CAAC,CACP,CAEJ,CACF,EAEA,OAAOH,CACT,EAEMK,EAAa,GAAW,CAC5B,IAAMJ,EAAMR,EAASF,CAAE,EACvB,OAAOU,GAAK,OAAS,OAASA,EAAI,MAAQ,IAAA,EAC5C,EAeaK,EACX,IACe,CAAE,QAAS,EAAG,KAAMV,EAAc,CAAC,CAACW,EAAM,MAAM,CAAE,G"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "ts-rules-composer",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.5.0",
|
|
4
4
|
"description": "Typescript rules engine by composition",
|
|
5
5
|
"main": "./dist/index.cjs",
|
|
6
6
|
"module": "./dist/index.js",
|
|
@@ -25,6 +25,16 @@
|
|
|
25
25
|
"types": "./dist/index.d.cts",
|
|
26
26
|
"default": "./dist/index.cjs"
|
|
27
27
|
}
|
|
28
|
+
},
|
|
29
|
+
"./mermaid": {
|
|
30
|
+
"import": {
|
|
31
|
+
"types": "./dist/mermaid.d.ts",
|
|
32
|
+
"default": "./dist/mermaid.js"
|
|
33
|
+
},
|
|
34
|
+
"require": {
|
|
35
|
+
"types": "./dist/mermaid.d.cts",
|
|
36
|
+
"default": "./dist/mermaid.cjs"
|
|
37
|
+
}
|
|
28
38
|
}
|
|
29
39
|
},
|
|
30
40
|
"scripts": {
|