@mark1russell7/vex 0.8.1 → 0.9.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.
package/build/index.js CHANGED
@@ -1057,6 +1057,607 @@ const LIST_OPS = /* @__PURE__ */ new Set([
1057
1057
  /** This function tells if a name is the name of a core list op. */
1058
1058
  const isListOp = (op) => LIST_OPS.has(op);
1059
1059
  //#endregion
1060
+ //#region ../../node_modules/.pnpm/@mark1russell7+coeval@0.1.0/node_modules/@mark1russell7/coeval/build/index.js
1061
+ /** The keys that an envelope can have. */
1062
+ const ENVELOPE_KEYS = [
1063
+ "type",
1064
+ "value",
1065
+ "name",
1066
+ "own"
1067
+ ];
1068
+ /**
1069
+ * This function tells if a value is a JSON record (not an array and not null).
1070
+ *
1071
+ * @param value - The value to examine.
1072
+ * @returns `true` for a record.
1073
+ */
1074
+ function isRecord$1(value) {
1075
+ return typeof value === "object" && value !== null && !Array.isArray(value);
1076
+ }
1077
+ /**
1078
+ * This function reads a field of a record. It reads only the own fields, thus `constructor` is not a field.
1079
+ *
1080
+ * @param record - The record.
1081
+ * @param key - The name of the field.
1082
+ * @returns The value of the field, or `undefined` when the record has no such field.
1083
+ */
1084
+ function field(record, key) {
1085
+ return Object.hasOwn(record, key) ? record[key] : void 0;
1086
+ }
1087
+ /**
1088
+ * This function tells if a value is a key of a path: a text, or a whole number from 0.
1089
+ *
1090
+ * @param value - The value to examine.
1091
+ * @returns `true` for a key.
1092
+ */
1093
+ function isKey(value) {
1094
+ return typeof value === "string" || typeof value === "number" && Number.isInteger(value) && value >= 0;
1095
+ }
1096
+ /**
1097
+ * This function tells if a value is a reference to a type. The reference is a text, a list of keys, or a document
1098
+ * of type `ref` whose path starts at the root `world`.
1099
+ *
1100
+ * @param value - The value to examine.
1101
+ * @returns `true` for a reference to a type.
1102
+ */
1103
+ function isTypeRef(value) {
1104
+ if (typeof value === "string") return value !== "";
1105
+ if (Array.isArray(value)) return value.length > 0 && value.every(isKey);
1106
+ if (!isRecord$1(value)) return false;
1107
+ const path = field(value, "value");
1108
+ return field(value, "type") === "ref" && Array.isArray(path) && path[0] === "world";
1109
+ }
1110
+ /**
1111
+ * This function gives the path of a reference to a type, from the root of the world.
1112
+ *
1113
+ * @param type - The reference.
1114
+ * @returns The keys from the root of the world, or `undefined` for a computed step that has no fixed key.
1115
+ */
1116
+ function typePath(type) {
1117
+ if (typeof type === "string") return [type];
1118
+ if (Array.isArray(type)) return type;
1119
+ const steps = type.value.slice(1);
1120
+ return steps.every(isKey) ? steps : void 0;
1121
+ }
1122
+ /**
1123
+ * This function gives the text of a type for a reader: its keys, joined with a dot.
1124
+ *
1125
+ * @param type - The reference to the type.
1126
+ * @returns The text, for example `git.push`.
1127
+ */
1128
+ function typeName(type) {
1129
+ return typePath(type)?.join(".") ?? "(computed)";
1130
+ }
1131
+ /**
1132
+ * This function tells if a value has the form of an envelope. That form is a record with a reference to a type
1133
+ * and a `value`. It has no other keys than the keys of an envelope. A contract decides where an envelope is
1134
+ * expected. This function only checks the form.
1135
+ *
1136
+ * @param value - The value to examine.
1137
+ * @returns `true` when the value has the form of an envelope.
1138
+ */
1139
+ function isEnvelope(value) {
1140
+ if (!isRecord$1(value)) return false;
1141
+ if (!isTypeRef(field(value, "type")) || !Object.hasOwn(value, "value")) return false;
1142
+ const name = field(value, "name");
1143
+ if (name !== void 0 && typeof name !== "string") return false;
1144
+ const own = field(value, "own");
1145
+ if (own !== void 0 && !isRecord$1(own)) return false;
1146
+ return Object.keys(value).every((key) => ENVELOPE_KEYS.includes(key));
1147
+ }
1148
+ /**
1149
+ * This function makes an envelope.
1150
+ *
1151
+ * @param type - The reference to the kind.
1152
+ * @param value - The value.
1153
+ * @param header - The optional name and own entries.
1154
+ * @returns The envelope.
1155
+ */
1156
+ function typed(type, value, header = {}) {
1157
+ return {
1158
+ type,
1159
+ value,
1160
+ ...header.name === void 0 ? {} : { name: header.name },
1161
+ ...header.own === void 0 ? {} : { own: header.own }
1162
+ };
1163
+ }
1164
+ /**
1165
+ * This function makes a reference document: a path from a root of the context.
1166
+ *
1167
+ * @param path - The steps. The first step is a root: `self`, `names`, `world`, `event` or `caps`.
1168
+ * @returns The document of type `ref`.
1169
+ */
1170
+ function ref$1(...path) {
1171
+ return typed("ref", path);
1172
+ }
1173
+ //#endregion
1174
+ //#region src/codec.ts
1175
+ /** This function tells if a value is a record: an object that is not an array. */
1176
+ const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
1177
+ const isPlainRecord = (u) => {
1178
+ if (!isRecord(u)) return false;
1179
+ const proto = Object.getPrototypeOf(u);
1180
+ return proto === Object.prototype || proto === null;
1181
+ };
1182
+ /** This function gives the JSON form of a value, or the reason why the value has no JSON form. */
1183
+ function encodeValue(u, domains) {
1184
+ if (u === null || typeof u === "string" || typeof u === "boolean") return ok(u);
1185
+ if (typeof u === "number") {
1186
+ if (Object.is(u, -0)) return ok({
1187
+ $vex: "number",
1188
+ value: "-0"
1189
+ });
1190
+ return Number.isFinite(u) ? ok(u) : ok({
1191
+ $vex: "number",
1192
+ value: Number.isNaN(u) ? "NaN" : u > 0 ? "Infinity" : "-Infinity"
1193
+ });
1194
+ }
1195
+ if (Array.isArray(u)) {
1196
+ const out = [];
1197
+ for (const x of u) {
1198
+ const r = encodeValue(x, domains);
1199
+ if (!r.ok) return r;
1200
+ out.push(r.value);
1201
+ }
1202
+ return ok(out);
1203
+ }
1204
+ if (isPlainRecord(u)) {
1205
+ const out = {};
1206
+ for (const [k, x] of Object.entries(u)) {
1207
+ const r = encodeValue(x, domains);
1208
+ if (!r.ok) return r;
1209
+ out[k] = r.value;
1210
+ }
1211
+ return ok(Object.hasOwn(u, "$vex") ? {
1212
+ $vex: "escape",
1213
+ value: out
1214
+ } : out);
1215
+ }
1216
+ const d = domains.find((dom) => dom.encode !== void 0 && dom.is(u));
1217
+ if (d?.encode !== void 0) return ok({
1218
+ $vex: "domain",
1219
+ domain: d.name,
1220
+ value: d.encode(u)
1221
+ });
1222
+ return fail(vexError("bad-expression", "a literal value is not JSON data and no domain encodes it"));
1223
+ }
1224
+ const NUMBERS = {
1225
+ "-0": -0,
1226
+ NaN: NaN,
1227
+ Infinity: Number.POSITIVE_INFINITY,
1228
+ "-Infinity": Number.NEGATIVE_INFINITY
1229
+ };
1230
+ /** This function reads a value from its JSON form. */
1231
+ function decodeValue(u, domains) {
1232
+ if (Array.isArray(u)) {
1233
+ const out = [];
1234
+ for (const x of u) {
1235
+ const r = decodeValue(x, domains);
1236
+ if (!r.ok) return r;
1237
+ out.push(r.value);
1238
+ }
1239
+ return ok(out);
1240
+ }
1241
+ if (!isRecord(u)) return ok(u);
1242
+ const fields = (record) => {
1243
+ const out = {};
1244
+ for (const [k, x] of Object.entries(record)) {
1245
+ const r = decodeValue(x, domains);
1246
+ if (!r.ok) return r;
1247
+ out[k] = r.value;
1248
+ }
1249
+ return ok(out);
1250
+ };
1251
+ const kind = u["$vex"];
1252
+ if (kind === "escape" && isRecord(u["value"])) return fields(u["value"]);
1253
+ if (kind === "number" && typeof u["value"] === "string" && Object.hasOwn(NUMBERS, u["value"])) return ok(NUMBERS[u["value"]]);
1254
+ if (kind === "domain" && typeof u["domain"] === "string") {
1255
+ const name = u["domain"];
1256
+ const d = domains.find((dom) => dom.name === name);
1257
+ if (d?.decode === void 0) return fail(vexError("bad-expression", `no domain "${name}" decodes a literal`));
1258
+ return ok(d.decode(u["value"]));
1259
+ }
1260
+ return fields(u);
1261
+ }
1262
+ //#endregion
1263
+ //#region src/document.ts
1264
+ /**
1265
+ * The documents of Vex. A document is the form of an expression in coeval, the language base of the family. Each term
1266
+ * is an envelope `{ type, value }`, and a reference is a path from a root. The rules are decision D12 of coeval:
1267
+ * <https://github.com/mark1russell7/coeval/blob/main/docs/DECISIONS.md>.
1268
+ *
1269
+ * | Expression | Document |
1270
+ * |---|---|
1271
+ * | `lit` | the JSON value of the literal. A value with the shape of an envelope is `{ "type": "lit", "value": x }`. |
1272
+ * | `ref` | `{ "type": "ref", "value": ["self", ...moves, ...fields] }` |
1273
+ * | `var` | `{ "type": "ref", "value": ["names", name] }` |
1274
+ * | `app` | `{ "type": ["ops", ...keys], "value": [...args] }`. The keys are the name of the op, split at its dots. |
1275
+ * | `let` | `{ "type": "let", "value": { "bind", "body" } }` |
1276
+ * | `fn` | `{ "type": "fn", "value": { "params", "body" } }` |
1277
+ * | `call` | `{ "type": "call", "value": { "fn": { "type": "ref", "value": ["names", name] }, "args" } }` |
1278
+ * | `rec` | `{ "type": "record", "value": { ...fields } }` |
1279
+ * | `each` | `{ "type": "each", "value": { "axis", "body", "at"? } }` |
1280
+ * | `fold` | `{ "type": "fold", "value": { "axis", "init", "step", "result", "at"? } }` |
1281
+ * | `iterate` | `{ "type": "iterate", "value": { "limit", "init", "step", "until"?, "result" } }` |
1282
+ * | `ext` | `{ "type": ["ext", ...keys], "value": data }` |
1283
+ * | a move | `{ "type": ["moves", kind], "value": v }` |
1284
+ * | an axis | `{ "type": ["axes", name], "value": { ...parameters } }` |
1285
+ *
1286
+ * The address `at` of `each` and `fold` is a reference from `self` with moves only. An empty address is no address.
1287
+ */
1288
+ /** The axes without parameters. */
1289
+ const PLAIN_AXES = /* @__PURE__ */ new Set([
1290
+ "all",
1291
+ "others",
1292
+ "other",
1293
+ "children",
1294
+ "ancestors",
1295
+ "descendants",
1296
+ "siblings",
1297
+ "successors",
1298
+ "predecessors",
1299
+ "reachable"
1300
+ ]);
1301
+ /** The moves without a value. */
1302
+ const PLAIN_MOVES = /* @__PURE__ */ new Map([
1303
+ ["other", other],
1304
+ ["origin", origin],
1305
+ ["parent", parent]
1306
+ ]);
1307
+ /** The stop of a conversion. The functions of this module throw it, and the top of the conversion gives its error. */
1308
+ var Stop = class {
1309
+ error;
1310
+ constructor(error) {
1311
+ this.error = error;
1312
+ }
1313
+ };
1314
+ /** This function gives the location of a child: a JSON Pointer, with the escapes of RFC 6901. */
1315
+ const into = (where, step) => `${where}/${String(step).replaceAll("~", "~0").replaceAll("/", "~1")}`;
1316
+ /** This function stops the reading of a document that is not valid at `where`. */
1317
+ function bad(where, reason) {
1318
+ throw new Stop(vexError("bad-expression", `the document is not valid at ${where === "" ? "its root" : `"${where}"`}: ${reason}`));
1319
+ }
1320
+ /** This function does a conversion. It gives its value, or the error of the conversion. It does not throw. */
1321
+ function attempt(work, threw, deep) {
1322
+ try {
1323
+ return ok(work());
1324
+ } catch (thrown) {
1325
+ if (thrown instanceof Stop) return fail(thrown.error);
1326
+ if (isStackOverflow(thrown)) return fail(vexError("depth", deep, { thrown }));
1327
+ return fail(vexError("threw", threw, { thrown }));
1328
+ }
1329
+ }
1330
+ /**
1331
+ * This function tells if a value is a document: an envelope `{ type, value }`. A node of the tagged IR is not an
1332
+ * envelope, because it has the key `tag`. Thus `compile` and `evaluate` can take either one (DOC.ENTRY).
1333
+ */
1334
+ function isDocument(u) {
1335
+ return isEnvelope(u);
1336
+ }
1337
+ /**
1338
+ * This function gives the document of an expression (DOC.TERM). The root is always an envelope, so `compile` can tell a
1339
+ * document from the tagged IR. A literal value has the JSON form of IR.JSON, so a domain value needs `encode` (DOC.LITERAL).
1340
+ * An expression that is not valid, or a literal without a JSON form, gives the error `#VALUE!` (DOC.ERROR).
1341
+ */
1342
+ function toDocument(e, domains = []) {
1343
+ const shape = shapeError(e);
1344
+ if (shape !== void 0) return fail(vexError("bad-expression", shape));
1345
+ return attempt(() => new Writer(domains).envelope(e), "the expression has no document", "the expression is too deep for the call stack of the engine");
1346
+ }
1347
+ /**
1348
+ * This function reads an expression from a document (DOC.TERM). It is the inverse of `toDocument`. It checks the
1349
+ * expression as `compile` does (EVAL.SHAPE). A document that is not valid gives `#VALUE!` with its location (DOC.ERROR).
1350
+ */
1351
+ function fromDocument(doc, domains = []) {
1352
+ const read = attempt(() => new Reader(domains).term(doc, ""), "a decoder of a domain threw an exception", "the document is too deep for the call stack of the engine");
1353
+ if (!read.ok) return read;
1354
+ const shape = shapeError(read.value);
1355
+ return shape === void 0 ? read : fail(vexError("bad-expression", `the document gives an expression that is not valid: ${shape}`));
1356
+ }
1357
+ /** The writer of documents. Its methods throw a `Stop` for a literal without a JSON form. */
1358
+ var Writer = class {
1359
+ #domains;
1360
+ constructor(domains) {
1361
+ this.#domains = domains;
1362
+ }
1363
+ /** This method gives the document of a term. A literal is its JSON value, except a value with the shape of an envelope. */
1364
+ term(e) {
1365
+ if (e.tag !== "lit") return this.envelope(e);
1366
+ const value = this.#value(e.value);
1367
+ return isEnvelope(value) ? typed("lit", value) : value;
1368
+ }
1369
+ /** This method gives the document of a term as an envelope. Here a literal is an envelope too. */
1370
+ envelope(e) {
1371
+ switch (e.tag) {
1372
+ case "lit": return typed("lit", this.#value(e.value));
1373
+ case "ref": return ref$1("self", ...this.#moves(e.at), ...e.path);
1374
+ case "var": return ref$1("names", e.name);
1375
+ case "app": return typed(["ops", ...e.op.split(".")], e.args.map((a) => this.term(a)));
1376
+ case "let": return typed("let", {
1377
+ bind: this.#names(e.bind),
1378
+ body: this.term(e.body)
1379
+ });
1380
+ case "fn": return typed("fn", {
1381
+ params: [...e.params],
1382
+ body: this.term(e.body)
1383
+ });
1384
+ case "call": return typed("call", {
1385
+ fn: ref$1("names", e.fn),
1386
+ args: e.args.map((a) => this.term(a))
1387
+ });
1388
+ case "rec": return typed("record", this.#names(e.fields));
1389
+ case "each": return typed("each", {
1390
+ axis: this.#axis(e.axis),
1391
+ body: this.term(e.body),
1392
+ ...this.#at(e.at)
1393
+ });
1394
+ case "fold": return typed("fold", {
1395
+ axis: this.#axis(e.axis),
1396
+ init: this.#names(e.init),
1397
+ step: this.#names(e.step),
1398
+ result: this.term(e.result),
1399
+ ...this.#at(e.at)
1400
+ });
1401
+ case "iterate": return typed("iterate", {
1402
+ limit: e.limit,
1403
+ init: this.#names(e.init),
1404
+ step: this.#names(e.step),
1405
+ ...e.until === void 0 ? {} : { until: this.term(e.until) },
1406
+ result: this.term(e.result)
1407
+ });
1408
+ case "ext": return typed(["ext", ...e.kind.split(".")], e.data);
1409
+ }
1410
+ }
1411
+ /** This method gives the JSON form of a literal value (IR.JSON). */
1412
+ #value(u) {
1413
+ const r = encodeValue(u, this.#domains);
1414
+ if (!r.ok) throw new Stop(r.error);
1415
+ return r.value;
1416
+ }
1417
+ /** This method gives the documents of the terms of a record of names. */
1418
+ #names(names) {
1419
+ return Object.fromEntries(Object.entries(names).map(([name, x]) => [name, this.term(x)]));
1420
+ }
1421
+ /** This method gives the step documents of the moves of an address. */
1422
+ #moves(at) {
1423
+ return (at ?? []).map((m) => this.#move(m));
1424
+ }
1425
+ /** This method gives the step document of a move. A computed key or position is an envelope (DOC.MOVE). */
1426
+ #move(m) {
1427
+ switch (m.t) {
1428
+ case "key": return typed(["moves", "key"], typeof m.key === "string" ? m.key : this.envelope(m.key));
1429
+ case "index": return typed(["moves", "index"], typeof m.i === "number" ? m.i : this.envelope(m.i));
1430
+ case "offset": return typed(["moves", "offset"], [...m.d]);
1431
+ case "other":
1432
+ case "origin":
1433
+ case "parent": return typed(["moves", m.t], null);
1434
+ }
1435
+ }
1436
+ /** This method gives the field `at` of `each` and `fold`: a reference from `self` with moves only, or no field. */
1437
+ #at(at) {
1438
+ return at === void 0 || at.length === 0 ? {} : { at: ref$1("self", ...this.#moves(at)) };
1439
+ }
1440
+ /** This method gives the document of an axis (DOC.AXIS). */
1441
+ #axis(a) {
1442
+ const name = ["axes", a.t];
1443
+ switch (a.t) {
1444
+ case "neighbors": return typed(name, { n: a.n });
1445
+ case "window": return typed(name, {
1446
+ from: a.from,
1447
+ to: a.to
1448
+ });
1449
+ case "table": return typed(name, { name: a.name });
1450
+ case "list": return typed(name, { list: this.term(a.list) });
1451
+ case "reverse": return typed(name, { axis: this.#axis(a.axis) });
1452
+ case "where": return typed(name, {
1453
+ axis: this.#axis(a.axis),
1454
+ test: this.term(a.test)
1455
+ });
1456
+ case "all":
1457
+ case "others":
1458
+ case "other":
1459
+ case "children":
1460
+ case "ancestors":
1461
+ case "descendants":
1462
+ case "siblings":
1463
+ case "successors":
1464
+ case "predecessors":
1465
+ case "reachable": return typed(name, {});
1466
+ }
1467
+ }
1468
+ };
1469
+ /** The reader of documents. Its methods throw a `Stop` at the first part that is not valid. */
1470
+ var Reader = class {
1471
+ #domains;
1472
+ constructor(domains) {
1473
+ this.#domains = domains;
1474
+ }
1475
+ /** This method reads a term. An envelope is a term, and another value is a literal (DOC.TERM). */
1476
+ term(u, where) {
1477
+ return isDocument(u) ? this.#envelope(u, where) : lit(this.#value(u, where));
1478
+ }
1479
+ /** This method reads a term in an envelope. */
1480
+ #envelope(u, where) {
1481
+ const at = into(where, "value");
1482
+ const [head, ...rest] = this.#type(u, where);
1483
+ if (rest.length > 0 && (head === "ops" || head === "ext")) {
1484
+ const name = this.#name(rest, into(where, "type"));
1485
+ return head === "ops" ? app(name, ...this.#list(u.value, at).map((x, i) => this.term(x, into(at, i)))) : ext(name, u.value);
1486
+ }
1487
+ if (rest.length > 0) return bad(where, `the type "${typeName(u.type)}" is not a term of Vex`);
1488
+ switch (head) {
1489
+ case "lit": return lit(this.#value(u.value, at));
1490
+ case "ref": return this.#ref(u.value, at);
1491
+ case "let": {
1492
+ const f = fields(u.value, at, ["bind", "body"]);
1493
+ return let_(this.#names(f["bind"], into(at, "bind")), this.term(f["body"], into(at, "body")));
1494
+ }
1495
+ case "fn": {
1496
+ const f = fields(u.value, at, ["params", "body"]);
1497
+ const params = this.#list(f["params"], into(at, "params"));
1498
+ if (!params.every((p) => typeof p === "string")) return bad(into(at, "params"), "a parameter is not a text");
1499
+ return fn(params, this.term(f["body"], into(at, "body")));
1500
+ }
1501
+ case "call": {
1502
+ const f = fields(u.value, at, ["fn", "args"]);
1503
+ const name = this.#function(f["fn"], into(at, "fn"));
1504
+ return call(name, ...this.#list(f["args"], into(at, "args")).map((x, i) => this.term(x, into(into(at, "args"), i))));
1505
+ }
1506
+ case "record": return rec(this.#names(u.value, at));
1507
+ case "each": {
1508
+ const f = fields(u.value, at, ["axis", "body"], ["at"]);
1509
+ return each(this.#axis(f["axis"], into(at, "axis")), this.term(f["body"], into(at, "body")), this.#address(f["at"], into(at, "at")));
1510
+ }
1511
+ case "fold": {
1512
+ const f = fields(u.value, at, [
1513
+ "axis",
1514
+ "init",
1515
+ "step",
1516
+ "result"
1517
+ ], ["at"]);
1518
+ return fold(this.#axis(f["axis"], into(at, "axis")), this.#names(f["init"], into(at, "init")), this.#names(f["step"], into(at, "step")), this.term(f["result"], into(at, "result")), this.#address(f["at"], into(at, "at")));
1519
+ }
1520
+ case "iterate": {
1521
+ const f = fields(u.value, at, [
1522
+ "limit",
1523
+ "init",
1524
+ "step",
1525
+ "result"
1526
+ ], ["until"]);
1527
+ const init = this.#names(f["init"], into(at, "init"));
1528
+ const step = this.#names(f["step"], into(at, "step"));
1529
+ const until = f["until"] === void 0 ? void 0 : this.term(f["until"], into(at, "until"));
1530
+ return iterate(f["limit"], init, step, this.term(f["result"], into(at, "result")), until);
1531
+ }
1532
+ default: return bad(where, `the type "${typeName(u.type)}" is not a term of Vex`);
1533
+ }
1534
+ }
1535
+ /** This method gives the keys of the type of an envelope. An envelope of a term has no header (DOC.TERM). */
1536
+ #type(u, where) {
1537
+ if (u.name !== void 0 || u.own !== void 0) return bad(where, "a term of Vex has no name and no own entries");
1538
+ const keys = typePath(u.type);
1539
+ if (keys === void 0) return bad(into(where, "type"), "the type has a computed step");
1540
+ return keys;
1541
+ }
1542
+ /** This method gives the name of an op or an extension: its keys, joined with dots (DOC.OPS, DOC.EXT). */
1543
+ #name(keys, where) {
1544
+ return keys.every((k) => typeof k === "string") ? keys.join(".") : bad(where, "a key of the name is not a text");
1545
+ }
1546
+ /** This method gives the value of a literal from its JSON form (DOC.LITERAL). */
1547
+ #value(u, where) {
1548
+ const r = decodeValue(u, this.#domains);
1549
+ return r.ok ? r.value : bad(where, r.error.message);
1550
+ }
1551
+ /** This method reads a list. */
1552
+ #list(u, where) {
1553
+ return Array.isArray(u) ? u : bad(where, "the value is not a list");
1554
+ }
1555
+ /** This method reads a record of names and the term of each name. */
1556
+ #names(u, where) {
1557
+ if (!isRecord(u)) return bad(where, "the value is not a record");
1558
+ return Object.fromEntries(Object.entries(u).map(([name, x]) => [name, this.term(x, into(where, name))]));
1559
+ }
1560
+ /** This method reads a reference: the fields of `self` after its moves, or a name of `names` (DOC.REF). */
1561
+ #ref(u, where) {
1562
+ const [root, ...steps] = this.#list(u, where);
1563
+ if (root === "names") return steps.length === 1 && typeof steps[0] === "string" ? v(steps[0]) : bad(where, "a reference to a name has one step: the name");
1564
+ if (root !== "self") return bad(into(where, 0), `Vex reads only from the roots "self" and "names", and this reference starts at ${JSON.stringify(root) ?? "nothing"}`);
1565
+ const moves = [];
1566
+ const names = [];
1567
+ steps.forEach((step, i) => {
1568
+ const at = into(where, i + 1);
1569
+ if (typeof step === "string") names.push(step);
1570
+ else if (!isDocument(step)) bad(at, "a step is not a text and not a move");
1571
+ else if (names.length > 0) bad(at, "a move comes after a field. Vex reads the fields at the end of the path");
1572
+ else moves.push(this.#move(step, at));
1573
+ });
1574
+ return ref(names, moves);
1575
+ }
1576
+ /** This method reads the function of a call: a reference to a name (DOC.CALL). */
1577
+ #function(u, where) {
1578
+ const e = isDocument(u) ? this.#envelope(u, where) : void 0;
1579
+ return e?.tag === "var" ? e.name : bad(where, "the function of a call is a reference to a name: { \"type\": \"ref\", \"value\": [\"names\", name] }");
1580
+ }
1581
+ /** This method reads the field `at` of `each` and `fold`: a reference from `self` with moves only (DOC.ADDRESS). */
1582
+ #address(u, where) {
1583
+ if (u === void 0) return void 0;
1584
+ const e = isDocument(u) ? this.#envelope(u, where) : void 0;
1585
+ return e?.tag === "ref" && e.path.length === 0 ? e.at ?? [] : bad(where, "the address is a reference from \"self\" with moves only: { \"type\": \"ref\", \"value\": [\"self\", ...moves] }");
1586
+ }
1587
+ /** This method reads a move (DOC.MOVE). A fixed key is a text, a fixed position is a number, and an envelope is a term. */
1588
+ #move(u, where) {
1589
+ const [head, kind, ...rest] = this.#type(u, where);
1590
+ const at = into(where, "value");
1591
+ if (head !== "moves" || typeof kind !== "string" || rest.length > 0) return bad(where, `Vex has no step of the type "${typeName(u.type)}"`);
1592
+ const value = u.value;
1593
+ switch (kind) {
1594
+ case "key": return typeof value === "string" ? key(value) : isDocument(value) ? key(this.#envelope(value, at)) : bad(at, "the key is not a text or a term in an envelope");
1595
+ case "index": return typeof value === "number" ? index(value) : isDocument(value) ? index(this.#envelope(value, at)) : bad(at, "the position is not a number or a term in an envelope");
1596
+ case "offset": return Array.isArray(value) && value.every((d) => typeof d === "number") ? offset(...value) : bad(at, "the offset is not a list of numbers");
1597
+ default: {
1598
+ const plain = PLAIN_MOVES.get(kind);
1599
+ if (plain === void 0) return bad(where, `Vex has no move "${kind}"`);
1600
+ return value === null ? plain : bad(at, `the value of the move "${kind}" is not null`);
1601
+ }
1602
+ }
1603
+ }
1604
+ /** This method reads an axis (DOC.AXIS). The check of the expression tells a bad parameter. */
1605
+ #axis(u, where) {
1606
+ if (!isDocument(u)) return bad(where, "the axis is not an envelope");
1607
+ const [head, name, ...rest] = this.#type(u, where);
1608
+ if (head !== "axes" || typeof name !== "string" || rest.length > 0) return bad(where, `the type "${typeName(u.type)}" is not an axis`);
1609
+ const at = into(where, "value");
1610
+ switch (name) {
1611
+ case "neighbors": return {
1612
+ t: name,
1613
+ n: fields(u.value, at, ["n"])["n"]
1614
+ };
1615
+ case "window": {
1616
+ const f = fields(u.value, at, ["from", "to"]);
1617
+ return {
1618
+ t: name,
1619
+ from: f["from"],
1620
+ to: f["to"]
1621
+ };
1622
+ }
1623
+ case "table": return {
1624
+ t: name,
1625
+ name: fields(u.value, at, ["name"])["name"]
1626
+ };
1627
+ case "list": return {
1628
+ t: name,
1629
+ list: this.term(fields(u.value, at, ["list"])["list"], into(at, "list"))
1630
+ };
1631
+ case "reverse": return {
1632
+ t: name,
1633
+ axis: this.#axis(fields(u.value, at, ["axis"])["axis"], into(at, "axis"))
1634
+ };
1635
+ case "where": {
1636
+ const f = fields(u.value, at, ["axis", "test"]);
1637
+ return {
1638
+ t: name,
1639
+ axis: this.#axis(f["axis"], into(at, "axis")),
1640
+ test: this.term(f["test"], into(at, "test"))
1641
+ };
1642
+ }
1643
+ default:
1644
+ if (!PLAIN_AXES.has(name)) return bad(where, `Vex has no axis "${name}"`);
1645
+ fields(u.value, at, []);
1646
+ return { t: name };
1647
+ }
1648
+ }
1649
+ };
1650
+ /**
1651
+ * This function reads the value of a construct: a record with each necessary field, and no field outside the necessary
1652
+ * and the optional fields. Thus a wrong name of a field gives an error, and the round trip keeps each field.
1653
+ */
1654
+ function fields(u, where, required, optional = []) {
1655
+ if (!isRecord(u)) return bad(where, "the value is not a record");
1656
+ for (const name of required) if (!Object.hasOwn(u, name)) bad(where, `the value has no field "${name}"`);
1657
+ for (const name of Object.keys(u)) if (!required.includes(name) && !optional.includes(name)) bad(into(where, name), `the field "${name}" is not a field of this term`);
1658
+ return u;
1659
+ }
1660
+ //#endregion
1060
1661
  //#region src/evaluate.ts
1061
1662
  /** The names of the special forms. Their arguments are not evaluated before the call. */
1062
1663
  const SPECIAL_FORMS = /* @__PURE__ */ new Set([
@@ -1066,10 +1667,6 @@ const SPECIAL_FORMS = /* @__PURE__ */ new Set([
1066
1667
  "ifError"
1067
1668
  ]);
1068
1669
  const isSpecialForm = (op) => SPECIAL_FORMS.has(op);
1069
- /**
1070
- * This function compiles an expression. The result gives the same results and the same traces as `evaluate`,
1071
- * because `evaluate` uses it too.
1072
- */
1073
1670
  /** A bound function (FN.BIND): its parameters, its compiled body and the names of the place of its binding. */
1074
1671
  var Closure = class {
1075
1672
  params;
@@ -1095,11 +1692,18 @@ function nestingOf(e) {
1095
1692
  }
1096
1693
  return deepest;
1097
1694
  }
1098
- function compile(expr, opts = {}) {
1099
- const shape = shapeError(expr);
1695
+ /**
1696
+ * This function compiles an expression or a document (DOC.ENTRY). The result gives the same results and the same traces
1697
+ * as `evaluate`, because `evaluate` uses it too.
1698
+ */
1699
+ function compile(source, opts = {}) {
1700
+ const read = isDocument(source) ? fromDocument(source, opts.domains) : ok(source);
1701
+ const expr = read.ok ? read.value : source;
1702
+ const shape = read.ok ? shapeError(expr) : read.error.message;
1100
1703
  const nesting = shape === void 0 ? nestingOf(expr) : 0;
1101
1704
  const bad = shape ?? (nesting > 500 ? `the expression is nested ${nesting} levels deep, and the limit is 500` : void 0);
1102
- const root = bad === void 0 ? new Compiler(opts).node(expr, []) : (f) => fail(vexError("bad-expression", bad, {
1705
+ const kind = read.ok ? "bad-expression" : read.error.kind;
1706
+ const root = bad === void 0 ? new Compiler(opts).node(expr, []) : (f) => fail(vexError(kind, bad, {
1103
1707
  path: [],
1104
1708
  origin: f.pos.origin,
1105
1709
  focus: f.pos.focus
@@ -1165,11 +1769,11 @@ function compiled(expr, opts) {
1165
1769
  });
1166
1770
  return program;
1167
1771
  }
1168
- /** This function evaluates an expression at the origin of a space. It does not throw. */
1772
+ /** This function evaluates an expression or a document at the origin of a space. It does not throw. */
1169
1773
  function evaluate(expr, opts) {
1170
1774
  return compiled(expr, opts).run(opts);
1171
1775
  }
1172
- /** This function evaluates an expression and records a trace of each node. */
1776
+ /** This function evaluates an expression or a document and records a trace of each node. */
1173
1777
  function explain(expr, opts) {
1174
1778
  return compiled(expr, opts).explain(opts);
1175
1779
  }
@@ -2061,92 +2665,6 @@ function deps(e) {
2061
2665
  }
2062
2666
  //#endregion
2063
2667
  //#region src/json.ts
2064
- const isRecord = (u) => typeof u === "object" && u !== null && !Array.isArray(u);
2065
- const isPlainRecord = (u) => {
2066
- if (!isRecord(u)) return false;
2067
- const proto = Object.getPrototypeOf(u);
2068
- return proto === Object.prototype || proto === null;
2069
- };
2070
- /** This function gives the JSON form of a value, or the reason why the value has no JSON form. */
2071
- function encodeValue(u, domains) {
2072
- if (u === null || typeof u === "string" || typeof u === "boolean") return ok(u);
2073
- if (typeof u === "number") {
2074
- if (Object.is(u, -0)) return ok({
2075
- $vex: "number",
2076
- value: "-0"
2077
- });
2078
- return Number.isFinite(u) ? ok(u) : ok({
2079
- $vex: "number",
2080
- value: Number.isNaN(u) ? "NaN" : u > 0 ? "Infinity" : "-Infinity"
2081
- });
2082
- }
2083
- if (Array.isArray(u)) {
2084
- const out = [];
2085
- for (const x of u) {
2086
- const r = encodeValue(x, domains);
2087
- if (!r.ok) return r;
2088
- out.push(r.value);
2089
- }
2090
- return ok(out);
2091
- }
2092
- if (isPlainRecord(u)) {
2093
- const out = {};
2094
- for (const [k, x] of Object.entries(u)) {
2095
- const r = encodeValue(x, domains);
2096
- if (!r.ok) return r;
2097
- out[k] = r.value;
2098
- }
2099
- return ok(Object.hasOwn(u, "$vex") ? {
2100
- $vex: "escape",
2101
- value: out
2102
- } : out);
2103
- }
2104
- const d = domains.find((dom) => dom.encode !== void 0 && dom.is(u));
2105
- if (d?.encode !== void 0) return ok({
2106
- $vex: "domain",
2107
- domain: d.name,
2108
- value: d.encode(u)
2109
- });
2110
- return fail(vexError("bad-expression", "a literal value is not JSON data and no domain encodes it"));
2111
- }
2112
- const NUMBERS = {
2113
- "-0": -0,
2114
- NaN: NaN,
2115
- Infinity: Number.POSITIVE_INFINITY,
2116
- "-Infinity": Number.NEGATIVE_INFINITY
2117
- };
2118
- /** This function reads a value from its JSON form. */
2119
- function decodeValue(u, domains) {
2120
- if (Array.isArray(u)) {
2121
- const out = [];
2122
- for (const x of u) {
2123
- const r = decodeValue(x, domains);
2124
- if (!r.ok) return r;
2125
- out.push(r.value);
2126
- }
2127
- return ok(out);
2128
- }
2129
- if (!isRecord(u)) return ok(u);
2130
- const fields = (record) => {
2131
- const out = {};
2132
- for (const [k, x] of Object.entries(record)) {
2133
- const r = decodeValue(x, domains);
2134
- if (!r.ok) return r;
2135
- out[k] = r.value;
2136
- }
2137
- return ok(out);
2138
- };
2139
- const kind = u["$vex"];
2140
- if (kind === "escape" && isRecord(u["value"])) return fields(u["value"]);
2141
- if (kind === "number" && typeof u["value"] === "string" && Object.hasOwn(NUMBERS, u["value"])) return ok(NUMBERS[u["value"]]);
2142
- if (kind === "domain" && typeof u["domain"] === "string") {
2143
- const name = u["domain"];
2144
- const d = domains.find((dom) => dom.name === name);
2145
- if (d?.decode === void 0) return fail(vexError("bad-expression", `no domain "${name}" decodes a literal`));
2146
- return ok(d.decode(u["value"]));
2147
- }
2148
- return fields(u);
2149
- }
2150
2668
  /** This function applies `f` to each literal value of a JSON tree of an expression. */
2151
2669
  function mapValues(u, f) {
2152
2670
  if (!isRecord(u)) return ok(u);
@@ -2264,7 +2782,10 @@ function serialize(e, domains = []) {
2264
2782
  return fail(vexError("threw", "the expression has no JSON form", { thrown }));
2265
2783
  }
2266
2784
  }
2267
- /** This function reads an expression from JSON text. It checks the whole tree. */
2785
+ /**
2786
+ * This function reads an expression from JSON text. It checks the whole tree. The text can also be a document: then
2787
+ * `fromDocument` reads it (DOC.ENTRY).
2788
+ */
2268
2789
  function parse(text, domains = []) {
2269
2790
  let raw;
2270
2791
  try {
@@ -2272,6 +2793,10 @@ function parse(text, domains = []) {
2272
2793
  } catch (thrown) {
2273
2794
  return fail(vexError("bad-expression", "the text is not JSON", { thrown }));
2274
2795
  }
2796
+ if (isDocument(raw)) {
2797
+ const read = fromDocument(raw, domains);
2798
+ return !read.ok || isExpr(read.value) ? read : fail(vexError("bad-expression", "the JSON is not a valid Vex expression"));
2799
+ }
2275
2800
  try {
2276
2801
  const tree = mapValues(raw, (v) => decodeValue(v, domains));
2277
2802
  if (!tree.ok) return fail(tree.error);
@@ -3470,6 +3995,6 @@ function vex(...domains) {
3470
3995
  };
3471
3996
  }
3472
3997
  //#endregion
3473
- export { CELL_KIND, LIST_OPS, MAX_ITERATIONS, MAX_NESTING, SPECIAL_FORMS, SheetRun, addrExprs, app, applyMove, axes, axisExprs, axisTargets, call, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, fixAddr, fn, fold, formatError, formatTrace, getOr, index, isAxis, isDepthError, isExpr, isFieldName, isFixedAddr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, iterate, key, labelOf, let_, liftsAt, listOf, lit, mapResult, matchesKind, monoids, moveExpr, nestingOf, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, safeIs, serialize, shapeError, sizeOf, some, space, toOptional, toPath, traversal, v, vex, vexError, vexList };
3998
+ export { CELL_KIND, LIST_OPS, MAX_ITERATIONS, MAX_NESTING, SPECIAL_FORMS, SheetRun, addrExprs, app, applyMove, axes, axisExprs, axisTargets, call, cell, chainResult, children, codeOf, compile, defineDomain, deps, describeType, domainOf, each, evaluate, explain, ext, fail, findMethod, fixAddr, fn, fold, formatError, formatTrace, fromDocument, getOr, index, isAxis, isDepthError, isDocument, isExpr, isFieldName, isFixedAddr, isListOp, isMove, isNone, isOpName, isSome, isStackOverflow, isVexList, iterate, key, labelOf, let_, liftsAt, listOf, lit, mapResult, matchesKind, monoids, moveExpr, nestingOf, none, offset, ok, origin, other, parent, parse, previewValue, rec, ref, resolveAddr, resolveOp, safeIs, serialize, shapeError, sizeOf, some, space, toDocument, toOptional, toPath, traversal, v, vex, vexError, vexList };
3474
3999
 
3475
4000
  //# sourceMappingURL=index.js.map