d365fo-mcp 1.19.1 → 1.20.0

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.
Files changed (63) hide show
  1. package/bridge/D365MetadataBridge/Models/Models.cs +7 -0
  2. package/bridge/D365MetadataBridge/Services/AccessGrantText.cs +88 -0
  3. package/bridge/D365MetadataBridge/Services/MetadataReadService.cs +2 -0
  4. package/bridge/D365MetadataBridge/Services/MetadataWriteService.cs +22 -1
  5. package/dist/bridge/bridgeAdapter.js +14 -0
  6. package/dist/bridge/bridgeTypes.d.ts +4 -0
  7. package/dist/config/settings.js +2 -1
  8. package/dist/scripts/build-database.js +3 -2
  9. package/dist/scripts/build-fts.js +3 -2
  10. package/dist/scripts/extract-metadata.js +3 -2
  11. package/dist/tools/analysis/findReferences.js +35 -8
  12. package/dist/tools/analysis/validateObjectNaming.js +5 -2
  13. package/dist/tools/readers/getWorkspaceInfo.js +3 -1
  14. package/dist/tools/readers/tableInfo.js +22 -12
  15. package/dist/tools/sdlc/aosWebConfig.js +1 -9
  16. package/dist/tools/sdlc/buildProject.d.ts +1 -0
  17. package/dist/tools/sdlc/buildProject.js +29 -12
  18. package/dist/tools/sdlc/sysTestRunner.d.ts +2 -2
  19. package/dist/tools/sdlc/sysTestRunner.js +2 -5
  20. package/dist/tools/smart/codeGen.js +1 -1
  21. package/dist/tools/smart/generateSmartTable.js +19 -0
  22. package/dist/tools/specs/d365foFileOpSpecs.js +68 -11
  23. package/dist/tools/write/compileLabels.d.ts +3 -3
  24. package/dist/tools/write/compileLabels.js +37 -16
  25. package/dist/tools/write/createD365File.js +77 -6
  26. package/dist/tools/write/dataEntityOps.d.ts +39 -0
  27. package/dist/tools/write/dataEntityOps.js +108 -0
  28. package/dist/tools/write/directXmlWriters.d.ts +16 -0
  29. package/dist/tools/write/directXmlWriters.js +122 -1
  30. package/dist/tools/write/modifyD365File.d.ts +5 -0
  31. package/dist/tools/write/modifyD365File.js +17 -17
  32. package/dist/tools/write/renameLabel.js +125 -25
  33. package/dist/tools/xml/createTablePropertyHonesty.js +49 -3
  34. package/dist/tools/xml/dataEntityViewEdit.d.ts +74 -0
  35. package/dist/tools/xml/dataEntityViewEdit.js +272 -0
  36. package/dist/tools/xml/dataEntityXml.d.ts +11 -0
  37. package/dist/tools/xml/dataEntityXml.js +63 -11
  38. package/dist/tools/xml/tableFieldPropertyEdit.d.ts +45 -0
  39. package/dist/tools/xml/tableFieldPropertyEdit.js +129 -0
  40. package/dist/tools/xml/tableXml.d.ts +6 -0
  41. package/dist/tools/xml/tableXml.js +13 -0
  42. package/dist/tools/xml/xmlTemplateGenerator.js +5 -1
  43. package/dist/utils/appSettings.d.ts +20 -0
  44. package/dist/utils/appSettings.js +58 -0
  45. package/dist/utils/axTablePropertyOrder.d.ts +10 -1
  46. package/dist/utils/axTablePropertyOrder.js +28 -1
  47. package/dist/utils/crossModelWriteGuard.d.ts +5 -0
  48. package/dist/utils/crossModelWriteGuard.js +4 -3
  49. package/dist/utils/indexedXmlLookup.d.ts +13 -12
  50. package/dist/utils/indexedXmlLookup.js +147 -33
  51. package/dist/utils/metadataResolver.d.ts +5 -0
  52. package/dist/utils/metadataResolver.js +19 -8
  53. package/dist/utils/modelClassifier.d.ts +69 -4
  54. package/dist/utils/modelClassifier.js +151 -16
  55. package/dist/utils/objectNaming.d.ts +3 -1
  56. package/dist/utils/objectNaming.js +16 -5
  57. package/dist/utils/objectNamingRules.d.ts +1 -0
  58. package/dist/utils/objectNamingRules.js +54 -13
  59. package/dist/utils/smartXmlBuilder.js +3 -0
  60. package/dist/utils/subscriberAccessLevel.d.ts +87 -0
  61. package/dist/utils/subscriberAccessLevel.js +251 -0
  62. package/dist/utils/symbolLookup.js +12 -1
  63. package/package.json +1 -1
@@ -36,6 +36,13 @@ namespace D365MetadataBridge.Models
36
36
  [JsonPropertyName("saveDataPerCompany")]
37
37
  public string? SaveDataPerCompany { get; set; }
38
38
 
39
+ /// <summary>"Read=Allow, Create=Deny" — the set permissions; null when none are.</summary>
40
+ [JsonPropertyName("subscriberAccessLevel")]
41
+ public string? SubscriberAccessLevel { get; set; }
42
+
43
+ [JsonPropertyName("allowRowVersionChangeTracking")]
44
+ public string? AllowRowVersionChangeTracking { get; set; }
45
+
39
46
  [JsonPropertyName("extends")]
40
47
  public string? Extends { get; set; }
41
48
 
