@atscript/core 0.1.33 → 0.1.35

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
@@ -35,7 +35,7 @@ const fs_promises = __toESM(require("fs/promises"));
35
35
  const glob = __toESM(require("glob"));
36
36
 
37
37
  //#region packages/core/src/parser/nodes/semantic-node.ts
38
- function _define_property$15(obj, key, value) {
38
+ function _define_property$16(obj, key, value) {
39
39
  if (key in obj) Object.defineProperty(obj, key, {
40
40
  value,
41
41
  enumerable: true,
@@ -99,6 +99,7 @@ else this.annotationsCounter.set(name, 1);
99
99
  }
100
100
  define(node) {
101
101
  this.definition = node;
102
+ node.ownerNode = this;
102
103
  return this;
103
104
  }
104
105
  get def() {
@@ -145,14 +146,15 @@ else this.annotationsCounter.set(name, 1);
145
146
  return this.definition;
146
147
  }
147
148
  constructor(entity) {
148
- _define_property$15(this, "entity", void 0);
149
- _define_property$15(this, "tokens", void 0);
150
- _define_property$15(this, "isGroup", void 0);
151
- _define_property$15(this, "definition", void 0);
152
- _define_property$15(this, "annotations", void 0);
153
- _define_property$15(this, "annotationsCounter", void 0);
154
- _define_property$15(this, "__typeId", void 0);
155
- _define_property$15(this, "_documentation", void 0);
149
+ _define_property$16(this, "entity", void 0);
150
+ _define_property$16(this, "tokens", void 0);
151
+ _define_property$16(this, "isGroup", void 0);
152
+ _define_property$16(this, "definition", void 0);
153
+ _define_property$16(this, "annotations", void 0);
154
+ _define_property$16(this, "annotationsCounter", void 0);
155
+ _define_property$16(this, "__typeId", void 0);
156
+ _define_property$16(this, "ownerNode", void 0);
157
+ _define_property$16(this, "_documentation", void 0);
156
158
  this.entity = entity;
157
159
  this.isGroup = false;
158
160
  }
@@ -249,7 +251,7 @@ var SemanticConstNode = class extends SemanticNode {
249
251
 
250
252
  //#endregion
251
253
  //#region packages/core/src/parser/nodes/group-node.ts
252
- function _define_property$14(obj, key, value) {
254
+ function _define_property$15(obj, key, value) {
253
255
  if (key in obj) Object.defineProperty(obj, key, {
254
256
  value,
255
257
  enumerable: true,
@@ -294,7 +296,7 @@ var SemanticGroup = class extends SemanticNode {
294
296
  return s;
295
297
  }
296
298
  constructor(nodes = [], operator) {
297
- super("group"), _define_property$14(this, "nodes", void 0), _define_property$14(this, "operator", void 0), _define_property$14(this, "isGroup", void 0), this.nodes = nodes, this.operator = operator, this.isGroup = true;
299
+ super("group"), _define_property$15(this, "nodes", void 0), _define_property$15(this, "operator", void 0), _define_property$15(this, "isGroup", void 0), this.nodes = nodes, this.operator = operator, this.isGroup = true;
298
300
  }
299
301
  };
300
302
 
@@ -316,7 +318,7 @@ var SemanticImportNode = class extends SemanticNode {
316
318
 
317
319
  //#endregion
318
320
  //#region packages/core/src/parser/nodes/interface-node.ts
319
- function _define_property$13(obj, key, value) {
321
+ function _define_property$14(obj, key, value) {
320
322
  if (key in obj) Object.defineProperty(obj, key, {
321
323
  value,
322
324
  enumerable: true,
@@ -364,13 +366,13 @@ var SemanticInterfaceNode = class extends SemanticNode {
364
366
  return s;
365
367
  }
366
368
  constructor() {
367
- super("interface"), _define_property$13(this, "_extendsTokens", []);
369
+ super("interface"), _define_property$14(this, "_extendsTokens", []);
368
370
  }
369
371
  };
370
372
 
371
373
  //#endregion
372
374
  //#region packages/core/src/parser/token.ts
373
- function _define_property$12(obj, key, value) {
375
+ function _define_property$13(obj, key, value) {
374
376
  if (key in obj) Object.defineProperty(obj, key, {
375
377
  value,
376
378
  enumerable: true,
@@ -416,43 +418,46 @@ var Token = class Token {
416
418
  return this._data.type === "annotation";
417
419
  }
418
420
  constructor(_data) {
419
- _define_property$12(this, "_data", void 0);
421
+ _define_property$13(this, "_data", void 0);
420
422
  /**
421
423
  * Set this to file path (e.g. "./src/file.as") for path token in import statement
422
- */ _define_property$12(this, "fromPath", void 0);
424
+ */ _define_property$13(this, "fromPath", void 0);
423
425
  /**
424
426
  * All definitions that exported must be marked with this flag
425
- */ _define_property$12(this, "exported", void 0);
427
+ */ _define_property$13(this, "exported", void 0);
426
428
  /**
427
429
  * All the definitions must be marked with this flag
428
- */ _define_property$12(this, "isDefinition", void 0);
430
+ */ _define_property$13(this, "isDefinition", void 0);
429
431
  /**
430
432
  * All the references must be marked with this flag
431
- */ _define_property$12(this, "isReference", void 0);
433
+ */ _define_property$13(this, "isReference", void 0);
432
434
  /**
433
435
  * All the import tokens must be marked with this flag
434
- */ _define_property$12(this, "imported", void 0);
436
+ */ _define_property$13(this, "imported", void 0);
435
437
  /**
436
438
  * Refs chained via . or ["propName"] are marked with this flag
437
- */ _define_property$12(this, "isChain", void 0);
439
+ */ _define_property$13(this, "isChain", void 0);
438
440
  /**
439
441
  * Prop patterns ([*] or [regexp]) are storing patterns here
440
- */ _define_property$12(this, "pattern", void 0);
441
- _define_property$12(this, "parentNode", void 0);
442
+ */ _define_property$13(this, "pattern", void 0);
443
+ _define_property$13(this, "parentNode", void 0);
442
444
  /**
443
445
  * Only for annotation arguments: reference to their annotation token
444
- */ _define_property$12(this, "annotationRef", void 0);
445
- _define_property$12(this, "index", void 0);
446
+ */ _define_property$13(this, "annotationRef", void 0);
447
+ _define_property$13(this, "index", void 0);
446
448
  /**
447
449
  * Block type
448
- */ _define_property$12(this, "blockType", void 0);
450
+ */ _define_property$13(this, "blockType", void 0);
451
+ /**
452
+ * Parsed query expression tree (for query-type annotation arguments)
453
+ */ _define_property$13(this, "queryNode", void 0);
449
454
  this._data = _data;
450
455
  }
451
456
  };
452
457
 
453
458
  //#endregion
454
459
  //#region packages/core/src/parser/nodes/primitive-node.ts
455
- function _define_property$11(obj, key, value) {
460
+ function _define_property$12(obj, key, value) {
456
461
  if (key in obj) Object.defineProperty(obj, key, {
457
462
  value,
458
463
  enumerable: true,
@@ -501,7 +506,7 @@ else if (value.length > 0) this.annotations.push(toAnnotationTokens(name, value[
501
506
  return indent + s.split("\n").join(`\n${indent}`);
502
507
  }
503
508
  constructor(_id, config, parentKey = "", annotationTree) {
504
- super("primitive"), _define_property$11(this, "_id", void 0), _define_property$11(this, "config", void 0), _define_property$11(this, "parentKey", void 0), _define_property$11(this, "annotationTree", void 0), _define_property$11(this, "type", void 0), _define_property$11(this, "props", void 0), _define_property$11(this, "tags", void 0), this._id = _id, this.config = config, this.parentKey = parentKey, this.annotationTree = annotationTree;
509
+ super("primitive"), _define_property$12(this, "_id", void 0), _define_property$12(this, "config", void 0), _define_property$12(this, "parentKey", void 0), _define_property$12(this, "annotationTree", void 0), _define_property$12(this, "type", void 0), _define_property$12(this, "props", void 0), _define_property$12(this, "tags", void 0), this._id = _id, this.config = config, this.parentKey = parentKey, this.annotationTree = annotationTree;
505
510
  this.props = new Map();
506
511
  this.tags = new Set([_id, ...config?.tags || []]);
507
512
  for (const [ext, def] of Object.entries(config.extensions || {})) {
@@ -622,7 +627,7 @@ var SemanticPropNode = class extends SemanticNode {
622
627
 
623
628
  //#endregion
624
629
  //#region packages/core/src/parser/nodes/ref-node.ts
625
- function _define_property$10(obj, key, value) {
630
+ function _define_property$11(obj, key, value) {
626
631
  if (key in obj) Object.defineProperty(obj, key, {
627
632
  value,
628
633
  enumerable: true,
@@ -674,13 +679,13 @@ var SemanticRefNode = class extends SemanticNode {
674
679
  return indent + s.split("\n").join(`\n${indent}`);
675
680
  }
676
681
  constructor() {
677
- super("ref"), _define_property$10(this, "_chain", []), _define_property$10(this, "_dots", []);
682
+ super("ref"), _define_property$11(this, "_chain", []), _define_property$11(this, "_dots", []);
678
683
  }
679
684
  };
680
685
 
681
686
  //#endregion
682
687
  //#region packages/core/src/parser/nodes/structure-node.ts
683
- function _define_property$9(obj, key, value) {
688
+ function _define_property$10(obj, key, value) {
684
689
  if (key in obj) Object.defineProperty(obj, key, {
685
690
  value,
686
691
  enumerable: true,
@@ -695,10 +700,12 @@ var SemanticStructureNode = class extends SemanticGroup {
695
700
  * Shortcut to set props, used as utility
696
701
  */ setProps(props$1) {
697
702
  this.nodes = props$1;
698
- for (const prop of props$1) this.props.set(prop.id, prop);
703
+ for (const prop of props$1) {
704
+ prop.ownerNode = this;
705
+ this.props.set(prop.id, prop);
706
+ }
699
707
  }
700
708
  registerAtDocument(doc) {
701
- super.registerAtDocument(doc);
702
709
  const block$2 = this.token("identifier");
703
710
  block$2.blockType = "structure";
704
711
  doc.blocksIndex.add(block$2);
@@ -721,8 +728,10 @@ var SemanticStructureNode = class extends SemanticGroup {
721
728
  doc.registerMessage(token, "Non-prop node");
722
729
  continue;
723
730
  }
731
+ node.ownerNode = this;
724
732
  this.props.set(name, node);
725
733
  }
734
+ super.registerAtDocument(doc);
726
735
  }
727
736
  addVirtualProp(opts) {
728
737
  const token = opts.refToken || this.token("identifier");
@@ -750,11 +759,12 @@ var SemanticStructureNode = class extends SemanticGroup {
750
759
  }
751
760
  prop.define(ref$1);
752
761
  } else prop.define(opts.type);
762
+ prop.ownerNode = this;
753
763
  this.nodes.push(prop);
754
764
  this.props.set(opts.name, prop);
755
765
  }
756
766
  constructor() {
757
- super(), _define_property$9(this, "props", new Map());
767
+ super(), _define_property$10(this, "props", new Map());
758
768
  this.entity = "structure";
759
769
  }
760
770
  };
@@ -787,6 +797,84 @@ var SemanticTypeNode = class extends SemanticNode {
787
797
  }
788
798
  };
789
799
 
800
+ //#endregion
801
+ //#region packages/core/src/parser/nodes/query-nodes.ts
802
+ function _define_property$9(obj, key, value) {
803
+ if (key in obj) Object.defineProperty(obj, key, {
804
+ value,
805
+ enumerable: true,
806
+ configurable: true,
807
+ writable: true
808
+ });
809
+ else obj[key] = value;
810
+ return obj;
811
+ }
812
+ var SemanticQueryNode = class extends SemanticNode {
813
+ registerAtDocument(doc) {
814
+ this.propagateQueryArgToken(this.expression);
815
+ this.expression.registerAtDocument(doc);
816
+ }
817
+ propagateQueryArgToken(expr) {
818
+ if ("left" in expr) {
819
+ expr.left.queryArgToken = this.sourceToken;
820
+ const right = expr.right;
821
+ if (right && "fieldRef" in right) right.queryArgToken = this.sourceToken;
822
+ } else if ("operands" in expr) for (const operand of expr.operands) this.propagateQueryArgToken(operand);
823
+ }
824
+ constructor() {
825
+ super("query"), _define_property$9(this, "expression", void 0), _define_property$9(this, "sourceToken", void 0);
826
+ }
827
+ };
828
+ var SemanticQueryLogicalNode = class extends SemanticNode {
829
+ registerAtDocument(doc) {
830
+ for (const operand of this.operands) operand.registerAtDocument(doc);
831
+ }
832
+ constructor() {
833
+ super("query-logical"), _define_property$9(this, "operator", void 0), _define_property$9(this, "operands", void 0);
834
+ }
835
+ };
836
+ var SemanticQueryComparisonNode = class extends SemanticNode {
837
+ registerAtDocument(doc) {
838
+ this.left.registerAtDocument(doc);
839
+ this.right?.registerAtDocument(doc);
840
+ }
841
+ constructor() {
842
+ super("query-comparison"), _define_property$9(this, "left", void 0), _define_property$9(this, "operator", void 0), _define_property$9(this, "right", void 0);
843
+ }
844
+ };
845
+ var SemanticQueryFieldRefNode = class extends SemanticNode {
846
+ registerAtDocument(doc) {
847
+ if (this.typeRef) {
848
+ this.typeRef.isReference = true;
849
+ this.typeRef.parentNode = this;
850
+ doc.referred.push(this.typeRef);
851
+ doc.tokensIndex.add(this.typeRef);
852
+ }
853
+ this.fieldRef.parentNode = this;
854
+ doc.tokensIndex.add(this.fieldRef);
855
+ doc.queryFieldRefs.push(this);
856
+ }
857
+ constructor() {
858
+ super("query-field-ref"), _define_property$9(this, "typeRef", void 0), _define_property$9(this, "fieldRef", void 0), _define_property$9(this, "queryArgToken", void 0);
859
+ }
860
+ };
861
+ var SemanticQueryValueNode = class extends SemanticNode {
862
+ registerAtDocument(doc) {
863
+ doc.tokensIndex.add(this.valueToken);
864
+ }
865
+ constructor() {
866
+ super("query-value"), _define_property$9(this, "valueToken", void 0);
867
+ }
868
+ };
869
+ var SemanticQueryValueListNode = class extends SemanticNode {
870
+ registerAtDocument(doc) {
871
+ for (const v of this.values) v.registerAtDocument(doc);
872
+ }
873
+ constructor() {
874
+ super("query-value-list"), _define_property$9(this, "values", void 0);
875
+ }
876
+ };
877
+
790
878
  //#endregion
791
879
  //#region packages/core/src/parser/nodes/index.ts
792
880
  const $n = {
@@ -839,6 +927,15 @@ function isPrimitive(node) {
839
927
  function isAnnotate(node) {
840
928
  return node?.entity === "annotate";
841
929
  }
930
+ function isQueryLogical(node) {
931
+ return node?.operands !== undefined;
932
+ }
933
+ function isQueryComparison(node) {
934
+ return node?.left !== undefined;
935
+ }
936
+ function isQueryFieldRef(node) {
937
+ return node?.fieldRef !== undefined;
938
+ }
842
939
 
843
940
  //#endregion
844
941
  //#region packages/core/src/annotations/annotation-spec.ts
@@ -862,7 +959,7 @@ var AnnotationSpec = class {
862
959
  return this.arguments.map((arg, index) => {
863
960
  const placeholderIndex = index + 1;
864
961
  const defaultValue = this.getDefaultValueForType(arg.name, arg.type);
865
- const quote = arg.type === "string" ? `'` : "";
962
+ const quote = arg.type === "string" ? `'` : arg.type === "query" ? "`" : "";
866
963
  return `${quote}\${${placeholderIndex}:${defaultValue}}${quote}`;
867
964
  }).join(", ");
868
965
  }
@@ -871,6 +968,8 @@ var AnnotationSpec = class {
871
968
  case "string": return tokenType === "text" ? undefined : "string expected.";
872
969
  case "number": return tokenType === "number" ? undefined : "number expected.";
873
970
  case "boolean": return tokenType === "identifier" ? undefined : "boolean expected.";
971
+ case "ref": return tokenType === "identifier" ? undefined : "type reference expected.";
972
+ case "query": return tokenType === "query" ? undefined : "query expression expected (use backticks).";
874
973
  default: return `unknown type "${type$1}".`;
875
974
  }
876
975
  }
@@ -963,6 +1062,8 @@ else if (isGroup(def) && def.entity !== "tuple") defEntity = def.op === "&" ? "i
963
1062
  case "string": return name;
964
1063
  case "number": return "0";
965
1064
  case "boolean": return "true";
1065
+ case "ref": return "TypeName";
1066
+ case "query": return "field = value";
966
1067
  default: return "";
967
1068
  }
968
1069
  }
@@ -980,10 +1081,13 @@ function resolveAnnotation(name, annotationsTree) {
980
1081
  const parts = name.split(".");
981
1082
  let current = annotationsTree;
982
1083
  for (const part of parts) {
1084
+ if (part === "$self") return undefined;
983
1085
  if (!current || isAnnotationSpec(current)) return undefined;
984
1086
  current = current[part];
985
1087
  }
986
- return isAnnotationSpec(current) ? current : undefined;
1088
+ if (isAnnotationSpec(current)) return current;
1089
+ if (current && !isAnnotationSpec(current) && current.$self) return current.$self;
1090
+ return undefined;
987
1091
  }
988
1092
 
989
1093
  //#endregion
@@ -1100,6 +1204,204 @@ else if (SUPPORTED_TS_CONFIG_FORMATS.includes(ext)) {
1100
1204
  }
1101
1205
  }
1102
1206
 
1207
+ //#endregion
1208
+ //#region packages/core/src/defaults/db-query-lsp.ts
1209
+ function getQueryScope(queryArgToken, doc) {
1210
+ const annotationRef = queryArgToken.annotationRef;
1211
+ if (!annotationRef) return undefined;
1212
+ const owner = queryArgToken.parentNode;
1213
+ if (!owner) return undefined;
1214
+ const annotationName = annotationRef.text.slice(1);
1215
+ if (annotationName === "db.view.filter") return getViewFilterScope(owner);
1216
+ if (annotationName === "db.view.joins") return getViewJoinsScope(owner, queryArgToken);
1217
+ if (annotationName === "db.rel.filter") return getRelFilterScope(owner);
1218
+ return undefined;
1219
+ }
1220
+ function getViewFilterScope(owner) {
1221
+ const forAnnotations = owner.annotations?.filter((a) => a.name === "db.view.for");
1222
+ const entryTypeName = forAnnotations?.[0]?.args[0]?.text;
1223
+ if (!entryTypeName) return undefined;
1224
+ const allowedTypes = [entryTypeName];
1225
+ const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
1226
+ if (joinsAnnotations) {
1227
+ for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
1228
+ }
1229
+ return {
1230
+ allowedTypes,
1231
+ unqualifiedTarget: entryTypeName
1232
+ };
1233
+ }
1234
+ function getViewJoinsScope(owner, queryArgToken) {
1235
+ const forAnnotations = owner.annotations?.filter((a) => a.name === "db.view.for");
1236
+ const entryTypeName = forAnnotations?.[0]?.args[0]?.text;
1237
+ if (!entryTypeName) return undefined;
1238
+ const joinsAnnotation = owner.annotations?.find((a) => a.name === "db.view.joins" && a.args.includes(queryArgToken));
1239
+ const joinTargetName = joinsAnnotation?.args[0]?.text;
1240
+ if (!joinTargetName) return undefined;
1241
+ return {
1242
+ allowedTypes: [joinTargetName, entryTypeName],
1243
+ unqualifiedTarget: entryTypeName
1244
+ };
1245
+ }
1246
+ function getRelFilterScope(owner) {
1247
+ let def = owner.getDefinition();
1248
+ if (isArray(def)) def = def?.getDefinition();
1249
+ if (!isRef(def)) return undefined;
1250
+ const targetTypeName = def.id;
1251
+ const allowedTypes = [targetTypeName];
1252
+ const viaAnnotation = owner.annotations?.find((a) => a.name === "db.rel.via");
1253
+ if (viaAnnotation?.args[0]) allowedTypes.push(viaAnnotation.args[0].text);
1254
+ return {
1255
+ allowedTypes,
1256
+ unqualifiedTarget: targetTypeName
1257
+ };
1258
+ }
1259
+ function resolveQueryFieldRef(fieldRefNode, doc, scope) {
1260
+ const typeName = fieldRefNode.typeRef?.text ?? scope.unqualifiedTarget;
1261
+ if (!typeName) return undefined;
1262
+ const fieldPath = fieldRefNode.fieldRef.text;
1263
+ const chain = fieldPath.split(".");
1264
+ const parentChain = chain.slice(0, -1);
1265
+ const parentUnwound = doc.unwindType(typeName, parentChain);
1266
+ if (!parentUnwound?.def) return undefined;
1267
+ const unwound = doc.unwindType(typeName, chain);
1268
+ if (!unwound?.node) return undefined;
1269
+ const prop = unwound.node;
1270
+ return {
1271
+ targetUri: parentUnwound.doc.id,
1272
+ doc: parentUnwound.doc,
1273
+ prop
1274
+ };
1275
+ }
1276
+ function getFieldsForType(doc, typeName) {
1277
+ const unwound = doc.unwindType(typeName);
1278
+ if (!unwound?.def) return [];
1279
+ let def = doc.mergeIntersection(unwound.def);
1280
+ if (isInterface(def)) {
1281
+ const resolved = doc.resolveInterfaceExtends(def);
1282
+ if (resolved) def = resolved;
1283
+ else def = def.getDefinition() || def;
1284
+ }
1285
+ if (isStructure(def) || isInterface(def)) return Array.from(def.props.values());
1286
+ return [];
1287
+ }
1288
+ function getQueryCompletionScope(queryArgToken, doc) {
1289
+ const scope = getQueryScope(queryArgToken, doc);
1290
+ if (!scope) return undefined;
1291
+ return {
1292
+ typeNames: scope.allowedTypes,
1293
+ unqualifiedTarget: scope.unqualifiedTarget,
1294
+ getFields: (typeName) => getFieldsForType(doc, typeName)
1295
+ };
1296
+ }
1297
+ const SYMBOLIC_OPS$1 = new Set([
1298
+ "=",
1299
+ "!=",
1300
+ ">",
1301
+ ">=",
1302
+ "<",
1303
+ "<="
1304
+ ]);
1305
+ const KEYWORD_OPS = new Set([
1306
+ "in",
1307
+ "matches",
1308
+ "exists"
1309
+ ]);
1310
+ const LOGICAL_KEYWORDS = new Set([
1311
+ "and",
1312
+ "or",
1313
+ "not"
1314
+ ]);
1315
+ const VALUE_KEYWORDS$1 = new Set([
1316
+ "true",
1317
+ "false",
1318
+ "null",
1319
+ "undefined"
1320
+ ]);
1321
+ function analyzeQueryCursorContext(textBeforeCursor) {
1322
+ const trimmed = textBeforeCursor.trimEnd();
1323
+ const hasTrailingSpace = textBeforeCursor.length > trimmed.length;
1324
+ if (trimmed.length === 0) return { type: "field-start" };
1325
+ if (trimmed.endsWith(".")) {
1326
+ const before = trimmed.slice(0, -1).trimEnd();
1327
+ const match = /(\w+)$/u.exec(before);
1328
+ if (match) return {
1329
+ type: "after-dot",
1330
+ typeName: match[1]
1331
+ };
1332
+ return { type: "field-start" };
1333
+ }
1334
+ const tokens$1 = tokenizeQueryText(trimmed);
1335
+ if (tokens$1.length === 0) return { type: "field-start" };
1336
+ const last = tokens$1[tokens$1.length - 1];
1337
+ if (LOGICAL_KEYWORDS.has(last) || last === "(") return { type: "field-start" };
1338
+ if (SYMBOLIC_OPS$1.has(last)) return { type: "after-operator" };
1339
+ if (last === "in" || last === "matches") return { type: "after-operator" };
1340
+ if (last === "exists") return { type: "after-comparison" };
1341
+ if (VALUE_KEYWORDS$1.has(last)) return { type: "after-comparison" };
1342
+ if (/^['"]/.test(last) || /^\d/.test(last)) return { type: "after-comparison" };
1343
+ if (tokens$1.length >= 2) {
1344
+ const prev = tokens$1[tokens$1.length - 2];
1345
+ if (SYMBOLIC_OPS$1.has(prev) || KEYWORD_OPS.has(prev)) return { type: "after-comparison" };
1346
+ }
1347
+ if (/^\w+$/u.test(last)) {
1348
+ if (!hasTrailingSpace) return { type: "field-start" };
1349
+ return { type: "after-field" };
1350
+ }
1351
+ return { type: "field-start" };
1352
+ }
1353
+ /**
1354
+ * Simple tokenizer for query text — splits into identifiers, operators, and punctuation.
1355
+ * Does NOT need to handle all edge cases; just enough for cursor context analysis.
1356
+ */ function tokenizeQueryText(text$2) {
1357
+ const tokens$1 = [];
1358
+ let i = 0;
1359
+ while (i < text$2.length) {
1360
+ if (/\s/.test(text$2[i])) {
1361
+ i++;
1362
+ continue;
1363
+ }
1364
+ if (text$2[i] === "'" || text$2[i] === "\"") {
1365
+ const quote = text$2[i];
1366
+ let j = i + 1;
1367
+ while (j < text$2.length && text$2[j] !== quote) {
1368
+ if (text$2[j] === "\\") j++;
1369
+ j++;
1370
+ }
1371
+ tokens$1.push(text$2.slice(i, j + 1));
1372
+ i = j + 1;
1373
+ continue;
1374
+ }
1375
+ if (i + 1 < text$2.length) {
1376
+ const two = text$2.slice(i, i + 2);
1377
+ if (two === "!=" || two === ">=" || two === "<=") {
1378
+ tokens$1.push(two);
1379
+ i += 2;
1380
+ continue;
1381
+ }
1382
+ }
1383
+ if ("=><(),".includes(text$2[i])) {
1384
+ tokens$1.push(text$2[i]);
1385
+ i++;
1386
+ continue;
1387
+ }
1388
+ if (text$2[i] === ".") {
1389
+ tokens$1.push(".");
1390
+ i++;
1391
+ continue;
1392
+ }
1393
+ if (/[\w]/u.test(text$2[i])) {
1394
+ let j = i;
1395
+ while (j < text$2.length && /[\w]/u.test(text$2[j])) j++;
1396
+ tokens$1.push(text$2.slice(i, j));
1397
+ i = j;
1398
+ continue;
1399
+ }
1400
+ i++;
1401
+ }
1402
+ return tokens$1;
1403
+ }
1404
+
1103
1405
  //#endregion
1104
1406
  //#region packages/core/src/parser/id-registry.ts
1105
1407
  function _define_property$7(obj, key, value) {
@@ -1290,40 +1592,21 @@ var NodeIterator = class NodeIterator {
1290
1592
  }
1291
1593
  };
1292
1594
 
1293
- //#endregion
1294
- //#region packages/core/src/parser/utils.ts
1295
- function toVsCodeRange(start, end, startOffset = 0, endOffset = 0) {
1296
- return {
1297
- start: {
1298
- line: start.row - 1,
1299
- character: start.col + startOffset
1300
- },
1301
- end: {
1302
- line: end.row - 1,
1303
- character: end.col + endOffset
1304
- }
1305
- };
1306
- }
1307
- function resolveAtscriptFromPath(from, id) {
1308
- return `file://${path.default.join(id.slice(7).split("/").slice(0, -1).join("/"), from)}.as`;
1309
- }
1310
- function getRelPath(fromUri, toUri) {
1311
- const fromPath = new url.URL(fromUri).pathname;
1312
- const toPath = new url.URL(toUri).pathname;
1313
- const relPath = path.default.relative(path.default.dirname(fromPath), toPath);
1314
- const { dir, name } = path.default.parse(relPath);
1315
- const prefix = dir.startsWith("..") ? "" : "./";
1316
- return `${prefix}${dir ? `${dir}/` : ""}${name}`;
1317
- }
1318
-
1319
1595
  //#endregion
1320
1596
  //#region packages/core/src/tokenizer/tokens/a-identifier.token.ts
1321
- const AIdentifierToken = new __prostojs_parser.BasicNode({
1322
- icon: "@",
1323
- tokens: [RegExp("@[\\p{ID_Continue}$.]*", "u"), RegExp("[^\\p{ID_Continue}$.]", "u")],
1324
- tokenOE: "-eject"
1325
- }).mapContent("text", "join-clear").onMatch((context) => {
1326
- context.customData.type = "annotation";
1597
+ const AIdentifierToken = new __prostojs_parser.Node({
1598
+ name: "annotation",
1599
+ start: { token: RegExp("@[\\p{ID_Continue}$.]*", "u") },
1600
+ end: {
1601
+ token: RegExp("[^\\p{ID_Continue}$.]", "u"),
1602
+ eject: true
1603
+ },
1604
+ eofClose: true,
1605
+ data: {
1606
+ type: "annotation",
1607
+ text: ""
1608
+ },
1609
+ mapContent: "text"
1327
1610
  });
1328
1611
 
1329
1612
  //#endregion
@@ -1333,33 +1616,59 @@ const pairs = {
1333
1616
  "(": ")",
1334
1617
  "[": "]"
1335
1618
  };
1336
- const BlockToken = new __prostojs_parser.BasicNode({
1337
- label: "block",
1338
- icon: "→",
1339
- tokens: [RegExp("(?<text>[([{])", "u"), (context) => pairs[context.getCustomData().text] || ""],
1340
- tokenOE: "omit-omit",
1341
- skipToken: /\s/u
1342
- }).onMatch((context) => {
1343
- context.customData.type = "block";
1619
+ const BlockToken = new __prostojs_parser.Node({
1620
+ name: "block",
1621
+ start: {
1622
+ token: RegExp("(?<text>[([{])", "u"),
1623
+ omit: true
1624
+ },
1625
+ end: {
1626
+ token: (ctx) => pairs[ctx.node.data.text] || "",
1627
+ omit: true
1628
+ },
1629
+ skip: /\s/u,
1630
+ eofClose: true,
1631
+ data: {
1632
+ type: "block",
1633
+ text: ""
1634
+ }
1344
1635
  });
1345
1636
 
1346
1637
  //#endregion
1347
1638
  //#region packages/core/src/tokenizer/tokens/comment.token.ts
1348
- const inline = new __prostojs_parser.BasicNode({
1349
- label: "inline-comment",
1350
- icon: "“",
1351
- tokens: ["//", /$/mu],
1352
- tokenOE: "omit-omit"
1353
- }).mapContent("text", "join-clear").popsAtEOFSource(true).onMatch((context) => {
1354
- context.customData.type = "comment";
1639
+ const inline = new __prostojs_parser.Node({
1640
+ name: "inline-comment",
1641
+ start: {
1642
+ token: "//",
1643
+ omit: true
1644
+ },
1645
+ end: {
1646
+ token: /$/mu,
1647
+ omit: true
1648
+ },
1649
+ eofClose: true,
1650
+ data: {
1651
+ type: "comment",
1652
+ text: ""
1653
+ },
1654
+ mapContent: "text"
1355
1655
  });
1356
- const block$1 = new __prostojs_parser.BasicNode({
1357
- label: "block-comment",
1358
- icon: "“",
1359
- tokens: ["/*", "*/"],
1360
- tokenOE: "omit-omit"
1361
- }).mapContent("text", "join-clear").popsAtEOFSource(true).onMatch((context) => {
1362
- context.customData.type = "comment";
1656
+ const block$1 = new __prostojs_parser.Node({
1657
+ name: "block-comment",
1658
+ start: {
1659
+ token: "/*",
1660
+ omit: true
1661
+ },
1662
+ end: {
1663
+ token: "*/",
1664
+ omit: true
1665
+ },
1666
+ eofClose: true,
1667
+ data: {
1668
+ type: "comment",
1669
+ text: ""
1670
+ },
1671
+ mapContent: "text"
1363
1672
  });
1364
1673
  const commentNodes = {
1365
1674
  inline,
@@ -1369,58 +1678,141 @@ const commentNodes = {
1369
1678
 
1370
1679
  //#endregion
1371
1680
  //#region packages/core/src/tokenizer/tokens/identifier.token.ts
1372
- const IdentifierToken = new __prostojs_parser.BasicNode({
1373
- icon: "I",
1374
- tokens: [RegExp("[\\p{ID_Start}$_][\\p{ID_Continue}$]*", "u"), RegExp("[^\\p{ID_Continue}$]", "u")],
1375
- tokenOE: "consume-eject"
1376
- }).mapContent("text", "join-clear").onMatch((context) => {
1377
- context.customData.type = "identifier";
1681
+ const IdentifierToken = new __prostojs_parser.Node({
1682
+ name: "identifier",
1683
+ start: { token: RegExp("[\\p{ID_Start}$_][\\p{ID_Continue}$]*", "u") },
1684
+ end: {
1685
+ token: RegExp("[^\\p{ID_Continue}$]", "u"),
1686
+ eject: true
1687
+ },
1688
+ eofClose: true,
1689
+ data: {
1690
+ type: "identifier",
1691
+ text: ""
1692
+ },
1693
+ mapContent: "text"
1378
1694
  });
1379
1695
 
1380
1696
  //#endregion
1381
1697
  //#region packages/core/src/tokenizer/tokens/number.token.ts
1382
- const NumberToken = new __prostojs_parser.BasicNode({
1383
- icon: "N",
1384
- tokens: [/[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?/u, /[^\d]/u],
1385
- tokenOE: "-eject"
1386
- }).mapContent("text", "join-clear").onMatch((context) => {
1387
- context.customData.type = "number";
1698
+ const NumberToken = new __prostojs_parser.Node({
1699
+ name: "number",
1700
+ start: { token: /[-+]?(?:\d*\.\d+|\d+)(?:[eE][-+]?\d+)?/u },
1701
+ end: {
1702
+ token: /[^\d]/u,
1703
+ eject: true
1704
+ },
1705
+ eofClose: true,
1706
+ data: {
1707
+ type: "number",
1708
+ text: ""
1709
+ },
1710
+ mapContent: "text"
1388
1711
  });
1389
1712
 
1390
1713
  //#endregion
1391
1714
  //#region packages/core/src/tokenizer/tokens/punctuation.token.ts
1392
- const PunctuationToken = new __prostojs_parser.BasicNode({
1393
- tokens: [RegExp("(?<text>[\\n!&+,./:;=?|])", "u"), ""],
1394
- tokenOE: "omit-omit",
1395
- icon: "..."
1396
- }).onMatch((context) => {
1397
- context.customData.type = "punctuation";
1715
+ const PunctuationToken = new __prostojs_parser.Node({
1716
+ name: "punctuation",
1717
+ start: {
1718
+ token: RegExp("(?<text>[\\n!&+,./:;=?|])", "u"),
1719
+ omit: true
1720
+ },
1721
+ end: {
1722
+ token: "",
1723
+ omit: true
1724
+ },
1725
+ eofClose: true,
1726
+ data: {
1727
+ type: "punctuation",
1728
+ text: ""
1729
+ }
1730
+ });
1731
+
1732
+ //#endregion
1733
+ //#region packages/core/src/tokenizer/tokens/query-operator.token.ts
1734
+ const QueryOperatorToken = new __prostojs_parser.Node({
1735
+ name: "punctuation",
1736
+ start: {
1737
+ token: RegExp("(?<text>!=|>=|<=|[=><])", "u"),
1738
+ omit: true
1739
+ },
1740
+ end: {
1741
+ token: "",
1742
+ omit: true
1743
+ },
1744
+ eofClose: true,
1745
+ data: {
1746
+ type: "punctuation",
1747
+ text: ""
1748
+ }
1749
+ });
1750
+
1751
+ //#endregion
1752
+ //#region packages/core/src/tokenizer/tokens/query.token.ts
1753
+ const QueryToken = new __prostojs_parser.Node({
1754
+ name: "query",
1755
+ start: {
1756
+ token: /`/u,
1757
+ omit: true
1758
+ },
1759
+ end: {
1760
+ token: /`/u,
1761
+ omit: true
1762
+ },
1763
+ skip: /\s/u,
1764
+ eofClose: true,
1765
+ data: {
1766
+ type: "query",
1767
+ text: ""
1768
+ }
1398
1769
  });
1399
1770
 
1400
1771
  //#endregion
1401
1772
  //#region packages/core/src/tokenizer/tokens/regexp.token.ts
1402
1773
  const REGEXP_LITERAL_RE = /\/(?![/*])(?:\\.|\[.*?]|[^/\\\n\r[])*\/[dgimsuy]*/;
1403
- const RegExpToken = new __prostojs_parser.BasicNode({
1404
- label: "regexp",
1405
- icon: "RG",
1406
- tokens: [REGEXP_LITERAL_RE, ""],
1407
- tokenOE: "omit-omit"
1408
- }).onMatch((ctx) => {
1409
- ctx.customData.type = "regexp";
1410
- ctx.customData.text = ctx.matched[0];
1774
+ const RegExpToken = new __prostojs_parser.Node({
1775
+ name: "regexp",
1776
+ start: {
1777
+ token: REGEXP_LITERAL_RE,
1778
+ omit: true
1779
+ },
1780
+ end: {
1781
+ token: "",
1782
+ omit: true
1783
+ },
1784
+ eofClose: true,
1785
+ data: {
1786
+ type: "regexp",
1787
+ text: ""
1788
+ }
1789
+ }).onOpen((node, match) => {
1790
+ node.data.text = match?.text ?? "";
1411
1791
  });
1412
1792
 
1413
1793
  //#endregion
1414
1794
  //#region packages/core/src/tokenizer/tokens/text.node.ts
1415
- const TextToken = new __prostojs_parser.BasicNode({
1416
- icon: "T",
1417
- tokens: [RegExp("(?<quote>[\"'])", "u"), (context) => new RegExp(`(?<end>${context.getCustomData().quote || ""}|\\n)`)],
1418
- backSlash: "-ignore",
1419
- tokenOE: "omit-omit"
1420
- }).mapContent("text", "join-clear").onMatch((context) => {
1421
- context.customData.type = "text";
1422
- }).onPop((context) => {
1423
- context.customData.multiline = context.customData.end === "\n";
1795
+ const TextToken = new __prostojs_parser.Node({
1796
+ name: "text",
1797
+ start: {
1798
+ token: RegExp("(?<quote>[\"'])", "u"),
1799
+ omit: true
1800
+ },
1801
+ end: {
1802
+ token: (ctx) => new RegExp(`(?<end>${ctx.node.data.quote || ""}|\\n)`),
1803
+ omit: true,
1804
+ backslash: true
1805
+ },
1806
+ eofClose: true,
1807
+ data: {
1808
+ type: "text",
1809
+ quote: "",
1810
+ end: "",
1811
+ text: ""
1812
+ },
1813
+ mapContent: "text"
1814
+ }).onClose((node) => {
1815
+ node.data.multiline = node.data.end === "\n";
1424
1816
  });
1425
1817
 
1426
1818
  //#endregion
@@ -1436,31 +1828,55 @@ const tokens = {
1436
1828
  number: NumberToken,
1437
1829
  text: TextToken,
1438
1830
  regexp: RegExpToken,
1831
+ query: QueryToken,
1439
1832
  root: undefined
1440
1833
  };
1441
- const root = new __prostojs_parser.BasicNode({
1442
- label: "root",
1443
- skipToken: /\s/u
1444
- }).addRecognizes(...tokens.comments, tokens.block, tokens.aIdentifier, tokens.identifier, tokens.text, tokens.number, tokens.punctuation);
1445
- tokens.root = root;
1446
- BlockToken.addRecognizes(tokens.regexp, ...tokens.comments, tokens.block, tokens.aIdentifier, tokens.identifier, tokens.text, tokens.number, tokens.punctuation);
1447
- const mapContent = (content) => content.map((item) => {
1448
- if (typeof item === "string") return {
1449
- type: "unknown",
1450
- text: item
1451
- };
1452
- const data = item.getCustomData();
1453
- data.getRange = () => toVsCodeRange(item.startPos, item.endPos, data.startOffset, data.endOffset);
1454
- return data;
1834
+ const root = new __prostojs_parser.Node({
1835
+ name: "root",
1836
+ skip: /\s/u,
1837
+ eofClose: true,
1838
+ recognizes: [
1839
+ ...commentNodes.all,
1840
+ BlockToken,
1841
+ QueryToken,
1842
+ AIdentifierToken,
1843
+ IdentifierToken,
1844
+ TextToken,
1845
+ NumberToken,
1846
+ PunctuationToken
1847
+ ]
1455
1848
  });
1456
- for (const node of Object.values(tokens)) if (node instanceof __prostojs_parser.BasicNode) node.popsAtEOFSource(true).mapContent("children", mapContent);
1849
+ tokens.root = root;
1850
+ BlockToken.recognize(RegExpToken, ...commentNodes.all, BlockToken, QueryToken, AIdentifierToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
1851
+ QueryToken.recognize(RegExpToken, QueryOperatorToken, BlockToken, IdentifierToken, TextToken, NumberToken, PunctuationToken);
1852
+ function extractTokens(node) {
1853
+ return node.content.map((item) => {
1854
+ if (typeof item === "string") return {
1855
+ type: "unknown",
1856
+ text: item
1857
+ };
1858
+ const data = item.data;
1859
+ data.getRange = () => ({
1860
+ start: {
1861
+ line: item.start.line - 1,
1862
+ character: item.start.column - 1 + (data.startOffset ?? 0)
1863
+ },
1864
+ end: {
1865
+ line: item.end.line - 1,
1866
+ character: item.end.column - 1 + (data.endOffset ?? 0)
1867
+ }
1868
+ });
1869
+ data.children = extractTokens(item);
1870
+ return data;
1871
+ });
1872
+ }
1457
1873
 
1458
1874
  //#endregion
1459
1875
  //#region packages/core/src/tokenizer/index.ts
1460
1876
  function tokenize(source, debug = false) {
1461
- const tokens$1 = root.parse(source);
1462
- if (debug) console.log(tokens$1.toTree());
1463
- return mapContent(tokens$1.content);
1877
+ const result = root.parse(source);
1878
+ if (debug) console.log((0, __prostojs_parser.printTree)(result));
1879
+ return extractTokens(result);
1464
1880
  }
1465
1881
 
1466
1882
  //#endregion
@@ -1716,67 +2132,359 @@ else if (isOperator && !(node instanceof Token)) throw new Error(`Unexpected tok
1716
2132
  }
1717
2133
 
1718
2134
  //#endregion
1719
- //#region packages/core/src/parser/pipes/special.pipe.ts
1720
- function refWithChain() {
1721
- const s = {
1722
- id: { node: "identifier" },
1723
- dot: {
1724
- node: "punctuation",
1725
- text: "."
1726
- },
1727
- block: {
1728
- node: "block",
1729
- text: "["
1730
- },
1731
- end: {
1732
- node: "punctuation",
1733
- text: ";"
2135
+ //#region packages/core/src/parser/pipes/query.pipe.ts
2136
+ const SYMBOLIC_OPS = new Set([
2137
+ "=",
2138
+ "!=",
2139
+ ">",
2140
+ ">=",
2141
+ "<",
2142
+ "<="
2143
+ ]);
2144
+ const VALUE_KEYWORDS = new Set([
2145
+ "true",
2146
+ "false",
2147
+ "null",
2148
+ "undefined"
2149
+ ]);
2150
+ function parseQueryExpression(children, messages, sourceToken) {
2151
+ if (children.length === 0) return undefined;
2152
+ const ni = new NodeIterator(children, messages);
2153
+ ni.move();
2154
+ const expr = parseOrExpr(ni, messages);
2155
+ if (!expr) return undefined;
2156
+ if (ni.$) messages.push({
2157
+ severity: 1,
2158
+ message: `Unexpected token in query expression: "${ni.$.text}"`,
2159
+ range: ni.$.getRange?.() ?? {
2160
+ start: {
2161
+ line: 0,
2162
+ character: 0
2163
+ },
2164
+ end: {
2165
+ line: 0,
2166
+ character: 0
2167
+ }
1734
2168
  }
1735
- };
1736
- return { handler(ni, target) {
1737
- ni.skip(["\n"]);
1738
- if (!ni.$) return false;
1739
- if (ni.satisfies(s.id)) {
1740
- ni.accepted();
1741
- target.node.saveToken(new Token(ni.$), "identifier");
1742
- } else return false;
2169
+ });
2170
+ const node = new SemanticQueryNode();
2171
+ node.expression = expr;
2172
+ node.sourceToken = sourceToken;
2173
+ return node;
2174
+ }
2175
+ function parseOrExpr(ni, messages) {
2176
+ const left = parseAndExpr(ni, messages);
2177
+ if (!left) return undefined;
2178
+ const operands = [left];
2179
+ while (ni.$?.type === "identifier" && ni.$.text === "or") {
1743
2180
  ni.move();
1744
- if (ni.fork().skip(["\n"]).satisfies(s.end)) {
1745
- ni.skip(["\n", ";"]);
1746
- return true;
2181
+ const right = parseAndExpr(ni, messages);
2182
+ if (!right) {
2183
+ pushError(ni, messages, "Expected expression after \"or\"");
2184
+ break;
1747
2185
  }
1748
- const fork = ni.fork();
1749
- let isDot = fork.skip(["\n"]).satisfies(s.dot);
1750
- let isBlock = fork.satisfies(s.block);
1751
- while (fork.$ && (isDot || isBlock)) {
1752
- if (isBlock) if (fork.$.children?.length === 0) {
1753
- while (isBlock && fork.$.children?.length === 0) {
1754
- target.node = new SemanticArrayNode().wrap(target.node, new Token(fork.$));
1755
- fork.move();
1756
- fork.skip(["\n", ";"]);
1757
- isBlock = fork.satisfies(s.block);
1758
- }
1759
- ni.unfork(fork);
1760
- return true;
1761
- } else if (fork.$.children?.length === 1 && fork.$.children[0].type === "text") {
1762
- if (isRef(target.node)) target.node.addChain(new Token(fork.$.children[0]));
1763
- } else return true;
1764
- else {
1765
- fork.skip(["\n"]);
1766
- if (fork.next().satisfies(s.id)) {
1767
- if (isRef(target.node)) target.node.addDot(new Token(fork.$));
1768
- fork.move();
1769
- if (isRef(target.node) && fork.$) target.node.addChain(new Token(fork.$));
1770
- } else {
1771
- if (isRef(target.node)) target.node.addDot(new Token(fork.$));
1772
- fork.unexpected();
1773
- fork.move(1);
1774
- fork.unexpected();
1775
- ni.unfork(fork);
1776
- ni.move();
1777
- ni.skip([";", "\n"]);
1778
- return true;
1779
- }
2186
+ operands.push(right);
2187
+ }
2188
+ if (operands.length === 1) return operands[0];
2189
+ const node = new SemanticQueryLogicalNode();
2190
+ node.operator = "or";
2191
+ node.operands = operands;
2192
+ return node;
2193
+ }
2194
+ function parseAndExpr(ni, messages) {
2195
+ const left = parseUnaryExpr(ni, messages);
2196
+ if (!left) return undefined;
2197
+ const operands = [left];
2198
+ while (ni.$?.type === "identifier" && ni.$.text === "and") {
2199
+ ni.move();
2200
+ const right = parseUnaryExpr(ni, messages);
2201
+ if (!right) {
2202
+ pushError(ni, messages, "Expected expression after \"and\"");
2203
+ break;
2204
+ }
2205
+ operands.push(right);
2206
+ }
2207
+ if (operands.length === 1) return operands[0];
2208
+ const node = new SemanticQueryLogicalNode();
2209
+ node.operator = "and";
2210
+ node.operands = operands;
2211
+ return node;
2212
+ }
2213
+ function parseUnaryExpr(ni, messages) {
2214
+ if (ni.$?.type === "identifier" && ni.$.text === "not") {
2215
+ ni.move();
2216
+ const operand = parseUnaryExpr(ni, messages);
2217
+ if (!operand) {
2218
+ pushError(ni, messages, "Expected expression after \"not\"");
2219
+ return undefined;
2220
+ }
2221
+ const node = new SemanticQueryLogicalNode();
2222
+ node.operator = "not";
2223
+ node.operands = [operand];
2224
+ return node;
2225
+ }
2226
+ if (ni.$?.type === "block" && ni.$.text === "(") {
2227
+ const blockChildren = ni.$.children || [];
2228
+ ni.move();
2229
+ if (blockChildren.length === 0) {
2230
+ pushError(ni, messages, "Empty parenthesized expression");
2231
+ return undefined;
2232
+ }
2233
+ const subNi = new NodeIterator(blockChildren, messages);
2234
+ subNi.move();
2235
+ const expr = parseOrExpr(subNi, messages);
2236
+ if (subNi.$) pushError(subNi, messages, `Unexpected token in parenthesized expression: "${subNi.$.text}"`);
2237
+ return expr;
2238
+ }
2239
+ return parseComparison(ni, messages);
2240
+ }
2241
+ function parseComparison(ni, messages) {
2242
+ const left = parseFieldRef(ni, messages);
2243
+ if (!left) return undefined;
2244
+ if (ni.$?.type === "punctuation" && SYMBOLIC_OPS.has(ni.$.text)) {
2245
+ const opText = ni.$.text;
2246
+ ni.move();
2247
+ const right = parseValueOrFieldRef(ni, messages);
2248
+ if (!right) {
2249
+ pushError(ni, messages, `Expected value or field reference after "${opText}"`);
2250
+ return undefined;
2251
+ }
2252
+ const node = new SemanticQueryComparisonNode();
2253
+ node.left = left;
2254
+ node.operator = opText;
2255
+ node.right = right;
2256
+ return node;
2257
+ }
2258
+ if (ni.$?.type === "identifier") {
2259
+ const opText = ni.$.text;
2260
+ if (opText === "in") {
2261
+ ni.move();
2262
+ const right = parseValueList(ni, messages);
2263
+ if (!right) return undefined;
2264
+ const node = new SemanticQueryComparisonNode();
2265
+ node.left = left;
2266
+ node.operator = "in";
2267
+ node.right = right;
2268
+ return node;
2269
+ }
2270
+ if (opText === "matches") {
2271
+ ni.move();
2272
+ const right = parseValueOrFieldRef(ni, messages);
2273
+ if (!right) {
2274
+ pushError(ni, messages, "Expected value after \"matches\"");
2275
+ return undefined;
2276
+ }
2277
+ const node = new SemanticQueryComparisonNode();
2278
+ node.left = left;
2279
+ node.operator = "matches";
2280
+ node.right = right;
2281
+ return node;
2282
+ }
2283
+ if (opText === "exists") {
2284
+ ni.move();
2285
+ const node = new SemanticQueryComparisonNode();
2286
+ node.left = left;
2287
+ node.operator = "exists";
2288
+ return node;
2289
+ }
2290
+ if (opText === "not") return parseNotComparison(ni, messages, left);
2291
+ pushError(ni, messages, `Unknown operator "${opText}"`);
2292
+ return undefined;
2293
+ }
2294
+ pushError(ni, messages, "Expected operator after field reference");
2295
+ return undefined;
2296
+ }
2297
+ function parseNotComparison(ni, messages, left) {
2298
+ ni.move();
2299
+ if (ni.$?.type === "identifier" && ni.$.text === "in") {
2300
+ ni.move();
2301
+ const right = parseValueList(ni, messages);
2302
+ if (!right) return undefined;
2303
+ const node = new SemanticQueryComparisonNode();
2304
+ node.left = left;
2305
+ node.operator = "not in";
2306
+ node.right = right;
2307
+ return node;
2308
+ }
2309
+ if (ni.$?.type === "identifier" && ni.$.text === "exists") {
2310
+ ni.move();
2311
+ const node = new SemanticQueryComparisonNode();
2312
+ node.left = left;
2313
+ node.operator = "not exists";
2314
+ return node;
2315
+ }
2316
+ pushError(ni, messages, "Expected \"in\" or \"exists\" after \"not\"");
2317
+ return undefined;
2318
+ }
2319
+ function parseFieldRef(ni, messages) {
2320
+ if (ni.$?.type !== "identifier") {
2321
+ pushError(ni, messages, "Expected field reference");
2322
+ return undefined;
2323
+ }
2324
+ const firstToken = new Token(ni.$);
2325
+ ni.move();
2326
+ if (ni.$?.type === "punctuation" && ni.$.text === ".") {
2327
+ ni.move();
2328
+ if (ni.$?.type === "identifier") {
2329
+ const secondToken = new Token(ni.$);
2330
+ ni.move();
2331
+ let fieldText = secondToken.text;
2332
+ while (ni.$?.type === "punctuation" && ni.$.text === ".") {
2333
+ ni.move();
2334
+ if (ni.$?.type === "identifier") {
2335
+ fieldText += `.${ni.$.text}`;
2336
+ ni.move();
2337
+ } else {
2338
+ pushError(ni, messages, "Expected identifier after \".\"");
2339
+ break;
2340
+ }
2341
+ }
2342
+ const node$2 = new SemanticQueryFieldRefNode();
2343
+ node$2.typeRef = firstToken;
2344
+ if (fieldText !== secondToken.text) node$2.fieldRef = secondToken.clone({ text: fieldText });
2345
+ else node$2.fieldRef = secondToken;
2346
+ return node$2;
2347
+ }
2348
+ pushError(ni, messages, "Expected identifier after \".\"");
2349
+ const node$1 = new SemanticQueryFieldRefNode();
2350
+ node$1.fieldRef = firstToken;
2351
+ return node$1;
2352
+ }
2353
+ const node = new SemanticQueryFieldRefNode();
2354
+ node.fieldRef = firstToken;
2355
+ return node;
2356
+ }
2357
+ function parseValueOrFieldRef(ni, messages) {
2358
+ if (!ni.$) return undefined;
2359
+ if (ni.$.type === "text" || ni.$.type === "number" || ni.$.type === "regexp") return parseValue(ni, messages);
2360
+ if (ni.$.type === "identifier") {
2361
+ if (VALUE_KEYWORDS.has(ni.$.text)) return parseValue(ni, messages);
2362
+ return parseFieldRef(ni, messages);
2363
+ }
2364
+ pushError(ni, messages, "Expected value or field reference");
2365
+ return undefined;
2366
+ }
2367
+ function parseValue(ni, messages) {
2368
+ if (!ni.$) {
2369
+ pushError(ni, messages, "Expected value");
2370
+ return undefined;
2371
+ }
2372
+ const token = ni.$;
2373
+ if (token.type === "text" || token.type === "number" || token.type === "regexp" || token.type === "identifier" && VALUE_KEYWORDS.has(token.text)) {
2374
+ const node = new SemanticQueryValueNode();
2375
+ node.valueToken = new Token(token);
2376
+ ni.move();
2377
+ return node;
2378
+ }
2379
+ pushError(ni, messages, `Unexpected token "${token.text}" where value expected`);
2380
+ return undefined;
2381
+ }
2382
+ function parseValueList(ni, messages) {
2383
+ if (ni.$?.type === "block" && ni.$.text === "(") {
2384
+ const blockChildren = ni.$.children || [];
2385
+ ni.move();
2386
+ const values = [];
2387
+ if (blockChildren.length === 0) {
2388
+ pushError(ni, messages, "Empty value list in \"in\" expression");
2389
+ return undefined;
2390
+ }
2391
+ const subNi = new NodeIterator(blockChildren, messages);
2392
+ subNi.move();
2393
+ const first = parseValue(subNi, messages);
2394
+ if (first) values.push(first);
2395
+ while (subNi.$?.type === "punctuation" && subNi.$.text === ",") {
2396
+ subNi.move();
2397
+ const v = parseValue(subNi, messages);
2398
+ if (v) values.push(v);
2399
+ }
2400
+ if (subNi.$) pushError(subNi, messages, `Unexpected token in value list: "${subNi.$.text}"`);
2401
+ const node = new SemanticQueryValueListNode();
2402
+ node.values = values;
2403
+ return node;
2404
+ }
2405
+ pushError(ni, messages, "Expected parenthesized value list after \"in\"");
2406
+ return undefined;
2407
+ }
2408
+ function pushError(ni, messages, message) {
2409
+ const range = ni.$?.getRange?.() ?? {
2410
+ start: {
2411
+ line: 0,
2412
+ character: 0
2413
+ },
2414
+ end: {
2415
+ line: 0,
2416
+ character: 0
2417
+ }
2418
+ };
2419
+ messages.push({
2420
+ severity: 1,
2421
+ message,
2422
+ range
2423
+ });
2424
+ }
2425
+
2426
+ //#endregion
2427
+ //#region packages/core/src/parser/pipes/special.pipe.ts
2428
+ function refWithChain() {
2429
+ const s = {
2430
+ id: { node: "identifier" },
2431
+ dot: {
2432
+ node: "punctuation",
2433
+ text: "."
2434
+ },
2435
+ block: {
2436
+ node: "block",
2437
+ text: "["
2438
+ },
2439
+ end: {
2440
+ node: "punctuation",
2441
+ text: ";"
2442
+ }
2443
+ };
2444
+ return { handler(ni, target) {
2445
+ ni.skip(["\n"]);
2446
+ if (!ni.$) return false;
2447
+ if (ni.satisfies(s.id)) {
2448
+ ni.accepted();
2449
+ target.node.saveToken(new Token(ni.$), "identifier");
2450
+ } else return false;
2451
+ ni.move();
2452
+ if (ni.fork().skip(["\n"]).satisfies(s.end)) {
2453
+ ni.skip(["\n", ";"]);
2454
+ return true;
2455
+ }
2456
+ const fork = ni.fork();
2457
+ let isDot = fork.skip(["\n"]).satisfies(s.dot);
2458
+ let isBlock = fork.satisfies(s.block);
2459
+ while (fork.$ && (isDot || isBlock)) {
2460
+ if (isBlock) if (fork.$.children?.length === 0) {
2461
+ while (isBlock && fork.$.children?.length === 0) {
2462
+ target.node = new SemanticArrayNode().wrap(target.node, new Token(fork.$));
2463
+ fork.move();
2464
+ fork.skip(["\n", ";"]);
2465
+ isBlock = fork.satisfies(s.block);
2466
+ }
2467
+ ni.unfork(fork);
2468
+ return true;
2469
+ } else if (fork.$.children?.length === 1 && fork.$.children[0].type === "text") {
2470
+ if (isRef(target.node)) target.node.addChain(new Token(fork.$.children[0]));
2471
+ } else return true;
2472
+ else {
2473
+ fork.skip(["\n"]);
2474
+ if (fork.next().satisfies(s.id)) {
2475
+ if (isRef(target.node)) target.node.addDot(new Token(fork.$));
2476
+ fork.move();
2477
+ if (isRef(target.node) && fork.$) target.node.addChain(new Token(fork.$));
2478
+ } else {
2479
+ if (isRef(target.node)) target.node.addDot(new Token(fork.$));
2480
+ fork.unexpected();
2481
+ fork.move(1);
2482
+ fork.unexpected();
2483
+ ni.unfork(fork);
2484
+ ni.move();
2485
+ ni.skip([";", "\n"]);
2486
+ return true;
2487
+ }
1780
2488
  }
1781
2489
  fork.move();
1782
2490
  ni.unfork(fork);
@@ -1793,15 +2501,25 @@ else {
1793
2501
  function annotations() {
1794
2502
  const opts = {
1795
2503
  annotation: { node: "annotation" },
1796
- argument: [{ node: ["number", "text"] }, {
1797
- node: "identifier",
1798
- text: [
1799
- "true",
1800
- "false",
1801
- "undefined",
1802
- "null"
1803
- ]
1804
- }],
2504
+ argument: [
2505
+ { node: ["number", "text"] },
2506
+ {
2507
+ node: "identifier",
2508
+ text: [
2509
+ "true",
2510
+ "false",
2511
+ "undefined",
2512
+ "null"
2513
+ ]
2514
+ },
2515
+ { node: "identifier" },
2516
+ { node: "query" }
2517
+ ],
2518
+ dot: {
2519
+ node: "punctuation",
2520
+ text: "."
2521
+ },
2522
+ ident: { node: "identifier" },
1805
2523
  comma: {
1806
2524
  node: "punctuation",
1807
2525
  text: ","
@@ -1823,9 +2541,30 @@ function annotations() {
1823
2541
  ni.move();
1824
2542
  }
1825
2543
  while (ni.satisfies(...opts.argument)) {
1826
- addArgument(new Token(ni.$));
2544
+ let argToken = new Token(ni.$);
1827
2545
  ni.accepted();
1828
2546
  ni.move();
2547
+ if (argToken.type === "identifier" && ![
2548
+ "true",
2549
+ "false",
2550
+ "undefined",
2551
+ "null"
2552
+ ].includes(argToken.text)) {
2553
+ let chainText = argToken.text;
2554
+ while (ni.satisfies(opts.dot) && ni.next()?.satisfies(opts.ident)) {
2555
+ ni.accepted();
2556
+ ni.move();
2557
+ chainText += `.${ni.$.text}`;
2558
+ ni.accepted();
2559
+ ni.move();
2560
+ }
2561
+ if (chainText !== argToken.text) argToken = argToken.clone({ text: chainText });
2562
+ }
2563
+ if (argToken.type === "query") {
2564
+ const queryNode = parseQueryExpression(argToken.children, ni.messages, argToken);
2565
+ if (queryNode) argToken.queryNode = queryNode;
2566
+ }
2567
+ addArgument(argToken);
1829
2568
  if (ni.satisfies(opts.comma)) {
1830
2569
  ni.accepted();
1831
2570
  ni.move();
@@ -2156,6 +2895,20 @@ var TSeverity = /*#__PURE__*/ function(TSeverity$1) {
2156
2895
  return TSeverity$1;
2157
2896
  }({});
2158
2897
 
2898
+ //#endregion
2899
+ //#region packages/core/src/parser/utils.ts
2900
+ function resolveAtscriptFromPath(from, id) {
2901
+ return `file://${path.default.join(id.slice(7).split("/").slice(0, -1).join("/"), from)}.as`;
2902
+ }
2903
+ function getRelPath(fromUri, toUri) {
2904
+ const fromPath = new url.URL(fromUri).pathname;
2905
+ const toPath = new url.URL(toUri).pathname;
2906
+ const relPath = path.default.relative(path.default.dirname(fromPath), toPath);
2907
+ const { dir, name } = path.default.parse(relPath);
2908
+ const prefix = dir.startsWith("..") ? "" : "./";
2909
+ return `${prefix}${dir ? `${dir}/` : ""}${name}`;
2910
+ }
2911
+
2159
2912
  //#endregion
2160
2913
  //#region packages/core/src/token-index/blocks-index.ts
2161
2914
  function _define_property$5(obj, key, value) {
@@ -2278,7 +3031,11 @@ var TokensIndex = class {
2278
3031
  */ at(line, character) {
2279
3032
  const tokens$1 = this.tokensMap[line];
2280
3033
  if (!tokens$1) return undefined;
2281
- return Array.from(tokens$1).find((t) => t.range.start.character <= character && t.range.end.character >= character);
3034
+ let best;
3035
+ for (const t of tokens$1) if (t.range.start.character <= character && t.range.end.character >= character) {
3036
+ if (!best || t.range.start.character > best.range.start.character || t.range.start.character === best.range.start.character && t.range.end.character < best.range.end.character) best = t;
3037
+ }
3038
+ return best;
2282
3039
  }
2283
3040
  /**
2284
3041
  * Retrieves either the token at the specified (line, character), or if none exists,
@@ -2380,6 +3137,7 @@ var AtscriptDoc = class {
2380
3137
  this.importedDefs.clear();
2381
3138
  this.messages = [];
2382
3139
  this.referred = [];
3140
+ this.queryFieldRefs = [];
2383
3141
  this.imports.clear();
2384
3142
  this._allMessages = undefined;
2385
3143
  this.tokensIndex = new TokensIndex();
@@ -2408,6 +3166,23 @@ var AtscriptDoc = class {
2408
3166
  this.registerMessages(annotationSpec.validate(mainToken, args || [], this));
2409
3167
  annotationSpec.modify(mainToken, args || [], this);
2410
3168
  this.resolvedAnnotations.push(mainToken);
3169
+ const specArgs = annotationSpec.arguments;
3170
+ for (let i = 0; i < (args?.length ?? 0); i++) {
3171
+ const argSpec = specArgs[i];
3172
+ if (argSpec?.type === "ref" && args?.[i]) {
3173
+ const refToken = args[i];
3174
+ const dotIdx = refToken.text.indexOf(".");
3175
+ if (dotIdx > 0) {
3176
+ const typeToken = refToken.clone({ text: refToken.text.slice(0, dotIdx) });
3177
+ typeToken.isReference = true;
3178
+ this.referred.push(typeToken);
3179
+ } else {
3180
+ refToken.isReference = true;
3181
+ this.referred.push(refToken);
3182
+ }
3183
+ }
3184
+ if (argSpec?.type === "query" && args?.[i]?.queryNode) args[i].queryNode.registerAtDocument(this);
3185
+ }
2411
3186
  } else {
2412
3187
  let severity = 0;
2413
3188
  switch (this.config.unknownAnnotation) {
@@ -2615,6 +3390,17 @@ else {
2615
3390
  });
2616
3391
  }
2617
3392
  }
3393
+ for (const qfr of doc.queryFieldRefs) {
3394
+ if (!qfr.queryArgToken || qfr.fieldRef.text !== propName$1) continue;
3395
+ const scope = getQueryScope(qfr.queryArgToken, doc);
3396
+ if (!scope) continue;
3397
+ const resolvedTypeName = qfr.typeRef?.text ?? scope.unqualifiedTarget;
3398
+ if (resolvedTypeName === parentName) refs.push({
3399
+ uri,
3400
+ range: qfr.fieldRef.range,
3401
+ token: qfr.fieldRef
3402
+ });
3403
+ }
2618
3404
  };
2619
3405
  searchDoc(this, this.id);
2620
3406
  const parentDefToken = this.registry.definitions.get(parentName);
@@ -2626,7 +3412,23 @@ else {
2626
3412
  }
2627
3413
  }
2628
3414
  return refs;
2629
- } else {
3415
+ }
3416
+ if (isQueryFieldRef(token.parentNode) && token === token.parentNode.fieldRef) {
3417
+ const fieldRefNode = token.parentNode;
3418
+ const queryArgToken = fieldRefNode.queryArgToken;
3419
+ if (queryArgToken) {
3420
+ const scope = getQueryScope(queryArgToken, this);
3421
+ if (scope) {
3422
+ const resolved = resolveQueryFieldRef(fieldRefNode, this, scope);
3423
+ if (resolved?.prop) {
3424
+ const propToken = resolved.prop.token("identifier");
3425
+ if (propToken) return resolved.doc.usageListFor(propToken);
3426
+ }
3427
+ }
3428
+ }
3429
+ return undefined;
3430
+ }
3431
+ {
2630
3432
  const defForToken = this.getDefinitionFor(token);
2631
3433
  if (defForToken?.token?.isDefinition && defForToken.doc) return defForToken.doc.usageListFor(defForToken.token);
2632
3434
  }
@@ -2700,6 +3502,37 @@ else {
2700
3502
  }];
2701
3503
  return undefined;
2702
3504
  }
3505
+ if (isQueryFieldRef(token.parentNode)) {
3506
+ const fieldRefNode = token.parentNode;
3507
+ const queryArgToken = fieldRefNode.queryArgToken;
3508
+ if (queryArgToken) {
3509
+ const scope = getQueryScope(queryArgToken, this);
3510
+ if (scope) {
3511
+ if (token === fieldRefNode.typeRef) {
3512
+ const result = this.getDefinitionFor(token);
3513
+ return result ? [{
3514
+ targetUri: result.uri,
3515
+ targetRange: result.token?.range ?? zeroRange,
3516
+ targetSelectionRange: result.token?.range ?? zeroRange,
3517
+ originSelectionRange: token.range
3518
+ }] : undefined;
3519
+ }
3520
+ if (token === fieldRefNode.fieldRef) {
3521
+ const resolved = resolveQueryFieldRef(fieldRefNode, this, scope);
3522
+ if (resolved?.prop) {
3523
+ const propToken = resolved.prop.token("identifier");
3524
+ return [{
3525
+ targetUri: resolved.targetUri,
3526
+ targetRange: propToken?.range ?? zeroRange,
3527
+ targetSelectionRange: propToken?.range ?? zeroRange,
3528
+ originSelectionRange: token.range
3529
+ }];
3530
+ }
3531
+ }
3532
+ }
3533
+ }
3534
+ return undefined;
3535
+ }
2703
3536
  if (isProp(token.parentNode)) return [{
2704
3537
  targetUri: this.id,
2705
3538
  targetRange: token.range,
@@ -3156,6 +3989,9 @@ else {
3156
3989
  * List of tokens that refer to some type or interface
3157
3990
  */ _define_property$3(this, "referred", void 0);
3158
3991
  /**
3992
+ * List of query field ref nodes (for find-references support)
3993
+ */ _define_property$3(this, "queryFieldRefs", void 0);
3994
+ /**
3159
3995
  * Map of dependencies (documents) by URI
3160
3996
  */ _define_property$3(this, "dependenciesMap", void 0);
3161
3997
  _define_property$3(this, "nodes", void 0);
@@ -3177,6 +4013,7 @@ else {
3177
4013
  this.dependencies = new Set();
3178
4014
  this.dependants = new Set();
3179
4015
  this.referred = [];
4016
+ this.queryFieldRefs = [];
3180
4017
  this.dependenciesMap = new Map();
3181
4018
  this.nodes = [];
3182
4019
  this._text = "";
@@ -3207,47 +4044,307 @@ function createSyntheticRef(name) {
3207
4044
  return ref$1;
3208
4045
  }
3209
4046
 
4047
+ //#endregion
4048
+ //#region packages/core/src/defaults/db-utils.ts
4049
+ function validateRefArgument(token, doc, options) {
4050
+ const messages = [];
4051
+ const text$2 = token.text;
4052
+ const [typeName, ...chain] = text$2.split(".");
4053
+ const decl = doc.getDeclarationOwnerNode(typeName);
4054
+ if (!decl) {
4055
+ const regDef = doc.registry.definitions.get(typeName);
4056
+ if (regDef?.imported) return messages;
4057
+ messages.push({
4058
+ severity: 1,
4059
+ message: `Unknown type '${typeName}'.`,
4060
+ range: token.range
4061
+ });
4062
+ return messages;
4063
+ }
4064
+ if (chain.length > 0) {
4065
+ const unwound = doc.unwindType(typeName, chain);
4066
+ if (!unwound) {
4067
+ messages.push({
4068
+ severity: 1,
4069
+ message: `Field '${chain.join(".")}' does not exist on type '${typeName}'.`,
4070
+ range: token.range
4071
+ });
4072
+ return messages;
4073
+ }
4074
+ }
4075
+ if (options?.requireDbTable && decl.node) {
4076
+ const hasDbTable = decl.node.countAnnotations("db.table") > 0;
4077
+ if (!hasDbTable) messages.push({
4078
+ severity: 1,
4079
+ message: `Type '${typeName}' must have @db.table annotation.`,
4080
+ range: token.range
4081
+ });
4082
+ }
4083
+ return messages;
4084
+ }
4085
+ function findFKFieldsPointingTo(doc, iface, targetTypeName, alias) {
4086
+ const results = [];
4087
+ let struct;
4088
+ if (isInterface(iface) && iface.hasExtends) {
4089
+ const resolved = doc.resolveInterfaceExtends(iface);
4090
+ if (resolved && isStructure(resolved)) struct = resolved;
4091
+ }
4092
+ if (!struct) struct = isStructure(iface) ? iface : isInterface(iface) && isStructure(iface.getDefinition()) ? iface.getDefinition() : undefined;
4093
+ if (!struct) return results;
4094
+ for (const [name, prop] of struct.props) {
4095
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
4096
+ const def = prop.getDefinition();
4097
+ if (!def || !isRef(def)) continue;
4098
+ const ref$1 = def;
4099
+ if (!ref$1.hasChain) continue;
4100
+ const refTypeName = ref$1.id;
4101
+ const refField = ref$1.chain.map((c) => c.text).join(".");
4102
+ if (refTypeName !== targetTypeName) continue;
4103
+ if (alias !== undefined) {
4104
+ const fkAnnotations = prop.annotations?.filter((a) => a.name === "db.rel.FK");
4105
+ const hasMatchingAlias = fkAnnotations?.some((a) => a.args.length > 0 && a.args[0].text === alias);
4106
+ if (!hasMatchingAlias) continue;
4107
+ }
4108
+ results.push({
4109
+ name,
4110
+ prop,
4111
+ chainRef: {
4112
+ type: refTypeName,
4113
+ field: refField
4114
+ }
4115
+ });
4116
+ }
4117
+ return results;
4118
+ }
4119
+ const viewAnnotationNames = [
4120
+ "db.view",
4121
+ "db.view.for",
4122
+ "db.view.joins",
4123
+ "db.view.filter",
4124
+ "db.view.materialized"
4125
+ ];
4126
+ function hasAnyViewAnnotation(node) {
4127
+ return viewAnnotationNames.some((name) => node.countAnnotations(name) > 0);
4128
+ }
4129
+ function validateQueryScope(queryToken, allowedTypes, unqualifiedTarget, doc) {
4130
+ const errors = [];
4131
+ const queryNode = queryToken.queryNode;
4132
+ if (!queryNode) return errors;
4133
+ function walkFieldRef(ref$1) {
4134
+ if (ref$1.typeRef) {
4135
+ const typeName = ref$1.typeRef.text;
4136
+ if (!allowedTypes.includes(typeName)) errors.push({
4137
+ message: `Query references '${typeName}' which is not in scope — expected ${allowedTypes.map((t) => `'${t}'`).join(" or ")}`,
4138
+ severity: 1,
4139
+ range: ref$1.typeRef.range
4140
+ });
4141
+ } else if (unqualifiedTarget === null) errors.push({
4142
+ message: `Unqualified field reference '${ref$1.fieldRef.text}' — use qualified form (e.g., Type.${ref$1.fieldRef.text})`,
4143
+ severity: 1,
4144
+ range: ref$1.fieldRef.range
4145
+ });
4146
+ else {
4147
+ const unwound = doc.unwindType(unqualifiedTarget);
4148
+ if (unwound) {
4149
+ const targetDef = unwound.def;
4150
+ if (isInterface(targetDef) || isStructure(targetDef)) {
4151
+ const struct = isInterface(targetDef) ? targetDef.getDefinition() : targetDef;
4152
+ if (struct && isStructure(struct) && !struct.props.has(ref$1.fieldRef.text)) errors.push({
4153
+ message: `Field '${ref$1.fieldRef.text}' does not exist on '${unqualifiedTarget}'`,
4154
+ severity: 1,
4155
+ range: ref$1.fieldRef.range
4156
+ });
4157
+ }
4158
+ }
4159
+ }
4160
+ }
4161
+ function walkExpr(expr) {
4162
+ if (isQueryLogical(expr)) for (const operand of expr.operands) walkExpr(operand);
4163
+ else if (isQueryComparison(expr)) {
4164
+ walkFieldRef(expr.left);
4165
+ if (expr.right && "fieldRef" in expr.right) walkFieldRef(expr.right);
4166
+ }
4167
+ }
4168
+ walkExpr(queryNode.expression);
4169
+ return errors;
4170
+ }
4171
+
3210
4172
  //#endregion
3211
4173
  //#region packages/core/src/defaults/db-annotations.ts
3212
- const dbAnnotations = {
3213
- patch: { strategy: new AnnotationSpec({
3214
- description: "Defines the **patching strategy** for updating nested objects.\n\n- **\"replace\"** → The field or object will be **fully replaced**.\n- **\"merge\"** → The field or object will be **merged recursively** (applies only to objects, not arrays).\n\n**Example:**\n```atscript\n@db.patch.strategy \"merge\"\nsettings: {\n notifications: boolean\n preferences: {\n theme: string\n }\n}\n```\n",
4174
+ /**
4175
+ * Traverse from annotation token → prop → structure → interface
4176
+ * to check if the parent interface has @db.table.
4177
+ */ function getDbTableOwner(token) {
4178
+ const field = token.parentNode;
4179
+ const struct = field.ownerNode;
4180
+ if (!struct || !isStructure(struct)) return undefined;
4181
+ const iface = struct.ownerNode;
4182
+ return iface && isInterface(iface) ? iface : struct;
4183
+ }
4184
+ /**
4185
+ * Get the parent structure node from an annotation token.
4186
+ */ function getParentStruct(token) {
4187
+ const field = token.parentNode;
4188
+ const struct = field.ownerNode;
4189
+ return struct && isStructure(struct) ? struct : undefined;
4190
+ }
4191
+ /**
4192
+ * Get the parent interface name (for error messages and cross-type resolution).
4193
+ */ function getParentTypeName(token) {
4194
+ const struct = getParentStruct(token);
4195
+ if (!struct) return undefined;
4196
+ const iface = struct.ownerNode;
4197
+ return iface && isInterface(iface) ? iface.id : struct.id;
4198
+ }
4199
+ /**
4200
+ * Extract target type name from a navigational field definition.
4201
+ * Unwraps arrays (e.g., `Post[]` → `Post`).
4202
+ */ function getNavTargetTypeName(field) {
4203
+ let def = field.getDefinition();
4204
+ if (isArray(def)) def = def?.getDefinition();
4205
+ if (isRef(def)) return def.id;
4206
+ return undefined;
4207
+ }
4208
+ /**
4209
+ * Get the alias argument from an annotation on a field.
4210
+ */ function getAnnotationAlias(prop, annotationName) {
4211
+ const annotations$1 = prop.annotations?.filter((a) => a.name === annotationName);
4212
+ if (!annotations$1 || annotations$1.length === 0) return undefined;
4213
+ return annotations$1[0].args.length > 0 ? annotations$1[0].args[0].text : undefined;
4214
+ }
4215
+ /**
4216
+ * Factory for @db.rel.onDelete / @db.rel.onUpdate — identical validation logic,
4217
+ * only the annotation name and description verb differ.
4218
+ */ function refActionAnnotation(name) {
4219
+ return new AnnotationSpec({
4220
+ description: `Referential action when the target ${name === "onDelete" ? "row is deleted" : "key is updated"}. Only valid on @db.rel.FK fields.\n\n` + "**Example:**\n" + "```atscript\n" + "@db.rel.FK\n" + `@db.rel.${name} "cascade"\n` + "authorId: User.id\n" + "```\n",
3215
4221
  nodeType: ["prop"],
3216
- multiple: false,
3217
4222
  argument: {
3218
- name: "strategy",
4223
+ name: "action",
3219
4224
  type: "string",
3220
- description: "The **patch strategy** for this field: `\"replace\"` (default) or `\"merge\"`.",
3221
- values: ["replace", "merge"]
4225
+ values: [
4226
+ "cascade",
4227
+ "restrict",
4228
+ "noAction",
4229
+ "setNull",
4230
+ "setDefault"
4231
+ ],
4232
+ description: "Referential action: \"cascade\", \"restrict\", \"noAction\", \"setNull\", or \"setDefault\"."
3222
4233
  },
3223
4234
  validate(token, args, doc) {
3224
- const field = token.parentNode;
3225
4235
  const errors = [];
3226
- const definition$1 = field.getDefinition();
3227
- if (!definition$1) return errors;
3228
- let wrongType = false;
3229
- if (isRef(definition$1)) {
3230
- const def = doc.unwindType(definition$1.id, definition$1.chain)?.def;
3231
- if (!isStructure(def) && !isInterface(def) && !isArray(def)) wrongType = true;
3232
- } else if (!isStructure(definition$1) && !isInterface(definition$1) && !isArray(definition$1)) wrongType = true;
3233
- if (wrongType) errors.push({
3234
- message: `@db.patch.strategy requires a field of type object or array`,
4236
+ const field = token.parentNode;
4237
+ if (field.countAnnotations("db.rel.FK") === 0) errors.push({
4238
+ message: `@db.rel.${name} is only valid on @db.rel.FK fields`,
3235
4239
  severity: 1,
3236
4240
  range: token.range
3237
4241
  });
3238
- return errors;
3239
- }
3240
- }) },
3241
- table: new AnnotationSpec({
3242
- description: "Marks an interface as a database-persisted entity (table in SQL, collection in MongoDB). If the name argument is omitted, the adapter derives the table name from the interface name.\n\n**Example:**\n```atscript\n@db.table \"users\"\nexport interface User { ... }\n```\n",
3243
- nodeType: ["interface"],
4242
+ if (args[0]) {
4243
+ const action = args[0].text;
4244
+ if (action === "setNull" && !field.has("optional")) errors.push({
4245
+ message: `@db.rel.${name} "setNull" requires the FK field to be optional (?)`,
4246
+ severity: 1,
4247
+ range: token.range
4248
+ });
4249
+ if (action === "setDefault" && field.countAnnotations("db.default") === 0 && field.countAnnotations("db.default.fn") === 0) errors.push({
4250
+ message: `@db.rel.${name} "setDefault" but no @db.default.* annotation — field will have no fallback value`,
4251
+ severity: 2,
4252
+ range: token.range
4253
+ });
4254
+ }
4255
+ const fkAlias = getAnnotationAlias(field, "db.rel.FK");
4256
+ if (fkAlias) {
4257
+ const struct = getParentStruct(token);
4258
+ if (struct) {
4259
+ const annotationName = `db.rel.${name}`;
4260
+ let count = 0;
4261
+ for (const [, prop] of struct.props) {
4262
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
4263
+ if (prop.countAnnotations(annotationName) === 0) continue;
4264
+ const propFkAlias = getAnnotationAlias(prop, "db.rel.FK");
4265
+ if (propFkAlias === fkAlias) count++;
4266
+ }
4267
+ if (count > 1) errors.push({
4268
+ message: `Composite FK '${fkAlias}' has @db.rel.${name} on multiple fields — declare it on exactly one`,
4269
+ severity: 1,
4270
+ range: token.range
4271
+ });
4272
+ }
4273
+ }
4274
+ return errors;
4275
+ }
4276
+ });
4277
+ }
4278
+ const dbAnnotations = {
4279
+ patch: { strategy: new AnnotationSpec({
4280
+ description: "Defines the **patching strategy** for updating nested objects.\n\n- **\"replace\"** → The field or object will be **fully replaced**.\n- **\"merge\"** → The field or object will be **merged recursively** (applies only to objects, not arrays).\n\n**Example:**\n```atscript\n@db.patch.strategy \"merge\"\nsettings: {\n notifications: boolean\n preferences: {\n theme: string\n }\n}\n```\n",
4281
+ nodeType: ["prop"],
4282
+ multiple: false,
3244
4283
  argument: {
3245
- optional: true,
3246
- name: "name",
4284
+ name: "strategy",
3247
4285
  type: "string",
3248
- description: "Table/collection name. If omitted, derived from interface name."
4286
+ description: "The **patch strategy** for this field: `\"replace\"` (default) or `\"merge\"`.",
4287
+ values: ["replace", "merge"]
4288
+ },
4289
+ validate(token, args, doc) {
4290
+ const field = token.parentNode;
4291
+ const errors = [];
4292
+ const definition$1 = field.getDefinition();
4293
+ if (!definition$1) return errors;
4294
+ let wrongType = false;
4295
+ if (isRef(definition$1)) {
4296
+ const def = doc.unwindType(definition$1.id, definition$1.chain)?.def;
4297
+ if (!isStructure(def) && !isInterface(def) && !isArray(def)) wrongType = true;
4298
+ } else if (!isStructure(definition$1) && !isInterface(definition$1) && !isArray(definition$1)) wrongType = true;
4299
+ if (wrongType) errors.push({
4300
+ message: `@db.patch.strategy requires a field of type object or array`,
4301
+ severity: 1,
4302
+ range: token.range
4303
+ });
4304
+ return errors;
3249
4305
  }
3250
- }),
4306
+ }) },
4307
+ table: {
4308
+ $self: new AnnotationSpec({
4309
+ description: "Marks an interface as a database-persisted entity (table in SQL, collection in MongoDB). If the name argument is omitted, the adapter derives the table name from the interface name.\n\n**Example:**\n```atscript\n@db.table \"users\"\nexport interface User { ... }\n```\n",
4310
+ nodeType: ["interface"],
4311
+ argument: {
4312
+ optional: true,
4313
+ name: "name",
4314
+ type: "string",
4315
+ description: "Table/collection name. If omitted, derived from interface name."
4316
+ },
4317
+ validate(token, _args, _doc) {
4318
+ const errors = [];
4319
+ const owner = token.parentNode;
4320
+ if (hasAnyViewAnnotation(owner)) errors.push({
4321
+ message: "An interface cannot be both a @db.table and a @db.view",
4322
+ severity: 1,
4323
+ range: token.range
4324
+ });
4325
+ return errors;
4326
+ }
4327
+ }),
4328
+ renamed: new AnnotationSpec({
4329
+ description: "Specifies the previous table name for table rename migration. The sync engine generates ALTER TABLE RENAME instead of drop+create.\n\n**Example:**\n```atscript\n@db.table \"app_users\"\n@db.table.renamed \"users\"\nexport interface User { ... }\n```\n",
4330
+ nodeType: ["interface"],
4331
+ argument: {
4332
+ name: "oldName",
4333
+ type: "string",
4334
+ description: "The previous table/collection name."
4335
+ },
4336
+ validate(token, _args, _doc) {
4337
+ const errors = [];
4338
+ const owner = token.parentNode;
4339
+ if (owner.countAnnotations("db.table") === 0) errors.push({
4340
+ message: "@db.table.renamed requires @db.table on the same interface",
4341
+ severity: 1,
4342
+ range: token.range
4343
+ });
4344
+ return errors;
4345
+ }
4346
+ })
4347
+ },
3251
4348
  schema: new AnnotationSpec({
3252
4349
  description: "Assigns the entity to a database schema/namespace.\n\n**Example:**\n```atscript\n@db.table \"users\"\n@db.schema \"auth\"\nexport interface User { ... }\n```\n",
3253
4350
  nodeType: ["interface"],
@@ -3306,18 +4403,29 @@ const dbAnnotations = {
3306
4403
  }]
3307
4404
  })
3308
4405
  },
3309
- column: new AnnotationSpec({
3310
- description: "Overrides the physical column/document-field name in the database.\n\n**Example:**\n```atscript\n@db.column \"first_name\"\nfirstName: string\n```\n",
3311
- nodeType: ["prop"],
3312
- argument: {
3313
- name: "name",
3314
- type: "string",
3315
- description: "The actual column/field name in the DB."
3316
- }
3317
- }),
4406
+ column: {
4407
+ $self: new AnnotationSpec({
4408
+ description: "Overrides the physical column name in the database. For nested (flattened) fields, the parent prefix is still prepended automatically.\n\n**Example:**\n```atscript\n@db.column \"first_name\"\nfirstName: string\n// → physical column: first_name\n\n// Nested:\naddress: {\n @db.column \"zip_code\"\n zip: string\n}\n// → physical column: address__zip_code\n```\n",
4409
+ nodeType: ["prop"],
4410
+ argument: {
4411
+ name: "name",
4412
+ type: "string",
4413
+ description: "The column/field name (without parent prefix for nested fields)."
4414
+ }
4415
+ }),
4416
+ renamed: new AnnotationSpec({
4417
+ description: "Specifies the previous local field name for column rename migration. The sync engine generates ALTER TABLE RENAME COLUMN instead of drop+add.\n\n**Example:**\n```atscript\n@db.column.renamed \"zip\"\npostalCode: string\n// Renames address__zip → address__postalCode\n```\n",
4418
+ nodeType: ["prop"],
4419
+ argument: {
4420
+ name: "oldName",
4421
+ type: "string",
4422
+ description: "The old local field name (parent prefix is reconstructed automatically)."
4423
+ }
4424
+ })
4425
+ },
3318
4426
  default: {
3319
- value: new AnnotationSpec({
3320
- description: "Sets a static DB-level default value (used in DDL DEFAULT clause). For string fields the value is used as-is; for other types it is parsed as JSON.\n\n**Example:**\n```atscript\n@db.default.value \"active\"\nstatus: string\n```\n",
4427
+ $self: new AnnotationSpec({
4428
+ description: "Sets a static DB-level default value (used in DDL DEFAULT clause). For string fields the value is used as-is; for other types it is parsed as JSON.\n\n**Example:**\n```atscript\n@db.default \"active\"\nstatus: string\n```\n",
3321
4429
  nodeType: ["prop"],
3322
4430
  argument: {
3323
4431
  name: "value",
@@ -3411,7 +4519,538 @@ else if (fnName === "now" && !["number", "string"].includes(baseType)) errors.pu
3411
4519
  });
3412
4520
  return errors;
3413
4521
  }
3414
- })
4522
+ }),
4523
+ sync: { method: new AnnotationSpec({
4524
+ description: "Controls how the sync engine handles structural changes that cannot be applied via ALTER TABLE.\n\n- `\"recreate\"` — lossless: create temp table, copy data, drop old, rename.\n- `\"drop\"` — lossy: drop table entirely and create from scratch.\n\nWithout this annotation, structural changes fail with an error requiring manual intervention.\n\n**Example:**\n```atscript\n@db.sync.method \"drop\"\ninterface Logs { ... }\n```\n",
4525
+ nodeType: ["interface"],
4526
+ argument: {
4527
+ name: "method",
4528
+ type: "string",
4529
+ description: "Sync method: \"drop\" (lossy) or \"recreate\" (lossless with data copy).",
4530
+ values: ["drop", "recreate"]
4531
+ }
4532
+ }) },
4533
+ rel: {
4534
+ FK: new AnnotationSpec({
4535
+ description: "Declares a foreign key constraint on this field. The field must use a chain reference type (e.g., `User.id`) to specify the FK target.\n\n**Example:**\n```atscript\n@db.rel.FK\nauthorId: User.id\n\n// With alias (required when multiple FKs point to the same type)\n@db.rel.FK \"author\"\nauthorId: User.id\n```\n",
4536
+ nodeType: ["prop"],
4537
+ argument: {
4538
+ optional: true,
4539
+ name: "alias",
4540
+ type: "string",
4541
+ description: "Alias for pairing with @db.rel.to. Required when multiple FKs point to the same target type."
4542
+ },
4543
+ validate(token, args, doc) {
4544
+ const errors = [];
4545
+ const field = token.parentNode;
4546
+ const alias = args[0]?.text;
4547
+ const owner = getDbTableOwner(token);
4548
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
4549
+ message: "@db.rel.FK is only valid on fields of a @db.table interface",
4550
+ severity: 1,
4551
+ range: token.range
4552
+ });
4553
+ if (field.countAnnotations("db.rel.to") > 0 || field.countAnnotations("db.rel.from") > 0) errors.push({
4554
+ message: "A field cannot be both a foreign key and a navigational property",
4555
+ severity: 1,
4556
+ range: token.range
4557
+ });
4558
+ const definition$1 = field.getDefinition();
4559
+ if (!definition$1 || !isRef(definition$1) || !definition$1.hasChain) {
4560
+ errors.push({
4561
+ message: `@db.rel.FK requires a chain reference type (e.g. User.id), got scalar type`,
4562
+ severity: 1,
4563
+ range: token.range
4564
+ });
4565
+ return errors;
4566
+ }
4567
+ const ref$1 = definition$1;
4568
+ const refTypeName = ref$1.id;
4569
+ const chainFields = ref$1.chain.map((c) => c.text);
4570
+ const targetUnwound = doc.unwindType(refTypeName);
4571
+ if (targetUnwound) {
4572
+ const targetDef = targetUnwound.def;
4573
+ if (isInterface(targetDef) || isStructure(targetDef)) {
4574
+ const struct = isInterface(targetDef) ? targetDef.getDefinition() : targetDef;
4575
+ if (struct && isStructure(struct) && chainFields.length > 0) {
4576
+ const targetProp = struct.props.get(chainFields[0]);
4577
+ if (targetProp) {
4578
+ if (targetProp.countAnnotations("meta.id") === 0 && targetProp.countAnnotations("db.index.unique") === 0) errors.push({
4579
+ message: `@db.rel.FK target '${refTypeName}.${chainFields.join(".")}' is not a primary key (@meta.id) or unique (@db.index.unique) field`,
4580
+ severity: 1,
4581
+ range: token.range
4582
+ });
4583
+ const propDef = targetProp.getDefinition();
4584
+ if (propDef && isRef(propDef)) {
4585
+ const propUnwound = targetUnwound.doc.unwindType(propDef.id, propDef.chain);
4586
+ if (propUnwound && !isPrimitive(propUnwound.def)) errors.push({
4587
+ message: `Foreign key field must resolve to a scalar type (number, string, etc.), got '${propDef.id}'`,
4588
+ severity: 1,
4589
+ range: token.range
4590
+ });
4591
+ } else if (propDef && !isPrimitive(propDef)) errors.push({
4592
+ message: `Foreign key field must resolve to a scalar type (number, string, etc.)`,
4593
+ severity: 1,
4594
+ range: token.range
4595
+ });
4596
+ }
4597
+ }
4598
+ }
4599
+ }
4600
+ if (!alias) {
4601
+ const struct = getParentStruct(token);
4602
+ if (struct) {
4603
+ let sameTargetCount = 0;
4604
+ for (const [, prop] of struct.props) {
4605
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
4606
+ const def = prop.getDefinition();
4607
+ if (!def || !isRef(def)) continue;
4608
+ const r = def;
4609
+ if (!r.hasChain) continue;
4610
+ if (r.id === refTypeName) {
4611
+ const fkAnnotations = prop.annotations?.filter((a) => a.name === "db.rel.FK");
4612
+ const hasAlias = fkAnnotations?.some((a) => a.args.length > 0);
4613
+ if (!hasAlias) sameTargetCount++;
4614
+ }
4615
+ }
4616
+ if (sameTargetCount > 1) errors.push({
4617
+ message: `Multiple @db.rel.FK fields resolve to type '${refTypeName}' — add alias to disambiguate`,
4618
+ severity: 1,
4619
+ range: token.range
4620
+ });
4621
+ }
4622
+ }
4623
+ return errors;
4624
+ }
4625
+ }),
4626
+ to: new AnnotationSpec({
4627
+ description: "Forward navigational property — the FK is on **this** interface. The compiler resolves the matching @db.rel.FK by target type or alias.\n\n**Example:**\n```atscript\n@db.rel.to\nauthor?: User\n\n// With alias\n@db.rel.to \"author\"\nauthor?: User\n```\n",
4628
+ nodeType: ["prop"],
4629
+ argument: {
4630
+ optional: true,
4631
+ name: "alias",
4632
+ type: "string",
4633
+ description: "Match a local @db.rel.FK by alias."
4634
+ },
4635
+ validate(token, args, doc) {
4636
+ const errors = [];
4637
+ const field = token.parentNode;
4638
+ const alias = args[0]?.text;
4639
+ const owner = getDbTableOwner(token);
4640
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
4641
+ message: "@db.rel.to is only valid on fields of a @db.table interface",
4642
+ severity: 1,
4643
+ range: token.range
4644
+ });
4645
+ if (field.countAnnotations("db.rel.FK") > 0) errors.push({
4646
+ message: "A field cannot be both a foreign key and a navigational property",
4647
+ severity: 1,
4648
+ range: token.range
4649
+ });
4650
+ const targetTypeName = getNavTargetTypeName(field);
4651
+ if (!targetTypeName) return errors;
4652
+ const unwound = doc.unwindType(targetTypeName);
4653
+ if (unwound) {
4654
+ const targetDef = unwound.def;
4655
+ const targetNode = isInterface(targetDef) ? targetDef : undefined;
4656
+ if (!targetNode || targetNode.countAnnotations("db.table") === 0) errors.push({
4657
+ message: `@db.rel.to target '${targetTypeName}' is not a @db.table entity`,
4658
+ severity: 1,
4659
+ range: token.range
4660
+ });
4661
+ }
4662
+ const fieldDef = field.getDefinition();
4663
+ if (fieldDef && fieldDef.entity === "group" && fieldDef.op === "|") errors.push({
4664
+ message: "@db.rel.to does not support union types — use separate relations",
4665
+ severity: 1,
4666
+ range: token.range
4667
+ });
4668
+ const struct = getParentStruct(token);
4669
+ if (struct) {
4670
+ const fieldName = field.id;
4671
+ for (const [name, prop] of struct.props) {
4672
+ if (name === fieldName) continue;
4673
+ if (prop.countAnnotations("db.rel.to") === 0) continue;
4674
+ const propAlias = getAnnotationAlias(prop, "db.rel.to");
4675
+ if ((alias || undefined) === (propAlias || undefined)) {
4676
+ const otherTarget = getNavTargetTypeName(prop);
4677
+ if (otherTarget === targetTypeName) {
4678
+ errors.push({
4679
+ message: `Duplicate @db.rel.to '${alias || targetTypeName}' — only one forward navigational property per alias`,
4680
+ severity: 1,
4681
+ range: token.range
4682
+ });
4683
+ break;
4684
+ }
4685
+ }
4686
+ }
4687
+ if (alias) {
4688
+ const matches = findFKFieldsPointingTo(doc, struct, targetTypeName, alias);
4689
+ if (matches.length === 0) errors.push({
4690
+ message: `No @db.rel.FK '${alias}' found on this interface`,
4691
+ severity: 1,
4692
+ range: token.range
4693
+ });
4694
+ } else {
4695
+ const matches = findFKFieldsPointingTo(doc, struct, targetTypeName);
4696
+ if (matches.length === 0) errors.push({
4697
+ message: `No @db.rel.FK on this interface points to '${targetTypeName}' — did you mean @db.rel.from?`,
4698
+ severity: 1,
4699
+ range: token.range
4700
+ });
4701
+ else if (matches.length > 1) errors.push({
4702
+ message: `Multiple @db.rel.FK fields point to '${targetTypeName}' — add alias to disambiguate`,
4703
+ severity: 1,
4704
+ range: token.range
4705
+ });
4706
+ }
4707
+ }
4708
+ return errors;
4709
+ }
4710
+ }),
4711
+ from: new AnnotationSpec({
4712
+ description: "Inverse navigational property — the FK is on the **target** interface, pointing back to this one.\n\n**Example:**\n```atscript\n@db.rel.from\nposts: Post[]\n\n// With alias\n@db.rel.from \"original\"\ncomments: Comment[]\n```\n",
4713
+ nodeType: ["prop"],
4714
+ argument: {
4715
+ optional: true,
4716
+ name: "alias",
4717
+ type: "string",
4718
+ description: "Match a @db.rel.FK on the target interface by alias."
4719
+ },
4720
+ validate(token, args, doc) {
4721
+ const errors = [];
4722
+ const field = token.parentNode;
4723
+ const alias = args[0]?.text;
4724
+ const owner = getDbTableOwner(token);
4725
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
4726
+ message: "@db.rel.from is only valid on fields of a @db.table interface",
4727
+ severity: 1,
4728
+ range: token.range
4729
+ });
4730
+ if (field.countAnnotations("db.rel.FK") > 0) errors.push({
4731
+ message: "A field cannot be both a foreign key and a navigational property",
4732
+ severity: 1,
4733
+ range: token.range
4734
+ });
4735
+ const targetTypeName = getNavTargetTypeName(field);
4736
+ if (!targetTypeName) return errors;
4737
+ const unwound = doc.unwindType(targetTypeName);
4738
+ if (!unwound) return errors;
4739
+ const targetDef = unwound.def;
4740
+ const targetDoc = unwound.doc;
4741
+ if (!isInterface(targetDef) || targetDef.countAnnotations("db.table") === 0) {
4742
+ errors.push({
4743
+ message: `@db.rel.from target '${targetTypeName}' is not a @db.table entity`,
4744
+ severity: 1,
4745
+ range: token.range
4746
+ });
4747
+ return errors;
4748
+ }
4749
+ const struct = getParentStruct(token);
4750
+ if (struct) {
4751
+ const fieldName = field.id;
4752
+ for (const [name, prop] of struct.props) {
4753
+ if (name === fieldName) continue;
4754
+ if (prop.countAnnotations("db.rel.from") === 0) continue;
4755
+ const propAlias = getAnnotationAlias(prop, "db.rel.from");
4756
+ if ((alias || undefined) === (propAlias || undefined)) {
4757
+ const otherTarget = getNavTargetTypeName(prop);
4758
+ if (otherTarget === targetTypeName) {
4759
+ errors.push({
4760
+ message: `Duplicate @db.rel.from '${alias || targetTypeName}' — only one inverse navigational property per alias`,
4761
+ severity: 1,
4762
+ range: token.range
4763
+ });
4764
+ break;
4765
+ }
4766
+ }
4767
+ }
4768
+ }
4769
+ const thisTypeName = getParentTypeName(token);
4770
+ if (!thisTypeName) return errors;
4771
+ const matches = findFKFieldsPointingTo(targetDoc, targetDef, thisTypeName, alias);
4772
+ if (alias) {
4773
+ if (matches.length === 0) errors.push({
4774
+ message: `No @db.rel.FK '${alias}' found on '${targetTypeName}'`,
4775
+ severity: 1,
4776
+ range: token.range
4777
+ });
4778
+ } else if (matches.length === 0) errors.push({
4779
+ message: `No @db.rel.FK on '${targetTypeName}' points to '${thisTypeName}'`,
4780
+ severity: 1,
4781
+ range: token.range
4782
+ });
4783
+ else if (matches.length > 1) errors.push({
4784
+ message: `'${targetTypeName}' has multiple @db.rel.FK fields pointing to '${thisTypeName}' — add alias`,
4785
+ severity: 1,
4786
+ range: token.range
4787
+ });
4788
+ const fieldDef = field.getDefinition();
4789
+ if (!isArray(fieldDef) && matches.length === 1) {
4790
+ const fkProp = matches[0].prop;
4791
+ if (fkProp.countAnnotations("db.index.unique") === 0) errors.push({
4792
+ message: `@db.rel.from '${field.id}' has singular type '${targetTypeName}' (1:1) but the FK on '${targetTypeName}' is not @db.index.unique — did you mean '${targetTypeName}[]' (1:N)?`,
4793
+ severity: 2,
4794
+ range: token.range
4795
+ });
4796
+ }
4797
+ return errors;
4798
+ }
4799
+ }),
4800
+ onDelete: refActionAnnotation("onDelete"),
4801
+ onUpdate: refActionAnnotation("onUpdate"),
4802
+ via: new AnnotationSpec({
4803
+ description: "Declares a many-to-many navigational property through an explicit junction table. `@db.rel.via` is self-sufficient — no `@db.rel.from` pairing is needed.\n\n**Example:**\n```atscript\n@db.rel.via PostTag\ntags: Tag[]\n```\n",
4804
+ nodeType: ["prop"],
4805
+ argument: {
4806
+ name: "junction",
4807
+ type: "ref",
4808
+ description: "The junction table type (must have @db.table and @db.rel.FK fields pointing to both sides)."
4809
+ },
4810
+ validate(token, args, doc) {
4811
+ const errors = [];
4812
+ const field = token.parentNode;
4813
+ if (field.countAnnotations("db.rel.to") > 0 || field.countAnnotations("db.rel.from") > 0) errors.push({
4814
+ message: "@db.rel.via is self-sufficient — cannot be combined with @db.rel.to or @db.rel.from",
4815
+ severity: 1,
4816
+ range: token.range
4817
+ });
4818
+ const definition$1 = field.getDefinition();
4819
+ if (!isArray(definition$1)) errors.push({
4820
+ message: "@db.rel.via requires an array type (e.g. Tag[])",
4821
+ severity: 1,
4822
+ range: token.range
4823
+ });
4824
+ if (!args[0]) return errors;
4825
+ const junctionName = args[0].text;
4826
+ errors.push(...validateRefArgument(args[0], doc, { requireDbTable: true }));
4827
+ if (errors.length > 0) return errors;
4828
+ const junctionUnwound = doc.unwindType(junctionName);
4829
+ if (!junctionUnwound) return errors;
4830
+ const junctionDef = junctionUnwound.def;
4831
+ if (!isInterface(junctionDef)) return errors;
4832
+ const thisTypeName = getParentTypeName(token);
4833
+ const targetTypeName = getNavTargetTypeName(field);
4834
+ if (!thisTypeName || !targetTypeName) return errors;
4835
+ const fksToThis = findFKFieldsPointingTo(junctionUnwound.doc, junctionDef, thisTypeName);
4836
+ if (fksToThis.length === 0) errors.push({
4837
+ message: `Junction '${junctionName}' has no @db.rel.FK pointing to '${thisTypeName}'`,
4838
+ severity: 1,
4839
+ range: args[0].range
4840
+ });
4841
+ else if (fksToThis.length > 1) errors.push({
4842
+ message: `Junction '${junctionName}' has multiple @db.rel.FK pointing to '${thisTypeName}' — not supported`,
4843
+ severity: 1,
4844
+ range: args[0].range
4845
+ });
4846
+ if (targetTypeName !== thisTypeName) {
4847
+ const fksToTarget = findFKFieldsPointingTo(junctionUnwound.doc, junctionDef, targetTypeName);
4848
+ if (fksToTarget.length === 0) errors.push({
4849
+ message: `Junction '${junctionName}' has no @db.rel.FK pointing to '${targetTypeName}'`,
4850
+ severity: 1,
4851
+ range: args[0].range
4852
+ });
4853
+ else if (fksToTarget.length > 1) errors.push({
4854
+ message: `Junction '${junctionName}' has multiple @db.rel.FK pointing to '${targetTypeName}' — not supported`,
4855
+ severity: 1,
4856
+ range: args[0].range
4857
+ });
4858
+ }
4859
+ return errors;
4860
+ }
4861
+ }),
4862
+ filter: new AnnotationSpec({
4863
+ description: "Applies a filter to a navigational property, restricting which related records are loaded.\n\n**Example:**\n```atscript\n@db.rel.from\n@db.rel.filter `Post.published = true`\npublishedPosts: Post[]\n```\n",
4864
+ nodeType: ["prop"],
4865
+ argument: {
4866
+ name: "condition",
4867
+ type: "query",
4868
+ description: "Filter expression restricting which related records are loaded."
4869
+ },
4870
+ validate(token, args, doc) {
4871
+ const errors = [];
4872
+ const field = token.parentNode;
4873
+ const hasTo = field.countAnnotations("db.rel.to") > 0;
4874
+ const hasFrom = field.countAnnotations("db.rel.from") > 0;
4875
+ const hasVia = field.countAnnotations("db.rel.via") > 0;
4876
+ if (!hasTo && !hasFrom && !hasVia) {
4877
+ errors.push({
4878
+ message: "@db.rel.filter is only valid on navigational fields (@db.rel.to, @db.rel.from, or @db.rel.via)",
4879
+ severity: 1,
4880
+ range: token.range
4881
+ });
4882
+ return errors;
4883
+ }
4884
+ if (!args[0]?.queryNode) return errors;
4885
+ const targetTypeName = getNavTargetTypeName(field);
4886
+ if (!targetTypeName) return errors;
4887
+ const allowedTypes = [targetTypeName];
4888
+ if (hasVia) {
4889
+ const viaAnnotations = field.annotations?.filter((a) => a.name === "db.rel.via");
4890
+ if (viaAnnotations?.[0]?.args[0]) allowedTypes.push(viaAnnotations[0].args[0].text);
4891
+ }
4892
+ errors.push(...validateQueryScope(args[0], allowedTypes, targetTypeName, doc));
4893
+ return errors;
4894
+ }
4895
+ })
4896
+ },
4897
+ view: {
4898
+ $self: new AnnotationSpec({
4899
+ description: "Marks an interface as a **database view**. Optionally takes a view name argument.\n\n**Example:**\n```atscript\n@db.view \"active_premium_users\"\n@db.view.for User\nexport interface ActivePremiumUser { ... }\n```\n",
4900
+ nodeType: ["interface"],
4901
+ argument: {
4902
+ optional: true,
4903
+ name: "name",
4904
+ type: "string",
4905
+ description: "The view name in the database. If omitted, derived from the interface name."
4906
+ },
4907
+ validate(token, _args, _doc) {
4908
+ const errors = [];
4909
+ const owner = token.parentNode;
4910
+ if (owner.countAnnotations("db.table") > 0) errors.push({
4911
+ message: "An interface cannot be both a @db.table and a @db.view",
4912
+ severity: 1,
4913
+ range: token.range
4914
+ });
4915
+ return errors;
4916
+ }
4917
+ }),
4918
+ for: new AnnotationSpec({
4919
+ description: "Specifies the entry/primary table for a computed view. Required for views that map fields via chain refs.\n\n**Example:**\n```atscript\n@db.view.for Order\n@db.view.filter `Order.status = 'active'`\nexport interface ActiveOrderDetails { ... }\n```\n",
4920
+ nodeType: ["interface"],
4921
+ argument: {
4922
+ name: "entry",
4923
+ type: "ref",
4924
+ description: "The primary/entry table type (must have @db.table)."
4925
+ },
4926
+ validate(token, args, doc) {
4927
+ const errors = [];
4928
+ const owner = token.parentNode;
4929
+ if (owner.countAnnotations("db.table") > 0) errors.push({
4930
+ message: "An interface cannot be both a @db.table and a @db.view",
4931
+ severity: 1,
4932
+ range: token.range
4933
+ });
4934
+ if (args[0]) errors.push(...validateRefArgument(args[0], doc, { requireDbTable: true }));
4935
+ return errors;
4936
+ }
4937
+ }),
4938
+ joins: new AnnotationSpec({
4939
+ description: "Declares an explicit join for a view. Use when no `@db.rel.*` path exists between the entry table and the target.\n\n**Example:**\n```atscript\n@db.view.for Order\n@db.view.joins Warehouse, `Warehouse.regionId = Order.regionId`\nexport interface OrderWarehouse { ... }\n```\n",
4940
+ nodeType: ["interface"],
4941
+ multiple: true,
4942
+ mergeStrategy: "append",
4943
+ argument: [{
4944
+ name: "target",
4945
+ type: "ref",
4946
+ description: "The table type to join (must have @db.table)."
4947
+ }, {
4948
+ name: "condition",
4949
+ type: "query",
4950
+ description: "Join condition expression."
4951
+ }],
4952
+ validate(token, args, doc) {
4953
+ const errors = [];
4954
+ const owner = token.parentNode;
4955
+ if (!hasAnyViewAnnotation(owner) && !args[0]) {
4956
+ errors.push({
4957
+ message: "@db.view.joins is only valid on @db.view interfaces",
4958
+ severity: 1,
4959
+ range: token.range
4960
+ });
4961
+ return errors;
4962
+ }
4963
+ if (args[0]) errors.push(...validateRefArgument(args[0], doc, { requireDbTable: true }));
4964
+ const forAnnotations = owner.annotations?.filter((a) => a.name === "db.view.for");
4965
+ const entryTypeName = forAnnotations?.[0]?.args[0]?.text;
4966
+ if (!entryTypeName) {
4967
+ errors.push({
4968
+ message: "@db.view.joins requires @db.view.for to identify the entry table",
4969
+ severity: 1,
4970
+ range: token.range
4971
+ });
4972
+ return errors;
4973
+ }
4974
+ if (args[1]?.queryNode && args[0]) {
4975
+ const joinTargetName = args[0].text;
4976
+ errors.push(...validateQueryScope(args[1], [joinTargetName, entryTypeName], entryTypeName, doc));
4977
+ }
4978
+ return errors;
4979
+ }
4980
+ }),
4981
+ filter: new AnnotationSpec({
4982
+ description: "WHERE clause for a view, filtering which rows are included.\n\n**Example:**\n```atscript\n@db.view.for User\n@db.view.filter `User.status = 'active' and User.age >= 18`\nexport interface ActiveUser { ... }\n```\n",
4983
+ nodeType: ["interface"],
4984
+ argument: {
4985
+ name: "condition",
4986
+ type: "query",
4987
+ description: "Filter expression for the view WHERE clause."
4988
+ },
4989
+ validate(token, args, doc) {
4990
+ const errors = [];
4991
+ const owner = token.parentNode;
4992
+ if (!hasAnyViewAnnotation(owner) && !args[0]) {
4993
+ errors.push({
4994
+ message: "@db.view.filter is only valid on @db.view interfaces",
4995
+ severity: 1,
4996
+ range: token.range
4997
+ });
4998
+ return errors;
4999
+ }
5000
+ if (!args[0]?.queryNode) return errors;
5001
+ const forAnnotations = owner.annotations?.filter((a) => a.name === "db.view.for");
5002
+ const entryTypeName = forAnnotations?.[0]?.args[0]?.text;
5003
+ if (!entryTypeName) {
5004
+ errors.push({
5005
+ message: "@db.view.filter requires @db.view.for to identify the entry table",
5006
+ severity: 1,
5007
+ range: token.range
5008
+ });
5009
+ return errors;
5010
+ }
5011
+ const allowedTypes = [entryTypeName];
5012
+ const joinsAnnotations = owner.annotations?.filter((a) => a.name === "db.view.joins");
5013
+ if (joinsAnnotations) {
5014
+ for (const join of joinsAnnotations) if (join.args[0]) allowedTypes.push(join.args[0].text);
5015
+ }
5016
+ errors.push(...validateQueryScope(args[0], allowedTypes, entryTypeName, doc));
5017
+ return errors;
5018
+ }
5019
+ }),
5020
+ materialized: new AnnotationSpec({
5021
+ description: "Marks a view as materialized (precomputed, stored on disk). Supported by PostgreSQL, CockroachDB, Oracle, SQL Server (indexed views), Snowflake. MongoDB supports on-demand materialized views via $merge/$out. Not applicable to MySQL or SQLite.\n\n**Example:**\n```atscript\n@db.view.materialized\n@db.view.for User\n@db.view.filter `User.status = 'active'`\nexport interface ActiveUsers { ... }\n```\n",
5022
+ nodeType: ["interface"],
5023
+ validate(token, _args, _doc) {
5024
+ const errors = [];
5025
+ const owner = token.parentNode;
5026
+ if (!hasAnyViewAnnotation(owner)) errors.push({
5027
+ message: "@db.view.materialized is only valid on @db.view interfaces",
5028
+ severity: 1,
5029
+ range: token.range
5030
+ });
5031
+ return errors;
5032
+ }
5033
+ }),
5034
+ renamed: new AnnotationSpec({
5035
+ description: "Specifies the previous view name for view rename migration. The sync engine drops the old view and creates the new one.\n\n**Example:**\n```atscript\n@db.view \"active_premium_users\"\n@db.view.renamed \"active_users\"\n@db.view.for User\nexport interface ActivePremiumUser { ... }\n```\n",
5036
+ nodeType: ["interface"],
5037
+ argument: {
5038
+ name: "oldName",
5039
+ type: "string",
5040
+ description: "The previous view name."
5041
+ },
5042
+ validate(token, _args, _doc) {
5043
+ const errors = [];
5044
+ const owner = token.parentNode;
5045
+ if (!hasAnyViewAnnotation(owner)) errors.push({
5046
+ message: "@db.view.renamed requires @db.view on the same interface",
5047
+ severity: 1,
5048
+ range: token.range
5049
+ });
5050
+ return errors;
5051
+ }
5052
+ })
5053
+ }
3415
5054
  };
3416
5055
 
3417
5056
  //#endregion
@@ -4110,8 +5749,12 @@ var PluginManager = class {
4110
5749
  return this._loopInAnnotationsSpec(annotations$1, cb);
4111
5750
  }
4112
5751
  _loopInAnnotationsSpec(annotations$1, cb, prefix) {
4113
- for (const [key, value] of Object.entries(annotations$1)) if (isAnnotationSpec(value)) cb(prefix ? `${prefix}.${key}` : key, value);
5752
+ if (annotations$1.$self && prefix) cb(prefix, annotations$1.$self);
5753
+ for (const [key, value] of Object.entries(annotations$1)) {
5754
+ if (key === "$self") continue;
5755
+ if (isAnnotationSpec(value)) cb(prefix ? `${prefix}.${key}` : key, value);
4114
5756
  else this._loopInAnnotationsSpec(value, cb, prefix ? `${prefix}.${key}` : key);
5757
+ }
4115
5758
  }
4116
5759
  constructor(cfg) {
4117
5760
  _define_property$2(this, "cfg", void 0);
@@ -4150,6 +5793,11 @@ var AtscriptRepo = class {
4150
5793
  return new Set(tags);
4151
5794
  }
4152
5795
  async getUsedAnnotations() {
5796
+ const ANNOTATION_TYPE_MAP = {
5797
+ ref: "import(\"@atscript/typescript/utils\").AtscriptRef",
5798
+ query: "import(\"@atscript/typescript/utils\").AtscriptQueryNode"
5799
+ };
5800
+ const mapArgType = (t) => ANNOTATION_TYPE_MAP[t] || t;
4153
5801
  const manager = await this.getSharedPluginManager();
4154
5802
  const annotations$1 = {};
4155
5803
  if (manager) await manager.loopInAnnotationsSpec((name, spec) => {
@@ -4161,12 +5809,12 @@ var AtscriptRepo = class {
4161
5809
  props: {}
4162
5810
  };
4163
5811
  for (const a of spec.arguments) o.props[a.name] = {
4164
- type: a.type,
5812
+ type: mapArgType(a.type),
4165
5813
  optional: a.optional
4166
5814
  };
4167
5815
  types.push(o);
4168
5816
  } else if (spec.config.argument) types.push({
4169
- type: spec.config.argument.type,
5817
+ type: mapArgType(spec.config.argument.type),
4170
5818
  optional: spec.config.argument.optional
4171
5819
  });
4172
5820
  else types.push({ type: "boolean" });
@@ -4307,34 +5955,28 @@ else types.push({ type: "boolean" });
4307
5955
  async checkImport(atscript, from, imports, checked) {
4308
5956
  const forId = resolveAtscriptFromPath(from.text, atscript.id);
4309
5957
  if (forId === atscript.id) {
4310
- const messages = atscript.getDiagMessages();
4311
- messages.push({
5958
+ atscript.registerMessages([{
4312
5959
  severity: 1,
4313
5960
  message: "\"import\" cannot import itself",
4314
5961
  range: from.range
4315
- });
5962
+ }]);
4316
5963
  return;
4317
5964
  }
4318
- const errors = [];
4319
5965
  let external;
4320
5966
  try {
4321
5967
  external = await this.openDocument(forId);
4322
5968
  await this.checkImports(external, checked);
4323
- for (const token of imports) if (!external.exports.has(token.text)) errors.push({
5969
+ for (const token of imports) if (!external.exports.has(token.text)) atscript.registerMessages([{
4324
5970
  severity: 1,
4325
5971
  message: `"${from.text}" has no exported member "${token.text}"`,
4326
5972
  range: token.range
4327
- });
5973
+ }]);
4328
5974
  } catch (error) {
4329
- errors.push({
5975
+ atscript.registerMessages([{
4330
5976
  severity: 1,
4331
5977
  message: `"${from.text}" not found`,
4332
5978
  range: from.range
4333
- });
4334
- }
4335
- if (errors.length > 0) {
4336
- const messages = atscript.getDiagMessages();
4337
- messages.push(...errors);
5979
+ }]);
4338
5980
  }
4339
5981
  return external;
4340
5982
  }
@@ -4395,7 +6037,9 @@ else {
4395
6037
  }
4396
6038
  const documents = [];
4397
6039
  for (const entry of entries) documents.push(await repo.openDocument(`file://${entry}`));
4398
- return new BuildRepo(rootDir, repo, documents.filter(Boolean));
6040
+ const docs = documents.filter(Boolean);
6041
+ for (const doc of docs) await repo.checkDoc(doc);
6042
+ return new BuildRepo(rootDir, repo, docs);
4399
6043
  }
4400
6044
  var BuildRepo = class {
4401
6045
  getDoc(id) {
@@ -4403,10 +6047,7 @@ var BuildRepo = class {
4403
6047
  }
4404
6048
  async diagnostics() {
4405
6049
  const docMessages = new Map();
4406
- for (const document of this.docs) {
4407
- await this.repo.checkDoc(document);
4408
- docMessages.set(document.id, document.getDiagMessages());
4409
- }
6050
+ for (const document of this.docs) docMessages.set(document.id, document.getDiagMessages());
4410
6051
  return docMessages;
4411
6052
  }
4412
6053
  async generate(config, docs = this.docs) {
@@ -4449,14 +6090,14 @@ var BuildRepo = class {
4449
6090
 
4450
6091
  //#endregion
4451
6092
  //#region packages/core/src/flatten.ts
4452
- function flattenInterfaceNode(doc, node) {
6093
+ function flattenInterfaceNode(doc, node, options) {
4453
6094
  const flatMap = new Map();
4454
6095
  const stack = new Set();
4455
6096
  let struct;
4456
6097
  if (node.hasExtends) struct = doc.resolveInterfaceExtends(node);
4457
6098
  if (!struct) struct = node.getDefinition();
4458
6099
  if (!struct || !isStructure(struct)) return flatMap;
4459
- walkStructure(doc, struct, "", false, flatMap, stack);
6100
+ walkStructure(doc, struct, "", false, flatMap, stack, options);
4460
6101
  return flatMap;
4461
6102
  }
4462
6103
  /**
@@ -4471,6 +6112,10 @@ function flattenInterfaceNode(doc, node) {
4471
6112
  if (!prop.annotations) return false;
4472
6113
  return prop.annotations.some((a) => a.name === "db.json");
4473
6114
  }
6115
+ function hasNavPropAnnotation(prop) {
6116
+ if (!prop.annotations) return false;
6117
+ return prop.annotations.some((a) => a.name === "db.rel.to" || a.name === "db.rel.from" || a.name === "db.rel.via");
6118
+ }
4474
6119
  function isPhantomNode(doc, def) {
4475
6120
  if (!def) return false;
4476
6121
  if (isPrimitive(def) && def.config.type === "phantom") return true;
@@ -4519,11 +6164,12 @@ function addToFlatMap(flatMap, path$5, descriptor) {
4519
6164
  });
4520
6165
  } else flatMap.set(path$5, descriptor);
4521
6166
  }
4522
- function walkStructure(doc, struct, prefix, parentOptional, flatMap, stack) {
6167
+ function walkStructure(doc, struct, prefix, parentOptional, flatMap, stack, options) {
4523
6168
  for (const [name, prop] of struct.props) {
4524
6169
  if (prop.token("identifier")?.pattern) continue;
4525
6170
  const propDef = prop.getDefinition();
4526
6171
  if (isPhantomNode(doc, propDef)) continue;
6172
+ if (options?.skipNavProps && hasNavPropAnnotation(prop)) continue;
4527
6173
  const path$5 = prefix ? `${prefix}.${name}` : name;
4528
6174
  const optional = parentOptional || !!prop.token("optional");
4529
6175
  const dbJson = hasDbJsonAnnotation(prop);
@@ -4556,10 +6202,10 @@ function walkStructure(doc, struct, prefix, parentOptional, flatMap, stack) {
4556
6202
  });
4557
6203
  continue;
4558
6204
  }
4559
- walkNode(resolved.doc, resolved.def, path$5, optional, prop, flatMap, stack);
6205
+ walkNode(resolved.doc, resolved.def, path$5, optional, prop, flatMap, stack, options);
4560
6206
  }
4561
6207
  }
4562
- function walkNode(doc, def, path$5, optional, propNode, flatMap, stack) {
6208
+ function walkNode(doc, def, path$5, optional, propNode, flatMap, stack, options) {
4563
6209
  if (stack.has(def)) {
4564
6210
  addToFlatMap(flatMap, path$5, {
4565
6211
  def,
@@ -4579,7 +6225,7 @@ function walkNode(doc, def, path$5, optional, propNode, flatMap, stack) {
4579
6225
  propNode,
4580
6226
  intermediate: true
4581
6227
  });
4582
- walkStructure(doc, def, path$5, optional, flatMap, stack);
6228
+ walkStructure(doc, def, path$5, optional, flatMap, stack, options);
4583
6229
  } else if (isArray(def)) {
4584
6230
  const elementDef = def.getDefinition();
4585
6231
  const resolvedElement = elementDef ? resolveNode(doc, elementDef) : undefined;
@@ -4592,7 +6238,7 @@ function walkNode(doc, def, path$5, optional, propNode, flatMap, stack) {
4592
6238
  propNode,
4593
6239
  intermediate: true
4594
6240
  });
4595
- walkArrayElement(doc, def, path$5, optional, flatMap, stack);
6241
+ walkArrayElement(doc, def, path$5, optional, flatMap, stack, options);
4596
6242
  } else addToFlatMap(flatMap, path$5, {
4597
6243
  def,
4598
6244
  doc,
@@ -4611,7 +6257,7 @@ function walkNode(doc, def, path$5, optional, propNode, flatMap, stack) {
4611
6257
  propNode,
4612
6258
  intermediate: true
4613
6259
  });
4614
- walkStructure(doc, merged, path$5, optional, flatMap, stack);
6260
+ walkStructure(doc, merged, path$5, optional, flatMap, stack, options);
4615
6261
  } else addToFlatMap(flatMap, path$5, {
4616
6262
  def,
4617
6263
  doc,
@@ -4643,7 +6289,7 @@ else addToFlatMap(flatMap, path$5, {
4643
6289
  });
4644
6290
  for (const branch of branches) {
4645
6291
  const resolved = resolveNode(doc, branch);
4646
- if (resolved) walkBranch(resolved.doc, resolved.def, path$5, optional, flatMap, stack);
6292
+ if (resolved) walkBranch(resolved.doc, resolved.def, path$5, optional, flatMap, stack, options);
4647
6293
  }
4648
6294
  } else addToFlatMap(flatMap, path$5, {
4649
6295
  def,
@@ -4667,27 +6313,27 @@ else addToFlatMap(flatMap, path$5, {
4667
6313
  stack.delete(def);
4668
6314
  }
4669
6315
  }
4670
- function walkArrayElement(doc, arrayNode, prefix, parentOptional, flatMap, stack) {
6316
+ function walkArrayElement(doc, arrayNode, prefix, parentOptional, flatMap, stack, options) {
4671
6317
  const elementDef = arrayNode.getDefinition();
4672
6318
  if (!elementDef) return;
4673
6319
  const resolved = resolveNode(doc, elementDef);
4674
6320
  if (!resolved) return;
4675
- walkBranch(resolved.doc, resolved.def, prefix, parentOptional, flatMap, stack);
6321
+ walkBranch(resolved.doc, resolved.def, prefix, parentOptional, flatMap, stack, options);
4676
6322
  }
4677
6323
  /**
4678
6324
  * Walks a branch (union branch or array element) to collect sub-paths.
4679
6325
  * Does NOT add an entry for the branch itself — the parent already did that.
4680
- */ function walkBranch(doc, def, prefix, parentOptional, flatMap, stack) {
4681
- if (isStructure(def)) walkStructure(doc, def, prefix, parentOptional, flatMap, stack);
4682
- else if (isArray(def)) walkArrayElement(doc, def, prefix, parentOptional, flatMap, stack);
6326
+ */ function walkBranch(doc, def, prefix, parentOptional, flatMap, stack, options) {
6327
+ if (isStructure(def)) walkStructure(doc, def, prefix, parentOptional, flatMap, stack, options);
6328
+ else if (isArray(def)) walkArrayElement(doc, def, prefix, parentOptional, flatMap, stack, options);
4683
6329
  else if (isGroup(def) && def.entity !== "structure") {
4684
6330
  const group$1 = def;
4685
6331
  if (group$1.op === "&") {
4686
6332
  const merged = doc.mergeIntersection(def);
4687
- if (isStructure(merged)) walkStructure(doc, merged, prefix, parentOptional, flatMap, stack);
6333
+ if (isStructure(merged)) walkStructure(doc, merged, prefix, parentOptional, flatMap, stack, options);
4688
6334
  } else if (group$1.op === "|") for (const branch of group$1.unwrap()) {
4689
6335
  const resolved = resolveNode(doc, branch);
4690
- if (resolved) walkBranch(resolved.doc, resolved.def, prefix, parentOptional, flatMap, stack);
6336
+ if (resolved) walkBranch(resolved.doc, resolved.def, prefix, parentOptional, flatMap, stack, options);
4691
6337
  }
4692
6338
  }
4693
6339
  }
@@ -4709,16 +6355,28 @@ exports.SemanticInterfaceNode = SemanticInterfaceNode
4709
6355
  exports.SemanticNode = SemanticNode
4710
6356
  exports.SemanticPrimitiveNode = SemanticPrimitiveNode
4711
6357
  exports.SemanticPropNode = SemanticPropNode
6358
+ exports.SemanticQueryComparisonNode = SemanticQueryComparisonNode
6359
+ exports.SemanticQueryFieldRefNode = SemanticQueryFieldRefNode
6360
+ exports.SemanticQueryLogicalNode = SemanticQueryLogicalNode
6361
+ exports.SemanticQueryNode = SemanticQueryNode
6362
+ exports.SemanticQueryValueListNode = SemanticQueryValueListNode
6363
+ exports.SemanticQueryValueNode = SemanticQueryValueNode
4712
6364
  exports.SemanticRefNode = SemanticRefNode
4713
6365
  exports.SemanticStructureNode = SemanticStructureNode
4714
6366
  exports.SemanticTupleNode = SemanticTupleNode
4715
6367
  exports.SemanticTypeNode = SemanticTypeNode
4716
6368
  exports.Token = Token
6369
+ exports.analyzeQueryCursorContext = analyzeQueryCursorContext
4717
6370
  exports.build = build
4718
6371
  exports.createAtscriptPlugin = createAtscriptPlugin
4719
6372
  exports.defineConfig = defineConfig
6373
+ exports.findFKFieldsPointingTo = findFKFieldsPointingTo
4720
6374
  exports.flattenInterfaceNode = flattenInterfaceNode
6375
+ exports.getFieldsForType = getFieldsForType
6376
+ exports.getQueryCompletionScope = getQueryCompletionScope
6377
+ exports.getQueryScope = getQueryScope
4721
6378
  exports.getRelPath = getRelPath
6379
+ exports.hasNavPropAnnotation = hasNavPropAnnotation
4722
6380
  exports.isAnnotate = isAnnotate
4723
6381
  exports.isAnnotationSpec = isAnnotationSpec
4724
6382
  exports.isArray = isArray
@@ -4729,6 +6387,9 @@ exports.isInterface = isInterface
4729
6387
  exports.isPhantomNode = isPhantomNode
4730
6388
  exports.isPrimitive = isPrimitive
4731
6389
  exports.isProp = isProp
6390
+ exports.isQueryComparison = isQueryComparison
6391
+ exports.isQueryFieldRef = isQueryFieldRef
6392
+ exports.isQueryLogical = isQueryLogical
4732
6393
  exports.isRef = isRef
4733
6394
  exports.isStructure = isStructure
4734
6395
  exports.isTuple = isTuple
@@ -4737,4 +6398,6 @@ exports.loadConfig = loadConfig
4737
6398
  exports.loadTsConfig = loadTsConfig
4738
6399
  exports.resolveAnnotation = resolveAnnotation
4739
6400
  exports.resolveAtscriptFromPath = resolveAtscriptFromPath
4740
- exports.resolveConfigFile = resolveConfigFile
6401
+ exports.resolveConfigFile = resolveConfigFile
6402
+ exports.resolveQueryFieldRef = resolveQueryFieldRef
6403
+ exports.validateRefArgument = validateRefArgument