@valbuild/core 0.12.0 → 0.13.1

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.
Files changed (72) hide show
  1. package/README.md +25 -37
  2. package/jest.config.js +4 -0
  3. package/package.json +1 -1
  4. package/src/Json.ts +4 -0
  5. package/src/expr/README.md +193 -0
  6. package/src/expr/eval.test.ts +202 -0
  7. package/src/expr/eval.ts +248 -0
  8. package/src/expr/expr.ts +91 -0
  9. package/src/expr/index.ts +3 -0
  10. package/src/expr/parser.test.ts +158 -0
  11. package/src/expr/parser.ts +229 -0
  12. package/src/expr/repl.ts +93 -0
  13. package/src/expr/tokenizer.test.ts +539 -0
  14. package/src/expr/tokenizer.ts +117 -0
  15. package/src/fetchVal.test.ts +164 -0
  16. package/src/fetchVal.ts +211 -0
  17. package/src/fp/array.ts +30 -0
  18. package/src/fp/index.ts +3 -0
  19. package/src/fp/result.ts +214 -0
  20. package/src/fp/util.ts +52 -0
  21. package/src/index.ts +55 -0
  22. package/src/initSchema.ts +45 -0
  23. package/src/initVal.ts +96 -0
  24. package/src/module.test.ts +170 -0
  25. package/src/module.ts +333 -0
  26. package/src/patch/deref.test.ts +300 -0
  27. package/src/patch/deref.ts +128 -0
  28. package/src/patch/index.ts +11 -0
  29. package/src/patch/json.test.ts +583 -0
  30. package/src/patch/json.ts +304 -0
  31. package/src/patch/operation.ts +74 -0
  32. package/src/patch/ops.ts +83 -0
  33. package/src/patch/parse.test.ts +202 -0
  34. package/src/patch/parse.ts +187 -0
  35. package/src/patch/patch.ts +46 -0
  36. package/src/patch/util.ts +67 -0
  37. package/src/schema/array.ts +52 -0
  38. package/src/schema/boolean.ts +38 -0
  39. package/src/schema/i18n.ts +65 -0
  40. package/src/schema/image.ts +70 -0
  41. package/src/schema/index.ts +46 -0
  42. package/src/schema/literal.ts +42 -0
  43. package/src/schema/number.ts +45 -0
  44. package/src/schema/object.ts +67 -0
  45. package/src/schema/oneOf.ts +60 -0
  46. package/src/schema/richtext.ts +417 -0
  47. package/src/schema/string.ts +49 -0
  48. package/src/schema/union.ts +62 -0
  49. package/src/selector/ExprProxy.test.ts +203 -0
  50. package/src/selector/ExprProxy.ts +209 -0
  51. package/src/selector/SelectorProxy.test.ts +172 -0
  52. package/src/selector/SelectorProxy.ts +237 -0
  53. package/src/selector/array.ts +37 -0
  54. package/src/selector/boolean.ts +4 -0
  55. package/src/selector/file.ts +14 -0
  56. package/src/selector/i18n.ts +13 -0
  57. package/src/selector/index.ts +159 -0
  58. package/src/selector/number.ts +4 -0
  59. package/src/selector/object.ts +22 -0
  60. package/src/selector/primitive.ts +17 -0
  61. package/src/selector/remote.ts +9 -0
  62. package/src/selector/selector.test.ts +453 -0
  63. package/src/selector/selectorOf.ts +7 -0
  64. package/src/selector/string.ts +4 -0
  65. package/src/source/file.ts +45 -0
  66. package/src/source/i18n.ts +60 -0
  67. package/src/source/index.ts +50 -0
  68. package/src/source/remote.ts +54 -0
  69. package/src/val/array.ts +10 -0
  70. package/src/val/index.ts +90 -0
  71. package/src/val/object.ts +13 -0
  72. package/src/val/primitive.ts +8 -0
