@atscript/core 0.1.101 → 0.1.103
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 +100 -23
- package/dist/index.d.ts +23 -2
- package/dist/index.mjs +100 -24
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1149,8 +1149,13 @@ var AnnotationSpec = class {
|
|
|
1149
1149
|
const idToken = isRef(parentNode) ? parentNode.token("identifier") : void 0;
|
|
1150
1150
|
if (!(!!idToken && !!doc.annotateBlockAt(idToken.range.start.line, idToken.range.start.character))) {
|
|
1151
1151
|
let def = parentNode.getDefinition();
|
|
1152
|
-
|
|
1153
|
-
|
|
1152
|
+
let defDoc = doc;
|
|
1153
|
+
if (isRef(def)) {
|
|
1154
|
+
const unwound = doc.unwindType(def.id, def.chain);
|
|
1155
|
+
def = unwound?.def || def;
|
|
1156
|
+
defDoc = unwound?.doc || doc;
|
|
1157
|
+
}
|
|
1158
|
+
messages.push(...this.validateTargetType(def, mainToken.range, defDoc) || []);
|
|
1154
1159
|
}
|
|
1155
1160
|
}
|
|
1156
1161
|
if (this.config.validate) messages.push(...this.config.validate(mainToken, args, doc) || []);
|
|
@@ -1163,13 +1168,23 @@ var AnnotationSpec = class {
|
|
|
1163
1168
|
* guard is configured. Shared by the parse-time check (for inline props) and
|
|
1164
1169
|
* the deferred annotate-entry check in `AtscriptDoc.getDiagMessages`, where
|
|
1165
1170
|
* imported target types finally resolve.
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1171
|
+
*
|
|
1172
|
+
* A union also matches when every member other than `null` / `undefined`
|
|
1173
|
+
* matches (`number | null`, `string[] | null`, an alias of such a union).
|
|
1174
|
+
* Union members are refs, so `doc` (the document the union is declared in) is
|
|
1175
|
+
* needed to resolve them; without it a union never matches.
|
|
1176
|
+
*/ validateTargetType(def, range, doc) {
|
|
1177
|
+
const defType = this.config.defType;
|
|
1178
|
+
if (!defType?.length) return;
|
|
1179
|
+
if (matchesDefType(def, defType)) return;
|
|
1180
|
+
let got;
|
|
1181
|
+
if (isGroup(def) && def.entity !== "tuple" && def.op !== "&") {
|
|
1182
|
+
const members = doc ? nonNullishMembers(def, doc) : void 0;
|
|
1183
|
+
if (members?.length && members.every((m) => matchesDefType(m, defType))) return;
|
|
1184
|
+
got = `union (${describeUnionMembers(def, doc)})`;
|
|
1185
|
+
} else got = `"${describeNode(def)}"`;
|
|
1186
|
+
return [{
|
|
1187
|
+
message: `Expected type is (${defType.join(" | ")}), got ${got}`,
|
|
1173
1188
|
severity: 1,
|
|
1174
1189
|
range
|
|
1175
1190
|
}];
|
|
@@ -1216,6 +1231,63 @@ function resolveAnnotation(name, annotationsTree) {
|
|
|
1216
1231
|
if (isAnnotationSpec(current)) return current;
|
|
1217
1232
|
if (current && !isAnnotationSpec(current) && current.$self) return current.$self;
|
|
1218
1233
|
}
|
|
1234
|
+
/** `null` / `undefined` / `void` primitive. */ function isNullishPrimitive(node) {
|
|
1235
|
+
return isPrimitive(node) && (node.type === "null" || node.type === "void");
|
|
1236
|
+
}
|
|
1237
|
+
/** Whether a resolved node satisfies a `defType` guard (a union as a whole, not its members). */ function matchesDefType(def, defType) {
|
|
1238
|
+
return defType.includes(describeNode(def));
|
|
1239
|
+
}
|
|
1240
|
+
/** The `defType` vocabulary name of a resolved node (`string`, `object`, `union`, `array`, …). */ function describeNode(def) {
|
|
1241
|
+
if (isPrimitive(def)) return def.type || "unknown";
|
|
1242
|
+
if (isInterface(def) || isStructure(def)) return "object";
|
|
1243
|
+
if (isGroup(def) && def.entity !== "tuple") return def.op === "&" ? "intersection" : "union";
|
|
1244
|
+
return def?.entity || "unknown";
|
|
1245
|
+
}
|
|
1246
|
+
/** Walks a `|` union (flattening nested unions and union aliases), resolving member refs. */ function walkUnionMembers(def, doc, cb, seen = /* @__PURE__ */ new Set()) {
|
|
1247
|
+
if (seen.has(def)) return;
|
|
1248
|
+
seen.add(def);
|
|
1249
|
+
for (const item of def.unwrap()) {
|
|
1250
|
+
let member = item;
|
|
1251
|
+
let memberDoc = doc;
|
|
1252
|
+
if (isRef(member)) {
|
|
1253
|
+
const unwound = doc?.unwindType(member.id, member.chain);
|
|
1254
|
+
member = unwound?.def;
|
|
1255
|
+
memberDoc = unwound?.doc || doc;
|
|
1256
|
+
}
|
|
1257
|
+
if (isGroup(member) && member.entity !== "tuple" && member.op !== "&") walkUnionMembers(member, memberDoc, cb, seen);
|
|
1258
|
+
else cb(member);
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
function describeUnionMembers(def, doc) {
|
|
1262
|
+
const names = [];
|
|
1263
|
+
walkUnionMembers(def, doc, (m) => {
|
|
1264
|
+
const name = describeNode(m);
|
|
1265
|
+
if (!names.includes(name)) names.push(name);
|
|
1266
|
+
});
|
|
1267
|
+
return names.join(" | ");
|
|
1268
|
+
}
|
|
1269
|
+
/**
|
|
1270
|
+
* Resolved members of a union other than `null` / `undefined`, or `undefined`
|
|
1271
|
+
* when `def` is not a union. Nested unions and union aliases are flattened and
|
|
1272
|
+
* member refs are resolved through `doc` (the document `def` is declared in);
|
|
1273
|
+
* members that can't be resolved are left out (they are reported as unknown
|
|
1274
|
+
* identifiers elsewhere).
|
|
1275
|
+
*
|
|
1276
|
+
* Use it in an annotation's `validate` hook to accept nullable targets, e.g.
|
|
1277
|
+
* treat `string | null` like `string`:
|
|
1278
|
+
*
|
|
1279
|
+
* ```ts
|
|
1280
|
+
* const members = nonNullishMembers(def, doc)
|
|
1281
|
+
* const ok = members ? members.length > 0 && members.every(isWanted) : isWanted(def)
|
|
1282
|
+
* ```
|
|
1283
|
+
*/ function nonNullishMembers(def, doc) {
|
|
1284
|
+
if (!isGroup(def) || def.entity === "tuple" || def.op === "&") return;
|
|
1285
|
+
const members = [];
|
|
1286
|
+
walkUnionMembers(def, doc, (m) => {
|
|
1287
|
+
if (m && !isNullishPrimitive(m)) members.push(m);
|
|
1288
|
+
});
|
|
1289
|
+
return members;
|
|
1290
|
+
}
|
|
1219
1291
|
|
|
1220
1292
|
//#endregion
|
|
1221
1293
|
//#region packages/core/src/config/define-config.ts
|
|
@@ -4783,7 +4855,7 @@ var AtscriptDoc = class AtscriptDoc {
|
|
|
4783
4855
|
}
|
|
4784
4856
|
}
|
|
4785
4857
|
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);
|
|
4858
|
+
const msgs = this.resolveAnnotation(a.token.text.slice(1))?.validateTargetType(resolvedType, a.token.range, unwound?.doc || this);
|
|
4787
4859
|
if (msgs) this._allMessages.push(...msgs);
|
|
4788
4860
|
}
|
|
4789
4861
|
continue;
|
|
@@ -5079,9 +5151,10 @@ const emitAnnotations = { jsonSchema: new AnnotationSpec({
|
|
|
5079
5151
|
|
|
5080
5152
|
//#endregion
|
|
5081
5153
|
//#region packages/core/src/defaults/expect-annotations.ts
|
|
5154
|
+
const NULLABLE_NOTE = "Also allowed on a nullable field (`T | null`, `T | undefined`): `null` passes, any other value must satisfy the constraint.";
|
|
5082
5155
|
const expectAnnotations = {
|
|
5083
5156
|
minLength: new AnnotationSpec({
|
|
5084
|
-
description:
|
|
5157
|
+
description: `Validates that a string or array has a minimum length. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.minLength 5name: string\`\`\``,
|
|
5085
5158
|
defType: ["array", "string"],
|
|
5086
5159
|
argument: [{
|
|
5087
5160
|
name: "length",
|
|
@@ -5095,7 +5168,7 @@ const expectAnnotations = {
|
|
|
5095
5168
|
}]
|
|
5096
5169
|
}),
|
|
5097
5170
|
maxLength: new AnnotationSpec({
|
|
5098
|
-
description:
|
|
5171
|
+
description: `Validates that a string or array has a maximum length. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.maxLength 5name: string\`\`\``,
|
|
5099
5172
|
defType: ["array", "string"],
|
|
5100
5173
|
argument: [{
|
|
5101
5174
|
name: "length",
|
|
@@ -5109,7 +5182,7 @@ const expectAnnotations = {
|
|
|
5109
5182
|
}]
|
|
5110
5183
|
}),
|
|
5111
5184
|
min: new AnnotationSpec({
|
|
5112
|
-
description:
|
|
5185
|
+
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
5186
|
defType: ["number"],
|
|
5114
5187
|
argument: [{
|
|
5115
5188
|
name: "minValue",
|
|
@@ -5123,7 +5196,7 @@ const expectAnnotations = {
|
|
|
5123
5196
|
}]
|
|
5124
5197
|
}),
|
|
5125
5198
|
max: new AnnotationSpec({
|
|
5126
|
-
description:
|
|
5199
|
+
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
5200
|
defType: ["number"],
|
|
5128
5201
|
argument: [{
|
|
5129
5202
|
name: "maxValue",
|
|
@@ -5137,11 +5210,11 @@ const expectAnnotations = {
|
|
|
5137
5210
|
}]
|
|
5138
5211
|
}),
|
|
5139
5212
|
int: new AnnotationSpec({
|
|
5140
|
-
description:
|
|
5213
|
+
description: `Validates that a number is an integer (no decimal places). ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.intage: number\`\`\``,
|
|
5141
5214
|
defType: ["number"]
|
|
5142
5215
|
}),
|
|
5143
5216
|
pattern: new AnnotationSpec({
|
|
5144
|
-
description:
|
|
5217
|
+
description: `Validates that a string matches a specific pattern. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.pattern "[a-z]+", "u"name: string\`\`\``,
|
|
5145
5218
|
defType: ["string"],
|
|
5146
5219
|
multiple: true,
|
|
5147
5220
|
mergeStrategy: "append",
|
|
@@ -5245,7 +5318,7 @@ const expectAnnotations = {
|
|
|
5245
5318
|
}),
|
|
5246
5319
|
array: {
|
|
5247
5320
|
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",
|
|
5321
|
+
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
5322
|
nodeType: ["prop"],
|
|
5250
5323
|
multiple: false,
|
|
5251
5324
|
argument: [{
|
|
@@ -5259,12 +5332,15 @@ const expectAnnotations = {
|
|
|
5259
5332
|
const errors = [];
|
|
5260
5333
|
const definition = field.getDefinition();
|
|
5261
5334
|
if (!definition) return errors;
|
|
5262
|
-
let
|
|
5335
|
+
let def = definition;
|
|
5336
|
+
let defDoc = doc;
|
|
5263
5337
|
if (isRef(definition)) {
|
|
5264
|
-
const
|
|
5265
|
-
|
|
5266
|
-
|
|
5267
|
-
|
|
5338
|
+
const unwound = doc.unwindType(definition.id, definition.chain);
|
|
5339
|
+
def = unwound?.def;
|
|
5340
|
+
defDoc = unwound?.doc || doc;
|
|
5341
|
+
}
|
|
5342
|
+
const members = nonNullishMembers(def, defDoc);
|
|
5343
|
+
if (!(members ? members.length > 0 && members.every((m) => isArray(m)) : isArray(def))) errors.push({
|
|
5268
5344
|
message: `@expect.array.uniqueItems requires an array field`,
|
|
5269
5345
|
severity: 1,
|
|
5270
5346
|
range: token.range
|
|
@@ -5353,7 +5429,7 @@ const metaAnnotations = {
|
|
|
5353
5429
|
passedWhenReferred: false
|
|
5354
5430
|
}),
|
|
5355
5431
|
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```",
|
|
5432
|
+
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
5433
|
defType: ["string", "boolean"],
|
|
5358
5434
|
argument: [{
|
|
5359
5435
|
name: "message",
|
|
@@ -6499,6 +6575,7 @@ exports.isTuple = isTuple;
|
|
|
6499
6575
|
exports.isType = isType;
|
|
6500
6576
|
exports.loadConfig = loadConfig;
|
|
6501
6577
|
exports.loadTsConfig = loadTsConfig;
|
|
6578
|
+
exports.nonNullishMembers = nonNullishMembers;
|
|
6502
6579
|
exports.parseBareSpecifier = parseBareSpecifier;
|
|
6503
6580
|
exports.resolveAnnotation = resolveAnnotation;
|
|
6504
6581
|
exports.resolveAtscriptFromPath = resolveAtscriptFromPath;
|
package/dist/index.d.ts
CHANGED
|
@@ -1143,13 +1143,34 @@ declare class AnnotationSpec {
|
|
|
1143
1143
|
* guard is configured. Shared by the parse-time check (for inline props) and
|
|
1144
1144
|
* the deferred annotate-entry check in `AtscriptDoc.getDiagMessages`, where
|
|
1145
1145
|
* imported target types finally resolve.
|
|
1146
|
+
*
|
|
1147
|
+
* A union also matches when every member other than `null` / `undefined`
|
|
1148
|
+
* matches (`number | null`, `string[] | null`, an alias of such a union).
|
|
1149
|
+
* Union members are refs, so `doc` (the document the union is declared in) is
|
|
1150
|
+
* needed to resolve them; without it a union never matches.
|
|
1146
1151
|
*/
|
|
1147
|
-
validateTargetType(def: SemanticNode | undefined, range: Token['range']): TMessages | undefined;
|
|
1152
|
+
validateTargetType(def: SemanticNode | undefined, range: Token['range'], doc?: AtscriptDoc): TMessages | undefined;
|
|
1148
1153
|
renderDocs(index: number | string): string | undefined;
|
|
1149
1154
|
protected getDefaultValueForType(name: string, type: TAnnotationArgument['type']): string;
|
|
1150
1155
|
}
|
|
1151
1156
|
declare function isAnnotationSpec(a?: TAnnotationsTree | AnnotationSpec): a is AnnotationSpec;
|
|
1152
1157
|
declare function resolveAnnotation(name: string, annotationsTree?: TAnnotationsTree): AnnotationSpec | undefined;
|
|
1158
|
+
/**
|
|
1159
|
+
* Resolved members of a union other than `null` / `undefined`, or `undefined`
|
|
1160
|
+
* when `def` is not a union. Nested unions and union aliases are flattened and
|
|
1161
|
+
* member refs are resolved through `doc` (the document `def` is declared in);
|
|
1162
|
+
* members that can't be resolved are left out (they are reported as unknown
|
|
1163
|
+
* identifiers elsewhere).
|
|
1164
|
+
*
|
|
1165
|
+
* Use it in an annotation's `validate` hook to accept nullable targets, e.g.
|
|
1166
|
+
* treat `string | null` like `string`:
|
|
1167
|
+
*
|
|
1168
|
+
* ```ts
|
|
1169
|
+
* const members = nonNullishMembers(def, doc)
|
|
1170
|
+
* const ok = members ? members.length > 0 && members.every(isWanted) : isWanted(def)
|
|
1171
|
+
* ```
|
|
1172
|
+
*/
|
|
1173
|
+
declare function nonNullishMembers(def: SemanticNode | undefined, doc: AtscriptDoc): SemanticNode[] | undefined;
|
|
1153
1174
|
|
|
1154
1175
|
declare function resolveAtscriptFromPath(from: string, id: string): string;
|
|
1155
1176
|
declare function fileUriToPath(id: string): string;
|
|
@@ -1371,5 +1392,5 @@ declare const BACKTICK_ARG_VOCABULARY: {
|
|
|
1371
1392
|
readonly orderDirections: readonly ["asc", "desc"];
|
|
1372
1393
|
};
|
|
1373
1394
|
|
|
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 };
|
|
1395
|
+
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
1396
|
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
|
@@ -1118,8 +1118,13 @@ var AnnotationSpec = class {
|
|
|
1118
1118
|
const idToken = isRef(parentNode) ? parentNode.token("identifier") : void 0;
|
|
1119
1119
|
if (!(!!idToken && !!doc.annotateBlockAt(idToken.range.start.line, idToken.range.start.character))) {
|
|
1120
1120
|
let def = parentNode.getDefinition();
|
|
1121
|
-
|
|
1122
|
-
|
|
1121
|
+
let defDoc = doc;
|
|
1122
|
+
if (isRef(def)) {
|
|
1123
|
+
const unwound = doc.unwindType(def.id, def.chain);
|
|
1124
|
+
def = unwound?.def || def;
|
|
1125
|
+
defDoc = unwound?.doc || doc;
|
|
1126
|
+
}
|
|
1127
|
+
messages.push(...this.validateTargetType(def, mainToken.range, defDoc) || []);
|
|
1123
1128
|
}
|
|
1124
1129
|
}
|
|
1125
1130
|
if (this.config.validate) messages.push(...this.config.validate(mainToken, args, doc) || []);
|
|
@@ -1132,13 +1137,23 @@ var AnnotationSpec = class {
|
|
|
1132
1137
|
* guard is configured. Shared by the parse-time check (for inline props) and
|
|
1133
1138
|
* the deferred annotate-entry check in `AtscriptDoc.getDiagMessages`, where
|
|
1134
1139
|
* imported target types finally resolve.
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1140
|
+
*
|
|
1141
|
+
* A union also matches when every member other than `null` / `undefined`
|
|
1142
|
+
* matches (`number | null`, `string[] | null`, an alias of such a union).
|
|
1143
|
+
* Union members are refs, so `doc` (the document the union is declared in) is
|
|
1144
|
+
* needed to resolve them; without it a union never matches.
|
|
1145
|
+
*/ validateTargetType(def, range, doc) {
|
|
1146
|
+
const defType = this.config.defType;
|
|
1147
|
+
if (!defType?.length) return;
|
|
1148
|
+
if (matchesDefType(def, defType)) return;
|
|
1149
|
+
let got;
|
|
1150
|
+
if (isGroup(def) && def.entity !== "tuple" && def.op !== "&") {
|
|
1151
|
+
const members = doc ? nonNullishMembers(def, doc) : void 0;
|
|
1152
|
+
if (members?.length && members.every((m) => matchesDefType(m, defType))) return;
|
|
1153
|
+
got = `union (${describeUnionMembers(def, doc)})`;
|
|
1154
|
+
} else got = `"${describeNode(def)}"`;
|
|
1155
|
+
return [{
|
|
1156
|
+
message: `Expected type is (${defType.join(" | ")}), got ${got}`,
|
|
1142
1157
|
severity: 1,
|
|
1143
1158
|
range
|
|
1144
1159
|
}];
|
|
@@ -1185,6 +1200,63 @@ function resolveAnnotation(name, annotationsTree) {
|
|
|
1185
1200
|
if (isAnnotationSpec(current)) return current;
|
|
1186
1201
|
if (current && !isAnnotationSpec(current) && current.$self) return current.$self;
|
|
1187
1202
|
}
|
|
1203
|
+
/** `null` / `undefined` / `void` primitive. */ function isNullishPrimitive(node) {
|
|
1204
|
+
return isPrimitive(node) && (node.type === "null" || node.type === "void");
|
|
1205
|
+
}
|
|
1206
|
+
/** Whether a resolved node satisfies a `defType` guard (a union as a whole, not its members). */ function matchesDefType(def, defType) {
|
|
1207
|
+
return defType.includes(describeNode(def));
|
|
1208
|
+
}
|
|
1209
|
+
/** The `defType` vocabulary name of a resolved node (`string`, `object`, `union`, `array`, …). */ function describeNode(def) {
|
|
1210
|
+
if (isPrimitive(def)) return def.type || "unknown";
|
|
1211
|
+
if (isInterface(def) || isStructure(def)) return "object";
|
|
1212
|
+
if (isGroup(def) && def.entity !== "tuple") return def.op === "&" ? "intersection" : "union";
|
|
1213
|
+
return def?.entity || "unknown";
|
|
1214
|
+
}
|
|
1215
|
+
/** Walks a `|` union (flattening nested unions and union aliases), resolving member refs. */ function walkUnionMembers(def, doc, cb, seen = /* @__PURE__ */ new Set()) {
|
|
1216
|
+
if (seen.has(def)) return;
|
|
1217
|
+
seen.add(def);
|
|
1218
|
+
for (const item of def.unwrap()) {
|
|
1219
|
+
let member = item;
|
|
1220
|
+
let memberDoc = doc;
|
|
1221
|
+
if (isRef(member)) {
|
|
1222
|
+
const unwound = doc?.unwindType(member.id, member.chain);
|
|
1223
|
+
member = unwound?.def;
|
|
1224
|
+
memberDoc = unwound?.doc || doc;
|
|
1225
|
+
}
|
|
1226
|
+
if (isGroup(member) && member.entity !== "tuple" && member.op !== "&") walkUnionMembers(member, memberDoc, cb, seen);
|
|
1227
|
+
else cb(member);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
function describeUnionMembers(def, doc) {
|
|
1231
|
+
const names = [];
|
|
1232
|
+
walkUnionMembers(def, doc, (m) => {
|
|
1233
|
+
const name = describeNode(m);
|
|
1234
|
+
if (!names.includes(name)) names.push(name);
|
|
1235
|
+
});
|
|
1236
|
+
return names.join(" | ");
|
|
1237
|
+
}
|
|
1238
|
+
/**
|
|
1239
|
+
* Resolved members of a union other than `null` / `undefined`, or `undefined`
|
|
1240
|
+
* when `def` is not a union. Nested unions and union aliases are flattened and
|
|
1241
|
+
* member refs are resolved through `doc` (the document `def` is declared in);
|
|
1242
|
+
* members that can't be resolved are left out (they are reported as unknown
|
|
1243
|
+
* identifiers elsewhere).
|
|
1244
|
+
*
|
|
1245
|
+
* Use it in an annotation's `validate` hook to accept nullable targets, e.g.
|
|
1246
|
+
* treat `string | null` like `string`:
|
|
1247
|
+
*
|
|
1248
|
+
* ```ts
|
|
1249
|
+
* const members = nonNullishMembers(def, doc)
|
|
1250
|
+
* const ok = members ? members.length > 0 && members.every(isWanted) : isWanted(def)
|
|
1251
|
+
* ```
|
|
1252
|
+
*/ function nonNullishMembers(def, doc) {
|
|
1253
|
+
if (!isGroup(def) || def.entity === "tuple" || def.op === "&") return;
|
|
1254
|
+
const members = [];
|
|
1255
|
+
walkUnionMembers(def, doc, (m) => {
|
|
1256
|
+
if (m && !isNullishPrimitive(m)) members.push(m);
|
|
1257
|
+
});
|
|
1258
|
+
return members;
|
|
1259
|
+
}
|
|
1188
1260
|
|
|
1189
1261
|
//#endregion
|
|
1190
1262
|
//#region packages/core/src/config/define-config.ts
|
|
@@ -4752,7 +4824,7 @@ var AtscriptDoc = class AtscriptDoc {
|
|
|
4752
4824
|
}
|
|
4753
4825
|
}
|
|
4754
4826
|
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);
|
|
4827
|
+
const msgs = this.resolveAnnotation(a.token.text.slice(1))?.validateTargetType(resolvedType, a.token.range, unwound?.doc || this);
|
|
4756
4828
|
if (msgs) this._allMessages.push(...msgs);
|
|
4757
4829
|
}
|
|
4758
4830
|
continue;
|
|
@@ -5048,9 +5120,10 @@ const emitAnnotations = { jsonSchema: new AnnotationSpec({
|
|
|
5048
5120
|
|
|
5049
5121
|
//#endregion
|
|
5050
5122
|
//#region packages/core/src/defaults/expect-annotations.ts
|
|
5123
|
+
const NULLABLE_NOTE = "Also allowed on a nullable field (`T | null`, `T | undefined`): `null` passes, any other value must satisfy the constraint.";
|
|
5051
5124
|
const expectAnnotations = {
|
|
5052
5125
|
minLength: new AnnotationSpec({
|
|
5053
|
-
description:
|
|
5126
|
+
description: `Validates that a string or array has a minimum length. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.minLength 5name: string\`\`\``,
|
|
5054
5127
|
defType: ["array", "string"],
|
|
5055
5128
|
argument: [{
|
|
5056
5129
|
name: "length",
|
|
@@ -5064,7 +5137,7 @@ const expectAnnotations = {
|
|
|
5064
5137
|
}]
|
|
5065
5138
|
}),
|
|
5066
5139
|
maxLength: new AnnotationSpec({
|
|
5067
|
-
description:
|
|
5140
|
+
description: `Validates that a string or array has a maximum length. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.maxLength 5name: string\`\`\``,
|
|
5068
5141
|
defType: ["array", "string"],
|
|
5069
5142
|
argument: [{
|
|
5070
5143
|
name: "length",
|
|
@@ -5078,7 +5151,7 @@ const expectAnnotations = {
|
|
|
5078
5151
|
}]
|
|
5079
5152
|
}),
|
|
5080
5153
|
min: new AnnotationSpec({
|
|
5081
|
-
description:
|
|
5154
|
+
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
5155
|
defType: ["number"],
|
|
5083
5156
|
argument: [{
|
|
5084
5157
|
name: "minValue",
|
|
@@ -5092,7 +5165,7 @@ const expectAnnotations = {
|
|
|
5092
5165
|
}]
|
|
5093
5166
|
}),
|
|
5094
5167
|
max: new AnnotationSpec({
|
|
5095
|
-
description:
|
|
5168
|
+
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
5169
|
defType: ["number"],
|
|
5097
5170
|
argument: [{
|
|
5098
5171
|
name: "maxValue",
|
|
@@ -5106,11 +5179,11 @@ const expectAnnotations = {
|
|
|
5106
5179
|
}]
|
|
5107
5180
|
}),
|
|
5108
5181
|
int: new AnnotationSpec({
|
|
5109
|
-
description:
|
|
5182
|
+
description: `Validates that a number is an integer (no decimal places). ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.intage: number\`\`\``,
|
|
5110
5183
|
defType: ["number"]
|
|
5111
5184
|
}),
|
|
5112
5185
|
pattern: new AnnotationSpec({
|
|
5113
|
-
description:
|
|
5186
|
+
description: `Validates that a string matches a specific pattern. ${NULLABLE_NOTE}\n\n**Example:**\`\`\`atscript@expect.pattern "[a-z]+", "u"name: string\`\`\``,
|
|
5114
5187
|
defType: ["string"],
|
|
5115
5188
|
multiple: true,
|
|
5116
5189
|
mergeStrategy: "append",
|
|
@@ -5214,7 +5287,7 @@ const expectAnnotations = {
|
|
|
5214
5287
|
}),
|
|
5215
5288
|
array: {
|
|
5216
5289
|
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",
|
|
5290
|
+
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
5291
|
nodeType: ["prop"],
|
|
5219
5292
|
multiple: false,
|
|
5220
5293
|
argument: [{
|
|
@@ -5228,12 +5301,15 @@ const expectAnnotations = {
|
|
|
5228
5301
|
const errors = [];
|
|
5229
5302
|
const definition = field.getDefinition();
|
|
5230
5303
|
if (!definition) return errors;
|
|
5231
|
-
let
|
|
5304
|
+
let def = definition;
|
|
5305
|
+
let defDoc = doc;
|
|
5232
5306
|
if (isRef(definition)) {
|
|
5233
|
-
const
|
|
5234
|
-
|
|
5235
|
-
|
|
5236
|
-
|
|
5307
|
+
const unwound = doc.unwindType(definition.id, definition.chain);
|
|
5308
|
+
def = unwound?.def;
|
|
5309
|
+
defDoc = unwound?.doc || doc;
|
|
5310
|
+
}
|
|
5311
|
+
const members = nonNullishMembers(def, defDoc);
|
|
5312
|
+
if (!(members ? members.length > 0 && members.every((m) => isArray(m)) : isArray(def))) errors.push({
|
|
5237
5313
|
message: `@expect.array.uniqueItems requires an array field`,
|
|
5238
5314
|
severity: 1,
|
|
5239
5315
|
range: token.range
|
|
@@ -5322,7 +5398,7 @@ const metaAnnotations = {
|
|
|
5322
5398
|
passedWhenReferred: false
|
|
5323
5399
|
}),
|
|
5324
5400
|
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```",
|
|
5401
|
+
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
5402
|
defType: ["string", "boolean"],
|
|
5327
5403
|
argument: [{
|
|
5328
5404
|
name: "message",
|
|
@@ -6394,4 +6470,4 @@ function walkArrayElement(doc, arrayNode, prefix, parentOptional, flatMap, stack
|
|
|
6394
6470
|
}
|
|
6395
6471
|
|
|
6396
6472
|
//#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 };
|
|
6473
|
+
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 };
|