@@ -0,0 +1,88 @@
1
+ using System;
2
+ using System.Collections.Generic;
3
+ using Microsoft.Dynamics.AX.Metadata.Core.MetaModel;
4
+
5
+ namespace D365MetadataBridge.Services
6
+ {
7
+ /// <summary>
8
+ /// Text form of an AccessGrant — AxTable.SubscriberAccessLevel, "Subscriber access
9
+ /// level" in Visual Studio. Six permissions, each Unset/Allow/Deny; the serializer
10
+ /// writes only the set ones, as child elements. AccessGrant is a STRUCT: change a
11
+ /// copy and assign it back, or the change is lost.
12
+ /// </summary>
13
+ internal static class AccessGrantText
14
+ {
15
+ private static readonly string[] Permissions = { "Correct", "Create", "Delete", "Invoke", "Read", "Update" };
16
+
17
+ /// <summary>"Create=Deny, Read=Allow" for the set permissions; null when none are.</summary>
18
+ public static string? Describe(AccessGrant grant)
19
+ {
20
+ var parts = new List<string>();
21
+ foreach (var name in Permissions)
22
+ {
23
+ var value = Get(grant, name);
24
+ if (value != AccessGrantPermission.Unset) parts.Add($"{name}={value}");
25
+ }
26
+ return parts.Count > 0 ? string.Join(", ", parts) : null;
27
+ }
28
+
29
+ /// <summary>
30
+ /// Parse "Read=Allow,Create=Deny", a bare list "Read,Update" (Allow), or "None".
31
+ /// Permissions not named are Unset. Throws ArgumentException on anything else.
32
+ /// </summary>
33
+ public static AccessGrant Parse(string? text)
34
+ {
35
+ var grant = new AccessGrant();
36
+ var s = (text ?? "").Trim();
37
+ if (s.Length == 0 || s.Equals("None", StringComparison.OrdinalIgnoreCase)
38
+ || s.Equals("Unset", StringComparison.OrdinalIgnoreCase))
39
+ return grant;
40
+
41
+ foreach (var raw in s.Split(new[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries))
42
+ {
43
+ var pair = raw.Split(new[] { '=', ':' }, 2);
44
+ var key = pair[0].Trim();
45
+ var name = Array.Find(Permissions, p => p.Equals(key, StringComparison.OrdinalIgnoreCase))
46
+ ?? throw new ArgumentException(
47
+ $"Unknown subscriber permission '{key}'. Permissions: {string.Join(", ", Permissions)}; " +
48
+ "values: Allow, Deny, Unset. Example: \"Read=Allow,Create=Deny\", or \"None\".");
49
+ var valueText = pair.Length > 1 ? pair[1].Trim() : "Allow";
50
+ if (!Enum.TryParse<AccessGrantPermission>(valueText, true, out var value) || !Enum.IsDefined(typeof(AccessGrantPermission), value))
51
+ throw new ArgumentException(
52
+ $"Invalid value '{valueText}' for subscriber permission {name}. Values: Allow, Deny, Unset.");
53
+ grant = Set(grant, name, value);
54
+ }
55
+ return grant;
56
+ }
57
+
58
+ /// <summary>What Visual Studio sets on a new regular table: Read=Allow.</summary>
59
+ public static AccessGrant VisualStudioDefault() => Set(new AccessGrant(), "Read", AccessGrantPermission.Allow);
60
+
61
+ private static AccessGrantPermission Get(AccessGrant g, string name)
62
+ {
63
+ switch (name)
64
+ {
65
+ case "Correct": return g.Correct;
66
+ case "Create": return g.Create;
67
+ case "Delete": return g.Delete;
68
+ case "Invoke": return g.Invoke;
69
+ case "Read": return g.Read;
70
+ default: return g.Update;
71
+ }
72
+ }
73
+
74
+ private static AccessGrant Set(AccessGrant g, string name, AccessGrantPermission value)
75
+ {
76
+ switch (name)
77
+ {
78
+ case "Correct": g.Correct = value; break;
79
+ case "Create": g.Create = value; break;
80
+ case "Delete": g.Delete = value; break;
81
+ case "Invoke": g.Invoke = value; break;
82
+ case "Read": g.Read = value; break;
83
+ default: g.Update = value; break;
84
+ }
85
+ return g;
86
+ }
87
+ }
88
+ }
@@ -432,6 +432,8 @@ namespace D365MetadataBridge.Services
432
432
  PrimaryIndex = Safe(() => table.PrimaryIndex),
433
433
  Extends = Safe(() => table.Extends),
434
434
  SaveDataPerCompany = Safe(() => table.SaveDataPerCompany.ToString()),
435
+ SubscriberAccessLevel = Safe(() => AccessGrantText.Describe(table.SubscriberAccessLevel)),
436
+ AllowRowVersionChangeTracking = Safe(() => table.AllowRowVersionChangeTracking.ToString()),
435
437
  SupportInheritance = Safe(() => table.SupportInheritance.ToString()),
436
438
  InstanceRelationType = Safe(() => table.InstanceRelationType),
437
439
  };
@@ -323,6 +323,10 @@ namespace D365MetadataBridge.Services
323
323
 
324
324
  var axTable = new AxTable { Name = name };
325
325
 
326
+ // Visual Studio puts SubscriberAccessLevel Read=Allow on a new table (issue
327
+ // #1073). Set before the caller's properties so an explicit value wins.
328
+ axTable.SubscriberAccessLevel = AccessGrantText.VisualStudioDefault();
329
+
326
330
  // Apply table-level properties (Label, TableGroup, CacheLookup, etc.).
327
331
  // Finding #35: an unknown key was dropped in silence — report it instead.
328
332
  var unsupportedProperties = new List<string>();
@@ -333,6 +337,12 @@ namespace D365MetadataBridge.Services
333
337
  unsupportedProperties.Add(kv.Key);
334
338
  }
335
339
 
