codeapp-js 0.3.0 → 1.0.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 (158) hide show
  1. package/AI/codeapp.agent.md +105 -0
  2. package/AI/skills/connections/SKILL.md +47 -0
  3. package/AI/skills/dataverse/SKILL.md +99 -0
  4. package/AI/skills/environment-variables/SKILL.md +89 -0
  5. package/AI/skills/frontend-design/SKILL.md +34 -0
  6. package/AI/skills/jira/SKILL.md +81 -0
  7. package/AI/skills/office365-groups/SKILL.md +61 -0
  8. package/AI/skills/office365-outlook/SKILL.md +52 -0
  9. package/AI/skills/office365-users/SKILL.md +78 -0
  10. package/AI/skills/sharepoint/SKILL.md +77 -0
  11. package/AI/skills/sql/SKILL.md +85 -0
  12. package/AI/skills/start/SKILL.md +46 -0
  13. package/AI/skills/teams/SKILL.md +55 -0
  14. package/{examples/combined demo/.power/schemas/office365groups/office365groups.Schema.json → codeApp/.power/schemas/office365groups/office365groups.Schema.json} +2203 -2203
  15. package/codeApp/dist/codeapp.js +95 -1792
  16. package/codeApp/dist/connectors/azureKeyvault.js +459 -0
  17. package/codeApp/dist/connectors/jira.js +1247 -0
  18. package/codeApp/dist/connectors/office365groups.js +642 -0
  19. package/codeApp/dist/connectors/office365users.js +513 -0
  20. package/codeApp/dist/connectors/outlook.js +1393 -0
  21. package/{dev files/sharepoint.js → codeApp/dist/connectors/sharepoint.js} +239 -112
  22. package/codeApp/dist/connectors/sql.js +149 -0
  23. package/codeApp/dist/connectors/teams.js +280 -0
  24. package/codeApp/dist/power-apps-data.js +16 -2
  25. package/examples/{kanban → apps/kanban}/dist/dataverse.js +94 -94
  26. package/examples/{kanban → apps/kanban}/dist/environmentVar.js +55 -55
  27. package/examples/{kanban → apps/kanban}/dist/index.css +605 -605
  28. package/examples/{kanban → apps/kanban}/dist/index.html +21 -21
  29. package/examples/{kanban → apps/kanban}/dist/index.js +860 -860
  30. package/examples/{kanban → apps/kanban}/dist/office365groups.js +97 -97
  31. package/examples/apps/kanban/dist/office365users.js +451 -0
  32. package/examples/{kanban → apps/kanban}/dist/outlook.js +162 -162
  33. package/examples/{planning Poker/dist/power-apps-data.js → apps/kanban/dist/power-apps-data.js} +2953 -2953
  34. package/examples/{kanban → apps/kanban}/dist/sharepoint.js +435 -339
  35. package/examples/{kanban → apps/kanban}/power.config.json +35 -35
  36. package/examples/{planning Poker → apps/planning Poker}/additional files/customizations (tables).xml +6428 -6428
  37. package/examples/{planning Poker → apps/planning Poker}/additional files/dataverse-tables.json +165 -165
  38. package/examples/{planning Poker → apps/planning Poker}/additional files/readme.md +122 -122
  39. package/examples/{planning Poker → apps/planning Poker}/dist/dataverse.js +78 -78
  40. package/examples/{planning Poker → apps/planning Poker}/dist/index.html +198 -198
  41. package/examples/{planning Poker → apps/planning Poker}/dist/index.js +954 -954
  42. package/examples/{todo/dist/power-apps-data.js → apps/planning Poker/dist/power-apps-data.js } +2953 -2953
  43. package/examples/{planning Poker → apps/planning Poker}/dist/styles.css +815 -815
  44. package/examples/{planning Poker → apps/planning Poker}/power.config.json +50 -50
  45. package/examples/{outlook Demo2 → apps/solution explorer}/dist/codeapp.js +9 -245
  46. package/examples/apps/solution explorer/dist/index.html +80 -0
  47. package/examples/apps/solution explorer/dist/index.js +735 -0
  48. package/examples/apps/solution explorer/dist/styles.css +571 -0
  49. package/examples/apps/solution explorer/power.config.json +151 -0
  50. package/examples/{todo → apps/todo}/dist/dataverse.js +64 -64
  51. package/examples/{todo → apps/todo}/dist/index.html +75 -75
  52. package/examples/{todo → apps/todo}/dist/index.js +8 -8
  53. package/examples/{kanban → apps/todo}/dist/power-apps-data.js +2953 -2953
  54. package/examples/{todo → apps/todo}/dist/renderer.js +375 -375
  55. package/examples/{todo → apps/todo}/dist/styles.css +691 -691
  56. package/examples/{todo → apps/todo}/power.config.json +34 -34
  57. package/examples/combined demo/.power/schemas/appschemas/dataSourcesInfo.ts +6275 -7830
  58. package/examples/combined demo/.power/schemas/jira/jira.Schema.json +6903 -0
  59. package/examples/combined demo/.power/schemas/keyvault/keyvault.Schema.json +1600 -0
  60. package/examples/combined demo/.power/schemas/teams/teams.Schema.json +11112 -0
  61. package/examples/combined demo/dist/codeapp.js +394 -1098
  62. package/examples/{outlook Demo2/OutlookDemo_1_0_0_1.zip → combined demo/dist/icon-512.png} +0 -0
  63. package/examples/combined demo/dist/index.html +29 -511
  64. package/examples/combined demo/dist/index.js +490 -470
  65. package/examples/combined demo/dist/office365users.js +513 -0
  66. package/examples/combined demo/dist/outlook.js +1393 -0
  67. package/examples/combined demo/dist/power-apps-data.js +3079 -3006
  68. package/examples/combined demo/dist/styles.css +483 -0
  69. package/examples/combined demo/power.config.json +33 -42
  70. package/examples/combined demo/src/generated/index.ts +12 -14
  71. package/examples/combined demo/src/generated/models/AzureKeyVaultModel.ts +107 -0
  72. package/examples/combined demo/src/generated/models/JiraModel.ts +501 -0
  73. package/examples/combined demo/src/generated/services/AzureKeyVaultService.ts +257 -0
  74. package/examples/combined demo/src/generated/services/JiraService.ts +1124 -0
  75. package/examples/dataverse Demo/dist/codeapp.js +394 -1085
  76. package/examples/dataverse Demo/dist/icon-512.png +0 -0
  77. package/examples/dataverse Demo/dist/index.html +146 -54
  78. package/examples/dataverse Demo/dist/index.js +693 -83
  79. package/examples/dataverse Demo/dist/power-apps-data.js +3079 -2911
  80. package/examples/dataverse Demo/dist/styles.css +528 -0
  81. package/examples/dataverse Demo/power.config.json +41 -35
  82. package/examples/dataverse Demo/readme.md +79 -79
  83. package/examples/groups Demo/dist/codeapp.js +394 -1085
  84. package/examples/groups Demo/dist/icon-512.png +0 -0
  85. package/examples/groups Demo/dist/index.html +21 -25
  86. package/examples/groups Demo/dist/index.js +304 -113
  87. package/examples/groups Demo/dist/office365groups.js +642 -0
  88. package/examples/groups Demo/dist/power-apps-data.js +3079 -2911
  89. package/examples/groups Demo/dist/styles.css +509 -0
  90. package/examples/groups Demo/power.config.json +25 -25
  91. package/examples/myProfile/dist/codeapp.js +398 -0
  92. package/examples/myProfile/dist/index.html +21 -184
  93. package/examples/myProfile/dist/index.js +324 -141
  94. package/examples/myProfile/dist/office365users.js +517 -169
  95. package/examples/myProfile/dist/power-apps-data.js +3080 -2953
  96. package/examples/myProfile/dist/styles.css +458 -0
  97. package/examples/myProfile/power.config.json +24 -23
  98. package/examples/outlook Demo/dist/codeapp.js +394 -1085
  99. package/examples/outlook Demo/dist/index.html +150 -35
  100. package/examples/outlook Demo/dist/index.js +516 -170
  101. package/examples/outlook Demo/dist/outlook.js +1393 -121
  102. package/examples/outlook Demo/dist/power-apps-data.js +3079 -2911
  103. package/examples/outlook Demo/dist/styles.css +408 -84
  104. package/examples/outlook Demo/power.config.json +24 -23
  105. package/examples/outlook Demo/readme.md +92 -82
  106. package/examples/sharePoint Demo/dist/codeapp.js +394 -1085
  107. package/examples/sharePoint Demo/dist/icon-512.png +0 -0
  108. package/examples/sharePoint Demo/dist/index.html +22 -255
  109. package/examples/sharePoint Demo/dist/index.js +899 -262
  110. package/examples/sharePoint Demo/dist/power-apps-data.js +3079 -2911
  111. package/examples/sharePoint Demo/dist/sharepoint.js +466 -0
  112. package/examples/sharePoint Demo/dist/styles.css +587 -0
  113. package/examples/sharePoint Demo/power.config.json +23 -22
  114. package/package.json +1 -1
  115. package/readme.md +465 -76
  116. package/.vscode/settings.json +0 -6
  117. package/dev files/customConnector.js +0 -98
  118. package/dev files/dataverse.js +0 -120
  119. package/dev files/environmentVar.js +0 -55
  120. package/dev files/office365groups.js +0 -65
  121. package/dev files/office365users.js +0 -169
  122. package/dev files/outlook.js +0 -330
  123. package/dev files/power-apps-data.js +0 -2952
  124. package/examples/combined demo/.power/schemas/office365/office365.Schema.json +0 -21098
  125. package/examples/combined demo/.power/schemas/office365users/office365users.Schema.json +0 -2094
  126. package/examples/kanban/agent/decision-log.md +0 -9
  127. package/examples/kanban/agent/mockup-01-editorial-glass.html +0 -159
  128. package/examples/kanban/agent/mockup-02-dark-rail.html +0 -147
  129. package/examples/kanban/agent/mockup-03-paper-grid.html +0 -114
  130. package/examples/kanban/agent/mockup-04-neon-minimal.html +0 -141
  131. package/examples/kanban/agent/mockup-05-mono-architect.html +0 -119
  132. package/examples/kanban/dist/office365users.js +0 -169
  133. package/examples/kanban/src/generated/index.ts +0 -14
  134. package/examples/kanban/src/generated/models/Office365GroupsModel.ts +0 -363
  135. package/examples/kanban/src/generated/models/Office365OutlookModel.ts +0 -2046
  136. package/examples/kanban/src/generated/models/Office365UsersModel.ts +0 -254
  137. package/examples/kanban/src/generated/services/Office365GroupsService.ts +0 -326
  138. package/examples/kanban/src/generated/services/Office365OutlookService.ts +0 -2476
  139. package/examples/kanban/src/generated/services/Office365UsersService.ts +0 -358
  140. package/examples/outlook Demo2/agent/decision-log.md +0 -7
  141. package/examples/outlook Demo2/dist/index.html +0 -98
  142. package/examples/outlook Demo2/dist/index.js +0 -272
  143. package/examples/outlook Demo2/dist/styles.css +0 -639
  144. package/examples/outlook Demo2/power.config.json +0 -23
  145. package/examples/planning Poker/.vscode/settings.json +0 -5
  146. package/examples/sharePoint Demo/agent/decision-log.md +0 -17
  147. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/index.ts +0 -0
  148. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/models/Office365GroupsModel.ts +0 -0
  149. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/models/Office365OutlookModel.ts +0 -0
  150. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/models/Office365UsersModel.ts +0 -0
  151. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/services/Office365GroupsService.ts +0 -0
  152. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/services/Office365OutlookService.ts +0 -0
  153. /package/examples/{outlook Demo2 → apps/kanban}/src/generated/services/Office365UsersService.ts +0 -0
  154. /package/examples/{planning Poker → apps/planning Poker}/additional files/AgilePoker_1_0_0_1.zip +0 -0
  155. /package/examples/{planning Poker → apps/planning Poker}/additional files/PokerTables_1_0_0_1.zip +0 -0
  156. /package/examples/{outlook Demo2 → apps/solution explorer}/dist/icon-512.png +0 -0
  157. /package/examples/{outlook Demo2 → apps/solution explorer}/dist/power-apps-data.js +0 -0
  158. /package/examples/{todo → apps/todo}/dist/icon192.png +0 -0
