@atscript/typescript 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/cli.cjs CHANGED
@@ -186,7 +186,7 @@ var BaseRenderer = class extends CodePrinter {
186
186
  renderType(node) {}
187
187
  renderAnnotate(node) {}
188
188
  transformFromPath(path) {
189
- return `${path}.as`;
189
+ return `${(0, _atscript_core.withoutAsExtension)(path)}.as`;
190
190
  }
191
191
  renderImport(node) {
192
192
  const def = node.getDefinition();
@@ -786,11 +786,14 @@ var TypeRenderer = class TypeRenderer extends BaseRenderer {
786
786
  const written = only?.prop.getDefinition();
787
787
  return written && !((0, _atscript_core.isGroup)(only.def) && only.def !== written) ? written : only?.def;
788
788
  }
789
+ /** The TypeScript type of a final primitive type (`any`, the `unknown` primitive: `unknown`). */ function finalTsType(t) {
790
+ return t === "void" ? "undefined" : t === "any" ? "unknown" : t;
791
+ }
789
792
  function renderPrimitiveTypeDef(def) {
790
793
  if (!def) return "unknown";
791
- if (typeof def === "string") return def === "void" ? "undefined" : def;
794
+ if (typeof def === "string") return finalTsType(def);
792
795
  switch (def.kind) {
793
- case "final": return def.value === "void" ? "undefined" : def.value;
796
+ case "final": return finalTsType(def.value);
794
797
  case "union": return def.items.map(renderPrimitiveTypeDef).join(" | ");
795
798
  case "intersection": return def.items.map((item) => typeof item === "object" && item.kind === "union" ? `(${renderPrimitiveTypeDef(item)})` : renderPrimitiveTypeDef(item)).join(" & ");
796
799
  case "tuple": return `[${def.items.map(renderPrimitiveTypeDef).join(", ")}]`;
@@ -875,7 +878,8 @@ const CHECKS_IMPORT_MARKER = "/*@@atscript-compiled-checks-import@@*/";
875
878
  bundledSchemaOf: "$jbm",
876
879
  $ps: "$ps",
877
880
  $ak: "$ak",
878
- $nr: "$nk"
881
+ $nr: "$nk",
882
+ $ut: "$ut"
879
883
  };
880
884
  const LITERAL_IDENTIFIERS = new Set([
881
885
  "true",
@@ -929,7 +933,8 @@ var JsRenderer = class extends BaseRenderer {
929
933
  /**
930
934
  * Relative imports get the configured `moduleExtension`; bare specifiers
931
935
  * always keep `.as` — they resolve through the package's `exports` map.
932
- */ transformFromPath(path) {
936
+ */ transformFromPath(written) {
937
+ const path = (0, _atscript_core.withoutAsExtension)(written);
933
938
  return (0, _atscript_core.isBareSpecifier)(path) ? `${path}.as` : `${path}${this.opts?.moduleExtension ?? ".as"}`;
934
939
  }
935
940
  /**
@@ -1074,6 +1079,7 @@ var JsRenderer = class extends BaseRenderer {
1074
1079
  const text = this.compiles ? this.spliceCompiledChecks(module.text, realm) : module.text;
1075
1080
  if (this.bundledSchemas.length === 0) return text;
1076
1081
  const views = /* @__PURE__ */ new Map();
1082
+ const options = jsonSchemaOptionsArg(this.opts);
1077
1083
  const viewOf = (id) => {
1078
1084
  let view = views.get(id);
1079
1085
  if (!view) {
@@ -1081,12 +1087,12 @@ var JsRenderer = class extends BaseRenderer {
1081
1087
  let accounted = [REALM_FAILED];
1082
1088
  try {
1083
1089
  const type = realm.classOf(this.doc, id);
1084
- schema = JSON.stringify(realm.rt.buildJsonSchema(type));
1090
+ schema = JSON.stringify(realm.rt.buildJsonSchema(type, this.opts?.jsonSchemaOptions));
1085
1091
  accounted = this.accountedFor(realm, type);
1086
1092
  } catch {}
1087
1093
  view = {
1088
1094
  schema,
1089
- accounted: accounted.length > 0 ? `, ${JSON.stringify(accounted)}` : ""
1095
+ accounted: accounted.length > 0 || options ? `, ${JSON.stringify(accounted)}${options ? `, ${options}` : ""}` : ""
1090
1096
  };
1091
1097
  views.set(id, view);
1092
1098
  }
@@ -1190,7 +1196,8 @@ var JsRenderer = class extends BaseRenderer {
1190
1196
  */ renderJsonSchemaMethod(_node) {
1191
1197
  if (this.jsonSchemaMode === "lazy") {
1192
1198
  this.writeln("static toJsonSchema() {");
1193
- this.indent().writeln(`return ${this.util("lazyJsonSchema")}(this)`);
1199
+ const options = jsonSchemaOptionsArg(this.opts);
1200
+ this.indent().writeln(`return ${this.util("lazyJsonSchema")}(this${options ? `, ${options}` : ""})`);
1194
1201
  this.unindent();
1195
1202
  this.writeln("}");
1196
1203
  } else {
@@ -1331,12 +1338,16 @@ var JsRenderer = class extends BaseRenderer {
1331
1338
  if (dotIdx === -1) return `() => ${this.annotationTypeName(text, origin)}`;
1332
1339
  return `{ type: () => ${this.annotationTypeName(text.slice(0, dotIdx), origin)}, field: "${escapeQuotes(text.slice(dotIdx + 1))}" }`;
1333
1340
  }
1334
- emitArgValue(aSpec, argToken, origin) {
1341
+ emitArgValue(aSpec, argToken, origin, mainToken) {
1335
1342
  if (aSpec.type === "ref") return this.emitRefValue(argToken.text, origin);
1336
1343
  if (aSpec.type === "query" && argToken.queryNode) return this.emitQueryTree(argToken.queryNode, origin);
1337
1344
  if (aSpec.type === "expr" && argToken.exprNode) return this.emitExprNode(argToken.exprNode.expression, origin);
1338
1345
  if (aSpec.type === "order" && argToken.orderNode) return `[${argToken.orderNode.items.map((item) => `{ ref: ${this.emitQueryFieldRef(item.ref, origin)}${item.desc ? ", desc: true" : ""} }`).join(", ")}]`;
1339
- return aSpec.type === "string" ? `"${escapeQuotes(argToken.text)}"` : argToken.text;
1346
+ return aSpec.type === "string" || aSpec.type === "value" && (argToken.type === "text" || argToken.type === "number" && this.decimalField(mainToken, origin)) ? `"${escapeQuotes(argToken.text)}"` : argToken.text;
1347
+ }
1348
+ /** Whether annotation `mainToken` is written on a `decimal` field (not one that holds numbers). */ decimalField(mainToken, origin) {
1349
+ const kinds = (0, _atscript_core.annotatedValueKinds)(mainToken, origin ?? this.doc);
1350
+ return !!kinds?.has("decimal") && !kinds.has("number") && !kinds.has("unknown");
1340
1351
  }
1341
1352
  emitExprNode(node, origin) {
1342
1353
  switch (node.entity) {
@@ -1416,13 +1427,13 @@ var JsRenderer = class extends BaseRenderer {
1416
1427
  targetValue = "{ ";
1417
1428
  let i = 0;
1418
1429
  for (const aSpec of spec.arguments) {
1419
- if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin)}${i === length - 1 ? "" : ", "} `;
1430
+ if (an.args[i]) targetValue += `${wrapProp(aSpec.name)}: ${this.emitArgValue(aSpec, an.args[i], origin, an.token)}${i === length - 1 ? "" : ", "} `;
1420
1431
  i++;
1421
1432
  }
1422
1433
  targetValue += "}";
1423
1434
  } else if (an.args[0]) {
1424
1435
  const aSpec = spec.arguments[0];
1425
- targetValue = this.emitArgValue(aSpec, an.args[0], origin);
1436
+ targetValue = this.emitArgValue(aSpec, an.args[0], origin, an.token);
1426
1437
  }
1427
1438
  }
1428
1439
  } else {
@@ -1468,6 +1479,17 @@ const JS_INTERPRETED_FORMAT = "js:interpreted";
1468
1479
  if (opts?.jsonSchema !== void 0) return opts.jsonSchema;
1469
1480
  return false;
1470
1481
  }
1482
+ /**
1483
+ * The `jsonSchemaOptions` argument the generated `toJsonSchema()` passes to the runtime: a JS
1484
+ * literal of the options that differ from the defaults, `undefined` when none do.
1485
+ */ function jsonSchemaOptionsArg(opts) {
1486
+ const o = opts?.jsonSchemaOptions;
1487
+ const set = {};
1488
+ if (o?.closed === true) set.closed = true;
1489
+ if (o?.annotations === false) set.annotations = false;
1490
+ if (o?.enums === false) set.enums = false;
1491
+ return Object.keys(set).length > 0 ? JSON.stringify(set) : void 0;
1492
+ }
1471
1493
  /** A generated JS module of `doc`, checked to load in a build (see `assertLoads`). */ function renderJs(doc, opts, mode, loadCheck) {
1472
1494
  const content = rendererOf(doc, opts, mode).render();
1473
1495
  assertLoads(doc, opts, mode, loadCheck);
@@ -1494,8 +1516,11 @@ const tsPlugin = (opts) => {
1494
1516
  for (const [key, val] of Object.entries(annotations)) {
1495
1517
  const multiple = val.multiple;
1496
1518
  const typeLine = Array.from(val.types).map((t) => {
1497
- if (t.type === "object" && "props" in t) return `{ ${Object.entries(t.props).map(([k, v]) => `${wrapProp(k)}${v.optional ? "?" : ""}: ${v.type}`).join(", ")} }`;
1498
- else return "optional" in t && t.optional ? `${t.type} | true` : t.type;
1519
+ if (t.type === "object" && "props" in t) {
1520
+ const props = Object.entries(t.props);
1521
+ const object = `{ ${props.map(([k, v]) => `${wrapProp(k)}${v.optional ? "?" : ""}: ${v.type}`).join(", ")} }`;
1522
+ return props.length === 1 && props[0][1].optional ? `${object} | true` : object;
1523
+ } else return "optional" in t && t.optional ? `${t.type} | true` : t.type;
1499
1524
  }).join(" | ");
1500
1525
  rendered.push(`${wrapProp(key)}: ${multiple ? "(" : ""}${typeLine}${multiple ? ")[]" : ""}`);
1501
1526
  }
@@ -1532,6 +1557,7 @@ const tsPlugin = (opts) => {
1532
1557
  "expect.maxLength",
1533
1558
  "expect.array.uniqueItems"
1534
1559
  ];
1560
+ /** Annotations of an object node, in check order (before its props). */ const OBJECT_KEYS = ["expect.minKeys", "expect.maxKeys"];
1535
1561
  /**
1536
1562
  * Every annotation key the validator pre-check reads. The order is the bit order of
1537
1563
  * compiled-check layouts: changing it changes the layout format.
@@ -1545,7 +1571,9 @@ const tsPlugin = (opts) => {
1545
1571
  "expect.max",
1546
1572
  "expect.exclusiveMin",
1547
1573
  "expect.exclusiveMax",
1548
- "expect.array.uniqueItems"
1574
+ "expect.array.uniqueItems",
1575
+ "expect.minKeys",
1576
+ "expect.maxKeys"
1549
1577
  ];
1550
1578
 
1551
1579
  //#endregion
@@ -1578,6 +1606,9 @@ const mapSet = Map.prototype.set;
1578
1606
  /** The number of metadata writes so far (see `metadataWrites`). */ function metadataWriteCount() {
1579
1607
  return metadataWrites;
1580
1608
  }
1609
+ /** Records a write of a node's metadata the maps do not see: the node's map replaced. */ function metadataReplaced() {
1610
+ metadataWrites++;
1611
+ }
1581
1612
  /**
1582
1613
  * Metadata map of runtime type nodes: a `Map` whose writes to validator annotation keys
1583
1614
  * are tracked (see {@link invalidateCompiledValidators}). Reads are the builtin ones.
@@ -1643,6 +1674,15 @@ const notReferred = (key) => ((FLAGS.get(key) ?? 0) & NOT_REFERRED) !== 0;
1643
1674
  * (`string.required` → `meta.required`) are part of the type, so they pass every reference layer
1644
1675
  * although their key is `passedWhenReferred: false` (0.1.110).
1645
1676
  */ const INTRINSIC = /* @__PURE__ */ new WeakMap();
1677
+ /**
1678
+ * Keys a map hides from its bases (`@annotate.reset`): read as if no base had them. Kept per map
1679
+ * (as `INTRINSIC`), moved with it when a node's map is replaced; `hiding`: some map hides a key
1680
+ * (until then the reads skip the lookup).
1681
+ */ const HIDDEN = /* @__PURE__ */ new WeakMap();
1682
+ let hiding = false;
1683
+ /** Whether map `m` hides `key` from its bases (see {@link HIDDEN}). */ function hides(m, key) {
1684
+ return hiding && HIDDEN.get(m)?.has(key) === true;
1685
+ }
1646
1686
  const MISS = Symbol("miss");
1647
1687
  /** The view of a layered map without effective entries (never written: views stay internal). */ const NO_ENTRIES = new AnnotationMap();
1648
1688
  const mapGet = Map.prototype.get;
@@ -1676,6 +1716,7 @@ let _Symbol_iterator = Symbol.iterator;
1676
1716
  const v = mapGet.call(this, key);
1677
1717
  if (v !== void 0 || mapHas.call(this, key)) return v;
1678
1718
  }
1719
+ if (hiding && hides(this, key)) return MISS;
1679
1720
  if (nr && this.r) {
1680
1721
  for (const n of this.b) {
1681
1722
  const x = intrinsicLookup(n.metadata, key);
@@ -1706,10 +1747,14 @@ let _Symbol_iterator = Symbol.iterator;
1706
1747
  }
1707
1748
  has(key) {
1708
1749
  const view = this.view();
1709
- return view === void 0 ? this.lookup(key, notReferred(key)) !== MISS : mapHas.call(view, key);
1750
+ return view === void 0 ? this.liveHas(key) : mapHas.call(view, key);
1751
+ }
1752
+ /** `has` read through the layers (see the file comment). */ liveHas(key) {
1753
+ return this.lookup(key, notReferred(key)) !== MISS;
1710
1754
  }
1711
1755
  /** An append key: the bases' values (lowest priority first), then the own ones. */ append(key) {
1712
1756
  const own = mapGet.call(this, key);
1757
+ if (hiding && hides(this, key)) return own;
1713
1758
  if (this.r && notReferred(key)) {
1714
1759
  const parts = [];
1715
1760
  const acc = {
@@ -1746,8 +1791,20 @@ let _Symbol_iterator = Symbol.iterator;
1746
1791
  }
1747
1792
  liveKeys() {
1748
1793
  const out = /* @__PURE__ */ new Set();
1749
- keysOf(this, false, out, /* @__PURE__ */ new Map());
1750
- return [...out];
1794
+ return keysOf(this, false, out, /* @__PURE__ */ new Map()) ? [...out].filter((k) => this.liveHas(k)) : [...out];
1795
+ }
1796
+ /** Deletes the own value of `key`; a key hidden from the bases (`hideKey`) shows them again. */ delete(key) {
1797
+ const deleted = super.delete(key);
1798
+ if ((hiding ? HIDDEN.get(this) : void 0)?.delete(key)) {
1799
+ touched(this);
1800
+ metadataReplaced();
1801
+ return true;
1802
+ }
1803
+ return deleted;
1804
+ }
1805
+ /** Deletes the own values; the keys hidden from the bases (`hideKey`) show them again. */ clear() {
1806
+ super.clear();
1807
+ HIDDEN.delete(this);
1751
1808
  }
1752
1809
  keys() {
1753
1810
  return this.effectiveKeys()[Symbol.iterator]();
@@ -1798,7 +1855,7 @@ Object.defineProperty(LayerMap.prototype, "size", {
1798
1855
  if (m instanceof LayerMap ? mapHas.call(m, key) : m.has(key)) return m instanceof LayerMap ? mapGet.call(m, key) : m.get(key);
1799
1856
  }
1800
1857
  const b = m.b;
1801
- if (b !== void 0) for (const n of b) {
1858
+ if (b !== void 0 && !hides(m, key)) for (const n of b) {
1802
1859
  const x = intrinsicLookup(n.metadata, key);
1803
1860
  if (x !== MISS) return x;
1804
1861
  }
@@ -1823,7 +1880,7 @@ Object.defineProperty(LayerMap.prototype, "size", {
1823
1880
  const was = acc.seen.get(m);
1824
1881
  if (!visit(m, filtered, acc.seen)) return;
1825
1882
  const layer = m instanceof LayerMap ? m : void 0;
1826
- if (layer) {
1883
+ if (layer && !hides(layer, key)) {
1827
1884
  const below = filtered || layer.r && notReferred(key);
1828
1885
  for (let i = layer.b.length - 1; i >= 0; i--) collect(layer.b[i].metadata, key, acc, below);
1829
1886
  }
@@ -1832,14 +1889,16 @@ Object.defineProperty(LayerMap.prototype, "size", {
1832
1889
  }
1833
1890
  /**
1834
1891
  * The keys of `m` (own first, then its bases'), each map once (see {@link visit}). `filtered`:
1835
- * reached through a reference layer.
1892
+ * reached through a reference layer. Returns whether a map visited hides keys from its bases.
1836
1893
  */ function keysOf(m, filtered, out, seen) {
1837
- if (!visit(m, filtered, seen)) return;
1894
+ if (!visit(m, filtered, seen)) return false;
1895
+ let hid = hiding && (HIDDEN.get(m)?.size ?? 0) > 0;
1838
1896
  const layer = m instanceof LayerMap ? m : void 0;
1839
1897
  const own = layer ? Map.prototype.keys.call(m) : m.keys();
1840
1898
  const intrinsic = INTRINSIC.get(m);
1841
1899
  for (const k of own) if (!filtered || !notReferred(k) || intrinsic?.has(k)) out.add(k);
1842
- if (layer) for (const n of layer.b) keysOf(n.metadata, filtered || layer.r, out, seen);
1900
+ if (layer) for (const n of layer.b) hid = keysOf(n.metadata, filtered || layer.r, out, seen) || hid;
1901
+ return hid;
1843
1902
  }
1844
1903
  /**
1845
1904
  * `m` has no entry (own or through its bases): the validators' `metadata.size === 0` fast path,
@@ -1959,11 +2018,14 @@ const B_MAX = bit("expect.max");
1959
2018
  const B_EX_MIN = bit("expect.exclusiveMin");
1960
2019
  const B_EX_MAX = bit("expect.exclusiveMax");
1961
2020
  const B_UNIQUE = bit("expect.array.uniqueItems");
2021
+ const B_MIN_KEYS = bit("expect.minKeys");
2022
+ const B_MAX_KEYS = bit("expect.maxKeys");
1962
2023
  /** Annotations the pre-check reads per kind of value (see validator-keys.ts). */ const STRING_BITS = bitsOf(STRING_KEYS);
1963
2024
  const NUMBER_BITS = bitsOf(NUMBER_KEYS);
1964
2025
  const ARRAY_BITS = bitsOf(ARRAY_KEYS);
2026
+ const OBJECT_BITS = bitsOf(OBJECT_KEYS);
1965
2027
  const BOOLEAN_BITS = bitsOf(BOOLEAN_KEYS);
1966
- /** Keys whose value the compiled code reads (one K slot each). */ const VALUE_BITS = B_MIN_LENGTH | B_MAX_LENGTH | B_MIN | B_MAX | B_EX_MIN | B_EX_MAX;
2028
+ /** Keys whose value the compiled code reads (one K slot each). */ const VALUE_BITS = B_MIN_LENGTH | B_MAX_LENGTH | B_MIN | B_MAX | B_EX_MIN | B_EX_MAX | B_MIN_KEYS | B_MAX_KEYS;
1967
2029
  const FLAG_BITS = B_REQUIRED | B_INT | B_UNIQUE;
1968
2030
  const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
1969
2031
  /** The field holding the bound of each value key's object form. */ const BOUND_FIELDS = {
@@ -1972,13 +2034,89 @@ const ALL_BITS = (1 << VALIDATOR_KEYS.length) - 1;
1972
2034
  [B_MIN]: "minValue",
1973
2035
  [B_MAX]: "maxValue",
1974
2036
  [B_EX_MIN]: "exclusiveMinValue",
1975
- [B_EX_MAX]: "exclusiveMaxValue"
2037
+ [B_EX_MAX]: "exclusiveMaxValue",
2038
+ [B_MIN_KEYS]: "count",
2039
+ [B_MAX_KEYS]: "count"
1976
2040
  };
1977
2041
 
1978
2042
  //#endregion
1979
2043
  //#region packages/typescript/src/runtime/validator-fast-check.ts
1980
2044
  /** Shared placeholder for the per-kind arrays of plans that don't use them. */ const EMPTY = Object.freeze([]);
1981
2045
 
2046
+ //#endregion
2047
+ //#region packages/typescript/src/runtime/validator-messages.ts
2048
+ /**
2049
+ * Validator error codes, their default English templates and the translation helpers.
2050
+ *
2051
+ * The validator is locale-agnostic: every error it reports carries a stable `code` and the
2052
+ * `params` its message needs, and its `message` is the default English text (the code's
2053
+ * template filled with the params) or the app's own text from an annotation (`custom: true`).
2054
+ * Translate after the fact with {@link localizeErrors}, or per validator with the `translate`
2055
+ * option.
2056
+ */ /**
2057
+ * Default English templates of the built-in error codes. `{name}` is replaced with
2058
+ * `params.name` (see {@link formatValidatorMessage}).
2059
+ */ const VALIDATOR_MESSAGES = Object.freeze({
2060
+ REQUIRED: "Must not be empty",
2061
+ REQUIRED_CHECKED: "Must be checked",
2062
+ TYPE: "Expected {expected}, got {actual}",
2063
+ TYPE_ARRAY: "Expected array",
2064
+ TYPE_OBJECT: "Expected object",
2065
+ TYPE_DECIMAL: "Expected string (decimal), got {actual}",
2066
+ NOT_FINITE: "Expected finite number, got {actual}",
2067
+ DECIMAL_FORMAT: "Invalid decimal format: \"{value}\"",
2068
+ NEVER: "This type is impossible, must be an internal problem",
2069
+ LITERAL: "Expected {expected}, got {actual}",
2070
+ UNION: "Value does not match any of the allowed types: {expected}",
2071
+ UNION_DISCRIMINATOR: "Expected one of {allowed}, got {actual}",
2072
+ UNEXPECTED_PROPERTY: "Unexpected property",
2073
+ TUPLE_LENGTH: "Expected array of length {length}",
2074
+ MIN_LENGTH: "Expected minimum length of {min} characters, got {actual} characters",
2075
+ MAX_LENGTH: "Expected maximum length of {max} characters, got {actual} characters",
2076
+ MIN_ITEMS: "Expected minimum length of {min} items, got {actual} items",
2077
+ MAX_ITEMS: "Expected maximum length of {max} items, got {actual} items",
2078
+ UNIQUE_ITEMS: "Duplicate items are not allowed",
2079
+ MIN_KEYS: "Expected at least {min} properties, got {actual}",
2080
+ MAX_KEYS: "Expected at most {max} properties, got {actual}",
2081
+ PATTERN: "Value is expected to match pattern \"{pattern}\"",
2082
+ INT: "Expected integer, got {actual}",
2083
+ MIN: "Expected minimum {min}, got {actual}",
2084
+ MAX: "Expected maximum {max}, got {actual}",
2085
+ EXCLUSIVE_MIN: "Expected greater than {min}, got {actual}",
2086
+ EXCLUSIVE_MAX: "Expected less than {max}, got {actual}",
2087
+ EMAIL: "Invalid email format.",
2088
+ PHONE: "Invalid phone number format.",
2089
+ DATE: "Invalid date format.",
2090
+ ISO_DATE: "Invalid ISO date format.",
2091
+ UUID: "Invalid UUID format.",
2092
+ URL: "Invalid URL format.",
2093
+ IPV4: "Invalid IPv4 address.",
2094
+ IPV6: "Invalid IPv6 address.",
2095
+ IP: "Invalid IP address."
2096
+ });
2097
+ /**
2098
+ * The built-in validator error codes by name (`VALIDATOR_ERROR_CODES.MIN_LENGTH === 'MIN_LENGTH'`).
2099
+ * `CUSTOM` is the code of an error a validator plugin reports without a code of its own.
2100
+ */ const VALIDATOR_ERROR_CODES = Object.freeze(Object.fromEntries([...Object.keys(VALIDATOR_MESSAGES), "CUSTOM"].map((code) => [code, code])));
2101
+ /**
2102
+ * Codes of the format messages built into the `string.*` primitives, by their English text
2103
+ * (the primitives' `@expect.pattern` message).
2104
+ */ const FORMAT_CODES = new Map([
2105
+ "EMAIL",
2106
+ "PHONE",
2107
+ "DATE",
2108
+ "ISO_DATE",
2109
+ "UUID",
2110
+ "URL",
2111
+ "IPV4",
2112
+ "IPV6",
2113
+ "IP"
2114
+ ].map((code) => [VALIDATOR_MESSAGES[code], code]));
2115
+ /**
2116
+ * The {@link VALIDATOR_MESSAGES} templates with placeholders, split at them: text, name, text,
2117
+ * name, …, text (`'a {b} c'.split(/\{(\w+)\}/)`).
2118
+ */ const BUILTIN_PARTS = new Map(Object.values(VALIDATOR_MESSAGES).filter((template) => template.includes("{")).map((template) => [template, template.split(/\{(\w+)\}/)]));
2119
+
1982
2120
  //#endregion
1983
2121
  //#region packages/typescript/src/runtime/annotated-type.ts
1984
2122
  /**
@@ -2006,6 +2144,40 @@ var _globalThis$1, _Symbol_for$1;
2006
2144
  return path.flatMap(([, kind], j) => kind !== 0 || j === path.length - 1 ? [j] : []);
2007
2145
  }
2008
2146
 
2147
+ //#endregion
2148
+ //#region packages/typescript/src/runtime/user-text.ts
2149
+ /**
2150
+ * The annotations holding user-facing text (labels, descriptions, error messages): the arguments
2151
+ * their specs flag `userText`. Core's are known from the start ({@link CORE_USER_TEXT}); a plugin's
2152
+ * are registered by the generated modules that write them (`$ut`), or by the plugin itself
2153
+ * ({@link registerUserText}), so a translator finds them at runtime without the specs.
2154
+ */ /**
2155
+ * `true`: the value itself is the text; `'expression'`: the value is the source of a function the
2156
+ * client evaluates, its string literals the texts; a list: those fields of the value object are
2157
+ * (a name ending in `()`: that field is an expression).
2158
+ */ /**
2159
+ * The user-facing text of `@atscript/core`'s annotations (its specs' `userText` arguments; a test
2160
+ * keeps them equal).
2161
+ */ const CORE_USER_TEXT = new Map([
2162
+ ["meta.label", true],
2163
+ ["meta.description", true],
2164
+ ["meta.required", ["message"]],
2165
+ ["expect.minLength", ["message"]],
2166
+ ["expect.maxLength", ["message"]],
2167
+ ["expect.min", ["message"]],
2168
+ ["expect.max", ["message"]],
2169
+ ["expect.exclusiveMin", ["message"]],
2170
+ ["expect.exclusiveMax", ["message"]],
2171
+ ["expect.int", ["message"]],
2172
+ ["expect.minKeys", ["message"]],
2173
+ ["expect.maxKeys", ["message"]],
2174
+ ["expect.message", true],
2175
+ ["expect.pattern", ["message"]],
2176
+ ["expect.array.uniqueItems", ["message"]],
2177
+ ["expect.array.key", ["message"]]
2178
+ ]);
2179
+ const USER_TEXT = new Map(CORE_USER_TEXT);
2180
+
2009
2181
  //#endregion
2010
2182
  //#region packages/typescript/src/codegen/import-cycles.ts
2011
2183
  /** The strongly connected component of each document's imports (see {@link sccOf}). */ const componentMemo = /* @__PURE__ */ new WeakMap();
@@ -2511,7 +2683,13 @@ var JsNextRenderer = class extends JsRenderer {
2511
2683
  }
2512
2684
  /** `$a(P.metadata, …)` writes of a class's own annotations (after its `$alias`). */ annotateCalls(name, node) {
2513
2685
  let out = "";
2686
+ const resets = (node.annotations ?? []).filter((an) => an.name === _atscript_core.ANNOTATE_RESET);
2687
+ if (resets.length > 0) {
2688
+ const data = this.blockAnnotationsData(node, resets);
2689
+ out += `\n${this.util("$blk")}(null, -1, ${name}, [[[${data.join(", ")}], []]])`;
2690
+ }
2514
2691
  for (const an of node.annotations ?? []) {
2692
+ if (an.name === _atscript_core.ANNOTATE_RESET) continue;
2515
2693
  const { value, multiple } = this.computeAnnotationValue(node, an);
2516
2694
  out += `\n${this.util("annotate")}(${name}.metadata, ${str(an.name)}, ${value}${multiple ? ", true" : ""})`;
2517
2695
  }
@@ -3452,19 +3630,21 @@ var JsNextRenderer = class extends JsRenderer {
3452
3630
  * The statement needs what the paths go through built (`$f` guards, needs).
3453
3631
  */ entriesData(b, reads) {
3454
3632
  const entries = [];
3455
- const annotationsOf = (node) => (node.annotations ?? []).map((an) => {
3456
- const { value, multiple } = this.computeAnnotationValue(node, an);
3457
- return `[${str(an.name)}, ${value}${multiple ? ", 1" : ""}]`;
3458
- });
3459
- if (b.rank && b.node.annotations?.length) entries.push(`[[${annotationsOf(b.node).join(", ")}], []]`);
3633
+ if (b.rank && b.node.annotations?.length) entries.push(`[[${this.blockAnnotationsData(b.node).join(", ")}], []]`);
3460
3634
  for (const en of b.entries) {
3461
3635
  if (en.error || en.paths.length === 0) continue;
3462
3636
  const copy = reads !== b.target;
3463
3637
  const paths = en.paths.map((p, i) => `[${stepsText(this.stepsData(reads, p, en.kinds[i], false, copy))}]`);
3464
- entries.push(`[[${annotationsOf(en.ref).join(", ")}], ${paths.join(", ")}]`);
3638
+ entries.push(`[[${this.blockAnnotationsData(en.ref).join(", ")}], ${paths.join(", ")}]`);
3465
3639
  }
3466
3640
  return entries.length > 0 ? `[\n ${entries.join(",\n ")},\n]` : "";
3467
3641
  }
3642
+ /** Annotations `anns` of `node` as `$blk` entry data: `[name, value]`, `, 1` for a `multiple`. */ blockAnnotationsData(node, anns = node.annotations ?? []) {
3643
+ return anns.map((an) => {
3644
+ const { value, multiple } = this.computeAnnotationValue(node, an);
3645
+ return `[${str(an.name)}, ${value}${multiple ? ", 1" : ""}]`;
3646
+ });
3647
+ }
3468
3648
  /**
3469
3649
  * The runtime `[step, kind]`s of model path `p` of `reads` (an `as` copy's: its target's
3470
3650
  * structure), and its needs: the classes it walks are built first (a shell def clones a built
@@ -3952,14 +4132,35 @@ var JsNextRenderer = class extends JsRenderer {
3952
4132
  const rank = blocks[0].rank;
3953
4133
  return `const ${R} = [${rank.depth}, ${str(rank.id)}]`;
3954
4134
  }
3955
- /** The layer registries (`$ak`, `$nr`: how layers read those keys), before any statement. */ registries() {
4135
+ /**
4136
+ * The registries (`$ak`, `$nr`: how layers read those keys; `$ut`: the keys holding user-facing
4137
+ * text), before any statement.
4138
+ */ registries() {
3956
4139
  const { append, notReferred } = flagKeys(this.doc.config.annotations);
3957
4140
  const out = [];
3958
4141
  if (append.length > 0) out.push(`${this.util("$ak")}(${append.map(str).join(", ")})`);
3959
4142
  if (notReferred.length > 0) out.push(`${this.util("$nr")}(${notReferred.map(str).join(", ")})`);
4143
+ const userText = this.moduleUserText();
4144
+ if (userText.length > 0) out.push(`${this.util("$ut")}(${userText.map(str).join(", ")})`);
3960
4145
  return out;
3961
4146
  }
3962
4147
  /**
4148
+ * The plugin annotations holding user-facing text this module writes (`$ut` entries: `key`,
4149
+ * `key()` for an expression, `key:field`, `key:field()`); core's are known to the runtime from
4150
+ * the start (`CORE_USER_TEXT`).
4151
+ */ moduleUserText() {
4152
+ const out = /* @__PURE__ */ new Set();
4153
+ for (const name of new Set(this.doc.annotations.map((a) => a.name))) {
4154
+ if (CORE_USER_TEXT.has(name)) continue;
4155
+ const spec = this.doc.resolveAnnotation(name);
4156
+ const fields = spec && (0, _atscript_core.userTextFields)(spec);
4157
+ if (fields === true) out.add(name);
4158
+ else if (fields === "expression") out.add(`${name}()`);
4159
+ else if (fields) for (const f of fields) out.add(`${name}:${f}`);
4160
+ }
4161
+ return [...out].sort();
4162
+ }
4163
+ /**
3963
4164
  * The runtime steps of a model path: a `X | null` union the model passes through is a union
3964
4165
  * node at runtime (its non-null item: `|i`, own when the union's holder is, else shelled).
3965
4166
  */ runtimeSteps(d, steps, kinds, { copy = false, items: withItems = false, pure = false } = {}) {
package/dist/index.cjs CHANGED
@@ -1,11 +1,11 @@
1
1
  Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
2
- const require_plugin = require('./plugin-oUSsb3Ri.cjs');
3
- const require_unique_name = require('./unique-name-xWd9uO-k.cjs');
2
+ const require_plugin = require('./plugin-JJ9MJ6AF.cjs');
3
+ const require_user_text = require('./user-text-Dl8FNKLL.cjs');
4
4
 
5
5
  exports.JS_COMPILED_FORMAT = require_plugin.JS_COMPILED_FORMAT;
6
6
  exports.JS_INTERPRETED_FORMAT = require_plugin.JS_INTERPRETED_FORMAT;
7
7
  exports.default = require_plugin.tsPlugin;
8
8
  exports.importCycle = require_plugin.importCycle;
9
- exports.invalidateCompiledValidators = require_unique_name.invalidateCompiledValidators;
9
+ exports.invalidateCompiledValidators = require_user_text.invalidateCompiledValidators;
10
10
  exports.tsPlugin = require_plugin.tsPlugin;
11
11
  exports.withLoadCheck = require_plugin.withLoadCheck;
package/dist/index.d.ts CHANGED
@@ -1,5 +1,25 @@
1
1
  import { TAtscriptPlugin, AtscriptDoc } from '@atscript/core';
2
2
 
3
+ /** Options of {@link buildJsonSchema} (and of the `jsonSchemaOptions` plugin option). */
4
+ interface TJsonSchemaOptions {
5
+ /**
6
+ * `additionalProperties: false` on every object schema: the schema rejects keys the type does
7
+ * not declare, as the validator does with its default `unknownProps: 'error'`.
8
+ * *(default: `false`)*
9
+ */
10
+ closed?: boolean;
11
+ /**
12
+ * `@meta.description` → `description` and `@meta.label` → `title`, on the schema of the
13
+ * type or field that carries them. *(default: `true`)*
14
+ */
15
+ annotations?: boolean;
16
+ /**
17
+ * A union of literals (`'a' | 'b'`, also with `null`) → `{ type, enum }` instead of an
18
+ * `anyOf` of `const` schemas. *(default: `true`)*
19
+ */
20
+ enums?: boolean;
21
+ }
22
+
3
23
  interface TTsPluginOptions {
4
24
  /**
5
25
  * JSON Schema support mode:
@@ -11,6 +31,14 @@ interface TTsPluginOptions {
11
31
  * to force build-time embedding regardless of this setting.
12
32
  */
13
33
  jsonSchema?: false | 'lazy' | 'bundle';
34
+ /**
35
+ * Options of the generated `toJsonSchema()` (`'lazy'`, `'bundle'` and `@emit.jsonSchema`
36
+ * alike): the same schema `buildJsonSchema(type, jsonSchemaOptions)` builds at runtime.
37
+ * `closed` (`additionalProperties: false`, default `false`), `annotations` (`description` /
38
+ * `title` from `@meta.description` / `@meta.label`, default `true`), `enums` (a union of
39
+ * literals as `enum`, default `true`).
40
+ */
41
+ jsonSchemaOptions?: TJsonSchemaOptions;
14
42
  /**
15
43
  * Example data support:
16
44
  * - `false` — No support. `toExampleData` is not rendered. *(default)*
@@ -102,4 +130,4 @@ declare function withLoadCheck<T>(fn: () => T): T;
102
130
  declare function importCycle(doc: AtscriptDoc): boolean;
103
131
 
104
132
  export { JS_COMPILED_FORMAT, JS_INTERPRETED_FORMAT, tsPlugin as default, importCycle, invalidateCompiledValidators, tsPlugin, withLoadCheck };
105
- export type { TTsPluginOptions };
133
+ export type { TJsonSchemaOptions, TTsPluginOptions };
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { a as withLoadCheck, i as importCycle, n as JS_INTERPRETED_FORMAT, r as tsPlugin, t as JS_COMPILED_FORMAT } from "./plugin-DhesoKce.mjs";
2
- import { I as invalidateCompiledValidators } from "./unique-name-hg1CyPIs.mjs";
1
+ import { a as withLoadCheck, i as importCycle, n as JS_INTERPRETED_FORMAT, r as tsPlugin, t as JS_COMPILED_FORMAT } from "./plugin-Bx7j-vWf.mjs";
2
+ import { X as invalidateCompiledValidators } from "./user-text-BOf56N4d.mjs";
3
3
 
4
4
  export { JS_COMPILED_FORMAT, JS_INTERPRETED_FORMAT, tsPlugin as default, tsPlugin, importCycle, invalidateCompiledValidators, withLoadCheck };