340
+ // ...except on TempDB/InMemory tables, which VS creates without one.
341
+ if ((axTable.TableType == Microsoft.Dynamics.AX.Metadata.Core.MetaModel.TableType.TempDB
342
+ || axTable.TableType == Microsoft.Dynamics.AX.Metadata.Core.MetaModel.TableType.InMemory)
343
+ && !(properties?.Keys.Any(k => k.Equals("subscriberAccessLevel", StringComparison.OrdinalIgnoreCase)) ?? false))
344
+ axTable.SubscriberAccessLevel = new Microsoft.Dynamics.AX.Metadata.Core.MetaModel.AccessGrant();
345
+
336
346
  // Add fields
337
347
  if (fields != null)
338
348
  {
@@ -493,6 +503,12 @@ namespace D365MetadataBridge.Services
493
503
  ? Microsoft.Dynamics.AX.Metadata.Core.MetaModel.NoYes.No
494
504
  : Microsoft.Dynamics.AX.Metadata.Core.MetaModel.NoYes.Yes;
495
505
 
506
+ // ── SubscriberAccessLevel — Read=Allow, as Visual Studio writes on a new
507
+ // regular table (issue #1073); none on TempDB/InMemory. extraProperties
508
+ // below can still set another value. ──
509
+ if (!isTempTable)
510
+ axTable.SubscriberAccessLevel = AccessGrantText.VisualStudioDefault();
511
+
496
512
  // ── Add fields ──
497
513
  var fieldNames = new List<string>();
498
514
  if (fields != null)
@@ -1663,7 +1679,7 @@ namespace D365MetadataBridge.Services
1663
1679
  ?? throw new ArgumentException($"Table '{objectName}' not found");
1664
1680
  var msi = GetModelSaveInfoForObject(_provider.Tables, objectName);
1665
1681
  if (!SetAxTableProperty(obj, propertyPath, propertyValue))
1666
- throw new ArgumentException($"Unknown AxTable property '{propertyPath}' — nothing was written. Supported: label, developerDocumentation, configurationKey, formRef, tableGroup, cacheLookup, clusteredIndex, primaryIndex, replacementKey, saveDataPerCompany, allowRowVersionChangeTracking, createdBy, createdDateTime, createdTransactionId, modifiedBy, modifiedDateTime, modifiedTransactionId, tableType, supportInheritance, instanceRelationType, extends, titleField1, titleField2.");
1682
+ throw new ArgumentException($"Unknown AxTable property '{propertyPath}' — nothing was written. Supported: label, developerDocumentation, configurationKey, formRef, tableGroup, cacheLookup, clusteredIndex, primaryIndex, replacementKey, saveDataPerCompany, allowRowVersionChangeTracking, subscriberAccessLevel, createdBy, createdDateTime, createdTransactionId, modifiedBy, modifiedDateTime, modifiedTransactionId, tableType, supportInheritance, instanceRelationType, extends, titleField1, titleField2.");
1667
1683
  ((IMetaTableProvider)_provider.Tables).Update(obj, msi);
1668
1684
  return new { success = true, operation = "modify-property", objectType, objectName, propertyPath, propertyValue, api = "Update" };
1669
1685
  }
@@ -3695,6 +3711,11 @@ namespace D365MetadataBridge.Services
3695
3711
  case "allowrowversionchangetracking":
3696
3712
  tbl.AllowRowVersionChangeTracking = ParseNoYes(value);
3697
3713
  break;
3714
+ // "Subscriber access level": an AccessGrant (a struct of six permissions),
3715
+ // written as "Read=Allow,Create=Deny" or "None" (issue #1073).
3716
+ case "subscriberaccesslevel":
3717
+ tbl.SubscriberAccessLevel = AccessGrantText.Parse(value);
3718
+ break;
3698
3719
  case "createdby": tbl.CreatedBy = ParseNoYes(value); break;
3699
3720
  case "createddatetime": tbl.CreatedDateTime = ParseNoYes(value); break;
3700
3721
  case "createdtransactionid": tbl.CreatedTransactionId = ParseNoYes(value); break;
@@ -29,6 +29,7 @@ import { ensureXppDocComment, ensureBlankLineBeforeClosingBrace } from '../utils
29
29
  import { parseXppDeclaration, parseXppClassHeader } from '../metadata/xppDeclaration.js';
30
30
  import { rankCustomFirst, isExactNameMatch } from '../utils/exactMatchRanking.js';
31
31
  import { COMPACT_METHODS_HINT, fullBodyHint } from '../utils/methodBodyHint.js';
32
+ import { subscriberAccessLevelValue } from '../utils/subscriberAccessLevel.js';
32
33
  import { pageFields, fieldsHeading, fieldsFooter, createControlBudget, chargeControl, chargeSkippedSubtree, controlsFooter, } from '../utils/payloadBudget.js';
33
34
  // TABLE
34
35
  const TABLE_METHOD_PAGE_SIZE = 25;