@@ -0,0 +1,248 @@
1
+ /* eslint-disable @typescript-eslint/no-explicit-any */
2
+ import { Call, Expr, StringLiteral, StringTemplate, Sym } from "./expr";
3
+ import { Source } from "../source";
4
+ import { result } from "../fp";
5
+ import { Path, SourceOrExpr } from "../selector";
6
+ import { newSelectorProxy } from "../selector/SelectorProxy";
7
+ import { isSerializedVal, SourcePath } from "../val";
8
+
9
+ export class EvalError {
10
+ constructor(public readonly message: string, public readonly expr: Expr) {}
11
+
12
+ toString() {
13
+ return `${this.message} in: ${this.expr.transpile()}`;
14
+ }
15
+ }
16
+
17
+ type LocalSelector<S extends Source> = {
18
+ readonly [key: string | number]:
19
+ | LocalSelector<Source>
20
+ | ((...args: any[]) => any);
21
+ } & {
22
+ [SourceOrExpr]: S;
23
+ [Path]: SourcePath | undefined;
24
+ };
25
+
26
+ const MAX_STACK_SIZE = 100; // an arbitrary semi-large number
27
+ function evaluateSync(
28
+ expr: Expr,
29
+ getSource: (ref: string) => LocalSelector<Source>,
30
+ stack: readonly LocalSelector<Source>[][]
31
+ ): LocalSelector<Source> {
32
+ // TODO: amount of evaluates should be limited?
33
+ if (stack.length > MAX_STACK_SIZE) {
34
+ throw new EvalError(
35
+ `Stack overflow. Final frames: ${stack
36
+ .slice(-10)
37
+ .map((frame, i) =>
38
+ frame.map((s, j) => `@[${i},${j}]: ${JSON.stringify(s)}`).join(", ")
39
+ )
40
+ .join(" -> ")}`,
41
+ expr
42
+ );
43
+ }
44
+ if (expr instanceof Call) {
45
+ if (expr.children[0] instanceof Sym) {
46
+ if (expr.children[0].value === "val") {
47
+ if (expr.isAnon) {
48
+ throw new EvalError("cannot call 'val' as anonymous function", expr);
49
+ }
50
+ if (expr.children[1] instanceof StringLiteral) {
51
+ return getSource(expr.children[1].value);
52
+ } else {
53
+ throw new EvalError(
54
+ "argument of 'val' must be a string literal",
55
+ expr
56
+ );
57
+ }
58
+ } else if (expr.children[0].value === "json") {
59
+ if (expr.children.length !== 2) {
60
+ throw new EvalError(
61
+ "must call 'json' with exactly one argument",
62
+ expr
63
+ );
64
+ }
65
+ const value = evaluateSync(expr.children[1], getSource, stack);
66
+
67
+ const valObj = value[SourceOrExpr];
68
+ const valPath = value[Path];
69
+ if (typeof valObj !== "string") {
70
+ throw new EvalError(
71
+ `cannot parse JSON: ${JSON.stringify(valObj)}, expected string`,
72
+ expr.children[1]
73
+ );
74
+ }
75
+ try {
76
+ const serialized = JSON.parse(valObj);
77
+ if (isSerializedVal(serialized)) {
78
+ return newSelectorProxy(serialized.val, serialized.valPath);
79
+ }
80
+ const parsedValue = newSelectorProxy(JSON.parse(valObj), valPath);
81
+ return parsedValue;
82
+ } catch (e) {
83
+ if (e instanceof SyntaxError) {
84
+ throw new EvalError(
85
+ `cannot parse JSON: ${valObj}, ${
86
+ e.message
87
+ } - value: ${JSON.stringify(value)}`,
88
+ expr.children[1]
89
+ );
90
+ }
91
+ throw e;
92
+ }
93
+ } else if (expr.children[0].value === "stringify") {
94
+ // TODO: remove stringify
95
+ if (expr.children.length !== 2) {
96
+ throw new EvalError(
97
+ "must call 'stringify' with exactly one argument",
98
+ expr
99
+ );
100
+ }
101
+ const res = evaluateSync(expr.children[1], getSource, stack);
102
+ return newSelectorProxy(JSON.stringify(res[SourceOrExpr]));
103
+ }
104
+ }
105
+ const prop = evaluateSync(expr.children[0], getSource, stack)[SourceOrExpr];
106
+ if (expr.children.length === 1) {
107
+ // TODO: return if literal only?
108
+ return newSelectorProxy(prop);
109
+ }
110
+ const obj = evaluateSync(expr.children[1], getSource, stack);
111
+ if (typeof prop !== "string" && typeof prop !== "number") {
112
+ throw new EvalError(
113
+ `cannot access ${JSON.stringify(obj)} with property ${JSON.stringify(
114
+ prop
115
+ )}: is not a string or number`,
116
+ expr
117
+ );
118
+ }
119
+
120
+ if (prop in obj) {
121
+ if (expr.isAnon) {
122
+ // anon functions:
123
+ const maybeFunction = obj[prop];
124
+ if (typeof maybeFunction !== "function") {
125
+ throw new EvalError(
126
+ `cannot access property ${JSON.stringify(prop)} of ${JSON.stringify(
127
+ obj
128
+ )}: required higher ordered function got ${typeof obj[prop]}`,
129
+ expr
130
+ );
131
+ }
132
+ if (expr.children[0] instanceof Sym) {
133
+ return maybeFunction((...args: any[]) => {
134
+ return evaluateSync(
135
+ expr.children[2],
136
+ getSource,
137
+ stack.concat([args])
138
+ );
139
+ });
140
+ } else {
141
+ throw new EvalError(
142
+ `cannot call an expression that is not a symbol, got: '${expr.children[0].type}'`,
143
+ expr
144
+ );
145
+ }
146
+ } else {
147
+ // non-anon functions:
148
+ if (expr.children[0] instanceof Sym) {
149
+ if (expr.children[0].value === "val") {
150
+ if (expr.children[1] instanceof StringLiteral) {
151
+ return getSource(expr.children[1].value);
152
+ } else {
153
+ throw new EvalError(
154
+ "argument of 'val' must be a string literal",
155
+ expr
156
+ );
157
+ }
158
+ }
159
+ }
160
+ const args = expr.children.slice(2);
161
+ if (args.length > 0) {
162
+ const maybeFunction = obj[prop];
163
+ if (typeof maybeFunction !== "function") {
164
+ throw new EvalError(
165
+ `cannot access property ${JSON.stringify(
166
+ prop
167
+ )} of ${JSON.stringify(obj)}: required function got ${typeof obj[
168
+ prop
169
+ ]}`,
170
+ expr
171
+ );
172
+ }
173
+ return maybeFunction(
174
+ ...args.map((arg) => evaluateSync(arg, getSource, stack))
175
+ );
176
+ }
177
+ const maybeValue = obj[prop];
178
+ if (typeof maybeValue === "function") {
179
+ throw new EvalError(
180
+ `cannot access property ${JSON.stringify(prop)} of ${JSON.stringify(
181
+ obj
182
+ )}: required value got ${typeof obj[prop]}`,
183
+ expr
184
+ );
185
+ }
186
+ return maybeValue;
187
+ }
188
+ }
189
+ } else if (expr instanceof Sym) {
190
+ if (expr.value.startsWith("@")) {
191
+ const [i, j, rest] = expr.value.slice(2, -1).split(",");
192
+ if (rest) {
193
+ throw new EvalError(`cannot access stack: too many indices`, expr);
194
+ }
195
+ const stackValue = stack[Number(i)]?.[Number(j)];
196
+ if (stackValue === undefined) {
197
+ throw new EvalError(`cannot access stack: out of bounds`, expr);
198
+ }
199
+ return stackValue;
200
+ } else if (expr.value === "()") {
201
+ return newSelectorProxy(null);
202
+ }
203
+ return newSelectorProxy(expr.value);
204
+ } else if (expr instanceof StringLiteral) {
205
+ return newSelectorProxy(expr.value);
206
+ } else if (expr instanceof StringTemplate) {
207
+ return newSelectorProxy(
208
+ expr.children
209
+ .map((child) => {
210
+ if (child instanceof Sym && child.value === "()") {
211
+ return "null";
212
+ }
213
+ const evalRes = evaluateSync(child, getSource, stack);
214
+ if (
215
+ child.type === "StringLiteral" ||
216
+ child.type === "StringTemplate"
217
+ ) {
218
+ return evalRes[SourceOrExpr];
219
+ }
220
+ if (Path in evalRes) {
221
+ // a selector, so serialize to Val
222
+ return JSON.stringify({
223
+ val: evalRes[SourceOrExpr],
224
+ valPath: evalRes[Path],
225
+ });
226
+ }
227
+ return JSON.stringify(evalRes[SourceOrExpr]);
228
+ })
229
+ .join("")
230
+ );
231
+ }
232
+ throw new EvalError(`could not evaluate`, expr);
233
+ }
234
+
235
+ export function evaluate(
236
+ expr: Expr,
237
+ source: (ref: string) => LocalSelector<Source>,
238
+ stack: readonly LocalSelector<Source>[][]
239
+ ): result.Result<LocalSelector<Source>, EvalError> {
240
+ try {
241
+ return result.ok(evaluateSync(expr, source, stack));
242
+ } catch (err) {
243
+ if (err instanceof EvalError) {
244
+ return result.err(err);
245
+ }
246
+ throw err;
247
+ }
248
+ }
@@ -0,0 +1,91 @@
1
+ /* eslint-disable @typescript-eslint/no-unused-vars */
2
+
3
+ export abstract class Expr {
4
+ abstract type: "StringLiteral" | "Sym" | "StringTemplate" | "Call";
5
+ abstract transpile(): string;
6
+ constructor(public readonly span?: [number, number?]) {}
7
+ }
8
+
9
+ export class StringLiteral extends Expr {
10
+ public type = "StringLiteral" as const;
11
+ constructor(
12
+ public readonly value: string,
13
+ span?: [start: number, stop: number]
14
+ ) {
15
+ super(span);
16
+ }
17
+
18
+ transpile() {
19
+ return `'${this.value}'`;
20
+ }
21
+ }
22
+
23
+ export class Sym extends Expr {
24
+ public type = "Sym" as const;
25
+ constructor(
26
+ public readonly value: string,
27
+ span?: [start: number, stop: number]
28
+ ) {
29
+ super(span);
30
+ }
31
+
32
+ transpile() {
33
+ return this.value;
34
+ }
35
+ }
36
+
37
+ export const NilSym = new Sym("()");
38
+
39
+ export class StringTemplate extends Expr {
40
+ public type = "StringTemplate" as const;
41
+ constructor(
42
+ public readonly children: readonly Expr[],
43
+ span?: [number, number]
44
+ ) {
45
+ super(span);
46
+ }
47
+
48
+ transpile() {
49
+ return `'${this.children
50
+ .map((child) => {
51
+ if (child instanceof StringLiteral) {
52
+ return child.value;
53
+ } else {
54
+ return `\${${child.transpile()}}`;
55
+ }
56
+ })
57
+ .join("")}'`;
58
+ }
59
+ }
60
+
61
+ export class Call extends Expr {
62
+ public type = "Call" as const;
63
+ constructor(
64
+ public readonly children: readonly Expr[],
65
+ public readonly isAnon: boolean,
66
+ span?: [number, number]
67
+ ) {
68
+ super(span);
69
+ }
70
+
71
+ transpile() {
72
+ if (this.isAnon) {
73
+ return `!(${this.children.map((child) => child.transpile()).join(" ")})`;
74
+ }
75
+ return `(${this.children.map((child) => child.transpile()).join(" ")})`;
76
+ }
77
+ }
78
+
79
+ // export function interpret(
80
+ // expr: SExpr,
81
+ // moduleId: string,
82
+ // schemas: {
83
+ // [moduleId: string]: Schema<Source>;
84
+ // },
85
+ // getSource: (moduleId: string) => Promise<Source>
86
+ // ) {}
87
+
88
+ // TODO: use this instead of including the unescaped strings in the parser
89
+ function escapeString(str: string) {
90
+ return str.replace(/\\/g, "\\\\");
91
+ }
@@ -0,0 +1,3 @@
1
+ export { parse } from "./parser";
2
+ export { Call, Expr, NilSym, StringLiteral, StringTemplate, Sym } from "./expr";
3
+ export { evaluate } from "./eval";
@@ -0,0 +1,158 @@
1
+ import { result } from "../../fp";
2
+ import { parse } from "./parser";
3
+
4
+ const ParserTestCases: {
5
+ input: string;
6
+ error?: {
7
+ span: [start: number, stop: number];
8
+ };
9
+ overrideTest?: string;
10
+ }[] = [
11
+ {
12
+ input: "!(",
13
+ error: {
14
+ span: [0, 0],
15
+ },
16
+ },
17
+ {
18
+ input: "')'",
19
+ },
20
+ {
21
+ input: "(",
22
+ error: {
23
+ span: [0, 0],
24
+ },
25
+ },
26
+ {
27
+ input: "()",
28
+ },
29
+ {
30
+ input: " ( ) ",
31
+ overrideTest: "()",
32
+ },
33
+ {
34
+ input: "(reverse foo ())",
35
+ },
36
+ {
37
+ input: "(b ab)", // single character tokens
38
+ },
39
+ {
40
+ input: "!(map fn value)",
41
+ },
42
+ {
43
+ input: "!(map (map foo bar) value)",
44
+ },
45
+ {
46
+ input: "'foo'",
47
+ },
48
+ // this is the JS equivalent: 'f\'oo'
49
+ {
50
+ input: "'f\\'oo'",
51
+ },
52
+ // lenient tokenization (errors must handled by the parser)
53
+ // this is the JS equivalent: 'f\\'oofail'
54
+ {
55
+ input: "'f\\\\'oo'fail",
56
+ error: {
57
+ span: [5, 11],
58
+ },
59
+ },
60
+ {
61
+ input: "(fo() (fail zoo))",
62
+ error: {
63
+ span: [1, 3], // this would preferably be [1, 4]
64
+ },
65
+ },
66
+ // this is the JS equivalent: 'f\\\'oo'
67
+ {
68
+ input: "'f\\\\\\'oo'",
69
+ },
70
+ {
71
+ input: "(foo (bar zoo))",
72
+ },
73
+ {
74
+ input: " (foo (bar 'he\\'pp' zoo)) ",
75
+ overrideTest: "(foo (bar 'he\\'pp' zoo))",
76
+ },
77
+ {
78
+ input: "''",
79
+ },
80
+ //interpolation:
81
+ {
82
+ input: "'${'str'}'",
83
+ overrideTest: "'str'",
84
+ },
85
+ {
86
+ input: "'${'${(foo bar)}'}'",
87
+ },
88
+ {
89
+ input: "'foo${(bar baz)}'",
90
+ },
91
+ {
92
+ input: "'${'foo ${(foo bar)}'}'",
93
+ },
94
+ {
95
+ input: "'${'${'${(foo bar)}'}'}'",
96
+ },
97
+ {
98
+ input: `(json '{"foo": "bar"}')`,
99
+ },
100
+ {
101
+ input: `(json '{"foo": \${(foo bar)}}')`,
102
+ },
103
+ {
104
+ input: `(json '{"foo": \${(foo bar)}, "baz": "baz"}')`,
105
+ },
106
+ {
107
+ input: `!(map 'title' )`,
108
+ overrideTest: `!(map 'title')`,
109
+ },
110
+ {
111
+ input: `!(map
112
+ (ref '/foo/bar')
113
+ ('title' @0)
114
+ )`,
115
+ overrideTest: `!(map (ref '/foo/bar') ('title' @0))`,
116
+ },
117
+ ];
118
+
119
+ describe("parser", () => {
120
+ test.each(ParserTestCases)(
121
+ 'expr: "$input"',
122
+ ({ input, error, overrideTest }) => {
123
+ const res = parse(input);
124
+ if (error) {
125
+ if (result.isErr(res)) {
126
+ expect(res.error.span).toEqual(error.span);
127
+ } else {
128
+ expect(res).toHaveProperty("error");
129
+ }
130
+ } else if (result.isErr(res)) {
131
+ process.stdout.write(res.error.message + ":\n\n");
132
+ process.stdout.write(input + "\n");
133
+ let underline = "";
134
+ for (let i = 0; i < input.length; i++) {
135
+ if (
136
+ res.error.span &&
137
+ i >= res.error.span[0] &&
138
+ i <= (res.error.span?.[1] || -1)
139
+ ) {
140
+ underline += "^";
141
+ } else {
142
+ if (input[i] === "\n") {
143
+ if (!underline.includes("^")) {
144
+ underline = "";
145
+ }
146
+ } else {
147
+ underline += " ";
148
+ }
149
+ }
150
+ }
151
+ process.stderr.write(underline + "\n");
152
+ expect(res).toHaveProperty("value");
153
+ } else {
154
+ expect(res.value.transpile()).toBe(overrideTest || input);
155
+ }
156
+ }
157
+ );
158
+ });