@atscript/core 0.1.32 → 0.1.34

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.mjs CHANGED
@@ -75,6 +75,7 @@ else this.annotationsCounter.set(name, 1);
75
75
  }
76
76
  define(node) {
77
77
  this.definition = node;
78
+ node.ownerNode = this;
78
79
  return this;
79
80
  }
80
81
  get def() {
@@ -128,6 +129,7 @@ else this.annotationsCounter.set(name, 1);
128
129
  _define_property$15(this, "annotations", void 0);
129
130
  _define_property$15(this, "annotationsCounter", void 0);
130
131
  _define_property$15(this, "__typeId", void 0);
132
+ _define_property$15(this, "ownerNode", void 0);
131
133
  _define_property$15(this, "_documentation", void 0);
132
134
  this.entity = entity;
133
135
  this.isGroup = false;
@@ -671,10 +673,12 @@ var SemanticStructureNode = class extends SemanticGroup {
671
673
  * Shortcut to set props, used as utility
672
674
  */ setProps(props$1) {
673
675
  this.nodes = props$1;
674
- for (const prop of props$1) this.props.set(prop.id, prop);
676
+ for (const prop of props$1) {
677
+ prop.ownerNode = this;
678
+ this.props.set(prop.id, prop);
679
+ }
675
680
  }
676
681
  registerAtDocument(doc) {
677
- super.registerAtDocument(doc);
678
682
  const block$2 = this.token("identifier");
679
683
  block$2.blockType = "structure";
680
684
  doc.blocksIndex.add(block$2);
@@ -697,8 +701,10 @@ var SemanticStructureNode = class extends SemanticGroup {
697
701
  doc.registerMessage(token, "Non-prop node");
698
702
  continue;
699
703
  }
704
+ node.ownerNode = this;
700
705
  this.props.set(name, node);
701
706
  }
707
+ super.registerAtDocument(doc);
702
708
  }
703
709
  addVirtualProp(opts) {
704
710
  const token = opts.refToken || this.token("identifier");
@@ -726,6 +732,7 @@ var SemanticStructureNode = class extends SemanticGroup {
726
732
  }
727
733
  prop.define(ref$1);
728
734
  } else prop.define(opts.type);
735
+ prop.ownerNode = this;
729
736
  this.nodes.push(prop);
730
737
  this.props.set(opts.name, prop);
731
738
  }
@@ -2711,14 +2718,14 @@ else {
2711
2718
  this.blocksIndex.add(block$2);
2712
2719
  block$2.blockType = "import";
2713
2720
  block$2.fromPath = from.text;
2721
+ this.tokensIndex.add(from);
2722
+ from.fromPath = from.text;
2714
2723
  imports.forEach((t) => {
2715
2724
  t.imported = true;
2716
2725
  t.fromPath = from.text;
2717
2726
  this.registerDefinition(t, true);
2718
2727
  this.tokensIndex.add(t);
2719
- this.tokensIndex.add(from);
2720
2728
  this.importedDefs.set(t.text, from);
2721
- from.fromPath = from.text;
2722
2729
  });
2723
2730
  }
