d365fo-mcp 1.19.0 → 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 (65) 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/cli/commands/update.d.ts +11 -0
  8. package/dist/cli/commands/update.js +22 -2
  9. package/dist/config/settings.js +2 -1
  10. package/dist/scripts/build-database.js +3 -2
  11. package/dist/scripts/build-fts.js +3 -2
  12. package/dist/scripts/extract-metadata.js +3 -2
  13. package/dist/tools/analysis/findReferences.js +35 -8
  14. package/dist/tools/analysis/validateObjectNaming.js +5 -2
  15. package/dist/tools/readers/getWorkspaceInfo.js +3 -1
  16. package/dist/tools/readers/tableInfo.js +22 -12
  17. package/dist/tools/sdlc/aosWebConfig.js +1 -9
  18. package/dist/tools/sdlc/buildProject.d.ts +1 -0
  19. package/dist/tools/sdlc/buildProject.js +29 -12
  20. package/dist/tools/sdlc/sysTestRunner.d.ts +2 -2
  21. package/dist/tools/sdlc/sysTestRunner.js +2 -5
  22. package/dist/tools/smart/codeGen.js +1 -1
  23. package/dist/tools/smart/generateSmartTable.js +19 -0
  24. package/dist/tools/specs/d365foFileOpSpecs.js +68 -11
  25. package/dist/tools/write/compileLabels.d.ts +3 -3
  26. package/dist/tools/write/compileLabels.js +37 -16
  27. package/dist/tools/write/createD365File.js +77 -6
  28. package/dist/tools/write/dataEntityOps.d.ts +39 -0
  29. package/dist/tools/write/dataEntityOps.js +108 -0
  30. package/dist/tools/write/directXmlWriters.d.ts +16 -0
  31. package/dist/tools/write/directXmlWriters.js +122 -1
  32. package/dist/tools/write/modifyD365File.d.ts +5 -0
  33. package/dist/tools/write/modifyD365File.js +17 -17
  34. package/dist/tools/write/renameLabel.js +125 -25
  35. package/dist/tools/xml/createTablePropertyHonesty.js +49 -3
  36. package/dist/tools/xml/dataEntityViewEdit.d.ts +74 -0
  37. package/dist/tools/xml/dataEntityViewEdit.js +272 -0
  38. package/dist/tools/xml/dataEntityXml.d.ts +11 -0
  39. package/dist/tools/xml/dataEntityXml.js +63 -11
  40. package/dist/tools/xml/tableFieldPropertyEdit.d.ts +45 -0
  41. package/dist/tools/xml/tableFieldPropertyEdit.js +129 -0
  42. package/dist/tools/xml/tableXml.d.ts +6 -0
  43. package/dist/tools/xml/tableXml.js +13 -0
  44. package/dist/tools/xml/xmlTemplateGenerator.js +5 -1
  45. package/dist/utils/appSettings.d.ts +20 -0
  46. package/dist/utils/appSettings.js +58 -0
  47. package/dist/utils/axTablePropertyOrder.d.ts +10 -1
  48. package/dist/utils/axTablePropertyOrder.js +28 -1
  49. package/dist/utils/crossModelWriteGuard.d.ts +5 -0
  50. package/dist/utils/crossModelWriteGuard.js +4 -3
  51. package/dist/utils/indexedXmlLookup.d.ts +13 -12
  52. package/dist/utils/indexedXmlLookup.js +147 -33
  53. package/dist/utils/metadataResolver.d.ts +5 -0
  54. package/dist/utils/metadataResolver.js +19 -8
  55. package/dist/utils/modelClassifier.d.ts +69 -4
  56. package/dist/utils/modelClassifier.js +151 -16
  57. package/dist/utils/objectNaming.d.ts +3 -1
  58. package/dist/utils/objectNaming.js +16 -5
  59. package/dist/utils/objectNamingRules.d.ts +1 -0
  60. package/dist/utils/objectNamingRules.js +54 -13
  61. package/dist/utils/smartXmlBuilder.js +3 -0
  62. package/dist/utils/subscriberAccessLevel.d.ts +87 -0
  63. package/dist/utils/subscriberAccessLevel.js +251 -0
  64. package/dist/utils/symbolLookup.js +12 -1
  65. 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;
