@atscript/core 0.2.3 → 0.2.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +399 -59
- package/dist/index.d.ts +86 -7
- package/dist/index.mjs +393 -59
- package/package.json +1 -1
package/dist/index.mjs
CHANGED
|
@@ -633,6 +633,17 @@ const text$1 = (val) => new Token({
|
|
|
633
633
|
return specifier[0] !== "." && specifier[0] !== "/";
|
|
634
634
|
}
|
|
635
635
|
/**
|
|
636
|
+
* The import path of an `.as` import as atscript resolves it: without a trailing `.as` extension.
|
|
637
|
+
* `.as` imports may name a file with or without its extension (`'./user'`, `'./user.as'`,
|
|
638
|
+
* `'my-lib/models.as'`); both spellings resolve to the same module. A bare package name
|
|
639
|
+
* (`'my-lib'`, no subpath) is kept as written.
|
|
640
|
+
*/ function withoutAsExtension(specifier) {
|
|
641
|
+
if (!specifier.endsWith(".as")) return specifier;
|
|
642
|
+
const slash = specifier.lastIndexOf("/");
|
|
643
|
+
if (specifier.slice(slash + 1) === ".as" || isBareSpecifier(specifier) && parseBareSpecifier(specifier).subpath === ".") return specifier;
|
|
644
|
+
return specifier.slice(0, -3);
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
636
647
|
* Returns true if the document ID is a bare specifier placeholder.
|
|
637
648
|
*/ function isBareId(id) {
|
|
638
649
|
return id.startsWith("bare:");
|
|
@@ -739,6 +750,7 @@ const resolveCache = /* @__PURE__ */ new Map();
|
|
|
739
750
|
* @param fromDir Absolute directory of the importing file
|
|
740
751
|
* @returns Resolved absolute file path, or undefined if not found
|
|
741
752
|
*/ async function resolveBareSpecifier(specifier, fromDir) {
|
|
753
|
+
specifier = withoutAsExtension(specifier);
|
|
742
754
|
const cacheKey = `${fromDir}\0${specifier}`;
|
|
743
755
|
if (resolveCache.has(cacheKey)) return resolveCache.get(cacheKey);
|
|
744
756
|
const result = await _resolveBareSpecifier(specifier, fromDir);
|
|
@@ -784,16 +796,17 @@ async function _resolveBareSpecifier(specifier, fromDir) {
|
|
|
784
796
|
//#endregion
|
|
785
797
|
//#region packages/core/src/parser/utils.ts
|
|
786
798
|
/** {@link resolveAtscriptFromPath} by document id and import path (a pure function of both). */ const resolvedFromPaths = /* @__PURE__ */ new Map();
|
|
787
|
-
function resolveAtscriptFromPath(
|
|
799
|
+
function resolveAtscriptFromPath(written, id) {
|
|
788
800
|
let byFrom = resolvedFromPaths.get(id);
|
|
789
801
|
if (!byFrom) {
|
|
790
802
|
byFrom = /* @__PURE__ */ new Map();
|
|
791
803
|
resolvedFromPaths.set(id, byFrom);
|
|
792
804
|
}
|
|
793
|
-
let resolved = byFrom.get(
|
|
805
|
+
let resolved = byFrom.get(written);
|
|
794
806
|
if (resolved === void 0) {
|
|
807
|
+
const from = withoutAsExtension(written);
|
|
795
808
|
resolved = isBareSpecifier(from) ? `bare:${from}.as` : `file://${path.join(fileUriToPath(id).split("/").slice(0, -1).join("/"), from)}.as`;
|
|
796
|
-
byFrom.set(
|
|
809
|
+
byFrom.set(written, resolved);
|
|
797
810
|
}
|
|
798
811
|
return resolved;
|
|
799
812
|
}
|
|
@@ -1262,6 +1275,10 @@ function _define_property$9(obj, key, value) {
|
|
|
1262
1275
|
else obj[key] = value;
|
|
1263
1276
|
return obj;
|
|
1264
1277
|
}
|
|
1278
|
+
/**
|
|
1279
|
+
* The built-in annotation of `annotate` blocks that removes another annotation from the node
|
|
1280
|
+
* (`@annotate.reset 'expect.pattern'`): a directive, never written as metadata.
|
|
1281
|
+
*/ const ANNOTATE_RESET = "annotate.reset";
|
|
1265
1282
|
/** Whether an annotation argument type is written in backticks (`query`, `expr`, `order`). */ function isBacktickArgType(type) {
|
|
1266
1283
|
return type === "query" || type === "expr" || type === "order";
|
|
1267
1284
|
}
|
|
@@ -1280,7 +1297,7 @@ var AnnotationSpec = class {
|
|
|
1280
1297
|
return this.arguments.map((arg, index) => {
|
|
1281
1298
|
const placeholderIndex = index + 1;
|
|
1282
1299
|
const defaultValue = this.getDefaultValueForType(arg.name, arg.type);
|
|
1283
|
-
const quote = arg.type === "string" ? `'` : isBacktickArgType(arg.type) ? "`" : "";
|
|
1300
|
+
const quote = arg.type === "string" || arg.type === "value" ? `'` : isBacktickArgType(arg.type) ? "`" : "";
|
|
1284
1301
|
return `${quote}\${${placeholderIndex}:${defaultValue}}${quote}`;
|
|
1285
1302
|
}).join(", ");
|
|
1286
1303
|
}
|
|
@@ -1290,6 +1307,7 @@ var AnnotationSpec = class {
|
|
|
1290
1307
|
case "number": return tokenType === "number" ? void 0 : "number expected.";
|
|
1291
1308
|
case "boolean": return tokenType === "identifier" ? void 0 : "boolean expected.";
|
|
1292
1309
|
case "ref": return tokenType === "identifier" ? void 0 : "type reference expected.";
|
|
1310
|
+
case "value": return tokenType === "text" || tokenType === "number" || tokenType === "identifier" ? void 0 : "string, number or boolean expected.";
|
|
1293
1311
|
case "query":
|
|
1294
1312
|
case "expr":
|
|
1295
1313
|
case "order": return tokenType === "query" ? void 0 : BACKTICK_TYPE_MESSAGES[type];
|
|
@@ -1346,7 +1364,7 @@ var AnnotationSpec = class {
|
|
|
1346
1364
|
});
|
|
1347
1365
|
continue;
|
|
1348
1366
|
}
|
|
1349
|
-
const values = argSpec.type === "boolean" ? ["true", "false"] : argSpec.values;
|
|
1367
|
+
const values = argSpec.type === "boolean" || argSpec.type === "value" && tokenType === "identifier" ? ["true", "false"] : argSpec.values;
|
|
1350
1368
|
if (values && !values.includes(valueText)) messages.push({
|
|
1351
1369
|
severity: 1,
|
|
1352
1370
|
message: `${mainToken.text} at argument #${i + 1} ("${argSpec.name}") must be one of [${values.join(", ")}]`,
|
|
@@ -1395,10 +1413,33 @@ var AnnotationSpec = class {
|
|
|
1395
1413
|
messages.push(...this.validateTargetType(def, mainToken.range, defDoc) || []);
|
|
1396
1414
|
}
|
|
1397
1415
|
}
|
|
1416
|
+
messages.push(...this.validateValueArgs(mainToken, args, doc));
|
|
1398
1417
|
if (this.config.validate) messages.push(...this.config.validate(mainToken, args, doc) || []);
|
|
1399
1418
|
return messages.length > 0 ? messages : void 0;
|
|
1400
1419
|
}
|
|
1401
1420
|
/**
|
|
1421
|
+
* `value` arguments written as a number or a boolean must fit the annotated field's type: a
|
|
1422
|
+
* number literal a field that holds numbers, a boolean literal one that holds booleans (a
|
|
1423
|
+
* union: one of its members; `unknown`: any). A string is accepted for any field.
|
|
1424
|
+
*/ validateValueArgs(mainToken, args, doc) {
|
|
1425
|
+
const messages = [];
|
|
1426
|
+
const specArgs = this.arguments;
|
|
1427
|
+
let kinds = null;
|
|
1428
|
+
for (let i = 0; i < args.length && i < specArgs.length; i++) {
|
|
1429
|
+
const token = args[i];
|
|
1430
|
+
const kind = token.type === "number" ? "number" : token.type === "identifier" ? "boolean" : void 0;
|
|
1431
|
+
if (specArgs[i].type !== "value" || !kind) continue;
|
|
1432
|
+
if (kinds === null) kinds = annotatedValueKinds(mainToken, doc);
|
|
1433
|
+
if (!kinds) return messages;
|
|
1434
|
+
if (!literalFits(kind, kinds)) messages.push({
|
|
1435
|
+
severity: 1,
|
|
1436
|
+
message: `${mainToken.text} at argument #${i + 1} ("${specArgs[i].name}"): a ${kind} does not fit the field's type (${[...kinds].join(" | ") || "unknown"}).`,
|
|
1437
|
+
range: token.range
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
return messages;
|
|
1441
|
+
}
|
|
1442
|
+
/**
|
|
1402
1443
|
* Checks an already-resolved target node against this annotation's `defType`
|
|
1403
1444
|
* guard (e.g. `@expect.minLength` requires `string | array`). Returns a
|
|
1404
1445
|
* diagnostic when the type doesn't match, or `undefined` when it matches or no
|
|
@@ -1413,11 +1454,12 @@ var AnnotationSpec = class {
|
|
|
1413
1454
|
*/ validateTargetType(def, range, doc) {
|
|
1414
1455
|
const defType = this.config.defType;
|
|
1415
1456
|
if (!defType?.length) return;
|
|
1416
|
-
|
|
1457
|
+
const literals = this.config.defTypeLiterals;
|
|
1458
|
+
if (matchesDefType(def, defType, literals)) return;
|
|
1417
1459
|
let got;
|
|
1418
1460
|
if (isGroup(def) && describeNode(def) === "union") {
|
|
1419
1461
|
const members = doc ? nonNullishMembers(def, doc) : void 0;
|
|
1420
|
-
if (members?.length && members.every((m) => matchesDefType(m, defType))) return;
|
|
1462
|
+
if (members?.length && members.every((m) => matchesDefType(m, defType, literals))) return;
|
|
1421
1463
|
got = `union (${describeUnionMembers(def, doc)})`;
|
|
1422
1464
|
} else got = `"${describeNode(def)}"`;
|
|
1423
1465
|
return [{
|
|
@@ -1431,9 +1473,9 @@ var AnnotationSpec = class {
|
|
|
1431
1473
|
const a = this.arguments[index];
|
|
1432
1474
|
if (a) {
|
|
1433
1475
|
const values = a.values ? `\n\nValues:\n${a.values.join(", ")}` : "";
|
|
1434
|
-
return `### \`${a.name}${a.optional ? "?" : ""}: ${a
|
|
1476
|
+
return `### \`${a.name}${a.optional ? "?" : ""}: ${argTypeLabel(a)}\`\n\n${a.description}${values}`;
|
|
1435
1477
|
}
|
|
1436
|
-
} else return `### ${index} ${this.arguments.map((a) => `\`${a.name}${a.optional ? "?" : ""}: ${a
|
|
1478
|
+
} else return `### ${index} ${this.arguments.map((a) => `\`${a.name}${a.optional ? "?" : ""}: ${argTypeLabel(a)}\``).join(", ")}\n\n${this.config.description}`;
|
|
1437
1479
|
}
|
|
1438
1480
|
getDefaultValueForType(name, type) {
|
|
1439
1481
|
switch (type) {
|
|
@@ -1444,6 +1486,7 @@ var AnnotationSpec = class {
|
|
|
1444
1486
|
case "query": return "field = value";
|
|
1445
1487
|
case "expr": return "field + 1";
|
|
1446
1488
|
case "order": return "field asc";
|
|
1489
|
+
case "value": return name;
|
|
1447
1490
|
default: return "";
|
|
1448
1491
|
}
|
|
1449
1492
|
}
|
|
@@ -1454,6 +1497,9 @@ var AnnotationSpec = class {
|
|
|
1454
1497
|
this.__is_annotation_spec = true;
|
|
1455
1498
|
}
|
|
1456
1499
|
};
|
|
1500
|
+
/** An argument's type as the docs show it (`value`: the literals it takes). */ function argTypeLabel(a) {
|
|
1501
|
+
return a.type === "value" ? "string | number | boolean" : a.type;
|
|
1502
|
+
}
|
|
1457
1503
|
function isAnnotationSpec(a) {
|
|
1458
1504
|
return Boolean(a) && a.__is_annotation_spec;
|
|
1459
1505
|
}
|
|
@@ -1477,6 +1523,30 @@ function isAnnotationSpec(a) {
|
|
|
1477
1523
|
};
|
|
1478
1524
|
walk(tree);
|
|
1479
1525
|
}
|
|
1526
|
+
/**
|
|
1527
|
+
* Where annotation `spec` holds user-facing text (arguments flagged `userText`): `true` — its
|
|
1528
|
+
* value itself (a spec with one argument, not a list: the value is the string; for a `multiple`
|
|
1529
|
+
* annotation, each value); `'expression'` — likewise, but the value is function source whose string
|
|
1530
|
+
* literals are the texts; a list — those fields of its value object (a spec with an argument
|
|
1531
|
+
* list), an expression field's name ending in `()`. `undefined`: no user-facing text.
|
|
1532
|
+
*/ function userTextFields(spec) {
|
|
1533
|
+
const arg = spec.config.argument;
|
|
1534
|
+
if (!arg) return;
|
|
1535
|
+
if (!Array.isArray(arg)) return arg.userText || void 0;
|
|
1536
|
+
const fields = arg.filter((a) => a.userText).map((a) => a.userText === "expression" ? `${a.name}()` : a.name);
|
|
1537
|
+
return fields.length > 0 ? fields : void 0;
|
|
1538
|
+
}
|
|
1539
|
+
/**
|
|
1540
|
+
* Every annotation of `tree` (core and plugins) holding user-facing text, by full name (see
|
|
1541
|
+
* {@link userTextFields}): what i18n tooling extracts and a translator translates.
|
|
1542
|
+
*/ function userTextAnnotations(tree) {
|
|
1543
|
+
const out = /* @__PURE__ */ new Map();
|
|
1544
|
+
forEachAnnotationSpec(tree, (name, spec) => {
|
|
1545
|
+
const fields = userTextFields(spec);
|
|
1546
|
+
if (fields) out.set(name, fields);
|
|
1547
|
+
});
|
|
1548
|
+
return out;
|
|
1549
|
+
}
|
|
1480
1550
|
function resolveAnnotation(name, annotationsTree) {
|
|
1481
1551
|
const parts = name.split(".");
|
|
1482
1552
|
let current = annotationsTree;
|
|
@@ -1491,15 +1561,28 @@ function resolveAnnotation(name, annotationsTree) {
|
|
|
1491
1561
|
/** `null` / `undefined` / `void` primitive. */ function isNullishPrimitive(node) {
|
|
1492
1562
|
return isPrimitive(node) && (node.type === "null" || node.type === "void");
|
|
1493
1563
|
}
|
|
1494
|
-
/**
|
|
1495
|
-
|
|
1564
|
+
/**
|
|
1565
|
+
* Whether a resolved node satisfies a `defType` guard (a union as a whole, not its members);
|
|
1566
|
+
* `literals`: a literal of an accepted type does too (see `defTypeLiterals`).
|
|
1567
|
+
*/ function matchesDefType(def, defType, literals) {
|
|
1568
|
+
if (defType.includes(describeNode(def))) return true;
|
|
1569
|
+
return !!literals && isConst(def) && defType.includes(literalType(def));
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* The `defType` vocabulary name of a literal's value (`'a'` → `string`, `1` → `number`; atscript
|
|
1573
|
+
* literals are strings and numbers).
|
|
1574
|
+
*/ function literalType(def) {
|
|
1575
|
+
return def.token("identifier")?.type === "number" ? "number" : "string";
|
|
1496
1576
|
}
|
|
1497
1577
|
/** The `defType` vocabulary name of a resolved node (`string`, `object`, `union`, `array`, …). */ function describeNode(def) {
|
|
1498
|
-
if (isPrimitive(def)) return def.type || "unknown";
|
|
1578
|
+
if (isPrimitive(def)) return def.type === "any" ? "unknown" : def.type || "unknown";
|
|
1499
1579
|
if (isInterface(def) || isStructure(def)) return "object";
|
|
1500
1580
|
if (isGroup(def) && def.entity !== "tuple") return def.op === "&" ? "intersection" : "union";
|
|
1501
1581
|
return def?.entity || "unknown";
|
|
1502
1582
|
}
|
|
1583
|
+
/** A `|` group (not a tuple, an inline object `{ … }` or a `&` group). */ function isUnionGroup(node) {
|
|
1584
|
+
return node?.entity === "group" && node.op !== "&";
|
|
1585
|
+
}
|
|
1503
1586
|
/** Walks a `|` union (flattening nested unions and union aliases), resolving member refs. */ function walkUnionMembers(def, doc, cb, seen = /* @__PURE__ */ new Set()) {
|
|
1504
1587
|
if (seen.has(def)) return;
|
|
1505
1588
|
seen.add(def);
|
|
@@ -1511,7 +1594,7 @@ function resolveAnnotation(name, annotationsTree) {
|
|
|
1511
1594
|
member = unwound?.def;
|
|
1512
1595
|
memberDoc = unwound?.doc || doc;
|
|
1513
1596
|
}
|
|
1514
|
-
if (
|
|
1597
|
+
if (isUnionGroup(member)) walkUnionMembers(member, memberDoc, cb, seen);
|
|
1515
1598
|
else cb(member);
|
|
1516
1599
|
}
|
|
1517
1600
|
}
|
|
@@ -1538,7 +1621,7 @@ function describeUnionMembers(def, doc) {
|
|
|
1538
1621
|
* const ok = members ? members.length > 0 && members.every(isWanted) : isWanted(def)
|
|
1539
1622
|
* ```
|
|
1540
1623
|
*/ function nonNullishMembers(def, doc) {
|
|
1541
|
-
if (!
|
|
1624
|
+
if (!isUnionGroup(def)) return;
|
|
1542
1625
|
const members = [];
|
|
1543
1626
|
walkUnionMembers(def, doc, (m) => {
|
|
1544
1627
|
if (m && !isNullishPrimitive(m)) members.push(m);
|
|
@@ -1546,6 +1629,73 @@ function describeUnionMembers(def, doc) {
|
|
|
1546
1629
|
return members;
|
|
1547
1630
|
}
|
|
1548
1631
|
/**
|
|
1632
|
+
* The resolved type of the field (or type) an annotation is written on: an inline prop's, the
|
|
1633
|
+
* prop an `annotate` block entry names, an `annotate` block's target. `undefined` when it does
|
|
1634
|
+
* not resolve (reported elsewhere).
|
|
1635
|
+
*/ function annotatedFieldType(mainToken, doc) {
|
|
1636
|
+
const parent = mainToken.parentNode;
|
|
1637
|
+
if (!parent) return;
|
|
1638
|
+
const at = parent.entity === "annotate" ? doc.unwindType(parent.targetName) : doc.annotatedDefinition(parent);
|
|
1639
|
+
if (!at?.def) return;
|
|
1640
|
+
if (isRef(at.def)) {
|
|
1641
|
+
const unwound = at.doc.unwindRef(at.def);
|
|
1642
|
+
return unwound?.def ? {
|
|
1643
|
+
def: unwound.def,
|
|
1644
|
+
doc: unwound.doc
|
|
1645
|
+
} : void 0;
|
|
1646
|
+
}
|
|
1647
|
+
return {
|
|
1648
|
+
def: at.def,
|
|
1649
|
+
doc: at.doc
|
|
1650
|
+
};
|
|
1651
|
+
}
|
|
1652
|
+
/**
|
|
1653
|
+
* The scalar kinds a resolved type holds (`string`, `number`, `boolean`, `decimal`; `unknown`:
|
|
1654
|
+
* any value), through references and aliases: a union's members' (not `null` / `undefined`), a
|
|
1655
|
+
* scalar merge's kinds every member has (`unknown` takes no part: `unknown & number` is a
|
|
1656
|
+
* number), a literal's.
|
|
1657
|
+
*/ function valueKinds(def, doc, seen = /* @__PURE__ */ new Set()) {
|
|
1658
|
+
let node = def;
|
|
1659
|
+
let at = doc;
|
|
1660
|
+
while (node && isGroup(node) && !node.op && node.unwrap().length === 1) node = node.unwrap()[0];
|
|
1661
|
+
if (isRef(node)) {
|
|
1662
|
+
const unwound = at.unwindRef(node);
|
|
1663
|
+
node = unwound?.def;
|
|
1664
|
+
at = unwound?.doc ?? at;
|
|
1665
|
+
}
|
|
1666
|
+
if (!node || seen.has(node)) return /* @__PURE__ */ new Set();
|
|
1667
|
+
seen.add(node);
|
|
1668
|
+
if (node.entity === "const") return new Set([literalType(node)]);
|
|
1669
|
+
if (isGroup(node) && node.entity !== "tuple" && node.op === "&") {
|
|
1670
|
+
let out;
|
|
1671
|
+
for (const m of node.unwrap()) {
|
|
1672
|
+
const ks = valueKinds(m, at, seen);
|
|
1673
|
+
if (ks.size === 1 && ks.has("unknown")) continue;
|
|
1674
|
+
out = out ? new Set([...out].filter((k) => ks.has(k))) : ks;
|
|
1675
|
+
}
|
|
1676
|
+
return out ?? new Set(["unknown"]);
|
|
1677
|
+
}
|
|
1678
|
+
const members = nonNullishMembers(node, at);
|
|
1679
|
+
if (members) {
|
|
1680
|
+
const out = /* @__PURE__ */ new Set();
|
|
1681
|
+
for (const m of members) for (const k of valueKinds(m, at, seen)) out.add(k);
|
|
1682
|
+
return out;
|
|
1683
|
+
}
|
|
1684
|
+
return new Set([describeNode(node)]);
|
|
1685
|
+
}
|
|
1686
|
+
/**
|
|
1687
|
+
* The scalar kinds the field (or type) annotation `mainToken` is written on holds (see
|
|
1688
|
+
* `valueKinds`): `string`, `number`, `boolean`, `decimal`, `unknown` (any value), or another
|
|
1689
|
+
* kind name (`object`, `array`, …). `undefined` when the field does not resolve. Code generators
|
|
1690
|
+
* use it for `value` arguments: a number literal on a `decimal` field is written as its string.
|
|
1691
|
+
*/ function annotatedValueKinds(mainToken, doc) {
|
|
1692
|
+
const target = annotatedFieldType(mainToken, doc);
|
|
1693
|
+
return target ? valueKinds(target.def, target.doc) : void 0;
|
|
1694
|
+
}
|
|
1695
|
+
/** Whether a literal of `kind` (`number`, `boolean`) fits a field of `kinds` (see `valueKinds`). */ function literalFits(kind, kinds) {
|
|
1696
|
+
return kinds.has("unknown") || kinds.has(kind) || kind === "number" && kinds.has("decimal");
|
|
1697
|
+
}
|
|
1698
|
+
/**
|
|
1549
1699
|
* The node type an `annotate` block's top-level annotations apply to: its target's (`interface`
|
|
1550
1700
|
* or `type`; through an `annotate … as` alias, the alias's target's). `undefined` while the
|
|
1551
1701
|
* target does not resolve (reported elsewhere).
|
|
@@ -4169,6 +4319,11 @@ var TSeverity = /* @__PURE__ */ function(TSeverity) {
|
|
|
4169
4319
|
const UNION_IN_RECURSIVE_MERGE = "union members are not supported in recursive merges; split with named types";
|
|
4170
4320
|
const MERGE_TOO_COMPLEX = "merge too complex: split it with named types";
|
|
4171
4321
|
/** Why scalars (or an object and a scalar) merge to `never`. */ const NOTHING_IN_COMMON = "values with nothing in common";
|
|
4322
|
+
/**
|
|
4323
|
+
* Why a merge of `unknown` (any value) with an object, an array or `null` is refused: TypeScript
|
|
4324
|
+
* reads `unknown & X` as `X`, a merge of values would be `never` (a compile error, not a
|
|
4325
|
+
* validator rejecting what the `.d.ts` accepts).
|
|
4326
|
+
*/ const OPAQUE_MERGE = "\"unknown\" cannot be merged with an object, an array or null";
|
|
4172
4327
|
/** A type written as an operand of its own merge (`type X = A & X`). */ const SELF_OPERAND = "a type cannot be an operand of its own merge; recurse through a field instead";
|
|
4173
4328
|
/** A db entity whose flattening reaches a web of mutually recursive merges. */ const FLATTEN_WEB = "flattening this type reaches mutually recursive merges; split it with named types";
|
|
4174
4329
|
/**
|
|
@@ -4176,6 +4331,8 @@ const MERGE_TOO_COMPLEX = "merge too complex: split it with named types";
|
|
|
4176
4331
|
* itself splits (MODEL §15 SELF-SPLIT): where it lands depends on the positions it decides.
|
|
4177
4332
|
*/ const SELF_SPLIT = "A block's path can't cross the type path it splits.";
|
|
4178
4333
|
const isBranch = (s) => s.startsWith("|");
|
|
4334
|
+
/** A shape of the `unknown` primitive (any value). */ const isAnyShape = (s) => s.k === "scalar" && s.any === true;
|
|
4335
|
+
/** Merge refusals reported as errors, never dropped as a `never` branch. */ const refused = (reason) => reason === MERGE_TOO_COMPLEX || reason === OPAQUE_MERGE;
|
|
4179
4336
|
/** A step that is a prop's name (not a union branch, an in-place merge operand or an element). */ const isNameStep = (s) => !s.startsWith("|") && !s.startsWith("&") && s !== "[]";
|
|
4180
4337
|
/** A written `null`. */ const isNull = (x) => x.k === "scalar" && isPrimitive(x.node) && x.node.key === "null";
|
|
4181
4338
|
/** A shape that is, or has a branch that is, an array. */ const holdsArray = (s) => s?.k === "arr" || s?.k === "uni" && s.items.some(holdsArray);
|
|
@@ -6380,7 +6537,12 @@ function fieldLoc(s) {
|
|
|
6380
6537
|
}
|
|
6381
6538
|
shape0(t) {
|
|
6382
6539
|
switch (t.k) {
|
|
6383
|
-
case "scalar":
|
|
6540
|
+
case "scalar":
|
|
6541
|
+
if (!isPrimitive(t.node)) return { k: "scalar" };
|
|
6542
|
+
return t.node.key === "null" ? { k: "mixed" } : t.node.type === "any" ? {
|
|
6543
|
+
k: "scalar",
|
|
6544
|
+
any: true
|
|
6545
|
+
} : { k: "scalar" };
|
|
6384
6546
|
case "tup": {
|
|
6385
6547
|
const items = t.items.map((i) => this.shape(i));
|
|
6386
6548
|
if (!items.every((s) => s.k === "scalar" || s.k === "never")) return { k: "mixed" };
|
|
@@ -6392,6 +6554,10 @@ function fieldLoc(s) {
|
|
|
6392
6554
|
case "uni": {
|
|
6393
6555
|
if (t.struct) return this.shape(structExpr(t));
|
|
6394
6556
|
const ss = t.items.map((i) => this.shape(i));
|
|
6557
|
+
if (ss.some(isAnyShape)) return {
|
|
6558
|
+
k: "scalar",
|
|
6559
|
+
any: true
|
|
6560
|
+
};
|
|
6395
6561
|
if (ss.every((s) => s.k === "scalar" || s.k === "never")) return ss.every((s) => s.k === "never") ? {
|
|
6396
6562
|
k: "never",
|
|
6397
6563
|
reason: "union"
|
|
@@ -6459,13 +6625,17 @@ function fieldLoc(s) {
|
|
|
6459
6625
|
* algebra: disjoint scalars are `never`), a single union operand of objects distributes.
|
|
6460
6626
|
*/ combine(ss, ends) {
|
|
6461
6627
|
if (ss.length === 1) return ss[0];
|
|
6628
|
+
if (ss.some(isAnyShape) && !ss.every((s) => s.k === "scalar" || s.k === "never")) return {
|
|
6629
|
+
k: "never",
|
|
6630
|
+
reason: OPAQUE_MERGE
|
|
6631
|
+
};
|
|
6462
6632
|
const tuple = ends.length === ss.length ? this.tupleShape(ends) : void 0;
|
|
6463
6633
|
if (tuple) return tuple;
|
|
6464
6634
|
if (ss.some((s) => s.k === "mixed")) {
|
|
6465
6635
|
if (ends.length === ss.length && ends.some(isNull) && ends.every((e) => isNull(e) || this.nullable(e))) return { k: "scalar" };
|
|
6466
6636
|
const leaves = ends.length === ss.length ? this.mixedLeaves(ss, ends) : void 0;
|
|
6467
6637
|
const product = leaves && this.productShape(leaves.ss, leaves.ends);
|
|
6468
|
-
if (product?.k === "never" && product.reason
|
|
6638
|
+
if (product?.k === "never" && refused(product.reason)) return product;
|
|
6469
6639
|
return product?.k === "never" ? {
|
|
6470
6640
|
k: "never",
|
|
6471
6641
|
reason: NOTHING_IN_COMMON
|
|
@@ -6536,6 +6706,7 @@ function fieldLoc(s) {
|
|
|
6536
6706
|
}
|
|
6537
6707
|
const es = pick.map((p) => p.e);
|
|
6538
6708
|
const c = this.combine(pick.map((p) => p.s), es.every(Boolean) ? es : []);
|
|
6709
|
+
if (c.k === "never" && c.reason === OPAQUE_MERGE) return c;
|
|
6539
6710
|
if (c.k !== "never" && c.k !== "mixed") out.push(c);
|
|
6540
6711
|
}
|
|
6541
6712
|
if (out.length === 0) return {
|
|
@@ -8255,12 +8426,12 @@ var AtscriptDoc = class AtscriptDoc {
|
|
|
8255
8426
|
* them to its target's metadata: an `append` annotation adds its values after the existing
|
|
8256
8427
|
* ones, any other replaces them.
|
|
8257
8428
|
*/ overlayAnnotations(base, overlay) {
|
|
8258
|
-
const replaced = /* @__PURE__ */ new Set();
|
|
8429
|
+
const replaced = resetNames(overlay) ?? /* @__PURE__ */ new Set();
|
|
8259
8430
|
for (const a of overlay) {
|
|
8260
8431
|
const spec = this.resolveAnnotation(a.name);
|
|
8261
8432
|
if (!(spec?.config.multiple && spec.config.mergeStrategy === "append")) replaced.add(a.name);
|
|
8262
8433
|
}
|
|
8263
|
-
return [...(base ?? []).filter((a) => !replaced.has(a.name)), ...overlay];
|
|
8434
|
+
return [...(base ?? []).filter((a) => a.name === ANNOTATE_RESET || !replaced.has(a.name)), ...overlay];
|
|
8264
8435
|
}
|
|
8265
8436
|
/**
|
|
8266
8437
|
* What declaration `decl` (of this document) is defined as — an alias's, its target's (an
|
|
@@ -8629,7 +8800,7 @@ var AtscriptDoc = class AtscriptDoc {
|
|
|
8629
8800
|
*/ evalAnnotationsForNode(givenNode, own = givenNode.annotations, blocks = false) {
|
|
8630
8801
|
if (isAnnotate(givenNode) && !givenNode.isMutating) {
|
|
8631
8802
|
const target = this.getDeclarationOwnerNode(givenNode.targetName);
|
|
8632
|
-
return this.mergeNodesAnnotations(target?.node && target.node !== givenNode ? target.doc.evalAnnotationsForNode(target.node, annotationsOf(target.node, blocks), blocks) : void 0, own);
|
|
8803
|
+
return stripResets(this.mergeNodesAnnotations(target?.node && target.node !== givenNode ? target.doc.evalAnnotationsForNode(target.node, annotationsOf(target.node, blocks), blocks) : void 0, own, true));
|
|
8633
8804
|
}
|
|
8634
8805
|
return this.evalAnnotationsForDefinition(givenNode.getDefinition(), own, givenNode, blocks);
|
|
8635
8806
|
}
|
|
@@ -8658,24 +8829,24 @@ var AtscriptDoc = class AtscriptDoc {
|
|
|
8658
8829
|
for (const chainNode of chainNodes) {
|
|
8659
8830
|
if (chainNode === unwound?.def) continue;
|
|
8660
8831
|
const anns = chainNode === unwound?.node && fieldAnns ? fieldAnns : annotationsOf(chainNode, blocks);
|
|
8661
|
-
right = this.mergeNodesAnnotations(this.filterPassedWhenReferred(anns, viaProp), right);
|
|
8832
|
+
right = this.mergeNodesAnnotations(this.filterPassedWhenReferred(anns, viaProp), right, true);
|
|
8662
8833
|
}
|
|
8663
8834
|
def = unwound?.def || def;
|
|
8664
8835
|
}
|
|
8665
8836
|
if (def) {
|
|
8666
8837
|
const merged = this.mergeIntersection(def);
|
|
8667
8838
|
if (merged !== def && isRef(merged)) {
|
|
8668
|
-
right = this.mergeNodesAnnotations(merged.annotations, right);
|
|
8839
|
+
right = this.mergeNodesAnnotations(merged.annotations, right, true);
|
|
8669
8840
|
def = merged;
|
|
8670
8841
|
continue;
|
|
8671
8842
|
}
|
|
8672
8843
|
const written = unparenthesized(def);
|
|
8673
8844
|
const own = isIntersection(written) ? this.intersectionAnnotations(written, blocks).map((p) => p.an) : refDef ? annotationsOf(merged, blocks) : merged.annotations;
|
|
8674
|
-
right = this.mergeNodesAnnotations(refDef ? this.filterPassedWhenReferred(own, viaProp) : own, right);
|
|
8845
|
+
right = this.mergeNodesAnnotations(refDef ? this.filterPassedWhenReferred(own, viaProp) : own, right, true);
|
|
8675
8846
|
}
|
|
8676
8847
|
break;
|
|
8677
8848
|
}
|
|
8678
|
-
return right;
|
|
8849
|
+
return stripResets(right);
|
|
8679
8850
|
}
|
|
8680
8851
|
/**
|
|
8681
8852
|
* The annotations of the field chain reference `ref` names (its node `node`), with the blocks:
|
|
@@ -8885,7 +9056,7 @@ var AtscriptDoc = class AtscriptDoc {
|
|
|
8885
9056
|
const idToken = prop.token("identifier");
|
|
8886
9057
|
if (idToken) cloned.saveToken(idToken, "identifier");
|
|
8887
9058
|
if (newDef) cloned.define(newDef);
|
|
8888
|
-
cloned.annotations = group.own.length === 0 ? prop.annotations : this.mergeNodesAnnotations(prop.annotations, group.own);
|
|
9059
|
+
cloned.annotations = group.own.length === 0 ? prop.annotations : this.mergeNodesAnnotations(prop.annotations, group.own, true);
|
|
8889
9060
|
const optionalToken = prop.token("optional");
|
|
8890
9061
|
if (optionalToken) cloned.saveToken(optionalToken, "optional");
|
|
8891
9062
|
newProps.push(cloned);
|
|
@@ -9508,6 +9679,11 @@ var AtscriptDoc = class AtscriptDoc {
|
|
|
9508
9679
|
message: MERGE_TOO_COMPLEX,
|
|
9509
9680
|
range: token.range
|
|
9510
9681
|
});
|
|
9682
|
+
else if (token && reason === OPAQUE_MERGE) messages.push({
|
|
9683
|
+
severity: TSeverity.Error,
|
|
9684
|
+
message: `${OPAQUE_MERGE}${path.length > 0 ? ` at "${decl.name}.${path.join(".")}"` : ` in "${decl.name}"`}: write the other type alone`,
|
|
9685
|
+
range: token.range
|
|
9686
|
+
});
|
|
9511
9687
|
else if (token) messages.push({
|
|
9512
9688
|
severity: TSeverity.Warning,
|
|
9513
9689
|
message: `Intersection of ${reason} cannot be merged${path.length > 0 ? ` at "${decl.name}.${path.join(".")}"` : ` in "${decl.name}"`}; the type resolves to never`,
|
|
@@ -10083,14 +10259,29 @@ var AtscriptDoc = class AtscriptDoc {
|
|
|
10083
10259
|
add(group);
|
|
10084
10260
|
return out;
|
|
10085
10261
|
}
|
|
10086
|
-
|
|
10262
|
+
/**
|
|
10263
|
+
* Annotations `right` over `left`: right's win, `append` ones of both kept (left's after).
|
|
10264
|
+
*
|
|
10265
|
+
* `layered`: `right` is a node's and `left` what the node is layered over (the type it
|
|
10266
|
+
* references, an `as` copy's target) — right's `@annotate.reset 'x'` drop left's x, and the
|
|
10267
|
+
* resets of both stay, for the layers further below (see {@link stripResets}). Else they are
|
|
10268
|
+
* siblings (the members of a merge): a reset applies within its member's own layers only, and
|
|
10269
|
+
* is left out.
|
|
10270
|
+
*/ mergeNodesAnnotations(left, right, layered = false) {
|
|
10087
10271
|
const annotations = [];
|
|
10088
10272
|
const savedAnnotations = /* @__PURE__ */ new Set();
|
|
10273
|
+
const hidden = layered ? resetNames(right) : void 0;
|
|
10089
10274
|
for (const a of right || []) {
|
|
10275
|
+
if (a.name === ANNOTATE_RESET && !layered) continue;
|
|
10090
10276
|
annotations.push(a);
|
|
10091
10277
|
savedAnnotations.add(a.name);
|
|
10092
10278
|
}
|
|
10093
10279
|
for (const a of left || []) {
|
|
10280
|
+
if (a.name === ANNOTATE_RESET) {
|
|
10281
|
+
if (layered) annotations.push(a);
|
|
10282
|
+
continue;
|
|
10283
|
+
}
|
|
10284
|
+
if (hidden?.has(a.name)) continue;
|
|
10094
10285
|
const spec = this.resolveAnnotation(a.name);
|
|
10095
10286
|
if (spec && spec.config.multiple && spec.config.mergeStrategy === "append" || !savedAnnotations.has(a.name)) annotations.push(a);
|
|
10096
10287
|
}
|
|
@@ -10299,6 +10490,72 @@ const zeroRange = {
|
|
|
10299
10490
|
for (const t of decl.referredIdentifiers) out.add(t);
|
|
10300
10491
|
return out;
|
|
10301
10492
|
}
|
|
10493
|
+
/** The annotation names `@annotate.reset` entries of `anns` reset; `undefined`: none. */ function resetNames(anns) {
|
|
10494
|
+
let out;
|
|
10495
|
+
for (const a of anns ?? []) if (a.name === ANNOTATE_RESET && a.args[0]?.type === "text") (out ?? (out = /* @__PURE__ */ new Set())).add(a.args[0].text);
|
|
10496
|
+
return out;
|
|
10497
|
+
}
|
|
10498
|
+
/**
|
|
10499
|
+
* `anns` without their `@annotate.reset` entries: a node's annotations once the resets applied to
|
|
10500
|
+
* the layers below it (see `AtscriptDoc.mergeNodesAnnotations`).
|
|
10501
|
+
*/ function stripResets(anns) {
|
|
10502
|
+
return anns?.some((a) => a.name === ANNOTATE_RESET) ? anns.filter((a) => a.name !== ANNOTATE_RESET) : anns;
|
|
10503
|
+
}
|
|
10504
|
+
|
|
10505
|
+
//#endregion
|
|
10506
|
+
//#region packages/core/src/defaults/annotate-annotations.ts
|
|
10507
|
+
/** Whether `name` is in the `annotate` namespace: a directive of `annotate` blocks, never metadata. */ function isAnnotateDirective(name) {
|
|
10508
|
+
return name.startsWith("annotate.");
|
|
10509
|
+
}
|
|
10510
|
+
/** The annotations of the `annotate` namespace: directives of `annotate` blocks, not metadata. */ const annotateAnnotations = { reset: new AnnotationSpec({
|
|
10511
|
+
description: annotationExample("Removes an annotation the annotated field or type would otherwise carry — declared on it, inherited from the type it references (`email: Email`, a primitive like `string.email`), from the target of an `annotate … as` copy, or written by a lower-ranked `annotate` block. Allowed only in `annotate` blocks (mutating and `annotate … as`), on an entry or at the top of the block (the type itself). The block's own value of that annotation applies over the reset; any other value does not. Repeat it to reset several annotations.", "annotate User as PublicUser {", " @annotate.reset 'expect.pattern'", " @expect.pattern '^[a-z]+$'", " login", "", " @annotate.reset 'meta.sensitive'", " token", "}"),
|
|
10512
|
+
multiple: true,
|
|
10513
|
+
argument: {
|
|
10514
|
+
name: "annotation",
|
|
10515
|
+
type: "string",
|
|
10516
|
+
description: "The full name of the annotation to remove, without `@` (`expect.pattern`, `meta.label`).",
|
|
10517
|
+
valueScope: (_token, doc) => annotationNames(doc.config.annotations)
|
|
10518
|
+
},
|
|
10519
|
+
validate(token, args, doc) {
|
|
10520
|
+
const messages = [];
|
|
10521
|
+
const parent = token.parentNode;
|
|
10522
|
+
const id = parent && isRef(parent) ? parent.token("identifier") : void 0;
|
|
10523
|
+
if (!(!!parent && isAnnotate(parent) || !!id && !!doc.annotateBlockAt(id.range.start.line, id.range.start.character))) messages.push({
|
|
10524
|
+
severity: TSeverity.Error,
|
|
10525
|
+
message: "@annotate.reset is allowed only in annotate blocks",
|
|
10526
|
+
range: token.range
|
|
10527
|
+
});
|
|
10528
|
+
const name = args[0]?.type === "text" ? args[0].text : void 0;
|
|
10529
|
+
if (name === void 0) return messages;
|
|
10530
|
+
if (isAnnotateDirective(name) || name === "annotate") messages.push({
|
|
10531
|
+
severity: TSeverity.Error,
|
|
10532
|
+
message: `"${name}" is not metadata: it cannot be reset`,
|
|
10533
|
+
range: args[0].range
|
|
10534
|
+
});
|
|
10535
|
+
else if (!doc.resolveAnnotation(name)) {
|
|
10536
|
+
const unknown = doc.config.unknownAnnotation;
|
|
10537
|
+
if (unknown !== "allow") messages.push({
|
|
10538
|
+
severity: unknown === "warn" ? TSeverity.Warning : TSeverity.Error,
|
|
10539
|
+
message: `Unknown annotation "@${name}"`,
|
|
10540
|
+
range: args[0].range
|
|
10541
|
+
});
|
|
10542
|
+
}
|
|
10543
|
+
return messages;
|
|
10544
|
+
}
|
|
10545
|
+
}) };
|
|
10546
|
+
/** The full names of the metadata annotations of `tree` (completion of `@annotate.reset`). */ function annotationNames(tree) {
|
|
10547
|
+
const out = [];
|
|
10548
|
+
forEachAnnotationSpec(tree ?? {}, (name, spec) => {
|
|
10549
|
+
if (!isAnnotateDirective(name)) {
|
|
10550
|
+
const doc = spec.config.description;
|
|
10551
|
+
out.push({
|
|
10552
|
+
value: name,
|
|
10553
|
+
documentation: doc
|
|
10554
|
+
});
|
|
10555
|
+
}
|
|
10556
|
+
});
|
|
10557
|
+
return out;
|
|
10558
|
+
}
|
|
10302
10559
|
|
|
10303
10560
|
//#endregion
|
|
10304
10561
|
//#region packages/core/src/defaults/emit-annotations.ts
|
|
@@ -10336,6 +10593,13 @@ const emitAnnotations = {
|
|
|
10336
10593
|
//#endregion
|
|
10337
10594
|
//#region packages/core/src/defaults/expect-annotations.ts
|
|
10338
10595
|
const NULLABLE_NOTE = "Also allowed on a nullable field (`T | null`, `T | undefined`): `null` passes, any other value must satisfy the constraint.";
|
|
10596
|
+
/** The optional message argument of a constraint annotation. */ const MESSAGE_ARG = {
|
|
10597
|
+
name: "message",
|
|
10598
|
+
optional: true,
|
|
10599
|
+
type: "string",
|
|
10600
|
+
description: "Optional error message to display if the validation fails.",
|
|
10601
|
+
userText: true
|
|
10602
|
+
};
|
|
10339
10603
|
/** Whether `flags` are flags of a JS regular expression. */ function validFlags(flags) {
|
|
10340
10604
|
try {
|
|
10341
10605
|
new RegExp("", flags);
|
|
@@ -10364,12 +10628,40 @@ const NULLABLE_NOTE = "Also allowed on a nullable field (`T | null`, `T | undefi
|
|
|
10364
10628
|
name: argName,
|
|
10365
10629
|
type: "number",
|
|
10366
10630
|
description: argDescription
|
|
10367
|
-
},
|
|
10368
|
-
|
|
10369
|
-
|
|
10370
|
-
|
|
10371
|
-
|
|
10372
|
-
|
|
10631
|
+
}, MESSAGE_ARG]
|
|
10632
|
+
});
|
|
10633
|
+
}
|
|
10634
|
+
/** Whether `text` (a number argument) is a non-negative integer. */ function isCount(text) {
|
|
10635
|
+
return /^\d+$/.test(text);
|
|
10636
|
+
}
|
|
10637
|
+
/**
|
|
10638
|
+
* `@expect.minKeys` / `maxKeys`: a key count (a non-negative integer) plus an optional message.
|
|
10639
|
+
* `@expect.maxKeys` also checks it is not below the node's `@expect.minKeys`.
|
|
10640
|
+
*/ function keyCountSpec(bound, example, argDescription, min) {
|
|
10641
|
+
return new AnnotationSpec({
|
|
10642
|
+
description: annotationExample(`${`Validates that an object has ${bound} this many keys: the keys it keeps (with unknown properties ignored, every own key; else the declared and pattern-matched ones).`} ${NULLABLE_NOTE}`, ...example),
|
|
10643
|
+
defType: ["object"],
|
|
10644
|
+
argument: [{
|
|
10645
|
+
name: "count",
|
|
10646
|
+
type: "number",
|
|
10647
|
+
description: argDescription
|
|
10648
|
+
}, MESSAGE_ARG],
|
|
10649
|
+
validate(mainToken, args) {
|
|
10650
|
+
const count = args[0];
|
|
10651
|
+
if (!count || count.type !== "number") return [];
|
|
10652
|
+
if (!isCount(count.text)) return [{
|
|
10653
|
+
message: `${mainToken.text} expects a non-negative integer`,
|
|
10654
|
+
range: count.range,
|
|
10655
|
+
severity: 1
|
|
10656
|
+
}];
|
|
10657
|
+
const lower = min ? mainToken.parentNode?.annotations?.find((a) => a.name === min)?.args[0] : void 0;
|
|
10658
|
+
if (lower && isCount(lower.text) && Number(lower.text) > Number(count.text)) return [{
|
|
10659
|
+
message: `${mainToken.text} is below @${min} (${lower.text})`,
|
|
10660
|
+
range: count.range,
|
|
10661
|
+
severity: 1
|
|
10662
|
+
}];
|
|
10663
|
+
return [];
|
|
10664
|
+
}
|
|
10373
10665
|
});
|
|
10374
10666
|
}
|
|
10375
10667
|
const expectAnnotations = {
|
|
@@ -10380,12 +10672,7 @@ const expectAnnotations = {
|
|
|
10380
10672
|
name: "length",
|
|
10381
10673
|
type: "number",
|
|
10382
10674
|
description: "The minimum length of the string or array."
|
|
10383
|
-
},
|
|
10384
|
-
name: "message",
|
|
10385
|
-
optional: true,
|
|
10386
|
-
type: "string",
|
|
10387
|
-
description: "Optional error message to display if the validation fails."
|
|
10388
|
-
}]
|
|
10675
|
+
}, MESSAGE_ARG]
|
|
10389
10676
|
}),
|
|
10390
10677
|
maxLength: new AnnotationSpec({
|
|
10391
10678
|
description: annotationExample(`Validates that a string or array has a maximum length. ${NULLABLE_NOTE}`, "@expect.maxLength 5", "name: string"),
|
|
@@ -10394,12 +10681,7 @@ const expectAnnotations = {
|
|
|
10394
10681
|
name: "length",
|
|
10395
10682
|
type: "number",
|
|
10396
10683
|
description: "The maximum length of the string or array."
|
|
10397
|
-
},
|
|
10398
|
-
name: "message",
|
|
10399
|
-
optional: true,
|
|
10400
|
-
type: "string",
|
|
10401
|
-
description: "Optional error message to display if the validation fails."
|
|
10402
|
-
}]
|
|
10684
|
+
}, MESSAGE_ARG]
|
|
10403
10685
|
}),
|
|
10404
10686
|
min: numberBoundSpec("Validates that a number is greater than or equal to a minimum value.", ["@expect.min 18", "age: number"], "minValue", "The minimum value."),
|
|
10405
10687
|
max: numberBoundSpec("Validates that a number is less than or equal to a maximum value.", ["@expect.max 10", "count: number"], "maxValue", "The maximum value."),
|
|
@@ -10407,7 +10689,20 @@ const expectAnnotations = {
|
|
|
10407
10689
|
exclusiveMax: numberBoundSpec("Validates that a number is strictly less than a value (the value itself is rejected).", ["@expect.exclusiveMax 1", "ratio: number"], "exclusiveMaxValue", "The exclusive upper bound (the value must be less than this)."),
|
|
10408
10690
|
int: new AnnotationSpec({
|
|
10409
10691
|
description: annotationExample(`Validates that a number is an integer (no decimal places). ${NULLABLE_NOTE}`, "@expect.int", "age: number"),
|
|
10410
|
-
defType: ["number"]
|
|
10692
|
+
defType: ["number"],
|
|
10693
|
+
argument: [MESSAGE_ARG]
|
|
10694
|
+
}),
|
|
10695
|
+
minKeys: keyCountSpec("at least", ["@expect.minKeys 1", "labels: { [*]: string }"], "The minimum number of keys."),
|
|
10696
|
+
maxKeys: keyCountSpec("at most", ["@expect.maxKeys 20", "labels: { [*]: string }"], "The maximum number of keys.", "expect.minKeys"),
|
|
10697
|
+
message: new AnnotationSpec({
|
|
10698
|
+
description: annotationExample("Custom error message for a type mismatch: wrong type (a non-finite number, a malformed decimal), not the literal (or not one of a literal union's values), no union branch, unknown discriminator, wrong tuple length. Constraint failures keep their own messages (`@expect.minLength` …, `@meta.required`).", "@expect.message 'Choose a valid status'", "status: 'active' | 'blocked'"),
|
|
10699
|
+
nodeType: ["prop", "type"],
|
|
10700
|
+
argument: {
|
|
10701
|
+
name: "message",
|
|
10702
|
+
type: "string",
|
|
10703
|
+
description: "The error message.",
|
|
10704
|
+
userText: true
|
|
10705
|
+
}
|
|
10411
10706
|
}),
|
|
10412
10707
|
pattern: new AnnotationSpec({
|
|
10413
10708
|
description: annotationExample(`Validates that a string matches a specific pattern. ${NULLABLE_NOTE}`, "@expect.pattern \"[a-z]+\", \"u\"", "name: string"),
|
|
@@ -10492,12 +10787,7 @@ const expectAnnotations = {
|
|
|
10492
10787
|
],
|
|
10493
10788
|
description: "Optional flags for the regular expression."
|
|
10494
10789
|
},
|
|
10495
|
-
|
|
10496
|
-
name: "message",
|
|
10497
|
-
optional: true,
|
|
10498
|
-
type: "string",
|
|
10499
|
-
description: "Optional error message to display if the validation fails."
|
|
10500
|
-
}
|
|
10790
|
+
MESSAGE_ARG
|
|
10501
10791
|
],
|
|
10502
10792
|
validate(mainToken, args) {
|
|
10503
10793
|
if (args[0]) {
|
|
@@ -10526,7 +10816,8 @@ const expectAnnotations = {
|
|
|
10526
10816
|
name: "message",
|
|
10527
10817
|
optional: true,
|
|
10528
10818
|
type: "string",
|
|
10529
|
-
description: "Optional custom error message when duplicate items are found."
|
|
10819
|
+
description: "Optional custom error message when duplicate items are found.",
|
|
10820
|
+
userText: true
|
|
10530
10821
|
}],
|
|
10531
10822
|
validate(token, args, doc) {
|
|
10532
10823
|
const field = token.parentNode;
|
|
@@ -10557,7 +10848,8 @@ const expectAnnotations = {
|
|
|
10557
10848
|
name: "message",
|
|
10558
10849
|
optional: true,
|
|
10559
10850
|
type: "string",
|
|
10560
|
-
description: "Optional custom error message (used by @expect.array.uniqueItems when checking key-based uniqueness)."
|
|
10851
|
+
description: "Optional custom error message (used by @expect.array.uniqueItems when checking key-based uniqueness).",
|
|
10852
|
+
userText: true
|
|
10561
10853
|
}],
|
|
10562
10854
|
validate(token, args, doc) {
|
|
10563
10855
|
const field = token.parentNode;
|
|
@@ -10593,7 +10885,8 @@ const metaAnnotations = {
|
|
|
10593
10885
|
argument: {
|
|
10594
10886
|
name: "text",
|
|
10595
10887
|
type: "string",
|
|
10596
|
-
description: "The label to be used for this field or entity."
|
|
10888
|
+
description: "The label to be used for this field or entity.",
|
|
10889
|
+
userText: true
|
|
10597
10890
|
}
|
|
10598
10891
|
}),
|
|
10599
10892
|
id: new AnnotationSpec({
|
|
@@ -10606,7 +10899,8 @@ const metaAnnotations = {
|
|
|
10606
10899
|
argument: {
|
|
10607
10900
|
name: "text",
|
|
10608
10901
|
type: "string",
|
|
10609
|
-
description: "Detailed description for this field or entity."
|
|
10902
|
+
description: "Detailed description for this field or entity.",
|
|
10903
|
+
userText: true
|
|
10610
10904
|
}
|
|
10611
10905
|
}),
|
|
10612
10906
|
documentation: new AnnotationSpec({
|
|
@@ -10636,7 +10930,8 @@ const metaAnnotations = {
|
|
|
10636
10930
|
name: "message",
|
|
10637
10931
|
optional: true,
|
|
10638
10932
|
type: "string",
|
|
10639
|
-
description: "Optional error message to display if the validation fails."
|
|
10933
|
+
description: "Optional error message to display if the validation fails.",
|
|
10934
|
+
userText: true
|
|
10640
10935
|
}],
|
|
10641
10936
|
passedWhenReferred: false
|
|
10642
10937
|
}),
|
|
@@ -10661,6 +10956,33 @@ const metaAnnotations = {
|
|
|
10661
10956
|
})
|
|
10662
10957
|
};
|
|
10663
10958
|
|
|
10959
|
+
//#endregion
|
|
10960
|
+
//#region packages/core/src/defaults/normalize-annotations.ts
|
|
10961
|
+
const NOTE = "Normalizers change the value before validation: they run where the input is normalized (`normalizeForType()`, the Moost validator pipe), never inside the validator itself. Applies to strings: a `string` field, a union of strings and literals (with `null` / `undefined`), or a type alias of one (its fields and array items inherit it). Order: trim, then lowercase, then uppercase.";
|
|
10962
|
+
function normalizeSpec(summary, example, validate) {
|
|
10963
|
+
return new AnnotationSpec({
|
|
10964
|
+
description: annotationExample(`${summary} ${NOTE}`, ...example),
|
|
10965
|
+
nodeType: ["prop", "type"],
|
|
10966
|
+
defType: ["string"],
|
|
10967
|
+
defTypeLiterals: true,
|
|
10968
|
+
multiple: false,
|
|
10969
|
+
validate
|
|
10970
|
+
});
|
|
10971
|
+
}
|
|
10972
|
+
const normalizeAnnotations = {
|
|
10973
|
+
trim: normalizeSpec("Removes leading and trailing whitespace from the string.", ["@normalize.trim", "name: string"]),
|
|
10974
|
+
lowercase: normalizeSpec("Converts the string to lower case.", [
|
|
10975
|
+
"@normalize.trim",
|
|
10976
|
+
"@normalize.lowercase",
|
|
10977
|
+
"email: string.email"
|
|
10978
|
+
]),
|
|
10979
|
+
uppercase: normalizeSpec("Converts the string to upper case.", ["@normalize.uppercase", "countryCode: string"], (mainToken) => mainToken.parentNode?.annotations?.some((a) => a.name === "normalize.lowercase") ? [{
|
|
10980
|
+
message: "@normalize.lowercase has no effect beside @normalize.uppercase (uppercase runs last)",
|
|
10981
|
+
range: mainToken.range,
|
|
10982
|
+
severity: TSeverity.Warning
|
|
10983
|
+
}] : [])
|
|
10984
|
+
};
|
|
10985
|
+
|
|
10664
10986
|
//#endregion
|
|
10665
10987
|
//#region packages/core/src/defaults/primitives.ts
|
|
10666
10988
|
const IPV4_PATTERN = "^((25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)$";
|
|
@@ -10757,6 +11079,10 @@ const primitives = {
|
|
|
10757
11079
|
required: {
|
|
10758
11080
|
documentation: "Non-empty string that contains at least one non-whitespace character.",
|
|
10759
11081
|
annotations: { "meta.required": true }
|
|
11082
|
+
},
|
|
11083
|
+
trimmed: {
|
|
11084
|
+
documentation: "String with leading and trailing whitespace removed before validation (`@normalize.trim`).",
|
|
11085
|
+
annotations: { "normalize.trim": true }
|
|
10760
11086
|
}
|
|
10761
11087
|
}
|
|
10762
11088
|
},
|
|
@@ -10901,6 +11227,10 @@ const primitives = {
|
|
|
10901
11227
|
type: "void",
|
|
10902
11228
|
documentation: "Represents no value."
|
|
10903
11229
|
},
|
|
11230
|
+
unknown: {
|
|
11231
|
+
type: "any",
|
|
11232
|
+
documentation: "Any value (an opaque value: JSON data of any shape). Not checked by the validator; JSON Schema `{}`; TypeScript `unknown`."
|
|
11233
|
+
},
|
|
10904
11234
|
phantom: {
|
|
10905
11235
|
type: "phantom",
|
|
10906
11236
|
documentation: "Phantom type. Does not affect the data type, validation, or schema. Discoverable via runtime type traversal."
|
|
@@ -10915,7 +11245,9 @@ function getDefaultAtscriptConfig() {
|
|
|
10915
11245
|
annotations: {
|
|
10916
11246
|
meta: { ...metaAnnotations },
|
|
10917
11247
|
expect: { ...expectAnnotations },
|
|
10918
|
-
|
|
11248
|
+
normalize: { ...normalizeAnnotations },
|
|
11249
|
+
emit: { ...emitAnnotations },
|
|
11250
|
+
annotate: { ...annotateAnnotations }
|
|
10919
11251
|
}
|
|
10920
11252
|
};
|
|
10921
11253
|
}
|
|
@@ -11077,12 +11409,14 @@ var AtscriptRepo = class {
|
|
|
11077
11409
|
ref: "import(\"@atscript/typescript/utils\").AtscriptRef",
|
|
11078
11410
|
query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode",
|
|
11079
11411
|
expr: "import(\"@atscript/typescript/utils\").AtscriptExprNode",
|
|
11080
|
-
order: "import(\"@atscript/typescript/utils\").AtscriptOrderItem[]"
|
|
11412
|
+
order: "import(\"@atscript/typescript/utils\").AtscriptOrderItem[]",
|
|
11413
|
+
value: "string | number | boolean"
|
|
11081
11414
|
};
|
|
11082
11415
|
const mapArgType = (t) => ANNOTATION_TYPE_MAP[t] || t;
|
|
11083
11416
|
const manager = await this.getSharedPluginManager();
|
|
11084
11417
|
const annotations = {};
|
|
11085
11418
|
if (manager) await manager.loopInAnnotationsSpec((name, spec) => {
|
|
11419
|
+
if (isAnnotateDirective(name)) return;
|
|
11086
11420
|
const types = [];
|
|
11087
11421
|
const multiple = !!spec.config.multiple;
|
|
11088
11422
|
if (Array.isArray(spec.config.argument)) {
|
|
@@ -11110,7 +11444,7 @@ var AtscriptRepo = class {
|
|
|
11110
11444
|
for (const doc of Array.from(this.atscripts.values())) {
|
|
11111
11445
|
const awaited = await doc;
|
|
11112
11446
|
for (const { name, token, args } of awaited.annotations) {
|
|
11113
|
-
if (annotations[name]?.fromSpec) continue;
|
|
11447
|
+
if (annotations[name]?.fromSpec || isAnnotateDirective(name)) continue;
|
|
11114
11448
|
if (!annotations[name]) annotations[name] = {
|
|
11115
11449
|
multiple: false,
|
|
11116
11450
|
fromSpec: false,
|
|
@@ -11459,4 +11793,4 @@ let tmpSeq = 0;
|
|
|
11459
11793
|
}
|
|
11460
11794
|
|
|
11461
11795
|
//#endregion
|
|
11462
|
-
export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BACKTICK_ARG_VOCABULARY, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, FLATTEN_WEB, MERGE_CAP, MERGE_TOO_COMPLEX, NAV_PROP_ANNOTATIONS, NOTHING_IN_COMMON, PRODUCT_CAP, PluginManager, SELF_OPERAND, SELF_SPLIT, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticExprBinaryNode, SemanticExprCallNode, SemanticExprNode, SemanticExprNumberNode, SemanticExprUnaryNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticOrderNode, SemanticPrimitiveNode, SemanticPropNode, SemanticQueryComparisonNode, SemanticQueryFieldRefNode, SemanticQueryLogicalNode, SemanticQueryNode, SemanticQueryValueListNode, SemanticQueryValueNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, StructureModel, Token, UNION_IN_RECURSIVE_MERGE, analyzeQueryCursorContext, andExprs, annotationExample, baseSlot, blockDependencies, blockTargetDocuments, build, clearResolveBareCache, componentOf, components, createAtscriptPlugin, defPosition, defineConfig, distinctFields, documentsEpoch, entryParts, fieldRefTokens, fileUriToPath, flatDefinitions, forEachAnnotationSpec, getDeclaredValue, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, getSiblingAnnotation, getValueCandidates, hasMutatingAnnotates, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isAsView, isBacktickArgType, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isNull, isPhantomNode, isPhantomPath, isPhantomPrimitive, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, moduleId, nonNullishMembers, parseBareSpecifier, pastViews, recordDocumentReads, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveFieldRefsAt, resolveQueryFieldRef, unshell, unwoundFields };
|
|
11796
|
+
export { $n, ANNOTATE_RESET, AnnotationSpec, AtscriptDoc, AtscriptRepo, BACKTICK_ARG_VOCABULARY, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, FLATTEN_WEB, MERGE_CAP, MERGE_TOO_COMPLEX, NAV_PROP_ANNOTATIONS, NOTHING_IN_COMMON, OPAQUE_MERGE, PRODUCT_CAP, PluginManager, SELF_OPERAND, SELF_SPLIT, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticExprBinaryNode, SemanticExprCallNode, SemanticExprNode, SemanticExprNumberNode, SemanticExprUnaryNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticOrderNode, SemanticPrimitiveNode, SemanticPropNode, SemanticQueryComparisonNode, SemanticQueryFieldRefNode, SemanticQueryLogicalNode, SemanticQueryNode, SemanticQueryValueListNode, SemanticQueryValueNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, StructureModel, Token, UNION_IN_RECURSIVE_MERGE, analyzeQueryCursorContext, andExprs, annotatedValueKinds, annotationExample, baseSlot, blockDependencies, blockTargetDocuments, build, clearResolveBareCache, componentOf, components, createAtscriptPlugin, defPosition, defineConfig, distinctFields, documentsEpoch, entryParts, fieldRefTokens, fileUriToPath, flatDefinitions, forEachAnnotationSpec, getDeclaredValue, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, getSiblingAnnotation, getValueCandidates, hasMutatingAnnotates, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isAsView, isBacktickArgType, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isNull, isPhantomNode, isPhantomPath, isPhantomPrimitive, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, moduleId, nonNullishMembers, parseBareSpecifier, pastViews, recordDocumentReads, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveFieldRefsAt, resolveQueryFieldRef, unshell, unwoundFields, userTextAnnotations, userTextFields, withoutAsExtension };
|