2724
2731
  nextTypeId() {
@@ -2787,7 +2794,7 @@ else {
2787
2794
  getUnusedTokens() {
2788
2795
  const refSet = new Set(this.referred.filter((r) => !r.imported).map((r) => r.text));
2789
2796
  const tokens$1 = [];
2790
- for (const [key, token] of Array.from(this.registry.definitions.entries())) if (!refSet.has(key) && !this.exports.has(key)) tokens$1.push(token);
2797
+ for (const [key, token] of this.registry.definitions) if (!refSet.has(key) && !this.exports.has(key)) tokens$1.push(token);
2791
2798
  return tokens$1;
2792
2799
  }
2793
2800
  renderDiagMessage(m, addSourceLinses = false, colors = false) {
@@ -2841,7 +2848,7 @@ else {
2841
2848
  l: lines[n - 1],
2842
2849
  i: n - 1
2843
2850
  }
2844
- ].filter(Boolean);
2851
+ ].filter((r) => r.l !== undefined);
2845
2852
  const nl = String(n).length + 1;
2846
2853
  for (const { l, i } of renderLines) {
2847
2854
  const prefix = `${c.dim + c.cyan}${`0${i}`.slice(-nl)} | ${c.reset}`;
@@ -3038,13 +3045,7 @@ else {
3038
3045
  if (!left || !right) return [_left, _right];
3039
3046
  if (isPrimitive(left) && isPrimitive(right)) {
3040
3047
  if (left.config.type === right.config.type) return [left];
3041
- const never$1 = new SemanticRefNode();
3042
- never$1.saveToken(new Token({
3043
- text: "never",
3044
- type: "identifier",
3045
- getRange: () => zeroRange
3046
- }), "identifier");
3047
- return [never$1];
3048
+ return [createSyntheticRef("never")];
3048
3049
  }
3049
3050
  if ((isStructure(left) || isInterface(left)) && (isStructure(right) || isInterface(right))) {
3050
3051
  const mergedProps = [];
@@ -3062,15 +3063,7 @@ else {
3062
3063
  }
3063
3064
  const prop = new SemanticPropNode();
3064
3065
  prop.saveToken((leftProp || rightProp).token("identifier"), "identifier");
3065
- if (isPrimitive(mergedDef)) {
3066
- const name = mergedDef.id;
3067
- mergedDef = new SemanticRefNode();
3068
- mergedDef.saveToken(new Token({
3069
- text: name,
3070
- type: "identifier",
3071
- getRange: () => zeroRange
3072
- }), "identifier");
3073
- }
3066
+ if (isPrimitive(mergedDef)) mergedDef = createSyntheticRef(mergedDef.id);
3074
3067
  prop.define(mergedDef);
3075
3068
  prop.annotations = this.mergeNodesAnnotations(leftProp?.annotations, rightProp?.annotations);
3076
3069
  const oldProps = [leftProp, rightProp].filter(Boolean);
@@ -3084,17 +3077,10 @@ else {
3084
3077
  }
3085
3078
  const mergedStructure = new SemanticStructureNode();
3086
3079
  mergedStructure.setProps(mergedProps);
3087
- this.resolveAnnotation;
3088
3080
  mergedStructure.annotations = this.mergeNodesAnnotations(left.annotations, right.annotations);
3089
3081
  return [mergedStructure];
3090
3082
  }
3091
- const never = new SemanticRefNode();
3092
- never.saveToken(new Token({
3093
- text: "never",
3094
- type: "identifier",
3095
- getRange: () => zeroRange
3096
- }), "identifier");
3097
- return [never];
3083
+ return [createSyntheticRef("never")];
3098
3084
  }
3099
3085
  /**
3100
3086
  * Merges two arrays of annotation tokens, ensuring that annotations from the
@@ -3194,9 +3180,159 @@ const zeroRange = {
3194
3180
  character: 0
3195
3181
  }
3196
3182
  };
3183
+ function createSyntheticRef(name) {
3184
+ const ref$1 = new SemanticRefNode();
3185
+ ref$1.saveToken(new Token({
3186
+ text: name,
3187
+ type: "identifier",
3188
+ getRange: () => zeroRange
3189
+ }), "identifier");
3190
+ return ref$1;
3191
+ }
3192
+
3193
+ //#endregion
3194
+ //#region packages/core/src/defaults/db-utils.ts
3195
+ function findFKFieldsPointingTo(doc, iface, targetTypeName, alias) {
3196
+ const results = [];
3197
+ let struct;
3198
+ if (isInterface(iface) && iface.hasExtends) {
3199
+ const resolved = doc.resolveInterfaceExtends(iface);
3200
+ if (resolved && isStructure(resolved)) struct = resolved;
3201
+ }
3202
+ if (!struct) struct = isStructure(iface) ? iface : isInterface(iface) && isStructure(iface.getDefinition()) ? iface.getDefinition() : undefined;
3203
+ if (!struct) return results;
3204
+ for (const [name, prop] of struct.props) {
3205
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
3206
+ const def = prop.getDefinition();
3207
+ if (!def || !isRef(def)) continue;
3208
+ const ref$1 = def;
3209
+ if (!ref$1.hasChain) continue;
3210
+ const refTypeName = ref$1.id;
3211
+ const refField = ref$1.chain.map((c) => c.text).join(".");
3212
+ if (refTypeName !== targetTypeName) continue;
3213
+ if (alias !== undefined) {
3214
+ const fkAnnotations = prop.annotations?.filter((a) => a.name === "db.rel.FK");
3215
+ const hasMatchingAlias = fkAnnotations?.some((a) => a.args.length > 0 && a.args[0].text === alias);
3216
+ if (!hasMatchingAlias) continue;
3217
+ }
3218
+ results.push({
3219
+ name,
3220
+ prop,
3221
+ chainRef: {
3222
+ type: refTypeName,
3223
+ field: refField
3224
+ }
3225
+ });
3226
+ }
3227
+ return results;
3228
+ }
3197
3229
 
3198
3230
  //#endregion
3199
3231
  //#region packages/core/src/defaults/db-annotations.ts
3232
+ /**
3233
+ * Traverse from annotation token → prop → structure → interface
3234
+ * to check if the parent interface has @db.table.
3235
+ */ function getDbTableOwner(token) {
3236
+ const field = token.parentNode;
3237
+ const struct = field.ownerNode;
3238
+ if (!struct || !isStructure(struct)) return undefined;
3239
+ const iface = struct.ownerNode;
3240
+ return iface && isInterface(iface) ? iface : struct;
3241
+ }
3242
+ /**
3243
+ * Get the parent structure node from an annotation token.
3244
+ */ function getParentStruct(token) {
3245
+ const field = token.parentNode;
3246
+ const struct = field.ownerNode;
3247
+ return struct && isStructure(struct) ? struct : undefined;
3248
+ }
3249
+ /**
3250
+ * Get the parent interface name (for error messages and cross-type resolution).
3251
+ */ function getParentTypeName(token) {
3252
+ const struct = getParentStruct(token);
3253
+ if (!struct) return undefined;
3254
+ const iface = struct.ownerNode;
3255
+ return iface && isInterface(iface) ? iface.id : struct.id;
3256
+ }
3257
+ /**
3258
+ * Extract target type name from a navigational field definition.
3259
+ * Unwraps arrays (e.g., `Post[]` → `Post`).
3260
+ */ function getNavTargetTypeName(field) {
3261
+ let def = field.getDefinition();
3262
+ if (isArray(def)) def = def?.getDefinition();
3263
+ if (isRef(def)) return def.id;
3264
+ return undefined;
3265
+ }
3266
+ /**
3267
+ * Get the alias argument from an annotation on a field.
3268
+ */ function getAnnotationAlias(prop, annotationName) {
3269
+ const annotations$1 = prop.annotations?.filter((a) => a.name === annotationName);
3270
+ if (!annotations$1 || annotations$1.length === 0) return undefined;
3271
+ return annotations$1[0].args.length > 0 ? annotations$1[0].args[0].text : undefined;
3272
+ }
3273
+ /**
3274
+ * Factory for @db.rel.onDelete / @db.rel.onUpdate — identical validation logic,
3275
+ * only the annotation name and description verb differ.
3276
+ */ function refActionAnnotation(name) {
3277
+ return new AnnotationSpec({
3278
+ 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",
3279
+ nodeType: ["prop"],
3280
+ argument: {
3281
+ name: "action",
3282
+ type: "string",
3283
+ values: [
3284
+ "cascade",
3285
+ "restrict",
3286
+ "noAction",
3287
+ "setNull",
3288
+ "setDefault"
3289
+ ],
3290
+ description: "Referential action: \"cascade\", \"restrict\", \"noAction\", \"setNull\", or \"setDefault\"."
3291
+ },
3292
+ validate(token, args, doc) {
3293
+ const errors = [];
3294
+ const field = token.parentNode;
3295
+ if (field.countAnnotations("db.rel.FK") === 0) errors.push({
3296
+ message: `@db.rel.${name} is only valid on @db.rel.FK fields`,
3297
+ severity: 1,
3298
+ range: token.range
3299
+ });
3300
+ if (args[0]) {
3301
+ const action = args[0].text;
3302
+ if (action === "setNull" && !field.has("optional")) errors.push({
3303
+ message: `@db.rel.${name} "setNull" requires the FK field to be optional (?)`,
3304
+ severity: 1,
3305
+ range: token.range
3306
+ });
3307
+ if (action === "setDefault" && field.countAnnotations("db.default.value") === 0 && field.countAnnotations("db.default.fn") === 0) errors.push({
3308
+ message: `@db.rel.${name} "setDefault" but no @db.default.* annotation — field will have no fallback value`,
3309
+ severity: 2,
3310
+ range: token.range
3311
+ });
3312
+ }
3313
+ const fkAlias = getAnnotationAlias(field, "db.rel.FK");
3314
+ if (fkAlias) {
3315
+ const struct = getParentStruct(token);
3316
+ if (struct) {
3317
+ const annotationName = `db.rel.${name}`;
3318
+ let count = 0;
3319
+ for (const [, prop] of struct.props) {
3320
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
3321
+ if (prop.countAnnotations(annotationName) === 0) continue;
3322
+ const propFkAlias = getAnnotationAlias(prop, "db.rel.FK");
3323
+ if (propFkAlias === fkAlias) count++;
3324
+ }
3325
+ if (count > 1) errors.push({
3326
+ message: `Composite FK '${fkAlias}' has @db.rel.${name} on multiple fields — declare it on exactly one`,
3327
+ severity: 1,
3328
+ range: token.range
3329
+ });
3330
+ }
3331
+ }
3332
+ return errors;
3333
+ }
3334
+ });
3335
+ }
3200
3336
  const dbAnnotations = {
3201
3337
  patch: { strategy: new AnnotationSpec({
3202
3338
  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",
@@ -3399,7 +3535,277 @@ else if (fnName === "now" && !["number", "string"].includes(baseType)) errors.pu
3399
3535
  });
3400
3536
  return errors;
3401
3537
  }
3402
- })
3538
+ }),
3539
+ rel: {
3540
+ FK: new AnnotationSpec({
3541
+ 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",
3542
+ nodeType: ["prop"],
3543
+ argument: {
3544
+ optional: true,
3545
+ name: "alias",
3546
+ type: "string",
3547
+ description: "Alias for pairing with @db.rel.to. Required when multiple FKs point to the same target type."
3548
+ },
3549
+ validate(token, args, doc) {
3550
+ const errors = [];
3551
+ const field = token.parentNode;
3552
+ const alias = args[0]?.text;
3553
+ const owner = getDbTableOwner(token);
3554
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
3555
+ message: "@db.rel.FK is only valid on fields of a @db.table interface",
3556
+ severity: 1,
3557
+ range: token.range
3558
+ });
3559
+ if (field.countAnnotations("db.rel.to") > 0 || field.countAnnotations("db.rel.from") > 0) errors.push({
3560
+ message: "A field cannot be both a foreign key and a navigational property",
3561
+ severity: 1,
3562
+ range: token.range
3563
+ });
3564
+ const definition$1 = field.getDefinition();
3565
+ if (!definition$1 || !isRef(definition$1) || !definition$1.hasChain) {
3566
+ errors.push({
3567
+ message: `@db.rel.FK requires a chain reference type (e.g. User.id), got scalar type`,
3568
+ severity: 1,
3569
+ range: token.range
3570
+ });
3571
+ return errors;
3572
+ }
3573
+ const ref$1 = definition$1;
3574
+ const refTypeName = ref$1.id;
3575
+ const chainFields = ref$1.chain.map((c) => c.text);
3576
+ const targetUnwound = doc.unwindType(refTypeName);
3577
+ if (targetUnwound) {
3578
+ const targetDef = targetUnwound.def;
3579
+ if (isInterface(targetDef) || isStructure(targetDef)) {
3580
+ const struct = isInterface(targetDef) ? targetDef.getDefinition() : targetDef;
3581
+ if (struct && isStructure(struct) && chainFields.length > 0) {
3582
+ const targetProp = struct.props.get(chainFields[0]);
3583
+ if (targetProp) {
3584
+ if (targetProp.countAnnotations("meta.id") === 0 && targetProp.countAnnotations("db.index.unique") === 0) errors.push({
3585
+ message: `@db.rel.FK target '${refTypeName}.${chainFields.join(".")}' is not a primary key (@meta.id) or unique (@db.index.unique) field`,
3586
+ severity: 1,
3587
+ range: token.range
3588
+ });
3589
+ const propDef = targetProp.getDefinition();
3590
+ if (propDef && isRef(propDef)) {
3591
+ const propUnwound = targetUnwound.doc.unwindType(propDef.id, propDef.chain);
3592
+ if (propUnwound && !isPrimitive(propUnwound.def)) errors.push({
3593
+ message: `Foreign key field must resolve to a scalar type (number, string, etc.), got '${propDef.id}'`,
3594
+ severity: 1,
3595
+ range: token.range
3596
+ });
3597
+ } else if (propDef && !isPrimitive(propDef)) errors.push({
3598
+ message: `Foreign key field must resolve to a scalar type (number, string, etc.)`,
3599
+ severity: 1,
3600
+ range: token.range
3601
+ });
3602
+ }
3603
+ }
3604
+ }
3605
+ }
3606
+ if (!alias) {
3607
+ const struct = getParentStruct(token);
3608
+ if (struct) {
3609
+ let sameTargetCount = 0;
3610
+ for (const [, prop] of struct.props) {
3611
+ if (prop.countAnnotations("db.rel.FK") === 0) continue;
3612
+ const def = prop.getDefinition();
3613
+ if (!def || !isRef(def)) continue;
3614
+ const r = def;
3615
+ if (!r.hasChain) continue;
3616
+ if (r.id === refTypeName) {
3617
+ const fkAnnotations = prop.annotations?.filter((a) => a.name === "db.rel.FK");
3618
+ const hasAlias = fkAnnotations?.some((a) => a.args.length > 0);
3619
+ if (!hasAlias) sameTargetCount++;
3620
+ }
3621
+ }
3622
+ if (sameTargetCount > 1) errors.push({
3623
+ message: `Multiple @db.rel.FK fields resolve to type '${refTypeName}' — add alias to disambiguate`,
3624
+ severity: 1,
3625
+ range: token.range
3626
+ });
3627
+ }
3628
+ }
3629
+ return errors;
3630
+ }
3631
+ }),
3632
+ to: new AnnotationSpec({
3633
+ 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",
3634
+ nodeType: ["prop"],
3635
+ argument: {
3636
+ optional: true,
3637
+ name: "alias",
3638
+ type: "string",
3639
+ description: "Match a local @db.rel.FK by alias."
3640
+ },
3641
+ validate(token, args, doc) {
3642
+ const errors = [];
3643
+ const field = token.parentNode;
3644
+ const alias = args[0]?.text;
3645
+ const owner = getDbTableOwner(token);
3646
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
3647
+ message: "@db.rel.to is only valid on fields of a @db.table interface",
3648
+ severity: 1,
3649
+ range: token.range
3650
+ });
3651
+ if (field.countAnnotations("db.rel.FK") > 0) errors.push({
3652
+ message: "A field cannot be both a foreign key and a navigational property",
3653
+ severity: 1,
3654
+ range: token.range
3655
+ });
3656
+ const targetTypeName = getNavTargetTypeName(field);
3657
+ if (!targetTypeName) return errors;
3658
+ const unwound = doc.unwindType(targetTypeName);
3659
+ if (unwound) {
3660
+ const targetDef = unwound.def;
3661
+ const targetNode = isInterface(targetDef) ? targetDef : undefined;
3662
+ if (!targetNode || targetNode.countAnnotations("db.table") === 0) errors.push({
3663
+ message: `@db.rel.to target '${targetTypeName}' is not a @db.table entity`,
3664
+ severity: 1,
3665
+ range: token.range
3666
+ });
3667
+ }
3668
+ const fieldDef = field.getDefinition();
3669
+ if (fieldDef && fieldDef.entity === "group" && fieldDef.op === "|") errors.push({
3670
+ message: "@db.rel.to does not support union types — use separate relations",
3671
+ severity: 1,
3672
+ range: token.range
3673
+ });
3674
+ const struct = getParentStruct(token);
3675
+ if (struct) {
3676
+ const fieldName = field.id;
3677
+ for (const [name, prop] of struct.props) {
3678
+ if (name === fieldName) continue;
3679
+ if (prop.countAnnotations("db.rel.to") === 0) continue;
3680
+ const propAlias = getAnnotationAlias(prop, "db.rel.to");
3681
+ if ((alias || undefined) === (propAlias || undefined)) {
3682
+ const otherTarget = getNavTargetTypeName(prop);
3683
+ if (otherTarget === targetTypeName) {
3684
+ errors.push({
3685
+ message: `Duplicate @db.rel.to '${alias || targetTypeName}' — only one forward navigational property per alias`,
3686
+ severity: 1,
3687
+ range: token.range
3688
+ });
3689
+ break;
3690
+ }
3691
+ }
3692
+ }
3693
+ if (alias) {
3694
+ const matches = findFKFieldsPointingTo(doc, struct, targetTypeName, alias);
3695
+ if (matches.length === 0) errors.push({
3696
+ message: `No @db.rel.FK '${alias}' found on this interface`,
3697
+ severity: 1,
3698
+ range: token.range
3699
+ });
3700
+ } else {
3701
+ const matches = findFKFieldsPointingTo(doc, struct, targetTypeName);
3702
+ if (matches.length === 0) errors.push({
3703
+ message: `No @db.rel.FK on this interface points to '${targetTypeName}' — did you mean @db.rel.from?`,
3704
+ severity: 1,
3705
+ range: token.range
3706
+ });
3707
+ else if (matches.length > 1) errors.push({
3708
+ message: `Multiple @db.rel.FK fields point to '${targetTypeName}' — add alias to disambiguate`,
3709
+ severity: 1,
3710
+ range: token.range
3711
+ });
3712
+ }
3713
+ }
3714
+ return errors;
3715
+ }
3716
+ }),
3717
+ from: new AnnotationSpec({
3718
+ 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",
3719
+ nodeType: ["prop"],
3720
+ argument: {
3721
+ optional: true,
3722
+ name: "alias",
3723
+ type: "string",
3724
+ description: "Match a @db.rel.FK on the target interface by alias."
3725
+ },
3726
+ validate(token, args, doc) {
3727
+ const errors = [];
3728
+ const field = token.parentNode;
3729
+ const alias = args[0]?.text;
3730
+ const owner = getDbTableOwner(token);
3731
+ if (!owner || owner.countAnnotations("db.table") === 0) errors.push({
3732
+ message: "@db.rel.from is only valid on fields of a @db.table interface",
3733
+ severity: 1,
3734
+ range: token.range
3735
+ });
3736
+ if (field.countAnnotations("db.rel.FK") > 0) errors.push({
3737
+ message: "A field cannot be both a foreign key and a navigational property",
3738
+ severity: 1,
3739
+ range: token.range
3740
+ });
3741
+ const targetTypeName = getNavTargetTypeName(field);
3742
+ if (!targetTypeName) return errors;
3743
+ const unwound = doc.unwindType(targetTypeName);
3744
+ if (!unwound) return errors;
3745
+ const targetDef = unwound.def;
3746
+ const targetDoc = unwound.doc;
3747
+ if (!isInterface(targetDef) || targetDef.countAnnotations("db.table") === 0) {
3748
+ errors.push({
3749
+ message: `@db.rel.from target '${targetTypeName}' is not a @db.table entity`,
3750
+ severity: 1,
3751
+ range: token.range
3752
+ });
3753
+ return errors;
3754
+ }
3755
+ const struct = getParentStruct(token);
3756
+ if (struct) {
3757
+ const fieldName = field.id;
3758
+ for (const [name, prop] of struct.props) {
3759
+ if (name === fieldName) continue;
3760
+ if (prop.countAnnotations("db.rel.from") === 0) continue;
3761
+ const propAlias = getAnnotationAlias(prop, "db.rel.from");
3762
+ if ((alias || undefined) === (propAlias || undefined)) {
3763
+ const otherTarget = getNavTargetTypeName(prop);
3764
+ if (otherTarget === targetTypeName) {
3765
+ errors.push({
3766
+ message: `Duplicate @db.rel.from '${alias || targetTypeName}' — only one inverse navigational property per alias`,
3767
+ severity: 1,
3768
+ range: token.range
3769
+ });
3770
+ break;
3771
+ }
3772
+ }
3773
+ }
3774
+ }
3775
+ const thisTypeName = getParentTypeName(token);
3776
+ if (!thisTypeName) return errors;
3777
+ const matches = findFKFieldsPointingTo(targetDoc, targetDef, thisTypeName, alias);
3778
+ if (alias) {
3779
+ if (matches.length === 0) errors.push({
3780
+ message: `No @db.rel.FK '${alias}' found on '${targetTypeName}'`,
3781
+ severity: 1,
3782
+ range: token.range
3783
+ });
3784
+ } else if (matches.length === 0) errors.push({
3785
+ message: `No @db.rel.FK on '${targetTypeName}' points to '${thisTypeName}'`,
3786
+ severity: 1,
3787
+ range: token.range
3788
+ });
3789
+ else if (matches.length > 1) errors.push({
3790
+ message: `'${targetTypeName}' has multiple @db.rel.FK fields pointing to '${thisTypeName}' — add alias`,
3791
+ severity: 1,
3792
+ range: token.range
3793
+ });
3794
+ const fieldDef = field.getDefinition();
3795
+ if (!isArray(fieldDef) && matches.length === 1) {
3796
+ const fkProp = matches[0].prop;
3797
+ if (fkProp.countAnnotations("db.index.unique") === 0) errors.push({
3798
+ 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)?`,
3799
+ severity: 2,
3800
+ range: token.range
3801
+ });
3802
+ }
3803
+ return errors;
3804
+ }
3805
+ }),
3806
+ onDelete: refActionAnnotation("onDelete"),
3807
+ onUpdate: refActionAnnotation("onUpdate")
3808
+ }
3403
3809
  };
3404
3810
 
3405
3811
  //#endregion
@@ -4040,31 +4446,22 @@ var PluginManager = class {
4040
4446
  const raw = await this.config();
4041
4447
  this._docConfig = {};
4042
4448
  if (raw?.primitives) {
4043
- this._docConfig.primitives = this._docConfig.primitives || new Map();
4449
+ this._docConfig.primitives = new Map();
4044
4450
  for (const [key, value] of Object.entries(raw.primitives)) this._docConfig.primitives.set(key, new SemanticPrimitiveNode(key, value, "", raw.annotations));
4045
4451
  }
4046
- if (raw?.annotations) {
4047
- this._docConfig.annotations = this._docConfig.annotations || {};
4048
- Object.assign(this._docConfig.annotations, raw.annotations);
4049
- }
4452
+ if (raw?.annotations) this._docConfig.annotations = { ...raw.annotations };
4050
4453
  this._docConfig.unknownAnnotation = raw?.unknownAnnotation;
4051
4454
  }
4052
4455
  return this._docConfig;
4053
4456
  }
4054
4457
  async config(config = this.cfg) {
4055
4458
  if (!this._config) {
4056
- const processed = new Set();
4057
4459
  config = defu(config, getDefaultAtscriptConfig());
4058
- const filtered = this.plugins.filter((plugin) => !processed.has(plugin.name));
4059
- let i = 0;
4060
- while (processed.size !== filtered.length) {
4061
- i++;
4062
- for (const plugin of filtered) {
4063
- if (processed.has(plugin.name)) continue;
4064
- config = defu(await plugin.config?.(config), config);
4065
- processed.add(plugin.name);
4066
- }
4067
- if (i > 100) throw new Error(`Too many iterations in config`);
4460
+ const seen = new Set();
4461
+ for (const plugin of this.plugins) {
4462
+ if (seen.has(plugin.name)) continue;
4463
+ seen.add(plugin.name);
4464
+ config = defu(await plugin.config?.(config), config);
4068
4465
  }
4069
4466
  this._config = config;
4070
4467
  }
@@ -4072,28 +4469,28 @@ var PluginManager = class {
4072
4469
  }
4073
4470
  async resolve(id) {
4074
4471
  let newId = id;
4075
- for (const plugin of this.plugins) if (plugin.resolve) newId = await plugin.resolve(id);
4472
+ for (const plugin of this.plugins) if (plugin.resolve) newId = await plugin.resolve(newId) ?? newId;
4076
4473
  return newId;
4077
4474
  }
4078
4475
  async load(id) {
4079
4476
  const filePath = id.startsWith("file://") ? id.slice(7) : id;
4080
4477
  for (const plugin of this.plugins) if (plugin.load) {
4081
- const content$1 = await plugin.load(id);
4082
- if (content$1) return content$1;
4478
+ const content = await plugin.load(id);
4479
+ if (content) return content;
4083
4480
  }
4084
- const content = await readFile(filePath, "utf8");
4085
- return content.toString();
4481
+ return readFile(filePath, "utf8");
4086
4482
  }
4087
4483
  async onDocument(doc) {
4088
4484
  for (const plugin of this.plugins) if (plugin.onDocument) await plugin.onDocument(doc);
4089
4485
  }
4090
4486
  async render(doc, format) {
4487
+ const source = doc.id.startsWith("file://") ? doc.id.slice(7) : doc.id;
4091
4488
  const files = [];
4092
4489
  for (const plugin of this.plugins) if (plugin.render) {
4093
4490
  const newFiles = await plugin.render(doc, format);
4094
4491
  if (newFiles?.length > 0) files.push(...newFiles.map((f) => ({
4095
4492
  ...f,
4096
- source: doc.id.startsWith("file://") ? doc.id.slice(7) : doc.id
4493
+ source
4097
4494
  })));
4098
4495
  }
4099
4496
  return files;
@@ -4227,17 +4624,16 @@ else types.push({ type: "boolean" });
4227
4624
  }
4228
4625
  const configFile = await resolveConfigFile(id, this.root);
4229
4626
  if (configFile) {
4230
- const globalPathToConfig = configFile;
4231
- if (!this.configFiles.has(globalPathToConfig)) {
4627
+ if (!this.configFiles.has(configFile)) {
4232
4628
  const rawConfigPromise = loadConfig(configFile, this.configFormat);
4233
- this.configFiles.set(globalPathToConfig, rawConfigPromise);
4629
+ this.configFiles.set(configFile, rawConfigPromise);
4234
4630
  }
4235
- const rawConfig = await this.configFiles.get(globalPathToConfig);
4631
+ const rawConfig = await this.configFiles.get(configFile);
4236
4632
  if (!rawConfig.rootDir) rawConfig.rootDir = path.dirname(configFile);
4237
4633
  const manager = new PluginManager(rawConfig);
4238
4634
  await manager.getDocConfig();
4239
4635
  return {
4240
- file: globalPathToConfig,
4636
+ file: configFile,
4241
4637
  manager,
4242
4638
  dependants: new Set()
4243
4639
  };
@@ -4264,10 +4660,13 @@ else types.push({ type: "boolean" });
4264
4660
  async openDocument(id, text$2) {
4265
4661
  let atscript = this.atscripts.get(id);
4266
4662
  if (atscript) {
4267
- if (text$2) atscript.then((d) => {
4268
- d.update(text$2);
4269
- return d;
4270
- });
4663
+ if (text$2) {
4664
+ atscript = atscript.then((d) => {
4665
+ d.update(text$2);
4666
+ return d;
4667
+ });
4668
+ this.atscripts.set(id, atscript);
4669
+ }
4271
4670
  } else {
4272
4671
  atscript = this._openDocument(id, text$2);
4273
4672
  atscript.catch(() => {
@@ -4688,4 +5087,4 @@ else if (isGroup(def) && def.entity !== "structure") {
4688
5087
  }
4689
5088
 
4690
5089
  //#endregion
4691
- export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, DEFAULT_FORMAT, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, build, createAtscriptPlugin, defineConfig, flattenInterfaceNode, getRelPath, isAnnotate, isAnnotationSpec, isArray, isConst, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, resolveAnnotation, resolveAtscriptFromPath, resolveConfigFile };
5090
+ export { $n, AnnotationSpec, AtscriptDoc, AtscriptRepo, BuildRepo, DEFAULT_FORMAT, PluginManager, SemanticAnnotateNode, SemanticArrayNode, SemanticConstNode, SemanticGroup, SemanticImportNode, SemanticInterfaceNode, SemanticNode, SemanticPrimitiveNode, SemanticPropNode, SemanticRefNode, SemanticStructureNode, SemanticTupleNode, SemanticTypeNode, Token, build, createAtscriptPlugin, defineConfig, findFKFieldsPointingTo, flattenInterfaceNode, getRelPath, isAnnotate, isAnnotationSpec, isArray, isConst, isGroup, isImport, isInterface, isPhantomNode, isPrimitive, isProp, isRef, isStructure, isTuple, isType, loadConfig, loadTsConfig, resolveAnnotation, resolveAtscriptFromPath, resolveConfigFile };