@@ -13,6 +13,17 @@
13
13
  */
14
14
  export type BridgeAction = 'none' | 'optional' | 'required';
15
15
  export declare function bridgeAction(hadBridge: boolean, existsNow: boolean): BridgeAction;
16
+ /**
17
+ * Where `npm install -g` runs. Anywhere but the package itself.
18
+ *
19
+ * runShell defaults to repoRoot, which for an npm install IS the directory
20
+ * npm is about to replace — and npm replaces it by renaming it aside first.
21
+ * Windows refuses to rename a directory that any process has as its working
22
+ * directory, so the shell and npm spawned there held the very lock that made
23
+ * the rename fail with EBUSY/EPERM. The home directory is outside every
24
+ * global prefix npm uses.
25
+ */
26
+ export declare function globalInstallCwd(): string;
16
27
  export declare function updateCommand(opts: {
17
28
  yes?: boolean;
18
29
  }): Promise<void>;
@@ -7,7 +7,8 @@
7
7
  * build); an npm install reinstalls itself from the registry.
8
8
  */
9
9
  import * as fs from 'node:fs';
10
- import { DOTNET_MISSING, bridgeBuildCommand, installMode, isWindows, paths } from '../context.js';
10
+ import { homedir } from 'node:os';
11
+ import { DOTNET_MISSING, bridgeBuildCommand, installMode, isWindows, paths, repoRoot } from '../context.js';
11
12
  import { commandExists, runExe, runShell } from '../exec.js';
12
13
  import { listInstances } from '../instances.js';
13
14
  import { checkRelease } from '../npmRegistry.js';
@@ -19,6 +20,19 @@ export function bridgeAction(hadBridge, existsNow) {
19
20
  return 'none';
20
21
  return existsNow ? 'optional' : 'required';
21
22
  }
23
+ /**
24
+ * Where `npm install -g` runs. Anywhere but the package itself.
25
+ *
26
+ * runShell defaults to repoRoot, which for an npm install IS the directory
27
+ * npm is about to replace — and npm replaces it by renaming it aside first.
28
+ * Windows refuses to rename a directory that any process has as its working
29
+ * directory, so the shell and npm spawned there held the very lock that made
30
+ * the rename fail with EBUSY/EPERM. The home directory is outside every
31
+ * global prefix npm uses.
32
+ */
33
+ export function globalInstallCwd() {
34
+ return homedir();
35
+ }
22
36
  export async function updateCommand(opts) {
23
37
  p.intro('d365fo-mcp update');
24
38
  if (!requireFullInstall())
@@ -47,7 +61,7 @@ export async function updateCommand(opts) {
47
61
  // as "this install never needed writes" and silently moving on.
48
62
  const hadBridge = isWindows && fs.existsSync(paths.bridgeExe);
49
63
  const steps = installMode === 'npm'
50
- ? [['npm install -g d365fo-mcp@latest', () => runShell('npm install -g d365fo-mcp@latest')]]
64
+ ? [['npm install -g d365fo-mcp@latest', () => runShell('npm install -g d365fo-mcp@latest', { cwd: globalInstallCwd() })]]
51
65
  : [
52
66
  ['git pull', () => runExe('git', ['pull'])],
53
67
  ['npm install', () => runShell('npm install')],
@@ -57,6 +71,12 @@ export async function updateCommand(opts) {
57
71
  p.log.step(label);
58
72
  if (await run() !== 0) {
59
73
  p.log.error(`${label} failed — fix the error above and re-run.`);
74
+ if (installMode === 'npm' && isWindows) {
75
+ // The other thing that pins the package directory: a server still
76
+ // running from it (VS Code / Visual Studio keep MCP servers alive) or
77
+ // its bridge, when an older release built the bridge inside the package.
78
+ p.log.info(`If npm reports EPERM/EBUSY on ${repoRoot}, close VS Code / Visual Studio (or stop the MCP server) and run the update again.`);
79
+ }
60
80
  process.exitCode = 1;
61
81
  return;
62
82
  }
@@ -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';