@inox-tools/utils 0.1.4 → 0.3.0-beta.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/dist/lazy.js +1 -4
- package/dist/once.js +1 -4
- package/dist/types.js +0 -1
- package/dist/unist/visit.d.ts +135 -0
- package/dist/unist/visit.js +2 -0
- package/dist/unist/visit.js.map +1 -0
- package/dist/values.d.ts +35 -1
- package/dist/values.js +1 -4
- package/dist/values.js.map +1 -1
- package/package.json +15 -9
- package/src/unist/visit.ts +332 -0
- package/src/values.ts +92 -0
package/dist/lazy.js
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
class a{constructor(i){this.factory=i;}initialized=!1;value;static of(i){return new this(i)}get(){return this.initialized||(this.value=this.factory(),this.initialized=!0),this.value}}
|
|
2
|
-
|
|
3
|
-
export { a as Lazy };
|
|
4
|
-
//# sourceMappingURL=lazy.js.map
|
|
1
|
+
class a{constructor(i){this.factory=i;}initialized=!1;value;static of(i){return new this(i)}get(){return this.initialized||(this.value=this.factory(),this.initialized=!0),this.value}}export{a as Lazy};//# sourceMappingURL=lazy.js.map
|
|
5
2
|
//# sourceMappingURL=lazy.js.map
|
package/dist/once.js
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
class o{#i=!1;do(i){this.#i||(i(),this.#i=!0);}async doAsync(i){this.#i||(await i(),this.#i=!0);}}
|
|
2
|
-
|
|
3
|
-
export { o as Once };
|
|
4
|
-
//# sourceMappingURL=once.js.map
|
|
1
|
+
class o{#i=!1;do(i){this.#i||(i(),this.#i=!0);}async doAsync(i){this.#i||(await i(),this.#i=!0);}}export{o as Once};//# sourceMappingURL=once.js.map
|
|
5
2
|
//# sourceMappingURL=once.js.map
|
package/dist/types.js
CHANGED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import * as unist_util_is from 'unist-util-is';
|
|
2
|
+
import * as unist from 'unist';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Continue traversing as normal.
|
|
6
|
+
*/
|
|
7
|
+
declare const CONTINUE = true;
|
|
8
|
+
/**
|
|
9
|
+
* Stop traversing immediately.
|
|
10
|
+
*/
|
|
11
|
+
declare const EXIT = false;
|
|
12
|
+
/**
|
|
13
|
+
* Do not traverse this node’s children.
|
|
14
|
+
*/
|
|
15
|
+
declare const SKIP = "skip";
|
|
16
|
+
type Options<Tree extends unist.Node, Check extends Test> = {
|
|
17
|
+
tree: Tree;
|
|
18
|
+
test?: Check;
|
|
19
|
+
enter?: BuildVisitor<Tree, Check>;
|
|
20
|
+
leave?: BuildVisitor<Tree, Check>;
|
|
21
|
+
reverse?: boolean;
|
|
22
|
+
};
|
|
23
|
+
declare function visitParents<Tree extends unist.Node, Check extends Test>({ tree, test, enter: enterVisitor, leave: leaveVisitor, reverse, }: Options<Tree, Check>): void;
|
|
24
|
+
type UnistNode = unist.Node;
|
|
25
|
+
type UnistParent = unist.Parent;
|
|
26
|
+
/**
|
|
27
|
+
* Test from `unist-util-is`.
|
|
28
|
+
*
|
|
29
|
+
* Note: we have remove and add `undefined`, because otherwise when generating
|
|
30
|
+
* automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
|
|
31
|
+
* which doesn’t work when publishing on npm.
|
|
32
|
+
*/
|
|
33
|
+
type Test = Exclude<unist_util_is.Test, undefined> | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* Get the value of a type guard `Fn`.
|
|
36
|
+
*/
|
|
37
|
+
type Predicate<Fn, Fallback> = Fn extends (value: any) => value is infer Thing ? Thing : Fallback;
|
|
38
|
+
/**
|
|
39
|
+
* Check whether a node matches a primitive check in the type system.
|
|
40
|
+
*/
|
|
41
|
+
type MatchesOne<Value, Check> = Check extends null | undefined ? Value : Value extends {
|
|
42
|
+
type: Check;
|
|
43
|
+
} ? Value : Value extends Check ? Value : Check extends Function ? Predicate<Check, Value> extends Value ? Predicate<Check, Value> : never : never;
|
|
44
|
+
/**
|
|
45
|
+
* Check whether a node matches a check in the type system.
|
|
46
|
+
*/
|
|
47
|
+
type Matches<Value, Check> = Check extends Array<any> ? MatchesOne<Value, Check[keyof Check]> : MatchesOne<Value, Check>;
|
|
48
|
+
/**
|
|
49
|
+
* Number; capped reasonably.
|
|
50
|
+
*/
|
|
51
|
+
type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
|
|
52
|
+
/**
|
|
53
|
+
* Increment a number in the type system.
|
|
54
|
+
*/
|
|
55
|
+
type Increment<I extends Uint = 0> = I extends 0 ? 1 : I extends 1 ? 2 : I extends 2 ? 3 : I extends 3 ? 4 : I extends 4 ? 5 : I extends 5 ? 6 : I extends 6 ? 7 : I extends 7 ? 8 : I extends 8 ? 9 : 10;
|
|
56
|
+
/**
|
|
57
|
+
* Collect nodes that can be parents of `Child`.
|
|
58
|
+
*/
|
|
59
|
+
type InternalParent<Node extends unist.Node, Child extends unist.Node> = Node extends unist.Parent ? Node extends {
|
|
60
|
+
children: (infer Children)[];
|
|
61
|
+
} ? Child extends Children ? Node : never : never : never;
|
|
62
|
+
/**
|
|
63
|
+
* Collect nodes in `Tree` that can be parents of `Child`.
|
|
64
|
+
*/
|
|
65
|
+
type Parent<Tree extends unist.Node, Child extends unist.Node> = InternalParent<InclusiveDescendant<Tree>, Child>;
|
|
66
|
+
/**
|
|
67
|
+
* Collect nodes in `Tree` that can be ancestors of `Child`.
|
|
68
|
+
*/
|
|
69
|
+
type InternalAncestor<Node extends unist.Node, Child extends unist.Node, Max extends Uint = 10, Depth extends Uint = 0> = Depth extends Max ? never : InternalParent<Node, Child> | InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>;
|
|
70
|
+
/**
|
|
71
|
+
* Collect nodes in `Tree` that can be ancestors of `Child`.
|
|
72
|
+
*/
|
|
73
|
+
type Ancestor<Tree extends unist.Node, Child extends unist.Node> = InternalAncestor<InclusiveDescendant<Tree>, Child>;
|
|
74
|
+
/**
|
|
75
|
+
* Collect all (inclusive) descendants of `Tree`.
|
|
76
|
+
*
|
|
77
|
+
* > 👉 **Note**: for performance reasons, this seems to be the fastest way to
|
|
78
|
+
* > recurse without actually running into an infinite loop, which the
|
|
79
|
+
* > previous version did.
|
|
80
|
+
* >
|
|
81
|
+
* > Practically, a max of `2` is typically enough assuming a `Root` is
|
|
82
|
+
* > passed, but it doesn’t improve performance.
|
|
83
|
+
* > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
|
|
84
|
+
* > Using up to `10` doesn’t hurt or help either.
|
|
85
|
+
*/
|
|
86
|
+
type InclusiveDescendant<Tree extends unist.Node, Max extends Uint = 10, Depth extends Uint = 0> = Tree extends UnistParent ? Depth extends Max ? Tree : Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>> : Tree;
|
|
87
|
+
/**
|
|
88
|
+
* Union of the action types.
|
|
89
|
+
*/
|
|
90
|
+
type Action = 'skip' | boolean;
|
|
91
|
+
/**
|
|
92
|
+
* Move to the sibling at `index` next (after node itself is completely
|
|
93
|
+
* traversed).
|
|
94
|
+
*
|
|
95
|
+
* Useful if mutating the tree, such as removing the node the visitor is
|
|
96
|
+
* currently on, or any of its previous siblings.
|
|
97
|
+
* Results less than 0 or greater than or equal to `children.length` stop
|
|
98
|
+
* traversing the parent.
|
|
99
|
+
*/
|
|
100
|
+
type Index = number;
|
|
101
|
+
/**
|
|
102
|
+
* List with one or two values, the first an action, the second an index.
|
|
103
|
+
*/
|
|
104
|
+
type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];
|
|
105
|
+
/**
|
|
106
|
+
* Any value that can be returned from a visitor.
|
|
107
|
+
*/
|
|
108
|
+
type VisitorResult = Action | [(void | Action | null | undefined)?, (number | null | undefined)?] | Index | null | undefined | void;
|
|
109
|
+
/**
|
|
110
|
+
* Handle a node (matching `test`, if given).
|
|
111
|
+
*
|
|
112
|
+
* Visitors are free to transform `node`.
|
|
113
|
+
* They can also transform the parent of node (the last of `ancestors`).
|
|
114
|
+
*
|
|
115
|
+
* Replacing `node` itself, if `SKIP` is not returned, still causes its
|
|
116
|
+
* descendants to be walked (which is a bug).
|
|
117
|
+
*
|
|
118
|
+
* When adding or removing previous siblings of `node` (or next siblings, in
|
|
119
|
+
* case of reverse), the `Visitor` should return a new `Index` to specify the
|
|
120
|
+
* sibling to traverse after `node` is traversed.
|
|
121
|
+
* Adding or removing next siblings of `node` (or previous siblings, in case
|
|
122
|
+
* of reverse) is handled as expected without needing to return a new `Index`.
|
|
123
|
+
*
|
|
124
|
+
* Removing the children property of an ancestor still results in them being
|
|
125
|
+
* traversed.
|
|
126
|
+
*/
|
|
127
|
+
type Visitor<Visited extends unist.Node = unist.Node, VisitedParents extends unist.Parent = unist.Parent> = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult;
|
|
128
|
+
/**
|
|
129
|
+
* Build a typed `Visitor` function from a tree and a test.
|
|
130
|
+
*
|
|
131
|
+
* It will infer which values are passed as `node` and which as `parents`.
|
|
132
|
+
*/
|
|
133
|
+
type BuildVisitor<Tree extends unist.Node = unist.Node, Check extends Test = Test> = Visitor<Matches<InclusiveDescendant<Tree>, Check>, Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>;
|
|
134
|
+
|
|
135
|
+
export { type Action, type ActionTuple, type Ancestor, type BuildVisitor, CONTINUE, EXIT, type InclusiveDescendant, type Increment, type Index, type InternalAncestor, type InternalParent, type Matches, type MatchesOne, type Options, type Parent, type Predicate, SKIP, type Test, type Uint, type UnistNode, type UnistParent, type Visitor, type VisitorResult, visitParents };
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import {convert}from'unist-util-is';const a=[],A=!0,f=!1,P="skip";function M({tree:e,test:u,enter:l,leave:c,reverse:p}){if(!e)throw new TypeError("A tree is required");if(!l&&!c)throw new Error("At least one visitor (`enter` or `leave`) must be provided");const I=convert(u),x=p?-1:1;h(e,void 0,[])();function h(n,k,s){const d=n;if(typeof d.type=="string"){const t=typeof d.tagName=="string"?d.tagName:typeof d.name=="string"?d.name:void 0;Object.defineProperty(y,"name",{value:"node ("+n.type+(t?"<"+t+">":"")+")"});}return y;function y(){let t=a,o,i,T;const m=!u||I(n,k,s[s.length-1]);if(m&&(t=C(l?.(n,s)),t[0]===f))return t;if("children"in n&&n.children){const r=n;if(r.children&&t[0]!==P)for(i=(p?r.children.length:-1)+x,T=s.concat(r);i>-1&&i<r.children.length;){const N=r.children[i];if(o=h(N,i,T)(),o[0]===f)return o;i=typeof o[1]=="number"?o[1]:i+x;}}if(m&&c){const r=C(c(n,s));return r===a?t:r}return t}}}function C(e){return Array.isArray(e)?e:typeof e=="number"?[A,e]:e==null?a:[e]}export{A as CONTINUE,f as EXIT,P as SKIP,M as visitParents};//# sourceMappingURL=visit.js.map
|
|
2
|
+
//# sourceMappingURL=visit.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/unist/visit.ts"],"names":["empty","CONTINUE","EXIT","SKIP","visitParents","tree","test","enterVisitor","leaveVisitor","reverse","is","convert","step","factory","node","index","parents","value","name","visit","result","subresult","offset","grandparents","isMatch","toResult","nodeAsParent","child","leaveResult"],"mappings":"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","file":"visit.js","sourcesContent":["import { convert } from 'unist-util-is';\n\nconst empty: ActionTuple = [];\n\n/**\n * Continue traversing as normal.\n */\nexport const CONTINUE = true;\n\n/**\n * Stop traversing immediately.\n */\nexport const EXIT = false;\n\n/**\n * Do not traverse this node’s children.\n */\nexport const SKIP = 'skip';\n\nexport type Options<Tree extends import('unist').Node, Check extends Test> = {\n\ttree: Tree;\n\ttest?: Check;\n\tenter?: BuildVisitor<Tree, Check>;\n\tleave?: BuildVisitor<Tree, Check>;\n\treverse?: boolean;\n};\n\nexport function visitParents<Tree extends import('unist').Node, Check extends Test>({\n\ttree,\n\ttest,\n\tenter: enterVisitor,\n\tleave: leaveVisitor,\n\treverse,\n}: Options<Tree, Check>) {\n\tif (!tree) {\n\t\tthrow new TypeError('A tree is required');\n\t}\n\n\tif (!enterVisitor && !leaveVisitor) {\n\t\tthrow new Error('At least one visitor (`enter` or `leave`) must be provided');\n\t}\n\n\tconst is = convert(test) as (\n\t\tnode: UnistNode,\n\t\tindex?: number,\n\t\tparent?: UnistParent\n\t) => node is Matches<InclusiveDescendant<Tree>, Check>;\n\tconst step = reverse ? -1 : 1;\n\n\tfactory(tree, undefined, [])();\n\n\tfunction factory(node: UnistNode, index: number | undefined, parents: UnistParent[]) {\n\t\tconst value = node as UnistNode & Record<string, unknown>;\n\n\t\tif (typeof value.type === 'string') {\n\t\t\tconst name =\n\t\t\t\t// `hast`\n\t\t\t\ttypeof value.tagName === 'string'\n\t\t\t\t\t? value.tagName\n\t\t\t\t\t: // `xast`\n\t\t\t\t\t\ttypeof value.name === 'string'\n\t\t\t\t\t\t? value.name\n\t\t\t\t\t\t: undefined;\n\n\t\t\tObject.defineProperty(visit, 'name', {\n\t\t\t\tvalue: 'node (' + node.type + (name ? '<' + name + '>' : '') + ')',\n\t\t\t});\n\t\t}\n\n\t\treturn visit;\n\n\t\tfunction visit() {\n\t\t\tlet result: Readonly<ActionTuple> = empty;\n\t\t\tlet subresult: Readonly<ActionTuple>;\n\t\t\tlet offset: number;\n\t\t\tlet grandparents: UnistParent[];\n\t\t\tconst isMatch = !test || is(node, index, parents[parents.length - 1]);\n\n\t\t\tif (isMatch) {\n\t\t\t\tresult = toResult(\n\t\t\t\t\tenterVisitor?.(\n\t\t\t\t\t\tnode as Matches<InclusiveDescendant<Tree>, Check>,\n\t\t\t\t\t\tparents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t\tif (result[0] === EXIT) {\n\t\t\t\t\treturn result;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif ('children' in node && node.children) {\n\t\t\t\tconst nodeAsParent = node as UnistParent;\n\n\t\t\t\tif (nodeAsParent.children && result[0] !== SKIP) {\n\t\t\t\t\toffset = (reverse ? nodeAsParent.children.length : -1) + step;\n\t\t\t\t\tgrandparents = parents.concat(nodeAsParent);\n\n\t\t\t\t\twhile (offset > -1 && offset < nodeAsParent.children.length) {\n\t\t\t\t\t\tconst child = nodeAsParent.children[offset];\n\n\t\t\t\t\t\tsubresult = factory(child, offset, grandparents)();\n\n\t\t\t\t\t\tif (subresult[0] === EXIT) {\n\t\t\t\t\t\t\treturn subresult;\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\toffset = typeof subresult[1] === 'number' ? subresult[1] : offset + step;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (isMatch && leaveVisitor) {\n\t\t\t\tconst leaveResult = toResult(\n\t\t\t\t\tleaveVisitor(\n\t\t\t\t\t\tnode as Matches<InclusiveDescendant<Tree>, Check>,\n\t\t\t\t\t\tparents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>\n\t\t\t\t\t)\n\t\t\t\t);\n\n\t\t\t\treturn leaveResult === empty ? result : leaveResult;\n\t\t\t}\n\n\t\t\treturn result;\n\t\t}\n\t}\n}\n\n/**\n * Turn a return value into a clean result.\n */\nfunction toResult(value: VisitorResult): Readonly<ActionTuple> {\n\tif (Array.isArray(value)) {\n\t\treturn value;\n\t}\n\n\tif (typeof value === 'number') {\n\t\treturn [CONTINUE, value];\n\t}\n\n\treturn value === null || value === undefined ? empty : [value];\n}\n\nexport type UnistNode = import('unist').Node;\nexport type UnistParent = import('unist').Parent;\n/**\n * Test from `unist-util-is`.\n *\n * Note: we have remove and add `undefined`, because otherwise when generating\n * automatic `.d.ts` files, TS tries to flatten paths from a local perspective,\n * which doesn’t work when publishing on npm.\n */\nexport type Test = Exclude<import('unist-util-is').Test, undefined> | undefined;\n/**\n * Get the value of a type guard `Fn`.\n */\nexport type Predicate<Fn, Fallback> = Fn extends (value: any) => value is infer Thing\n\t? Thing\n\t: Fallback;\n/**\n * Check whether a node matches a primitive check in the type system.\n */\nexport type MatchesOne<Value, Check> = Check extends null | undefined\n\t? Value\n\t: Value extends {\n\t\t\t\ttype: Check;\n\t\t }\n\t\t? Value\n\t\t: Value extends Check\n\t\t\t? Value\n\t\t\t: Check extends Function\n\t\t\t\t? Predicate<Check, Value> extends Value\n\t\t\t\t\t? Predicate<Check, Value>\n\t\t\t\t\t: never\n\t\t\t\t: never;\n/**\n * Check whether a node matches a check in the type system.\n */\nexport type Matches<Value, Check> =\n\tCheck extends Array<any> ? MatchesOne<Value, Check[keyof Check]> : MatchesOne<Value, Check>;\n/**\n * Number; capped reasonably.\n */\nexport type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;\n/**\n * Increment a number in the type system.\n */\nexport type Increment<I extends Uint = 0> = I extends 0\n\t? 1\n\t: I extends 1\n\t\t? 2\n\t\t: I extends 2\n\t\t\t? 3\n\t\t\t: I extends 3\n\t\t\t\t? 4\n\t\t\t\t: I extends 4\n\t\t\t\t\t? 5\n\t\t\t\t\t: I extends 5\n\t\t\t\t\t\t? 6\n\t\t\t\t\t\t: I extends 6\n\t\t\t\t\t\t\t? 7\n\t\t\t\t\t\t\t: I extends 7\n\t\t\t\t\t\t\t\t? 8\n\t\t\t\t\t\t\t\t: I extends 8\n\t\t\t\t\t\t\t\t\t? 9\n\t\t\t\t\t\t\t\t\t: 10;\n/**\n * Collect nodes that can be parents of `Child`.\n */\nexport type InternalParent<\n\tNode extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = Node extends import('unist').Parent\n\t? Node extends {\n\t\t\tchildren: (infer Children)[];\n\t\t}\n\t\t? Child extends Children\n\t\t\t? Node\n\t\t\t: never\n\t\t: never\n\t: never;\n/**\n * Collect nodes in `Tree` that can be parents of `Child`.\n */\nexport type Parent<\n\tTree extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = InternalParent<InclusiveDescendant<Tree>, Child>;\n/**\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n */\nexport type InternalAncestor<\n\tNode extends import('unist').Node,\n\tChild extends import('unist').Node,\n\tMax extends Uint = 10,\n\tDepth extends Uint = 0,\n> = Depth extends Max\n\t? never\n\t:\n\t\t\t| InternalParent<Node, Child>\n\t\t\t| InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>;\n/**\n * Collect nodes in `Tree` that can be ancestors of `Child`.\n */\nexport type Ancestor<\n\tTree extends import('unist').Node,\n\tChild extends import('unist').Node,\n> = InternalAncestor<InclusiveDescendant<Tree>, Child>;\n/**\n * Collect all (inclusive) descendants of `Tree`.\n *\n * > 👉 **Note**: for performance reasons, this seems to be the fastest way to\n * > recurse without actually running into an infinite loop, which the\n * > previous version did.\n * >\n * > Practically, a max of `2` is typically enough assuming a `Root` is\n * > passed, but it doesn’t improve performance.\n * > It gets higher with `List > ListItem > Table > TableRow > TableCell`.\n * > Using up to `10` doesn’t hurt or help either.\n */\nexport type InclusiveDescendant<\n\tTree extends import('unist').Node,\n\tMax extends Uint = 10,\n\tDepth extends Uint = 0,\n> = Tree extends UnistParent\n\t? Depth extends Max\n\t\t? Tree\n\t\t: Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>\n\t: Tree;\n/**\n * Union of the action types.\n */\nexport type Action = 'skip' | boolean;\n/**\n * Move to the sibling at `index` next (after node itself is completely\n * traversed).\n *\n * Useful if mutating the tree, such as removing the node the visitor is\n * currently on, or any of its previous siblings.\n * Results less than 0 or greater than or equal to `children.length` stop\n * traversing the parent.\n */\nexport type Index = number;\n/**\n * List with one or two values, the first an action, the second an index.\n */\nexport type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];\n/**\n * Any value that can be returned from a visitor.\n */\nexport type VisitorResult =\n\t| Action\n\t| [(void | Action | null | undefined)?, (number | null | undefined)?]\n\t| Index\n\t| null\n\t| undefined\n\t| void;\n/**\n * Handle a node (matching `test`, if given).\n *\n * Visitors are free to transform `node`.\n * They can also transform the parent of node (the last of `ancestors`).\n *\n * Replacing `node` itself, if `SKIP` is not returned, still causes its\n * descendants to be walked (which is a bug).\n *\n * When adding or removing previous siblings of `node` (or next siblings, in\n * case of reverse), the `Visitor` should return a new `Index` to specify the\n * sibling to traverse after `node` is traversed.\n * Adding or removing next siblings of `node` (or previous siblings, in case\n * of reverse) is handled as expected without needing to return a new `Index`.\n *\n * Removing the children property of an ancestor still results in them being\n * traversed.\n */\nexport type Visitor<\n\tVisited extends import('unist').Node = import('unist').Node,\n\tVisitedParents extends import('unist').Parent = import('unist').Parent,\n> = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult;\n\n/**\n * Build a typed `Visitor` function from a tree and a test.\n *\n * It will infer which values are passed as `node` and which as `parents`.\n */\nexport type BuildVisitor<\n\tTree extends import('unist').Node = import('unist').Node,\n\tCheck extends Test = Test,\n> = Visitor<\n\tMatches<InclusiveDescendant<Tree>, Check>,\n\tAncestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>\n>;\n"]}
|
package/dist/values.d.ts
CHANGED
|
@@ -35,5 +35,39 @@ type MaybeAsyncThunk<T> = MaybeThunk<MaybePromise<T>>;
|
|
|
35
35
|
* @see MaybeThunk
|
|
36
36
|
*/
|
|
37
37
|
declare function loadThunkValue<T>(value: MaybeThunk<T>): T;
|
|
38
|
+
type NextDepth = [1, 2, 3, 4, 5, 6, 7];
|
|
39
|
+
/**
|
|
40
|
+
* Extract key-value entry pairs for each node in an object tree.
|
|
41
|
+
*/
|
|
42
|
+
type NodeEntries<T, NoCircle = never, MaxDepth extends number = 0> = MaxDepth extends 7 ? never : T extends object ? {
|
|
43
|
+
[Key in keyof T & string]-?: T[Key] extends NoCircle ? never : NodeEntries<T[Key], NoCircle | T[Key], NextDepth[MaxDepth]> extends infer Nested ? Nested extends {
|
|
44
|
+
key: string;
|
|
45
|
+
value: unknown;
|
|
46
|
+
} ? Nested['key'] extends '' ? {
|
|
47
|
+
key: Key;
|
|
48
|
+
value: Nested['value'];
|
|
49
|
+
} : {
|
|
50
|
+
key: Key;
|
|
51
|
+
value: T[Key];
|
|
52
|
+
} | {
|
|
53
|
+
key: `${Key}.${Nested['key']}`;
|
|
54
|
+
value: Nested['value'];
|
|
55
|
+
} : never : never;
|
|
56
|
+
}[keyof T & string] : {
|
|
57
|
+
key: '';
|
|
58
|
+
value: T;
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Sets a value nested in an object tree, creating the path as needed.
|
|
62
|
+
*/
|
|
63
|
+
declare function setNested<T extends object, const P extends NodeEntries<T>['key']>(obj: T, prop: P, value: Extract<NodeEntries<T>, {
|
|
64
|
+
key: P;
|
|
65
|
+
}>['value']): void;
|
|
66
|
+
/**
|
|
67
|
+
* Sets a value nested in an object tree, creating the path as needed, if it is not already set to a non-nullish value.
|
|
68
|
+
*/
|
|
69
|
+
declare function setNestedIfNullish<T extends object, const P extends NodeEntries<T>['key']>(obj: T, prop: P, value: Extract<NodeEntries<T>, {
|
|
70
|
+
key: P;
|
|
71
|
+
}>['value']): void;
|
|
38
72
|
|
|
39
|
-
export { type MaybeAsyncThunk, type MaybePromise, type MaybeThunk, loadThunkValue };
|
|
73
|
+
export { type MaybeAsyncThunk, type MaybePromise, type MaybeThunk, type NodeEntries, loadThunkValue, setNested, setNestedIfNullish };
|
package/dist/values.js
CHANGED
|
@@ -1,5 +1,2 @@
|
|
|
1
|
-
function
|
|
2
|
-
|
|
3
|
-
export { T as loadThunkValue };
|
|
4
|
-
//# sourceMappingURL=values.js.map
|
|
1
|
+
function p(n){return typeof n=="function"?n():n}function u(n,i,y){if(n==null)throw new Error("Root object is nullish.");const t=i.split(".");let e=n;for(const[l,s]of t.slice(0,-1).entries()){const o=e[s],r=t.slice(0,l).join(".");if(o==null){e=e[s]={};continue}if(typeof o!="object")throw new Error(`Cannot set property on ${typeof o} value at "${r}".`);e=o;}e[t[t.length-1]]=y;}function a(n,i,y){if(n==null)throw new Error("Root object is nullish.");const t=i.split(".");let e=n;for(const[s,o]of t.slice(0,-1).entries()){const r=e[o],c=t.slice(0,s).join(".");if(r==null){e=e[o]={};continue}if(typeof r!="object")throw new Error(`Cannot set property on ${typeof r} value at "${c}".`);e=r;}const l=t[t.length-1];e[l]==null&&(e[t[t.length-1]]=y);}export{p as loadThunkValue,u as setNested,a as setNestedIfNullish};//# sourceMappingURL=values.js.map
|
|
5
2
|
//# sourceMappingURL=values.js.map
|
package/dist/values.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/values.ts"],"names":["loadThunkValue","value"],"mappings":"AAuCO,SAASA,CAAAA,CAAkBC,EAAyB,CAC1D,OAAO,OAAOA,CAAU,EAAA,UAAA,CAAaA,CAAM,EAAA,
|
|
1
|
+
{"version":3,"sources":["../src/values.ts"],"names":["loadThunkValue","value","setNested","obj","prop","parts","current","idx","propName","next","path","setNestedIfNullish","key"],"mappings":"AAuCO,SAASA,CAAAA,CAAkBC,EAAyB,CAC1D,OAAO,OAAOA,CAAU,EAAA,UAAA,CAAaA,GAAUA,CAAAA,CAChD,CAkCO,SAASC,CAAAA,CACfC,EACAC,CACAH,CAAAA,CAAAA,CACO,CACP,GAAIE,CAAAA,EAAO,IAAM,CAAA,MAAM,IAAI,KAAA,CAAM,yBAAyB,CAC1D,CAAA,MAAME,EAAQD,CAAK,CAAA,KAAA,CAAM,GAAG,CAE5B,CAAA,IAAIE,EAAeH,CACnB,CAAA,IAAA,KAAW,CAACI,CAAKC,CAAAA,CAAQ,IAAKH,CAAM,CAAA,KAAA,CAAM,EAAG,CAAE,CAAA,CAAA,CAAE,OAAQ,EAAA,CAAG,CAC3D,MAAMI,EAAOH,CAAQE,CAAAA,CAAQ,EACvBE,CAAOL,CAAAA,CAAAA,CAAM,MAAM,CAAGE,CAAAA,CAAG,EAAE,IAAK,CAAA,GAAG,EAEzC,GAAIE,CAAAA,EAAQ,KAAM,CACjBH,CAAAA,CAAUA,EAAQE,CAAQ,CAAA,CAAI,EAAC,CAC/B,QACD,CAEA,GAAI,OAAOC,CAAAA,EAAS,SACnB,MAAM,IAAI,MAAM,CAA0B,uBAAA,EAAA,OAAOA,CAAI,CAAcC,WAAAA,EAAAA,CAAI,IAAI,CAE5EJ,CAAAA,CAAAA,CAAUG,EACX,CAEAH,CAAAA,CAAQD,EAAMA,CAAM,CAAA,MAAA,CAAS,CAAC,CAAC,CAAIJ,CAAAA,EACpC,CAKO,SAASU,CAAAA,CACfR,EACAC,CACAH,CAAAA,CAAAA,CACO,CACP,GAAIE,CAAAA,EAAO,KAAM,MAAM,IAAI,MAAM,yBAAyB,CAAA,CAC1D,MAAME,CAAQD,CAAAA,CAAAA,CAAK,MAAM,GAAG,CAAA,CAE5B,IAAIE,CAAAA,CAAeH,CACnB,CAAA,IAAA,KAAW,CAACI,CAAKC,CAAAA,CAAQ,IAAKH,CAAM,CAAA,KAAA,CAAM,EAAG,CAAE,CAAA,CAAA,CAAE,SAAW,CAAA,CAC3D,MAAMI,CAAOH,CAAAA,CAAAA,CAAQE,CAAQ,CACvBE,CAAAA,CAAAA,CAAOL,EAAM,KAAM,CAAA,CAAA,CAAGE,CAAG,CAAA,CAAE,IAAK,CAAA,GAAG,EAEzC,GAAIE,CAAAA,EAAQ,KAAM,CACjBH,CAAAA,CAAUA,EAAQE,CAAQ,CAAA,CAAI,EAC9B,CAAA,QACD,CAEA,GAAI,OAAOC,GAAS,QACnB,CAAA,MAAM,IAAI,KAAM,CAAA,CAAA,uBAAA,EAA0B,OAAOA,CAAI,CAAcC,WAAAA,EAAAA,CAAI,IAAI,CAE5EJ,CAAAA,CAAAA,CAAUG,EACX,CAEA,MAAMG,EAAMP,CAAMA,CAAAA,CAAAA,CAAM,OAAS,CAAC,CAAA,CAC9BC,EAAQM,CAAG,CAAA,EAAK,OACnBN,CAAQD,CAAAA,CAAAA,CAAMA,EAAM,MAAS,CAAA,CAAC,CAAC,CAAA,CAAIJ,CAErC,EAAA","file":"values.js","sourcesContent":["/**\n * A value that can be might be pending to be resolved.\n */\nexport type MaybePromise<T> = T | Promise<T>;\n\n/**\n * A value or a thunk for a value.\n *\n * A \"thunk\" is a function that takes no arguments and return\n * a value that is potentially expensive to compute.\n * This can be used when the value might not be needed and as\n * such can be computed on demand potentially saving the\n * expensive computation.\n *\n * If the value is not expensive to compute it can be used directly\n * for simplicity.\n *\n * A value type that is itself a function cannot be a \"maybe\" thunk.\n *\n * @see https://en.wikipedia.org/wiki/Thunk\n */\nexport type MaybeThunk<T> = T extends Function ? never : T | (() => T);\n\n/**\n * A value or a thunk for a synchronous or asynchronous value.\n *\n * @see MaybePromise\n * @see MaybeThunk\n */\nexport type MaybeAsyncThunk<T> = MaybeThunk<MaybePromise<T>>;\n\n/**\n * Load a value from a possibly thunk argument.\n *\n * If the value is a thunk it is called and the result is returned.\n * Otherwise the value itself is returned.\n *\n * @see MaybeThunk\n */\nexport function loadThunkValue<T>(value: MaybeThunk<T>): T {\n\treturn typeof value === 'function' ? value() : value;\n}\n\ntype NextDepth = [1, 2, 3, 4, 5, 6, 7];\n\n/**\n * Extract key-value entry pairs for each node in an object tree.\n */\nexport type NodeEntries<T, NoCircle = never, MaxDepth extends number = 0> = MaxDepth extends 7\n\t? never\n\t: T extends object\n\t\t? {\n\t\t\t\t[Key in keyof T & string]-?: T[Key] extends NoCircle\n\t\t\t\t\t? never\n\t\t\t\t\t: NodeEntries<T[Key], NoCircle | T[Key], NextDepth[MaxDepth]> extends infer Nested\n\t\t\t\t\t\t? Nested extends { key: string; value: unknown }\n\t\t\t\t\t\t\t? Nested['key'] extends ''\n\t\t\t\t\t\t\t\t? {\n\t\t\t\t\t\t\t\t\t\tkey: Key;\n\t\t\t\t\t\t\t\t\t\tvalue: Nested['value'];\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t:\n\t\t\t\t\t\t\t\t\t\t| { key: Key; value: T[Key] }\n\t\t\t\t\t\t\t\t\t\t| {\n\t\t\t\t\t\t\t\t\t\t\t\tkey: `${Key}.${Nested['key']}`;\n\t\t\t\t\t\t\t\t\t\t\t\tvalue: Nested['value'];\n\t\t\t\t\t\t\t\t\t\t }\n\t\t\t\t\t\t\t: never\n\t\t\t\t\t\t: never;\n\t\t\t}[keyof T & string]\n\t\t: { key: ''; value: T };\n\n/**\n * Sets a value nested in an object tree, creating the path as needed.\n */\nexport function setNested<T extends object, const P extends NodeEntries<T>['key']>(\n\tobj: T,\n\tprop: P,\n\tvalue: Extract<NodeEntries<T>, { key: P }>['value']\n): void {\n\tif (obj == null) throw new Error('Root object is nullish.');\n\tconst parts = prop.split('.');\n\n\tlet current: any = obj;\n\tfor (const [idx, propName] of parts.slice(0, -1).entries()) {\n\t\tconst next = current[propName];\n\t\tconst path = parts.slice(0, idx).join('.');\n\n\t\tif (next == null) {\n\t\t\tcurrent = current[propName] = {};\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typeof next !== 'object')\n\t\t\tthrow new Error(`Cannot set property on ${typeof next} value at \"${path}\".`);\n\n\t\tcurrent = next;\n\t}\n\n\tcurrent[parts[parts.length - 1]] = value;\n}\n\n/**\n * Sets a value nested in an object tree, creating the path as needed, if it is not already set to a non-nullish value.\n */\nexport function setNestedIfNullish<T extends object, const P extends NodeEntries<T>['key']>(\n\tobj: T,\n\tprop: P,\n\tvalue: Extract<NodeEntries<T>, { key: P }>['value']\n): void {\n\tif (obj == null) throw new Error('Root object is nullish.');\n\tconst parts = prop.split('.');\n\n\tlet current: any = obj;\n\tfor (const [idx, propName] of parts.slice(0, -1).entries()) {\n\t\tconst next = current[propName];\n\t\tconst path = parts.slice(0, idx).join('.');\n\n\t\tif (next == null) {\n\t\t\tcurrent = current[propName] = {};\n\t\t\tcontinue;\n\t\t}\n\n\t\tif (typeof next !== 'object')\n\t\t\tthrow new Error(`Cannot set property on ${typeof next} value at \"${path}\".`);\n\n\t\tcurrent = next;\n\t}\n\n\tconst key = parts[parts.length - 1];\n\tif (current[key] == null) {\n\t\tcurrent[parts[parts.length - 1]] = value;\n\t}\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@inox-tools/utils",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0-beta.0",
|
|
4
4
|
"description": "A collection of utilities used throughout Inox Tools",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"utilities"
|
|
@@ -20,15 +20,21 @@
|
|
|
20
20
|
"src"
|
|
21
21
|
],
|
|
22
22
|
"devDependencies": {
|
|
23
|
-
"@types/
|
|
24
|
-
"@
|
|
25
|
-
"@
|
|
26
|
-
"
|
|
23
|
+
"@types/hast": "^3.0.4",
|
|
24
|
+
"@types/mdast": "^4.0.4",
|
|
25
|
+
"@types/node": "^22.8.4",
|
|
26
|
+
"@types/unist": "^3.0.3",
|
|
27
|
+
"@types/xast": "^2.0.4",
|
|
28
|
+
"@vitest/coverage-v8": "^2.1.4",
|
|
29
|
+
"@vitest/ui": "^2.1.4",
|
|
30
|
+
"astro": "^5.0.0-beta",
|
|
27
31
|
"jest-extended": "^4.0.2",
|
|
28
|
-
"
|
|
29
|
-
"
|
|
30
|
-
"
|
|
31
|
-
"
|
|
32
|
+
"mdast-util-from-markdown": "^2.0.2",
|
|
33
|
+
"tsup": "8.3.5",
|
|
34
|
+
"typescript": "^5.6.3",
|
|
35
|
+
"unist-util-is": "^6.0.0",
|
|
36
|
+
"vite": "^6.0.0-beta",
|
|
37
|
+
"vitest": "^2.1.4"
|
|
32
38
|
},
|
|
33
39
|
"scripts": {
|
|
34
40
|
"build": "tsup",
|
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
import { convert } from 'unist-util-is';
|
|
2
|
+
|
|
3
|
+
const empty: ActionTuple = [];
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Continue traversing as normal.
|
|
7
|
+
*/
|
|
8
|
+
export const CONTINUE = true;
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Stop traversing immediately.
|
|
12
|
+
*/
|
|
13
|
+
export const EXIT = false;
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Do not traverse this node’s children.
|
|
17
|
+
*/
|
|
18
|
+
export const SKIP = 'skip';
|
|
19
|
+
|
|
20
|
+
export type Options<Tree extends import('unist').Node, Check extends Test> = {
|
|
21
|
+
tree: Tree;
|
|
22
|
+
test?: Check;
|
|
23
|
+
enter?: BuildVisitor<Tree, Check>;
|
|
24
|
+
leave?: BuildVisitor<Tree, Check>;
|
|
25
|
+
reverse?: boolean;
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
export function visitParents<Tree extends import('unist').Node, Check extends Test>({
|
|
29
|
+
tree,
|
|
30
|
+
test,
|
|
31
|
+
enter: enterVisitor,
|
|
32
|
+
leave: leaveVisitor,
|
|
33
|
+
reverse,
|
|
34
|
+
}: Options<Tree, Check>) {
|
|
35
|
+
if (!tree) {
|
|
36
|
+
throw new TypeError('A tree is required');
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (!enterVisitor && !leaveVisitor) {
|
|
40
|
+
throw new Error('At least one visitor (`enter` or `leave`) must be provided');
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const is = convert(test) as (
|
|
44
|
+
node: UnistNode,
|
|
45
|
+
index?: number,
|
|
46
|
+
parent?: UnistParent
|
|
47
|
+
) => node is Matches<InclusiveDescendant<Tree>, Check>;
|
|
48
|
+
const step = reverse ? -1 : 1;
|
|
49
|
+
|
|
50
|
+
factory(tree, undefined, [])();
|
|
51
|
+
|
|
52
|
+
function factory(node: UnistNode, index: number | undefined, parents: UnistParent[]) {
|
|
53
|
+
const value = node as UnistNode & Record<string, unknown>;
|
|
54
|
+
|
|
55
|
+
if (typeof value.type === 'string') {
|
|
56
|
+
const name =
|
|
57
|
+
// `hast`
|
|
58
|
+
typeof value.tagName === 'string'
|
|
59
|
+
? value.tagName
|
|
60
|
+
: // `xast`
|
|
61
|
+
typeof value.name === 'string'
|
|
62
|
+
? value.name
|
|
63
|
+
: undefined;
|
|
64
|
+
|
|
65
|
+
Object.defineProperty(visit, 'name', {
|
|
66
|
+
value: 'node (' + node.type + (name ? '<' + name + '>' : '') + ')',
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return visit;
|
|
71
|
+
|
|
72
|
+
function visit() {
|
|
73
|
+
let result: Readonly<ActionTuple> = empty;
|
|
74
|
+
let subresult: Readonly<ActionTuple>;
|
|
75
|
+
let offset: number;
|
|
76
|
+
let grandparents: UnistParent[];
|
|
77
|
+
const isMatch = !test || is(node, index, parents[parents.length - 1]);
|
|
78
|
+
|
|
79
|
+
if (isMatch) {
|
|
80
|
+
result = toResult(
|
|
81
|
+
enterVisitor?.(
|
|
82
|
+
node as Matches<InclusiveDescendant<Tree>, Check>,
|
|
83
|
+
parents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>
|
|
84
|
+
)
|
|
85
|
+
);
|
|
86
|
+
|
|
87
|
+
if (result[0] === EXIT) {
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if ('children' in node && node.children) {
|
|
93
|
+
const nodeAsParent = node as UnistParent;
|
|
94
|
+
|
|
95
|
+
if (nodeAsParent.children && result[0] !== SKIP) {
|
|
96
|
+
offset = (reverse ? nodeAsParent.children.length : -1) + step;
|
|
97
|
+
grandparents = parents.concat(nodeAsParent);
|
|
98
|
+
|
|
99
|
+
while (offset > -1 && offset < nodeAsParent.children.length) {
|
|
100
|
+
const child = nodeAsParent.children[offset];
|
|
101
|
+
|
|
102
|
+
subresult = factory(child, offset, grandparents)();
|
|
103
|
+
|
|
104
|
+
if (subresult[0] === EXIT) {
|
|
105
|
+
return subresult;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
offset = typeof subresult[1] === 'number' ? subresult[1] : offset + step;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (isMatch && leaveVisitor) {
|
|
114
|
+
const leaveResult = toResult(
|
|
115
|
+
leaveVisitor(
|
|
116
|
+
node as Matches<InclusiveDescendant<Tree>, Check>,
|
|
117
|
+
parents as Array<Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>>
|
|
118
|
+
)
|
|
119
|
+
);
|
|
120
|
+
|
|
121
|
+
return leaveResult === empty ? result : leaveResult;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
return result;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Turn a return value into a clean result.
|
|
131
|
+
*/
|
|
132
|
+
function toResult(value: VisitorResult): Readonly<ActionTuple> {
|
|
133
|
+
if (Array.isArray(value)) {
|
|
134
|
+
return value;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
if (typeof value === 'number') {
|
|
138
|
+
return [CONTINUE, value];
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
return value === null || value === undefined ? empty : [value];
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
export type UnistNode = import('unist').Node;
|
|
145
|
+
export type UnistParent = import('unist').Parent;
|
|
146
|
+
/**
|
|
147
|
+
* Test from `unist-util-is`.
|
|
148
|
+
*
|
|
149
|
+
* Note: we have remove and add `undefined`, because otherwise when generating
|
|
150
|
+
* automatic `.d.ts` files, TS tries to flatten paths from a local perspective,
|
|
151
|
+
* which doesn’t work when publishing on npm.
|
|
152
|
+
*/
|
|
153
|
+
export type Test = Exclude<import('unist-util-is').Test, undefined> | undefined;
|
|
154
|
+
/**
|
|
155
|
+
* Get the value of a type guard `Fn`.
|
|
156
|
+
*/
|
|
157
|
+
export type Predicate<Fn, Fallback> = Fn extends (value: any) => value is infer Thing
|
|
158
|
+
? Thing
|
|
159
|
+
: Fallback;
|
|
160
|
+
/**
|
|
161
|
+
* Check whether a node matches a primitive check in the type system.
|
|
162
|
+
*/
|
|
163
|
+
export type MatchesOne<Value, Check> = Check extends null | undefined
|
|
164
|
+
? Value
|
|
165
|
+
: Value extends {
|
|
166
|
+
type: Check;
|
|
167
|
+
}
|
|
168
|
+
? Value
|
|
169
|
+
: Value extends Check
|
|
170
|
+
? Value
|
|
171
|
+
: Check extends Function
|
|
172
|
+
? Predicate<Check, Value> extends Value
|
|
173
|
+
? Predicate<Check, Value>
|
|
174
|
+
: never
|
|
175
|
+
: never;
|
|
176
|
+
/**
|
|
177
|
+
* Check whether a node matches a check in the type system.
|
|
178
|
+
*/
|
|
179
|
+
export type Matches<Value, Check> =
|
|
180
|
+
Check extends Array<any> ? MatchesOne<Value, Check[keyof Check]> : MatchesOne<Value, Check>;
|
|
181
|
+
/**
|
|
182
|
+
* Number; capped reasonably.
|
|
183
|
+
*/
|
|
184
|
+
export type Uint = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10;
|
|
185
|
+
/**
|
|
186
|
+
* Increment a number in the type system.
|
|
187
|
+
*/
|
|
188
|
+
export type Increment<I extends Uint = 0> = I extends 0
|
|
189
|
+
? 1
|
|
190
|
+
: I extends 1
|
|
191
|
+
? 2
|
|
192
|
+
: I extends 2
|
|
193
|
+
? 3
|
|
194
|
+
: I extends 3
|
|
195
|
+
? 4
|
|
196
|
+
: I extends 4
|
|
197
|
+
? 5
|
|
198
|
+
: I extends 5
|
|
199
|
+
? 6
|
|
200
|
+
: I extends 6
|
|
201
|
+
? 7
|
|
202
|
+
: I extends 7
|
|
203
|
+
? 8
|
|
204
|
+
: I extends 8
|
|
205
|
+
? 9
|
|
206
|
+
: 10;
|
|
207
|
+
/**
|
|
208
|
+
* Collect nodes that can be parents of `Child`.
|
|
209
|
+
*/
|
|
210
|
+
export type InternalParent<
|
|
211
|
+
Node extends import('unist').Node,
|
|
212
|
+
Child extends import('unist').Node,
|
|
213
|
+
> = Node extends import('unist').Parent
|
|
214
|
+
? Node extends {
|
|
215
|
+
children: (infer Children)[];
|
|
216
|
+
}
|
|
217
|
+
? Child extends Children
|
|
218
|
+
? Node
|
|
219
|
+
: never
|
|
220
|
+
: never
|
|
221
|
+
: never;
|
|
222
|
+
/**
|
|
223
|
+
* Collect nodes in `Tree` that can be parents of `Child`.
|
|
224
|
+
*/
|
|
225
|
+
export type Parent<
|
|
226
|
+
Tree extends import('unist').Node,
|
|
227
|
+
Child extends import('unist').Node,
|
|
228
|
+
> = InternalParent<InclusiveDescendant<Tree>, Child>;
|
|
229
|
+
/**
|
|
230
|
+
* Collect nodes in `Tree` that can be ancestors of `Child`.
|
|
231
|
+
*/
|
|
232
|
+
export type InternalAncestor<
|
|
233
|
+
Node extends import('unist').Node,
|
|
234
|
+
Child extends import('unist').Node,
|
|
235
|
+
Max extends Uint = 10,
|
|
236
|
+
Depth extends Uint = 0,
|
|
237
|
+
> = Depth extends Max
|
|
238
|
+
? never
|
|
239
|
+
:
|
|
240
|
+
| InternalParent<Node, Child>
|
|
241
|
+
| InternalAncestor<Node, InternalParent<Node, Child>, Max, Increment<Depth>>;
|
|
242
|
+
/**
|
|
243
|
+
* Collect nodes in `Tree` that can be ancestors of `Child`.
|
|
244
|
+
*/
|
|
245
|
+
export type Ancestor<
|
|
246
|
+
Tree extends import('unist').Node,
|
|
247
|
+
Child extends import('unist').Node,
|
|
248
|
+
> = InternalAncestor<InclusiveDescendant<Tree>, Child>;
|
|
249
|
+
/**
|
|
250
|
+
* Collect all (inclusive) descendants of `Tree`.
|
|
251
|
+
*
|
|
252
|
+
* > 👉 **Note**: for performance reasons, this seems to be the fastest way to
|
|
253
|
+
* > recurse without actually running into an infinite loop, which the
|
|
254
|
+
* > previous version did.
|
|
255
|
+
* >
|
|
256
|
+
* > Practically, a max of `2` is typically enough assuming a `Root` is
|
|
257
|
+
* > passed, but it doesn’t improve performance.
|
|
258
|
+
* > It gets higher with `List > ListItem > Table > TableRow > TableCell`.
|
|
259
|
+
* > Using up to `10` doesn’t hurt or help either.
|
|
260
|
+
*/
|
|
261
|
+
export type InclusiveDescendant<
|
|
262
|
+
Tree extends import('unist').Node,
|
|
263
|
+
Max extends Uint = 10,
|
|
264
|
+
Depth extends Uint = 0,
|
|
265
|
+
> = Tree extends UnistParent
|
|
266
|
+
? Depth extends Max
|
|
267
|
+
? Tree
|
|
268
|
+
: Tree | InclusiveDescendant<Tree['children'][number], Max, Increment<Depth>>
|
|
269
|
+
: Tree;
|
|
270
|
+
/**
|
|
271
|
+
* Union of the action types.
|
|
272
|
+
*/
|
|
273
|
+
export type Action = 'skip' | boolean;
|
|
274
|
+
/**
|
|
275
|
+
* Move to the sibling at `index` next (after node itself is completely
|
|
276
|
+
* traversed).
|
|
277
|
+
*
|
|
278
|
+
* Useful if mutating the tree, such as removing the node the visitor is
|
|
279
|
+
* currently on, or any of its previous siblings.
|
|
280
|
+
* Results less than 0 or greater than or equal to `children.length` stop
|
|
281
|
+
* traversing the parent.
|
|
282
|
+
*/
|
|
283
|
+
export type Index = number;
|
|
284
|
+
/**
|
|
285
|
+
* List with one or two values, the first an action, the second an index.
|
|
286
|
+
*/
|
|
287
|
+
export type ActionTuple = [(Action | null | undefined | void)?, (Index | null | undefined)?];
|
|
288
|
+
/**
|
|
289
|
+
* Any value that can be returned from a visitor.
|
|
290
|
+
*/
|
|
291
|
+
export type VisitorResult =
|
|
292
|
+
| Action
|
|
293
|
+
| [(void | Action | null | undefined)?, (number | null | undefined)?]
|
|
294
|
+
| Index
|
|
295
|
+
| null
|
|
296
|
+
| undefined
|
|
297
|
+
| void;
|
|
298
|
+
/**
|
|
299
|
+
* Handle a node (matching `test`, if given).
|
|
300
|
+
*
|
|
301
|
+
* Visitors are free to transform `node`.
|
|
302
|
+
* They can also transform the parent of node (the last of `ancestors`).
|
|
303
|
+
*
|
|
304
|
+
* Replacing `node` itself, if `SKIP` is not returned, still causes its
|
|
305
|
+
* descendants to be walked (which is a bug).
|
|
306
|
+
*
|
|
307
|
+
* When adding or removing previous siblings of `node` (or next siblings, in
|
|
308
|
+
* case of reverse), the `Visitor` should return a new `Index` to specify the
|
|
309
|
+
* sibling to traverse after `node` is traversed.
|
|
310
|
+
* Adding or removing next siblings of `node` (or previous siblings, in case
|
|
311
|
+
* of reverse) is handled as expected without needing to return a new `Index`.
|
|
312
|
+
*
|
|
313
|
+
* Removing the children property of an ancestor still results in them being
|
|
314
|
+
* traversed.
|
|
315
|
+
*/
|
|
316
|
+
export type Visitor<
|
|
317
|
+
Visited extends import('unist').Node = import('unist').Node,
|
|
318
|
+
VisitedParents extends import('unist').Parent = import('unist').Parent,
|
|
319
|
+
> = (node: Visited, ancestors: Array<VisitedParents>) => VisitorResult;
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Build a typed `Visitor` function from a tree and a test.
|
|
323
|
+
*
|
|
324
|
+
* It will infer which values are passed as `node` and which as `parents`.
|
|
325
|
+
*/
|
|
326
|
+
export type BuildVisitor<
|
|
327
|
+
Tree extends import('unist').Node = import('unist').Node,
|
|
328
|
+
Check extends Test = Test,
|
|
329
|
+
> = Visitor<
|
|
330
|
+
Matches<InclusiveDescendant<Tree>, Check>,
|
|
331
|
+
Ancestor<Tree, Matches<InclusiveDescendant<Tree>, Check>>
|
|
332
|
+
>;
|
package/src/values.ts
CHANGED
|
@@ -40,3 +40,95 @@ export type MaybeAsyncThunk<T> = MaybeThunk<MaybePromise<T>>;
|
|
|
40
40
|
export function loadThunkValue<T>(value: MaybeThunk<T>): T {
|
|
41
41
|
return typeof value === 'function' ? value() : value;
|
|
42
42
|
}
|
|
43
|
+
|
|
44
|
+
type NextDepth = [1, 2, 3, 4, 5, 6, 7];
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Extract key-value entry pairs for each node in an object tree.
|
|
48
|
+
*/
|
|
49
|
+
export type NodeEntries<T, NoCircle = never, MaxDepth extends number = 0> = MaxDepth extends 7
|
|
50
|
+
? never
|
|
51
|
+
: T extends object
|
|
52
|
+
? {
|
|
53
|
+
[Key in keyof T & string]-?: T[Key] extends NoCircle
|
|
54
|
+
? never
|
|
55
|
+
: NodeEntries<T[Key], NoCircle | T[Key], NextDepth[MaxDepth]> extends infer Nested
|
|
56
|
+
? Nested extends { key: string; value: unknown }
|
|
57
|
+
? Nested['key'] extends ''
|
|
58
|
+
? {
|
|
59
|
+
key: Key;
|
|
60
|
+
value: Nested['value'];
|
|
61
|
+
}
|
|
62
|
+
:
|
|
63
|
+
| { key: Key; value: T[Key] }
|
|
64
|
+
| {
|
|
65
|
+
key: `${Key}.${Nested['key']}`;
|
|
66
|
+
value: Nested['value'];
|
|
67
|
+
}
|
|
68
|
+
: never
|
|
69
|
+
: never;
|
|
70
|
+
}[keyof T & string]
|
|
71
|
+
: { key: ''; value: T };
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Sets a value nested in an object tree, creating the path as needed.
|
|
75
|
+
*/
|
|
76
|
+
export function setNested<T extends object, const P extends NodeEntries<T>['key']>(
|
|
77
|
+
obj: T,
|
|
78
|
+
prop: P,
|
|
79
|
+
value: Extract<NodeEntries<T>, { key: P }>['value']
|
|
80
|
+
): void {
|
|
81
|
+
if (obj == null) throw new Error('Root object is nullish.');
|
|
82
|
+
const parts = prop.split('.');
|
|
83
|
+
|
|
84
|
+
let current: any = obj;
|
|
85
|
+
for (const [idx, propName] of parts.slice(0, -1).entries()) {
|
|
86
|
+
const next = current[propName];
|
|
87
|
+
const path = parts.slice(0, idx).join('.');
|
|
88
|
+
|
|
89
|
+
if (next == null) {
|
|
90
|
+
current = current[propName] = {};
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (typeof next !== 'object')
|
|
95
|
+
throw new Error(`Cannot set property on ${typeof next} value at "${path}".`);
|
|
96
|
+
|
|
97
|
+
current = next;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
current[parts[parts.length - 1]] = value;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Sets a value nested in an object tree, creating the path as needed, if it is not already set to a non-nullish value.
|
|
105
|
+
*/
|
|
106
|
+
export function setNestedIfNullish<T extends object, const P extends NodeEntries<T>['key']>(
|
|
107
|
+
obj: T,
|
|
108
|
+
prop: P,
|
|
109
|
+
value: Extract<NodeEntries<T>, { key: P }>['value']
|
|
110
|
+
): void {
|
|
111
|
+
if (obj == null) throw new Error('Root object is nullish.');
|
|
112
|
+
const parts = prop.split('.');
|
|
113
|
+
|
|
114
|
+
let current: any = obj;
|
|
115
|
+
for (const [idx, propName] of parts.slice(0, -1).entries()) {
|
|
116
|
+
const next = current[propName];
|
|
117
|
+
const path = parts.slice(0, idx).join('.');
|
|
118
|
+
|
|
119
|
+
if (next == null) {
|
|
120
|
+
current = current[propName] = {};
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (typeof next !== 'object')
|
|
125
|
+
throw new Error(`Cannot set property on ${typeof next} value at "${path}".`);
|
|
126
|
+
|
|
127
|
+
current = next;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const key = parts[parts.length - 1];
|
|
131
|
+
if (current[key] == null) {
|
|
132
|
+
current[parts[parts.length - 1]] = value;
|
|
133
|
+
}
|
|
134
|
+
}
|