@@ -91,6 +92,10 @@ function formatTable(t, methodOffset, fieldsOffset = 0, fieldFilter, render = {}
91
92
  out += `**ClusteredIndex:** ${t.clusteredIndex}\n`;
92
93
  if (t.primaryIndex)
93
94
  out += `**PrimaryIndex:** ${t.primaryIndex}\n`;
95
+ if (t.subscriberAccessLevel)
96
+ out += `**SubscriberAccessLevel:** ${t.subscriberAccessLevel}\n`;
97
+ if (t.allowRowVersionChangeTracking === 'Yes')
98
+ out += `**AllowRowVersionChangeTracking:** Yes\n`;
94
99
  out += `_Source: C# bridge (IMetadataProvider)_\n\n`;
95
100
  // Fields — paged like methods below. A Microsoft table can carry 400+ fields,
96
101
  // which dominated this response and was paid again on every re-read.
@@ -1593,6 +1598,15 @@ export async function bridgeSetProperty(bridge, objectType, objectName, property
1593
1598
  return null;
1594
1599
  if (!BRIDGE_MODIFY_TYPES.has(objectType.toLowerCase()))
1595
1600
  return null;
1601
+ // SubscriberAccessLevel (#1073): the bridge reads "Read=Allow,Create=Deny" or
1602
+ // "None", so a JSON object value is passed in that form. An invalid value is not
1603
+ // sent at all; the direct XML fallback refuses it with the reason.
1604
+ if (objectType.toLowerCase() === 'table' && propertyPath.toLowerCase() === 'subscriberaccesslevel') {
1605
+ const v = subscriberAccessLevelValue(propertyValue);
1606
+ if (!v.ok)
1607
+ return null;
1608
+ propertyValue = v.bridgeText;
1609
+ }
1596
1610
  try {
1597
1611
  const result = await bridge.setProperty(objectType, objectName, propertyPath, propertyValue);
1598
1612
  return {
@@ -40,6 +40,10 @@ export interface BridgeTableInfo {
40
40
  clusteredIndex?: string;
41
41
  primaryIndex?: string;
42
42
  saveDataPerCompany?: string;
43
+ /** "Read=Allow, Create=Deny" — the permissions the AccessGrant sets; absent when none are. */
44
+ subscriberAccessLevel?: string;
45
+ /** "Yes" when set; absent from bridges built before it was read. */
46
+ allowRowVersionChangeTracking?: string;
43
47
  extends?: string;
44
48
  supportInheritance?: string;
45
49
  instanceRelationType?: string;
@@ -287,8 +287,9 @@ export const SETTINGS = [
287
287
  default: 'inherit',
288
288
  choices: [
289
289
  { value: 'inherit', hint: 'follow naming.extensionStyle — the default, behaviour unchanged' },
290
- { value: 'prefix', hint: 'CustTableCtso_Extension — embeds the extension prefix' },
290
+ { value: 'prefix', hint: 'CustTableCtso_Extension — embeds the extension prefix, trailing' },
291
291
  { value: 'model-name', hint: 'CustTable_ContosoRobotics_Extension — embeds the model name' },
292
+ { value: 'prefix-leading', hint: 'CtsoCustTable_Extension — embeds the extension prefix, leading (e.g. Avanade Development Guidelines)' },
292
293
  ],
293
294
  },
294
295
  // ── index ────────────────────────────────────────────────────────────────
@@ -206,8 +206,9 @@ var SETTINGS = [
206
206
  default: "inherit",
207
207
  choices: [
208
208
  { value: "inherit", hint: "follow naming.extensionStyle \u2014 the default, behaviour unchanged" },
209
- { value: "prefix", hint: "CustTableCtso_Extension \u2014 embeds the extension prefix" },
210
- { value: "model-name", hint: "CustTable_ContosoRobotics_Extension \u2014 embeds the model name" }
209
+ { value: "prefix", hint: "CustTableCtso_Extension \u2014 embeds the extension prefix, trailing" },
210
+ { value: "model-name", hint: "CustTable_ContosoRobotics_Extension \u2014 embeds the model name" },
211
+ { value: "prefix-leading", hint: "CtsoCustTable_Extension \u2014 embeds the extension prefix, leading (e.g. Avanade Development Guidelines)" }
211
212
  ]
212
213
  },
213
214
  // ── index ────────────────────────────────────────────────────────────────
@@ -206,8 +206,9 @@ var SETTINGS = [
206
206
  default: "inherit",
207
207
  choices: [
208
208
  { value: "inherit", hint: "follow naming.extensionStyle \u2014 the default, behaviour unchanged" },
209
- { value: "prefix", hint: "CustTableCtso_Extension \u2014 embeds the extension prefix" },
210
- { value: "model-name", hint: "CustTable_ContosoRobotics_Extension \u2014 embeds the model name" }
209
+ { value: "prefix", hint: "CustTableCtso_Extension \u2014 embeds the extension prefix, trailing" },
210
+ { value: "model-name", hint: "CustTable_ContosoRobotics_Extension \u2014 embeds the model name" },
211
+ { value: "prefix-leading", hint: "CtsoCustTable_Extension \u2014 embeds the extension prefix, leading (e.g. Avanade Development Guidelines)" }
211
212
  ]
212
213
  },
213
214
  // ── index ────────────────────────────────────────────────────────────────
@@ -206,8 +206,9 @@ var SETTINGS = [
206
206
  default: "inherit",
207
207
  choices: [
208
208
  { value: "inherit", hint: "follow naming.extensionStyle \u2014 the default, behaviour unchanged" },
209
- { value: "prefix", hint: "CustTableCtso_Extension \u2014 embeds the extension prefix" },
210
- { value: "model-name", hint: "CustTable_ContosoRobotics_Extension \u2014 embeds the model name" }
209
+ { value: "prefix", hint: "CustTableCtso_Extension \u2014 embeds the extension prefix, trailing" },
210
+ { value: "model-name", hint: "CustTable_ContosoRobotics_Extension \u2014 embeds the model name" },
211
+ { value: "prefix-leading", hint: "CtsoCustTable_Extension \u2014 embeds the extension prefix, leading (e.g. Avanade Development Guidelines)" }
211
212
  ]
212
213
  },
213
214
  // ── index ────────────────────────────────────────────────────────────────
@@ -461,7 +461,17 @@ export async function findReferencesTool(request, context) {
461
461
  // intra-type calls are where that bites hardest. Recover them from the
462
462
  // declaring type's own source — one indexed lookup and up to three files.
463
463
  const intraTypeRefs = wantsMethod
464
- ? scanDeclaringTypeSource(symbolIndex, ftsName, limit).filter(r => !references.some(existing => existing.file === r.file && existing.context === r.context))
464
+ ? scanDeclaringTypeSource(symbolIndex, ftsName, limit).filter(
465
+ // Same call site already reported from the index. The two paths cut
466
+ // different windows around it (±1 line here, ±2 there), so equal
467
+ // contexts never matched and every call both found was listed twice.
468
+ // Compared by the call line, not the whole window: a call on the first
469
+ // line of a method body takes its leading line from the FILE here but
470
+ // has none in the indexed body, so the window is not a substring there.
471
+ r => {
472
+ const callLine = r.context.split('\n').find(l => callOf(ftsName).test(l))?.trim();
473
+ return !references.some(existing => existing.file === r.file && (existing.context.includes(r.context) || (!!callLine && existing.context.includes(callLine))));
474
+ })
465
475
  : [];
466
476
  references.push(...intraTypeRefs);
467
477
  totalReferences = references.length;
@@ -695,6 +705,8 @@ function scanDeclaringTypeSource(symbolIndex, methodName, limit) {
695
705
  continue;
696
706
  texts = [...bodies.values()].map(m => m.source);
697
707
  }
708
+ const call = callOf(methodName);
709
+ const qualifiedCall = new RegExp(`::\\s*${escapeRegExp(methodName)}\\s*\\(`, 'i');
698
710
  for (const text of texts) {
699
711
  if (found.length >= limit)
700
712
  break;
@@ -702,9 +714,9 @@ function scanDeclaringTypeSource(symbolIndex, methodName, limit) {
702
714
  for (let i = 0; i < lines.length && found.length < limit; i++) {
703
715
  // `this.m(` and `Type::m(` are calls; `m(` alone would match the
704
716
  // declaration and every same-named member in the file.
705
- if (!/\bthis\.(\w+)\(/.test(lines[i]) && !new RegExp(`::${methodName}\\s*\\(`).test(lines[i]))
717
+ if (!/\bthis\s*\.\s*\w+\s*\(/.test(lines[i]) && !qualifiedCall.test(lines[i]))
706
718
  continue;
707
- if (!lines[i].includes(methodName + '('))
719
+ if (!call.test(lines[i]))
708
720
  continue;
709
721
  found.push({
710
722
  file: owner.file_path,
@@ -879,6 +891,21 @@ function findEnumReferences(symbolIndex, enumName, _scope, limit, value) {
879
891
  }
880
892
  return references;
881
893
  }
894
+ /** A symbol name as a literal regex fragment. */
895
+ function escapeRegExp(name) {
896
+ return name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
897
+ }
898
+ /**
899
+ * "name(" the way X++ may write it: identifiers are case-insensitive and a
900
+ * space may stand before the parenthesis, so "validatewrite()" and
901
+ * "validateWrite ()" call validateWrite just as much. An exact
902
+ * includes("validateWrite(") dropped them — after the case-insensitive FTS
903
+ * lookup had already matched the method — and it also matched the tail of a
904
+ * longer name ("myValidateWrite(").
905
+ */
906
+ function callOf(name) {
907
+ return new RegExp(`(?<![\\w$])${escapeRegExp(name)}\\s*\\(`, 'i');
908
+ }
882
909
  /** Leading words that make a "name(" line a statement, not a declaration. */
883
910
  const STATEMENT_START = /^\s*(?:return|if|while|for|switch|case|throw|else|print|info|warning|error|next|super)\b/i;
884
911
  /**
@@ -887,8 +914,7 @@ const STATEMENT_START = /^\s*(?:return|if|while|for|switch|case|throw|else|print
887
914
  * same-named call elsewhere is never dropped by this.
888
915
  */
889
916
  function isMethodDeclarationLine(line, methodName) {
890
- const escaped = methodName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
891
- const declaration = new RegExp(`^\\s*(?:[A-Za-z_][\\w.<>\\[\\]]*\\s+)+${escaped}\\s*\\(`, 'i');
917
+ const declaration = new RegExp(`^\\s*(?:[A-Za-z_][\\w.<>\\[\\]]*\\s+)+${escapeRegExp(methodName)}\\s*\\(`, 'i');
892
918
  // No "=" test: an assignment ("real t = calcTotal(") cannot match the anchored
893
919
  // type-and-modifier prefix anyway, while a default parameter value
894
920
  // ("void foo(int _x = 5)") is still a declaration.
@@ -897,9 +923,10 @@ function isMethodDeclarationLine(line, methodName) {
897
923
  function extractMethodCallContext(source, methodName, skipDeclaration = false) {
898
924
  if (!source)
899
925
  return null;
926
+ const call = callOf(methodName);
900
927
  const lines = source.split('\n');
901
928
  for (let i = 0; i < lines.length; i++) {
902
- if (lines[i].includes(methodName + '(')) {
929
+ if (call.test(lines[i])) {
903
930
  // The declaration counted as a call of the method to itself.
904
931
  if (skipDeclaration && isMethodDeclarationLine(lines[i], methodName))
905
932
  continue;
@@ -914,10 +941,10 @@ function extractMethodCallContext(source, methodName, skipDeclaration = false) {
914
941
  function extractInstantiationContext(source, className) {
915
942
  if (!source)
916
943
  return null;
917
- const pattern = `new ${className}(`;
944
+ const pattern = new RegExp(`\\bnew\\s+${escapeRegExp(className)}\\s*\\(`, 'i');
918
945
  const lines = source.split('\n');
919
946
  for (let i = 0; i < lines.length; i++) {
920
- if (lines[i].includes(pattern)) {
947
+ if (pattern.test(lines[i])) {
921
948
  const start = Math.max(0, i - 1);
922
949
  const end = Math.min(lines.length, i + 2);
923
950
  return lines.slice(start, end).join('\n').trim();
@@ -45,7 +45,7 @@ export async function validateObjectNamingTool(request, context) {
45
45
  const args = ValidateObjectNamingArgsSchema.parse(request.params.arguments);
46
46
  const db = context.symbolIndex.getReadDb();
47
47
  const check = await checkObjectNaming(db, args);
48
- const { errors, warnings, suggestions, exactConflict, similarSymbols, isExtension, prefix, modelName, modelTokenPhrase, extensionInfix, useModelName, namingStyle, useModelNameForClass, classNamingStyle, } = check;
48
+ const { errors, warnings, suggestions, exactConflict, similarSymbols, isExtension, prefix, modelName, modelTokenPhrase, extensionInfix, useModelName, namingStyle, useModelNameForClass, usePrefixLeadingForClass, classNamingStyle, } = check;
49
49
  const name = args.proposedName;
50
50
  const reinterpreted = check.reinterpretedNote ? { note: check.reinterpretedNote } : undefined;
51
51
  const explicitPrefix = args.modelPrefix?.trim() || '';
@@ -72,13 +72,16 @@ export async function validateObjectNamingTool(request, context) {
72
72
  // the two are the same unless EXTENSION_CLASS_NAMING_STYLE says otherwise.
73
73
  const isClassExt = args.objectType === 'class-extension';
74
74
  const appliedUseModelName = isClassExt ? useModelNameForClass : useModelName;
75
+ const appliedUsePrefixLeading = isClassExt && usePrefixLeadingForClass;
75
76
  const appliedStyle = isClassExt ? classNamingStyle : namingStyle;
76
77
  const appliedVar = isClassExt && classNamingStyle !== namingStyle
77
78
  ? 'EXTENSION_CLASS_NAMING_STYLE'
78
79
  : 'EXTENSION_NAMING_STYLE';
79
80
  output += appliedUseModelName
80
81
  ? `Extension Style: model-name (token = ${modelTokenPhrase})\n`
81
- : `Extension Style: prefix (token = "${extensionInfix}")\n`;
82
+ : appliedUsePrefixLeading
83
+ ? `Extension Style: prefix-leading (token = "${extensionInfix}")\n`
84
+ : `Extension Style: prefix (token = "${extensionInfix}")\n`;
82
85
  if (classNamingStyle !== namingStyle) {
83
86
  output += ` ℹ Element extensions use "${namingStyle}", extension classes use "${classNamingStyle}" (EXTENSION_CLASS_NAMING_STYLE).\n`;
84
87
  }
@@ -192,7 +192,9 @@ export async function getWorkspaceInfoTool(request, context) {
192
192
  const extClassNamingStyle = getExtensionClassNamingStyle();
193
193
  const sampleClassExt = extClassNamingStyle === 'model-name' && writeModelToken
194
194
  ? `CustTable_${writeModelToken}_Extension`
195
- : `CustTable${extInfix}_Extension`;
195
+ : extClassNamingStyle === 'prefix-leading'
196
+ ? `${extInfix}CustTable_Extension`
197
+ : `CustTable${extInfix}_Extension`;
196
198
  const sampleElemExt = extNamingStyle === 'model-name' && writeModelToken
197
199
  ? `CustTable.${writeModelToken}`
198
200
  : `CustTable.${extInfix}Extension`;
@@ -5,12 +5,12 @@
5
5
  * PRIMARY: C# bridge (IMetadataProvider) — 100% reliable, always available on VM.
6
6
  * FALLBACK: Only for newly created tables not yet indexed, uses disk scan.
7
7
  */
8
- import * as fs from 'fs';
9
8
  import * as path from 'path';
10
9
  import { z } from 'zod';
11
10
  import { findD365FileOnDisk } from '../../utils/objectFileLookup.js';
12
11
  import { tryBridgeTable } from '../../bridge/bridgeAdapter.js';
13
- import { bridgeUnavailableNote } from '../../utils/indexedXmlLookup.js';
12
+ import { bridgeUnavailableNote, indexedPathIsMissing } from '../../utils/indexedXmlLookup.js';
13
+ import { canonicalSymbolName } from '../../utils/symbolLookup.js';
14
14
  import { indexedEdtStringSize, INDEXED_SIZE_CAVEAT } from './edtInfo.js';
15
15
  import { pageFields, fieldsHeading, fieldsFooter, TABLE_FIELD_PAGE_SIZE } from '../../utils/payloadBudget.js';
16
16
  const TableInfoArgsSchema = z.object({
@@ -66,7 +66,7 @@ export async function tableInfoTool(request, context) {
66
66
  }
67
67
  // 2. DB index fallback — serves offline / write-only / build-agent scenarios.
68
68
  const { symbolIndex } = context;
69
- const dbResponse = buildTableResponseFromDb(symbolIndex, args.tableName, args.methodOffset, args.fieldsOffset, args.fieldFilter);
69
+ const dbResponse = await buildTableResponseFromDb(symbolIndex, args.tableName, args.methodOffset, args.fieldsOffset, args.fieldFilter);
70
70
  if (dbResponse) {
71
71
  const note = unhonouredOptionsNote(args, 'symbol index');
72
72
  return note ? appendTextNote(dbResponse, note) : dbResponse;
@@ -149,24 +149,34 @@ function indexedFieldSize(db, edtName) {
149
149
  * resolving here as if it still existed ("Served from symbol index"), and
150
150
  * generate_object(scaffold) trusted that phantom hit to bind a new form's
151
151
  * datasource, producing a form that references a table with no file on disk —
152
- * 4 build errors ("Table '<Name>' does not exist"). Guard against a stale row by
153
- * checking the indexed filePath actually still exists before trusting the hit;
152
+ * 4 build errors ("Table '<Name>' does not exist"). Guard against a stale row with
153
+ * the shared rule (indexedPathIsMissing) before trusting the hit;
154
154
  * a stale entry is treated the same as "not found" so the caller's disk-scan
155
155
  * fallback (or the final not-found error, which now hints at re-indexing) applies.
156
156
  */
157
- function buildTableResponseFromDb(symbolIndex, tableName, methodOffset, fieldsOffset = 0, fieldFilter) {
158
- const tableSym = symbolIndex.getSymbolByName?.(tableName, 'table');
157
+ async function buildTableResponseFromDb(symbolIndex, tableName, methodOffset, fieldsOffset = 0, fieldFilter) {
158
+ let tableSym = symbolIndex.getSymbolByName?.(tableName, 'table');
159
+ const rdb = symbolIndex.getReadDb();
160
+ if (!tableSym) {
161
+ // `custtable` must find CustTable — the lookup above is BINARY.
162
+ const canonical = canonicalSymbolName(rdb, tableName, ['table']);
163
+ if (canonical && canonical !== tableName)
164
+ tableSym = symbolIndex.getSymbolByName?.(canonical, 'table');
165
+ }
159
166
  if (!tableSym)
160
167
  return null;
161
- if (tableSym.filePath && !fs.existsSync(tableSym.filePath)) {
162
- console.error(`[tableInfo] Stale symbol-index entry for table '${tableName}' — indexed file ` +
168
+ // Only a file deleted from THIS machine makes the row stale. A path that simply
169
+ // is not here (the shipped index records build-agent paths) is not evidence of
170
+ // anything — rejecting it made every standard table "not found" without the bridge.
171
+ // Same rule as every other index reader and search's stale-row marking.
172
+ if (tableSym.filePath && await indexedPathIsMissing(tableSym.filePath)) {
173
+ console.error(`[tableInfo] Stale symbol-index entry for table '${tableSym.name}' — indexed file ` +
163
174
  `'${tableSym.filePath}' no longer exists on disk (likely rolled back/deleted since ` +
164
175
  `the index was built). Treating as not-found; run update_symbol_index to refresh.`);
165
176
  return null;
166
177
  }
167
- const rdb = symbolIndex.getReadDb();
168
- const fields = rdb.prepare(`SELECT name, signature FROM symbols WHERE parent_name = ? AND type = 'field' ORDER BY name`).all(tableName);
169
- const methods = rdb.prepare(`SELECT name, signature FROM symbols WHERE parent_name = ? AND type = 'method' ORDER BY name`).all(tableName);
178
+ const fields = rdb.prepare(`SELECT name, signature FROM symbols WHERE parent_name = ? AND type = 'field' ORDER BY name`).all(tableSym.name);
179
+ const methods = rdb.prepare(`SELECT name, signature FROM symbols WHERE parent_name = ? AND type = 'method' ORDER BY name`).all(tableSym.name);
170
180
  const METHOD_PAGE = 25;
171
181
  const totalMethods = methods.length;
172
182
  const paged = methods.slice(methodOffset, methodOffset + METHOD_PAGE);
@@ -12,15 +12,7 @@
12
12
  */
13
13
  import { readFile } from 'fs/promises';
14
14
  import path from 'path';
15
- /** One `<add key="…" value="…"/>` out of a .config document, whatever the attribute order. */
16
- function readAppSetting(xml, key) {
17
- for (const [tag] of xml.matchAll(/<add\s[^>]*>/gi)) {
18
- const attr = (name) => new RegExp(`\\s${name}\\s*=\\s*"([^"]*)"`, 'i').exec(tag)?.[1];
19
- if (attr('key')?.toLowerCase() === key.toLowerCase())
20
- return attr('value');
21
- }
22
- return undefined;
23
- }
15
+ import { readAppSetting } from '../../utils/appSettings.js';
24
16
  /** Environment root named by the web.config beside the first packages root that has one. */
25
17
  export async function localAosUrl(packagesRoots) {
26
18
  for (const root of new Set(packagesRoots.filter((r) => !!r))) {
@@ -65,6 +65,7 @@ interface BuildJobState {
65
65
  targetModel: string;
66
66
  tool: string;
67
67
  startTime: string;
68
+ sourcesAsOf?: string;
68
69
  logFile: string;
69
70
  status: 'running' | 'succeeded' | 'failed';
70
71
  phase?: 'compiling' | 'finalizing';
@@ -329,9 +329,11 @@ function logFilePath(targetModel, queueIndex, customPackagesPath) {
329
329
  }
330
330
  /**
331
331
  * Written BY the build, so always newer than it — scanning them would make
332
- * every cached result look stale and rebuild forever.
332
+ * every cached result look stale and rebuild forever. `Resources` is labelc's
333
+ * output (compileModelLabels, which runs before xppc and so after the build
334
+ * started); the label sources are under `<Model>\AxLabelFile`.
333
335
  */
334
- const BUILD_OUTPUT_DIRS = new Set(['bin', 'xppmetadata']);
336
+ const BUILD_OUTPUT_DIRS = new Set(['bin', 'xppmetadata', 'resources']);
335
337
  /**
336
338
  * True when any source file in the model package changed after `since` (epoch
337
339
  * ms). Short-circuits on the first hit, so the "something changed" case — the
@@ -353,7 +355,11 @@ export async function hasSourceChangesSince(modelDir, since, budgetMs = 3000) {
353
355
  // The directory's OWN mtime is what catches a DELETION: removing a class
354
356
  // leaves no file to stat, but the parent's mtime moves. Without this a
355
357
  // deleted source reads as "unchanged" and the stale result comes back.
356
- if ((await stat(dir)).mtimeMs > since)
358
+ // Not for the package root: its entries are the build's own bin and
359
+ // XppMetadata, which a build creates and a full build deletes, so its
360
+ // mtime moves during every such build — and `since` is now the build's
361
+ // START, so that would make every result look stale.
362
+ if (dir !== modelDir && (await stat(dir)).mtimeMs > since)
357
363
  return true;
358
364
  entries = await readdir(dir, { withFileTypes: true });
359
365
  }
@@ -394,12 +400,21 @@ export async function hasSourceChangesSince(modelDir, since, budgetMs = 3000) {
394
400
  * is indistinguishable from a real one without checking log timestamps by hand.
395
401
  */
396
402
  export async function finishedResultStillDescribesDisk(state, targetModel, customPackagesPath) {
397
- if (!state.endTime)
398
- return false; // no idea when it finished — do not trust it
399
- const endedAt = new Date(state.endTime).getTime();
400
- if (!Number.isFinite(endedAt))
403
+ // No idea whether, or when, it finished — do not trust it.
404
+ if (!state.endTime || !Number.isFinite(new Date(state.endTime).getTime()))
401
405
  return false;
402
- return !(await hasSourceChangesSince(path.join(customPackagesPath, targetModel), endedAt));
406
+ // Measured from when the build STARTED, not from when it ended: xppc reads
407
+ // the sources at the start, and endTime is written only after runtime
408
+ // metadata regeneration (and a restart, if one was asked for). A file
409
+ // changed in between — tens of seconds of "finalizing" on a real VM, plus
410
+ // the compile itself — was older than endTime, so the result of a compile
411
+ // that never saw it came back as current. Older state files without
412
+ // sourcesAsOf fall back to the current queue entry's startTime: the target
413
+ // model is compiled last, so that is when its sources were read.
414
+ const sourcesAt = new Date(state.sourcesAsOf ?? state.startTime).getTime();
415
+ if (!Number.isFinite(sourcesAt))
416
+ return false;
417
+ return !(await hasSourceChangesSince(path.join(customPackagesPath, targetModel), sourcesAt));
403
418
  }
404
419
  async function readBuildState(targetModel, customPackagesPath) {
405
420
  try {
@@ -1779,7 +1794,7 @@ const buildProjectInternal = async (params, context, onProgress, releaseAdmissio
1779
1794
  // Build finished. It may be this caller collecting the result they were
1780
1795
  // handed off ("call again to collect"), or a fresh build request that
1781
1796
  // merely arrived after an old state file. Only the disk can tell them
1782
- // apart: if sources changed since the build ended, the cached result
1797
+ // apart: if sources changed since the build started, the cached result
1783
1798
  // describes a tree that no longer exists and must not be replayed as
1784
1799
  // this call's success.
1785
1800
  const stillCurrent = await finishedResultStillDescribesDisk(existingState, targetModel, customPackagesPath);
@@ -1796,14 +1811,14 @@ const buildProjectInternal = async (params, context, onProgress, releaseAdmissio
1796
1811
  // Say plainly that nothing was compiled just now, so a reader can never
1797
1812
  // mistake a collected result for a fresh one.
1798
1813
  const collected = `ℹ️ Collected the result of the build that ended ${existingState.endTime} ` +
1799
- `(no source changes since — nothing was recompiled by this call).\n\n`;
1814
+ `(no source changes since it started — nothing was recompiled by this call).\n\n`;
1800
1815
  return {
1801
1816
  ...result,
1802
1817
  content: [{ type: 'text', text: collected + (result.content[0]?.text ?? '') }],
1803
1818
  };
1804
1819
  }
1805
1820
  // Sources moved on — fall through and build for real.
1806
- await buildLog('WARN', `discarding finished build state for ${targetModel}: sources changed after ${existingState.endTime}`);
1821
+ await buildLog('WARN', `discarding finished build state for ${targetModel}: sources changed after ${existingState.sourcesAsOf ?? existingState.startTime}`);
1807
1822
  } // end else (buildModeChanged)
1808
1823
  }
1809
1824
  // ------------------------------------------------------------------
@@ -1880,6 +1895,7 @@ const buildProjectInternal = async (params, context, onProgress, releaseAdmissio
1880
1895
  // ------------------------------------------------------------------
1881
1896
  // Initial state
1882
1897
  // ------------------------------------------------------------------
1898
+ const jobStartedAt = new Date().toISOString();
1883
1899
  const initState = {
1884
1900
  jobId: crypto.randomUUID(),
1885
1901
  ownerPid: process.pid,
@@ -1898,7 +1914,8 @@ const buildProjectInternal = async (params, context, onProgress, releaseAdmissio
1898
1914
  modelName: firstModel,
1899
1915
  targetModel,
1900
1916
  tool: 'xppc.exe',
1901
- startTime: new Date().toISOString(),
1917
+ startTime: jobStartedAt,
1918
+ sourcesAsOf: jobStartedAt,
1902
1919
  logFile: firstLogFile,
1903
1920
  status: 'running',
1904
1921
  fullBuild,
@@ -1,5 +1,5 @@
1
- /** One `<add key="…" value="…"/>` out of a .config document. */
2
- export declare function readAppSetting(xml: string, key: string): string | undefined;
1
+ import { readAppSetting } from '../../utils/appSettings.js';
2
+ export { readAppSetting };
3
3
  export interface DataAccessDrift {
4
4
  key: string;
5
5
  /** Never the secret itself — a password is described, not quoted. */