@atscript/core 0.2.4 → 0.2.6

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 CHANGED
@@ -1485,11 +1485,12 @@ var AnnotationSpec = class {
1485
1485
  */ validateTargetType(def, range, doc) {
1486
1486
  const defType = this.config.defType;
1487
1487
  if (!defType?.length) return;
1488
- if (matchesDefType(def, defType)) return;
1488
+ const literals = this.config.defTypeLiterals;
1489
+ if (matchesDefType(def, defType, literals)) return;
1489
1490
  let got;
1490
1491
  if (isGroup(def) && describeNode(def) === "union") {
1491
1492
  const members = doc ? nonNullishMembers(def, doc) : void 0;
1492
- if (members?.length && members.every((m) => matchesDefType(m, defType))) return;
1493
+ if (members?.length && members.every((m) => matchesDefType(m, defType, literals))) return;
1493
1494
  got = `union (${describeUnionMembers(def, doc)})`;
1494
1495
  } else got = `"${describeNode(def)}"`;
1495
1496
  return [{
@@ -1556,13 +1557,14 @@ function isAnnotationSpec(a) {
1556
1557
  /**
1557
1558
  * Where annotation `spec` holds user-facing text (arguments flagged `userText`): `true` — its
1558
1559
  * value itself (a spec with one argument, not a list: the value is the string; for a `multiple`
1559
- * annotation, each value); a list — those fields of its value object (a spec with an argument
1560
- * list). `undefined`: no user-facing text.
1560
+ * annotation, each value); `'expression'` — likewise, but the value is function source whose string
1561
+ * literals are the texts; a list — those fields of its value object (a spec with an argument
1562
+ * list), an expression field's name ending in `()`. `undefined`: no user-facing text.
1561
1563
  */ function userTextFields(spec) {
1562
1564
  const arg = spec.config.argument;
1563
1565
  if (!arg) return;
1564
- if (!Array.isArray(arg)) return arg.userText ? true : void 0;
1565
- const fields = arg.filter((a) => a.userText).map((a) => a.name);
1566
+ if (!Array.isArray(arg)) return arg.userText || void 0;
1567
+ const fields = arg.filter((a) => a.userText).map((a) => a.userText === "expression" ? `${a.name}()` : a.name);
1566
1568
  return fields.length > 0 ? fields : void 0;
1567
1569
  }
1568
1570
  /**
@@ -1590,8 +1592,18 @@ function resolveAnnotation(name, annotationsTree) {
1590
1592
  /** `null` / `undefined` / `void` primitive. */ function isNullishPrimitive(node) {
1591
1593
  return isPrimitive(node) && (node.type === "null" || node.type === "void");
1592
1594
  }
1593
- /** Whether a resolved node satisfies a `defType` guard (a union as a whole, not its members). */ function matchesDefType(def, defType) {
1594
- return defType.includes(describeNode(def));
1595
+ /**
1596
+ * Whether a resolved node satisfies a `defType` guard (a union as a whole, not its members);
1597
+ * `literals`: a literal of an accepted type does too (see `defTypeLiterals`).
1598
+ */ function matchesDefType(def, defType, literals) {
1599
+ if (defType.includes(describeNode(def))) return true;
1600
+ return !!literals && isConst(def) && defType.includes(literalType(def));
1601
+ }
1602
+ /**
1603
+ * The `defType` vocabulary name of a literal's value (`'a'` → `string`, `1` → `number`; atscript
1604
+ * literals are strings and numbers).
1605
+ */ function literalType(def) {
1606
+ return def.token("identifier")?.type === "number" ? "number" : "string";
1595
1607
  }
1596
1608
  /** The `defType` vocabulary name of a resolved node (`string`, `object`, `union`, `array`, …). */ function describeNode(def) {
1597
1609
  if (isPrimitive(def)) return def.type === "any" ? "unknown" : def.type || "unknown";
@@ -1684,7 +1696,7 @@ function describeUnionMembers(def, doc) {
1684
1696
  }
1685
1697
  if (!node || seen.has(node)) return /* @__PURE__ */ new Set();
1686
1698
  seen.add(node);
1687
- if (node.entity === "const") return new Set([node.token("identifier")?.type === "number" ? "number" : "string"]);
1699
+ if (node.entity === "const") return new Set([literalType(node)]);
1688
1700
  if (isGroup(node) && node.entity !== "tuple" && node.op === "&") {
1689
1701
  let out;
1690
1702
  for (const m of node.unwrap()) {
@@ -9470,7 +9482,8 @@ var AtscriptDoc = class AtscriptDoc {
9470
9482
  return `${out}\n`;
9471
9483
  }
9472
9484
  getDiagMessages() {
9473
- if (!this._allMessages) {
9485
+ if (!this._allMessages || this._messagesAt !== epoch) {
9486
+ this._messagesAt = epoch;
9474
9487
  this._allMessages = [
9475
9488
  ...this.registry.getErrors(),
9476
9489
  ...this.semanticMessages,
@@ -10366,6 +10379,11 @@ var AtscriptDoc = class AtscriptDoc {
10366
10379
  _define_property$3(this, "annotations", void 0);
10367
10380
  _define_property$3(this, "_nextTypeId", void 0);
10368
10381
  _define_property$3(this, "_allMessages", void 0);
10382
+ /**
10383
+ * The documents' epoch {@link _allMessages} were computed at: they derive from other documents
10384
+ * (its imports, its import component), possibly read before their imports were wired, so they
10385
+ * hold only until any document changes.
10386
+ */ _define_property$3(this, "_messagesAt", void 0);
10369
10387
  _define_property$3(this, "_structure", void 0);
10370
10388
  this.id = id;
10371
10389
  this.config = config;
@@ -10395,6 +10413,7 @@ var AtscriptDoc = class AtscriptDoc {
10395
10413
  this.annotations = [];
10396
10414
  this._nextTypeId = 0;
10397
10415
  this._allMessages = void 0;
10416
+ this._messagesAt = -1;
10398
10417
  this.registry = new IdRegistry(Array.from(config.primitives?.keys() || []));
10399
10418
  }
10400
10419
  };
@@ -10975,6 +10994,33 @@ const metaAnnotations = {
10975
10994
  })
10976
10995
  };
10977
10996
 
10997
+ //#endregion
10998
+ //#region packages/core/src/defaults/normalize-annotations.ts
10999
+ 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.";
11000
+ function normalizeSpec(summary, example, validate) {
11001
+ return new AnnotationSpec({
11002
+ description: annotationExample(`${summary} ${NOTE}`, ...example),
11003
+ nodeType: ["prop", "type"],
11004
+ defType: ["string"],
11005
+ defTypeLiterals: true,
11006
+ multiple: false,
11007
+ validate
11008
+ });
11009
+ }
11010
+ const normalizeAnnotations = {
11011
+ trim: normalizeSpec("Removes leading and trailing whitespace from the string.", ["@normalize.trim", "name: string"]),
11012
+ lowercase: normalizeSpec("Converts the string to lower case.", [
11013
+ "@normalize.trim",
11014
+ "@normalize.lowercase",
11015
+ "email: string.email"
11016
+ ]),
11017
+ uppercase: normalizeSpec("Converts the string to upper case.", ["@normalize.uppercase", "countryCode: string"], (mainToken) => mainToken.parentNode?.annotations?.some((a) => a.name === "normalize.lowercase") ? [{
11018
+ message: "@normalize.lowercase has no effect beside @normalize.uppercase (uppercase runs last)",
11019
+ range: mainToken.range,
11020
+ severity: TSeverity.Warning
11021
+ }] : [])
11022
+ };
11023
+
10978
11024
  //#endregion
10979
11025
  //#region packages/core/src/defaults/primitives.ts
10980
11026
  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)$";
@@ -11071,6 +11117,10 @@ const primitives = {
11071
11117
  required: {
11072
11118
  documentation: "Non-empty string that contains at least one non-whitespace character.",
11073
11119
  annotations: { "meta.required": true }
11120
+ },
11121
+ trimmed: {
11122
+ documentation: "String with leading and trailing whitespace removed before validation (`@normalize.trim`).",
11123
+ annotations: { "normalize.trim": true }
11074
11124
  }
11075
11125
  }
11076
11126
  },
@@ -11233,6 +11283,7 @@ function getDefaultAtscriptConfig() {
11233
11283
  annotations: {
11234
11284
  meta: { ...metaAnnotations },
11235
11285
  expect: { ...expectAnnotations },
11286
+ normalize: { ...normalizeAnnotations },
11236
11287
  emit: { ...emitAnnotations },
11237
11288
  annotate: { ...annotateAnnotations }
11238
11289
  }
package/dist/index.d.ts CHANGED
@@ -2107,6 +2107,12 @@ declare class AtscriptDoc {
2107
2107
  registerMessage(token: Token, message: string, severity?: TSeverity, tag?: 'dim' | 'crossed'): void;
2108
2108
  registerMessages(messages?: TMessages): void;
2109
2109
  private _allMessages;
2110
+ /**
2111
+ * The documents' epoch {@link _allMessages} were computed at: they derive from other documents
2112
+ * (its imports, its import component), possibly read before their imports were wired, so they
2113
+ * hold only until any document changes.
2114
+ */
2115
+ private _messagesAt;
2110
2116
  clearMessages(): void;
2111
2117
  getUnusedTokens(): Token[];
2112
2118
  renderDiagMessage(m: TMessages[number], addSourceLinses?: boolean, colors?: boolean): string;
@@ -2667,9 +2673,11 @@ interface TAnnotationArgument {
2667
2673
  * The argument is user-facing text (a label, a description, an error message): i18n tooling
2668
2674
  * and translators read the annotations holding such text through {@link userTextAnnotations}
2669
2675
  * (build time) and `userTextOf` / `userTextKeys` of `@atscript/typescript/utils` (runtime).
2670
- * A `string` argument only.
2676
+ * `'expression'`: the argument is the source of a function the client evaluates (a computed
2677
+ * label, a custom validator returning its message); the texts it writes are the string literals
2678
+ * in that source, which a translator extracts and serves next to it. A `string` argument only.
2671
2679
  */
2672
- userText?: boolean;
2680
+ userText?: boolean | 'expression';
2673
2681
  }
2674
2682
  interface TAnnotationSpecConfig {
2675
2683
  multiple?: boolean;
@@ -2687,6 +2695,11 @@ interface TAnnotationSpecConfig {
2687
2695
  description?: string;
2688
2696
  nodeType?: TNodeEntity[];
2689
2697
  defType?: Array<SemanticPrimitiveNode['type']>;
2698
+ /**
2699
+ * With `defType`: a literal of an accepted type matches too (`'a'` for `string`, `1` for
2700
+ * `number`), alone or as a union member (`'a' | 'b' | null`).
2701
+ */
2702
+ defTypeLiterals?: boolean;
2690
2703
  argument?: TAnnotationArgument[] | TAnnotationArgument;
2691
2704
  validate?: (mainToken: Token, args: Token[], doc: AtscriptDoc) => TMessages | undefined;
2692
2705
  modify?: (mainToken: Token, args: Token[], doc: AtscriptDoc) => void;
@@ -2745,15 +2758,16 @@ declare function forEachAnnotationSpec(tree: TAnnotationsTree, cb: (name: string
2745
2758
  /**
2746
2759
  * Where annotation `spec` holds user-facing text (arguments flagged `userText`): `true` — its
2747
2760
  * value itself (a spec with one argument, not a list: the value is the string; for a `multiple`
2748
- * annotation, each value); a list — those fields of its value object (a spec with an argument
2749
- * list). `undefined`: no user-facing text.
2761
+ * annotation, each value); `'expression'` — likewise, but the value is function source whose string
2762
+ * literals are the texts; a list — those fields of its value object (a spec with an argument
2763
+ * list), an expression field's name ending in `()`. `undefined`: no user-facing text.
2750
2764
  */
2751
- declare function userTextFields(spec: AnnotationSpec): true | string[] | undefined;
2765
+ declare function userTextFields(spec: AnnotationSpec): true | 'expression' | string[] | undefined;
2752
2766
  /**
2753
2767
  * Every annotation of `tree` (core and plugins) holding user-facing text, by full name (see
2754
2768
  * {@link userTextFields}): what i18n tooling extracts and a translator translates.
2755
2769
  */
2756
- declare function userTextAnnotations(tree: TAnnotationsTree): Map<string, true | string[]>;
2770
+ declare function userTextAnnotations(tree: TAnnotationsTree): Map<string, true | 'expression' | string[]>;
2757
2771
  declare function resolveAnnotation(name: string, annotationsTree?: TAnnotationsTree): AnnotationSpec | undefined;
2758
2772
  /**
2759
2773
  * Resolved members of a union other than `null` / `undefined`, or `undefined`
package/dist/index.mjs CHANGED
@@ -1454,11 +1454,12 @@ var AnnotationSpec = class {
1454
1454
  */ validateTargetType(def, range, doc) {
1455
1455
  const defType = this.config.defType;
1456
1456
  if (!defType?.length) return;
1457
- if (matchesDefType(def, defType)) return;
1457
+ const literals = this.config.defTypeLiterals;
1458
+ if (matchesDefType(def, defType, literals)) return;
1458
1459
  let got;
1459
1460
  if (isGroup(def) && describeNode(def) === "union") {
1460
1461
  const members = doc ? nonNullishMembers(def, doc) : void 0;
1461
- if (members?.length && members.every((m) => matchesDefType(m, defType))) return;
1462
+ if (members?.length && members.every((m) => matchesDefType(m, defType, literals))) return;
1462
1463
  got = `union (${describeUnionMembers(def, doc)})`;
1463
1464
  } else got = `"${describeNode(def)}"`;
1464
1465
  return [{
@@ -1525,13 +1526,14 @@ function isAnnotationSpec(a) {
1525
1526
  /**
1526
1527
  * Where annotation `spec` holds user-facing text (arguments flagged `userText`): `true` — its
1527
1528
  * value itself (a spec with one argument, not a list: the value is the string; for a `multiple`
1528
- * annotation, each value); a list — those fields of its value object (a spec with an argument
1529
- * list). `undefined`: no user-facing text.
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.
1530
1532
  */ function userTextFields(spec) {
1531
1533
  const arg = spec.config.argument;
1532
1534
  if (!arg) return;
1533
- if (!Array.isArray(arg)) return arg.userText ? true : void 0;
1534
- const fields = arg.filter((a) => a.userText).map((a) => a.name);
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);
1535
1537
  return fields.length > 0 ? fields : void 0;
1536
1538
  }
1537
1539
  /**
@@ -1559,8 +1561,18 @@ function resolveAnnotation(name, annotationsTree) {
1559
1561
  /** `null` / `undefined` / `void` primitive. */ function isNullishPrimitive(node) {
1560
1562
  return isPrimitive(node) && (node.type === "null" || node.type === "void");
1561
1563
  }
1562
- /** Whether a resolved node satisfies a `defType` guard (a union as a whole, not its members). */ function matchesDefType(def, defType) {
1563
- return defType.includes(describeNode(def));
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";
1564
1576
  }
1565
1577
  /** The `defType` vocabulary name of a resolved node (`string`, `object`, `union`, `array`, …). */ function describeNode(def) {
1566
1578
  if (isPrimitive(def)) return def.type === "any" ? "unknown" : def.type || "unknown";
@@ -1653,7 +1665,7 @@ function describeUnionMembers(def, doc) {
1653
1665
  }
1654
1666
  if (!node || seen.has(node)) return /* @__PURE__ */ new Set();
1655
1667
  seen.add(node);
1656
- if (node.entity === "const") return new Set([node.token("identifier")?.type === "number" ? "number" : "string"]);
1668
+ if (node.entity === "const") return new Set([literalType(node)]);
1657
1669
  if (isGroup(node) && node.entity !== "tuple" && node.op === "&") {
1658
1670
  let out;
1659
1671
  for (const m of node.unwrap()) {
@@ -9439,7 +9451,8 @@ var AtscriptDoc = class AtscriptDoc {
9439
9451
  return `${out}\n`;
9440
9452
  }
9441
9453
  getDiagMessages() {
9442
- if (!this._allMessages) {
9454
+ if (!this._allMessages || this._messagesAt !== epoch) {
9455
+ this._messagesAt = epoch;
9443
9456
  this._allMessages = [
9444
9457
  ...this.registry.getErrors(),
9445
9458
  ...this.semanticMessages,
@@ -10335,6 +10348,11 @@ var AtscriptDoc = class AtscriptDoc {
10335
10348
  _define_property$3(this, "annotations", void 0);
10336
10349
  _define_property$3(this, "_nextTypeId", void 0);
10337
10350
  _define_property$3(this, "_allMessages", void 0);
10351
+ /**
10352
+ * The documents' epoch {@link _allMessages} were computed at: they derive from other documents
10353
+ * (its imports, its import component), possibly read before their imports were wired, so they
10354
+ * hold only until any document changes.
10355
+ */ _define_property$3(this, "_messagesAt", void 0);
10338
10356
  _define_property$3(this, "_structure", void 0);
10339
10357
  this.id = id;
10340
10358
  this.config = config;
@@ -10364,6 +10382,7 @@ var AtscriptDoc = class AtscriptDoc {
10364
10382
  this.annotations = [];
10365
10383
  this._nextTypeId = 0;
10366
10384
  this._allMessages = void 0;
10385
+ this._messagesAt = -1;
10367
10386
  this.registry = new IdRegistry(Array.from(config.primitives?.keys() || []));
10368
10387
  }
10369
10388
  };
@@ -10944,6 +10963,33 @@ const metaAnnotations = {
10944
10963
  })
10945
10964
  };
10946
10965
 
10966
+ //#endregion
10967
+ //#region packages/core/src/defaults/normalize-annotations.ts
10968
+ 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.";
10969
+ function normalizeSpec(summary, example, validate) {
10970
+ return new AnnotationSpec({
10971
+ description: annotationExample(`${summary} ${NOTE}`, ...example),
10972
+ nodeType: ["prop", "type"],
10973
+ defType: ["string"],
10974
+ defTypeLiterals: true,
10975
+ multiple: false,
10976
+ validate
10977
+ });
10978
+ }
10979
+ const normalizeAnnotations = {
10980
+ trim: normalizeSpec("Removes leading and trailing whitespace from the string.", ["@normalize.trim", "name: string"]),
10981
+ lowercase: normalizeSpec("Converts the string to lower case.", [
10982
+ "@normalize.trim",
10983
+ "@normalize.lowercase",
10984
+ "email: string.email"
10985
+ ]),
10986
+ uppercase: normalizeSpec("Converts the string to upper case.", ["@normalize.uppercase", "countryCode: string"], (mainToken) => mainToken.parentNode?.annotations?.some((a) => a.name === "normalize.lowercase") ? [{
10987
+ message: "@normalize.lowercase has no effect beside @normalize.uppercase (uppercase runs last)",
10988
+ range: mainToken.range,
10989
+ severity: TSeverity.Warning
10990
+ }] : [])
10991
+ };
10992
+
10947
10993
  //#endregion
10948
10994
  //#region packages/core/src/defaults/primitives.ts
10949
10995
  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)$";
@@ -11040,6 +11086,10 @@ const primitives = {
11040
11086
  required: {
11041
11087
  documentation: "Non-empty string that contains at least one non-whitespace character.",
11042
11088
  annotations: { "meta.required": true }
11089
+ },
11090
+ trimmed: {
11091
+ documentation: "String with leading and trailing whitespace removed before validation (`@normalize.trim`).",
11092
+ annotations: { "normalize.trim": true }
11043
11093
  }
11044
11094
  }
11045
11095
  },
@@ -11202,6 +11252,7 @@ function getDefaultAtscriptConfig() {
11202
11252
  annotations: {
11203
11253
  meta: { ...metaAnnotations },
11204
11254
  expect: { ...expectAnnotations },
11255
+ normalize: { ...normalizeAnnotations },
11205
11256
  emit: { ...emitAnnotations },
11206
11257
  annotate: { ...annotateAnnotations }
11207
11258
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/core",
3
- "version": "0.2.4",
3
+ "version": "0.2.6",
4
4
  "description": "Core library for Atscript parsing and file generation.",
5
5
  "keywords": [
6
6
  "annotations",