@atscript/core 0.1.102 → 0.1.104

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
@@ -549,17 +549,20 @@ function toAnnotationTokens(name, value, spec) {
549
549
  if (typeof value === "boolean") return {
550
550
  name,
551
551
  token: dummyToken,
552
- args: []
552
+ args: [],
553
+ intrinsic: true
553
554
  };
554
555
  if (typeof value === "string") return {
555
556
  name,
556
557
  token: dummyToken,
557
- args: [text$1(value)]
558
+ args: [text$1(value)],
559
+ intrinsic: true
558
560
  };
559
561
  if (typeof value === "number") return {
560
562
  name,
561
563
  token: dummyToken,
562
- args: [num(value)]
564
+ args: [num(value)],
565
+ intrinsic: true
563
566
  };
564
567
  const raw = (spec?.arguments.map((a) => a.name) ?? Object.keys(value)).map((argName) => {
565
568
  const v = value[argName];
@@ -570,7 +573,8 @@ function toAnnotationTokens(name, value, spec) {
570
573
  return {
571
574
  name,
572
575
  token: dummyToken,
573
- args: raw.map((t) => t ?? text$1(""))
576
+ args: raw.map((t) => t ?? text$1("")),
577
+ intrinsic: true
574
578
  };
575
579
  }
576
580
  const dummyToken = new Token({
@@ -1149,8 +1153,13 @@ var AnnotationSpec = class {
1149
1153
  const idToken = isRef(parentNode) ? parentNode.token("identifier") : void 0;
1150
1154
  if (!(!!idToken && !!doc.annotateBlockAt(idToken.range.start.line, idToken.range.start.character))) {
1151
1155
  let def = parentNode.getDefinition();
1152
- if (isRef(def)) def = doc.unwindType(def.id, def.chain)?.def || def;
1153
- messages.push(...this.validateTargetType(def, mainToken.range) || []);
1156
+ let defDoc = doc;
1157
+ if (isRef(def)) {
1158
+ const unwound = doc.unwindType(def.id, def.chain);
1159
+ def = unwound?.def || def;
1160
+ defDoc = unwound?.doc || doc;
1161
+ }
1162
+ messages.push(...this.validateTargetType(def, mainToken.range, defDoc) || []);
1154
1163
  }
1155
1164
  }
1156
1165
  if (this.config.validate) messages.push(...this.config.validate(mainToken, args, doc) || []);
@@ -1163,13 +1172,23 @@ var AnnotationSpec = class {
1163
1172
  * guard is configured. Shared by the parse-time check (for inline props) and
1164
1173
  * the deferred annotate-entry check in `AtscriptDoc.getDiagMessages`, where
1165
1174
  * imported target types finally resolve.
1166
- */ validateTargetType(def, range) {
1167
- if (!this.config.defType?.length) return;
1168
- let defEntity = def?.entity || "unknown";
1169
- if (isInterface(def) || isStructure(def)) defEntity = "object";
1170
- else if (isGroup(def) && def.entity !== "tuple") defEntity = def.op === "&" ? "intersection" : "union";
1171
- if (!isPrimitive(def) && !this.config.defType.includes(defEntity) || isPrimitive(def) && !this.config.defType.includes(def.type)) return [{
1172
- message: `Expected type is (${this.config.defType.join(" | ")}), got "${isPrimitive(def) ? def.type : def?.entity || "unknown"}"`,
1175
+ *
1176
+ * A union also matches when every member other than `null` / `undefined`
1177
+ * matches (`number | null`, `string[] | null`, an alias of such a union).
1178
+ * Union members are refs, so `doc` (the document the union is declared in) is
1179
+ * needed to resolve them; without it a union never matches.
1180
+ */ validateTargetType(def, range, doc) {
1181
+ const defType = this.config.defType;
1182
+ if (!defType?.length) return;
1183
+ if (matchesDefType(def, defType)) return;
1184
+ let got;
1185
+ if (isGroup(def) && def.entity !== "tuple" && def.op !== "&") {
1186
+ const members = doc ? nonNullishMembers(def, doc) : void 0;
1187
+ if (members?.length && members.every((m) => matchesDefType(m, defType))) return;
1188
+ got = `union (${describeUnionMembers(def, doc)})`;
1189
+ } else got = `"${describeNode(def)}"`;
1190
+ return [{
1191
+ message: `Expected type is (${defType.join(" | ")}), got ${got}`,
1173
1192
  severity: 1,
1174
1193
  range
1175
1194
  }];
@@ -1216,6 +1235,63 @@ function resolveAnnotation(name, annotationsTree) {
1216
1235
  if (isAnnotationSpec(current)) return current;
1217
1236
  if (current && !isAnnotationSpec(current) && current.$self) return current.$self;
1218
1237
  }
1238
+ /** `null` / `undefined` / `void` primitive. */ function isNullishPrimitive(node) {
1239
+ return isPrimitive(node) && (node.type === "null" || node.type === "void");
1240
+ }
1241
+ /** Whether a resolved node satisfies a `defType` guard (a union as a whole, not its members). */ function matchesDefType(def, defType) {
1242
+ return defType.includes(describeNode(def));
1243
+ }
1244
+ /** The `defType` vocabulary name of a resolved node (`string`, `object`, `union`, `array`, …). */ function describeNode(def) {
1245
+ if (isPrimitive(def)) return def.type || "unknown";
1246
+ if (isInterface(def) || isStructure(def)) return "object";
1247
+ if (isGroup(def) && def.entity !== "tuple") return def.op === "&" ? "intersection" : "union";
1248
+ return def?.entity || "unknown";
1249
+ }
1250
+ /** Walks a `|` union (flattening nested unions and union aliases), resolving member refs. */ function walkUnionMembers(def, doc, cb, seen = /* @__PURE__ */ new Set()) {
1251
+ if (seen.has(def)) return;
1252
+ seen.add(def);
1253
+ for (const item of def.unwrap()) {
1254
+ let member = item;
1255
+ let memberDoc = doc;
1256
+ if (isRef(member)) {
1257
+ const unwound = doc?.unwindType(member.id, member.chain);
1258
+ member = unwound?.def;
1259
+ memberDoc = unwound?.doc || doc;
1260
+ }
1261
+ if (isGroup(member) && member.entity !== "tuple" && member.op !== "&") walkUnionMembers(member, memberDoc, cb, seen);
1262
+ else cb(member);
1263
+ }
1264
+ }
1265
+ function describeUnionMembers(def, doc) {
1266
+ const names = [];
1267
+ walkUnionMembers(def, doc, (m) => {
1268
+ const name = describeNode(m);
1269
+ if (!names.includes(name)) names.push(name);
1270
+ });
1271
+ return names.join(" | ");
1272
+ }
1273
+ /**
1274
+ * Resolved members of a union other than `null` / `undefined`, or `undefined`
1275
+ * when `def` is not a union. Nested unions and union aliases are flattened and
1276
+ * member refs are resolved through `doc` (the document `def` is declared in);
1277
+ * members that can't be resolved are left out (they are reported as unknown
1278
+ * identifiers elsewhere).
1279
+ *
1280
+ * Use it in an annotation's `validate` hook to accept nullable targets, e.g.
1281
+ * treat `string | null` like `string`:
1282
+ *
1283
+ * ```ts
1284
+ * const members = nonNullishMembers(def, doc)
1285
+ * const ok = members ? members.length > 0 && members.every(isWanted) : isWanted(def)
1286
+ * ```
1287
+ */ function nonNullishMembers(def, doc) {
1288
+ if (!isGroup(def) || def.entity === "tuple" || def.op === "&") return;
1289
+ const members = [];
1290
+ walkUnionMembers(def, doc, (m) => {
1291
+ if (m && !isNullishPrimitive(m)) members.push(m);
1292
+ });
1293
+ return members;
1294
+ }
1219
1295
 
1220
1296
  //#endregion
1221
1297
  //#region packages/core/src/config/define-config.ts
@@ -4141,37 +4217,58 @@ var AtscriptDoc = class AtscriptDoc {
4141
4217
  const token = this.tokensIndex.at(line, character);
4142
4218
  if (token) return this.usageListFor(token, character);
4143
4219
  }
4144
- evalAnnotationsForNode(givenNode) {
4145
- let right = givenNode.annotations;
4220
+ evalAnnotationsForNode(givenNode, own = givenNode.annotations) {
4221
+ let right = own;
4146
4222
  let def = givenNode.getDefinition();
4147
4223
  if (def) {
4148
4224
  const refDef = isRef(def) ? def : void 0;
4225
+ let viaProp = false;
4149
4226
  if (refDef) {
4150
4227
  const chainNodes = [];
4151
4228
  const unwound = this.unwindType(refDef.token("identifier").text, refDef.chain, (intermediate) => {
4229
+ if (isProp(intermediate) && intermediate !== givenNode) viaProp = true;
4152
4230
  if (intermediate?.annotations?.length) chainNodes.push(intermediate);
4153
4231
  });
4154
- if (unwound?.node && unwound.node !== givenNode && unwound.node.annotations?.length && !chainNodes.includes(unwound.node)) chainNodes.unshift(unwound.node);
4155
- for (const chainNode of chainNodes) right = this.mergeNodesAnnotations(this.filterPassedWhenReferred(chainNode.annotations), right);
4232
+ if (unwound?.node && unwound.node !== givenNode) {
4233
+ viaProp || (viaProp = isProp(unwound.node));
4234
+ if (unwound.node.annotations?.length && !chainNodes.includes(unwound.node)) chainNodes.unshift(unwound.node);
4235
+ }
4236
+ for (const chainNode of chainNodes) {
4237
+ if (chainNode === unwound?.def) continue;
4238
+ right = this.mergeNodesAnnotations(this.filterPassedWhenReferred(chainNode.annotations, viaProp), right);
4239
+ }
4156
4240
  def = unwound?.def || def;
4157
4241
  }
4158
4242
  if (def) {
4159
4243
  const merged = this.mergeIntersection(def);
4160
- right = this.mergeNodesAnnotations(refDef ? this.filterPassedWhenReferred(merged.annotations) : merged.annotations, right);
4244
+ right = this.mergeNodesAnnotations(refDef ? this.filterPassedWhenReferred(merged.annotations, viaProp) : merged.annotations, right);
4161
4245
  }
4162
4246
  }
4163
4247
  return right;
4164
4248
  }
4165
4249
  /**
4250
+ * The annotations a reference to `node` (`field: Alias`) inherits: its evaluated
4251
+ * set without the `passedWhenReferred: false` ones. The node's own are filtered
4252
+ * before the merge, so a dropped one cannot shadow a primitive's intrinsic
4253
+ * annotation of the same name (`@meta.required 'msg'` on `type N = string.required`).
4254
+ */ evalReferredAnnotations(node) {
4255
+ return this.filterPassedWhenReferred(this.evalAnnotationsForNode(node, this.filterPassedWhenReferred(node.annotations)));
4256
+ }
4257
+ /**
4166
4258
  * Drops annotations whose spec declares `passedWhenReferred: false` — used
4167
4259
  * when folding annotations across a ref boundary. Annotations without a
4168
- * resolvable spec pass through (default is to inherit). Returns the input
4260
+ * resolvable spec pass through (default is to inherit), and so do a
4261
+ * primitive's intrinsic ones (`number.timestamp.created` → `@db.default.now`)
4262
+ * unless the boundary is a reference to a prop (`viaProp`). Returns the input
4169
4263
  * array unchanged when nothing is dropped.
4170
- */ filterPassedWhenReferred(annotations) {
4264
+ */ filterPassedWhenReferred(annotations, viaProp = false) {
4171
4265
  if (!annotations?.length) return annotations;
4172
4266
  let filtered;
4173
- for (let i = 0; i < annotations.length; i++) if (this.resolveAnnotation(annotations[i].name)?.config.passedWhenReferred === false) filtered ?? (filtered = annotations.slice(0, i));
4174
- else filtered?.push(annotations[i]);
4267
+ for (let i = 0; i < annotations.length; i++) {
4268
+ const a = annotations[i];
4269
+ if ((viaProp || !a.intrinsic) && this.resolveAnnotation(a.name)?.config.passedWhenReferred === false) filtered ?? (filtered = annotations.slice(0, i));
4270
+ else filtered?.push(a);
4271
+ }
4175
4272
  return filtered ?? annotations;
4176
4273
  }
4177
4274
  /**
@@ -4783,7 +4880,7 @@ var AtscriptDoc = class AtscriptDoc {
4783
4880
  }
4784
4881
  }
4785
4882
  if (resolvedType && isRef(t.parentNode) && t.parentNode.annotations) for (const a of t.parentNode.annotations) {
4786
- const msgs = this.resolveAnnotation(a.token.text.slice(1))?.validateTargetType(resolvedType, a.token.range);
4883
+ const msgs = this.resolveAnnotation(a.token.text.slice(1))?.validateTargetType(resolvedType, a.token.range, unwound?.doc || this);
4787
4884
  if (msgs) this._allMessages.push(...msgs);
4788
4885
  }
4789
4886
  continue;
@@ -5079,9 +5176,10 @@ const emitAnnotations = { jsonSchema: new AnnotationSpec({
5079
5176
 
5080
5177
  //#endregion
5081
5178
  //#region packages/core/src/defaults/expect-annotations.ts
5179
+ const NULLABLE_NOTE = "Also allowed on a nullable field (`T | null`, `T | undefined`): `null` passes, any other value must satisfy the constraint.";
5082
5180
  const expectAnnotations = {
5083
5181
  minLength: new AnnotationSpec({
5084
- description: "Validates that a string or array has a minimum length.\n\n**Example:**```atscript@expect.minLength 5name: string```",
5182
+ description: `Validates that a string or array has a minimum length. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.minLength 5name: string\`\`\``,
5085
5183
  defType: ["array", "string"],
5086
5184
  argument: [{
5087
5185
  name: "length",
@@ -5095,7 +5193,7 @@ const expectAnnotations = {
5095
5193
  }]
5096
5194
  }),
5097
5195
  maxLength: new AnnotationSpec({
5098
- description: "Validates that a string or array has a maximum length.\n\n**Example:**```atscript@expect.maxLength 5name: string```",
5196
+ description: `Validates that a string or array has a maximum length. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.maxLength 5name: string\`\`\``,
5099
5197
  defType: ["array", "string"],
5100
5198
  argument: [{
5101
5199
  name: "length",
@@ -5109,7 +5207,7 @@ const expectAnnotations = {
5109
5207
  }]
5110
5208
  }),
5111
5209
  min: new AnnotationSpec({
5112
- description: "Validates that a number is greater than or equal to a minimum value.\n\n**Example:**```atscript@expect.min 18age: number```",
5210
+ description: `Validates that a number is greater than or equal to a minimum value. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.min 18age: number\`\`\``,
5113
5211
  defType: ["number"],
5114
5212
  argument: [{
5115
5213
  name: "minValue",
@@ -5123,7 +5221,7 @@ const expectAnnotations = {
5123
5221
  }]
5124
5222
  }),
5125
5223
  max: new AnnotationSpec({
5126
- description: "Validates that a number is less than or equal to a maximum value.\n\n**Example:**```atscript@expect.max 10count: number```",
5224
+ description: `Validates that a number is less than or equal to a maximum value. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.max 10count: number\`\`\``,
5127
5225
  defType: ["number"],
5128
5226
  argument: [{
5129
5227
  name: "maxValue",
@@ -5137,11 +5235,11 @@ const expectAnnotations = {
5137
5235
  }]
5138
5236
  }),
5139
5237
  int: new AnnotationSpec({
5140
- description: "Validates that a number is an integer (no decimal places).\n\n**Example:**```atscript@expect.intage: number```",
5238
+ description: `Validates that a number is an integer (no decimal places). ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.intage: number\`\`\``,
5141
5239
  defType: ["number"]
5142
5240
  }),
5143
5241
  pattern: new AnnotationSpec({
5144
- description: "Validates that a string matches a specific pattern.\n\n**Example:**```atscript@expect.pattern \"[a-z]+\", \"u\"name: string```",
5242
+ description: `Validates that a string matches a specific pattern. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.pattern "[a-z]+", "u"name: string\`\`\``,
5145
5243
  defType: ["string"],
5146
5244
  multiple: true,
5147
5245
  mergeStrategy: "append",
@@ -5245,7 +5343,7 @@ const expectAnnotations = {
5245
5343
  }),
5246
5344
  array: {
5247
5345
  uniqueItems: new AnnotationSpec({
5248
- description: "Enforces **unique items** in an array field.\n\nWorks with both **primitive arrays** and **object arrays**:\n\n- **Primitive arrays** (`string[]`, `number[]`) — duplicates are detected by deep equality.\n- **Object arrays** — if the element type defines `@expect.array.key` properties, uniqueness is checked by those keys only; otherwise by deep equality of the whole object.\n\nUnlike `@expect.array.key` (which only *identifies* key fields for lookup/patch operations), `@expect.array.uniqueItems` actively *enforces* uniqueness during validation.\n\n**Examples:**\n```atscript\n// Primitive array — no duplicates allowed\n@expect.array.uniqueItems\ntags: string[]\n\n// Object array with keys — unique by key fields\n@expect.array.uniqueItems\nitems: {\n @expect.array.key\n id: string\n value: number\n}[]\n```\n",
5346
+ description: "Enforces **unique items** in an array field.\n\nWorks with both **primitive arrays** and **object arrays**:\n\n- **Primitive arrays** (`string[]`, `number[]`) — duplicates are detected by deep equality.\n- **Object arrays** — if the element type defines `@expect.array.key` properties, uniqueness is checked by those keys only; otherwise by deep equality of the whole object.\n\nUnlike `@expect.array.key` (which only *identifies* key fields for lookup/patch operations), `@expect.array.uniqueItems` actively *enforces* uniqueness during validation.\n\nAlso allowed on a nullable array (`T[] | null`); `null` passes.\n\n**Examples:**\n```atscript\n// Primitive array — no duplicates allowed\n@expect.array.uniqueItems\ntags: string[]\n\n// Object array with keys — unique by key fields\n@expect.array.uniqueItems\nitems: {\n @expect.array.key\n id: string\n value: number\n}[]\n```\n",
5249
5347
  nodeType: ["prop"],
5250
5348
  multiple: false,
5251
5349
  argument: [{
@@ -5259,12 +5357,15 @@ const expectAnnotations = {
5259
5357
  const errors = [];
5260
5358
  const definition = field.getDefinition();
5261
5359
  if (!definition) return errors;
5262
- let wrongType = false;
5360
+ let def = definition;
5361
+ let defDoc = doc;
5263
5362
  if (isRef(definition)) {
5264
- const def = doc.unwindType(definition.id, definition.chain)?.def;
5265
- if (!isArray(def)) wrongType = true;
5266
- } else if (!isArray(definition)) wrongType = true;
5267
- if (wrongType) errors.push({
5363
+ const unwound = doc.unwindType(definition.id, definition.chain);
5364
+ def = unwound?.def;
5365
+ defDoc = unwound?.doc || doc;
5366
+ }
5367
+ const members = nonNullishMembers(def, defDoc);
5368
+ if (!(members ? members.length > 0 && members.every((m) => isArray(m)) : isArray(def))) errors.push({
5268
5369
  message: `@expect.array.uniqueItems requires an array field`,
5269
5370
  severity: 1,
5270
5371
  range: token.range
@@ -5353,7 +5454,7 @@ const metaAnnotations = {
5353
5454
  passedWhenReferred: false
5354
5455
  }),
5355
5456
  required: new AnnotationSpec({
5356
- description: "Marks a field as required for form validation. For strings: must contain at least one non-whitespace character. For booleans: must be true.\n\n**Example:**```atscript@meta.requiredname: string\n@meta.required \"You must accept the terms\"agreed: boolean```",
5457
+ description: "Marks a field as required for form validation. For strings: must contain at least one non-whitespace character. For booleans: must be true. On an optional field (`name?: string`) the field may be omitted, but `null` is rejected. On a nullable field (`string | null`) `null` is accepted and a string must not be empty.\n\n**Example:**```atscript@meta.requiredname: string\n@meta.required \"You must accept the terms\"agreed: boolean```",
5357
5458
  defType: ["string", "boolean"],
5358
5459
  argument: [{
5359
5460
  name: "message",
@@ -5585,7 +5686,7 @@ const primitives = {
5585
5686
  annotations: { "db.default.now": true }
5586
5687
  },
5587
5688
  updated: {
5588
- documentation: "Timestamp auto-updated on every write. DB adapters read the \"updated\" tag.",
5689
+ documentation: "Last-modified timestamp (tag \"updated\"). A marker only: it carries no default and is not set on write.",
5589
5690
  tags: ["updated"]
5590
5691
  }
5591
5692
  }
@@ -6499,6 +6600,7 @@ exports.isTuple = isTuple;
6499
6600
  exports.isType = isType;
6500
6601
  exports.loadConfig = loadConfig;
6501
6602
  exports.loadTsConfig = loadTsConfig;
6603
+ exports.nonNullishMembers = nonNullishMembers;
6502
6604
  exports.parseBareSpecifier = parseBareSpecifier;
6503
6605
  exports.resolveAnnotation = resolveAnnotation;
6504
6606
  exports.resolveAtscriptFromPath = resolveAtscriptFromPath;
package/dist/index.d.ts CHANGED
@@ -291,6 +291,13 @@ interface TAnnotationTokens {
291
291
  name: string;
292
292
  token: Token;
293
293
  args: Token[];
294
+ /**
295
+ * Built into a primitive extension (`number.timestamp.created` → `@db.default.now`,
296
+ * `string.required` → `@meta.required`). Part of the type itself, so it follows
297
+ * type references and aliases even when its spec sets `passedWhenReferred: false`;
298
+ * only a reference to a prop (`User.createdAt`) drops such an annotation.
299
+ */
300
+ intrinsic?: true;
294
301
  }
295
302
  type TPrimitiveAnnotationArg = string | number | boolean;
296
303
  type TPrimitiveAnnotationArgs = Record<string, TPrimitiveAnnotationArg>;
@@ -595,14 +602,23 @@ declare class AtscriptDoc {
595
602
  range: Token["range"];
596
603
  token: Token;
597
604
  }[] | undefined;
598
- evalAnnotationsForNode(givenNode: SemanticNode): TAnnotationTokens[] | undefined;
605
+ evalAnnotationsForNode(givenNode: SemanticNode, own?: TAnnotationTokens[] | undefined): TAnnotationTokens[] | undefined;
606
+ /**
607
+ * The annotations a reference to `node` (`field: Alias`) inherits: its evaluated
608
+ * set without the `passedWhenReferred: false` ones. The node's own are filtered
609
+ * before the merge, so a dropped one cannot shadow a primitive's intrinsic
610
+ * annotation of the same name (`@meta.required 'msg'` on `type N = string.required`).
611
+ */
612
+ evalReferredAnnotations(node: SemanticNode): TAnnotationTokens[] | undefined;
599
613
  /**
600
614
  * Drops annotations whose spec declares `passedWhenReferred: false` — used
601
615
  * when folding annotations across a ref boundary. Annotations without a
602
- * resolvable spec pass through (default is to inherit). Returns the input
616
+ * resolvable spec pass through (default is to inherit), and so do a
617
+ * primitive's intrinsic ones (`number.timestamp.created` → `@db.default.now`)
618
+ * unless the boundary is a reference to a prop (`viaProp`). Returns the input
603
619
  * array unchanged when nothing is dropped.
604
620
  */
605
- filterPassedWhenReferred(annotations?: TAnnotationTokens[]): TAnnotationTokens[] | undefined;
621
+ filterPassedWhenReferred(annotations?: TAnnotationTokens[], viaProp?: boolean): TAnnotationTokens[] | undefined;
606
622
  /**
607
623
  * If the position falls inside an `annotate` block, returns that block's node
608
624
  * (whose `targetName` is the annotated interface). Entry refs within the block
@@ -1143,13 +1159,34 @@ declare class AnnotationSpec {
1143
1159
  * guard is configured. Shared by the parse-time check (for inline props) and
1144
1160
  * the deferred annotate-entry check in `AtscriptDoc.getDiagMessages`, where
1145
1161
  * imported target types finally resolve.
1162
+ *
1163
+ * A union also matches when every member other than `null` / `undefined`
1164
+ * matches (`number | null`, `string[] | null`, an alias of such a union).
1165
+ * Union members are refs, so `doc` (the document the union is declared in) is
1166
+ * needed to resolve them; without it a union never matches.
1146
1167
  */
1147
- validateTargetType(def: SemanticNode | undefined, range: Token['range']): TMessages | undefined;
1168
+ validateTargetType(def: SemanticNode | undefined, range: Token['range'], doc?: AtscriptDoc): TMessages | undefined;
1148
1169
  renderDocs(index: number | string): string | undefined;
1149
1170
  protected getDefaultValueForType(name: string, type: TAnnotationArgument['type']): string;
1150
1171
  }
1151
1172
  declare function isAnnotationSpec(a?: TAnnotationsTree | AnnotationSpec): a is AnnotationSpec;
1152
1173
  declare function resolveAnnotation(name: string, annotationsTree?: TAnnotationsTree): AnnotationSpec | undefined;
1174
+ /**
1175
+ * Resolved members of a union other than `null` / `undefined`, or `undefined`
1176
+ * when `def` is not a union. Nested unions and union aliases are flattened and
1177
+ * member refs are resolved through `doc` (the document `def` is declared in);
1178
+ * members that can't be resolved are left out (they are reported as unknown
1179
+ * identifiers elsewhere).
1180
+ *
1181
+ * Use it in an annotation's `validate` hook to accept nullable targets, e.g.
1182
+ * treat `string | null` like `string`:
1183
+ *
1184
+ * ```ts
1185
+ * const members = nonNullishMembers(def, doc)
1186
+ * const ok = members ? members.length > 0 && members.every(isWanted) : isWanted(def)
1187
+ * ```
1188
+ */
1189
+ declare function nonNullishMembers(def: SemanticNode | undefined, doc: AtscriptDoc): SemanticNode[] | undefined;
1153
1190
 
1154
1191
  declare function resolveAtscriptFromPath(from: string, id: string): string;
1155
1192
  declare function fileUriToPath(id: string): string;
@@ -1371,5 +1408,5 @@ declare const BACKTICK_ARG_VOCABULARY: {
1371
1408
  readonly orderDirections: readonly ["asc", "desc"];
1372
1409
  };
1373
1410
 
1374
- export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BACKTICK_ARG_VOCABULARY, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, PluginManager, 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, Token, analyzeQueryCursorContext, build, clearResolveBareCache, createAtscriptPlugin, defineConfig, fileUriToPath, flattenInterfaceNode, getDeclaredValue, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, getSiblingAnnotation, getValueCandidates, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isBacktickArgType, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, parseBareSpecifier, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveQueryFieldRef };
1411
+ export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BACKTICK_ARG_VOCABULARY, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, PluginManager, 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, Token, analyzeQueryCursorContext, build, clearResolveBareCache, createAtscriptPlugin, defineConfig, fileUriToPath, flattenInterfaceNode, getDeclaredValue, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, getSiblingAnnotation, getValueCandidates, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isBacktickArgType, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, nonNullishMembers, parseBareSpecifier, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveQueryFieldRef };
1375
1412
  export type { SemanticExprItemNode, SemanticQueryExprNode, TAnnotationArgument, TAnnotationSpecConfig, TAnnotationTokens, TAnnotationsTree, TAtscriptConfig, TAtscriptConfigInput, TAtscriptConfigOutput, TAtscriptDocConfig, TAtscriptPlugin, TAtscriptRenderFormat, TBacktickArgKind, TDbConfig, TDbConfigDeclarative, TExprBinaryOperator, TFlatFieldDescriptor, TFlattenOptions, TMessages, TNodeEntity, TOrderItem, TOutput, TOutputWithSource, TPluginManagers, TPluginOutput, TPrimitiveAnnotationArg, TPrimitiveAnnotationArgs, TPrimitiveAnnotationValue, TPrimitiveBaseConfig, TPrimitiveConfig, TPrimitiveTypeArray, TPrimitiveTypeComplex, TPrimitiveTypeDef, TPrimitiveTypeFinal, TPrimitiveTypeFinalOptional, TPrimitiveTypeObject, TQueryCursorContext, TQueryLogicalOperator, TQueryOperator, TQueryScope, TSemanticToken, TValueCandidate };
package/dist/index.mjs CHANGED
@@ -518,17 +518,20 @@ function toAnnotationTokens(name, value, spec) {
518
518
  if (typeof value === "boolean") return {
519
519
  name,
520
520
  token: dummyToken,
521
- args: []
521
+ args: [],
522
+ intrinsic: true
522
523
  };
523
524
  if (typeof value === "string") return {
524
525
  name,
525
526
  token: dummyToken,
526
- args: [text$1(value)]
527
+ args: [text$1(value)],
528
+ intrinsic: true
527
529
  };
528
530
  if (typeof value === "number") return {
529
531
  name,
530
532
  token: dummyToken,
531
- args: [num(value)]
533
+ args: [num(value)],
534
+ intrinsic: true
532
535
  };
533
536
  const raw = (spec?.arguments.map((a) => a.name) ?? Object.keys(value)).map((argName) => {
534
537
  const v = value[argName];
@@ -539,7 +542,8 @@ function toAnnotationTokens(name, value, spec) {
539
542
  return {
540
543
  name,
541
544
  token: dummyToken,
542
- args: raw.map((t) => t ?? text$1(""))
545
+ args: raw.map((t) => t ?? text$1("")),
546
+ intrinsic: true
543
547
  };
544
548
  }
545
549
  const dummyToken = new Token({
@@ -1118,8 +1122,13 @@ var AnnotationSpec = class {
1118
1122
  const idToken = isRef(parentNode) ? parentNode.token("identifier") : void 0;
1119
1123
  if (!(!!idToken && !!doc.annotateBlockAt(idToken.range.start.line, idToken.range.start.character))) {
1120
1124
  let def = parentNode.getDefinition();
1121
- if (isRef(def)) def = doc.unwindType(def.id, def.chain)?.def || def;
1122
- messages.push(...this.validateTargetType(def, mainToken.range) || []);
1125
+ let defDoc = doc;
1126
+ if (isRef(def)) {
1127
+ const unwound = doc.unwindType(def.id, def.chain);
1128
+ def = unwound?.def || def;
1129
+ defDoc = unwound?.doc || doc;
1130
+ }
1131
+ messages.push(...this.validateTargetType(def, mainToken.range, defDoc) || []);
1123
1132
  }
1124
1133
  }
1125
1134
  if (this.config.validate) messages.push(...this.config.validate(mainToken, args, doc) || []);
@@ -1132,13 +1141,23 @@ var AnnotationSpec = class {
1132
1141
  * guard is configured. Shared by the parse-time check (for inline props) and
1133
1142
  * the deferred annotate-entry check in `AtscriptDoc.getDiagMessages`, where
1134
1143
  * imported target types finally resolve.
1135
- */ validateTargetType(def, range) {
1136
- if (!this.config.defType?.length) return;
1137
- let defEntity = def?.entity || "unknown";
1138
- if (isInterface(def) || isStructure(def)) defEntity = "object";
1139
- else if (isGroup(def) && def.entity !== "tuple") defEntity = def.op === "&" ? "intersection" : "union";
1140
- if (!isPrimitive(def) && !this.config.defType.includes(defEntity) || isPrimitive(def) && !this.config.defType.includes(def.type)) return [{
1141
- message: `Expected type is (${this.config.defType.join(" | ")}), got "${isPrimitive(def) ? def.type : def?.entity || "unknown"}"`,
1144
+ *
1145
+ * A union also matches when every member other than `null` / `undefined`
1146
+ * matches (`number | null`, `string[] | null`, an alias of such a union).
1147
+ * Union members are refs, so `doc` (the document the union is declared in) is
1148
+ * needed to resolve them; without it a union never matches.
1149
+ */ validateTargetType(def, range, doc) {
1150
+ const defType = this.config.defType;
1151
+ if (!defType?.length) return;
1152
+ if (matchesDefType(def, defType)) return;
1153
+ let got;
1154
+ if (isGroup(def) && def.entity !== "tuple" && def.op !== "&") {
1155
+ const members = doc ? nonNullishMembers(def, doc) : void 0;
1156
+ if (members?.length && members.every((m) => matchesDefType(m, defType))) return;
1157
+ got = `union (${describeUnionMembers(def, doc)})`;
1158
+ } else got = `"${describeNode(def)}"`;
1159
+ return [{
1160
+ message: `Expected type is (${defType.join(" | ")}), got ${got}`,
1142
1161
  severity: 1,
1143
1162
  range
1144
1163
  }];
@@ -1185,6 +1204,63 @@ function resolveAnnotation(name, annotationsTree) {
1185
1204
  if (isAnnotationSpec(current)) return current;
1186
1205
  if (current && !isAnnotationSpec(current) && current.$self) return current.$self;
1187
1206
  }
1207
+ /** `null` / `undefined` / `void` primitive. */ function isNullishPrimitive(node) {
1208
+ return isPrimitive(node) && (node.type === "null" || node.type === "void");
1209
+ }
1210
+ /** Whether a resolved node satisfies a `defType` guard (a union as a whole, not its members). */ function matchesDefType(def, defType) {
1211
+ return defType.includes(describeNode(def));
1212
+ }
1213
+ /** The `defType` vocabulary name of a resolved node (`string`, `object`, `union`, `array`, …). */ function describeNode(def) {
1214
+ if (isPrimitive(def)) return def.type || "unknown";
1215
+ if (isInterface(def) || isStructure(def)) return "object";
1216
+ if (isGroup(def) && def.entity !== "tuple") return def.op === "&" ? "intersection" : "union";
1217
+ return def?.entity || "unknown";
1218
+ }
1219
+ /** Walks a `|` union (flattening nested unions and union aliases), resolving member refs. */ function walkUnionMembers(def, doc, cb, seen = /* @__PURE__ */ new Set()) {
1220
+ if (seen.has(def)) return;
1221
+ seen.add(def);
1222
+ for (const item of def.unwrap()) {
1223
+ let member = item;
1224
+ let memberDoc = doc;
1225
+ if (isRef(member)) {
1226
+ const unwound = doc?.unwindType(member.id, member.chain);
1227
+ member = unwound?.def;
1228
+ memberDoc = unwound?.doc || doc;
1229
+ }
1230
+ if (isGroup(member) && member.entity !== "tuple" && member.op !== "&") walkUnionMembers(member, memberDoc, cb, seen);
1231
+ else cb(member);
1232
+ }
1233
+ }
1234
+ function describeUnionMembers(def, doc) {
1235
+ const names = [];
1236
+ walkUnionMembers(def, doc, (m) => {
1237
+ const name = describeNode(m);
1238
+ if (!names.includes(name)) names.push(name);
1239
+ });
1240
+ return names.join(" | ");
1241
+ }
1242
+ /**
1243
+ * Resolved members of a union other than `null` / `undefined`, or `undefined`
1244
+ * when `def` is not a union. Nested unions and union aliases are flattened and
1245
+ * member refs are resolved through `doc` (the document `def` is declared in);
1246
+ * members that can't be resolved are left out (they are reported as unknown
1247
+ * identifiers elsewhere).
1248
+ *
1249
+ * Use it in an annotation's `validate` hook to accept nullable targets, e.g.
1250
+ * treat `string | null` like `string`:
1251
+ *
1252
+ * ```ts
1253
+ * const members = nonNullishMembers(def, doc)
1254
+ * const ok = members ? members.length > 0 && members.every(isWanted) : isWanted(def)
1255
+ * ```
1256
+ */ function nonNullishMembers(def, doc) {
1257
+ if (!isGroup(def) || def.entity === "tuple" || def.op === "&") return;
1258
+ const members = [];
1259
+ walkUnionMembers(def, doc, (m) => {
1260
+ if (m && !isNullishPrimitive(m)) members.push(m);
1261
+ });
1262
+ return members;
1263
+ }
1188
1264
 
1189
1265
  //#endregion
1190
1266
  //#region packages/core/src/config/define-config.ts
@@ -4110,37 +4186,58 @@ var AtscriptDoc = class AtscriptDoc {
4110
4186
  const token = this.tokensIndex.at(line, character);
4111
4187
  if (token) return this.usageListFor(token, character);
4112
4188
  }
4113
- evalAnnotationsForNode(givenNode) {
4114
- let right = givenNode.annotations;
4189
+ evalAnnotationsForNode(givenNode, own = givenNode.annotations) {
4190
+ let right = own;
4115
4191
  let def = givenNode.getDefinition();
4116
4192
  if (def) {
4117
4193
  const refDef = isRef(def) ? def : void 0;
4194
+ let viaProp = false;
4118
4195
  if (refDef) {
4119
4196
  const chainNodes = [];
4120
4197
  const unwound = this.unwindType(refDef.token("identifier").text, refDef.chain, (intermediate) => {
4198
+ if (isProp(intermediate) && intermediate !== givenNode) viaProp = true;
4121
4199
  if (intermediate?.annotations?.length) chainNodes.push(intermediate);
4122
4200
  });
4123
- if (unwound?.node && unwound.node !== givenNode && unwound.node.annotations?.length && !chainNodes.includes(unwound.node)) chainNodes.unshift(unwound.node);
4124
- for (const chainNode of chainNodes) right = this.mergeNodesAnnotations(this.filterPassedWhenReferred(chainNode.annotations), right);
4201
+ if (unwound?.node && unwound.node !== givenNode) {
4202
+ viaProp || (viaProp = isProp(unwound.node));
4203
+ if (unwound.node.annotations?.length && !chainNodes.includes(unwound.node)) chainNodes.unshift(unwound.node);
4204
+ }
4205
+ for (const chainNode of chainNodes) {
4206
+ if (chainNode === unwound?.def) continue;
4207
+ right = this.mergeNodesAnnotations(this.filterPassedWhenReferred(chainNode.annotations, viaProp), right);
4208
+ }
4125
4209
  def = unwound?.def || def;
4126
4210
  }
4127
4211
  if (def) {
4128
4212
  const merged = this.mergeIntersection(def);
4129
- right = this.mergeNodesAnnotations(refDef ? this.filterPassedWhenReferred(merged.annotations) : merged.annotations, right);
4213
+ right = this.mergeNodesAnnotations(refDef ? this.filterPassedWhenReferred(merged.annotations, viaProp) : merged.annotations, right);
4130
4214
  }
4131
4215
  }
4132
4216
  return right;
4133
4217
  }
4134
4218
  /**
4219
+ * The annotations a reference to `node` (`field: Alias`) inherits: its evaluated
4220
+ * set without the `passedWhenReferred: false` ones. The node's own are filtered
4221
+ * before the merge, so a dropped one cannot shadow a primitive's intrinsic
4222
+ * annotation of the same name (`@meta.required 'msg'` on `type N = string.required`).
4223
+ */ evalReferredAnnotations(node) {
4224
+ return this.filterPassedWhenReferred(this.evalAnnotationsForNode(node, this.filterPassedWhenReferred(node.annotations)));
4225
+ }
4226
+ /**
4135
4227
  * Drops annotations whose spec declares `passedWhenReferred: false` — used
4136
4228
  * when folding annotations across a ref boundary. Annotations without a
4137
- * resolvable spec pass through (default is to inherit). Returns the input
4229
+ * resolvable spec pass through (default is to inherit), and so do a
4230
+ * primitive's intrinsic ones (`number.timestamp.created` → `@db.default.now`)
4231
+ * unless the boundary is a reference to a prop (`viaProp`). Returns the input
4138
4232
  * array unchanged when nothing is dropped.
4139
- */ filterPassedWhenReferred(annotations) {
4233
+ */ filterPassedWhenReferred(annotations, viaProp = false) {
4140
4234
  if (!annotations?.length) return annotations;
4141
4235
  let filtered;
4142
- for (let i = 0; i < annotations.length; i++) if (this.resolveAnnotation(annotations[i].name)?.config.passedWhenReferred === false) filtered ?? (filtered = annotations.slice(0, i));
4143
- else filtered?.push(annotations[i]);
4236
+ for (let i = 0; i < annotations.length; i++) {
4237
+ const a = annotations[i];
4238
+ if ((viaProp || !a.intrinsic) && this.resolveAnnotation(a.name)?.config.passedWhenReferred === false) filtered ?? (filtered = annotations.slice(0, i));
4239
+ else filtered?.push(a);
4240
+ }
4144
4241
  return filtered ?? annotations;
4145
4242
  }
4146
4243
  /**
@@ -4752,7 +4849,7 @@ var AtscriptDoc = class AtscriptDoc {
4752
4849
  }
4753
4850
  }
4754
4851
  if (resolvedType && isRef(t.parentNode) && t.parentNode.annotations) for (const a of t.parentNode.annotations) {
4755
- const msgs = this.resolveAnnotation(a.token.text.slice(1))?.validateTargetType(resolvedType, a.token.range);
4852
+ const msgs = this.resolveAnnotation(a.token.text.slice(1))?.validateTargetType(resolvedType, a.token.range, unwound?.doc || this);
4756
4853
  if (msgs) this._allMessages.push(...msgs);
4757
4854
  }
4758
4855
  continue;
@@ -5048,9 +5145,10 @@ const emitAnnotations = { jsonSchema: new AnnotationSpec({
5048
5145
 
5049
5146
  //#endregion
5050
5147
  //#region packages/core/src/defaults/expect-annotations.ts
5148
+ const NULLABLE_NOTE = "Also allowed on a nullable field (`T | null`, `T | undefined`): `null` passes, any other value must satisfy the constraint.";
5051
5149
  const expectAnnotations = {
5052
5150
  minLength: new AnnotationSpec({
5053
- description: "Validates that a string or array has a minimum length.\n\n**Example:**```atscript@expect.minLength 5name: string```",
5151
+ description: `Validates that a string or array has a minimum length. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.minLength 5name: string\`\`\``,
5054
5152
  defType: ["array", "string"],
5055
5153
  argument: [{
5056
5154
  name: "length",
@@ -5064,7 +5162,7 @@ const expectAnnotations = {
5064
5162
  }]
5065
5163
  }),
5066
5164
  maxLength: new AnnotationSpec({
5067
- description: "Validates that a string or array has a maximum length.\n\n**Example:**```atscript@expect.maxLength 5name: string```",
5165
+ description: `Validates that a string or array has a maximum length. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.maxLength 5name: string\`\`\``,
5068
5166
  defType: ["array", "string"],
5069
5167
  argument: [{
5070
5168
  name: "length",
@@ -5078,7 +5176,7 @@ const expectAnnotations = {
5078
5176
  }]
5079
5177
  }),
5080
5178
  min: new AnnotationSpec({
5081
- description: "Validates that a number is greater than or equal to a minimum value.\n\n**Example:**```atscript@expect.min 18age: number```",
5179
+ description: `Validates that a number is greater than or equal to a minimum value. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.min 18age: number\`\`\``,
5082
5180
  defType: ["number"],
5083
5181
  argument: [{
5084
5182
  name: "minValue",
@@ -5092,7 +5190,7 @@ const expectAnnotations = {
5092
5190
  }]
5093
5191
  }),
5094
5192
  max: new AnnotationSpec({
5095
- description: "Validates that a number is less than or equal to a maximum value.\n\n**Example:**```atscript@expect.max 10count: number```",
5193
+ description: `Validates that a number is less than or equal to a maximum value. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.max 10count: number\`\`\``,
5096
5194
  defType: ["number"],
5097
5195
  argument: [{
5098
5196
  name: "maxValue",
@@ -5106,11 +5204,11 @@ const expectAnnotations = {
5106
5204
  }]
5107
5205
  }),
5108
5206
  int: new AnnotationSpec({
5109
- description: "Validates that a number is an integer (no decimal places).\n\n**Example:**```atscript@expect.intage: number```",
5207
+ description: `Validates that a number is an integer (no decimal places). ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.intage: number\`\`\``,
5110
5208
  defType: ["number"]
5111
5209
  }),
5112
5210
  pattern: new AnnotationSpec({
5113
- description: "Validates that a string matches a specific pattern.\n\n**Example:**```atscript@expect.pattern \"[a-z]+\", \"u\"name: string```",
5211
+ description: `Validates that a string matches a specific pattern. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.pattern "[a-z]+", "u"name: string\`\`\``,
5114
5212
  defType: ["string"],
5115
5213
  multiple: true,
5116
5214
  mergeStrategy: "append",
@@ -5214,7 +5312,7 @@ const expectAnnotations = {
5214
5312
  }),
5215
5313
  array: {
5216
5314
  uniqueItems: new AnnotationSpec({
5217
- description: "Enforces **unique items** in an array field.\n\nWorks with both **primitive arrays** and **object arrays**:\n\n- **Primitive arrays** (`string[]`, `number[]`) — duplicates are detected by deep equality.\n- **Object arrays** — if the element type defines `@expect.array.key` properties, uniqueness is checked by those keys only; otherwise by deep equality of the whole object.\n\nUnlike `@expect.array.key` (which only *identifies* key fields for lookup/patch operations), `@expect.array.uniqueItems` actively *enforces* uniqueness during validation.\n\n**Examples:**\n```atscript\n// Primitive array — no duplicates allowed\n@expect.array.uniqueItems\ntags: string[]\n\n// Object array with keys — unique by key fields\n@expect.array.uniqueItems\nitems: {\n @expect.array.key\n id: string\n value: number\n}[]\n```\n",
5315
+ description: "Enforces **unique items** in an array field.\n\nWorks with both **primitive arrays** and **object arrays**:\n\n- **Primitive arrays** (`string[]`, `number[]`) — duplicates are detected by deep equality.\n- **Object arrays** — if the element type defines `@expect.array.key` properties, uniqueness is checked by those keys only; otherwise by deep equality of the whole object.\n\nUnlike `@expect.array.key` (which only *identifies* key fields for lookup/patch operations), `@expect.array.uniqueItems` actively *enforces* uniqueness during validation.\n\nAlso allowed on a nullable array (`T[] | null`); `null` passes.\n\n**Examples:**\n```atscript\n// Primitive array — no duplicates allowed\n@expect.array.uniqueItems\ntags: string[]\n\n// Object array with keys — unique by key fields\n@expect.array.uniqueItems\nitems: {\n @expect.array.key\n id: string\n value: number\n}[]\n```\n",
5218
5316
  nodeType: ["prop"],
5219
5317
  multiple: false,
5220
5318
  argument: [{
@@ -5228,12 +5326,15 @@ const expectAnnotations = {
5228
5326
  const errors = [];
5229
5327
  const definition = field.getDefinition();
5230
5328
  if (!definition) return errors;
5231
- let wrongType = false;
5329
+ let def = definition;
5330
+ let defDoc = doc;
5232
5331
  if (isRef(definition)) {
5233
- const def = doc.unwindType(definition.id, definition.chain)?.def;
5234
- if (!isArray(def)) wrongType = true;
5235
- } else if (!isArray(definition)) wrongType = true;
5236
- if (wrongType) errors.push({
5332
+ const unwound = doc.unwindType(definition.id, definition.chain);
5333
+ def = unwound?.def;
5334
+ defDoc = unwound?.doc || doc;
5335
+ }
5336
+ const members = nonNullishMembers(def, defDoc);
5337
+ if (!(members ? members.length > 0 && members.every((m) => isArray(m)) : isArray(def))) errors.push({
5237
5338
  message: `@expect.array.uniqueItems requires an array field`,
5238
5339
  severity: 1,
5239
5340
  range: token.range
@@ -5322,7 +5423,7 @@ const metaAnnotations = {
5322
5423
  passedWhenReferred: false
5323
5424
  }),
5324
5425
  required: new AnnotationSpec({
5325
- description: "Marks a field as required for form validation. For strings: must contain at least one non-whitespace character. For booleans: must be true.\n\n**Example:**```atscript@meta.requiredname: string\n@meta.required \"You must accept the terms\"agreed: boolean```",
5426
+ description: "Marks a field as required for form validation. For strings: must contain at least one non-whitespace character. For booleans: must be true. On an optional field (`name?: string`) the field may be omitted, but `null` is rejected. On a nullable field (`string | null`) `null` is accepted and a string must not be empty.\n\n**Example:**```atscript@meta.requiredname: string\n@meta.required \"You must accept the terms\"agreed: boolean```",
5326
5427
  defType: ["string", "boolean"],
5327
5428
  argument: [{
5328
5429
  name: "message",
@@ -5554,7 +5655,7 @@ const primitives = {
5554
5655
  annotations: { "db.default.now": true }
5555
5656
  },
5556
5657
  updated: {
5557
- documentation: "Timestamp auto-updated on every write. DB adapters read the \"updated\" tag.",
5658
+ documentation: "Last-modified timestamp (tag \"updated\"). A marker only: it carries no default and is not set on write.",
5558
5659
  tags: ["updated"]
5559
5660
  }
5560
5661
  }
@@ -6394,4 +6495,4 @@ function walkArrayElement(doc, arrayNode, prefix, parentOptional, flatMap, stack
6394
6495
  }
6395
6496
 
6396
6497
  //#endregion
6397
- export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BACKTICK_ARG_VOCABULARY, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, PluginManager, 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, Token, analyzeQueryCursorContext, build, clearResolveBareCache, createAtscriptPlugin, defineConfig, fileUriToPath, flattenInterfaceNode, getDeclaredValue, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, getSiblingAnnotation, getValueCandidates, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isBacktickArgType, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, parseBareSpecifier, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveQueryFieldRef };
6498
+ export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BACKTICK_ARG_VOCABULARY, BuildRepo, DB_ENTITY_ANNOTATIONS, DEFAULT_FORMAT, PluginManager, 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, Token, analyzeQueryCursorContext, build, clearResolveBareCache, createAtscriptPlugin, defineConfig, fileUriToPath, flattenInterfaceNode, getDeclaredValue, getFieldPathCompletionScope, getFieldsForType, getQueryCompletionScope, getQueryScope, getRelPath, getSiblingAnnotation, getValueCandidates, hasNavPropAnnotation, isAnnotate, isAnnotationSpec, isArray, isBacktickArgType, isBareId, isBareSpecifier, isConst, isDbEntityNode, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isQueryComparison, isQueryFieldRef, isQueryLogical, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, nonNullishMembers, parseBareSpecifier, resolveAnnotation, resolveAtscriptFromPath, resolveBareSpecifier, resolveConfigFile, resolveFieldRefAt, resolveQueryFieldRef };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atscript/core",
3
- "version": "0.1.102",
3
+ "version": "0.1.104",
4
4
  "description": "Core library for Atscript parsing and file generation.",
5
5
  "keywords": [
6
6
  "annotations",