@@ -1,1085 +1,394 @@
1
- import { getClient } from "./power-apps-data.js";
2
-
3
- // ── Initialize SDK & Client ────────────────────────────────────
4
- let oSharedClient = null;
5
- let oInitialDataSources = {};
6
-
7
- // ── Set initial data sources (call before any API calls) ───────
8
- export function initDataSources(oSources) {
9
- return _dbgWrap('initDataSources', [oSources], function() {
10
- oInitialDataSources = oSources || {};
11
- oSharedClient = null;
12
- });
13
- }
14
-
15
- function getSharedClient() {
16
- if (!oSharedClient) {
17
- oSharedClient = getClient(Object.assign({}, oInitialDataSources, oDataSources));
18
- }
19
- return oSharedClient;
20
- }
21
-
22
- // ── Unwrap SDK response ────────────────────────────────────────
23
- function unwrapResult(result) {
24
- if (result && result.success === false) {
25
- let sMsg = result.error ? (result.error.message || JSON.stringify(result.error)) : "Operation failed";
26
- throw new Error(sMsg);
27
- }
28
- return result && "data" in result ? result.data : result;
29
- }
30
-
31
- // ── Debugger ───────────────────────────────────────────────────
32
- let _bDebugActive = false;
33
- let _aDebugEntries = [];
34
- let _eDebugPanel = null;
35
- let _eDebugIcon = null;
36
- let _eDebugList = null;
37
- let _iDebugCounter = 0;
38
-
39
- function _dbgWrap(sName, aArgs, fnBody) {
40
- if (!_bDebugActive) return fnBody();
41
- let oEntry = { iId: ++_iDebugCounter, sName: sName, aArgs: _dbgClone(aArgs), iTime: Date.now() };
42
- _aDebugEntries.unshift(oEntry);
43
- _dbgRenderEntry(oEntry, true);
44
- let oResult;
45
- try {
46
- oResult = fnBody();
47
- } catch (oErr) {
48
- oEntry.oError = oErr && oErr.message ? oErr.message : String(oErr);
49
- oEntry.iDuration = Date.now() - oEntry.iTime;
50
- _dbgRenderEntry(oEntry, false);
51
- throw oErr;
52
- }
53
- if (oResult && typeof oResult.then === 'function') {
54
- return oResult.then(function(oVal) {
55
- oEntry.oResult = _dbgClone(oVal);
56
- oEntry.iDuration = Date.now() - oEntry.iTime;
57
- _dbgRenderEntry(oEntry, false);
58
- return oVal;
59
- }, function(oErr) {
60
- oEntry.oError = oErr && oErr.message ? oErr.message : String(oErr);
61
- oEntry.iDuration = Date.now() - oEntry.iTime;
62
- _dbgRenderEntry(oEntry, false);
63
- throw oErr;
64
- });
65
- }
66
- oEntry.oResult = _dbgClone(oResult);
67
- oEntry.iDuration = Date.now() - oEntry.iTime;
68
- _dbgRenderEntry(oEntry, false);
69
- return oResult;
70
- }
71
-
72
- function _dbgClone(oVal) {
73
- try { return JSON.parse(JSON.stringify(oVal)); }
74
- catch (oErr) { return String(oVal); }
75
- }
76
-
77
- function _dbgFormatTime(iTimestamp) {
78
- let oDate = new Date(iTimestamp);
79
- let sH = String(oDate.getHours()).padStart(2, '0');
80
- let sM = String(oDate.getMinutes()).padStart(2, '0');
81
- let sS = String(oDate.getSeconds()).padStart(2, '0');
82
- let sMs = String(oDate.getMilliseconds()).padStart(3, '0');
83
- return sH + ':' + sM + ':' + sS + '.' + sMs;
84
- }
85
-
86
- function _dbgEscapeHtml(sStr) {
87
- if (typeof sStr !== 'string') sStr = String(sStr);
88
- return sStr.replace(new RegExp('&', 'g'), '&amp;').replace(new RegExp('<', 'g'), '&lt;').replace(new RegExp('>', 'g'), '&gt;');
89
- }
90
-
91
- function _dbgRenderEntry(oEntry, bPending) {
92
- if (!_eDebugList) return;
93
- let sId = 'dbg-' + oEntry.iId;
94
- let eRow = _eDebugList.querySelector('[data-dbg-id="' + sId + '"]');
95
- if (!eRow) {
96
- eRow = document.createElement('div');
97
- eRow.setAttribute('data-dbg-id', sId);
98
- eRow.style.cssText = 'border-bottom:1px solid #333;padding:6px 8px;font-size:12px;cursor:pointer;';
99
- _eDebugList.prepend(eRow);
100
- }
101
- let sStatus = bPending ? '\u23F3' : (oEntry.oError ? '\u274C' : '\u2705');
102
- let sDuration = bPending ? '\u2026' : oEntry.iDuration + 'ms';
103
- eRow.innerHTML = '<div style="display:flex;justify-content:space-between;align-items:center;">'
104
- + '<span><strong>' + sStatus + ' ' + _dbgEscapeHtml(oEntry.sName) + '</strong></span>'
105
- + '<span style="color:#888;font-size:11px;">' + _dbgFormatTime(oEntry.iTime) + ' | ' + sDuration + '</span>'
106
- + '</div>';
107
- eRow.onclick = function() {
108
- let eDetail = eRow.querySelector('.dbg-detail');
109
- if (eDetail) { eDetail.remove(); return; }
110
- eDetail = document.createElement('div');
111
- eDetail.className = 'dbg-detail';
112
- eDetail.style.cssText = 'margin-top:4px;padding:4px;background:#1a1a2e;border-radius:4px;font-size:11px;overflow:auto;max-height:300px;';
113
- let sArgsHtml = '<div style="color:#61dafb;margin-bottom:4px;"><b>Args:</b> <pre style="margin:2px 0;white-space:pre-wrap;word-break:break-all;">' + _dbgEscapeHtml(JSON.stringify(oEntry.aArgs, null, 2)) + '</pre></div>';
114
- let sResultHtml = '';
115
- if (oEntry.oError) {
116
- sResultHtml = '<div style="color:#ff6b6b;"><b>Error:</b> <pre style="margin:2px 0;white-space:pre-wrap;word-break:break-all;">' + _dbgEscapeHtml(oEntry.oError) + '</pre></div>';
117
- } else if (!bPending) {
118
- sResultHtml = '<div style="color:#a8e6cf;"><b>Result:</b> <pre style="margin:2px 0;white-space:pre-wrap;word-break:break-all;">' + _dbgEscapeHtml(JSON.stringify(oEntry.oResult, null, 2)) + '</pre></div>';
119
- }
120
- eDetail.innerHTML = sArgsHtml + sResultHtml;
121
- eRow.appendChild(eDetail);
122
- };
123
- if (_eDebugIcon) {
124
- let eBadge = _eDebugIcon.querySelector('.dbg-badge');
125
- if (eBadge) eBadge.textContent = String(_aDebugEntries.length);
126
- }
127
- }
128
-
129
- function _dbgInjectUI() {
130
- _eDebugIcon = document.createElement('div');
131
- _eDebugIcon.id = 'codeapp-debug-icon';
132
- _eDebugIcon.innerHTML = '<span style="font-size:18px;">\uD83D\uDC1B</span>'
133
- + '<span class="dbg-badge" style="position:absolute;top:-4px;right:-4px;background:#ff6b6b;color:#fff;font-size:10px;border-radius:50%;width:18px;height:18px;display:flex;align-items:center;justify-content:center;">0</span>';
134
- _eDebugIcon.style.cssText = 'position:fixed;top:10px;right:10px;z-index:999999;width:36px;height:36px;background:#1e1e2e;border:1px solid #444;border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 2px 8px rgba(0,0,0,0.4);user-select:none;';
135
- _eDebugIcon.onclick = function() {
136
- _eDebugPanel.style.display = _eDebugPanel.style.display === 'none' ? 'flex' : 'none';
137
- };
138
- document.body.appendChild(_eDebugIcon);
139
-
140
- _eDebugPanel = document.createElement('div');
141
- _eDebugPanel.id = 'codeapp-debug-panel';
142
- _eDebugPanel.style.cssText = 'position:fixed;top:0;right:0;z-index:999998;width:420px;height:100vh;background:#16161e;color:#e0e0e0;font-family:monospace;display:none;flex-direction:column;box-shadow:-4px 0 16px rgba(0,0,0,0.5);';
143
-
144
- let eHeader = document.createElement('div');
145
- eHeader.style.cssText = 'padding:10px 12px;background:#1e1e2e;border-bottom:1px solid #333;display:flex;justify-content:space-between;align-items:center;flex-shrink:0;';
146
- eHeader.innerHTML = '<span style="font-weight:bold;font-size:14px;">\uD83D\uDC1B codeapp.js Debugger</span>';
147
- let eClear = document.createElement('button');
148
- eClear.textContent = 'Clear';
149
- eClear.style.cssText = 'background:#333;color:#e0e0e0;border:1px solid #555;border-radius:4px;padding:3px 10px;cursor:pointer;font-size:12px;';
150
- eClear.onclick = function() {
151
- _aDebugEntries = [];
152
- _eDebugList.innerHTML = '';
153
- let eBadge = _eDebugIcon.querySelector('.dbg-badge');
154
- if (eBadge) eBadge.textContent = '0';
155
- };
156
- eHeader.appendChild(eClear);
157
- _eDebugPanel.appendChild(eHeader);
158
-
159
- _eDebugList = document.createElement('div');
160
- _eDebugList.style.cssText = 'flex:1;overflow-y:auto;';
161
- _eDebugPanel.appendChild(_eDebugList);
162
- document.body.appendChild(_eDebugPanel);
163
-
164
- // Render entries logged before UI was ready
165
- _aDebugEntries.slice().reverse().forEach(function(oEntry) {
166
- _dbgRenderEntry(oEntry, false);
167
- });
168
- }
169
-
170
- export function enableDebugger() {
171
- if (_bDebugActive) return;
172
- _bDebugActive = true;
173
- if (document.body) {
174
- _dbgInjectUI();
175
- } else {
176
- document.addEventListener('DOMContentLoaded', _dbgInjectUI);
177
- }
178
- }
179
-
180
- // ── Get Environment Variable (single query with expand) ────────
181
- export async function getEnvironmentVariable(sSchemaName) {
182
- return _dbgWrap('getEnvironmentVariable', [sSchemaName], async function() {
183
- let client = getSharedClient();
184
-
185
- // Try single query: filter values by expanded definition schema name
186
- let valResult = await client.retrieveMultipleRecordsAsync("environmentvariablevalues", {
187
- filter: "EnvironmentVariableDefinitionId/schemaname eq '" + sSchemaName + "'",
188
- select: ["value"],
189
- expand: [{ name: "EnvironmentVariableDefinitionId", select: ["defaultvalue", "schemaname"] }],
190
- });
191
- let aVals = unwrapResult(valResult);
192
-
193
- // If value record exists, return it
194
- if (Array.isArray(aVals) && aVals.length > 0 && aVals[0].value) {
195
- return aVals[0].value;
196
- }
197
-
198
- // No value record — fall back to definition default value
199
- let defResult = await client.retrieveMultipleRecordsAsync("environmentvariabledefinitions", {
200
- filter: "schemaname eq '" + sSchemaName + "'",
201
- select: ["defaultvalue"],
202
- });
203
- let aDefs = unwrapResult(defResult);
204
- if (!Array.isArray(aDefs) || aDefs.length === 0) {
205
- throw new Error("Environment variable not found: " + sSchemaName);
206
- }
207
- return aDefs[0].defaultvalue || "";
208
- });
209
- }
210
-
211
- // ────────────────────────────────────────────────────────────────────────────
212
- // ─────────────────────────────── Dataverse ──────────────────────────────────
213
- // ────────────────────────────────────────────────────────────────────────────
214
-
215
- // ── Table Registry (populated at runtime via registerTable) ────
216
- let oDataSources = {};
217
-
218
- // ── Register a Dataverse table for use by the library ──────────
219
- export function registerTable(sTableName, sPrimaryKey) {
220
- return _dbgWrap('registerTable', [sTableName, sPrimaryKey], function() {
221
- oDataSources[sTableName] = {
222
- tableId: '',
223
- version: '',
224
- primaryKey: sPrimaryKey,
225
- dataSourceType: 'Dataverse',
226
- apis: {}
227
- };
228
- // reset client so it picks up the new table on next call
229
- oSharedClient = null;
230
- });
231
- }
232
-
233
- // ── Ensure value is an array (accepts array or comma-separated string)
234
- function ensureArray(value) {
235
- if (!value) return value;
236
- if (Array.isArray(value)) return value;
237
- if (typeof value === 'string') return value.split(',').map(function (s) { return s.trim(); });
238
- return value;
239
- }
240
-
241
- // ── Create ─────────────────────────────────────────────────────
242
- export async function createItem(tableName, primaryKey, record) {
243
- return _dbgWrap('createItem', [tableName, primaryKey, record], async function() {
244
- const client = getSharedClient();
245
- const result = await client.createRecordAsync(tableName, record);
246
- return unwrapResult(result);
247
- });
248
- }
249
-
250
- // ── Read (single) ──────────────────────────────────────────────
251
- export async function getItem(tableName, primaryKey, id, select) {
252
- return _dbgWrap('getItem', [tableName, primaryKey, id, select], async function() {
253
- const client = getSharedClient();
254
- select = ensureArray(select);
255
- const options = select ? { select } : undefined;
256
- const result = await client.retrieveRecordAsync(tableName, id, options);
257
- return unwrapResult(result);
258
- });
259
- }
260
-
261
- // ── List (multiple) ────────────────────────────────────────────
262
- export async function listItems(tableName, primaryKey, { filter, select, orderBy, top, skip } = {}) {
263
- return _dbgWrap('listItems', [tableName, primaryKey, { filter, select, orderBy, top, skip }], async function() {
264
- const client = getSharedClient();
265
- select = ensureArray(select);
266
- orderBy = ensureArray(orderBy);
267
- const result = await client.retrieveMultipleRecordsAsync(tableName, {
268
- filter,
269
- select,
270
- orderBy,
271
- top,
272
- skip,
273
- });
274
- var unwrapped = unwrapResult(result);
275
- return { entities: Array.isArray(unwrapped) ? unwrapped : [] };
276
- });
277
- }
278
-
279
- // ── Update ─────────────────────────────────────────────────────
280
- export async function updateItem(tableName, primaryKey, id, changedFields) {
281
- return _dbgWrap('updateItem', [tableName, primaryKey, id, changedFields], async function() {
282
- const client = getSharedClient();
283
- const result = await client.updateRecordAsync(tableName, id, changedFields);
284
- return unwrapResult(result);
285
- });
286
- }
287
-
288
- // ── Delete ─────────────────────────────────────────────────────
289
- export async function deleteItem(tableName, primaryKey, id) {
290
- return _dbgWrap('deleteItem', [tableName, primaryKey, id], async function() {
291
- const client = getSharedClient();
292
- const result = await client.deleteRecordAsync(tableName, id);
293
- return unwrapResult(result);
294
- });
295
- }
296
-
297
- // ── Unbound Action ─────────────────────────────────────────────
298
- export async function callUnboundAction(tableName, primaryKey, actionName, params) {
299
- return _dbgWrap('callUnboundAction', [tableName, primaryKey, actionName, params], async function() {
300
- const client = getSharedClient();
301
- const result = await client.invokeActionAsync(tableName, actionName, params);
302
- return unwrapResult(result);
303
- });
304
- }
305
-
306
- // ── WhoAmI ─────────────────────────────────────────────────────
307
- export async function whoAmI() {
308
- return _dbgWrap('whoAmI', [], async function() {
309
- const client = getSharedClient();
310
- const result = await client.invokeActionAsync('', 'WhoAmI', {});
311
- var data = unwrapResult(result);
312
- return data.UserId || data.userid || data.systemuserid || data;
313
- });
314
- }
315
-
316
- // ────────────────────────────────────────────────────────────────────────────
317
- // ─────────────────────────────── SharePoint ─────────────────────────────────
318
- // ────────────────────────────────────────────────────────────────────────────
319
-
320
- // ── Data source name (must match connectionReferences in power.config.json) ──
321
- const DATA_SOURCE_SP = "sharepointonline";
322
-
323
- // ── Initialize SDK client for the SharePoint connector ─────────
324
- function initSpClient() {
325
- const dataSourcesInfo = {
326
- [DATA_SOURCE_SP]: {
327
- tableId: "",
328
- version: "",
329
- primaryKey: "",
330
- dataSourceType: "Connector",
331
- apis: {
332
- GetItems: {
333
- path: "/{connectionId}/datasets/{siteUrl}/tables/{table}/items",
334
- method: "GET",
335
- parameters: [
336
- { name: "connectionId", in: "path", required: true },
337
- { name: "siteUrl", in: "path", required: true },
338
- { name: "table", in: "path", required: true },
339
- { name: "$filter", in: "query", required: false },
340
- { name: "$orderby", in: "query", required: false },
341
- { name: "$top", in: "query", required: false },
342
- { name: "$skip", in: "query", required: false },
343
- ],
344
- },
345
- GetItem: {
346
- path: "/{connectionId}/datasets/{siteUrl}/tables/{table}/items/{id}",
347
- method: "GET",
348
- parameters: [
349
- { name: "connectionId", in: "path", required: true },
350
- { name: "siteUrl", in: "path", required: true },
351
- { name: "table", in: "path", required: true },
352
- { name: "id", in: "path", required: true },
353
- ],
354
- },
355
- PostItem: {
356
- path: "/{connectionId}/datasets/{siteUrl}/tables/{table}/items",
357
- method: "POST",
358
- parameters: [
359
- { name: "connectionId", in: "path", required: true },
360
- { name: "siteUrl", in: "path", required: true },
361
- { name: "table", in: "path", required: true },
362
- { name: "item", in: "body", required: true },
363
- ],
364
- },
365
- PatchItem: {
366
- path: "/{connectionId}/datasets/{siteUrl}/tables/{table}/items/{id}",
367
- method: "PATCH",
368
- parameters: [
369
- { name: "connectionId", in: "path", required: true },
370
- { name: "siteUrl", in: "path", required: true },
371
- { name: "table", in: "path", required: true },
372
- { name: "id", in: "path", required: true },
373
- { name: "item", in: "body", required: true },
374
- ],
375
- },
376
- DeleteItem: {
377
- path: "/{connectionId}/datasets/{siteUrl}/tables/{table}/items/{id}",
378
- method: "DELETE",
379
- parameters: [
380
- { name: "connectionId", in: "path", required: true },
381
- { name: "siteUrl", in: "path", required: true },
382
- { name: "table", in: "path", required: true },
383
- { name: "id", in: "path", required: true },
384
- ],
385
- },
386
- GetTables: {
387
- path: "/{connectionId}/datasets/{siteUrl}/tables",
388
- method: "GET",
389
- parameters: [
390
- { name: "connectionId", in: "path", required: true },
391
- { name: "siteUrl", in: "path", required: true },
392
- ],
393
- },
394
- GetDataSetsMetadata: {
395
- path: "/{connectionId}/datasets/{siteUrl}",
396
- method: "GET",
397
- parameters: [
398
- { name: "connectionId", in: "path", required: true },
399
- { name: "siteUrl", in: "path", required: true },
400
- ],
401
- },
402
- CreateFile: {
403
- path: "/{connectionId}/datasets/{siteUrl}/files",
404
- method: "POST",
405
- parameters: [
406
- { name: "connectionId", in: "path", required: true },
407
- { name: "siteUrl", in: "path", required: true },
408
- { name: "folderPath", in: "query", required: true },
409
- { name: "name", in: "query", required: true },
410
- { name: "body", in: "body", required: true },
411
- ],
412
- },
413
- UpdateFile: {
414
- path: "/{connectionId}/datasets/{siteUrl}/files/{id}",
415
- method: "PUT",
416
- parameters: [
417
- { name: "connectionId", in: "path", required: true },
418
- { name: "siteUrl", in: "path", required: true },
419
- { name: "id", in: "path", required: true },
420
- { name: "body", in: "body", required: true },
421
- ],
422
- },
423
- DeleteFile: {
424
- path: "/{connectionId}/datasets/{siteUrl}/files/{id}",
425
- method: "DELETE",
426
- parameters: [
427
- { name: "connectionId", in: "path", required: true },
428
- { name: "siteUrl", in: "path", required: true },
429
- { name: "id", in: "path", required: true },
430
- ],
431
- },
432
- MoveFile: {
433
- path: "/{connectionId}/datasets/{siteUrl}/files/{id}/moveto",
434
- method: "POST",
435
- parameters: [
436
- { name: "connectionId", in: "path", required: true },
437
- { name: "siteUrl", in: "path", required: true },
438
- { name: "id", in: "path", required: true },
439
- { name: "destinationFolderPath", in: "query", required: true },
440
- { name: "newFileName", in: "query", required: false },
441
- ],
442
- },
443
- GetFileMetadata: {
444
- path: "/{connectionId}/datasets/{siteUrl}/files/{id}",
445
- method: "GET",
446
- parameters: [
447
- { name: "connectionId", in: "path", required: true },
448
- { name: "siteUrl", in: "path", required: true },
449
- { name: "id", in: "path", required: true },
450
- ],
451
- },
452
- HttpRequest: {
453
- path: "/{connectionId}/httprequest",
454
- method: "POST",
455
- parameters: [
456
- { name: "connectionId", in: "path", required: true },
457
- ],
458
- },
459
- },
460
- },
461
- };
462
- return getClient(dataSourcesInfo);
463
- }
464
-
465
- // ── Internal: execute a connector operation ────────────────────
466
- async function execSpOp(operationName, parameters) {
467
- const client = await initSpClient();
468
- const result = await client.executeAsync({
469
- connectorOperation: {
470
- tableName: DATA_SOURCE_SP,
471
- operationName,
472
- parameters,
473
- },
474
- });
475
- if (!result.success) {
476
- throw new Error(result.error?.message || "Operation failed");
477
- }
478
- return result.data;
479
- }
480
-
481
- // ═══════════════════════════════════════════════════════════════
482
- // GENERIC
483
- // ═══════════════════════════════════════════════════════════════
484
-
485
- // ── Call any SharePoint connector operation by name ─────────────
486
- export async function callSharePointOperation(operationName, parameters = {}) {
487
- return _dbgWrap('callSharePointOperation', [operationName, parameters], async function() {
488
- return execSpOp(operationName, parameters);
489
- });
490
- }
491
-
492
- // ── Send HTTP Request (for list-name-based operations) ─────────
493
- export async function sendHttpRequest({ method = "GET", uri, headers, body }) {
494
- return _dbgWrap('sendHttpRequest', [{ method, uri, headers, body }], async function() {
495
- return execSpOp("HttpRequest", {
496
- method,
497
- uri,
498
- headers: headers || {},
499
- body: body || "",
500
- });
501
- });
502
- }
503
-
504
- // ═══════════════════════════════════════════════════════════════
505
- // ITEMS (standard API — uses list ID)
506
- // ═══════════════════════════════════════════════════════════════
507
-
508
- // ── Get Items ──────────────────────────────────────────────────
509
- export async function getItems(sSiteUrl, sListId, { filter, orderBy, top, skip } = {}) {
510
- return _dbgWrap('getItems', [sSiteUrl, sListId, { filter, orderBy, top, skip }], async function() {
511
- let params = { siteUrl: encodeURIComponent(sSiteUrl), table: sListId };
512
- if (filter) params.$filter = filter;
513
- if (orderBy) params.$orderby = orderBy;
514
- if (top != null) params.$top = top;
515
- if (skip != null) params.$skip = skip;
516
- return execSpOp("GetItems", params);
517
- });
518
- }
519
-
520
- // ── Get Item ───────────────────────────────────────────────────
521
- export async function getSpItem(sSiteUrl, sListId, iItemId) {
522
- return _dbgWrap('getSpItem', [sSiteUrl, sListId, iItemId], async function() {
523
- return execSpOp("GetItem", {
524
- siteUrl: encodeURIComponent(sSiteUrl),
525
- table: sListId,
526
- id: iItemId,
527
- });
528
- });
529
- }
530
-
531
- // ── Create Item ────────────────────────────────────────────────
532
- export async function createSpItem(sSiteUrl, sListId, oFields) {
533
- return _dbgWrap('createSpItem', [sSiteUrl, sListId, oFields], async function() {
534
- return execSpOp("PostItem", {
535
- siteUrl: encodeURIComponent(sSiteUrl),
536
- table: sListId,
537
- item: oFields,
538
- });
539
- });
540
- }
541
-
542
- // ── Update Item ────────────────────────────────────────────────
543
- export async function updateSpItem(sSiteUrl, sListId, iItemId, oChangedFields) {
544
- return _dbgWrap('updateSpItem', [sSiteUrl, sListId, iItemId, oChangedFields], async function() {
545
- return execSpOp("PatchItem", {
546
- siteUrl: encodeURIComponent(sSiteUrl),
547
- table: sListId,
548
- id: iItemId,
549
- item: oChangedFields,
550
- });
551
- });
552
- }
553
-
554
- // ── Delete Item ────────────────────────────────────────────────
555
- export async function deleteSpItem(sSiteUrl, sListId, iItemId) {
556
- return _dbgWrap('deleteSpItem', [sSiteUrl, sListId, iItemId], async function() {
557
- return execSpOp("DeleteItem", {
558
- siteUrl: encodeURIComponent(sSiteUrl),
559
- table: sListId,
560
- id: iItemId,
561
- });
562
- });
563
- }
564
-
565
- // ═══════════════════════════════════════════════════════════════
566
- // ITEMS (HTTP API — uses list name)
567
- // ═══════════════════════════════════════════════════════════════
568
-
569
- // ── Get Items by List Name ─────────────────────────────────────
570
- export async function getItemsByName(sSiteUrl, sListName, { filter, orderBy, top, skip } = {}) {
571
- return _dbgWrap('getItemsByName', [sSiteUrl, sListName, { filter, orderBy, top, skip }], async function() {
572
- let sUri = sSiteUrl + "/_api/web/lists/getbytitle('" + sListName + "')/items";
573
- let aQuery = [];
574
- if (filter) aQuery.push("$filter=" + filter);
575
- if (orderBy) aQuery.push("$orderby=" + orderBy);
576
- if (top != null) aQuery.push("$top=" + top);
577
- if (skip != null) aQuery.push("$skip=" + skip);
578
- if (aQuery.length > 0) sUri = sUri + "?" + aQuery.join("&");
579
- return sendHttpRequest({ method: "GET", uri: sUri, headers: { Accept: "application/json;odata=nometadata" } });
580
- });
581
- }
582
-
583
- // ── Get Item by List Name ──────────────────────────────────────
584
- export async function getItemByName(sSiteUrl, sListName, iItemId) {
585
- return _dbgWrap('getItemByName', [sSiteUrl, sListName, iItemId], async function() {
586
- let sUri = sSiteUrl + "/_api/web/lists/getbytitle('" + sListName + "')/items(" + iItemId + ")";
587
- return sendHttpRequest({ method: "GET", uri: sUri, headers: { Accept: "application/json;odata=nometadata" } });
588
- });
589
- }
590
-
591
- // ── Create Item by List Name ───────────────────────────────────
592
- export async function createItemByName(sSiteUrl, sListName, oFields) {
593
- return _dbgWrap('createItemByName', [sSiteUrl, sListName, oFields], async function() {
594
- let sUri = sSiteUrl + "/_api/web/lists/getbytitle('" + sListName + "')/items";
595
- return sendHttpRequest({ method: "POST", uri: sUri, headers: { Accept: "application/json;odata=nometadata", "Content-Type": "application/json;odata=nometadata" }, body: JSON.stringify(oFields) });
596
- });
597
- }
598
-
599
- // ── Update Item by List Name ───────────────────────────────────
600
- export async function updateItemByName(sSiteUrl, sListName, iItemId, oChangedFields) {
601
- return _dbgWrap('updateItemByName', [sSiteUrl, sListName, iItemId, oChangedFields], async function() {
602
- let sUri = sSiteUrl + "/_api/web/lists/getbytitle('" + sListName + "')/items(" + iItemId + ")";
603
- return sendHttpRequest({ method: "PATCH", uri: sUri, headers: { Accept: "application/json;odata=nometadata", "Content-Type": "application/json;odata=nometadata", "If-Match": "*" }, body: JSON.stringify(oChangedFields) });
604
- });
605
- }
606
-
607
- // ── Delete Item by List Name ───────────────────────────────────
608
- export async function deleteItemByName(sSiteUrl, sListName, iItemId) {
609
- return _dbgWrap('deleteItemByName', [sSiteUrl, sListName, iItemId], async function() {
610
- let sUri = sSiteUrl + "/_api/web/lists/getbytitle('" + sListName + "')/items(" + iItemId + ")";
611
- return sendHttpRequest({ method: "DELETE", uri: sUri, headers: { Accept: "application/json;odata=nometadata", "If-Match": "*" } });
612
- });
613
- }
614
-
615
- // ═══════════════════════════════════════════════════════════════
616
- // TABLES / LISTS
617
- // ═══════════════════════════════════════════════════════════════
618
-
619
- // ── List Tables (Lists) ────────────────────────────────────────
620
- export async function listTables(sSiteUrl) {
621
- return _dbgWrap('listTables', [sSiteUrl], async function() {
622
- return execSpOp("GetTables", {
623
- siteUrl: encodeURIComponent(sSiteUrl),
624
- });
625
- });
626
- }
627
-
628
- // ── List Library (Document Libraries) ──────────────────────────
629
- export async function listLibrary(sSiteUrl) {
630
- return _dbgWrap('listLibrary', [sSiteUrl], async function() {
631
- return execSpOp("GetDataSetsMetadata", {
632
- siteUrl: encodeURIComponent(sSiteUrl),
633
- });
634
- });
635
- }
636
-
637
- // ═══════════════════════════════════════════════════════════════
638
- // FILES
639
- // ═══════════════════════════════════════════════════════════════
640
-
641
- // ── Create File ────────────────────────────────────────────────
642
- export async function createFile(sSiteUrl, sLibraryName, sFileName, fileContent) {
643
- return _dbgWrap('createFile', [sSiteUrl, sLibraryName, sFileName, fileContent], async function() {
644
- return execSpOp("CreateFile", {
645
- siteUrl: encodeURIComponent(sSiteUrl),
646
- folderPath: sLibraryName,
647
- name: sFileName,
648
- body: fileContent,
649
- });
650
- });
651
- }
652
-
653
- // ── Update File ────────────────────────────────────────────────
654
- export async function updateFile(sSiteUrl, sFileId, fileContent) {
655
- return _dbgWrap('updateFile', [sSiteUrl, sFileId, fileContent], async function() {
656
- return execSpOp("UpdateFile", {
657
- siteUrl: encodeURIComponent(sSiteUrl),
658
- id: sFileId,
659
- body: fileContent,
660
- });
661
- });
662
- }
663
-
664
- // ── Delete File ────────────────────────────────────────────────
665
- export async function deleteFile(sSiteUrl, sFileId) {
666
- return _dbgWrap('deleteFile', [sSiteUrl, sFileId], async function() {
667
- return execSpOp("DeleteFile", {
668
- siteUrl: encodeURIComponent(sSiteUrl),
669
- id: sFileId,
670
- });
671
- });
672
- }
673
-
674
- // ── Move File ──────────────────────────────────────────────────
675
- export async function moveFile(sSiteUrl, sSourceFileId, sDestinationFolderPath, sNewFileName) {
676
- return _dbgWrap('moveFile', [sSiteUrl, sSourceFileId, sDestinationFolderPath, sNewFileName], async function() {
677
- return execSpOp("MoveFile", {
678
- siteUrl: encodeURIComponent(sSiteUrl),
679
- id: sSourceFileId,
680
- destinationFolderPath: sDestinationFolderPath,
681
- newFileName: sNewFileName || "",
682
- });
683
- });
684
- }
685
-
686
- // ── Get File Metadata ──────────────────────────────────────────
687
- export async function getFileMetadata(sSiteUrl, sFileId) {
688
- return _dbgWrap('getFileMetadata', [sSiteUrl, sFileId], async function() {
689
- return execSpOp("GetFileMetadata", {
690
- siteUrl: encodeURIComponent(sSiteUrl),
691
- id: sFileId,
692
- });
693
- });
694
- }
695
-
696
- // ────────────────────────────────────────────────────────────────────────────
697
- // ────────────────────────────── Outlook365 ──────────────────────────────────
698
- // ────────────────────────────────────────────────────────────────────────────
699
-
700
- // ── Data source name (must match connectionReferences in power.config.json) ──
701
- const DATA_SOURCE_CANDIDATES = ["office365outlook", "Office365Outlook", "office365"];
702
- const OUTLOOK_APIS = {
703
- GetEmailsV3: {
704
- path: "/{connectionId}/v3/Mail",
705
- method: "GET",
706
- parameters: [
707
- { name: "connectionId", in: "path", required: true },
708
- { name: "folderPath", in: "query", required: false },
709
- { name: "to", in: "query", required: false },
710
- { name: "cc", in: "query", required: false },
711
- { name: "toOrCc", in: "query", required: false },
712
- { name: "from", in: "query", required: false },
713
- { name: "importance", in: "query", required: false },
714
- { name: "fetchOnlyWithAttachment", in: "query", required: false },
715
- { name: "subjectFilter", in: "query", required: false },
716
- { name: "fetchOnlyUnread", in: "query", required: false },
717
- { name: "fetchOnlyFlagged", in: "query", required: false },
718
- { name: "mailboxAddress", in: "query", required: false },
719
- { name: "includeAttachments", in: "query", required: false },
720
- { name: "searchQuery", in: "query", required: false },
721
- { name: "top", in: "query", required: false },
722
- ],
723
- },
724
- };
725
-
726
- // ── Initialize SDK client for the Office 365 Outlook connector ──
727
- function initOutlookClient() {
728
- const dataSourcesInfo = {};
729
-
730
- DATA_SOURCE_CANDIDATES.forEach((sDataSourceName) => {
731
- dataSourcesInfo[sDataSourceName] = {
732
- tableId: "",
733
- version: "",
734
- primaryKey: "",
735
- dataSourceType: "Connector",
736
- apis: OUTLOOK_APIS,
737
- };
738
- });
739
-
740
- return getClient(dataSourcesInfo);
741
- }
742
-
743
- function stringifyOutlookError(oError) {
744
- if (!oError) return "Operation failed";
745
- if (typeof oError === "string") return oError;
746
- if (oError instanceof Error) return oError.message || "Operation failed";
747
-
748
- var aPropertyNames = Object.getOwnPropertyNames(oError);
749
- var oSerializable = {};
750
- aPropertyNames.forEach((sName) => {
751
- oSerializable[sName] = oError[sName];
752
- });
753
-
754
- try {
755
- return JSON.stringify(oSerializable);
756
- } catch {
757
- return String(oError);
758
- }
759
- }
760
-
761
- function unwrapOutlookResult(oResult) {
762
- if (oResult && oResult.success === false) {
763
- var sMessage = stringifyOutlookError(oResult.error);
764
- if (oResult.data !== undefined) {
765
- sMessage += " | data: " + stringifyOutlookError(oResult.data);
766
- }
767
- throw new Error(sMessage);
768
- }
769
-
770
- if (oResult && Object.prototype.hasOwnProperty.call(oResult, "data")) {
771
- return oResult.data;
772
- }
773
-
774
- return oResult;
775
- }
776
-
777
- // ── Internal: execute a connector operation ────────────────────
778
- async function execOutlookOp(operationName, parameters) {
779
- const client = await initOutlookClient();
780
- const aErrors = [];
781
-
782
- for (let iIndex = 0; iIndex < DATA_SOURCE_CANDIDATES.length; iIndex += 1) {
783
- const sDataSourceName = DATA_SOURCE_CANDIDATES[iIndex];
784
-
785
- try {
786
- const result = await client.executeAsync({
787
- connectorOperation: {
788
- tableName: sDataSourceName,
789
- operationName,
790
- parameters,
791
- },
792
- });
793
-
794
- return unwrapOutlookResult(result);
795
- } catch (oErr) {
796
- const sMessage = stringifyOutlookError(oErr);
797
- aErrors.push(sDataSourceName + ": " + sMessage);
798
-
799
- if (sMessage.indexOf("Connection reference not found") === -1) {
800
- throw oErr;
801
- }
802
- }
803
- }
804
-
805
- throw new Error("No Outlook connection reference matched. Tried: " + aErrors.join(" || "));
806
- }
807
-
808
- // ── List Emails ────────────────────────────────────────────────
809
- export async function listEmails({ folderId = "Inbox", fetchOnlyUnread, searchQuery, top, skip } = {}) {
810
- return _dbgWrap('listEmails', [{ folderId, fetchOnlyUnread, searchQuery, top, skip }], async function() {
811
- void skip;
812
-
813
- return execOutlookOp("GetEmailsV3", {
814
- folderPath: folderId,
815
- fetchOnlyUnread,
816
- searchQuery,
817
- top: top != null ? top : 10,
818
- });
819
- });
820
- }
821
-
822
- // ────────────────────────────────────────────────────────────────────────────
823
- // ─────────────────────────────── O365 User ──────────────────────────────────
824
- // ────────────────────────────────────────────────────────────────────────────
825
-
826
- // ── Data source name (must match connectionReferences in power.config.json) ──
827
- const DATA_SOURCE_USERS = "office365users";
828
-
829
- // ── Initialize SDK client for the Office 365 Users connector ───
830
- function initUsersClient() {
831
- const dataSourcesInfo = {
832
- [DATA_SOURCE_USERS]: {
833
- tableId: "",
834
- version: "",
835
- primaryKey: "",
836
- dataSourceType: "Connector",
837
- apis: {
838
- MyProfile_V2: {
839
- path: "/{connectionId}/codeless/v1.0/me",
840
- method: "GET",
841
- parameters: [
842
- { name: "connectionId", in: "path", required: true },
843
- ],
844
- },
845
- UserProfile_V2: {
846
- path: "/{connectionId}/codeless/v1.0/users/{id}",
847
- method: "GET",
848
- parameters: [
849
- { name: "connectionId", in: "path", required: true },
850
- { name: "id", in: "path", required: true },
851
- ],
852
- },
853
- Manager_V2: {
854
- path: "/{connectionId}/codeless/v1.0/users/{id}/manager",
855
- method: "GET",
856
- parameters: [
857
- { name: "connectionId", in: "path", required: true },
858
- { name: "id", in: "path", required: true },
859
- ],
860
- },
861
- DirectReports_V2: {
862
- path: "/{connectionId}/codeless/v1.0/users/{id}/directReports",
863
- method: "GET",
864
- parameters: [
865
- { name: "connectionId", in: "path", required: true },
866
- { name: "id", in: "path", required: true },
867
- ],
868
- },
869
- UserPhoto_V2: {
870
- path: "/{connectionId}/codeless/v1.0/users/{id}/photo/$value",
871
- method: "GET",
872
- parameters: [
873
- { name: "connectionId", in: "path", required: true },
874
- { name: "id", in: "path", required: true },
875
- ],
876
- responseInfo: { "200": "image/jpeg" },
877
- },
878
- SearchUser_V2: {
879
- path: "/{connectionId}/codeless/v1.0/users",
880
- method: "GET",
881
- parameters: [
882
- { name: "connectionId", in: "path", required: true },
883
- { name: "searchTerm", in: "query", required: false },
884
- { name: "$top", in: "query", required: false },
885
- { name: "$skip", in: "query", required: false },
886
- ],
887
- },
888
- HttpRequest: {
889
- path: "/{connectionId}/codeless/v1.0/httprequest",
890
- method: "POST",
891
- parameters: [
892
- { name: "connectionId", in: "path", required: true },
893
- ],
894
- },
895
- },
896
- },
897
- };
898
- return getClient(dataSourcesInfo);
899
- }
900
-
901
- // ── Internal: execute a connector operation ────────────────────
902
- async function execUsersOp(operationName, parameters) {
903
- const client = await initUsersClient();
904
- const result = await client.executeAsync({
905
- connectorOperation: {
906
- tableName: DATA_SOURCE_USERS,
907
- operationName,
908
- parameters,
909
- },
910
- });
911
- if (!result.success) {
912
- throw new Error(result.error?.message || "Operation failed");
913
- }
914
- return result.data;
915
- }
916
-
917
- // ═══════════════════════════════════════════════════════════════
918
- // GENERIC
919
- // ═══════════════════════════════════════════════════════════════
920
-
921
- // ── Call any Office 365 Users operation by name ────────────────
922
- export async function callUsersOperation(operationName, parameters = {}) {
923
- return _dbgWrap('callUsersOperation', [operationName, parameters], async function() {
924
- return execUsersOp(operationName, parameters);
925
- });
926
- }
927
-
928
- // ── Open HTTP Request ──────────────────────────────────────────
929
- export async function openUsersHttpRequest({ method = "GET", uri, headers, body }) {
930
- return _dbgWrap('openUsersHttpRequest', [{ method, uri, headers, body }], async function() {
931
- return execUsersOp("HttpRequest", {
932
- method,
933
- uri,
934
- headers: headers || {},
935
- body: body || "",
936
- });
937
- });
938
- }
939
-
940
- // ═══════════════════════════════════════════════════════════════
941
- // PROFILE
942
- // ═══════════════════════════════════════════════════════════════
943
-
944
- // ── Get My Profile ─────────────────────────────────────────────
945
- export async function getMyProfile() {
946
- return _dbgWrap('getMyProfile', [], async function() {
947
- return execUsersOp("MyProfile_V2", {});
948
- });
949
- }
950
-
951
- // ── Get User Profile ───────────────────────────────────────────
952
- export async function getUserProfile(userId) {
953
- return _dbgWrap('getUserProfile', [userId], async function() {
954
- return execUsersOp("UserProfile_V2", {
955
- id: userId,
956
- });
957
- });
958
- }
959
-
960
- // ═══════════════════════════════════════════════════════════════
961
- // MANAGER & REPORTS
962
- // ═══════════════════════════════════════════════════════════════
963
-
964
- // ── Get Manager ────────────────────────────────────────────────
965
- export async function getManager(userId) {
966
- return _dbgWrap('getManager', [userId], async function() {
967
- return execUsersOp("Manager_V2", {
968
- id: userId,
969
- });
970
- });
971
- }
972
-
973
- // ── Get Direct Reports ─────────────────────────────────────────
974
- export async function getDirectReports(userId) {
975
- return _dbgWrap('getDirectReports', [userId], async function() {
976
- return execUsersOp("DirectReports_V2", {
977
- id: userId,
978
- });
979
- });
980
- }
981
-
982
- // ═══════════════════════════════════════════════════════════════
983
- // PHOTO
984
- // ═══════════════════════════════════════════════════════════════
985
-
986
- // ── Get User Photo ─────────────────────────────────────────────
987
- export async function getUserPhoto(userId) {
988
- return _dbgWrap('getUserPhoto', [userId], async function() {
989
- return execUsersOp("UserPhoto_V2", {
990
- id: userId,
991
- });
992
- });
993
- }
994
-
995
- // ═══════════════════════════════════════════════════════════════
996
- // SEARCH
997
- // ═══════════════════════════════════════════════════════════════
998
-
999
- // ── Search for Users ───────────────────────────────────────────
1000
- export async function searchForUsers({ searchTerm, top, skip } = {}) {
1001
- return _dbgWrap('searchForUsers', [{ searchTerm, top, skip }], async function() {
1002
- const params = {};
1003
- if (searchTerm) params.searchTerm = searchTerm;
1004
- if (top != null) params.$top = top;
1005
- if (skip != null) params.$skip = skip;
1006
- return execUsersOp("SearchUser_V2", params);
1007
- });
1008
- }
1009
-
1010
- // ────────────────────────────────────────────────────────────────────────────
1011
- // ────────────────────────────── O365 Groups──────────────────────────────────
1012
- // ────────────────────────────────────────────────────────────────────────────
1013
-
1014
-
1015
- // ── Data source name (must match connectionReferences in power.config.json) ──
1016
- const DATA_SOURCE_GROUPS = "Office365Groups";
1017
-
1018
- // ── Initialize SDK client for the Office 365 Groups connector ──
1019
- function initGroupsClient() {
1020
- const dataSourcesInfo = {
1021
- [DATA_SOURCE_GROUPS]: {
1022
- tableId: "",
1023
- version: "",
1024
- primaryKey: "",
1025
- dataSourceType: "Connector",
1026
- apis: {},
1027
- },
1028
- };
1029
- return getClient(dataSourcesInfo);
1030
- }
1031
-
1032
- // ── Internal: execute a connector operation ────────────────────
1033
- async function execGroupsOp(operationName, parameters) {
1034
- const client = await initGroupsClient();
1035
- return client.executeAsync({
1036
- connectorOperation: {
1037
- tableName: DATA_SOURCE_GROUPS,
1038
- operationName,
1039
- parameters,
1040
- },
1041
- });
1042
- }
1043
-
1044
- // ═══════════════════════════════════════════════════════════════
1045
- // GENERIC
1046
- // ═══════════════════════════════════════════════════════════════
1047
-
1048
- // ── Call any Office 365 Groups operation by name ───────────────
1049
- export async function callGroupsOperation(operationName, parameters = {}) {
1050
- return _dbgWrap('callGroupsOperation', [operationName, parameters], async function() {
1051
- return execGroupsOp(operationName, parameters);
1052
- });
1053
- }
1054
-
1055
- // ── Open HTTP Request ──────────────────────────────────────────
1056
- export async function openGroupsHttpRequest({ method = "GET", uri, headers, body }) {
1057
- return _dbgWrap('openGroupsHttpRequest', [{ method, uri, headers, body }], async function() {
1058
- return execGroupsOp("HttpRequest", {
1059
- method,
1060
- uri,
1061
- headers: headers || {},
1062
- body: body || "",
1063
- });
1064
- });
1065
- }
1066
-
1067
- // ═══════════════════════════════════════════════════════════════
1068
- // GROUPS
1069
- // ═══════════════════════════════════════════════════════════════
1070
-
1071
- // ── List My Groups ─────────────────────────────────────────────
1072
- export async function listMyGroups() {
1073
- return _dbgWrap('listMyGroups', [], async function() {
1074
- return execGroupsOp("ListOwnedGroups", {});
1075
- });
1076
- }
1077
-
1078
- // ── List Members of a Group ────────────────────────────────────
1079
- export async function listGroupMembers(groupId) {
1080
- return _dbgWrap('listGroupMembers', [groupId], async function() {
1081
- return execGroupsOp("ListGroupMembers", {
1082
- groupId,
1083
- });
1084
- });
1085
- }
1
+ import { getClient, getContext, callActionAsync } from "./power-apps-data.js";
2
+
3
+ // ── Initialize SDK & Client ────────────────────────────────────
4
+ let oSharedClient = null;
5
+ let oInitialDataSources = {};
6
+
7
+ // ── Set initial data sources (call before any API calls) ───────
8
+ export function initDataSources(oSources) {
9
+ return _dbgWrap('initDataSources', [oSources], function() {
10
+ oInitialDataSources = oSources || {};
11
+ oSharedClient = null;
12
+ });
13
+ }
14
+
15
+ function getSharedClient() {
16
+ if (!oSharedClient) {
17
+ oSharedClient = getClient(Object.assign({}, oInitialDataSources, oDataSources));
18
+ }
19
+ return oSharedClient;
20
+ }
21
+
22
+ // ── Unwrap SDK response ────────────────────────────────────────
23
+ export function unwrapResult(result) {
24
+ if (result && result.success === false) {
25
+ let sMsg = result.error ? (result.error.message || JSON.stringify(result.error)) : 'Operation failed';
26
+ throw new Error(sMsg);
27
+ }
28
+ return result && 'data' in result ? result.data : result;
29
+ }
30
+
31
+ function stringifyConnectorError(oError) {
32
+ if (!oError) return 'Unknown error';
33
+ if (typeof oError === 'string') return oError;
34
+ if (typeof oError.message === 'string' && oError.message) return oError.message;
35
+
36
+ try {
37
+ return JSON.stringify(oError);
38
+ } catch (oErr) {
39
+ return String(oError);
40
+ }
41
+ }
42
+
43
+ // ── Debugger ───────────────────────────────────────────────────
44
+ let _bDebugActive = false;
45
+ let _aDebugEntries = [];
46
+ let _eDebugPanel = null;
47
+ let _eDebugIcon = null;
48
+ let _eDebugList = null;
49
+ let _iDebugCounter = 0;
50
+
51
+ export function _dbgWrap(sName, aArgs, fnBody) {
52
+ if (!_bDebugActive) return fnBody();
53
+ let oEntry = { iId: ++_iDebugCounter, sName: sName, aArgs: _dbgClone(aArgs), iTime: Date.now() };
54
+ _aDebugEntries.unshift(oEntry);
55
+ _dbgRenderEntry(oEntry, true);
56
+ let oResult;
57
+ try {
58
+ oResult = fnBody();
59
+ } catch (oErr) {
60
+ oEntry.oError = oErr && oErr.message ? oErr.message : String(oErr);
61
+ oEntry.iDuration = Date.now() - oEntry.iTime;
62
+ _dbgRenderEntry(oEntry, false);
63
+ throw oErr;
64
+ }
65
+ if (oResult && typeof oResult.then === 'function') {
66
+ return oResult.then(function(oVal) {
67
+ oEntry.oResult = _dbgClone(oVal);
68
+ oEntry.iDuration = Date.now() - oEntry.iTime;
69
+ _dbgRenderEntry(oEntry, false);
70
+ return oVal;
71
+ }, function(oErr) {
72
+ oEntry.oError = oErr && oErr.message ? oErr.message : String(oErr);
73
+ oEntry.iDuration = Date.now() - oEntry.iTime;
74
+ _dbgRenderEntry(oEntry, false);
75
+ throw oErr;
76
+ });
77
+ }
78
+ oEntry.oResult = _dbgClone(oResult);
79
+ oEntry.iDuration = Date.now() - oEntry.iTime;
80
+ _dbgRenderEntry(oEntry, false);
81
+ return oResult;
82
+ }
83
+
84
+ function _dbgClone(oVal) {
85
+ try { return JSON.parse(JSON.stringify(oVal)); }
86
+ catch (oErr) { return String(oVal); }
87
+ }
88
+
89
+ function _dbgFormatTime(iTimestamp) {
90
+ let oDate = new Date(iTimestamp);
91
+ let sH = String(oDate.getHours()).padStart(2, '0');
92
+ let sM = String(oDate.getMinutes()).padStart(2, '0');
93
+ let sS = String(oDate.getSeconds()).padStart(2, '0');
94
+ let sMs = String(oDate.getMilliseconds()).padStart(3, '0');
95
+ return sH + ':' + sM + ':' + sS + '.' + sMs;
96
+ }
97
+
98
+ function _dbgEscapeHtml(sStr) {
99
+ if (typeof sStr !== 'string') sStr = String(sStr);
100
+ return sStr.replace(new RegExp('&', 'g'), '&amp;').replace(new RegExp('<', 'g'), '&lt;').replace(new RegExp('>', 'g'), '&gt;');
101
+ }
102
+
103
+ function _dbgRenderEntry(oEntry, bPending) {
104
+ if (!_eDebugList) return;
105
+ let sId = 'dbg-' + oEntry.iId;
106
+ let eRow = _eDebugList.querySelector('[data-dbg-id="' + sId + '"]');
107
+ if (!eRow) {
108
+ eRow = document.createElement('div');
109
+ eRow.setAttribute('data-dbg-id', sId);
110
+ eRow.style.cssText = 'border-bottom:1px solid #333;padding:6px 8px;font-size:12px;cursor:pointer;';
111
+ _eDebugList.prepend(eRow);
112
+ }
113
+ let sStatus = bPending ? '\u23F3' : (oEntry.oError ? '\u274C' : '\u2705');
114
+ let sDuration = bPending ? '\u2026' : oEntry.iDuration + 'ms';
115
+ eRow.innerHTML = '<div style="display:flex;justify-content:space-between;align-items:center;gap:6px;">'
116
+ + '<span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;"><strong>' + sStatus + ' ' + _dbgEscapeHtml(oEntry.sName) + '</strong></span>'
117
+ + '<span style="color:#888;font-size:11px;white-space:nowrap;">' + _dbgFormatTime(oEntry.iTime) + ' | ' + sDuration + '</span>'
118
+ + '<button class="dbg-copy" style="background:#333;color:#e0e0e0;border:1px solid #555;border-radius:3px;padding:1px 6px;cursor:pointer;font-size:11px;white-space:nowrap;" title="Copy to clipboard">⎘</button>'
119
+ + '</div>';
120
+ eRow.querySelector('.dbg-copy').onclick = function(e) {
121
+ e.stopPropagation();
122
+ let oData = { name: oEntry.sName, args: oEntry.aArgs, time: _dbgFormatTime(oEntry.iTime) };
123
+ if (oEntry.oError) { oData.error = oEntry.oError; }
124
+ else if (oEntry.oResult !== undefined) { oData.result = oEntry.oResult; }
125
+ if (oEntry.iDuration !== undefined) { oData.duration = oEntry.iDuration + 'ms'; }
126
+ navigator.clipboard.writeText(JSON.stringify(oData, null, 2)).then(function() {
127
+ let eBtn = eRow.querySelector('.dbg-copy');
128
+ eBtn.textContent = '\u2713';
129
+ setTimeout(function() { eBtn.textContent = '\u2398'; }, 1000);
130
+ });
131
+ };
132
+ eRow.onclick = function() {
133
+ let eDetail = eRow.querySelector('.dbg-detail');
134
+ if (eDetail) { eDetail.remove(); return; }
135
+ eDetail = document.createElement('div');
136
+ eDetail.className = 'dbg-detail';
137
+ eDetail.style.cssText = 'margin-top:4px;padding:4px;background:#1a1a2e;border-radius:4px;font-size:11px;overflow:auto;max-height:300px;';
138
+ let sArgsHtml = '<div style="color:#61dafb;margin-bottom:4px;"><b>Args:</b> <pre style="margin:2px 0;white-space:pre-wrap;word-break:break-all;">' + _dbgEscapeHtml(JSON.stringify(oEntry.aArgs, null, 2)) + '</pre></div>';
139
+ let sResultHtml = '';
140
+ if (oEntry.oError) {
141
+ sResultHtml = '<div style="color:#ff6b6b;"><b>Error:</b> <pre style="margin:2px 0;white-space:pre-wrap;word-break:break-all;">' + _dbgEscapeHtml(oEntry.oError) + '</pre></div>';
142
+ } else if (!bPending) {
143
+ sResultHtml = '<div style="color:#a8e6cf;"><b>Result:</b> <pre style="margin:2px 0;white-space:pre-wrap;word-break:break-all;">' + _dbgEscapeHtml(JSON.stringify(oEntry.oResult, null, 2)) + '</pre></div>';
144
+ }
145
+ eDetail.innerHTML = sArgsHtml + sResultHtml;
146
+ eRow.appendChild(eDetail);
147
+ };
148
+ if (_eDebugIcon) {
149
+ let eBadge = _eDebugIcon.querySelector('.dbg-badge');
150
+ if (eBadge) eBadge.textContent = String(_aDebugEntries.length);
151
+ }
152
+ }
153
+
154
+ function _dbgInjectUI() {
155
+ _eDebugIcon = document.createElement('div');
156
+ _eDebugIcon.id = 'codeapp-debug-icon';
157
+ _eDebugIcon.innerHTML = '<span style="font-size:18px;">\uD83D\uDC1B</span>'
158
+ + '<span class="dbg-badge" style="position:absolute;top:-4px;right:-4px;background:#ff6b6b;color:#fff;font-size:10px;border-radius:50%;width:18px;height:18px;display:flex;align-items:center;justify-content:center;">0</span>';
159
+ _eDebugIcon.style.cssText = 'position:fixed;top:10px;right:70px;z-index:999999;width:36px;height:36px;background:#1e1e2e;border:1px solid #444;border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 2px 8px rgba(0,0,0,0.4);user-select:none;';
160
+ _eDebugIcon.onclick = function() {
161
+ _eDebugPanel.style.display = _eDebugPanel.style.display === 'none' ? 'flex' : 'none';
162
+ };
163
+ document.body.appendChild(_eDebugIcon);
164
+
165
+ _eDebugPanel = document.createElement('div');
166
+ _eDebugPanel.id = 'codeapp-debug-panel';
167
+ _eDebugPanel.style.cssText = 'position:fixed;top:0;right:0;z-index:999998;width:420px;height:100vh;background:#16161e;color:#e0e0e0;font-family:monospace;display:none;flex-direction:column;box-shadow:-4px 0 16px rgba(0,0,0,0.5);';
168
+
169
+ let eHeader = document.createElement('div');
170
+ eHeader.style.cssText = 'padding:10px 12px;background:#1e1e2e;border-bottom:1px solid #333;display:flex;justify-content:space-between;align-items:center;flex-shrink:0;';
171
+ eHeader.innerHTML = '<span style="font-weight:bold;font-size:14px;">\uD83D\uDC1B codeapp.js Debugger</span>';
172
+ let eClear = document.createElement('button');
173
+ eClear.textContent = 'Clear';
174
+ eClear.style.cssText = 'background:#333;color:#e0e0e0;border:1px solid #555;border-radius:4px;padding:3px 10px;cursor:pointer;font-size:12px;';
175
+ eClear.onclick = function() {
176
+ _aDebugEntries = [];
177
+ _eDebugList.innerHTML = '';
178
+ let eBadge = _eDebugIcon.querySelector('.dbg-badge');
179
+ if (eBadge) eBadge.textContent = '0';
180
+ };
181
+ eHeader.appendChild(eClear);
182
+ _eDebugPanel.appendChild(eHeader);
183
+
184
+ _eDebugList = document.createElement('div');
185
+ _eDebugList.style.cssText = 'flex:1;overflow-y:auto;';
186
+ _eDebugPanel.appendChild(_eDebugList);
187
+ document.body.appendChild(_eDebugPanel);
188
+
189
+ // Render entries logged before UI was ready
190
+ _aDebugEntries.slice().reverse().forEach(function(oEntry) {
191
+ _dbgRenderEntry(oEntry, false);
192
+ });
193
+ }
194
+
195
+ export function enableDebugger() {
196
+ console.warn('Debug mode enabled: all API calls will be logged in the debug panel. Call enableDebugger() only in development environments.');
197
+ if (_bDebugActive) return;
198
+ _bDebugActive = true;
199
+ if (document.body) {
200
+ _dbgInjectUI();
201
+ } else {
202
+ document.addEventListener('DOMContentLoaded', _dbgInjectUI);
203
+ }
204
+ }
205
+
206
+ // ── Get Environment Variable (single query with expand) ────────
207
+ export async function getEnvironmentVariable(sSchemaName) {
208
+ return _dbgWrap('getEnvironmentVariable', [sSchemaName], async function() {
209
+ let client = getSharedClient();
210
+
211
+ // Try single query: filter values by expanded definition schema name
212
+ let valResult = await client.retrieveMultipleRecordsAsync('environmentvariablevalues', {
213
+ filter: "EnvironmentVariableDefinitionId/schemaname eq '" + sSchemaName + "'",
214
+ select: ['value'],
215
+ expand: [{ name: 'EnvironmentVariableDefinitionId', select: ['defaultvalue', 'schemaname'] }],
216
+ });
217
+ let aVals = unwrapResult(valResult);
218
+
219
+ // If value record exists, return it
220
+ if (Array.isArray(aVals) && aVals.length > 0 && aVals[0].value) {
221
+ return aVals[0].value;
222
+ }
223
+
224
+ // No value record — fall back to definition default value
225
+ let defResult = await client.retrieveMultipleRecordsAsync('environmentvariabledefinitions', {
226
+ filter: "schemaname eq '" + sSchemaName + "'",
227
+ select: ['defaultvalue'],
228
+ });
229
+ let aDefs = unwrapResult(defResult);
230
+ if (!Array.isArray(aDefs) || aDefs.length === 0) {
231
+ throw new Error('Environment variable not found: ' + sSchemaName);
232
+ }
233
+ return aDefs[0].defaultvalue || '';
234
+ });
235
+ }
236
+
237
+ // ────────────────────────────────────────────────────────────────────────────
238
+ // ─────────────────────────────── Dataverse ──────────────────────────────────
239
+ // ────────────────────────────────────────────────────────────────────────────
240
+
241
+ // ── Table Registry (populated at runtime via registerTable) ────
242
+ let oDataSources = {};
243
+
244
+ // ── Register a Dataverse table for use by the library ──────────
245
+ export function registerTable(sTableName, sPrimaryKey) {
246
+ return _dbgWrap('registerTable', [sTableName, sPrimaryKey], function() {
247
+ oDataSources[sTableName] = {
248
+ tableId: '',
249
+ version: '',
250
+ primaryKey: sPrimaryKey,
251
+ dataSourceType: 'Dataverse',
252
+ apis: {},
253
+ };
254
+ // reset client so it picks up the new table on next call
255
+ oSharedClient = null;
256
+ });
257
+ }
258
+
259
+ // ── Ensure value is an array (accepts array or comma-separated string)
260
+ function ensureArray(value) {
261
+ if (!value) return value;
262
+ if (Array.isArray(value)) return value;
263
+ if (typeof value === 'string') return value.split(',').map(function(s) { return s.trim(); });
264
+ return value;
265
+ }
266
+
267
+ // ── Create ─────────────────────────────────────────────────────
268
+ export async function createItem(tableName, primaryKey, record) {
269
+ return _dbgWrap('createItem', [tableName, primaryKey, record], async function() {
270
+ const client = getSharedClient();
271
+ const result = await client.createRecordAsync(tableName, record);
272
+ return unwrapResult(result);
273
+ });
274
+ }
275
+
276
+ // ── Read (single) ──────────────────────────────────────────────
277
+ export async function getItem(tableName, primaryKey, id, select) {
278
+ return _dbgWrap('getItem', [tableName, primaryKey, id, select], async function() {
279
+ const client = getSharedClient();
280
+ select = ensureArray(select);
281
+ const options = select ? { select } : undefined;
282
+ const result = await client.retrieveRecordAsync(tableName, id, options);
283
+ return unwrapResult(result);
284
+ });
285
+ }
286
+
287
+ // ── List (multiple) ────────────────────────────────────────────
288
+ export async function listItems(tableName, primaryKey, { filter, select, orderBy, top, skip } = {}) {
289
+ return _dbgWrap('listItems', [tableName, primaryKey, { filter, select, orderBy, top, skip }], async function() {
290
+ const client = getSharedClient();
291
+ select = ensureArray(select);
292
+ orderBy = ensureArray(orderBy);
293
+ const result = await client.retrieveMultipleRecordsAsync(tableName, {
294
+ filter,
295
+ select,
296
+ orderBy,
297
+ top,
298
+ skip,
299
+ });
300
+ let oUnwrapped = unwrapResult(result);
301
+ return { entities: Array.isArray(oUnwrapped) ? oUnwrapped : [] };
302
+ });
303
+ }
304
+
305
+ // ── Update ─────────────────────────────────────────────────────
306
+ export async function updateItem(tableName, primaryKey, id, changedFields) {
307
+ return _dbgWrap('updateItem', [tableName, primaryKey, id, changedFields], async function() {
308
+ const client = getSharedClient();
309
+ const result = await client.updateRecordAsync(tableName, id, changedFields);
310
+ return unwrapResult(result);
311
+ });
312
+ }
313
+
314
+ // ── Delete ─────────────────────────────────────────────────────
315
+ export async function deleteItem(tableName, primaryKey, id) {
316
+ return _dbgWrap('deleteItem', [tableName, primaryKey, id], async function() {
317
+ const client = getSharedClient();
318
+ const result = await client.deleteRecordAsync(tableName, id);
319
+ return unwrapResult(result);
320
+ });
321
+ }
322
+
323
+ // ── Unbound Action ─────────────────────────────────────────────
324
+ // Calls an unbound Dataverse action by POSTing to the action endpoint.
325
+ // Do NOT add action names to power.config.json dataSources — they are
326
+ // not entities and will cause deploy errors.
327
+ export async function callUnboundAction(tableName, primaryKey, actionName, params) {
328
+ return _dbgWrap('callUnboundAction', [tableName, primaryKey, actionName, params], async function() {
329
+ let oAllSources = Object.assign({}, oInitialDataSources, oDataSources);
330
+ let result = await callActionAsync(oAllSources, actionName, params || {});
331
+ return unwrapResult(result);
332
+ });
333
+ }
334
+
335
+ // ── WhoAmI ─────────────────────────────────────────────────────
336
+ export async function whoAmI() {
337
+ return _dbgWrap('whoAmI', [], async function() {
338
+ let oCtx = await getContext();
339
+ let sId = oCtx.UserId || oCtx.userId || oCtx.systemuserid;
340
+ if (sId) return sId;
341
+ if (oCtx.userSettings && oCtx.userSettings.userId) return oCtx.userSettings.userId;
342
+ return oCtx;
343
+ });
344
+ }
345
+
346
+ // ────────────────────────────────────────────────────────────────────────────
347
+ // ───────────────────────── Connector Helpers ────────────────────────────────
348
+ // ────────────────────────────────────────────────────────────────────────────
349
+
350
+ function initConnectorClientWithCandidates(aDataSourceCandidates, oApis) {
351
+ const dataSourcesInfo = {};
352
+
353
+ aDataSourceCandidates.forEach(function(sDataSourceName) {
354
+ dataSourcesInfo[sDataSourceName] = {
355
+ tableId: '',
356
+ version: '',
357
+ primaryKey: '',
358
+ dataSourceType: 'Connector',
359
+ apis: oApis,
360
+ };
361
+ });
362
+
363
+ return getClient(dataSourcesInfo);
364
+ }
365
+
366
+ async function execConnectorOpWithCandidates(aDataSourceCandidates, oApis, sConnectorName, operationName, parameters) {
367
+ const client = await initConnectorClientWithCandidates(aDataSourceCandidates, oApis);
368
+ const aErrors = [];
369
+
370
+ for (let iIndex = 0; iIndex < aDataSourceCandidates.length; iIndex += 1) {
371
+ const sDataSourceName = aDataSourceCandidates[iIndex];
372
+
373
+ try {
374
+ const result = await client.executeAsync({
375
+ connectorOperation: {
376
+ tableName: sDataSourceName,
377
+ operationName,
378
+ parameters,
379
+ },
380
+ });
381
+
382
+ return unwrapResult(result);
383
+ } catch (oErr) {
384
+ const sMessage = stringifyConnectorError(oErr);
385
+ aErrors.push(sDataSourceName + ': ' + sMessage);
386
+
387
+ if (sMessage.indexOf('Connection reference not found') === -1) {
388
+ throw oErr;
389
+ }
390
+ }
391
+ }
392
+
393
+ throw new Error('No ' + sConnectorName + ' connection reference matched. Tried: ' + aErrors.join(' || '));
394
+ }