codeapp-js 0.1.1 → 0.2.2

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 (121) hide show
  1. package/codeApp/dist/codeapp.js +552 -78
  2. package/codeApp/dist/power-apps-data.js +2531 -2531
  3. package/dev files/outlook.js +218 -9
  4. package/examples/combined demo/dist/codeapp.js +1098 -0
  5. package/examples/combined demo/dist/index.js +69 -114
  6. package/examples/combined demo/dist/power-apps-data.js +646 -170
  7. package/examples/combined demo/power.config.json +42 -42
  8. package/examples/dataverse Demo/dist/codeapp.js +1085 -0
  9. package/examples/dataverse Demo/dist/index.html +54 -54
  10. package/examples/dataverse Demo/dist/index.js +82 -70
  11. package/examples/dataverse Demo/dist/power-apps-data.js +551 -170
  12. package/examples/dataverse Demo/power.config.json +34 -34
  13. package/examples/dataverse Demo/readme.md +79 -79
  14. package/examples/groups Demo/dist/codeapp.js +1085 -0
  15. package/examples/groups Demo/dist/index.js +27 -27
  16. package/examples/groups Demo/dist/power-apps-data.js +551 -170
  17. package/examples/kanban/dist/dataverse.js +94 -94
  18. package/examples/kanban/dist/environmentVar.js +55 -55
  19. package/examples/kanban/dist/office365groups.js +97 -97
  20. package/examples/kanban/dist/office365users.js +169 -169
  21. package/examples/kanban/dist/outlook.js +162 -162
  22. package/examples/kanban/dist/power-apps-data.js +560 -138
  23. package/examples/kanban/dist/sharepoint.js +339 -339
  24. package/examples/myProfile/dist/index.html +184 -184
  25. package/examples/myProfile/dist/index.js +141 -141
  26. package/examples/myProfile/dist/office365users.js +169 -169
  27. package/examples/myProfile/dist/power-apps-data.js +560 -138
  28. package/examples/myProfile/power.config.json +22 -22
  29. package/examples/myProfile/readme.md +79 -79
  30. package/examples/outlook Demo/dist/codeapp.js +1085 -0
  31. package/examples/outlook Demo/dist/index.html +35 -35
  32. package/examples/outlook Demo/dist/index.js +170 -166
  33. package/examples/outlook Demo/dist/outlook.js +121 -121
  34. package/examples/outlook Demo/dist/power-apps-data.js +551 -170
  35. package/examples/outlook Demo/dist/styles.css +84 -84
  36. package/examples/outlook Demo/readme.md +82 -82
  37. package/examples/outlook Demo2/OutlookDemo_1_0_0_1.zip +0 -0
  38. package/examples/outlook Demo2/agent/decision-log.md +7 -0
  39. package/examples/outlook Demo2/dist/codeapp.js +1334 -0
  40. package/examples/outlook Demo2/dist/icon-512.png +0 -0
  41. package/examples/outlook Demo2/dist/index.html +98 -0
  42. package/examples/outlook Demo2/dist/index.js +346 -0
  43. package/examples/outlook Demo2/dist/power-apps-data.js +3007 -0
  44. package/examples/outlook Demo2/dist/styles.css +639 -0
  45. package/examples/outlook Demo2/power.config.json +23 -0
  46. package/examples/outlook Demo2/src/generated/index.ts +14 -0
  47. package/examples/outlook Demo2/src/generated/models/Office365GroupsModel.ts +363 -0
  48. package/examples/outlook Demo2/src/generated/models/Office365OutlookModel.ts +2046 -0
  49. package/examples/outlook Demo2/src/generated/models/Office365UsersModel.ts +254 -0
  50. package/examples/outlook Demo2/src/generated/services/Office365GroupsService.ts +326 -0
  51. package/examples/outlook Demo2/src/generated/services/Office365OutlookService.ts +2476 -0
  52. package/examples/outlook Demo2/src/generated/services/Office365UsersService.ts +358 -0
  53. package/examples/planning Poker/.vscode/settings.json +4 -4
  54. package/examples/planning Poker/additional files/customizations (tables).xml +6428 -6428
  55. package/examples/planning Poker/additional files/dataverse-tables.json +165 -165
  56. package/examples/planning Poker/additional files/readme.md +122 -122
  57. package/examples/planning Poker/dist/dataverse.js +78 -78
  58. package/examples/planning Poker/dist/index.html +198 -198
  59. package/examples/planning Poker/dist/index.js +954 -954
  60. package/examples/planning Poker/dist/power-apps-data.js +560 -138
  61. package/examples/planning Poker/dist/styles.css +815 -815
  62. package/examples/sharePoint Demo/agent/decision-log.md +5 -5
  63. package/examples/sharePoint Demo/dist/codeapp.js +1085 -0
  64. package/examples/sharePoint Demo/dist/index.js +44 -51
  65. package/examples/sharePoint Demo/dist/power-apps-data.js +551 -170
  66. package/examples/sharePoint Demo/power.config.json +22 -22
  67. package/examples/solution explorer/agent/decision-log.md +27 -0
  68. package/examples/solution explorer/agent/mockup-01-swiss-grid.html +452 -0
  69. package/examples/solution explorer/agent/mockup-02-dark-glass.html +496 -0
  70. package/examples/solution explorer/agent/mockup-03-paper-console.html +510 -0
  71. package/examples/solution explorer/agent/mockup-04-neon-noir.html +546 -0
  72. package/examples/solution explorer/agent/mockup-05-zen-garden.html +534 -0
  73. package/examples/solution explorer/dist/codeapp.js +1098 -0
  74. package/examples/solution explorer/dist/icon-512.png +0 -0
  75. package/examples/solution explorer/dist/index.html +80 -0
  76. package/examples/solution explorer/dist/index.js +735 -0
  77. package/examples/solution explorer/dist/power-apps-data.js +3007 -0
  78. package/examples/solution explorer/dist/styles.css +571 -0
  79. package/examples/solution explorer/power.config.json +151 -0
  80. package/examples/todo/dist/dataverse.js +64 -64
  81. package/examples/todo/dist/index.html +75 -75
  82. package/examples/todo/dist/index.js +8 -8
  83. package/examples/todo/dist/power-apps-data.js +560 -138
  84. package/examples/todo/dist/renderer.js +375 -375
  85. package/examples/todo/dist/styles.css +691 -691
  86. package/examples/todo/power.config.json +34 -34
  87. package/package.json +1 -8
  88. package/docs-mockups/atelier/index.html +0 -120
  89. package/docs-mockups/atelier/script.js +0 -23
  90. package/docs-mockups/atelier/styles.css +0 -361
  91. package/docs-mockups/field-guide/index.html +0 -112
  92. package/docs-mockups/field-guide/script.js +0 -20
  93. package/docs-mockups/field-guide/styles.css +0 -272
  94. package/docs-mockups/index.html +0 -80
  95. package/docs-mockups/maker-hub/index.html +0 -178
  96. package/docs-mockups/maker-hub/script.js +0 -20
  97. package/docs-mockups/maker-hub/styles.css +0 -404
  98. package/docs-mockups/script.js +0 -26
  99. package/docs-mockups/signal/index.html +0 -146
  100. package/docs-mockups/signal/script.js +0 -20
  101. package/docs-mockups/signal/styles.css +0 -314
  102. package/docs-mockups/styles.css +0 -287
  103. package/examples/combined demo/dist/dataverse.js +0 -86
  104. package/examples/combined demo/dist/environmentVar.js +0 -55
  105. package/examples/combined demo/dist/office365groups.js +0 -97
  106. package/examples/combined demo/dist/office365users.js +0 -169
  107. package/examples/combined demo/dist/outlook.js +0 -162
  108. package/examples/combined demo/dist/sharepoint.js +0 -339
  109. package/examples/dataverse Demo/dist/dataverse.js +0 -86
  110. package/examples/groups Demo/dist/dataverse.js +0 -86
  111. package/examples/groups Demo/dist/environmentVar.js +0 -55
  112. package/examples/groups Demo/dist/office365groups.js +0 -97
  113. package/examples/groups Demo/dist/office365users.js +0 -169
  114. package/examples/groups Demo/dist/outlook.js +0 -162
  115. package/examples/groups Demo/dist/sharepoint.js +0 -339
  116. package/examples/sharePoint Demo/dist/dataverse.js +0 -94
  117. package/examples/sharePoint Demo/dist/environmentVar.js +0 -55
  118. package/examples/sharePoint Demo/dist/office365groups.js +0 -97
  119. package/examples/sharePoint Demo/dist/office365users.js +0 -169
  120. package/examples/sharePoint Demo/dist/outlook.js +0 -162
  121. package/examples/sharePoint Demo/dist/sharepoint.js +0 -339
@@ -1,2531 +1,2531 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
-
5
- // node_modules/@microsoft/power-apps/lib/internal/data/core/common/types.js
6
- var HttpMethod;
7
- (function(HttpMethod2) {
8
- HttpMethod2["GET"] = "GET";
9
- HttpMethod2["POST"] = "POST";
10
- HttpMethod2["PUT"] = "PUT";
11
- HttpMethod2["DELETE"] = "DELETE";
12
- HttpMethod2["PATCH"] = "PATCH";
13
- })(HttpMethod || (HttpMethod = {}));
14
- var DataSources;
15
- (function(DataSources2) {
16
- DataSources2["Dataverse"] = "Dataverse";
17
- DataSources2["Connector"] = "Connector";
18
- })(DataSources || (DataSources = {}));
19
-
20
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/codes.js
21
- var ErrorCodes;
22
- (function(ErrorCodes2) {
23
- ErrorCodes2["InitializationFailed"] = "PDR_INIT_FAILED";
24
- ErrorCodes2["InvalidXrmInfo"] = "INVALID_XRM_INFO";
25
- ErrorCodes2["OperationsNotInitialized"] = "OPS_NOT_INITIALIZED";
26
- ErrorCodes2["InvalidOperationExecutor"] = "INVALID_OPERATION_EXECUTOR";
27
- ErrorCodes2["DataSourceNotFound"] = "CONNECTION_NOT_FOUND";
28
- ErrorCodes2["DuplicateDataSource"] = "DUPLICATE_DATA_SOURCE";
29
- ErrorCodes2["InitializationError"] = "RDSS_INIT_ERROR";
30
- ErrorCodes2["InvalidDataSource"] = "INVALID_DATA_SOURCE";
31
- ErrorCodes2["DataSourcesInfoNotFound"] = "DATA_SOURCES_INFO_NOT_FOUND";
32
- ErrorCodes2["DataClientInitFailed"] = "DATA_CLIENT_INIT_FAILED";
33
- ErrorCodes2["DataClientNotInitialized"] = "DATA_CLIENT_NOT_INITIALIZED";
34
- ErrorCodes2["MetadataClientInitFailed"] = "METADATA_CLIENT_INIT_FAILED";
35
- ErrorCodes2["MetadataClientNotInitialized"] = "METADATA_CLIENT_NOT_INITIALIZED";
36
- ErrorCodes2["ClientProviderNotAvailable"] = "CLIENT_PROVIDER_NOT_AVAILABLE";
37
- ErrorCodes2["ConnectionReferenceNotFound"] = "CONNECTION_REFERENCE_NOT_FOUND";
38
- ErrorCodes2["DataClientNotAvailable"] = "DATA_CLIENT_NOT_AVAILABLE";
39
- ErrorCodes2["DataSourceServiceNotAvailable"] = "DATA_SOURCE_SERVICE_NOT_AVAILABLE";
40
- ErrorCodes2["MetadataClientNotAvailable"] = "METADATA_CLIENT_NOT_AVAILABLE";
41
- ErrorCodes2["ConnectionConfigFetchFailed"] = "CONNECTION_CONFIG_FETCH_FAILED";
42
- ErrorCodes2["DataSourceConfigFetchFailed"] = "DATA_SOURCE_CONFIG_FETCH_FAILED";
43
- ErrorCodes2["InvalidMetadataResponse"] = "INVALID_METADATA_RESPONSE";
44
- ErrorCodes2["TokenAcquisitionFailed"] = "TOKEN_ACQUISITION_FAILED";
45
- })(ErrorCodes || (ErrorCodes = {}));
46
-
47
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/messages.js
48
- var UnknownErrorMessage = "An unknown error occurred";
49
- var ErrorMessages = {
50
- // PowerDataRuntime specific errors
51
- [ErrorCodes.InitializationFailed]: "Failed to initialize PowerDataRuntime",
52
- [ErrorCodes.InvalidXrmInfo]: "Xrm info is required",
53
- [ErrorCodes.OperationsNotInitialized]: "PowerDataRuntime is not initialized",
54
- // RuntimeDataSourceService specific errors
55
- [ErrorCodes.DataSourceNotFound]: "Data source not found",
56
- [ErrorCodes.DuplicateDataSource]: "Duplicate data source",
57
- [ErrorCodes.InitializationError]: "Failed to initialize RuntimeDataSourceService",
58
- [ErrorCodes.InvalidDataSource]: "Invalid data source",
59
- // PowerDataSourcesInfoProvider specific errors
60
- [ErrorCodes.DataSourcesInfoNotFound]: "DataSourcesInfo must be provided to initialize the singleton instance.",
61
- // DataClientProvider specific errors
62
- [ErrorCodes.DataClientInitFailed]: "Failed to initialize PowerDataClient",
63
- [ErrorCodes.DataClientNotInitialized]: "PowerDataClient is not initialized",
64
- [ErrorCodes.MetadataClientInitFailed]: "Failed to initialize PowerMetadataClient",
65
- [ErrorCodes.MetadataClientNotInitialized]: "PowerMetadataClient is not initialized",
66
- // DataOperation specific errors
67
- [ErrorCodes.ClientProviderNotAvailable]: "Client provider is not available",
68
- [ErrorCodes.ConnectionReferenceNotFound]: "Connection reference not found",
69
- [ErrorCodes.DataClientNotAvailable]: "PowerDataClient is not available",
70
- [ErrorCodes.DataSourceServiceNotAvailable]: "Data source service is not available",
71
- [ErrorCodes.MetadataClientNotAvailable]: "PowerMetadataClient is not available",
72
- // MetadataClient specific errors
73
- [ErrorCodes.ConnectionConfigFetchFailed]: "Failed to fetch connection configurations",
74
- [ErrorCodes.DataSourceConfigFetchFailed]: "Failed to fetch data source configurations",
75
- [ErrorCodes.InvalidMetadataResponse]: "Invalid metadata response format",
76
- // RuntimeDataClient specific errors
77
- [ErrorCodes.TokenAcquisitionFailed]: "Failed to acquire access token"
78
- };
79
- var DataOperationErrorMessages;
80
- (function(DataOperationErrorMessages2) {
81
- DataOperationErrorMessages2["CreateFailed"] = "Create operation failure";
82
- DataOperationErrorMessages2["DeleteFailed"] = "Delete operation failure";
83
- DataOperationErrorMessages2["ExecuteFailed"] = "Execute operation failure";
84
- DataOperationErrorMessages2["InvalidOperationParameters"] = "Invalid operation parameters";
85
- DataOperationErrorMessages2["InvalidRequest"] = "Invalid request";
86
- DataOperationErrorMessages2["InvalidResponse"] = "Invalid response format";
87
- DataOperationErrorMessages2["MissingConnectorOperation"] = "Connector operation is required";
88
- DataOperationErrorMessages2["MissingDataverseRequest"] = "Dataverse request is required";
89
- DataOperationErrorMessages2["MissingOperationName"] = "Operation name is required";
90
- DataOperationErrorMessages2["MissingRequestBody"] = "Request body is required";
91
- DataOperationErrorMessages2["RetrieveFailed"] = "Retrieve operation failure";
92
- DataOperationErrorMessages2["RetrieveMultipleFailed"] = "Retrieve multiple records operation failure";
93
- DataOperationErrorMessages2["UpdateFailed"] = "Update operation failure";
94
- })(DataOperationErrorMessages || (DataOperationErrorMessages = {}));
95
-
96
- // node_modules/@microsoft/power-apps/lib/internal/data/core/types/index.js
97
- function isOperationResult(result) {
98
- return result?.success !== void 0;
99
- }
100
-
101
- // node_modules/@microsoft/power-apps/lib/internal/data/core/telemetry/log.js
102
- var ServiceName = "PublishedAppTelemetry";
103
- var TelemetryActionNames;
104
- (function(TelemetryActionNames2) {
105
- TelemetryActionNames2["trackEvent"] = "trackEvent";
106
- TelemetryActionNames2["trackException"] = "trackException";
107
- TelemetryActionNames2["trackMetric"] = "trackMetric";
108
- TelemetryActionNames2["startScenario"] = "startScenario";
109
- TelemetryActionNames2["endScenario"] = "endScenario";
110
- TelemetryActionNames2["setDefaultProperties"] = "setDefaultProperties";
111
- })(TelemetryActionNames || (TelemetryActionNames = {}));
112
- var _Log = class _Log {
113
- constructor(_powerOperationExecutor) {
114
- __publicField(this, "_powerOperationExecutor");
115
- this._powerOperationExecutor = _powerOperationExecutor;
116
- }
117
- static createInstance(powerOperationExecutor) {
118
- if (!_Log._instance) {
119
- _Log._instance = new _Log(powerOperationExecutor);
120
- } else {
121
- _Log.trackEvent("TelemetryLogger", {
122
- message: "Attempted to create an instance when instance is already created."
123
- });
124
- }
125
- return _Log._instance;
126
- }
127
- // Since powerDataRuntime can be reset, we need to be able to reset the instance of Log as well.
128
- static resetInstance() {
129
- _Log._instance = null;
130
- }
131
- static async _sendMessage(actionName, ...args) {
132
- try {
133
- const instance = _Log._getInstance();
134
- const result = await instance._powerOperationExecutor.execute(ServiceName, actionName, args);
135
- if (!result.success) {
136
- console.error({
137
- message: `PowerDataRuntime.TelemetryLogger: Failed to send telemetry message.`,
138
- error: result.error,
139
- telemetryArgs: args
140
- });
141
- }
142
- } catch (error) {
143
- console.error({
144
- message: `PowerDataRuntime.TelemetryLogger: Failed to send telemetry message.`,
145
- error,
146
- telemetryArgs: args
147
- });
148
- }
149
- }
150
- static trackEvent(eventName, eventData) {
151
- const serializedData = eventData ? _Log._serializeErrors(eventData) : eventData;
152
- return _Log._sendMessage(TelemetryActionNames.trackEvent, `PowerDataRuntime.${eventName}`, serializedData);
153
- }
154
- static trackException(exception) {
155
- return _Log._sendMessage(TelemetryActionNames.trackException, exception);
156
- }
157
- static trackMetric(metricName, value) {
158
- return _Log._sendMessage(TelemetryActionNames.trackMetric, `PowerDataRuntime.${metricName}`, value);
159
- }
160
- static startScenario(scenarioName) {
161
- return _Log._sendMessage(TelemetryActionNames.startScenario, `PowerDataRuntime.${scenarioName}`);
162
- }
163
- static endScenario(scenarioName) {
164
- return _Log._sendMessage(TelemetryActionNames.endScenario, `PowerDataRuntime.${scenarioName}`);
165
- }
166
- static setDefaultProperties(properties) {
167
- return _Log._sendMessage(TelemetryActionNames.setDefaultProperties, properties);
168
- }
169
- static _getInstance() {
170
- if (!_Log._instance) {
171
- throw new Error("PowerDataRuntime.TelemetryLogger: Attempted to log telemetry prior to instantiation.");
172
- }
173
- return _Log._instance;
174
- }
175
- /**
176
- * Recursively serializes Error objects in an object to prevent empty object serialization
177
- * when passed through postMessage's structured clone algorithm.
178
- * @param obj - The object to process
179
- * @returns A new object with Error instances replaced by serializable objects
180
- */
181
- static _serializeErrors(obj) {
182
- if (obj === null || obj === void 0) {
183
- return obj;
184
- }
185
- if (obj instanceof Error) {
186
- return {
187
- errorMessage: obj.message,
188
- errorStack: obj.stack,
189
- errorType: obj.name
190
- };
191
- }
192
- if (Array.isArray(obj)) {
193
- return obj.map((item) => _Log._serializeErrors(item));
194
- }
195
- if (typeof obj === "object" && obj !== null && Object.getPrototypeOf(obj) === Object.prototype) {
196
- const serialized = {};
197
- for (const key in obj) {
198
- if (Object.prototype.hasOwnProperty.call(obj, key)) {
199
- serialized[key] = _Log._serializeErrors(obj[key]);
200
- }
201
- }
202
- return serialized;
203
- }
204
- return obj;
205
- }
206
- };
207
- __publicField(_Log, "_instance", null);
208
- var Log = _Log;
209
-
210
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/types.js
211
- var PowerDataRuntimeError = class extends Error {
212
- /**
213
- * Creates an instance of PowerDataRuntimeError.
214
- * @param code - The error code associated with the error.
215
- * @param additionalInfo - Optional additional information to include in the error message.
216
- * @param messageOverride - Optional override for the default error message.
217
- */
218
- constructor(code, additionalInfo, messageOverride) {
219
- let message = messageOverride || ErrorMessages[code] || UnknownErrorMessage;
220
- if (additionalInfo) {
221
- message += `: ${additionalInfo}`;
222
- }
223
- super(message);
224
- __publicField(this, "code");
225
- this.code = code;
226
- this.name = "PowerDataRuntimeError";
227
- Log.trackException(this);
228
- }
229
- };
230
-
231
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/constants.js
232
- var HeaderNames;
233
- (function(HeaderNames2) {
234
- HeaderNames2["RequestId"] = "x-ms-client-request-id";
235
- })(HeaderNames || (HeaderNames = {}));
236
- var DataverseOperationName;
237
- (function(DataverseOperationName2) {
238
- DataverseOperationName2["CreateRecord"] = "dataverseDataOperation.createRecordAsync";
239
- DataverseOperationName2["UpdateRecord"] = "dataverseDataOperation.updateRecordAsync";
240
- DataverseOperationName2["DeleteRecord"] = "dataverseDataOperation.deleteRecordAsync";
241
- DataverseOperationName2["RetrieveRecord"] = "dataverseDataOperation.retrieveRecordAsync";
242
- DataverseOperationName2["RetrieveMultipleRecords"] = "dataverseDataOperation.retrieveMultipleRecordsAsync";
243
- })(DataverseOperationName || (DataverseOperationName = {}));
244
- var ConnectorOperationName;
245
- (function(ConnectorOperationName2) {
246
- ConnectorOperationName2["CreateRecord"] = "connectorDataOperation.createRecordAsync";
247
- ConnectorOperationName2["UpdateRecord"] = "connectorDataOperation.updateRecordAsync";
248
- ConnectorOperationName2["DeleteRecord"] = "connectorDataOperation.deleteRecordAsync";
249
- ConnectorOperationName2["RetrieveRecord"] = "connectorDataOperation.retrieveRecordAsync";
250
- ConnectorOperationName2["RetrieveMultipleRecords"] = "connectorDataOperation.retrieveMultipleRecordsAsync";
251
- })(ConnectorOperationName || (ConnectorOperationName = {}));
252
-
253
- // node_modules/@microsoft/power-apps/lib/internal/data/core/error/util.js
254
- function getErrorMessage(error) {
255
- if (typeof error === "string") {
256
- return error;
257
- }
258
- if (error instanceof Error || error instanceof PowerDataRuntimeError) {
259
- return error.message || UnknownErrorMessage;
260
- }
261
- if (isOperationResult(error)) {
262
- return error.error?.message || UnknownErrorMessage;
263
- }
264
- if (typeof error === "object") {
265
- return JSON.stringify(error);
266
- }
267
- return UnknownErrorMessage;
268
- }
269
- function createErrorResponse(error, friendlyMessage) {
270
- const message = getErrorMessage(error);
271
- let data;
272
- if (isOperationResult(error)) {
273
- data = error.data;
274
- }
275
- const errorData = new Error(`${friendlyMessage}: ${message}`);
276
- if (error instanceof Error) {
277
- errorData.stack = error.stack;
278
- }
279
- return {
280
- success: false,
281
- error: errorData,
282
- data
283
- };
284
- }
285
- function parseHttpPluginError(error) {
286
- let message = UnknownErrorMessage;
287
- let response;
288
- if (Array.isArray(error)) {
289
- if (Array.isArray(error[0])) {
290
- message = error[0][0] || UnknownErrorMessage;
291
- response = error[0][2];
292
- }
293
- }
294
- const status = response?.status;
295
- const requestId = response?.headers?.[HeaderNames.RequestId];
296
- return {
297
- message,
298
- status,
299
- requestId
300
- };
301
- }
302
-
303
- // node_modules/@microsoft/power-apps/lib/internal/data/core/data/defaultOperationOrchestrator.js
304
- var DefaultDataOperationOrchestrator = class {
305
- // Static identifiers for services and actions
306
- // Used to identify specific services and actions within the PowerApps environment
307
- constructor(_dataverseOperation, _connectorOperation, _connectionsService) {
308
- __publicField(this, "_dataverseOperation");
309
- __publicField(this, "_connectorOperation");
310
- __publicField(this, "_connectionsService");
311
- this._dataverseOperation = _dataverseOperation;
312
- this._connectorOperation = _connectorOperation;
313
- this._connectionsService = _connectionsService;
314
- }
315
- /**
316
- * Creates a new record in the specified data source.
317
- * @param tableName - The name of the table.
318
- * @param data - The record data to create.
319
- * @returns A promise that resolves to the operation result.
320
- * @throws DataOperationError if the operation fails.
321
- */
322
- async createRecordAsync(tableName, data) {
323
- try {
324
- this._validateParams({ tableName, data });
325
- const executor = await this._getExecutor(tableName);
326
- return await executor.createRecordAsync(tableName, data);
327
- } catch (error) {
328
- return createErrorResponse(error, "Create record operation failed");
329
- }
330
- }
331
- /**
332
- * Updates an existing record in the specified data source.
333
- * @param tableName - The name of the table.
334
- * @param id - The ID of the record to update.
335
- * @param data - The updated record data.
336
- * @returns A promise that resolves to the operation result.
337
- * @throws DataOperationError if the operation fails.
338
- */
339
- async updateRecordAsync(tableName, id, data) {
340
- try {
341
- this._validateParams({ tableName, id, data });
342
- const executor = await this._getExecutor(tableName);
343
- return await executor.updateRecordAsync(tableName, id, data);
344
- } catch (error) {
345
- return createErrorResponse(error, "Update record operation failed");
346
- }
347
- }
348
- /**
349
- * Deletes a record from the specified data source.
350
- * @param tableName - The name of the table.
351
- * @param id - The ID of the record to delete.
352
- * @returns A promise that resolves to the operation result.
353
- * @throws DataOperationError if the operation fails.
354
- */
355
- async deleteRecordAsync(tableName, id) {
356
- try {
357
- this._validateParams({ tableName, id });
358
- const executor = await this._getExecutor(tableName);
359
- return await executor.deleteRecordAsync(tableName, id);
360
- } catch (error) {
361
- return createErrorResponse(error, "Delete record operation failed");
362
- }
363
- }
364
- /**
365
- * Retrieves a record from the specified data source.
366
- * @param tableName - The name of the table.
367
- * @param id - The ID of the record to retrieve.
368
- * @param options - Optional operation options.
369
- * @returns A promise that resolves to the operation result.
370
- * @throws DataOperationError if the operation fails.
371
- */
372
- async retrieveRecordAsync(tableName, id, options) {
373
- try {
374
- this._validateParams({ tableName, id });
375
- const executor = await this._getExecutor(tableName);
376
- this._validateOptions(options);
377
- return await executor.retrieveRecordAsync(tableName, id, options);
378
- } catch (error) {
379
- return createErrorResponse(error, "Retrieve record operation failed");
380
- }
381
- }
382
- /**
383
- * Retrieves multiple records from the specified data source.
384
- * @param tableName - The name of the table.
385
- * @param options - Optional operation options.
386
- * @returns A promise that resolves to the operation result.
387
- * @throws DataOperationError if the operation fails.
388
- */
389
- async retrieveMultipleRecordsAsync(tableName, options) {
390
- try {
391
- this._validateParams({ tableName });
392
- const executor = await this._getExecutor(tableName);
393
- this._validateOptions(options);
394
- return await executor.retrieveMultipleRecordsAsync(tableName, options);
395
- } catch (error) {
396
- return createErrorResponse(error, "Retrieve multiple records operation failed");
397
- }
398
- }
399
- /**
400
- * Executes a data operation on the specified data source.
401
- * @param operation - The operation to execute
402
- * @returns A promise that resolves to the operation result.
403
- * @throws DataOperationError if the operation fails.
404
- */
405
- async executeAsync(operation) {
406
- try {
407
- this._validateParams({ operation });
408
- const executor = await this._getExecutor("", operation.connectorOperation ? DataSources.Connector : DataSources.Dataverse);
409
- return await executor.executeAsync(operation);
410
- } catch (error) {
411
- return createErrorResponse(error, "Execute operation failed");
412
- }
413
- }
414
- /**
415
- * Retrieves the appropriate executor based on the data source.
416
- * @param dataSource - The data source to retrieve the executor for.
417
- * @returns The corresponding executor instance.
418
- * @throws DataOperationError if the data source is invalid.
419
- * // TODO: Add Dataverse support
420
- */
421
- async _getExecutor(tableName, dataSource) {
422
- const dataOperationExecutorOverride = getDataOperationExecutor();
423
- if (dataOperationExecutorOverride) {
424
- return dataOperationExecutorOverride;
425
- }
426
- const dataSourceType = dataSource || (await this._connectionsService.getDataSource(tableName)).dataSourceType;
427
- switch (dataSourceType) {
428
- case DataSources.Dataverse:
429
- return this._dataverseOperation;
430
- case DataSources.Connector:
431
- return this._connectorOperation;
432
- default:
433
- return this._connectorOperation;
434
- }
435
- }
436
- /**
437
- * Validates the input parameters for data operations.
438
- * @param params - The parameters to validate.
439
- * @throws DataOperationError if validation fails.
440
- */
441
- _validateParams(params) {
442
- for (const [key, value] of Object.entries(params)) {
443
- if (!value) {
444
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: ${key} is required`);
445
- }
446
- }
447
- }
448
- /**
449
- * Validates the operation options.
450
- * @param options - The operation options to validate.
451
- * @throws Error if validation fails.
452
- */
453
- _validateOptions(options) {
454
- if (!options) {
455
- return;
456
- }
457
- if (options.maxPageSize && typeof options.maxPageSize !== "number") {
458
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: maxPageSize must be a number`);
459
- }
460
- if (options.select) {
461
- if (!Array.isArray(options.select)) {
462
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: select must be an array of strings`);
463
- }
464
- if (options.select.some((s) => typeof s !== "string" || s.trim() === "")) {
465
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: select must contain only non-empty strings`);
466
- }
467
- }
468
- if (options.filter && typeof options.filter !== "string") {
469
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: filter must be a string`);
470
- }
471
- if (options.orderBy) {
472
- if (!Array.isArray(options.orderBy)) {
473
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: orderBy must be an array of strings`);
474
- }
475
- if (options.orderBy.some((s) => typeof s !== "string" || s.trim() === "")) {
476
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: orderBy must contain only non-empty strings`);
477
- }
478
- }
479
- if (options.top && typeof options.top !== "number") {
480
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: top must be a number`);
481
- }
482
- if (options.skip && typeof options.skip !== "number") {
483
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: skip must be a number`);
484
- }
485
- if (options.count && typeof options.count !== "boolean") {
486
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: count must be a boolean`);
487
- }
488
- }
489
- };
490
-
491
- // node_modules/@microsoft/power-apps/lib/internal/data/core/metadata/runtimeMetadataOperations.js
492
- var RuntimeMetadataOperations = class {
493
- // Static identifiers for services and actions
494
- // Used to identify specific services and actions within the PowerApps environment
495
- constructor(_clientProvider) {
496
- __publicField(this, "_clientProvider");
497
- this._clientProvider = _clientProvider;
498
- }
499
- async getConnections(context) {
500
- const client = await this._clientProvider.getMetadataClientAsync();
501
- const response = await client.getAppConnectionConfigsAsync(context);
502
- return {
503
- success: response.success,
504
- data: response.data ? [response.data] : [],
505
- error: response.error
506
- };
507
- }
508
- async getConnectionApis(_connectionId, context) {
509
- const client = await this._clientProvider.getMetadataClientAsync();
510
- const response = await client.getAppDataSourceConfigsAsync(context);
511
- return {
512
- success: response.success,
513
- data: response.data ? [response.data] : [],
514
- error: response.error
515
- };
516
- }
517
- };
518
-
519
- // node_modules/@microsoft/power-apps/lib/internal/data/core/common/utils.js
520
- function arrayBufferToBase64(buffer) {
521
- return window.btoa(convertArrayBufferToString(buffer));
522
- }
523
- function convertArrayBufferToString(buf) {
524
- if (buf.byteLength <= 65535) {
525
- return String.fromCharCode(...new Uint8Array(buf));
526
- }
527
- let binary = "";
528
- for (let i = 0, bytes = new Uint8Array(buf); i < bytes.byteLength; i++) {
529
- binary += String.fromCharCode(bytes[i]);
530
- }
531
- return binary;
532
- }
533
- function strictEncode(str) {
534
- return encodeURIComponent(str).replace(/\(/g, "%28").replace(/\)/g, "%29");
535
- }
536
- function extractDataverseUrlParts(url) {
537
- const baseUrlMatch = url.match(/^(https?:\/\/[^/]+\/api\/data\/v9\.0)/);
538
- const baseUrl = baseUrlMatch ? baseUrlMatch[1] : "";
539
- const pathMatch = url.match(/\/api\/data\/v9\.0\/(.+)$/);
540
- const encodedPath = pathMatch ? strictEncode(pathMatch[1]) : "";
541
- return { baseUrl, encodedPath };
542
- }
543
-
544
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtimeClient/runtimeDataClient.js
545
- var _RuntimeDataClient = class _RuntimeDataClient {
546
- // Constructor for RuntimeDataClient
547
- // Accepts an IPowerOperationExecutor instance for executing operations
548
- constructor(_powerOperationExecutor) {
549
- __publicField(this, "_powerOperationExecutor");
550
- this._powerOperationExecutor = _powerOperationExecutor;
551
- }
552
- /**
553
- * Creates a new instance of RuntimeDataClient
554
- */
555
- static createInstanceAsync(powerOperationExecutor) {
556
- return Promise.resolve(new _RuntimeDataClient(powerOperationExecutor));
557
- }
558
- /**
559
- * Creates data using POST method
560
- * @param url - The URL for the request
561
- * @param apiId - The API ID for authentication
562
- * @param tableName - The name of the table to access
563
- * @param body - The request body for the POST method
564
- * @param operationName - Optional operation name for telemetry
565
- * @return Promise resolving to the response data
566
- * @throws Error if the request fails or the response is invalid
567
- * @throws Error if the request body is invalid
568
- */
569
- async createDataAsync(url, apiId, tableName, body, context) {
570
- try {
571
- if (!body) {
572
- throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingRequestBody}`);
573
- }
574
- const config = {
575
- url,
576
- method: HttpMethod.POST,
577
- apiId,
578
- tableName,
579
- body: JSON.stringify(body)
580
- };
581
- context = this._ensureContext(context, "runtimeDataClient.createDataAsync");
582
- return await this._executeRequest(config, context);
583
- } catch (error) {
584
- if (isOperationResult(error)) {
585
- return error;
586
- } else {
587
- return createErrorResponse(error, DataOperationErrorMessages.CreateFailed);
588
- }
589
- }
590
- }
591
- /**
592
- * Updates data using PATCH method
593
- * @param url - The URL for the request
594
- * @param apiId - The API ID for authentication
595
- * @param tableName - The name of the table to access
596
- * @param body - The request body for the PATCH method
597
- * @param operationName - Optional operation name for telemetry
598
- * @return Promise resolving to the response data
599
- * @throws Error if the request fails or the response is invalid
600
- * @throws Error if the request body is invalid
601
- */
602
- async updateDataAsync(url, apiId, tableName, body, context) {
603
- try {
604
- if (!body) {
605
- throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingRequestBody}`);
606
- }
607
- const config = {
608
- url,
609
- method: HttpMethod.PATCH,
610
- apiId,
611
- tableName,
612
- body: JSON.stringify(body)
613
- };
614
- context = this._ensureContext(context, "runtimeDataClient.updateDataAsync");
615
- return await this._executeRequest(config, context);
616
- } catch (error) {
617
- if (isOperationResult(error)) {
618
- return error;
619
- } else {
620
- return createErrorResponse(error, DataOperationErrorMessages.UpdateFailed);
621
- }
622
- }
623
- }
624
- /**
625
- * Deletes data using DELETE method
626
- * @param url - The URL for the request
627
- * @param connectionApi - The API ID for authentication
628
- * @param serviceNamespace - The name of the service namespace
629
- * @param operationName - Optional operation name for telemetry
630
- * @return Promise resolving to the response data
631
- * @throws Error if the request fails or the response is invalid
632
- */
633
- async deleteDataAsync(url, connectionApi, serviceNamespace, context) {
634
- try {
635
- const config = {
636
- url,
637
- method: HttpMethod.DELETE,
638
- apiId: connectionApi,
639
- tableName: serviceNamespace
640
- };
641
- context = this._ensureContext(context, "runtimeDataClient.deleteDataAsync");
642
- return await this._executeRequest(config, context);
643
- } catch (error) {
644
- if (isOperationResult(error)) {
645
- return error;
646
- } else {
647
- return createErrorResponse(error, DataOperationErrorMessages.DeleteFailed);
648
- }
649
- }
650
- }
651
- /**
652
- * Retrieves data using GET or POST method
653
- * @param url - The URL for the request
654
- * @param apiId - The API ID for authentication
655
- * @param tableName - The name of the table to access
656
- * @param method - The HTTP method
657
- * @param body - Optional request body for POST method
658
- * @param context - Optional operation context
659
- * @param operationName - Optional operation name for telemetry
660
- * @return Promise resolving to the response data
661
- * @throws Error if the request fails or the response is invalid
662
- */
663
- async retrieveDataAsync(url, apiId, tableName, method, headers, body, context) {
664
- try {
665
- const config = {
666
- url,
667
- method,
668
- apiId,
669
- tableName,
670
- headers,
671
- body: body ? typeof body === "string" ? body : JSON.stringify(body) : void 0
672
- };
673
- context = this._ensureContext(context, "runtimeDataClient.retrieveDataAsync");
674
- return await this._executeRequest(config, context);
675
- } catch (error) {
676
- if (isOperationResult(error)) {
677
- return error;
678
- } else {
679
- return createErrorResponse(error, DataOperationErrorMessages.RetrieveFailed);
680
- }
681
- }
682
- }
683
- /**
684
- * Gets an access token for the specified API.
685
- * If the API is Dataverse, retrieves a dynamic resource token; otherwise, retrieves a standard appservice API token.
686
- * @param apiId - The API ID for authentication
687
- * @param datasetName - Optional dataset name for Dataverse
688
- * @returns Promise resolving to the access token
689
- * @throws Error if token acquisition fails
690
- */
691
- async _getAccessToken(apiId, datasetName) {
692
- try {
693
- let result;
694
- if (apiId === DataSources.Dataverse) {
695
- result = await this._powerOperationExecutor.execute(_RuntimeDataClient.SERVICES.identityService, _RuntimeDataClient.ACTIONS.getDynamicToken, [datasetName]);
696
- } else {
697
- result = await this._powerOperationExecutor.execute(_RuntimeDataClient.SERVICES.identityService, _RuntimeDataClient.ACTIONS.getToken, [apiId]);
698
- }
699
- return result.data;
700
- } catch (error) {
701
- throw new PowerDataRuntimeError(ErrorCodes.TokenAcquisitionFailed, getErrorMessage(error));
702
- }
703
- }
704
- // Merge Prefer headers for Dataverse batch payloads
705
- _mergePreferHeaders(configHeaders, method) {
706
- let preferHeader = "";
707
- if (configHeaders?.Prefer) {
708
- preferHeader += configHeaders.Prefer;
709
- }
710
- if (method === HttpMethod.POST || method === HttpMethod.PATCH) {
711
- const defaultPrefer = "return=representation,odata.include-annotations=*";
712
- if (preferHeader) {
713
- if (!preferHeader.includes("return=representation")) {
714
- preferHeader += (preferHeader ? "," : "") + defaultPrefer;
715
- }
716
- } else {
717
- preferHeader = defaultPrefer;
718
- }
719
- }
720
- return preferHeader;
721
- }
722
- /**
723
- * Creates headers for the HTTP request.
724
- * Combines default headers with any custom headers provided in the config.
725
- * Custom headers are optional and take precedence over default headers.
726
- * @param token - The access token for authentication
727
- * @param config - The HTTP request configuration
728
- * @return The headers for the request
729
- * @throws Error if header creation fails
730
- */
731
- _createHeaders(token, config, context) {
732
- const baseHeaders = {
733
- Accept: "application/json",
734
- "x-ms-protocol-semantics": "cdp",
735
- ServiceNamespace: config.tableName,
736
- Authorization: `paauth ${token}`,
737
- "x-ms-pa-client-custom-headers-options": '{"addCustomHeaders":true}',
738
- "x-ms-enable-selects": "true",
739
- "x-ms-pa-client-telemetry-options": `paclient-telemetry {"operationName":"${context?.operationName ?? "runtimeDataClient.executeRequest"}"}`,
740
- "x-ms-pa-client-telemetry-additional-data": `{"apiId":"${config.apiId}"}`
741
- };
742
- if (config.apiId === DataSources.Dataverse) {
743
- baseHeaders["x-ms-protocol-semantics"] = DataSources.Dataverse;
744
- baseHeaders.Authorization = `dynamicauth ${token}`;
745
- const { baseUrl, encodedPath } = extractDataverseUrlParts(config.url);
746
- const batchId = context?.batchId || "";
747
- const preferHeader = this._mergePreferHeaders(config.headers, config.method);
748
- baseHeaders.BatchInfo = JSON.stringify({
749
- baseUrl,
750
- encodedPath,
751
- headers: {
752
- Accept: "application/json",
753
- ...preferHeader ? { Prefer: preferHeader } : {},
754
- ...config.method === HttpMethod.POST || config.method === HttpMethod.PATCH ? { "Content-Type": "application/json" } : {}
755
- },
756
- batchId
757
- });
758
- }
759
- if (config.headers) {
760
- return { ...baseHeaders, ...config.headers };
761
- }
762
- return baseHeaders;
763
- }
764
- /**
765
- * Executes an HTTP request with the given configuration
766
- * @param config - The HTTP request configuration
767
- * @param context - Optional operation context
768
- * @return Promise resolving to the response data
769
- * @throws Error if the request fails or the response is invalid
770
- * @throws Error if the response content type is invalid
771
- */
772
- async _executeRequest(config, context) {
773
- const token = await this._getAccessToken(config.apiId, context?.datasetName);
774
- const headers = this._createHeaders(token, config, context);
775
- const requestBody = config.body ? new Blob([config.body], { type: "application/json" }) : "";
776
- let result;
777
- try {
778
- result = await this._powerOperationExecutor.execute(_RuntimeDataClient.SERVICES.dataClient, _RuntimeDataClient.ACTIONS.sendHttp, [
779
- {
780
- url: config.url,
781
- method: config.method,
782
- requestSource: _RuntimeDataClient.REQUEST_SOURCE,
783
- allowSessionStorage: true,
784
- returnDirectResponse: true,
785
- headers
786
- },
787
- requestBody,
788
- "arraybuffer"
789
- ]);
790
- } catch (error) {
791
- return {
792
- success: false,
793
- error: parseHttpPluginError(error),
794
- data: void 0
795
- };
796
- }
797
- const responseData = result.data;
798
- const responseHeaders = responseData[0].headers;
799
- const contentType = responseHeaders["Content-Type"];
800
- if (!contentType) {
801
- return {
802
- success: true,
803
- data: void 0
804
- };
805
- } else if (contentType.indexOf("application/json") !== -1) {
806
- const data = result.data[1];
807
- let text = this._decodeArrayBuffer(data);
808
- if (!text) {
809
- text = "{}";
810
- }
811
- const parsedResult = JSON.parse(text);
812
- if (context?.isDataVerseOperation || this._isDataverseCall(config.url)) {
813
- return {
814
- success: true,
815
- data: parsedResult
816
- };
817
- } else if (!context?.isExecuteAsync && "value" in parsedResult && Array.isArray(parsedResult.value)) {
818
- return {
819
- success: true,
820
- data: parsedResult.value,
821
- count: parsedResult["@odata.count"]
822
- };
823
- } else {
824
- return {
825
- success: true,
826
- data: parsedResult
827
- };
828
- }
829
- } else if (contentType.indexOf("image/") !== -1) {
830
- const buffer = result.data[1];
831
- if (buffer instanceof ArrayBuffer) {
832
- const value = arrayBufferToBase64(buffer);
833
- return {
834
- success: true,
835
- data: value
836
- };
837
- }
838
- return {
839
- success: true,
840
- data: buffer
841
- };
842
- } else {
843
- const buffer = result.data[1];
844
- if (buffer instanceof ArrayBuffer) {
845
- const value = convertArrayBufferToString(buffer);
846
- const status = responseData[0].status;
847
- const responseType = context?.responseInfo?.[status];
848
- if (responseType) {
849
- let parsedValue;
850
- try {
851
- parsedValue = JSON.parse(value);
852
- } catch (err) {
853
- return {
854
- success: false,
855
- data: void 0,
856
- error: new Error(DataOperationErrorMessages.InvalidResponse)
857
- };
858
- }
859
- if (responseType.type === "array" && !Array.isArray(parsedValue)) {
860
- return {
861
- success: false,
862
- data: void 0,
863
- error: new Error(DataOperationErrorMessages.InvalidResponse)
864
- };
865
- }
866
- if (responseType.type === "object" && (typeof parsedValue !== "object" || Array.isArray(parsedValue) || parsedValue === null)) {
867
- return {
868
- success: false,
869
- data: void 0,
870
- error: new Error(DataOperationErrorMessages.InvalidResponse)
871
- };
872
- }
873
- return {
874
- success: true,
875
- data: parsedValue
876
- };
877
- } else {
878
- return {
879
- success: true,
880
- data: value
881
- };
882
- }
883
- }
884
- return {
885
- success: false,
886
- data: responseData,
887
- error: new Error(DataOperationErrorMessages.InvalidResponse)
888
- };
889
- }
890
- }
891
- _ensureContext(context, defaultOperationName) {
892
- if (!context) {
893
- context = {};
894
- }
895
- if (!context.operationName) {
896
- context.operationName = defaultOperationName;
897
- }
898
- return context;
899
- }
900
- /**
901
- * Checks if the given URL is a Dataverse API call
902
- * @param url - The URL to check
903
- * @returns True if the URL is a Dataverse API call, false otherwise
904
- */
905
- _isDataverseCall(url) {
906
- if (!url) {
907
- return false;
908
- }
909
- const urlLower = decodeURIComponent(url).toLowerCase();
910
- return urlLower.includes("/api/data/") && !urlLower.includes("/apim");
911
- }
912
- /**
913
- * Decodes ArrayBuffer to string, handling both browser and Node.js environments
914
- * @param buffer - The ArrayBuffer to decode
915
- * @returns The decoded string
916
- */
917
- _decodeArrayBuffer(buffer) {
918
- if (typeof TextDecoder !== "undefined") {
919
- return new TextDecoder().decode(buffer);
920
- }
921
- const uint8Array = new Uint8Array(buffer);
922
- const results = [];
923
- const chunkSize = 8192;
924
- for (let i = 0; i < uint8Array.length; i += chunkSize) {
925
- const chunk = uint8Array.subarray(i, Math.min(i + chunkSize, uint8Array.length));
926
- results.push(String.fromCharCode.apply(null, Array.from(chunk)));
927
- }
928
- try {
929
- return results.join("");
930
- } catch {
931
- return results.join("");
932
- }
933
- }
934
- };
935
- // Static identifiers for services
936
- // Used to identify specific services within the PowerApps environment
937
- __publicField(_RuntimeDataClient, "SERVICES", {
938
- dataClient: "AppHttpClientPlugin",
939
- identityService: "AppIdentityServicePlugin"
940
- });
941
- // Static identifiers for service actions
942
- // Used to identify specific actions within the service
943
- // These actions are used to send HTTP requests and get access tokens
944
- __publicField(_RuntimeDataClient, "ACTIONS", {
945
- sendHttp: "sendHttpAsync",
946
- getToken: "getAppAccessTokenAsync",
947
- getDynamicToken: "getAppDynamicResourceAccessTokenAsync"
948
- });
949
- // Request source identifier for telemetry
950
- // Used to identify the source of the request in telemetry data
951
- __publicField(_RuntimeDataClient, "REQUEST_SOURCE", "PublishedApp");
952
- var RuntimeDataClient = _RuntimeDataClient;
953
-
954
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtimeClient/runtimeMetadataClient.js
955
- var _RuntimeMetadataClient = class _RuntimeMetadataClient {
956
- // Private member for the PowerOperationExecutor
957
- // The PowerOperationExecutor is used to execute operations on the clients
958
- constructor(_powerOperationExecutor) {
959
- __publicField(this, "_powerOperationExecutor");
960
- this._powerOperationExecutor = _powerOperationExecutor;
961
- }
962
- /**
963
- * Creates a new instance of RuntimeMetadataClient
964
- * @param powerOperationExecutor - The powerOperationExecutor instance
965
- * @returns Promise resolving to IRuntimeMetadataClient
966
- */
967
- static createInstanceAsync(powerOperationExecutor) {
968
- return Promise.resolve(new _RuntimeMetadataClient(powerOperationExecutor));
969
- }
970
- /**
971
- * Fetches app connection configurations
972
- * @returns Promise resolving to connection reference details
973
- * @throws Error if the operation fails
974
- */
975
- async getAppConnectionConfigsAsync() {
976
- try {
977
- const config = {
978
- service: _RuntimeMetadataClient.SERVICES.powerAppsClient,
979
- action: _RuntimeMetadataClient.ACTIONS.getConnectionConfigs,
980
- params: []
981
- };
982
- const result = await this._executeOperation(config);
983
- return { success: true, data: result };
984
- } catch (error) {
985
- throw new PowerDataRuntimeError(ErrorCodes.ConnectionConfigFetchFailed, getErrorMessage(error));
986
- }
987
- }
988
- /**
989
- * Fetches app data source configurations
990
- * @returns Promise resolving to connection reference details
991
- * @throws Error if the operation fails
992
- */
993
- async getAppDataSourceConfigsAsync() {
994
- try {
995
- const config = {
996
- service: _RuntimeMetadataClient.SERVICES.powerAppsClient,
997
- action: _RuntimeMetadataClient.ACTIONS.getDataSourceConfigs,
998
- params: []
999
- };
1000
- const result = await this._executeOperation(config);
1001
- return { success: true, data: result };
1002
- } catch (error) {
1003
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceConfigFetchFailed, getErrorMessage(error));
1004
- }
1005
- }
1006
- /**
1007
- * Executes a metadata operation with the given configuration
1008
- * @param config - The operation configuration
1009
- * @returns Promise resolving to the operation result
1010
- * @throws Error if the operation fails
1011
- */
1012
- async _executeOperation(config) {
1013
- try {
1014
- const result = await this._powerOperationExecutor.execute(config.service, config.action, config.params || []);
1015
- const lowerCaseResult = Object.keys(result.data).reduce((acc, key) => {
1016
- acc[key.toLowerCase()] = (result.data ?? {})[key];
1017
- return acc;
1018
- }, {});
1019
- return lowerCaseResult;
1020
- } catch {
1021
- throw new PowerDataRuntimeError(ErrorCodes.InvalidMetadataResponse);
1022
- }
1023
- }
1024
- };
1025
- // Static identifiers for services and actions
1026
- // Used to identify specific services and actions within the PowerApps environment
1027
- // These identifiers are used to execute operations through the PowerOperationExecutor
1028
- // The services provide the functionality for the operations
1029
- __publicField(_RuntimeMetadataClient, "SERVICES", {
1030
- powerAppsClient: "AppPowerAppsClientPlugin"
1031
- });
1032
- // The actions define the specific operations to be performed
1033
- __publicField(_RuntimeMetadataClient, "ACTIONS", {
1034
- getConnectionConfigs: "loadAppConnectionsAsync_v2",
1035
- getDataSourceConfigs: "getAppCdsDataSourceConfigsAsync"
1036
- });
1037
- var RuntimeMetadataClient = _RuntimeMetadataClient;
1038
-
1039
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtimeClient/runtimeClientProvider.js
1040
- var RuntimeClientProvider = class {
1041
- // Constructor for RuntimeClientProvider
1042
- // Accepts an optional IPowerOperationExecutor instance for executing operations
1043
- // If not provided, uses the default PowerOperationExecutor instance
1044
- constructor(powerOperationExecutor) {
1045
- // Private members for data and metadata clients
1046
- // The data client is responsible for handling data operations
1047
- __publicField(this, "_dataClient");
1048
- // The metadata client is responsible for handling metadata operations
1049
- __publicField(this, "_metadataClient");
1050
- // The operation executor is used to execute operations on the clients
1051
- // It is an instance of IPowerOperationExecutor, which provides the necessary methods for executing operations
1052
- __publicField(this, "_operationExecutor");
1053
- this._operationExecutor = powerOperationExecutor;
1054
- }
1055
- /**
1056
- * Gets or initializes the data client
1057
- * @throws Error if client initialization fails
1058
- * @returns Promise resolving to IRuntimeDataClient
1059
- */
1060
- async getDataClientAsync() {
1061
- try {
1062
- if (!this._dataClient) {
1063
- this._dataClient = await this._initializeDataClient();
1064
- }
1065
- if (!this._dataClient) {
1066
- throw new PowerDataRuntimeError(ErrorCodes.DataClientNotInitialized);
1067
- }
1068
- return this._dataClient;
1069
- } catch (error) {
1070
- throw new PowerDataRuntimeError(ErrorCodes.DataClientInitFailed, getErrorMessage(error));
1071
- }
1072
- }
1073
- /**
1074
- * Gets or initializes the metadata client
1075
- * @throws Error if client initialization fails
1076
- * @returns Promise resolving to IRuntimeMetadataClient
1077
- */
1078
- async getMetadataClientAsync() {
1079
- try {
1080
- if (!this._metadataClient) {
1081
- this._metadataClient = await this._initializeMetadataClient();
1082
- }
1083
- if (!this._metadataClient) {
1084
- throw new PowerDataRuntimeError(ErrorCodes.MetadataClientNotInitialized);
1085
- }
1086
- return this._metadataClient;
1087
- } catch (error) {
1088
- throw new PowerDataRuntimeError(ErrorCodes.MetadataClientInitFailed, getErrorMessage(error));
1089
- }
1090
- }
1091
- /**
1092
- * Initializes the data client
1093
- * @returns Promise resolving to IRuntimeDataClient
1094
- */
1095
- async _initializeDataClient() {
1096
- return RuntimeDataClient.createInstanceAsync(this._operationExecutor);
1097
- }
1098
- /**
1099
- * Initializes the metadata client
1100
- * @returns Promise resolving to IRuntimeMetadataClient
1101
- */
1102
- async _initializeMetadataClient() {
1103
- return RuntimeMetadataClient.createInstanceAsync(this._operationExecutor);
1104
- }
1105
- /**
1106
- * Resets both clients, forcing re-initialization on next use
1107
- * Useful for testing or recovering from error states
1108
- */
1109
- reset() {
1110
- this._dataClient = void 0;
1111
- this._metadataClient = void 0;
1112
- }
1113
- };
1114
-
1115
- // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/shared/stringQueryOptions.js
1116
- function convertOptionsToQueryString(options) {
1117
- if (!options) {
1118
- return "";
1119
- }
1120
- const parts = [];
1121
- if (options.select && options.select.length > 0) {
1122
- parts.push(`$select=${encodeURIComponent(options.select.map((s) => s.trim().replace(/%20/g, "+").replace(/'/g, "%27")).join(","))}`);
1123
- }
1124
- if (options.filter) {
1125
- const encodedFilter = encodeURIComponent(options.filter.trim()).replace(/%20/g, "+").replace(/'/g, "%27");
1126
- parts.push(`$filter=${encodedFilter}`);
1127
- }
1128
- if (options.orderBy && options.orderBy.length > 0) {
1129
- parts.push(`$orderby=${encodeURIComponent(options.orderBy.map((s) => s.trim().replace(/%20/g, "+").replace(/'/g, "%27")).join(","))}`);
1130
- }
1131
- if (options.top !== void 0 && options.top !== null) {
1132
- parts.push(`$top=${options.top}`);
1133
- }
1134
- if (options.skip !== void 0 && options.skip !== null) {
1135
- parts.push(`$skip=${options.skip}`);
1136
- }
1137
- if (options.count !== void 0 && options.count !== null) {
1138
- parts.push(`$count=${options.count}`);
1139
- }
1140
- if (options.skipToken && options.skipToken.trim() !== "") {
1141
- parts.push(`$skiptoken=${encodeURIComponent(options.skipToken.trim())}`);
1142
- }
1143
- return parts.length ? `?${parts.join("&")}` : "";
1144
- }
1145
-
1146
- // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/dataverseDataOperationExecutor.js
1147
- var ODATA_NEXT_LINK = "@odata.nextLink";
1148
- var DataverseDataOperationExecutor = class {
1149
- constructor(clientProvider) {
1150
- // Static identifiers for services and actions
1151
- // Used to identify specific services and actions within the PowerApps environment
1152
- __publicField(this, "_clientProvider");
1153
- __publicField(this, "_databaseReferences");
1154
- this._clientProvider = clientProvider;
1155
- }
1156
- /**
1157
- * Creates a new record in Dataverse
1158
- * @param tableName - The name of the table
1159
- * @param data - The record data to create
1160
- * @returns Promise resolving to operation result
1161
- */
1162
- async createRecordAsync(tableName, data) {
1163
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName), async (dataClient, requestUrl, dataSourceInfo) => {
1164
- const dataverseResponse = await dataClient.createDataAsync(
1165
- requestUrl,
1166
- DataSources.Dataverse,
1167
- // Use environment name for Dataverse authentication
1168
- tableName,
1169
- data,
1170
- {
1171
- operationName: DataverseOperationName.CreateRecord,
1172
- datasetName: dataSourceInfo.datasetName,
1173
- isDataVerseOperation: true
1174
- }
1175
- );
1176
- const returnValue = {
1177
- success: dataverseResponse.success,
1178
- data: dataverseResponse.data,
1179
- error: dataverseResponse.error
1180
- };
1181
- return returnValue;
1182
- }, DataOperationErrorMessages.CreateFailed);
1183
- }
1184
- /**
1185
- * Updates an existing record in Dataverse
1186
- * @param tableName - The name of the table
1187
- * @param id - The record identifier
1188
- * @param data - The updated record data
1189
- * @returns Promise resolving to operation result
1190
- */
1191
- async updateRecordAsync(tableName, id, data) {
1192
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, `(${id})`), async (dataClient, requestUrl, dataSourceInfo) => {
1193
- const dataverseResponse = await dataClient.updateDataAsync(requestUrl, DataSources.Dataverse, tableName, data, {
1194
- operationName: DataverseOperationName.UpdateRecord,
1195
- datasetName: dataSourceInfo.datasetName,
1196
- isDataVerseOperation: true
1197
- });
1198
- const returnValue = {
1199
- success: dataverseResponse.success,
1200
- data: dataverseResponse.data,
1201
- error: dataverseResponse.error
1202
- };
1203
- return returnValue;
1204
- }, DataOperationErrorMessages.UpdateFailed);
1205
- }
1206
- /**
1207
- * Deletes a record from Dataverse
1208
- * @param tableName - The name of the table
1209
- * @param id - The record identifier
1210
- * @returns Promise resolving to operation result
1211
- */
1212
- async deleteRecordAsync(tableName, id) {
1213
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, `(${id})`), async (dataClient, requestUrl, dataSourceInfo) => {
1214
- const dataverseResponse = await dataClient.deleteDataAsync(requestUrl, DataSources.Dataverse, tableName, {
1215
- operationName: DataverseOperationName.DeleteRecord,
1216
- datasetName: dataSourceInfo.datasetName,
1217
- isDataVerseOperation: true
1218
- });
1219
- const returnValue = {
1220
- success: dataverseResponse.success,
1221
- data: dataverseResponse.data,
1222
- error: dataverseResponse.error
1223
- };
1224
- return returnValue;
1225
- }, DataOperationErrorMessages.DeleteFailed);
1226
- }
1227
- /**
1228
- * Retrieves a single record from Dataverse
1229
- * @param tableName - The name of the table
1230
- * @param id - The record identifier
1231
- * @param options - The retrieval options
1232
- * @returns Promise resolving to operation result
1233
- */
1234
- async retrieveRecordAsync(tableName, id, options) {
1235
- const { maxPageSize = 500, ...rest } = options || {};
1236
- const optionsString = convertOptionsToQueryString(rest);
1237
- const headers = { Prefer: `odata.maxpagesize=${maxPageSize},odata.include-annotations=*` };
1238
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, `(${id})${optionsString}`), async (dataClient, requestUrl, dataSourceInfo) => {
1239
- const dataverseResponse = await dataClient.retrieveDataAsync(
1240
- requestUrl,
1241
- DataSources.Dataverse,
1242
- tableName,
1243
- HttpMethod.GET,
1244
- headers,
1245
- void 0,
1246
- // No body for GET requests
1247
- {
1248
- operationName: DataverseOperationName.RetrieveRecord,
1249
- datasetName: dataSourceInfo.datasetName,
1250
- isDataVerseOperation: true
1251
- }
1252
- );
1253
- const returnValue = {
1254
- success: dataverseResponse.success,
1255
- data: dataverseResponse.data,
1256
- error: dataverseResponse.error
1257
- };
1258
- return returnValue;
1259
- }, DataOperationErrorMessages.RetrieveFailed);
1260
- }
1261
- /**
1262
- * Retrieves multiple records from Dataverse
1263
- * @param tableName - The name of the table
1264
- * @param options - The retrieval options
1265
- * @param maxPageSize - Optional maximum page size
1266
- * @returns Promise resolving to operation result
1267
- */
1268
- async retrieveMultipleRecordsAsync(tableName, options) {
1269
- const { maxPageSize = 500, ...rest } = options || {};
1270
- const optionsString = convertOptionsToQueryString(rest);
1271
- const headers = { Prefer: `odata.maxpagesize=${maxPageSize},odata.include-annotations=*` };
1272
- return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, optionsString), async (dataClient, requestUrl, dataSourceInfo) => {
1273
- const dataverseResponse = await dataClient.retrieveDataAsync(
1274
- requestUrl,
1275
- DataSources.Dataverse,
1276
- tableName,
1277
- HttpMethod.GET,
1278
- headers,
1279
- void 0,
1280
- // No body for GET requests
1281
- {
1282
- operationName: DataverseOperationName.RetrieveMultipleRecords,
1283
- datasetName: dataSourceInfo.datasetName,
1284
- isDataVerseOperation: true
1285
- }
1286
- );
1287
- const returnValue = {
1288
- success: dataverseResponse.success,
1289
- data: dataverseResponse?.data?.value || [],
1290
- skipToken: extractSkipToken(dataverseResponse?.data?.[ODATA_NEXT_LINK]),
1291
- error: dataverseResponse.error
1292
- };
1293
- return returnValue;
1294
- }, DataOperationErrorMessages.RetrieveMultipleFailed);
1295
- }
1296
- /**
1297
- * Executes a custom Dataverse operation
1298
- * @param operation - The operation to execute
1299
- * @returns Promise resolving to operation result
1300
- */
1301
- async executeAsync(operation) {
1302
- const { dataverseRequest } = operation;
1303
- if (!dataverseRequest) {
1304
- return {
1305
- success: false,
1306
- data: null,
1307
- error: { message: "Dataverse request details are required for Dataverse operations." }
1308
- };
1309
- }
1310
- const { action, parameters } = dataverseRequest;
1311
- switch (action) {
1312
- // Future custom actions can be handled here
1313
- case "getEntityMetadata":
1314
- const { tableName, options } = parameters;
1315
- if (!tableName) {
1316
- return {
1317
- success: false,
1318
- data: null,
1319
- error: { message: "Table name is required for getEntityMetadata action." }
1320
- };
1321
- }
1322
- return this._getEntityMetadata(tableName, options ?? {});
1323
- default:
1324
- Log.trackEvent("DataverseDataOperation.UnsupportedAction", {
1325
- message: `Unsupported Dataverse action: ${action}`
1326
- });
1327
- return {
1328
- success: false,
1329
- data: null,
1330
- error: { message: `Unsupported Dataverse action: "${action}"` }
1331
- };
1332
- }
1333
- }
1334
- async _getEntityMetadata(tableName, options) {
1335
- const client = await this._getDataClient();
1336
- const dataSourceInfo = await this._getDataverseDataSourceInfo(tableName);
1337
- const url = this._generateMetadataRequestUrl(dataSourceInfo, options);
1338
- return client.retrieveDataAsync(url, DataSources.Dataverse, "EntityDefinitions", HttpMethod.GET, {
1339
- Consistency: "Strong"
1340
- // Force CDS to return latest metadata
1341
- }, void 0, {
1342
- operationName: DataverseOperationName.RetrieveRecord,
1343
- datasetName: dataSourceInfo.datasetName,
1344
- isDataVerseOperation: true
1345
- });
1346
- }
1347
- /**
1348
- * Returns the database references for Dataverse, grouped by environment/database.
1349
- * These come from the launch app response via runtime metadata client.
1350
- */
1351
- async getDatabaseReferences() {
1352
- if (this._databaseReferences) {
1353
- return this._databaseReferences;
1354
- }
1355
- const runtimeDatabaseReferences = await this._loadDatabaseReferencesFromRuntime();
1356
- if (runtimeDatabaseReferences && Object.keys(runtimeDatabaseReferences).length > 0) {
1357
- this._databaseReferences = runtimeDatabaseReferences;
1358
- return this._databaseReferences;
1359
- }
1360
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, "Failed to load Dataverse database references from runtime.");
1361
- }
1362
- /**
1363
- * Loads database references from runtime metadata client (launch app response).
1364
- */
1365
- async _loadDatabaseReferencesFromRuntime() {
1366
- try {
1367
- const metadataClient = await this._getMetadataClient();
1368
- const response = await metadataClient.getAppDataSourceConfigsAsync();
1369
- if (!response.success || !response.data) {
1370
- return void 0;
1371
- }
1372
- const cdsDataSources = Object.values(response.data);
1373
- if (cdsDataSources.length === 0) {
1374
- return void 0;
1375
- }
1376
- const databaseReferences = {};
1377
- for (const cdsDataSource of cdsDataSources) {
1378
- const cdsConfig = cdsDataSource;
1379
- const instanceUrl = this._extractInstanceUrlFromRuntimeUrl(cdsConfig.runtimeUrl);
1380
- const envName = "default.cds";
1381
- if (!databaseReferences[envName]) {
1382
- databaseReferences[envName] = {
1383
- databaseDetails: {
1384
- referenceType: "Environmental",
1385
- environmentName: envName,
1386
- overrideValues: {
1387
- status: "NotSpecified",
1388
- environmentVariableName: ""
1389
- },
1390
- linkedEnvironmentMetadata: {
1391
- resourceId: "",
1392
- friendlyName: "",
1393
- uniqueName: "",
1394
- domainName: "",
1395
- version: cdsConfig.version || "9.2",
1396
- instanceUrl,
1397
- instanceApiUrl: cdsConfig.runtimeUrl,
1398
- baseLanguage: 1033,
1399
- instanceState: "Ready",
1400
- createdTime: "",
1401
- platformSku: ""
1402
- }
1403
- },
1404
- dataSources: {}
1405
- };
1406
- }
1407
- const dataSourceName = cdsConfig.entitySetName || cdsConfig.logicalName;
1408
- databaseReferences[envName].dataSources[dataSourceName] = {
1409
- entitySetName: cdsConfig.entitySetName,
1410
- logicalName: cdsConfig.logicalName,
1411
- isHidden: false
1412
- };
1413
- }
1414
- return databaseReferences;
1415
- } catch (error) {
1416
- Log.trackEvent("DataverseDataOperation.FailedToLoadDatabaseReferences", {
1417
- message: "[DataverseDataOperation] Failed to load database references from runtime",
1418
- error
1419
- });
1420
- return void 0;
1421
- }
1422
- }
1423
- _extractInstanceUrlFromRuntimeUrl(runtimeUrl) {
1424
- try {
1425
- const matches = runtimeUrl.match(/^(https?:\/\/[^\/]+)/);
1426
- return matches ? matches[1] : runtimeUrl;
1427
- } catch (error) {
1428
- Log.trackEvent("DataverseDataOperation.FailedToExtractInstanceUrl", {
1429
- message: "[DataverseDataOperation] Failed to extract instance URL from runtime URL",
1430
- error
1431
- });
1432
- return runtimeUrl;
1433
- }
1434
- }
1435
- /**
1436
- * Helper to get a native data client and database reference
1437
- */
1438
- async _getDataClient() {
1439
- const dataClient = await this._clientProvider.getDataClientAsync();
1440
- if (!dataClient) {
1441
- Log.trackEvent("DataverseDataOperation.DataClientNotAvailable", {
1442
- message: "[DataverseDataOperation] Data client is not available"
1443
- });
1444
- throw new PowerDataRuntimeError(ErrorCodes.DataClientNotAvailable, "Data client is not available.");
1445
- }
1446
- return dataClient;
1447
- }
1448
- /**
1449
- * Gets the metadata client instance
1450
- */
1451
- async _getMetadataClient() {
1452
- const metadataClient = await this._clientProvider.getMetadataClientAsync();
1453
- if (!metadataClient) {
1454
- Log.trackEvent("DataverseDataOperation.MetadataClientNotAvailable", {
1455
- message: "[DataverseDataOperation] Metadata client is not available"
1456
- });
1457
- throw new PowerDataRuntimeError(ErrorCodes.MetadataClientNotAvailable);
1458
- }
1459
- return metadataClient;
1460
- }
1461
- /**
1462
- * Template method for connector-style CRUD operations to reduce duplication.
1463
- * Handles client, dataSourceInfo, requestUrl, and error handling.
1464
- */
1465
- async _executeNativeDataverseOperation(tableName, buildUrl, operation, errorMessage) {
1466
- try {
1467
- const dataClient = await this._getDataClient();
1468
- const dataSourceInfo = await this._getDataverseDataSourceInfo(tableName);
1469
- const requestUrl = buildUrl(dataSourceInfo, tableName);
1470
- return operation(dataClient, requestUrl, dataSourceInfo);
1471
- } catch (error) {
1472
- return createErrorResponse(error, errorMessage);
1473
- }
1474
- }
1475
- /**
1476
- * Helper to get the Dataverse datasourceinfo from databaseReferences
1477
- */
1478
- async _getDataverseDataSourceInfo(tableName) {
1479
- let dbRefs;
1480
- try {
1481
- dbRefs = await this.getDatabaseReferences();
1482
- } catch (error) {
1483
- Log.trackEvent("DataverseDataOperation.GetDataSourceInfoFailed", {
1484
- message: "[DataverseDataOperation] Failed to get database references",
1485
- tableName,
1486
- error
1487
- });
1488
- const errorMessage = error instanceof Error ? error.message : String(error);
1489
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, `Failed to get Dataverse data source info for table '${tableName}': ${errorMessage}`);
1490
- }
1491
- for (const dbKey of Object.keys(dbRefs)) {
1492
- const db = dbRefs[dbKey];
1493
- if (db.dataSources[tableName]) {
1494
- const ds = db.dataSources[tableName];
1495
- return {
1496
- datasetName: db.databaseDetails?.environmentName,
1497
- referenceType: db.databaseDetails?.referenceType,
1498
- linkedEnvironmentMetadata: db.databaseDetails?.linkedEnvironmentMetadata,
1499
- entitySetName: ds?.entitySetName,
1500
- logicalName: ds?.logicalName,
1501
- isHidden: ds?.isHidden,
1502
- tableId: ds?.logicalName,
1503
- apis: {}
1504
- };
1505
- }
1506
- }
1507
- const notFoundMsg = `No Dataverse data source found for table: ${tableName}`;
1508
- Log.trackEvent("DataverseDataOperation.DataSourceNotFound", {
1509
- message: notFoundMsg,
1510
- tableName
1511
- });
1512
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, notFoundMsg);
1513
- }
1514
- /**
1515
- * Helper to construct the Dataverse API URL using instanceUrl if available, otherwise fallback to runtimeUrl.
1516
- */
1517
- _getInstanceUrl(dataSourceInfo) {
1518
- const instanceUrl = dataSourceInfo.linkedEnvironmentMetadata?.instanceUrl;
1519
- if (!instanceUrl) {
1520
- throw new PowerDataRuntimeError(ErrorCodes.DataClientInitFailed, "No instanceUrl found for Dataverse table.");
1521
- }
1522
- const baseUrl = instanceUrl.endsWith("/") ? instanceUrl : `${instanceUrl}/`;
1523
- return baseUrl;
1524
- }
1525
- /**
1526
- * Helper to construct the Dataverse API URL using instanceUrl if available, otherwise fallback to runtimeUrl.
1527
- */
1528
- _getDataverseRequestUrl(dataSourceInfo, tableName, urlPath = "") {
1529
- const baseUrl = this._getInstanceUrl(dataSourceInfo);
1530
- return `${baseUrl}api/data/v9.0/${tableName}${urlPath}`;
1531
- }
1532
- /**
1533
- * Constructs GET request URL for fetching metadata using options object.
1534
- * @param dataSourceInfo - The data source information for the Dataverse table.
1535
- * @param options - The options for the metadata request.
1536
- * @returns The constructed metadata request URL.
1537
- */
1538
- _generateMetadataRequestUrl(dataSourceInfo, options) {
1539
- const { logicalName } = dataSourceInfo;
1540
- if (!logicalName) {
1541
- throw new PowerDataRuntimeError(ErrorCodes.DataClientInitFailed, "No logicalName found for Dataverse table.");
1542
- }
1543
- const url = new URL(`${this._getInstanceUrl(dataSourceInfo)}api/data/v9.0/EntityDefinitions(LogicalName='${logicalName}')`);
1544
- const { metadata, schema } = options;
1545
- const selects = new Set(Array.isArray(metadata) ? metadata : []);
1546
- selects.add("LogicalName");
1547
- const expands = [];
1548
- if (schema?.manyToOne) {
1549
- expands.push("ManyToOneRelationships");
1550
- }
1551
- if (schema?.oneToMany) {
1552
- expands.push("OneToManyRelationships");
1553
- }
1554
- if (schema?.manyToMany) {
1555
- expands.push("ManyToManyRelationships");
1556
- }
1557
- if (schema?.columns === "all") {
1558
- expands.push("Attributes");
1559
- } else if (schema && Array.isArray(schema.columns) && schema.columns.length > 0) {
1560
- const attributesCollection = schema.columns.map((a) => `'${a}'`).join(",");
1561
- expands.push(`Attributes($filter=Microsoft.Dynamics.CRM.In(PropertyName='LogicalName',PropertyValues=[${attributesCollection}]))`);
1562
- }
1563
- url.search = new URLSearchParams({
1564
- $select: [...selects].join(","),
1565
- $expand: expands.join(",")
1566
- }).toString();
1567
- return url.toString();
1568
- }
1569
- };
1570
- function extractSkipToken(nextLink) {
1571
- if (!nextLink?.trim()) {
1572
- return void 0;
1573
- }
1574
- const match = nextLink.match(/[\?&]\$?skiptoken=([^&#]+)/i);
1575
- return match ? decodeURIComponent(match[1]) : void 0;
1576
- }
1577
-
1578
- // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/connectorDataOperationExecutor.js
1579
- var ConnectorDataOperationExecutor = class {
1580
- // =====================================
1581
- // Constructor
1582
- // =====================================
1583
- constructor(clientProvider, connectionsService) {
1584
- // =====================================
1585
- // Private Members
1586
- // =====================================
1587
- __publicField(this, "_clientProvider");
1588
- __publicField(this, "_connectionsService");
1589
- __publicField(this, "_databaseReferences");
1590
- __publicField(this, "_connectionReferences");
1591
- this._validateConstructorParams(clientProvider, connectionsService);
1592
- this._clientProvider = clientProvider;
1593
- this._connectionsService = connectionsService;
1594
- }
1595
- // =====================================
1596
- // Public Methods
1597
- // =====================================
1598
- /**
1599
- * Creates a new record in the specified table
1600
- */
1601
- async createRecordAsync(tableName, data) {
1602
- try {
1603
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1604
- const requestUrl = await this._buildTableUrl(tableName, connectionReference);
1605
- const result = await dataClient.createDataAsync(requestUrl, connectionReference.apiId, tableName, data, { operationName: ConnectorOperationName.CreateRecord });
1606
- return result;
1607
- } catch (error) {
1608
- return createErrorResponse(error, DataOperationErrorMessages.CreateFailed);
1609
- }
1610
- }
1611
- /**
1612
- * Updates an existing record in the specified table
1613
- */
1614
- async updateRecordAsync(tableName, id, data) {
1615
- try {
1616
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1617
- const requestUrl = await this._buildTableUrl(tableName, connectionReference, `/${id}`);
1618
- const result = await dataClient.updateDataAsync(requestUrl, connectionReference.apiId, tableName, data, { operationName: ConnectorOperationName.UpdateRecord });
1619
- return result;
1620
- } catch (error) {
1621
- return createErrorResponse(error, DataOperationErrorMessages.UpdateFailed);
1622
- }
1623
- }
1624
- /**
1625
- * Deletes a record from the specified table
1626
- */
1627
- async deleteRecordAsync(tableName, id) {
1628
- try {
1629
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1630
- const requestUrl = await this._buildTableUrl(tableName, connectionReference, `/${id}`);
1631
- const result = await dataClient.deleteDataAsync(requestUrl, connectionReference.apiId, tableName, { operationName: ConnectorOperationName.DeleteRecord });
1632
- return result;
1633
- } catch (error) {
1634
- return createErrorResponse(error, DataOperationErrorMessages.DeleteFailed);
1635
- }
1636
- }
1637
- /**
1638
- * Retrieves a single record from the specified table
1639
- */
1640
- async retrieveRecordAsync(tableName, id, options) {
1641
- try {
1642
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1643
- const requestUrl = await this._buildTableUrl(tableName, connectionReference, `/${id}${convertOptionsToQueryString(options)}`);
1644
- const result = await dataClient.retrieveDataAsync(
1645
- requestUrl,
1646
- connectionReference.apiId,
1647
- tableName,
1648
- HttpMethod.GET,
1649
- void 0,
1650
- // body
1651
- { operationName: ConnectorOperationName.RetrieveRecord }
1652
- );
1653
- return result;
1654
- } catch (error) {
1655
- return createErrorResponse(error, DataOperationErrorMessages.RetrieveFailed);
1656
- }
1657
- }
1658
- /**
1659
- * Retrieves multiple records from the specified table
1660
- */
1661
- async retrieveMultipleRecordsAsync(tableName, options) {
1662
- try {
1663
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1664
- const requestUrl = await this._buildTableUrl(tableName, connectionReference, convertOptionsToQueryString(options), false);
1665
- const result = await dataClient.retrieveDataAsync(
1666
- requestUrl,
1667
- connectionReference.apiId,
1668
- tableName,
1669
- HttpMethod.GET,
1670
- void 0,
1671
- // body
1672
- { operationName: ConnectorOperationName.RetrieveMultipleRecords }
1673
- );
1674
- return result;
1675
- } catch (error) {
1676
- return createErrorResponse(error, DataOperationErrorMessages.RetrieveMultipleFailed);
1677
- }
1678
- }
1679
- /**
1680
- * Executes a custom operation on the data source
1681
- */
1682
- async executeAsync(operation) {
1683
- try {
1684
- if (!operation?.connectorOperation) {
1685
- throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingConnectorOperation}`);
1686
- }
1687
- const tableName = operation.connectorOperation.tableName;
1688
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1689
- const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1690
- const config = await this._getOperationConfig(operation, connectionReference, tableName);
1691
- const requestUrl = await this._buildOperationUrl(operation, config);
1692
- const bodyParam = await this._buildOperationBody(operation, tableName);
1693
- const headers = await this._buildOperationHeader(operation, tableName);
1694
- const httpMethod = this._getHttpMethod(requestUrl, dataSourceInfo, operation.connectorOperation.operationName);
1695
- const responseInfo = dataSourceInfo.apis[operation.connectorOperation.operationName]?.responseInfo;
1696
- const result = await dataClient.retrieveDataAsync(requestUrl, config.apiId, tableName, httpMethod, headers, bodyParam, {
1697
- isExecuteAsync: true,
1698
- // Use the connector operation name for telemetry, may be a better idea to use executeAsync
1699
- // here and just log the connector operation name in the custom dimensions leaving comment for PR.
1700
- operationName: `connectorDataOperation.${operation.connectorOperation.operationName}`,
1701
- responseInfo
1702
- });
1703
- return result;
1704
- } catch (error) {
1705
- return createErrorResponse(error, DataOperationErrorMessages.ExecuteFailed);
1706
- }
1707
- }
1708
- // =====================================
1709
- // Private Methods
1710
- // =====================================
1711
- /**
1712
- * Determines the appropriate HTTP method for a request
1713
- * @param requestUrl - The URL for the request
1714
- * @param dataSourceInfo - The data source information
1715
- * @param operation - The operation name
1716
- * @returns The HTTP method to use
1717
- */
1718
- _getHttpMethod(requestUrl, dataSourceInfo, operation) {
1719
- const isSqlStoredProcedure = requestUrl.indexOf("apim/sql") > -1;
1720
- if (isSqlStoredProcedure) {
1721
- return HttpMethod.POST;
1722
- }
1723
- const method = dataSourceInfo.apis[operation]?.method;
1724
- if (method) {
1725
- return method;
1726
- }
1727
- return HttpMethod.GET;
1728
- }
1729
- /**
1730
- * Builds the operation body parameters
1731
- */
1732
- async _buildOperationBody(operation, tableName) {
1733
- const operationName = operation?.connectorOperation?.operationName;
1734
- if (operationName) {
1735
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1736
- const hasBodyParameter = dataSourceInfo?.apis?.[operationName]?.parameters?.some((param) => param.in === "body");
1737
- if (hasBodyParameter) {
1738
- return await this._buildOperationBodyParam(operation, tableName);
1739
- }
1740
- }
1741
- return void 0;
1742
- }
1743
- /**
1744
- * Builds operation body parameters from the operation and data source info
1745
- */
1746
- async _buildOperationBodyParam(operation, tableName) {
1747
- const operationName = operation.connectorOperation?.operationName;
1748
- if (!operationName) {
1749
- return "{}";
1750
- }
1751
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1752
- const apiParams = dataSourceInfo?.apis?.[operationName]?.parameters || [];
1753
- const rawParams = operation.connectorOperation?.parameters || [];
1754
- if (typeof rawParams !== "object" || rawParams === null) {
1755
- return "{}";
1756
- }
1757
- const bodyParam = apiParams.find((param) => param.in === "body");
1758
- if (bodyParam) {
1759
- const value = rawParams[bodyParam.name];
1760
- if (value !== void 0 && value !== null) {
1761
- return JSON.stringify(value);
1762
- }
1763
- }
1764
- return "{}";
1765
- }
1766
- /**
1767
- * Builds the operation header for a given data operation if required.
1768
- *
1769
- * @template TRequest - The type of the request payload for the data operation.
1770
- * @param dataOperationRequest - The data operation containing details about the connector operation.
1771
- * @param tableName - The name of the table associated with the data operation.
1772
- * @returns A promise that resolves to the operation header as a string if a header parameter is required,
1773
- * or `undefined` if no header parameter is needed.
1774
- */
1775
- async _buildOperationHeader(dataOperationRequest, tableName) {
1776
- const operationName = dataOperationRequest.connectorOperation?.operationName;
1777
- if (operationName) {
1778
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1779
- const hasHeaderParameter = dataSourceInfo?.apis?.[operationName]?.parameters?.some((param) => param.in === "header");
1780
- if (hasHeaderParameter) {
1781
- return await this._buildOperationHeaderParam(dataOperationRequest, tableName);
1782
- }
1783
- }
1784
- return void 0;
1785
- }
1786
- /**
1787
- * Builds the operation header parameters as a JSON string for a given data operation.
1788
- *
1789
- * @template TRequest - The type of the request object for the data operation.
1790
- * @param dataOperationRequest - The data operation containing connector operation details and parameters.
1791
- * @param tableName - The name of the table associated with the data operation.
1792
- * @returns A promise that resolves to a JSON string representing the header parameters,
1793
- * or `undefined` if no `header` parameters are available.
1794
- */
1795
- async _buildOperationHeaderParam(dataOperationRequest, tableName) {
1796
- const operationName = dataOperationRequest.connectorOperation?.operationName;
1797
- if (!operationName) {
1798
- return {};
1799
- }
1800
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1801
- const apiParamSpec = dataSourceInfo?.apis?.[operationName]?.parameters || [];
1802
- const inputParams = dataOperationRequest.connectorOperation?.parameters;
1803
- const headers = {};
1804
- if (!inputParams) {
1805
- return void 0;
1806
- }
1807
- if (typeof inputParams === "string") {
1808
- if (apiParamSpec.length === 1 && apiParamSpec[0].in === "header") {
1809
- headers[apiParamSpec[0].name] = inputParams;
1810
- }
1811
- }
1812
- if (typeof inputParams === "object" && !Array.isArray(inputParams)) {
1813
- apiParamSpec.forEach((param) => {
1814
- if (param.in === "header" && param.name in inputParams) {
1815
- headers[param.name] = inputParams[param.name];
1816
- }
1817
- });
1818
- }
1819
- if (Array.isArray(inputParams)) {
1820
- apiParamSpec.forEach((param, index) => {
1821
- if (param.in === "header" && inputParams[index] !== void 0) {
1822
- headers[param.name] = inputParams[index];
1823
- }
1824
- });
1825
- }
1826
- return headers;
1827
- }
1828
- /**
1829
- * Constructs the request URL for table operations
1830
- * @param tableName - The name of the table
1831
- * @param connectionReference - The connection reference
1832
- * @param options - Optional URL parameters
1833
- * @param encodeOptions - Whether to encode the options
1834
- * @returns The constructed URL
1835
- */
1836
- async _buildTableUrl(tableName, connectionReference, options = "", encodeOptions = true) {
1837
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1838
- const isSharedSql = (connectionReference.apiId ?? "").indexOf("shared_sql") > -1;
1839
- const isSharePoint = (connectionReference.apiId ?? "").indexOf("shared_sharepointonline") > -1;
1840
- const urlBuilder = {
1841
- runtimeUrl: connectionReference.runtimeUrl ?? "",
1842
- connectionName: connectionReference.connectionName ?? "",
1843
- datasetName: connectionReference.datasetName ? isSharedSql ? connectionReference.datasetNameOverride : isSharePoint ? encodeURIComponent(encodeURIComponent(connectionReference.datasetName)) : encodeURIComponent(connectionReference.datasetName) : "",
1844
- tableId: isSharedSql ? encodeURIComponent(encodeURIComponent(dataSourceInfo.tableId)) : dataSourceInfo.tableId,
1845
- version: dataSourceInfo.version,
1846
- isSharedSql
1847
- };
1848
- return this._constructUrl(urlBuilder, options, encodeOptions);
1849
- }
1850
- /**
1851
- * Builds the operation URL
1852
- */
1853
- async _buildOperationUrl(operation, config) {
1854
- const operationName = operation.connectorOperation?.operationName;
1855
- if (!operationName) {
1856
- throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: ${DataOperationErrorMessages.MissingOperationName}`);
1857
- }
1858
- const dataSourceInfo = await this._connectionsService.getDataSource(config.tableName);
1859
- const isSharedSql = (config.apiId ?? "").indexOf("shared_sql") > -1;
1860
- const path = dataSourceInfo.apis[operationName].path;
1861
- if (isSharedSql) {
1862
- return this._buildSharedSqlOperationUrl(config, path);
1863
- }
1864
- return this._buildStandardOperationUrl(operation, config, operationName, path);
1865
- }
1866
- /**
1867
- * Gets the connection references
1868
- */
1869
- async _getConnectionReferencesAsync() {
1870
- if (this._connectionReferences) {
1871
- return this._connectionReferences;
1872
- }
1873
- const metadataClient = await this._getMetadataClient();
1874
- const response = await metadataClient.getAppConnectionConfigsAsync();
1875
- this._connectionReferences = response.data;
1876
- return this._connectionReferences;
1877
- }
1878
- /**
1879
- * Gets the database references
1880
- */
1881
- async _getDatabaseReferencesAsync() {
1882
- if (this._databaseReferences) {
1883
- return this._databaseReferences;
1884
- }
1885
- const metadataClient = await this._getMetadataClient();
1886
- const response = await metadataClient.getAppDataSourceConfigsAsync();
1887
- this._databaseReferences = response.data;
1888
- return this._databaseReferences;
1889
- }
1890
- /**
1891
- * Gets the metadata client instance
1892
- */
1893
- async _getMetadataClient() {
1894
- const metadataClient = await this._clientProvider.getMetadataClientAsync();
1895
- if (!metadataClient) {
1896
- throw new PowerDataRuntimeError(ErrorCodes.MetadataClientNotAvailable);
1897
- }
1898
- return metadataClient;
1899
- }
1900
- /**
1901
- * Gets the connection reference for a table
1902
- */
1903
- _getConnectionReference(tableName) {
1904
- const connectionReference = this._connectionReferences?.[tableName];
1905
- if (!connectionReference) {
1906
- throw new PowerDataRuntimeError(ErrorCodes.ConnectionReferenceNotFound, tableName);
1907
- }
1908
- return connectionReference;
1909
- }
1910
- /**
1911
- * Gets both the data client and connection reference
1912
- */
1913
- async _getClientsAndConnection(tableName) {
1914
- await this._getReferences();
1915
- const dataClient = await this._clientProvider.getDataClientAsync();
1916
- if (!dataClient) {
1917
- throw new PowerDataRuntimeError(ErrorCodes.DataClientNotAvailable);
1918
- }
1919
- const connectionReference = this._getConnectionReference(tableName);
1920
- return { dataClient, connectionReference };
1921
- }
1922
- /**
1923
- * Builds the URL for shared SQL operations
1924
- */
1925
- _buildSharedSqlOperationUrl(config, path) {
1926
- const version = config.version ? `/${config.version}/` : "/";
1927
- return `${config.runtimeUrl}/${config.connectionName}${version}datasets/${config.datasetName}/procedures${path}`;
1928
- }
1929
- /**
1930
- * Builds the URL for standard operations
1931
- * Assumptions / Invariants:
1932
- * - The connector always defines a required path parameter for the connection id named 'connectionId'.
1933
- * - When a dataset is applicable, the parameter name is 'dataset'.
1934
- * - When a table is applicable, the parameter name is 'tableName'.
1935
- * - A lone string parameter maps to the first remaining (non-synthetic) required API parameter.
1936
- * - Array parameters map positionally to the remaining API parameters after filtering.
1937
- * - Object parameters map by (case-insensitive, hyphen/underscore agnostic) key.
1938
- * @param operation - The data operation containing connector operation details from runtime
1939
- * @param config - The connector operation configuration
1940
- * @param operationName - The name of the operation to be performed
1941
- * @param path - The path template for the operation
1942
- */
1943
- async _buildStandardOperationUrl(operation, config, operationName, path) {
1944
- const dataSourceInfo = await this._connectionsService.getDataSource(config.tableName);
1945
- let apiParams = dataSourceInfo.apis[operationName]?.parameters || [];
1946
- if (apiParams.length > 0) {
1947
- apiParams = apiParams.filter((param) => param.name !== "connectionId" && param.name !== "dataset" && param.name !== "tableName");
1948
- }
1949
- const operationParams = operation.connectorOperation?.parameters;
1950
- const rawParamValues = {
1951
- connectionId: config.connectionName,
1952
- dataset: (
1953
- // The dataset name needs to be double encoded for sharepoint, once here and then once in the HTTP pipeline
1954
- // CRUD operations already handle this, so we need to do the same here
1955
- config.apiId.indexOf("shared_sharepointonline") !== -1 && config.datasetName ? encodeURIComponent(config.datasetName) : config.datasetName
1956
- ),
1957
- tableName: config.tableName
1958
- };
1959
- if (operationParams !== void 0) {
1960
- if (typeof operationParams === "string") {
1961
- if (apiParams.length > 0) {
1962
- const requiredParams = apiParams.filter((param) => param.required);
1963
- rawParamValues[requiredParams?.[0]?.name ?? apiParams[0].name] = operationParams;
1964
- }
1965
- } else if (typeof operationParams === "object" && !Array.isArray(operationParams)) {
1966
- apiParams.forEach((param) => {
1967
- if (operationParams) {
1968
- const value = this._getNormalizedParamValue(operationParams, param.name);
1969
- if (value !== void 0) {
1970
- rawParamValues[param.name] = value;
1971
- }
1972
- }
1973
- });
1974
- } else if (Array.isArray(operationParams)) {
1975
- apiParams.forEach((param, index) => {
1976
- rawParamValues[param.name] = operationParams[index];
1977
- });
1978
- }
1979
- }
1980
- const { processedPath, queryParams } = this._processParameters(
1981
- // deliberately pass the unfiltered list to _processParameters so path placeholders still see synthetic params.
1982
- dataSourceInfo.apis[operationName]?.parameters || [],
1983
- rawParamValues,
1984
- path
1985
- );
1986
- const separator = queryParams ? processedPath.includes("?") ? "&" : "?" : "";
1987
- return `${config.runtimeUrl}${processedPath}${separator}${queryParams}`;
1988
- }
1989
- /**
1990
- * Normalizes the parameter name by replacing hyphens with underscores and performs case-insensitive matching
1991
- */
1992
- _getNormalizedParamValue(obj, paramName) {
1993
- const normalizedParamName = paramName.replace(/-/g, "_").toLowerCase();
1994
- const foundKey = Object.keys(obj).find((key) => key.replace(/-/g, "_").toLowerCase() === normalizedParamName);
1995
- return foundKey !== void 0 ? obj[foundKey] : void 0;
1996
- }
1997
- /**
1998
- * Processes operation parameters into path and query parameters
1999
- * @param apiParams - The API parameter specifications from the data source info
2000
- * @param rawParamValues - The raw parameter values provided in the operation at runtime
2001
- * @param path - The initial path template
2002
- * @returns An object containing the processed path and query parameters
2003
- */
2004
- _processParameters(apiParams, rawParamValues, path) {
2005
- const usedParams = /* @__PURE__ */ new Set();
2006
- let processedPath = path;
2007
- const queryParams = [];
2008
- apiParams.forEach((param, index) => {
2009
- const paramValue = rawParamValues[param.name];
2010
- if (paramValue === void 0) {
2011
- return;
2012
- }
2013
- if (param.in === "path") {
2014
- const placeholder = `{${param.name}}`;
2015
- if (processedPath.includes(placeholder)) {
2016
- processedPath = processedPath.replace(placeholder, encodeURIComponent(String(paramValue)));
2017
- usedParams.add(param.name);
2018
- }
2019
- } else if (param.in === "query") {
2020
- queryParams.push(`${encodeURIComponent(param.name)}=${encodeURIComponent(String(paramValue))}`);
2021
- usedParams.add(param.name);
2022
- }
2023
- });
2024
- return {
2025
- processedPath,
2026
- queryParams: queryParams.join("&")
2027
- };
2028
- }
2029
- /**
2030
- * Gets the operation configuration
2031
- */
2032
- async _getOperationConfig(operation, connectionReference, tableName) {
2033
- if (!operation.connectorOperation) {
2034
- throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingConnectorOperation}`);
2035
- }
2036
- const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
2037
- const config = {
2038
- tableName,
2039
- apiId: connectionReference.apiId ?? "",
2040
- runtimeUrl: connectionReference.runtimeUrl ?? "",
2041
- connectionName: connectionReference.connectionName ?? "",
2042
- datasetName: connectionReference.datasetName ?? "",
2043
- tableId: dataSourceInfo.tableId,
2044
- version: dataSourceInfo.version
2045
- };
2046
- return config;
2047
- }
2048
- /**
2049
- * Initializes the clients
2050
- */
2051
- async _getReferences() {
2052
- await this._getConnectionReferencesAsync();
2053
- await this._getDatabaseReferencesAsync();
2054
- }
2055
- /**
2056
- * Validates constructor parameters
2057
- */
2058
- _validateConstructorParams(clientProvider, connectionsService) {
2059
- if (!clientProvider) {
2060
- throw new PowerDataRuntimeError(ErrorCodes.ClientProviderNotAvailable);
2061
- }
2062
- if (!connectionsService) {
2063
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceServiceNotAvailable);
2064
- }
2065
- }
2066
- /**
2067
- * Constructs the final URL
2068
- */
2069
- _constructUrl(urlBuilder, options = "", encodeOptions = true) {
2070
- const apiVersion = urlBuilder.version ? `/${urlBuilder.version}/` : "/";
2071
- const encodedOptions = encodeOptions && options ? options.charAt(0) + encodeURIComponent(options.slice(1)) : options;
2072
- if (urlBuilder.datasetName) {
2073
- return `${urlBuilder.runtimeUrl}/${urlBuilder.connectionName}${apiVersion}datasets/${urlBuilder.datasetName}/tables/${urlBuilder.tableId}/items${encodedOptions}`;
2074
- }
2075
- return `${urlBuilder.runtimeUrl}/${urlBuilder.connectionName}/tables/${urlBuilder.tableId}/items${encodedOptions}`;
2076
- }
2077
- };
2078
-
2079
- // node_modules/@microsoft/power-apps/lib/internal/data/core/metadata/runtimeDataSourceService.js
2080
- var DataSourceServiceError;
2081
- /* @__PURE__ */ (function(DataSourceServiceError2) {
2082
- })(DataSourceServiceError || (DataSourceServiceError = {}));
2083
- var RuntimeDataSourceService = class {
2084
- /**
2085
- * Creates a new instance of RuntimeDataSourceService
2086
- */
2087
- constructor(_powerDataSourcesInfoProvider) {
2088
- __publicField(this, "_powerDataSourcesInfoProvider");
2089
- /**
2090
- * Data source information
2091
- */
2092
- __publicField(this, "_dataSourcesInfo");
2093
- /**
2094
- * Indicates whether the service has been initialized
2095
- */
2096
- __publicField(this, "_isInitialized");
2097
- this._powerDataSourcesInfoProvider = _powerDataSourcesInfoProvider;
2098
- this._dataSourcesInfo = {};
2099
- this._isInitialized = false;
2100
- }
2101
- /**
2102
- * Initializes the service by loading user data sources
2103
- * @throws PowerDataRuntimeError if initialization fails
2104
- */
2105
- async initialize() {
2106
- try {
2107
- const userDataSources = await this._getUserDataSources();
2108
- this._dataSourcesInfo = {};
2109
- Object.keys(userDataSources).forEach((key) => {
2110
- this._dataSourcesInfo[key] = userDataSources[key];
2111
- });
2112
- this._isInitialized = true;
2113
- } catch (error) {
2114
- throw new PowerDataRuntimeError(ErrorCodes.InitializationError, getErrorMessage(error));
2115
- }
2116
- }
2117
- /**
2118
- * Gets all user data sources
2119
- * @returns Array of data source information
2120
- * @throws PowerDataRuntimeError if service is not initialized
2121
- */
2122
- async getUserDataSources() {
2123
- await this._ensureInitialized();
2124
- return this._dataSourcesInfo;
2125
- }
2126
- /**
2127
- * Gets information for a specific data source
2128
- * @param dataSource - The ID of the data source
2129
- * @returns Data source information
2130
- * @throws PowerDataRuntimeError if data source is not found or service is not initialized
2131
- */
2132
- async getDataSource(dataSource) {
2133
- await this._ensureInitialized();
2134
- const dataSourceInfo = this._dataSourcesInfo[dataSource];
2135
- if (!dataSourceInfo) {
2136
- const errorMessage = `Unable to find data source: ${dataSource} in data sources info.`;
2137
- throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, errorMessage);
2138
- }
2139
- return dataSourceInfo;
2140
- }
2141
- /**
2142
- * Checks if a data source exists
2143
- * @param dataSourceId - The ID of the data source to check
2144
- * @returns True if the data source exists, false otherwise
2145
- * @throws PowerDataRuntimeError if service is not initialized
2146
- */
2147
- async hasDataSource(dataSource) {
2148
- await this._ensureInitialized();
2149
- return dataSource in this._dataSourcesInfo;
2150
- }
2151
- /**
2152
- * Ensures the service is initialized
2153
- * @throws PowerDataRuntimeError if service is not initialized
2154
- */
2155
- async _ensureInitialized() {
2156
- if (!this._isInitialized) {
2157
- await this.initialize();
2158
- }
2159
- }
2160
- /**
2161
- * Gets user data sources from the provided data source schemas
2162
- * @returns Promise resolving to array of data source information
2163
- */
2164
- async _getUserDataSources() {
2165
- const dataSourcesInfo = await this._powerDataSourcesInfoProvider.getDataSourcesInfo();
2166
- return Promise.resolve(dataSourcesInfo);
2167
- }
2168
- };
2169
-
2170
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/powerDataRuntime.js
2171
- var PowerDataRuntime = class {
2172
- /**
2173
- * Creates a new instance of PowerDataRuntime
2174
- * @param params - Initialization parameters
2175
- * @throws DataRuntimeError if initialization fails
2176
- */
2177
- constructor(params) {
2178
- __publicField(this, "_clientProvider");
2179
- __publicField(this, "_dataSourceService");
2180
- __publicField(this, "_dataOperations");
2181
- __publicField(this, "_metadataOperations");
2182
- __publicField(this, "_isInitialized");
2183
- try {
2184
- Log.createInstance(params.powerOperationExecutor);
2185
- this._clientProvider = new RuntimeClientProvider(params.powerOperationExecutor);
2186
- this._dataSourceService = new RuntimeDataSourceService(params.powerDataSourcesInfoProvider);
2187
- this._isInitialized = false;
2188
- this._initialize();
2189
- } catch (error) {
2190
- if (error instanceof Error) {
2191
- Log.trackException(error);
2192
- }
2193
- throw error;
2194
- }
2195
- }
2196
- /**
2197
- * Gets the Data operations interface
2198
- * @throws PowerDataRuntimeError if operations are not initialized
2199
- */
2200
- get Data() {
2201
- this._ensureInitialized();
2202
- if (!this._dataOperations) {
2203
- this._dataOperations = this._createDataOperations();
2204
- }
2205
- return this._dataOperations;
2206
- }
2207
- /**
2208
- * Gets the Metadata operations interface
2209
- * @throws PowerDataRuntimeError if operations are not initialized
2210
- */
2211
- get Metadata() {
2212
- this._ensureInitialized();
2213
- if (!this._metadataOperations) {
2214
- this._metadataOperations = this._createMetadataOperations();
2215
- }
2216
- return this._metadataOperations;
2217
- }
2218
- /**
2219
- * Ensures the PowerDataRuntime is initialized
2220
- * @throws PowerDataRuntimeError if not initialized
2221
- */
2222
- _ensureInitialized() {
2223
- if (!this._isInitialized) {
2224
- throw new PowerDataRuntimeError(ErrorCodes.OperationsNotInitialized);
2225
- }
2226
- }
2227
- /**
2228
- * Initializes the PowerDataRuntime components
2229
- * @throws PowerDataRuntimeError if initialization fails
2230
- */
2231
- _initialize() {
2232
- try {
2233
- this._dataOperations = this._createDataOperations();
2234
- this._metadataOperations = this._createMetadataOperations();
2235
- this._isInitialized = true;
2236
- } catch (error) {
2237
- throw new PowerDataRuntimeError(ErrorCodes.InitializationFailed, getErrorMessage(error));
2238
- }
2239
- }
2240
- /**
2241
- * Creates a new instance of DataOperations
2242
- */
2243
- _createDataOperations() {
2244
- const dataverseOperation = new DataverseDataOperationExecutor(this._clientProvider);
2245
- const connectorOperation = new ConnectorDataOperationExecutor(this._clientProvider, this._dataSourceService);
2246
- return new DefaultDataOperationOrchestrator(dataverseOperation, connectorOperation, this._dataSourceService);
2247
- }
2248
- /**
2249
- * Creates a new instance of MetadataOperations
2250
- */
2251
- _createMetadataOperations() {
2252
- return new RuntimeMetadataOperations(this._clientProvider);
2253
- }
2254
- };
2255
-
2256
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/powerDataRuntimeInstance.js
2257
- var powerDataRuntimeInstance;
2258
- function getPowerDataRuntime(powerDataSourcesInfoProvider, powerOperationExecutor) {
2259
- if (!powerDataRuntimeInstance) {
2260
- powerDataRuntimeInstance = new PowerDataRuntime({
2261
- powerDataSourcesInfoProvider,
2262
- powerOperationExecutor
2263
- });
2264
- }
2265
- return powerDataRuntimeInstance;
2266
- }
2267
-
2268
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/powerDataSourcesInfoProvider.js
2269
- var _PowerDataSourcesInfoProvider = class _PowerDataSourcesInfoProvider {
2270
- /**
2271
- * Private constructor to enforce the singleton pattern.
2272
- * @param dataSourcesInfo The data sources information to initialize the provider with.
2273
- */
2274
- constructor(dataSourcesInfo) {
2275
- __publicField(this, "dataSourcesInfo");
2276
- this.dataSourcesInfo = dataSourcesInfo;
2277
- }
2278
- /**
2279
- * Retrieves the singleton instance of PowerDataSourcesInfoProvider.
2280
- * If the instance does not exist, it initializes it with the provided data sources info.
2281
- *
2282
- * @param dataSourcesInfo Optional parameter to initialize the instance if it doesn't exist.
2283
- * @returns The singleton instance of PowerDataSourcesInfoProvider.
2284
- * @throws Error if the instance is not initialized and no dataSourcesInfo is provided.
2285
- */
2286
- static getInstance(dataSourcesInfo) {
2287
- if (!this.instance) {
2288
- if (!dataSourcesInfo) {
2289
- throw new PowerDataRuntimeError(ErrorCodes.DataSourcesInfoNotFound);
2290
- }
2291
- this.instance = new _PowerDataSourcesInfoProvider(dataSourcesInfo);
2292
- }
2293
- return this.instance;
2294
- }
2295
- /**
2296
- * Retrieves the data sources information.
2297
- *
2298
- * @returns A promise resolving to the data sources information.
2299
- */
2300
- async getDataSourcesInfo() {
2301
- return this.dataSourcesInfo;
2302
- }
2303
- };
2304
- __publicField(_PowerDataSourcesInfoProvider, "instance", null);
2305
- var PowerDataSourcesInfoProvider = _PowerDataSourcesInfoProvider;
2306
- var powerDataSourcesInfoProvider_default = PowerDataSourcesInfoProvider;
2307
-
2308
- // node_modules/@microsoft/power-apps/lib/internal/plugins/DefaultPowerAppsBridge.js
2309
- var DefaultPowerAppsBridge = class {
2310
- constructor() {
2311
- __publicField(this, "_antiCSRFToken");
2312
- __publicField(this, "_callbacks", {});
2313
- __publicField(this, "_currentCallbackId", 0);
2314
- __publicField(this, "_instanceId", Date.now().toString());
2315
- __publicField(this, "_messageChannel", new window.MessageChannel());
2316
- __publicField(this, "_postMessageQueue", []);
2317
- __publicField(this, "_postMessageSource");
2318
- __publicField(this, "_handleMessageEvent", (messageEvent) => {
2319
- const message = messageEvent.data;
2320
- if (message && typeof message.isPluginCall === "boolean") {
2321
- if (message.isPluginCall) {
2322
- const callbackId = message.callbackId;
2323
- const status = message.status;
2324
- const args = message.args;
2325
- const keepCallback = message.keepCallback;
2326
- try {
2327
- const callback = this._callbacks[callbackId];
2328
- if (keepCallback) {
2329
- if (callback && callback.onUpdate) {
2330
- callback.onUpdate(message.args?.[0]);
2331
- }
2332
- } else {
2333
- if (callback) {
2334
- if (status === 1) {
2335
- callback.resolve(args[0]);
2336
- } else if (status !== 0) {
2337
- callback.reject(args);
2338
- }
2339
- }
2340
- if (!keepCallback) {
2341
- delete this._callbacks[callbackId];
2342
- }
2343
- }
2344
- } catch (error) {
2345
- console.error(error);
2346
- }
2347
- }
2348
- } else if (message && message.messageType === "initCommunication") {
2349
- this._antiCSRFToken = message.antiCSRFToken;
2350
- this._postMessageSource = this._messageChannel.port1;
2351
- if (this._postMessageSource) {
2352
- for (let i = 0; i < this._postMessageQueue.length; i++) {
2353
- this._postMessageQueue[i].antiCSRFToken = this._antiCSRFToken;
2354
- this._postMessageSource.postMessage(this._postMessageQueue[i]);
2355
- }
2356
- }
2357
- }
2358
- });
2359
- }
2360
- async initialize() {
2361
- this._messageChannel.port1.onmessage = this._handleMessageEvent;
2362
- window.parent.postMessage({
2363
- messageType: "initCommunicationWithPort",
2364
- instanceId: this._instanceId
2365
- }, "*", [this._messageChannel.port2]);
2366
- }
2367
- async executePluginAsync(pluginName, pluginAction, params = [], onUpdate) {
2368
- return new Promise((resolve, reject) => {
2369
- const callbackId = this._getCallbackId(pluginName);
2370
- this._callbacks[callbackId] = { resolve, reject, onUpdate };
2371
- this._sendMessage({
2372
- isPluginCall: true,
2373
- callbackId,
2374
- service: pluginName,
2375
- action: pluginAction,
2376
- actionArgs: params,
2377
- antiCSRFToken: this._antiCSRFToken
2378
- });
2379
- });
2380
- }
2381
- _sendMessage(message) {
2382
- if (!this._postMessageSource) {
2383
- this._postMessageQueue.push(message);
2384
- } else {
2385
- this._postMessageSource.postMessage(message);
2386
- }
2387
- }
2388
- _getCallbackId(pluginName) {
2389
- return "instanceId=" + this._instanceId + "_" + pluginName + this._currentCallbackId++;
2390
- }
2391
- };
2392
-
2393
- // node_modules/@microsoft/power-apps/lib/internal/plugins/PluginBridge.js
2394
- var bridgePromise;
2395
- async function executePluginAsync(pluginName, pluginAction, params = [], update) {
2396
- const powerAppsBridge = await getBridge();
2397
- return powerAppsBridge.executePluginAsync(pluginName, pluginAction, params, update);
2398
- }
2399
- async function getBridge() {
2400
- if (!bridgePromise) {
2401
- bridgePromise = new Promise(async (resolve, reject) => {
2402
- try {
2403
- const bridge = window && window.powerAppsBridge ? window.powerAppsBridge : new DefaultPowerAppsBridge();
2404
- await bridge.initialize();
2405
- resolve(bridge);
2406
- } catch (error) {
2407
- reject(error);
2408
- }
2409
- });
2410
- }
2411
- return bridgePromise;
2412
- }
2413
-
2414
- // node_modules/@microsoft/power-apps/lib/internal/data/ConnectionUtils.js
2415
- var connectionsLoaded = false;
2416
- async function loadConnections() {
2417
- if (connectionsLoaded) {
2418
- return;
2419
- }
2420
- connectionsLoaded = true;
2421
- await loadNonCompositeConnectionsAsync();
2422
- await resolveCompositeConnectionsAsync();
2423
- }
2424
- async function loadNonCompositeConnectionsAsync() {
2425
- return executePluginAsync("AppPowerAppsClientPlugin", "loadNonCompositeConnectionsAsync", []);
2426
- }
2427
- async function resolveCompositeConnectionsAsync() {
2428
- return executePluginAsync("AppPowerAppsClientPlugin", "resolveCompositeConnectionsAsync", []);
2429
- }
2430
-
2431
- // node_modules/@microsoft/power-apps/lib/internal/data/OperationExecutor.js
2432
- var loadConnectionsPromise;
2433
- var OperationExecutor = class {
2434
- /**
2435
- * Executes an operation using the plugin.
2436
- * @param operationName The name of the operation.
2437
- * @param action The action to perform.
2438
- * @param params The parameters for the operation.
2439
- * @returns A promise resolving to the operation result.
2440
- */
2441
- async execute(operationName, action, params) {
2442
- try {
2443
- if (!loadConnectionsPromise) {
2444
- loadConnectionsPromise = loadConnections();
2445
- }
2446
- await loadConnectionsPromise;
2447
- const result = await executePluginAsync(operationName, action, params);
2448
- return {
2449
- success: true,
2450
- data: result
2451
- };
2452
- } catch (error) {
2453
- throw error;
2454
- }
2455
- }
2456
- };
2457
-
2458
- // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/getRuntimeContext.js
2459
- var _executor;
2460
- function getExecutor() {
2461
- if (!_executor) {
2462
- _executor = new OperationExecutor();
2463
- }
2464
- return _executor;
2465
- }
2466
- async function getPowerSdkInstance(dataSourcesInfo) {
2467
- const executor = getExecutor();
2468
- const provider = powerDataSourcesInfoProvider_default.getInstance(dataSourcesInfo);
2469
- return getPowerDataRuntime(provider, executor);
2470
- }
2471
-
2472
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/createRecord.js
2473
- async function createRecordAsync(dataSourcesInfo, tableName, record) {
2474
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.createRecordAsync(tableName, record);
2475
- }
2476
-
2477
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/updateRecord.js
2478
- async function updateRecordAsync(dataSourcesInfo, tableName, recordId, changes) {
2479
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.updateRecordAsync(tableName, recordId, changes);
2480
- }
2481
-
2482
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/deleteRecord.js
2483
- async function deleteRecordAsync(dataSourcesInfo, tableName, recordId) {
2484
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.deleteRecordAsync(tableName, recordId);
2485
- }
2486
-
2487
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/retrieveRecord.js
2488
- async function retrieveRecordAsync(dataSourcesInfo, tableName, recordId, options) {
2489
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.retrieveRecordAsync(tableName, recordId, options);
2490
- }
2491
-
2492
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/retrieveMultipleRecords.js
2493
- async function retrieveMultipleRecordsAsync(dataSourcesInfo, tableName, options) {
2494
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.retrieveMultipleRecordsAsync(tableName, options);
2495
- }
2496
-
2497
- // node_modules/@microsoft/power-apps/lib/internal/data/core/api/execute.js
2498
- async function executeAsync(dataSourcesInfo, operation) {
2499
- return await (await getPowerSdkInstance(dataSourcesInfo)).Data.executeAsync(operation);
2500
- }
2501
-
2502
- // node_modules/@microsoft/power-apps/lib/data/powerAppsData.js
2503
- var _dataOperationExecutor;
2504
- function getDataOperationExecutor() {
2505
- return _dataOperationExecutor;
2506
- }
2507
- function getClient(dataSourcesInfo) {
2508
- return {
2509
- createRecordAsync: (tableName, record) => {
2510
- return createRecordAsync(dataSourcesInfo, tableName, record);
2511
- },
2512
- deleteRecordAsync: (tableName, recordId) => {
2513
- return deleteRecordAsync(dataSourcesInfo, tableName, recordId);
2514
- },
2515
- executeAsync: (operation) => {
2516
- return executeAsync(dataSourcesInfo, operation);
2517
- },
2518
- retrieveMultipleRecordsAsync: (tableName, options) => {
2519
- return retrieveMultipleRecordsAsync(dataSourcesInfo, tableName, options);
2520
- },
2521
- retrieveRecordAsync: (tableName, recordId, options) => {
2522
- return retrieveRecordAsync(dataSourcesInfo, tableName, recordId, options);
2523
- },
2524
- updateRecordAsync: (tableName, recordId, changes) => {
2525
- return updateRecordAsync(dataSourcesInfo, tableName, recordId, changes);
2526
- }
2527
- };
2528
- }
2529
- export {
2530
- getClient
2531
- };
1
+ var __defProp = Object.defineProperty;
2
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
+ var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
+
5
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/common/types.js
6
+ var HttpMethod;
7
+ (function(HttpMethod2) {
8
+ HttpMethod2["GET"] = "GET";
9
+ HttpMethod2["POST"] = "POST";
10
+ HttpMethod2["PUT"] = "PUT";
11
+ HttpMethod2["DELETE"] = "DELETE";
12
+ HttpMethod2["PATCH"] = "PATCH";
13
+ })(HttpMethod || (HttpMethod = {}));
14
+ var DataSources;
15
+ (function(DataSources2) {
16
+ DataSources2["Dataverse"] = "Dataverse";
17
+ DataSources2["Connector"] = "Connector";
18
+ })(DataSources || (DataSources = {}));
19
+
20
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/error/codes.js
21
+ var ErrorCodes;
22
+ (function(ErrorCodes2) {
23
+ ErrorCodes2["InitializationFailed"] = "PDR_INIT_FAILED";
24
+ ErrorCodes2["InvalidXrmInfo"] = "INVALID_XRM_INFO";
25
+ ErrorCodes2["OperationsNotInitialized"] = "OPS_NOT_INITIALIZED";
26
+ ErrorCodes2["InvalidOperationExecutor"] = "INVALID_OPERATION_EXECUTOR";
27
+ ErrorCodes2["DataSourceNotFound"] = "CONNECTION_NOT_FOUND";
28
+ ErrorCodes2["DuplicateDataSource"] = "DUPLICATE_DATA_SOURCE";
29
+ ErrorCodes2["InitializationError"] = "RDSS_INIT_ERROR";
30
+ ErrorCodes2["InvalidDataSource"] = "INVALID_DATA_SOURCE";
31
+ ErrorCodes2["DataSourcesInfoNotFound"] = "DATA_SOURCES_INFO_NOT_FOUND";
32
+ ErrorCodes2["DataClientInitFailed"] = "DATA_CLIENT_INIT_FAILED";
33
+ ErrorCodes2["DataClientNotInitialized"] = "DATA_CLIENT_NOT_INITIALIZED";
34
+ ErrorCodes2["MetadataClientInitFailed"] = "METADATA_CLIENT_INIT_FAILED";
35
+ ErrorCodes2["MetadataClientNotInitialized"] = "METADATA_CLIENT_NOT_INITIALIZED";
36
+ ErrorCodes2["ClientProviderNotAvailable"] = "CLIENT_PROVIDER_NOT_AVAILABLE";
37
+ ErrorCodes2["ConnectionReferenceNotFound"] = "CONNECTION_REFERENCE_NOT_FOUND";
38
+ ErrorCodes2["DataClientNotAvailable"] = "DATA_CLIENT_NOT_AVAILABLE";
39
+ ErrorCodes2["DataSourceServiceNotAvailable"] = "DATA_SOURCE_SERVICE_NOT_AVAILABLE";
40
+ ErrorCodes2["MetadataClientNotAvailable"] = "METADATA_CLIENT_NOT_AVAILABLE";
41
+ ErrorCodes2["ConnectionConfigFetchFailed"] = "CONNECTION_CONFIG_FETCH_FAILED";
42
+ ErrorCodes2["DataSourceConfigFetchFailed"] = "DATA_SOURCE_CONFIG_FETCH_FAILED";
43
+ ErrorCodes2["InvalidMetadataResponse"] = "INVALID_METADATA_RESPONSE";
44
+ ErrorCodes2["TokenAcquisitionFailed"] = "TOKEN_ACQUISITION_FAILED";
45
+ })(ErrorCodes || (ErrorCodes = {}));
46
+
47
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/error/messages.js
48
+ var UnknownErrorMessage = "An unknown error occurred";
49
+ var ErrorMessages = {
50
+ // PowerDataRuntime specific errors
51
+ [ErrorCodes.InitializationFailed]: "Failed to initialize PowerDataRuntime",
52
+ [ErrorCodes.InvalidXrmInfo]: "Xrm info is required",
53
+ [ErrorCodes.OperationsNotInitialized]: "PowerDataRuntime is not initialized",
54
+ // RuntimeDataSourceService specific errors
55
+ [ErrorCodes.DataSourceNotFound]: "Data source not found",
56
+ [ErrorCodes.DuplicateDataSource]: "Duplicate data source",
57
+ [ErrorCodes.InitializationError]: "Failed to initialize RuntimeDataSourceService",
58
+ [ErrorCodes.InvalidDataSource]: "Invalid data source",
59
+ // PowerDataSourcesInfoProvider specific errors
60
+ [ErrorCodes.DataSourcesInfoNotFound]: "DataSourcesInfo must be provided to initialize the singleton instance.",
61
+ // DataClientProvider specific errors
62
+ [ErrorCodes.DataClientInitFailed]: "Failed to initialize PowerDataClient",
63
+ [ErrorCodes.DataClientNotInitialized]: "PowerDataClient is not initialized",
64
+ [ErrorCodes.MetadataClientInitFailed]: "Failed to initialize PowerMetadataClient",
65
+ [ErrorCodes.MetadataClientNotInitialized]: "PowerMetadataClient is not initialized",
66
+ // DataOperation specific errors
67
+ [ErrorCodes.ClientProviderNotAvailable]: "Client provider is not available",
68
+ [ErrorCodes.ConnectionReferenceNotFound]: "Connection reference not found",
69
+ [ErrorCodes.DataClientNotAvailable]: "PowerDataClient is not available",
70
+ [ErrorCodes.DataSourceServiceNotAvailable]: "Data source service is not available",
71
+ [ErrorCodes.MetadataClientNotAvailable]: "PowerMetadataClient is not available",
72
+ // MetadataClient specific errors
73
+ [ErrorCodes.ConnectionConfigFetchFailed]: "Failed to fetch connection configurations",
74
+ [ErrorCodes.DataSourceConfigFetchFailed]: "Failed to fetch data source configurations",
75
+ [ErrorCodes.InvalidMetadataResponse]: "Invalid metadata response format",
76
+ // RuntimeDataClient specific errors
77
+ [ErrorCodes.TokenAcquisitionFailed]: "Failed to acquire access token"
78
+ };
79
+ var DataOperationErrorMessages;
80
+ (function(DataOperationErrorMessages2) {
81
+ DataOperationErrorMessages2["CreateFailed"] = "Create operation failure";
82
+ DataOperationErrorMessages2["DeleteFailed"] = "Delete operation failure";
83
+ DataOperationErrorMessages2["ExecuteFailed"] = "Execute operation failure";
84
+ DataOperationErrorMessages2["InvalidOperationParameters"] = "Invalid operation parameters";
85
+ DataOperationErrorMessages2["InvalidRequest"] = "Invalid request";
86
+ DataOperationErrorMessages2["InvalidResponse"] = "Invalid response format";
87
+ DataOperationErrorMessages2["MissingConnectorOperation"] = "Connector operation is required";
88
+ DataOperationErrorMessages2["MissingDataverseRequest"] = "Dataverse request is required";
89
+ DataOperationErrorMessages2["MissingOperationName"] = "Operation name is required";
90
+ DataOperationErrorMessages2["MissingRequestBody"] = "Request body is required";
91
+ DataOperationErrorMessages2["RetrieveFailed"] = "Retrieve operation failure";
92
+ DataOperationErrorMessages2["RetrieveMultipleFailed"] = "Retrieve multiple records operation failure";
93
+ DataOperationErrorMessages2["UpdateFailed"] = "Update operation failure";
94
+ })(DataOperationErrorMessages || (DataOperationErrorMessages = {}));
95
+
96
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/types/index.js
97
+ function isOperationResult(result) {
98
+ return result?.success !== void 0;
99
+ }
100
+
101
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/telemetry/log.js
102
+ var ServiceName = "PublishedAppTelemetry";
103
+ var TelemetryActionNames;
104
+ (function(TelemetryActionNames2) {
105
+ TelemetryActionNames2["trackEvent"] = "trackEvent";
106
+ TelemetryActionNames2["trackException"] = "trackException";
107
+ TelemetryActionNames2["trackMetric"] = "trackMetric";
108
+ TelemetryActionNames2["startScenario"] = "startScenario";
109
+ TelemetryActionNames2["endScenario"] = "endScenario";
110
+ TelemetryActionNames2["setDefaultProperties"] = "setDefaultProperties";
111
+ })(TelemetryActionNames || (TelemetryActionNames = {}));
112
+ var _Log = class _Log {
113
+ constructor(_powerOperationExecutor) {
114
+ __publicField(this, "_powerOperationExecutor");
115
+ this._powerOperationExecutor = _powerOperationExecutor;
116
+ }
117
+ static createInstance(powerOperationExecutor) {
118
+ if (!_Log._instance) {
119
+ _Log._instance = new _Log(powerOperationExecutor);
120
+ } else {
121
+ _Log.trackEvent("TelemetryLogger", {
122
+ message: "Attempted to create an instance when instance is already created."
123
+ });
124
+ }
125
+ return _Log._instance;
126
+ }
127
+ // Since powerDataRuntime can be reset, we need to be able to reset the instance of Log as well.
128
+ static resetInstance() {
129
+ _Log._instance = null;
130
+ }
131
+ static async _sendMessage(actionName, ...args) {
132
+ try {
133
+ const instance = _Log._getInstance();
134
+ const result = await instance._powerOperationExecutor.execute(ServiceName, actionName, args);
135
+ if (!result.success) {
136
+ console.error({
137
+ message: `PowerDataRuntime.TelemetryLogger: Failed to send telemetry message.`,
138
+ error: result.error,
139
+ telemetryArgs: args
140
+ });
141
+ }
142
+ } catch (error) {
143
+ console.error({
144
+ message: `PowerDataRuntime.TelemetryLogger: Failed to send telemetry message.`,
145
+ error,
146
+ telemetryArgs: args
147
+ });
148
+ }
149
+ }
150
+ static trackEvent(eventName, eventData) {
151
+ const serializedData = eventData ? _Log._serializeErrors(eventData) : eventData;
152
+ return _Log._sendMessage(TelemetryActionNames.trackEvent, `PowerDataRuntime.${eventName}`, serializedData);
153
+ }
154
+ static trackException(exception) {
155
+ return _Log._sendMessage(TelemetryActionNames.trackException, exception);
156
+ }
157
+ static trackMetric(metricName, value) {
158
+ return _Log._sendMessage(TelemetryActionNames.trackMetric, `PowerDataRuntime.${metricName}`, value);
159
+ }
160
+ static startScenario(scenarioName) {
161
+ return _Log._sendMessage(TelemetryActionNames.startScenario, `PowerDataRuntime.${scenarioName}`);
162
+ }
163
+ static endScenario(scenarioName) {
164
+ return _Log._sendMessage(TelemetryActionNames.endScenario, `PowerDataRuntime.${scenarioName}`);
165
+ }
166
+ static setDefaultProperties(properties) {
167
+ return _Log._sendMessage(TelemetryActionNames.setDefaultProperties, properties);
168
+ }
169
+ static _getInstance() {
170
+ if (!_Log._instance) {
171
+ throw new Error("PowerDataRuntime.TelemetryLogger: Attempted to log telemetry prior to instantiation.");
172
+ }
173
+ return _Log._instance;
174
+ }
175
+ /**
176
+ * Recursively serializes Error objects in an object to prevent empty object serialization
177
+ * when passed through postMessage's structured clone algorithm.
178
+ * @param obj - The object to process
179
+ * @returns A new object with Error instances replaced by serializable objects
180
+ */
181
+ static _serializeErrors(obj) {
182
+ if (obj === null || obj === void 0) {
183
+ return obj;
184
+ }
185
+ if (obj instanceof Error) {
186
+ return {
187
+ errorMessage: obj.message,
188
+ errorStack: obj.stack,
189
+ errorType: obj.name
190
+ };
191
+ }
192
+ if (Array.isArray(obj)) {
193
+ return obj.map((item) => _Log._serializeErrors(item));
194
+ }
195
+ if (typeof obj === "object" && obj !== null && Object.getPrototypeOf(obj) === Object.prototype) {
196
+ const serialized = {};
197
+ for (const key in obj) {
198
+ if (Object.prototype.hasOwnProperty.call(obj, key)) {
199
+ serialized[key] = _Log._serializeErrors(obj[key]);
200
+ }
201
+ }
202
+ return serialized;
203
+ }
204
+ return obj;
205
+ }
206
+ };
207
+ __publicField(_Log, "_instance", null);
208
+ var Log = _Log;
209
+
210
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/error/types.js
211
+ var PowerDataRuntimeError = class extends Error {
212
+ /**
213
+ * Creates an instance of PowerDataRuntimeError.
214
+ * @param code - The error code associated with the error.
215
+ * @param additionalInfo - Optional additional information to include in the error message.
216
+ * @param messageOverride - Optional override for the default error message.
217
+ */
218
+ constructor(code, additionalInfo, messageOverride) {
219
+ let message = messageOverride || ErrorMessages[code] || UnknownErrorMessage;
220
+ if (additionalInfo) {
221
+ message += `: ${additionalInfo}`;
222
+ }
223
+ super(message);
224
+ __publicField(this, "code");
225
+ this.code = code;
226
+ this.name = "PowerDataRuntimeError";
227
+ Log.trackException(this);
228
+ }
229
+ };
230
+
231
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/error/constants.js
232
+ var HeaderNames;
233
+ (function(HeaderNames2) {
234
+ HeaderNames2["RequestId"] = "x-ms-client-request-id";
235
+ })(HeaderNames || (HeaderNames = {}));
236
+ var DataverseOperationName;
237
+ (function(DataverseOperationName2) {
238
+ DataverseOperationName2["CreateRecord"] = "dataverseDataOperation.createRecordAsync";
239
+ DataverseOperationName2["UpdateRecord"] = "dataverseDataOperation.updateRecordAsync";
240
+ DataverseOperationName2["DeleteRecord"] = "dataverseDataOperation.deleteRecordAsync";
241
+ DataverseOperationName2["RetrieveRecord"] = "dataverseDataOperation.retrieveRecordAsync";
242
+ DataverseOperationName2["RetrieveMultipleRecords"] = "dataverseDataOperation.retrieveMultipleRecordsAsync";
243
+ })(DataverseOperationName || (DataverseOperationName = {}));
244
+ var ConnectorOperationName;
245
+ (function(ConnectorOperationName2) {
246
+ ConnectorOperationName2["CreateRecord"] = "connectorDataOperation.createRecordAsync";
247
+ ConnectorOperationName2["UpdateRecord"] = "connectorDataOperation.updateRecordAsync";
248
+ ConnectorOperationName2["DeleteRecord"] = "connectorDataOperation.deleteRecordAsync";
249
+ ConnectorOperationName2["RetrieveRecord"] = "connectorDataOperation.retrieveRecordAsync";
250
+ ConnectorOperationName2["RetrieveMultipleRecords"] = "connectorDataOperation.retrieveMultipleRecordsAsync";
251
+ })(ConnectorOperationName || (ConnectorOperationName = {}));
252
+
253
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/error/util.js
254
+ function getErrorMessage(error) {
255
+ if (typeof error === "string") {
256
+ return error;
257
+ }
258
+ if (error instanceof Error || error instanceof PowerDataRuntimeError) {
259
+ return error.message || UnknownErrorMessage;
260
+ }
261
+ if (isOperationResult(error)) {
262
+ return error.error?.message || UnknownErrorMessage;
263
+ }
264
+ if (typeof error === "object") {
265
+ return JSON.stringify(error);
266
+ }
267
+ return UnknownErrorMessage;
268
+ }
269
+ function createErrorResponse(error, friendlyMessage) {
270
+ const message = getErrorMessage(error);
271
+ let data;
272
+ if (isOperationResult(error)) {
273
+ data = error.data;
274
+ }
275
+ const errorData = new Error(`${friendlyMessage}: ${message}`);
276
+ if (error instanceof Error) {
277
+ errorData.stack = error.stack;
278
+ }
279
+ return {
280
+ success: false,
281
+ error: errorData,
282
+ data
283
+ };
284
+ }
285
+ function parseHttpPluginError(error) {
286
+ let message = UnknownErrorMessage;
287
+ let response;
288
+ if (Array.isArray(error)) {
289
+ if (Array.isArray(error[0])) {
290
+ message = error[0][0] || UnknownErrorMessage;
291
+ response = error[0][2];
292
+ }
293
+ }
294
+ const status = response?.status;
295
+ const requestId = response?.headers?.[HeaderNames.RequestId];
296
+ return {
297
+ message,
298
+ status,
299
+ requestId
300
+ };
301
+ }
302
+
303
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/data/defaultOperationOrchestrator.js
304
+ var DefaultDataOperationOrchestrator = class {
305
+ // Static identifiers for services and actions
306
+ // Used to identify specific services and actions within the PowerApps environment
307
+ constructor(_dataverseOperation, _connectorOperation, _connectionsService) {
308
+ __publicField(this, "_dataverseOperation");
309
+ __publicField(this, "_connectorOperation");
310
+ __publicField(this, "_connectionsService");
311
+ this._dataverseOperation = _dataverseOperation;
312
+ this._connectorOperation = _connectorOperation;
313
+ this._connectionsService = _connectionsService;
314
+ }
315
+ /**
316
+ * Creates a new record in the specified data source.
317
+ * @param tableName - The name of the table.
318
+ * @param data - The record data to create.
319
+ * @returns A promise that resolves to the operation result.
320
+ * @throws DataOperationError if the operation fails.
321
+ */
322
+ async createRecordAsync(tableName, data) {
323
+ try {
324
+ this._validateParams({ tableName, data });
325
+ const executor = await this._getExecutor(tableName);
326
+ return await executor.createRecordAsync(tableName, data);
327
+ } catch (error) {
328
+ return createErrorResponse(error, "Create record operation failed");
329
+ }
330
+ }
331
+ /**
332
+ * Updates an existing record in the specified data source.
333
+ * @param tableName - The name of the table.
334
+ * @param id - The ID of the record to update.
335
+ * @param data - The updated record data.
336
+ * @returns A promise that resolves to the operation result.
337
+ * @throws DataOperationError if the operation fails.
338
+ */
339
+ async updateRecordAsync(tableName, id, data) {
340
+ try {
341
+ this._validateParams({ tableName, id, data });
342
+ const executor = await this._getExecutor(tableName);
343
+ return await executor.updateRecordAsync(tableName, id, data);
344
+ } catch (error) {
345
+ return createErrorResponse(error, "Update record operation failed");
346
+ }
347
+ }
348
+ /**
349
+ * Deletes a record from the specified data source.
350
+ * @param tableName - The name of the table.
351
+ * @param id - The ID of the record to delete.
352
+ * @returns A promise that resolves to the operation result.
353
+ * @throws DataOperationError if the operation fails.
354
+ */
355
+ async deleteRecordAsync(tableName, id) {
356
+ try {
357
+ this._validateParams({ tableName, id });
358
+ const executor = await this._getExecutor(tableName);
359
+ return await executor.deleteRecordAsync(tableName, id);
360
+ } catch (error) {
361
+ return createErrorResponse(error, "Delete record operation failed");
362
+ }
363
+ }
364
+ /**
365
+ * Retrieves a record from the specified data source.
366
+ * @param tableName - The name of the table.
367
+ * @param id - The ID of the record to retrieve.
368
+ * @param options - Optional operation options.
369
+ * @returns A promise that resolves to the operation result.
370
+ * @throws DataOperationError if the operation fails.
371
+ */
372
+ async retrieveRecordAsync(tableName, id, options) {
373
+ try {
374
+ this._validateParams({ tableName, id });
375
+ const executor = await this._getExecutor(tableName);
376
+ this._validateOptions(options);
377
+ return await executor.retrieveRecordAsync(tableName, id, options);
378
+ } catch (error) {
379
+ return createErrorResponse(error, "Retrieve record operation failed");
380
+ }
381
+ }
382
+ /**
383
+ * Retrieves multiple records from the specified data source.
384
+ * @param tableName - The name of the table.
385
+ * @param options - Optional operation options.
386
+ * @returns A promise that resolves to the operation result.
387
+ * @throws DataOperationError if the operation fails.
388
+ */
389
+ async retrieveMultipleRecordsAsync(tableName, options) {
390
+ try {
391
+ this._validateParams({ tableName });
392
+ const executor = await this._getExecutor(tableName);
393
+ this._validateOptions(options);
394
+ return await executor.retrieveMultipleRecordsAsync(tableName, options);
395
+ } catch (error) {
396
+ return createErrorResponse(error, "Retrieve multiple records operation failed");
397
+ }
398
+ }
399
+ /**
400
+ * Executes a data operation on the specified data source.
401
+ * @param operation - The operation to execute
402
+ * @returns A promise that resolves to the operation result.
403
+ * @throws DataOperationError if the operation fails.
404
+ */
405
+ async executeAsync(operation) {
406
+ try {
407
+ this._validateParams({ operation });
408
+ const executor = await this._getExecutor("", operation.connectorOperation ? DataSources.Connector : DataSources.Dataverse);
409
+ return await executor.executeAsync(operation);
410
+ } catch (error) {
411
+ return createErrorResponse(error, "Execute operation failed");
412
+ }
413
+ }
414
+ /**
415
+ * Retrieves the appropriate executor based on the data source.
416
+ * @param dataSource - The data source to retrieve the executor for.
417
+ * @returns The corresponding executor instance.
418
+ * @throws DataOperationError if the data source is invalid.
419
+ * // TODO: Add Dataverse support
420
+ */
421
+ async _getExecutor(tableName, dataSource) {
422
+ const dataOperationExecutorOverride = getDataOperationExecutor();
423
+ if (dataOperationExecutorOverride) {
424
+ return dataOperationExecutorOverride;
425
+ }
426
+ const dataSourceType = dataSource || (await this._connectionsService.getDataSource(tableName)).dataSourceType;
427
+ switch (dataSourceType) {
428
+ case DataSources.Dataverse:
429
+ return this._dataverseOperation;
430
+ case DataSources.Connector:
431
+ return this._connectorOperation;
432
+ default:
433
+ return this._connectorOperation;
434
+ }
435
+ }
436
+ /**
437
+ * Validates the input parameters for data operations.
438
+ * @param params - The parameters to validate.
439
+ * @throws DataOperationError if validation fails.
440
+ */
441
+ _validateParams(params) {
442
+ for (const [key, value] of Object.entries(params)) {
443
+ if (!value) {
444
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: ${key} is required`);
445
+ }
446
+ }
447
+ }
448
+ /**
449
+ * Validates the operation options.
450
+ * @param options - The operation options to validate.
451
+ * @throws Error if validation fails.
452
+ */
453
+ _validateOptions(options) {
454
+ if (!options) {
455
+ return;
456
+ }
457
+ if (options.maxPageSize && typeof options.maxPageSize !== "number") {
458
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: maxPageSize must be a number`);
459
+ }
460
+ if (options.select) {
461
+ if (!Array.isArray(options.select)) {
462
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: select must be an array of strings`);
463
+ }
464
+ if (options.select.some((s) => typeof s !== "string" || s.trim() === "")) {
465
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: select must contain only non-empty strings`);
466
+ }
467
+ }
468
+ if (options.filter && typeof options.filter !== "string") {
469
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: filter must be a string`);
470
+ }
471
+ if (options.orderBy) {
472
+ if (!Array.isArray(options.orderBy)) {
473
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: orderBy must be an array of strings`);
474
+ }
475
+ if (options.orderBy.some((s) => typeof s !== "string" || s.trim() === "")) {
476
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: orderBy must contain only non-empty strings`);
477
+ }
478
+ }
479
+ if (options.top && typeof options.top !== "number") {
480
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: top must be a number`);
481
+ }
482
+ if (options.skip && typeof options.skip !== "number") {
483
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: skip must be a number`);
484
+ }
485
+ if (options.count && typeof options.count !== "boolean") {
486
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: count must be a boolean`);
487
+ }
488
+ }
489
+ };
490
+
491
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/metadata/runtimeMetadataOperations.js
492
+ var RuntimeMetadataOperations = class {
493
+ // Static identifiers for services and actions
494
+ // Used to identify specific services and actions within the PowerApps environment
495
+ constructor(_clientProvider) {
496
+ __publicField(this, "_clientProvider");
497
+ this._clientProvider = _clientProvider;
498
+ }
499
+ async getConnections(context) {
500
+ const client = await this._clientProvider.getMetadataClientAsync();
501
+ const response = await client.getAppConnectionConfigsAsync(context);
502
+ return {
503
+ success: response.success,
504
+ data: response.data ? [response.data] : [],
505
+ error: response.error
506
+ };
507
+ }
508
+ async getConnectionApis(_connectionId, context) {
509
+ const client = await this._clientProvider.getMetadataClientAsync();
510
+ const response = await client.getAppDataSourceConfigsAsync(context);
511
+ return {
512
+ success: response.success,
513
+ data: response.data ? [response.data] : [],
514
+ error: response.error
515
+ };
516
+ }
517
+ };
518
+
519
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/common/utils.js
520
+ function arrayBufferToBase64(buffer) {
521
+ return window.btoa(convertArrayBufferToString(buffer));
522
+ }
523
+ function convertArrayBufferToString(buf) {
524
+ if (buf.byteLength <= 65535) {
525
+ return String.fromCharCode(...new Uint8Array(buf));
526
+ }
527
+ let binary = "";
528
+ for (let i = 0, bytes = new Uint8Array(buf); i < bytes.byteLength; i++) {
529
+ binary += String.fromCharCode(bytes[i]);
530
+ }
531
+ return binary;
532
+ }
533
+ function strictEncode(str) {
534
+ return encodeURIComponent(str).replace(/\(/g, "%28").replace(/\)/g, "%29");
535
+ }
536
+ function extractDataverseUrlParts(url) {
537
+ const baseUrlMatch = url.match(/^(https?:\/\/[^/]+\/api\/data\/v9\.0)/);
538
+ const baseUrl = baseUrlMatch ? baseUrlMatch[1] : "";
539
+ const pathMatch = url.match(/\/api\/data\/v9\.0\/(.+)$/);
540
+ const encodedPath = pathMatch ? strictEncode(pathMatch[1]) : "";
541
+ return { baseUrl, encodedPath };
542
+ }
543
+
544
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/runtimeClient/runtimeDataClient.js
545
+ var _RuntimeDataClient = class _RuntimeDataClient {
546
+ // Constructor for RuntimeDataClient
547
+ // Accepts an IPowerOperationExecutor instance for executing operations
548
+ constructor(_powerOperationExecutor) {
549
+ __publicField(this, "_powerOperationExecutor");
550
+ this._powerOperationExecutor = _powerOperationExecutor;
551
+ }
552
+ /**
553
+ * Creates a new instance of RuntimeDataClient
554
+ */
555
+ static createInstanceAsync(powerOperationExecutor) {
556
+ return Promise.resolve(new _RuntimeDataClient(powerOperationExecutor));
557
+ }
558
+ /**
559
+ * Creates data using POST method
560
+ * @param url - The URL for the request
561
+ * @param apiId - The API ID for authentication
562
+ * @param tableName - The name of the table to access
563
+ * @param body - The request body for the POST method
564
+ * @param operationName - Optional operation name for telemetry
565
+ * @return Promise resolving to the response data
566
+ * @throws Error if the request fails or the response is invalid
567
+ * @throws Error if the request body is invalid
568
+ */
569
+ async createDataAsync(url, apiId, tableName, body, context) {
570
+ try {
571
+ if (!body) {
572
+ throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingRequestBody}`);
573
+ }
574
+ const config = {
575
+ url,
576
+ method: HttpMethod.POST,
577
+ apiId,
578
+ tableName,
579
+ body: JSON.stringify(body)
580
+ };
581
+ context = this._ensureContext(context, "runtimeDataClient.createDataAsync");
582
+ return await this._executeRequest(config, context);
583
+ } catch (error) {
584
+ if (isOperationResult(error)) {
585
+ return error;
586
+ } else {
587
+ return createErrorResponse(error, DataOperationErrorMessages.CreateFailed);
588
+ }
589
+ }
590
+ }
591
+ /**
592
+ * Updates data using PATCH method
593
+ * @param url - The URL for the request
594
+ * @param apiId - The API ID for authentication
595
+ * @param tableName - The name of the table to access
596
+ * @param body - The request body for the PATCH method
597
+ * @param operationName - Optional operation name for telemetry
598
+ * @return Promise resolving to the response data
599
+ * @throws Error if the request fails or the response is invalid
600
+ * @throws Error if the request body is invalid
601
+ */
602
+ async updateDataAsync(url, apiId, tableName, body, context) {
603
+ try {
604
+ if (!body) {
605
+ throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingRequestBody}`);
606
+ }
607
+ const config = {
608
+ url,
609
+ method: HttpMethod.PATCH,
610
+ apiId,
611
+ tableName,
612
+ body: JSON.stringify(body)
613
+ };
614
+ context = this._ensureContext(context, "runtimeDataClient.updateDataAsync");
615
+ return await this._executeRequest(config, context);
616
+ } catch (error) {
617
+ if (isOperationResult(error)) {
618
+ return error;
619
+ } else {
620
+ return createErrorResponse(error, DataOperationErrorMessages.UpdateFailed);
621
+ }
622
+ }
623
+ }
624
+ /**
625
+ * Deletes data using DELETE method
626
+ * @param url - The URL for the request
627
+ * @param connectionApi - The API ID for authentication
628
+ * @param serviceNamespace - The name of the service namespace
629
+ * @param operationName - Optional operation name for telemetry
630
+ * @return Promise resolving to the response data
631
+ * @throws Error if the request fails or the response is invalid
632
+ */
633
+ async deleteDataAsync(url, connectionApi, serviceNamespace, context) {
634
+ try {
635
+ const config = {
636
+ url,
637
+ method: HttpMethod.DELETE,
638
+ apiId: connectionApi,
639
+ tableName: serviceNamespace
640
+ };
641
+ context = this._ensureContext(context, "runtimeDataClient.deleteDataAsync");
642
+ return await this._executeRequest(config, context);
643
+ } catch (error) {
644
+ if (isOperationResult(error)) {
645
+ return error;
646
+ } else {
647
+ return createErrorResponse(error, DataOperationErrorMessages.DeleteFailed);
648
+ }
649
+ }
650
+ }
651
+ /**
652
+ * Retrieves data using GET or POST method
653
+ * @param url - The URL for the request
654
+ * @param apiId - The API ID for authentication
655
+ * @param tableName - The name of the table to access
656
+ * @param method - The HTTP method
657
+ * @param body - Optional request body for POST method
658
+ * @param context - Optional operation context
659
+ * @param operationName - Optional operation name for telemetry
660
+ * @return Promise resolving to the response data
661
+ * @throws Error if the request fails or the response is invalid
662
+ */
663
+ async retrieveDataAsync(url, apiId, tableName, method, headers, body, context) {
664
+ try {
665
+ const config = {
666
+ url,
667
+ method,
668
+ apiId,
669
+ tableName,
670
+ headers,
671
+ body: body ? typeof body === "string" ? body : JSON.stringify(body) : void 0
672
+ };
673
+ context = this._ensureContext(context, "runtimeDataClient.retrieveDataAsync");
674
+ return await this._executeRequest(config, context);
675
+ } catch (error) {
676
+ if (isOperationResult(error)) {
677
+ return error;
678
+ } else {
679
+ return createErrorResponse(error, DataOperationErrorMessages.RetrieveFailed);
680
+ }
681
+ }
682
+ }
683
+ /**
684
+ * Gets an access token for the specified API.
685
+ * If the API is Dataverse, retrieves a dynamic resource token; otherwise, retrieves a standard appservice API token.
686
+ * @param apiId - The API ID for authentication
687
+ * @param datasetName - Optional dataset name for Dataverse
688
+ * @returns Promise resolving to the access token
689
+ * @throws Error if token acquisition fails
690
+ */
691
+ async _getAccessToken(apiId, datasetName) {
692
+ try {
693
+ let result;
694
+ if (apiId === DataSources.Dataverse) {
695
+ result = await this._powerOperationExecutor.execute(_RuntimeDataClient.SERVICES.identityService, _RuntimeDataClient.ACTIONS.getDynamicToken, [datasetName]);
696
+ } else {
697
+ result = await this._powerOperationExecutor.execute(_RuntimeDataClient.SERVICES.identityService, _RuntimeDataClient.ACTIONS.getToken, [apiId]);
698
+ }
699
+ return result.data;
700
+ } catch (error) {
701
+ throw new PowerDataRuntimeError(ErrorCodes.TokenAcquisitionFailed, getErrorMessage(error));
702
+ }
703
+ }
704
+ // Merge Prefer headers for Dataverse batch payloads
705
+ _mergePreferHeaders(configHeaders, method) {
706
+ let preferHeader = "";
707
+ if (configHeaders?.Prefer) {
708
+ preferHeader += configHeaders.Prefer;
709
+ }
710
+ if (method === HttpMethod.POST || method === HttpMethod.PATCH) {
711
+ const defaultPrefer = "return=representation,odata.include-annotations=*";
712
+ if (preferHeader) {
713
+ if (!preferHeader.includes("return=representation")) {
714
+ preferHeader += (preferHeader ? "," : "") + defaultPrefer;
715
+ }
716
+ } else {
717
+ preferHeader = defaultPrefer;
718
+ }
719
+ }
720
+ return preferHeader;
721
+ }
722
+ /**
723
+ * Creates headers for the HTTP request.
724
+ * Combines default headers with any custom headers provided in the config.
725
+ * Custom headers are optional and take precedence over default headers.
726
+ * @param token - The access token for authentication
727
+ * @param config - The HTTP request configuration
728
+ * @return The headers for the request
729
+ * @throws Error if header creation fails
730
+ */
731
+ _createHeaders(token, config, context) {
732
+ const baseHeaders = {
733
+ Accept: "application/json",
734
+ "x-ms-protocol-semantics": "cdp",
735
+ ServiceNamespace: config.tableName,
736
+ Authorization: `paauth ${token}`,
737
+ "x-ms-pa-client-custom-headers-options": '{"addCustomHeaders":true}',
738
+ "x-ms-enable-selects": "true",
739
+ "x-ms-pa-client-telemetry-options": `paclient-telemetry {"operationName":"${context?.operationName ?? "runtimeDataClient.executeRequest"}"}`,
740
+ "x-ms-pa-client-telemetry-additional-data": `{"apiId":"${config.apiId}"}`
741
+ };
742
+ if (config.apiId === DataSources.Dataverse) {
743
+ baseHeaders["x-ms-protocol-semantics"] = DataSources.Dataverse;
744
+ baseHeaders.Authorization = `dynamicauth ${token}`;
745
+ const { baseUrl, encodedPath } = extractDataverseUrlParts(config.url);
746
+ const batchId = context?.batchId || "";
747
+ const preferHeader = this._mergePreferHeaders(config.headers, config.method);
748
+ baseHeaders.BatchInfo = JSON.stringify({
749
+ baseUrl,
750
+ encodedPath,
751
+ headers: {
752
+ Accept: "application/json",
753
+ ...preferHeader ? { Prefer: preferHeader } : {},
754
+ ...config.method === HttpMethod.POST || config.method === HttpMethod.PATCH ? { "Content-Type": "application/json" } : {}
755
+ },
756
+ batchId
757
+ });
758
+ }
759
+ if (config.headers) {
760
+ return { ...baseHeaders, ...config.headers };
761
+ }
762
+ return baseHeaders;
763
+ }
764
+ /**
765
+ * Executes an HTTP request with the given configuration
766
+ * @param config - The HTTP request configuration
767
+ * @param context - Optional operation context
768
+ * @return Promise resolving to the response data
769
+ * @throws Error if the request fails or the response is invalid
770
+ * @throws Error if the response content type is invalid
771
+ */
772
+ async _executeRequest(config, context) {
773
+ const token = await this._getAccessToken(config.apiId, context?.datasetName);
774
+ const headers = this._createHeaders(token, config, context);
775
+ const requestBody = config.body ? new Blob([config.body], { type: "application/json" }) : "";
776
+ let result;
777
+ try {
778
+ result = await this._powerOperationExecutor.execute(_RuntimeDataClient.SERVICES.dataClient, _RuntimeDataClient.ACTIONS.sendHttp, [
779
+ {
780
+ url: config.url,
781
+ method: config.method,
782
+ requestSource: _RuntimeDataClient.REQUEST_SOURCE,
783
+ allowSessionStorage: true,
784
+ returnDirectResponse: true,
785
+ headers
786
+ },
787
+ requestBody,
788
+ "arraybuffer"
789
+ ]);
790
+ } catch (error) {
791
+ return {
792
+ success: false,
793
+ error: parseHttpPluginError(error),
794
+ data: void 0
795
+ };
796
+ }
797
+ const responseData = result.data;
798
+ const responseHeaders = responseData[0].headers;
799
+ const contentType = responseHeaders["Content-Type"];
800
+ if (!contentType) {
801
+ return {
802
+ success: true,
803
+ data: void 0
804
+ };
805
+ } else if (contentType.indexOf("application/json") !== -1) {
806
+ const data = result.data[1];
807
+ let text = this._decodeArrayBuffer(data);
808
+ if (!text) {
809
+ text = "{}";
810
+ }
811
+ const parsedResult = JSON.parse(text);
812
+ if (context?.isDataVerseOperation || this._isDataverseCall(config.url)) {
813
+ return {
814
+ success: true,
815
+ data: parsedResult
816
+ };
817
+ } else if (!context?.isExecuteAsync && "value" in parsedResult && Array.isArray(parsedResult.value)) {
818
+ return {
819
+ success: true,
820
+ data: parsedResult.value,
821
+ count: parsedResult["@odata.count"]
822
+ };
823
+ } else {
824
+ return {
825
+ success: true,
826
+ data: parsedResult
827
+ };
828
+ }
829
+ } else if (contentType.indexOf("image/") !== -1) {
830
+ const buffer = result.data[1];
831
+ if (buffer instanceof ArrayBuffer) {
832
+ const value = arrayBufferToBase64(buffer);
833
+ return {
834
+ success: true,
835
+ data: value
836
+ };
837
+ }
838
+ return {
839
+ success: true,
840
+ data: buffer
841
+ };
842
+ } else {
843
+ const buffer = result.data[1];
844
+ if (buffer instanceof ArrayBuffer) {
845
+ const value = convertArrayBufferToString(buffer);
846
+ const status = responseData[0].status;
847
+ const responseType = context?.responseInfo?.[status];
848
+ if (responseType) {
849
+ let parsedValue;
850
+ try {
851
+ parsedValue = JSON.parse(value);
852
+ } catch (err) {
853
+ return {
854
+ success: false,
855
+ data: void 0,
856
+ error: new Error(DataOperationErrorMessages.InvalidResponse)
857
+ };
858
+ }
859
+ if (responseType.type === "array" && !Array.isArray(parsedValue)) {
860
+ return {
861
+ success: false,
862
+ data: void 0,
863
+ error: new Error(DataOperationErrorMessages.InvalidResponse)
864
+ };
865
+ }
866
+ if (responseType.type === "object" && (typeof parsedValue !== "object" || Array.isArray(parsedValue) || parsedValue === null)) {
867
+ return {
868
+ success: false,
869
+ data: void 0,
870
+ error: new Error(DataOperationErrorMessages.InvalidResponse)
871
+ };
872
+ }
873
+ return {
874
+ success: true,
875
+ data: parsedValue
876
+ };
877
+ } else {
878
+ return {
879
+ success: true,
880
+ data: value
881
+ };
882
+ }
883
+ }
884
+ return {
885
+ success: false,
886
+ data: responseData,
887
+ error: new Error(DataOperationErrorMessages.InvalidResponse)
888
+ };
889
+ }
890
+ }
891
+ _ensureContext(context, defaultOperationName) {
892
+ if (!context) {
893
+ context = {};
894
+ }
895
+ if (!context.operationName) {
896
+ context.operationName = defaultOperationName;
897
+ }
898
+ return context;
899
+ }
900
+ /**
901
+ * Checks if the given URL is a Dataverse API call
902
+ * @param url - The URL to check
903
+ * @returns True if the URL is a Dataverse API call, false otherwise
904
+ */
905
+ _isDataverseCall(url) {
906
+ if (!url) {
907
+ return false;
908
+ }
909
+ const urlLower = decodeURIComponent(url).toLowerCase();
910
+ return urlLower.includes("/api/data/") && !urlLower.includes("/apim");
911
+ }
912
+ /**
913
+ * Decodes ArrayBuffer to string, handling both browser and Node.js environments
914
+ * @param buffer - The ArrayBuffer to decode
915
+ * @returns The decoded string
916
+ */
917
+ _decodeArrayBuffer(buffer) {
918
+ if (typeof TextDecoder !== "undefined") {
919
+ return new TextDecoder().decode(buffer);
920
+ }
921
+ const uint8Array = new Uint8Array(buffer);
922
+ const results = [];
923
+ const chunkSize = 8192;
924
+ for (let i = 0; i < uint8Array.length; i += chunkSize) {
925
+ const chunk = uint8Array.subarray(i, Math.min(i + chunkSize, uint8Array.length));
926
+ results.push(String.fromCharCode.apply(null, Array.from(chunk)));
927
+ }
928
+ try {
929
+ return results.join("");
930
+ } catch {
931
+ return results.join("");
932
+ }
933
+ }
934
+ };
935
+ // Static identifiers for services
936
+ // Used to identify specific services within the PowerApps environment
937
+ __publicField(_RuntimeDataClient, "SERVICES", {
938
+ dataClient: "AppHttpClientPlugin",
939
+ identityService: "AppIdentityServicePlugin"
940
+ });
941
+ // Static identifiers for service actions
942
+ // Used to identify specific actions within the service
943
+ // These actions are used to send HTTP requests and get access tokens
944
+ __publicField(_RuntimeDataClient, "ACTIONS", {
945
+ sendHttp: "sendHttpAsync",
946
+ getToken: "getAppAccessTokenAsync",
947
+ getDynamicToken: "getAppDynamicResourceAccessTokenAsync"
948
+ });
949
+ // Request source identifier for telemetry
950
+ // Used to identify the source of the request in telemetry data
951
+ __publicField(_RuntimeDataClient, "REQUEST_SOURCE", "PublishedApp");
952
+ var RuntimeDataClient = _RuntimeDataClient;
953
+
954
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/runtimeClient/runtimeMetadataClient.js
955
+ var _RuntimeMetadataClient = class _RuntimeMetadataClient {
956
+ // Private member for the PowerOperationExecutor
957
+ // The PowerOperationExecutor is used to execute operations on the clients
958
+ constructor(_powerOperationExecutor) {
959
+ __publicField(this, "_powerOperationExecutor");
960
+ this._powerOperationExecutor = _powerOperationExecutor;
961
+ }
962
+ /**
963
+ * Creates a new instance of RuntimeMetadataClient
964
+ * @param powerOperationExecutor - The powerOperationExecutor instance
965
+ * @returns Promise resolving to IRuntimeMetadataClient
966
+ */
967
+ static createInstanceAsync(powerOperationExecutor) {
968
+ return Promise.resolve(new _RuntimeMetadataClient(powerOperationExecutor));
969
+ }
970
+ /**
971
+ * Fetches app connection configurations
972
+ * @returns Promise resolving to connection reference details
973
+ * @throws Error if the operation fails
974
+ */
975
+ async getAppConnectionConfigsAsync() {
976
+ try {
977
+ const config = {
978
+ service: _RuntimeMetadataClient.SERVICES.powerAppsClient,
979
+ action: _RuntimeMetadataClient.ACTIONS.getConnectionConfigs,
980
+ params: []
981
+ };
982
+ const result = await this._executeOperation(config);
983
+ return { success: true, data: result };
984
+ } catch (error) {
985
+ throw new PowerDataRuntimeError(ErrorCodes.ConnectionConfigFetchFailed, getErrorMessage(error));
986
+ }
987
+ }
988
+ /**
989
+ * Fetches app data source configurations
990
+ * @returns Promise resolving to connection reference details
991
+ * @throws Error if the operation fails
992
+ */
993
+ async getAppDataSourceConfigsAsync() {
994
+ try {
995
+ const config = {
996
+ service: _RuntimeMetadataClient.SERVICES.powerAppsClient,
997
+ action: _RuntimeMetadataClient.ACTIONS.getDataSourceConfigs,
998
+ params: []
999
+ };
1000
+ const result = await this._executeOperation(config);
1001
+ return { success: true, data: result };
1002
+ } catch (error) {
1003
+ throw new PowerDataRuntimeError(ErrorCodes.DataSourceConfigFetchFailed, getErrorMessage(error));
1004
+ }
1005
+ }
1006
+ /**
1007
+ * Executes a metadata operation with the given configuration
1008
+ * @param config - The operation configuration
1009
+ * @returns Promise resolving to the operation result
1010
+ * @throws Error if the operation fails
1011
+ */
1012
+ async _executeOperation(config) {
1013
+ try {
1014
+ const result = await this._powerOperationExecutor.execute(config.service, config.action, config.params || []);
1015
+ const lowerCaseResult = Object.keys(result.data).reduce((acc, key) => {
1016
+ acc[key.toLowerCase()] = (result.data ?? {})[key];
1017
+ return acc;
1018
+ }, {});
1019
+ return lowerCaseResult;
1020
+ } catch {
1021
+ throw new PowerDataRuntimeError(ErrorCodes.InvalidMetadataResponse);
1022
+ }
1023
+ }
1024
+ };
1025
+ // Static identifiers for services and actions
1026
+ // Used to identify specific services and actions within the PowerApps environment
1027
+ // These identifiers are used to execute operations through the PowerOperationExecutor
1028
+ // The services provide the functionality for the operations
1029
+ __publicField(_RuntimeMetadataClient, "SERVICES", {
1030
+ powerAppsClient: "AppPowerAppsClientPlugin"
1031
+ });
1032
+ // The actions define the specific operations to be performed
1033
+ __publicField(_RuntimeMetadataClient, "ACTIONS", {
1034
+ getConnectionConfigs: "loadAppConnectionsAsync_v2",
1035
+ getDataSourceConfigs: "getAppCdsDataSourceConfigsAsync"
1036
+ });
1037
+ var RuntimeMetadataClient = _RuntimeMetadataClient;
1038
+
1039
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/runtimeClient/runtimeClientProvider.js
1040
+ var RuntimeClientProvider = class {
1041
+ // Constructor for RuntimeClientProvider
1042
+ // Accepts an optional IPowerOperationExecutor instance for executing operations
1043
+ // If not provided, uses the default PowerOperationExecutor instance
1044
+ constructor(powerOperationExecutor) {
1045
+ // Private members for data and metadata clients
1046
+ // The data client is responsible for handling data operations
1047
+ __publicField(this, "_dataClient");
1048
+ // The metadata client is responsible for handling metadata operations
1049
+ __publicField(this, "_metadataClient");
1050
+ // The operation executor is used to execute operations on the clients
1051
+ // It is an instance of IPowerOperationExecutor, which provides the necessary methods for executing operations
1052
+ __publicField(this, "_operationExecutor");
1053
+ this._operationExecutor = powerOperationExecutor;
1054
+ }
1055
+ /**
1056
+ * Gets or initializes the data client
1057
+ * @throws Error if client initialization fails
1058
+ * @returns Promise resolving to IRuntimeDataClient
1059
+ */
1060
+ async getDataClientAsync() {
1061
+ try {
1062
+ if (!this._dataClient) {
1063
+ this._dataClient = await this._initializeDataClient();
1064
+ }
1065
+ if (!this._dataClient) {
1066
+ throw new PowerDataRuntimeError(ErrorCodes.DataClientNotInitialized);
1067
+ }
1068
+ return this._dataClient;
1069
+ } catch (error) {
1070
+ throw new PowerDataRuntimeError(ErrorCodes.DataClientInitFailed, getErrorMessage(error));
1071
+ }
1072
+ }
1073
+ /**
1074
+ * Gets or initializes the metadata client
1075
+ * @throws Error if client initialization fails
1076
+ * @returns Promise resolving to IRuntimeMetadataClient
1077
+ */
1078
+ async getMetadataClientAsync() {
1079
+ try {
1080
+ if (!this._metadataClient) {
1081
+ this._metadataClient = await this._initializeMetadataClient();
1082
+ }
1083
+ if (!this._metadataClient) {
1084
+ throw new PowerDataRuntimeError(ErrorCodes.MetadataClientNotInitialized);
1085
+ }
1086
+ return this._metadataClient;
1087
+ } catch (error) {
1088
+ throw new PowerDataRuntimeError(ErrorCodes.MetadataClientInitFailed, getErrorMessage(error));
1089
+ }
1090
+ }
1091
+ /**
1092
+ * Initializes the data client
1093
+ * @returns Promise resolving to IRuntimeDataClient
1094
+ */
1095
+ async _initializeDataClient() {
1096
+ return RuntimeDataClient.createInstanceAsync(this._operationExecutor);
1097
+ }
1098
+ /**
1099
+ * Initializes the metadata client
1100
+ * @returns Promise resolving to IRuntimeMetadataClient
1101
+ */
1102
+ async _initializeMetadataClient() {
1103
+ return RuntimeMetadataClient.createInstanceAsync(this._operationExecutor);
1104
+ }
1105
+ /**
1106
+ * Resets both clients, forcing re-initialization on next use
1107
+ * Useful for testing or recovering from error states
1108
+ */
1109
+ reset() {
1110
+ this._dataClient = void 0;
1111
+ this._metadataClient = void 0;
1112
+ }
1113
+ };
1114
+
1115
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/shared/stringQueryOptions.js
1116
+ function convertOptionsToQueryString(options) {
1117
+ if (!options) {
1118
+ return "";
1119
+ }
1120
+ const parts = [];
1121
+ if (options.select && options.select.length > 0) {
1122
+ parts.push(`$select=${encodeURIComponent(options.select.map((s) => s.trim().replace(/%20/g, "+").replace(/'/g, "%27")).join(","))}`);
1123
+ }
1124
+ if (options.filter) {
1125
+ const encodedFilter = encodeURIComponent(options.filter.trim()).replace(/%20/g, "+").replace(/'/g, "%27");
1126
+ parts.push(`$filter=${encodedFilter}`);
1127
+ }
1128
+ if (options.orderBy && options.orderBy.length > 0) {
1129
+ parts.push(`$orderby=${encodeURIComponent(options.orderBy.map((s) => s.trim().replace(/%20/g, "+").replace(/'/g, "%27")).join(","))}`);
1130
+ }
1131
+ if (options.top !== void 0 && options.top !== null) {
1132
+ parts.push(`$top=${options.top}`);
1133
+ }
1134
+ if (options.skip !== void 0 && options.skip !== null) {
1135
+ parts.push(`$skip=${options.skip}`);
1136
+ }
1137
+ if (options.count !== void 0 && options.count !== null) {
1138
+ parts.push(`$count=${options.count}`);
1139
+ }
1140
+ if (options.skipToken && options.skipToken.trim() !== "") {
1141
+ parts.push(`$skiptoken=${encodeURIComponent(options.skipToken.trim())}`);
1142
+ }
1143
+ return parts.length ? `?${parts.join("&")}` : "";
1144
+ }
1145
+
1146
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/dataverseDataOperationExecutor.js
1147
+ var ODATA_NEXT_LINK = "@odata.nextLink";
1148
+ var DataverseDataOperationExecutor = class {
1149
+ constructor(clientProvider) {
1150
+ // Static identifiers for services and actions
1151
+ // Used to identify specific services and actions within the PowerApps environment
1152
+ __publicField(this, "_clientProvider");
1153
+ __publicField(this, "_databaseReferences");
1154
+ this._clientProvider = clientProvider;
1155
+ }
1156
+ /**
1157
+ * Creates a new record in Dataverse
1158
+ * @param tableName - The name of the table
1159
+ * @param data - The record data to create
1160
+ * @returns Promise resolving to operation result
1161
+ */
1162
+ async createRecordAsync(tableName, data) {
1163
+ return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName), async (dataClient, requestUrl, dataSourceInfo) => {
1164
+ const dataverseResponse = await dataClient.createDataAsync(
1165
+ requestUrl,
1166
+ DataSources.Dataverse,
1167
+ // Use environment name for Dataverse authentication
1168
+ tableName,
1169
+ data,
1170
+ {
1171
+ operationName: DataverseOperationName.CreateRecord,
1172
+ datasetName: dataSourceInfo.datasetName,
1173
+ isDataVerseOperation: true
1174
+ }
1175
+ );
1176
+ const returnValue = {
1177
+ success: dataverseResponse.success,
1178
+ data: dataverseResponse.data,
1179
+ error: dataverseResponse.error
1180
+ };
1181
+ return returnValue;
1182
+ }, DataOperationErrorMessages.CreateFailed);
1183
+ }
1184
+ /**
1185
+ * Updates an existing record in Dataverse
1186
+ * @param tableName - The name of the table
1187
+ * @param id - The record identifier
1188
+ * @param data - The updated record data
1189
+ * @returns Promise resolving to operation result
1190
+ */
1191
+ async updateRecordAsync(tableName, id, data) {
1192
+ return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, `(${id})`), async (dataClient, requestUrl, dataSourceInfo) => {
1193
+ const dataverseResponse = await dataClient.updateDataAsync(requestUrl, DataSources.Dataverse, tableName, data, {
1194
+ operationName: DataverseOperationName.UpdateRecord,
1195
+ datasetName: dataSourceInfo.datasetName,
1196
+ isDataVerseOperation: true
1197
+ });
1198
+ const returnValue = {
1199
+ success: dataverseResponse.success,
1200
+ data: dataverseResponse.data,
1201
+ error: dataverseResponse.error
1202
+ };
1203
+ return returnValue;
1204
+ }, DataOperationErrorMessages.UpdateFailed);
1205
+ }
1206
+ /**
1207
+ * Deletes a record from Dataverse
1208
+ * @param tableName - The name of the table
1209
+ * @param id - The record identifier
1210
+ * @returns Promise resolving to operation result
1211
+ */
1212
+ async deleteRecordAsync(tableName, id) {
1213
+ return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, `(${id})`), async (dataClient, requestUrl, dataSourceInfo) => {
1214
+ const dataverseResponse = await dataClient.deleteDataAsync(requestUrl, DataSources.Dataverse, tableName, {
1215
+ operationName: DataverseOperationName.DeleteRecord,
1216
+ datasetName: dataSourceInfo.datasetName,
1217
+ isDataVerseOperation: true
1218
+ });
1219
+ const returnValue = {
1220
+ success: dataverseResponse.success,
1221
+ data: dataverseResponse.data,
1222
+ error: dataverseResponse.error
1223
+ };
1224
+ return returnValue;
1225
+ }, DataOperationErrorMessages.DeleteFailed);
1226
+ }
1227
+ /**
1228
+ * Retrieves a single record from Dataverse
1229
+ * @param tableName - The name of the table
1230
+ * @param id - The record identifier
1231
+ * @param options - The retrieval options
1232
+ * @returns Promise resolving to operation result
1233
+ */
1234
+ async retrieveRecordAsync(tableName, id, options) {
1235
+ const { maxPageSize = 500, ...rest } = options || {};
1236
+ const optionsString = convertOptionsToQueryString(rest);
1237
+ const headers = { Prefer: `odata.maxpagesize=${maxPageSize},odata.include-annotations=*` };
1238
+ return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, `(${id})${optionsString}`), async (dataClient, requestUrl, dataSourceInfo) => {
1239
+ const dataverseResponse = await dataClient.retrieveDataAsync(
1240
+ requestUrl,
1241
+ DataSources.Dataverse,
1242
+ tableName,
1243
+ HttpMethod.GET,
1244
+ headers,
1245
+ void 0,
1246
+ // No body for GET requests
1247
+ {
1248
+ operationName: DataverseOperationName.RetrieveRecord,
1249
+ datasetName: dataSourceInfo.datasetName,
1250
+ isDataVerseOperation: true
1251
+ }
1252
+ );
1253
+ const returnValue = {
1254
+ success: dataverseResponse.success,
1255
+ data: dataverseResponse.data,
1256
+ error: dataverseResponse.error
1257
+ };
1258
+ return returnValue;
1259
+ }, DataOperationErrorMessages.RetrieveFailed);
1260
+ }
1261
+ /**
1262
+ * Retrieves multiple records from Dataverse
1263
+ * @param tableName - The name of the table
1264
+ * @param options - The retrieval options
1265
+ * @param maxPageSize - Optional maximum page size
1266
+ * @returns Promise resolving to operation result
1267
+ */
1268
+ async retrieveMultipleRecordsAsync(tableName, options) {
1269
+ const { maxPageSize = 500, ...rest } = options || {};
1270
+ const optionsString = convertOptionsToQueryString(rest);
1271
+ const headers = { Prefer: `odata.maxpagesize=${maxPageSize},odata.include-annotations=*` };
1272
+ return this._executeNativeDataverseOperation(tableName, (dataSourceInfo, tblName) => this._getDataverseRequestUrl(dataSourceInfo, tblName, optionsString), async (dataClient, requestUrl, dataSourceInfo) => {
1273
+ const dataverseResponse = await dataClient.retrieveDataAsync(
1274
+ requestUrl,
1275
+ DataSources.Dataverse,
1276
+ tableName,
1277
+ HttpMethod.GET,
1278
+ headers,
1279
+ void 0,
1280
+ // No body for GET requests
1281
+ {
1282
+ operationName: DataverseOperationName.RetrieveMultipleRecords,
1283
+ datasetName: dataSourceInfo.datasetName,
1284
+ isDataVerseOperation: true
1285
+ }
1286
+ );
1287
+ const returnValue = {
1288
+ success: dataverseResponse.success,
1289
+ data: dataverseResponse?.data?.value || [],
1290
+ skipToken: extractSkipToken(dataverseResponse?.data?.[ODATA_NEXT_LINK]),
1291
+ error: dataverseResponse.error
1292
+ };
1293
+ return returnValue;
1294
+ }, DataOperationErrorMessages.RetrieveMultipleFailed);
1295
+ }
1296
+ /**
1297
+ * Executes a custom Dataverse operation
1298
+ * @param operation - The operation to execute
1299
+ * @returns Promise resolving to operation result
1300
+ */
1301
+ async executeAsync(operation) {
1302
+ const { dataverseRequest } = operation;
1303
+ if (!dataverseRequest) {
1304
+ return {
1305
+ success: false,
1306
+ data: null,
1307
+ error: { message: "Dataverse request details are required for Dataverse operations." }
1308
+ };
1309
+ }
1310
+ const { action, parameters } = dataverseRequest;
1311
+ switch (action) {
1312
+ // Future custom actions can be handled here
1313
+ case "getEntityMetadata":
1314
+ const { tableName, options } = parameters;
1315
+ if (!tableName) {
1316
+ return {
1317
+ success: false,
1318
+ data: null,
1319
+ error: { message: "Table name is required for getEntityMetadata action." }
1320
+ };
1321
+ }
1322
+ return this._getEntityMetadata(tableName, options ?? {});
1323
+ default:
1324
+ Log.trackEvent("DataverseDataOperation.UnsupportedAction", {
1325
+ message: `Unsupported Dataverse action: ${action}`
1326
+ });
1327
+ return {
1328
+ success: false,
1329
+ data: null,
1330
+ error: { message: `Unsupported Dataverse action: "${action}"` }
1331
+ };
1332
+ }
1333
+ }
1334
+ async _getEntityMetadata(tableName, options) {
1335
+ const client = await this._getDataClient();
1336
+ const dataSourceInfo = await this._getDataverseDataSourceInfo(tableName);
1337
+ const url = this._generateMetadataRequestUrl(dataSourceInfo, options);
1338
+ return client.retrieveDataAsync(url, DataSources.Dataverse, "EntityDefinitions", HttpMethod.GET, {
1339
+ Consistency: "Strong"
1340
+ // Force CDS to return latest metadata
1341
+ }, void 0, {
1342
+ operationName: DataverseOperationName.RetrieveRecord,
1343
+ datasetName: dataSourceInfo.datasetName,
1344
+ isDataVerseOperation: true
1345
+ });
1346
+ }
1347
+ /**
1348
+ * Returns the database references for Dataverse, grouped by environment/database.
1349
+ * These come from the launch app response via runtime metadata client.
1350
+ */
1351
+ async getDatabaseReferences() {
1352
+ if (this._databaseReferences) {
1353
+ return this._databaseReferences;
1354
+ }
1355
+ const runtimeDatabaseReferences = await this._loadDatabaseReferencesFromRuntime();
1356
+ if (runtimeDatabaseReferences && Object.keys(runtimeDatabaseReferences).length > 0) {
1357
+ this._databaseReferences = runtimeDatabaseReferences;
1358
+ return this._databaseReferences;
1359
+ }
1360
+ throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, "Failed to load Dataverse database references from runtime.");
1361
+ }
1362
+ /**
1363
+ * Loads database references from runtime metadata client (launch app response).
1364
+ */
1365
+ async _loadDatabaseReferencesFromRuntime() {
1366
+ try {
1367
+ const metadataClient = await this._getMetadataClient();
1368
+ const response = await metadataClient.getAppDataSourceConfigsAsync();
1369
+ if (!response.success || !response.data) {
1370
+ return void 0;
1371
+ }
1372
+ const cdsDataSources = Object.values(response.data);
1373
+ if (cdsDataSources.length === 0) {
1374
+ return void 0;
1375
+ }
1376
+ const databaseReferences = {};
1377
+ for (const cdsDataSource of cdsDataSources) {
1378
+ const cdsConfig = cdsDataSource;
1379
+ const instanceUrl = this._extractInstanceUrlFromRuntimeUrl(cdsConfig.runtimeUrl);
1380
+ const envName = "default.cds";
1381
+ if (!databaseReferences[envName]) {
1382
+ databaseReferences[envName] = {
1383
+ databaseDetails: {
1384
+ referenceType: "Environmental",
1385
+ environmentName: envName,
1386
+ overrideValues: {
1387
+ status: "NotSpecified",
1388
+ environmentVariableName: ""
1389
+ },
1390
+ linkedEnvironmentMetadata: {
1391
+ resourceId: "",
1392
+ friendlyName: "",
1393
+ uniqueName: "",
1394
+ domainName: "",
1395
+ version: cdsConfig.version || "9.2",
1396
+ instanceUrl,
1397
+ instanceApiUrl: cdsConfig.runtimeUrl,
1398
+ baseLanguage: 1033,
1399
+ instanceState: "Ready",
1400
+ createdTime: "",
1401
+ platformSku: ""
1402
+ }
1403
+ },
1404
+ dataSources: {}
1405
+ };
1406
+ }
1407
+ const dataSourceName = cdsConfig.entitySetName || cdsConfig.logicalName;
1408
+ databaseReferences[envName].dataSources[dataSourceName] = {
1409
+ entitySetName: cdsConfig.entitySetName,
1410
+ logicalName: cdsConfig.logicalName,
1411
+ isHidden: false
1412
+ };
1413
+ }
1414
+ return databaseReferences;
1415
+ } catch (error) {
1416
+ Log.trackEvent("DataverseDataOperation.FailedToLoadDatabaseReferences", {
1417
+ message: "[DataverseDataOperation] Failed to load database references from runtime",
1418
+ error
1419
+ });
1420
+ return void 0;
1421
+ }
1422
+ }
1423
+ _extractInstanceUrlFromRuntimeUrl(runtimeUrl) {
1424
+ try {
1425
+ const matches = runtimeUrl.match(/^(https?:\/\/[^\/]+)/);
1426
+ return matches ? matches[1] : runtimeUrl;
1427
+ } catch (error) {
1428
+ Log.trackEvent("DataverseDataOperation.FailedToExtractInstanceUrl", {
1429
+ message: "[DataverseDataOperation] Failed to extract instance URL from runtime URL",
1430
+ error
1431
+ });
1432
+ return runtimeUrl;
1433
+ }
1434
+ }
1435
+ /**
1436
+ * Helper to get a native data client and database reference
1437
+ */
1438
+ async _getDataClient() {
1439
+ const dataClient = await this._clientProvider.getDataClientAsync();
1440
+ if (!dataClient) {
1441
+ Log.trackEvent("DataverseDataOperation.DataClientNotAvailable", {
1442
+ message: "[DataverseDataOperation] Data client is not available"
1443
+ });
1444
+ throw new PowerDataRuntimeError(ErrorCodes.DataClientNotAvailable, "Data client is not available.");
1445
+ }
1446
+ return dataClient;
1447
+ }
1448
+ /**
1449
+ * Gets the metadata client instance
1450
+ */
1451
+ async _getMetadataClient() {
1452
+ const metadataClient = await this._clientProvider.getMetadataClientAsync();
1453
+ if (!metadataClient) {
1454
+ Log.trackEvent("DataverseDataOperation.MetadataClientNotAvailable", {
1455
+ message: "[DataverseDataOperation] Metadata client is not available"
1456
+ });
1457
+ throw new PowerDataRuntimeError(ErrorCodes.MetadataClientNotAvailable);
1458
+ }
1459
+ return metadataClient;
1460
+ }
1461
+ /**
1462
+ * Template method for connector-style CRUD operations to reduce duplication.
1463
+ * Handles client, dataSourceInfo, requestUrl, and error handling.
1464
+ */
1465
+ async _executeNativeDataverseOperation(tableName, buildUrl, operation, errorMessage) {
1466
+ try {
1467
+ const dataClient = await this._getDataClient();
1468
+ const dataSourceInfo = await this._getDataverseDataSourceInfo(tableName);
1469
+ const requestUrl = buildUrl(dataSourceInfo, tableName);
1470
+ return operation(dataClient, requestUrl, dataSourceInfo);
1471
+ } catch (error) {
1472
+ return createErrorResponse(error, errorMessage);
1473
+ }
1474
+ }
1475
+ /**
1476
+ * Helper to get the Dataverse datasourceinfo from databaseReferences
1477
+ */
1478
+ async _getDataverseDataSourceInfo(tableName) {
1479
+ let dbRefs;
1480
+ try {
1481
+ dbRefs = await this.getDatabaseReferences();
1482
+ } catch (error) {
1483
+ Log.trackEvent("DataverseDataOperation.GetDataSourceInfoFailed", {
1484
+ message: "[DataverseDataOperation] Failed to get database references",
1485
+ tableName,
1486
+ error
1487
+ });
1488
+ const errorMessage = error instanceof Error ? error.message : String(error);
1489
+ throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, `Failed to get Dataverse data source info for table '${tableName}': ${errorMessage}`);
1490
+ }
1491
+ for (const dbKey of Object.keys(dbRefs)) {
1492
+ const db = dbRefs[dbKey];
1493
+ if (db.dataSources[tableName]) {
1494
+ const ds = db.dataSources[tableName];
1495
+ return {
1496
+ datasetName: db.databaseDetails?.environmentName,
1497
+ referenceType: db.databaseDetails?.referenceType,
1498
+ linkedEnvironmentMetadata: db.databaseDetails?.linkedEnvironmentMetadata,
1499
+ entitySetName: ds?.entitySetName,
1500
+ logicalName: ds?.logicalName,
1501
+ isHidden: ds?.isHidden,
1502
+ tableId: ds?.logicalName,
1503
+ apis: {}
1504
+ };
1505
+ }
1506
+ }
1507
+ const notFoundMsg = `No Dataverse data source found for table: ${tableName}`;
1508
+ Log.trackEvent("DataverseDataOperation.DataSourceNotFound", {
1509
+ message: notFoundMsg,
1510
+ tableName
1511
+ });
1512
+ throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, notFoundMsg);
1513
+ }
1514
+ /**
1515
+ * Helper to construct the Dataverse API URL using instanceUrl if available, otherwise fallback to runtimeUrl.
1516
+ */
1517
+ _getInstanceUrl(dataSourceInfo) {
1518
+ const instanceUrl = dataSourceInfo.linkedEnvironmentMetadata?.instanceUrl;
1519
+ if (!instanceUrl) {
1520
+ throw new PowerDataRuntimeError(ErrorCodes.DataClientInitFailed, "No instanceUrl found for Dataverse table.");
1521
+ }
1522
+ const baseUrl = instanceUrl.endsWith("/") ? instanceUrl : `${instanceUrl}/`;
1523
+ return baseUrl;
1524
+ }
1525
+ /**
1526
+ * Helper to construct the Dataverse API URL using instanceUrl if available, otherwise fallback to runtimeUrl.
1527
+ */
1528
+ _getDataverseRequestUrl(dataSourceInfo, tableName, urlPath = "") {
1529
+ const baseUrl = this._getInstanceUrl(dataSourceInfo);
1530
+ return `${baseUrl}api/data/v9.0/${tableName}${urlPath}`;
1531
+ }
1532
+ /**
1533
+ * Constructs GET request URL for fetching metadata using options object.
1534
+ * @param dataSourceInfo - The data source information for the Dataverse table.
1535
+ * @param options - The options for the metadata request.
1536
+ * @returns The constructed metadata request URL.
1537
+ */
1538
+ _generateMetadataRequestUrl(dataSourceInfo, options) {
1539
+ const { logicalName } = dataSourceInfo;
1540
+ if (!logicalName) {
1541
+ throw new PowerDataRuntimeError(ErrorCodes.DataClientInitFailed, "No logicalName found for Dataverse table.");
1542
+ }
1543
+ const url = new URL(`${this._getInstanceUrl(dataSourceInfo)}api/data/v9.0/EntityDefinitions(LogicalName='${logicalName}')`);
1544
+ const { metadata, schema } = options;
1545
+ const selects = new Set(Array.isArray(metadata) ? metadata : []);
1546
+ selects.add("LogicalName");
1547
+ const expands = [];
1548
+ if (schema?.manyToOne) {
1549
+ expands.push("ManyToOneRelationships");
1550
+ }
1551
+ if (schema?.oneToMany) {
1552
+ expands.push("OneToManyRelationships");
1553
+ }
1554
+ if (schema?.manyToMany) {
1555
+ expands.push("ManyToManyRelationships");
1556
+ }
1557
+ if (schema?.columns === "all") {
1558
+ expands.push("Attributes");
1559
+ } else if (schema && Array.isArray(schema.columns) && schema.columns.length > 0) {
1560
+ const attributesCollection = schema.columns.map((a) => `'${a}'`).join(",");
1561
+ expands.push(`Attributes($filter=Microsoft.Dynamics.CRM.In(PropertyName='LogicalName',PropertyValues=[${attributesCollection}]))`);
1562
+ }
1563
+ url.search = new URLSearchParams({
1564
+ $select: [...selects].join(","),
1565
+ $expand: expands.join(",")
1566
+ }).toString();
1567
+ return url.toString();
1568
+ }
1569
+ };
1570
+ function extractSkipToken(nextLink) {
1571
+ if (!nextLink?.trim()) {
1572
+ return void 0;
1573
+ }
1574
+ const match = nextLink.match(/[\?&]\$?skiptoken=([^&#]+)/i);
1575
+ return match ? decodeURIComponent(match[1]) : void 0;
1576
+ }
1577
+
1578
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/data/executors/connectorDataOperationExecutor.js
1579
+ var ConnectorDataOperationExecutor = class {
1580
+ // =====================================
1581
+ // Constructor
1582
+ // =====================================
1583
+ constructor(clientProvider, connectionsService) {
1584
+ // =====================================
1585
+ // Private Members
1586
+ // =====================================
1587
+ __publicField(this, "_clientProvider");
1588
+ __publicField(this, "_connectionsService");
1589
+ __publicField(this, "_databaseReferences");
1590
+ __publicField(this, "_connectionReferences");
1591
+ this._validateConstructorParams(clientProvider, connectionsService);
1592
+ this._clientProvider = clientProvider;
1593
+ this._connectionsService = connectionsService;
1594
+ }
1595
+ // =====================================
1596
+ // Public Methods
1597
+ // =====================================
1598
+ /**
1599
+ * Creates a new record in the specified table
1600
+ */
1601
+ async createRecordAsync(tableName, data) {
1602
+ try {
1603
+ const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1604
+ const requestUrl = await this._buildTableUrl(tableName, connectionReference);
1605
+ const result = await dataClient.createDataAsync(requestUrl, connectionReference.apiId, tableName, data, { operationName: ConnectorOperationName.CreateRecord });
1606
+ return result;
1607
+ } catch (error) {
1608
+ return createErrorResponse(error, DataOperationErrorMessages.CreateFailed);
1609
+ }
1610
+ }
1611
+ /**
1612
+ * Updates an existing record in the specified table
1613
+ */
1614
+ async updateRecordAsync(tableName, id, data) {
1615
+ try {
1616
+ const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1617
+ const requestUrl = await this._buildTableUrl(tableName, connectionReference, `/${id}`);
1618
+ const result = await dataClient.updateDataAsync(requestUrl, connectionReference.apiId, tableName, data, { operationName: ConnectorOperationName.UpdateRecord });
1619
+ return result;
1620
+ } catch (error) {
1621
+ return createErrorResponse(error, DataOperationErrorMessages.UpdateFailed);
1622
+ }
1623
+ }
1624
+ /**
1625
+ * Deletes a record from the specified table
1626
+ */
1627
+ async deleteRecordAsync(tableName, id) {
1628
+ try {
1629
+ const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1630
+ const requestUrl = await this._buildTableUrl(tableName, connectionReference, `/${id}`);
1631
+ const result = await dataClient.deleteDataAsync(requestUrl, connectionReference.apiId, tableName, { operationName: ConnectorOperationName.DeleteRecord });
1632
+ return result;
1633
+ } catch (error) {
1634
+ return createErrorResponse(error, DataOperationErrorMessages.DeleteFailed);
1635
+ }
1636
+ }
1637
+ /**
1638
+ * Retrieves a single record from the specified table
1639
+ */
1640
+ async retrieveRecordAsync(tableName, id, options) {
1641
+ try {
1642
+ const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1643
+ const requestUrl = await this._buildTableUrl(tableName, connectionReference, `/${id}${convertOptionsToQueryString(options)}`);
1644
+ const result = await dataClient.retrieveDataAsync(
1645
+ requestUrl,
1646
+ connectionReference.apiId,
1647
+ tableName,
1648
+ HttpMethod.GET,
1649
+ void 0,
1650
+ // body
1651
+ { operationName: ConnectorOperationName.RetrieveRecord }
1652
+ );
1653
+ return result;
1654
+ } catch (error) {
1655
+ return createErrorResponse(error, DataOperationErrorMessages.RetrieveFailed);
1656
+ }
1657
+ }
1658
+ /**
1659
+ * Retrieves multiple records from the specified table
1660
+ */
1661
+ async retrieveMultipleRecordsAsync(tableName, options) {
1662
+ try {
1663
+ const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1664
+ const requestUrl = await this._buildTableUrl(tableName, connectionReference, convertOptionsToQueryString(options), false);
1665
+ const result = await dataClient.retrieveDataAsync(
1666
+ requestUrl,
1667
+ connectionReference.apiId,
1668
+ tableName,
1669
+ HttpMethod.GET,
1670
+ void 0,
1671
+ // body
1672
+ { operationName: ConnectorOperationName.RetrieveMultipleRecords }
1673
+ );
1674
+ return result;
1675
+ } catch (error) {
1676
+ return createErrorResponse(error, DataOperationErrorMessages.RetrieveMultipleFailed);
1677
+ }
1678
+ }
1679
+ /**
1680
+ * Executes a custom operation on the data source
1681
+ */
1682
+ async executeAsync(operation) {
1683
+ try {
1684
+ if (!operation?.connectorOperation) {
1685
+ throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingConnectorOperation}`);
1686
+ }
1687
+ const tableName = operation.connectorOperation.tableName;
1688
+ const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1689
+ const { dataClient, connectionReference } = await this._getClientsAndConnection(tableName);
1690
+ const config = await this._getOperationConfig(operation, connectionReference, tableName);
1691
+ const requestUrl = await this._buildOperationUrl(operation, config);
1692
+ const bodyParam = await this._buildOperationBody(operation, tableName);
1693
+ const headers = await this._buildOperationHeader(operation, tableName);
1694
+ const httpMethod = this._getHttpMethod(requestUrl, dataSourceInfo, operation.connectorOperation.operationName);
1695
+ const responseInfo = dataSourceInfo.apis[operation.connectorOperation.operationName]?.responseInfo;
1696
+ const result = await dataClient.retrieveDataAsync(requestUrl, config.apiId, tableName, httpMethod, headers, bodyParam, {
1697
+ isExecuteAsync: true,
1698
+ // Use the connector operation name for telemetry, may be a better idea to use executeAsync
1699
+ // here and just log the connector operation name in the custom dimensions leaving comment for PR.
1700
+ operationName: `connectorDataOperation.${operation.connectorOperation.operationName}`,
1701
+ responseInfo
1702
+ });
1703
+ return result;
1704
+ } catch (error) {
1705
+ return createErrorResponse(error, DataOperationErrorMessages.ExecuteFailed);
1706
+ }
1707
+ }
1708
+ // =====================================
1709
+ // Private Methods
1710
+ // =====================================
1711
+ /**
1712
+ * Determines the appropriate HTTP method for a request
1713
+ * @param requestUrl - The URL for the request
1714
+ * @param dataSourceInfo - The data source information
1715
+ * @param operation - The operation name
1716
+ * @returns The HTTP method to use
1717
+ */
1718
+ _getHttpMethod(requestUrl, dataSourceInfo, operation) {
1719
+ const isSqlStoredProcedure = requestUrl.indexOf("apim/sql") > -1;
1720
+ if (isSqlStoredProcedure) {
1721
+ return HttpMethod.POST;
1722
+ }
1723
+ const method = dataSourceInfo.apis[operation]?.method;
1724
+ if (method) {
1725
+ return method;
1726
+ }
1727
+ return HttpMethod.GET;
1728
+ }
1729
+ /**
1730
+ * Builds the operation body parameters
1731
+ */
1732
+ async _buildOperationBody(operation, tableName) {
1733
+ const operationName = operation?.connectorOperation?.operationName;
1734
+ if (operationName) {
1735
+ const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1736
+ const hasBodyParameter = dataSourceInfo?.apis?.[operationName]?.parameters?.some((param) => param.in === "body");
1737
+ if (hasBodyParameter) {
1738
+ return await this._buildOperationBodyParam(operation, tableName);
1739
+ }
1740
+ }
1741
+ return void 0;
1742
+ }
1743
+ /**
1744
+ * Builds operation body parameters from the operation and data source info
1745
+ */
1746
+ async _buildOperationBodyParam(operation, tableName) {
1747
+ const operationName = operation.connectorOperation?.operationName;
1748
+ if (!operationName) {
1749
+ return "{}";
1750
+ }
1751
+ const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1752
+ const apiParams = dataSourceInfo?.apis?.[operationName]?.parameters || [];
1753
+ const rawParams = operation.connectorOperation?.parameters || [];
1754
+ if (typeof rawParams !== "object" || rawParams === null) {
1755
+ return "{}";
1756
+ }
1757
+ const bodyParam = apiParams.find((param) => param.in === "body");
1758
+ if (bodyParam) {
1759
+ const value = rawParams[bodyParam.name];
1760
+ if (value !== void 0 && value !== null) {
1761
+ return JSON.stringify(value);
1762
+ }
1763
+ }
1764
+ return "{}";
1765
+ }
1766
+ /**
1767
+ * Builds the operation header for a given data operation if required.
1768
+ *
1769
+ * @template TRequest - The type of the request payload for the data operation.
1770
+ * @param dataOperationRequest - The data operation containing details about the connector operation.
1771
+ * @param tableName - The name of the table associated with the data operation.
1772
+ * @returns A promise that resolves to the operation header as a string if a header parameter is required,
1773
+ * or `undefined` if no header parameter is needed.
1774
+ */
1775
+ async _buildOperationHeader(dataOperationRequest, tableName) {
1776
+ const operationName = dataOperationRequest.connectorOperation?.operationName;
1777
+ if (operationName) {
1778
+ const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1779
+ const hasHeaderParameter = dataSourceInfo?.apis?.[operationName]?.parameters?.some((param) => param.in === "header");
1780
+ if (hasHeaderParameter) {
1781
+ return await this._buildOperationHeaderParam(dataOperationRequest, tableName);
1782
+ }
1783
+ }
1784
+ return void 0;
1785
+ }
1786
+ /**
1787
+ * Builds the operation header parameters as a JSON string for a given data operation.
1788
+ *
1789
+ * @template TRequest - The type of the request object for the data operation.
1790
+ * @param dataOperationRequest - The data operation containing connector operation details and parameters.
1791
+ * @param tableName - The name of the table associated with the data operation.
1792
+ * @returns A promise that resolves to a JSON string representing the header parameters,
1793
+ * or `undefined` if no `header` parameters are available.
1794
+ */
1795
+ async _buildOperationHeaderParam(dataOperationRequest, tableName) {
1796
+ const operationName = dataOperationRequest.connectorOperation?.operationName;
1797
+ if (!operationName) {
1798
+ return {};
1799
+ }
1800
+ const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1801
+ const apiParamSpec = dataSourceInfo?.apis?.[operationName]?.parameters || [];
1802
+ const inputParams = dataOperationRequest.connectorOperation?.parameters;
1803
+ const headers = {};
1804
+ if (!inputParams) {
1805
+ return void 0;
1806
+ }
1807
+ if (typeof inputParams === "string") {
1808
+ if (apiParamSpec.length === 1 && apiParamSpec[0].in === "header") {
1809
+ headers[apiParamSpec[0].name] = inputParams;
1810
+ }
1811
+ }
1812
+ if (typeof inputParams === "object" && !Array.isArray(inputParams)) {
1813
+ apiParamSpec.forEach((param) => {
1814
+ if (param.in === "header" && param.name in inputParams) {
1815
+ headers[param.name] = inputParams[param.name];
1816
+ }
1817
+ });
1818
+ }
1819
+ if (Array.isArray(inputParams)) {
1820
+ apiParamSpec.forEach((param, index) => {
1821
+ if (param.in === "header" && inputParams[index] !== void 0) {
1822
+ headers[param.name] = inputParams[index];
1823
+ }
1824
+ });
1825
+ }
1826
+ return headers;
1827
+ }
1828
+ /**
1829
+ * Constructs the request URL for table operations
1830
+ * @param tableName - The name of the table
1831
+ * @param connectionReference - The connection reference
1832
+ * @param options - Optional URL parameters
1833
+ * @param encodeOptions - Whether to encode the options
1834
+ * @returns The constructed URL
1835
+ */
1836
+ async _buildTableUrl(tableName, connectionReference, options = "", encodeOptions = true) {
1837
+ const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
1838
+ const isSharedSql = (connectionReference.apiId ?? "").indexOf("shared_sql") > -1;
1839
+ const isSharePoint = (connectionReference.apiId ?? "").indexOf("shared_sharepointonline") > -1;
1840
+ const urlBuilder = {
1841
+ runtimeUrl: connectionReference.runtimeUrl ?? "",
1842
+ connectionName: connectionReference.connectionName ?? "",
1843
+ datasetName: connectionReference.datasetName ? isSharedSql ? connectionReference.datasetNameOverride : isSharePoint ? encodeURIComponent(encodeURIComponent(connectionReference.datasetName)) : encodeURIComponent(connectionReference.datasetName) : "",
1844
+ tableId: isSharedSql ? encodeURIComponent(encodeURIComponent(dataSourceInfo.tableId)) : dataSourceInfo.tableId,
1845
+ version: dataSourceInfo.version,
1846
+ isSharedSql
1847
+ };
1848
+ return this._constructUrl(urlBuilder, options, encodeOptions);
1849
+ }
1850
+ /**
1851
+ * Builds the operation URL
1852
+ */
1853
+ async _buildOperationUrl(operation, config) {
1854
+ const operationName = operation.connectorOperation?.operationName;
1855
+ if (!operationName) {
1856
+ throw new Error(`${DataOperationErrorMessages.InvalidOperationParameters}: ${DataOperationErrorMessages.MissingOperationName}`);
1857
+ }
1858
+ const dataSourceInfo = await this._connectionsService.getDataSource(config.tableName);
1859
+ const isSharedSql = (config.apiId ?? "").indexOf("shared_sql") > -1;
1860
+ const path = dataSourceInfo.apis[operationName].path;
1861
+ if (isSharedSql) {
1862
+ return this._buildSharedSqlOperationUrl(config, path);
1863
+ }
1864
+ return this._buildStandardOperationUrl(operation, config, operationName, path);
1865
+ }
1866
+ /**
1867
+ * Gets the connection references
1868
+ */
1869
+ async _getConnectionReferencesAsync() {
1870
+ if (this._connectionReferences) {
1871
+ return this._connectionReferences;
1872
+ }
1873
+ const metadataClient = await this._getMetadataClient();
1874
+ const response = await metadataClient.getAppConnectionConfigsAsync();
1875
+ this._connectionReferences = response.data;
1876
+ return this._connectionReferences;
1877
+ }
1878
+ /**
1879
+ * Gets the database references
1880
+ */
1881
+ async _getDatabaseReferencesAsync() {
1882
+ if (this._databaseReferences) {
1883
+ return this._databaseReferences;
1884
+ }
1885
+ const metadataClient = await this._getMetadataClient();
1886
+ const response = await metadataClient.getAppDataSourceConfigsAsync();
1887
+ this._databaseReferences = response.data;
1888
+ return this._databaseReferences;
1889
+ }
1890
+ /**
1891
+ * Gets the metadata client instance
1892
+ */
1893
+ async _getMetadataClient() {
1894
+ const metadataClient = await this._clientProvider.getMetadataClientAsync();
1895
+ if (!metadataClient) {
1896
+ throw new PowerDataRuntimeError(ErrorCodes.MetadataClientNotAvailable);
1897
+ }
1898
+ return metadataClient;
1899
+ }
1900
+ /**
1901
+ * Gets the connection reference for a table
1902
+ */
1903
+ _getConnectionReference(tableName) {
1904
+ const connectionReference = this._connectionReferences?.[tableName];
1905
+ if (!connectionReference) {
1906
+ throw new PowerDataRuntimeError(ErrorCodes.ConnectionReferenceNotFound, tableName);
1907
+ }
1908
+ return connectionReference;
1909
+ }
1910
+ /**
1911
+ * Gets both the data client and connection reference
1912
+ */
1913
+ async _getClientsAndConnection(tableName) {
1914
+ await this._getReferences();
1915
+ const dataClient = await this._clientProvider.getDataClientAsync();
1916
+ if (!dataClient) {
1917
+ throw new PowerDataRuntimeError(ErrorCodes.DataClientNotAvailable);
1918
+ }
1919
+ const connectionReference = this._getConnectionReference(tableName);
1920
+ return { dataClient, connectionReference };
1921
+ }
1922
+ /**
1923
+ * Builds the URL for shared SQL operations
1924
+ */
1925
+ _buildSharedSqlOperationUrl(config, path) {
1926
+ const version = config.version ? `/${config.version}/` : "/";
1927
+ return `${config.runtimeUrl}/${config.connectionName}${version}datasets/${config.datasetName}/procedures${path}`;
1928
+ }
1929
+ /**
1930
+ * Builds the URL for standard operations
1931
+ * Assumptions / Invariants:
1932
+ * - The connector always defines a required path parameter for the connection id named 'connectionId'.
1933
+ * - When a dataset is applicable, the parameter name is 'dataset'.
1934
+ * - When a table is applicable, the parameter name is 'tableName'.
1935
+ * - A lone string parameter maps to the first remaining (non-synthetic) required API parameter.
1936
+ * - Array parameters map positionally to the remaining API parameters after filtering.
1937
+ * - Object parameters map by (case-insensitive, hyphen/underscore agnostic) key.
1938
+ * @param operation - The data operation containing connector operation details from runtime
1939
+ * @param config - The connector operation configuration
1940
+ * @param operationName - The name of the operation to be performed
1941
+ * @param path - The path template for the operation
1942
+ */
1943
+ async _buildStandardOperationUrl(operation, config, operationName, path) {
1944
+ const dataSourceInfo = await this._connectionsService.getDataSource(config.tableName);
1945
+ let apiParams = dataSourceInfo.apis[operationName]?.parameters || [];
1946
+ if (apiParams.length > 0) {
1947
+ apiParams = apiParams.filter((param) => param.name !== "connectionId" && param.name !== "dataset" && param.name !== "tableName");
1948
+ }
1949
+ const operationParams = operation.connectorOperation?.parameters;
1950
+ const rawParamValues = {
1951
+ connectionId: config.connectionName,
1952
+ dataset: (
1953
+ // The dataset name needs to be double encoded for sharepoint, once here and then once in the HTTP pipeline
1954
+ // CRUD operations already handle this, so we need to do the same here
1955
+ config.apiId.indexOf("shared_sharepointonline") !== -1 && config.datasetName ? encodeURIComponent(config.datasetName) : config.datasetName
1956
+ ),
1957
+ tableName: config.tableName
1958
+ };
1959
+ if (operationParams !== void 0) {
1960
+ if (typeof operationParams === "string") {
1961
+ if (apiParams.length > 0) {
1962
+ const requiredParams = apiParams.filter((param) => param.required);
1963
+ rawParamValues[requiredParams?.[0]?.name ?? apiParams[0].name] = operationParams;
1964
+ }
1965
+ } else if (typeof operationParams === "object" && !Array.isArray(operationParams)) {
1966
+ apiParams.forEach((param) => {
1967
+ if (operationParams) {
1968
+ const value = this._getNormalizedParamValue(operationParams, param.name);
1969
+ if (value !== void 0) {
1970
+ rawParamValues[param.name] = value;
1971
+ }
1972
+ }
1973
+ });
1974
+ } else if (Array.isArray(operationParams)) {
1975
+ apiParams.forEach((param, index) => {
1976
+ rawParamValues[param.name] = operationParams[index];
1977
+ });
1978
+ }
1979
+ }
1980
+ const { processedPath, queryParams } = this._processParameters(
1981
+ // deliberately pass the unfiltered list to _processParameters so path placeholders still see synthetic params.
1982
+ dataSourceInfo.apis[operationName]?.parameters || [],
1983
+ rawParamValues,
1984
+ path
1985
+ );
1986
+ const separator = queryParams ? processedPath.includes("?") ? "&" : "?" : "";
1987
+ return `${config.runtimeUrl}${processedPath}${separator}${queryParams}`;
1988
+ }
1989
+ /**
1990
+ * Normalizes the parameter name by replacing hyphens with underscores and performs case-insensitive matching
1991
+ */
1992
+ _getNormalizedParamValue(obj, paramName) {
1993
+ const normalizedParamName = paramName.replace(/-/g, "_").toLowerCase();
1994
+ const foundKey = Object.keys(obj).find((key) => key.replace(/-/g, "_").toLowerCase() === normalizedParamName);
1995
+ return foundKey !== void 0 ? obj[foundKey] : void 0;
1996
+ }
1997
+ /**
1998
+ * Processes operation parameters into path and query parameters
1999
+ * @param apiParams - The API parameter specifications from the data source info
2000
+ * @param rawParamValues - The raw parameter values provided in the operation at runtime
2001
+ * @param path - The initial path template
2002
+ * @returns An object containing the processed path and query parameters
2003
+ */
2004
+ _processParameters(apiParams, rawParamValues, path) {
2005
+ const usedParams = /* @__PURE__ */ new Set();
2006
+ let processedPath = path;
2007
+ const queryParams = [];
2008
+ apiParams.forEach((param, index) => {
2009
+ const paramValue = rawParamValues[param.name];
2010
+ if (paramValue === void 0) {
2011
+ return;
2012
+ }
2013
+ if (param.in === "path") {
2014
+ const placeholder = `{${param.name}}`;
2015
+ if (processedPath.includes(placeholder)) {
2016
+ processedPath = processedPath.replace(placeholder, encodeURIComponent(String(paramValue)));
2017
+ usedParams.add(param.name);
2018
+ }
2019
+ } else if (param.in === "query") {
2020
+ queryParams.push(`${encodeURIComponent(param.name)}=${encodeURIComponent(String(paramValue))}`);
2021
+ usedParams.add(param.name);
2022
+ }
2023
+ });
2024
+ return {
2025
+ processedPath,
2026
+ queryParams: queryParams.join("&")
2027
+ };
2028
+ }
2029
+ /**
2030
+ * Gets the operation configuration
2031
+ */
2032
+ async _getOperationConfig(operation, connectionReference, tableName) {
2033
+ if (!operation.connectorOperation) {
2034
+ throw new Error(`${DataOperationErrorMessages.InvalidRequest}: ${DataOperationErrorMessages.MissingConnectorOperation}`);
2035
+ }
2036
+ const dataSourceInfo = await this._connectionsService.getDataSource(tableName);
2037
+ const config = {
2038
+ tableName,
2039
+ apiId: connectionReference.apiId ?? "",
2040
+ runtimeUrl: connectionReference.runtimeUrl ?? "",
2041
+ connectionName: connectionReference.connectionName ?? "",
2042
+ datasetName: connectionReference.datasetName ?? "",
2043
+ tableId: dataSourceInfo.tableId,
2044
+ version: dataSourceInfo.version
2045
+ };
2046
+ return config;
2047
+ }
2048
+ /**
2049
+ * Initializes the clients
2050
+ */
2051
+ async _getReferences() {
2052
+ await this._getConnectionReferencesAsync();
2053
+ await this._getDatabaseReferencesAsync();
2054
+ }
2055
+ /**
2056
+ * Validates constructor parameters
2057
+ */
2058
+ _validateConstructorParams(clientProvider, connectionsService) {
2059
+ if (!clientProvider) {
2060
+ throw new PowerDataRuntimeError(ErrorCodes.ClientProviderNotAvailable);
2061
+ }
2062
+ if (!connectionsService) {
2063
+ throw new PowerDataRuntimeError(ErrorCodes.DataSourceServiceNotAvailable);
2064
+ }
2065
+ }
2066
+ /**
2067
+ * Constructs the final URL
2068
+ */
2069
+ _constructUrl(urlBuilder, options = "", encodeOptions = true) {
2070
+ const apiVersion = urlBuilder.version ? `/${urlBuilder.version}/` : "/";
2071
+ const encodedOptions = encodeOptions && options ? options.charAt(0) + encodeURIComponent(options.slice(1)) : options;
2072
+ if (urlBuilder.datasetName) {
2073
+ return `${urlBuilder.runtimeUrl}/${urlBuilder.connectionName}${apiVersion}datasets/${urlBuilder.datasetName}/tables/${urlBuilder.tableId}/items${encodedOptions}`;
2074
+ }
2075
+ return `${urlBuilder.runtimeUrl}/${urlBuilder.connectionName}/tables/${urlBuilder.tableId}/items${encodedOptions}`;
2076
+ }
2077
+ };
2078
+
2079
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/metadata/runtimeDataSourceService.js
2080
+ var DataSourceServiceError;
2081
+ /* @__PURE__ */ (function(DataSourceServiceError2) {
2082
+ })(DataSourceServiceError || (DataSourceServiceError = {}));
2083
+ var RuntimeDataSourceService = class {
2084
+ /**
2085
+ * Creates a new instance of RuntimeDataSourceService
2086
+ */
2087
+ constructor(_powerDataSourcesInfoProvider) {
2088
+ __publicField(this, "_powerDataSourcesInfoProvider");
2089
+ /**
2090
+ * Data source information
2091
+ */
2092
+ __publicField(this, "_dataSourcesInfo");
2093
+ /**
2094
+ * Indicates whether the service has been initialized
2095
+ */
2096
+ __publicField(this, "_isInitialized");
2097
+ this._powerDataSourcesInfoProvider = _powerDataSourcesInfoProvider;
2098
+ this._dataSourcesInfo = {};
2099
+ this._isInitialized = false;
2100
+ }
2101
+ /**
2102
+ * Initializes the service by loading user data sources
2103
+ * @throws PowerDataRuntimeError if initialization fails
2104
+ */
2105
+ async initialize() {
2106
+ try {
2107
+ const userDataSources = await this._getUserDataSources();
2108
+ this._dataSourcesInfo = {};
2109
+ Object.keys(userDataSources).forEach((key) => {
2110
+ this._dataSourcesInfo[key] = userDataSources[key];
2111
+ });
2112
+ this._isInitialized = true;
2113
+ } catch (error) {
2114
+ throw new PowerDataRuntimeError(ErrorCodes.InitializationError, getErrorMessage(error));
2115
+ }
2116
+ }
2117
+ /**
2118
+ * Gets all user data sources
2119
+ * @returns Array of data source information
2120
+ * @throws PowerDataRuntimeError if service is not initialized
2121
+ */
2122
+ async getUserDataSources() {
2123
+ await this._ensureInitialized();
2124
+ return this._dataSourcesInfo;
2125
+ }
2126
+ /**
2127
+ * Gets information for a specific data source
2128
+ * @param dataSource - The ID of the data source
2129
+ * @returns Data source information
2130
+ * @throws PowerDataRuntimeError if data source is not found or service is not initialized
2131
+ */
2132
+ async getDataSource(dataSource) {
2133
+ await this._ensureInitialized();
2134
+ const dataSourceInfo = this._dataSourcesInfo[dataSource];
2135
+ if (!dataSourceInfo) {
2136
+ const errorMessage = `Unable to find data source: ${dataSource} in data sources info.`;
2137
+ throw new PowerDataRuntimeError(ErrorCodes.DataSourceNotFound, errorMessage);
2138
+ }
2139
+ return dataSourceInfo;
2140
+ }
2141
+ /**
2142
+ * Checks if a data source exists
2143
+ * @param dataSourceId - The ID of the data source to check
2144
+ * @returns True if the data source exists, false otherwise
2145
+ * @throws PowerDataRuntimeError if service is not initialized
2146
+ */
2147
+ async hasDataSource(dataSource) {
2148
+ await this._ensureInitialized();
2149
+ return dataSource in this._dataSourcesInfo;
2150
+ }
2151
+ /**
2152
+ * Ensures the service is initialized
2153
+ * @throws PowerDataRuntimeError if service is not initialized
2154
+ */
2155
+ async _ensureInitialized() {
2156
+ if (!this._isInitialized) {
2157
+ await this.initialize();
2158
+ }
2159
+ }
2160
+ /**
2161
+ * Gets user data sources from the provided data source schemas
2162
+ * @returns Promise resolving to array of data source information
2163
+ */
2164
+ async _getUserDataSources() {
2165
+ const dataSourcesInfo = await this._powerDataSourcesInfoProvider.getDataSourcesInfo();
2166
+ return Promise.resolve(dataSourcesInfo);
2167
+ }
2168
+ };
2169
+
2170
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/powerDataRuntime.js
2171
+ var PowerDataRuntime = class {
2172
+ /**
2173
+ * Creates a new instance of PowerDataRuntime
2174
+ * @param params - Initialization parameters
2175
+ * @throws DataRuntimeError if initialization fails
2176
+ */
2177
+ constructor(params) {
2178
+ __publicField(this, "_clientProvider");
2179
+ __publicField(this, "_dataSourceService");
2180
+ __publicField(this, "_dataOperations");
2181
+ __publicField(this, "_metadataOperations");
2182
+ __publicField(this, "_isInitialized");
2183
+ try {
2184
+ Log.createInstance(params.powerOperationExecutor);
2185
+ this._clientProvider = new RuntimeClientProvider(params.powerOperationExecutor);
2186
+ this._dataSourceService = new RuntimeDataSourceService(params.powerDataSourcesInfoProvider);
2187
+ this._isInitialized = false;
2188
+ this._initialize();
2189
+ } catch (error) {
2190
+ if (error instanceof Error) {
2191
+ Log.trackException(error);
2192
+ }
2193
+ throw error;
2194
+ }
2195
+ }
2196
+ /**
2197
+ * Gets the Data operations interface
2198
+ * @throws PowerDataRuntimeError if operations are not initialized
2199
+ */
2200
+ get Data() {
2201
+ this._ensureInitialized();
2202
+ if (!this._dataOperations) {
2203
+ this._dataOperations = this._createDataOperations();
2204
+ }
2205
+ return this._dataOperations;
2206
+ }
2207
+ /**
2208
+ * Gets the Metadata operations interface
2209
+ * @throws PowerDataRuntimeError if operations are not initialized
2210
+ */
2211
+ get Metadata() {
2212
+ this._ensureInitialized();
2213
+ if (!this._metadataOperations) {
2214
+ this._metadataOperations = this._createMetadataOperations();
2215
+ }
2216
+ return this._metadataOperations;
2217
+ }
2218
+ /**
2219
+ * Ensures the PowerDataRuntime is initialized
2220
+ * @throws PowerDataRuntimeError if not initialized
2221
+ */
2222
+ _ensureInitialized() {
2223
+ if (!this._isInitialized) {
2224
+ throw new PowerDataRuntimeError(ErrorCodes.OperationsNotInitialized);
2225
+ }
2226
+ }
2227
+ /**
2228
+ * Initializes the PowerDataRuntime components
2229
+ * @throws PowerDataRuntimeError if initialization fails
2230
+ */
2231
+ _initialize() {
2232
+ try {
2233
+ this._dataOperations = this._createDataOperations();
2234
+ this._metadataOperations = this._createMetadataOperations();
2235
+ this._isInitialized = true;
2236
+ } catch (error) {
2237
+ throw new PowerDataRuntimeError(ErrorCodes.InitializationFailed, getErrorMessage(error));
2238
+ }
2239
+ }
2240
+ /**
2241
+ * Creates a new instance of DataOperations
2242
+ */
2243
+ _createDataOperations() {
2244
+ const dataverseOperation = new DataverseDataOperationExecutor(this._clientProvider);
2245
+ const connectorOperation = new ConnectorDataOperationExecutor(this._clientProvider, this._dataSourceService);
2246
+ return new DefaultDataOperationOrchestrator(dataverseOperation, connectorOperation, this._dataSourceService);
2247
+ }
2248
+ /**
2249
+ * Creates a new instance of MetadataOperations
2250
+ */
2251
+ _createMetadataOperations() {
2252
+ return new RuntimeMetadataOperations(this._clientProvider);
2253
+ }
2254
+ };
2255
+
2256
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/powerDataRuntimeInstance.js
2257
+ var powerDataRuntimeInstance;
2258
+ function getPowerDataRuntime(powerDataSourcesInfoProvider, powerOperationExecutor) {
2259
+ if (!powerDataRuntimeInstance) {
2260
+ powerDataRuntimeInstance = new PowerDataRuntime({
2261
+ powerDataSourcesInfoProvider,
2262
+ powerOperationExecutor
2263
+ });
2264
+ }
2265
+ return powerDataRuntimeInstance;
2266
+ }
2267
+
2268
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/powerDataSourcesInfoProvider.js
2269
+ var _PowerDataSourcesInfoProvider = class _PowerDataSourcesInfoProvider {
2270
+ /**
2271
+ * Private constructor to enforce the singleton pattern.
2272
+ * @param dataSourcesInfo The data sources information to initialize the provider with.
2273
+ */
2274
+ constructor(dataSourcesInfo) {
2275
+ __publicField(this, "dataSourcesInfo");
2276
+ this.dataSourcesInfo = dataSourcesInfo;
2277
+ }
2278
+ /**
2279
+ * Retrieves the singleton instance of PowerDataSourcesInfoProvider.
2280
+ * If the instance does not exist, it initializes it with the provided data sources info.
2281
+ *
2282
+ * @param dataSourcesInfo Optional parameter to initialize the instance if it doesn't exist.
2283
+ * @returns The singleton instance of PowerDataSourcesInfoProvider.
2284
+ * @throws Error if the instance is not initialized and no dataSourcesInfo is provided.
2285
+ */
2286
+ static getInstance(dataSourcesInfo) {
2287
+ if (!this.instance) {
2288
+ if (!dataSourcesInfo) {
2289
+ throw new PowerDataRuntimeError(ErrorCodes.DataSourcesInfoNotFound);
2290
+ }
2291
+ this.instance = new _PowerDataSourcesInfoProvider(dataSourcesInfo);
2292
+ }
2293
+ return this.instance;
2294
+ }
2295
+ /**
2296
+ * Retrieves the data sources information.
2297
+ *
2298
+ * @returns A promise resolving to the data sources information.
2299
+ */
2300
+ async getDataSourcesInfo() {
2301
+ return this.dataSourcesInfo;
2302
+ }
2303
+ };
2304
+ __publicField(_PowerDataSourcesInfoProvider, "instance", null);
2305
+ var PowerDataSourcesInfoProvider = _PowerDataSourcesInfoProvider;
2306
+ var powerDataSourcesInfoProvider_default = PowerDataSourcesInfoProvider;
2307
+
2308
+ // node_modules/@microsoft/power-apps/lib/internal/plugins/DefaultPowerAppsBridge.js
2309
+ var DefaultPowerAppsBridge = class {
2310
+ constructor() {
2311
+ __publicField(this, "_antiCSRFToken");
2312
+ __publicField(this, "_callbacks", {});
2313
+ __publicField(this, "_currentCallbackId", 0);
2314
+ __publicField(this, "_instanceId", Date.now().toString());
2315
+ __publicField(this, "_messageChannel", new window.MessageChannel());
2316
+ __publicField(this, "_postMessageQueue", []);
2317
+ __publicField(this, "_postMessageSource");
2318
+ __publicField(this, "_handleMessageEvent", (messageEvent) => {
2319
+ const message = messageEvent.data;
2320
+ if (message && typeof message.isPluginCall === "boolean") {
2321
+ if (message.isPluginCall) {
2322
+ const callbackId = message.callbackId;
2323
+ const status = message.status;
2324
+ const args = message.args;
2325
+ const keepCallback = message.keepCallback;
2326
+ try {
2327
+ const callback = this._callbacks[callbackId];
2328
+ if (keepCallback) {
2329
+ if (callback && callback.onUpdate) {
2330
+ callback.onUpdate(message.args?.[0]);
2331
+ }
2332
+ } else {
2333
+ if (callback) {
2334
+ if (status === 1) {
2335
+ callback.resolve(args[0]);
2336
+ } else if (status !== 0) {
2337
+ callback.reject(args);
2338
+ }
2339
+ }
2340
+ if (!keepCallback) {
2341
+ delete this._callbacks[callbackId];
2342
+ }
2343
+ }
2344
+ } catch (error) {
2345
+ console.error(error);
2346
+ }
2347
+ }
2348
+ } else if (message && message.messageType === "initCommunication") {
2349
+ this._antiCSRFToken = message.antiCSRFToken;
2350
+ this._postMessageSource = this._messageChannel.port1;
2351
+ if (this._postMessageSource) {
2352
+ for (let i = 0; i < this._postMessageQueue.length; i++) {
2353
+ this._postMessageQueue[i].antiCSRFToken = this._antiCSRFToken;
2354
+ this._postMessageSource.postMessage(this._postMessageQueue[i]);
2355
+ }
2356
+ }
2357
+ }
2358
+ });
2359
+ }
2360
+ async initialize() {
2361
+ this._messageChannel.port1.onmessage = this._handleMessageEvent;
2362
+ window.parent.postMessage({
2363
+ messageType: "initCommunicationWithPort",
2364
+ instanceId: this._instanceId
2365
+ }, "*", [this._messageChannel.port2]);
2366
+ }
2367
+ async executePluginAsync(pluginName, pluginAction, params = [], onUpdate) {
2368
+ return new Promise((resolve, reject) => {
2369
+ const callbackId = this._getCallbackId(pluginName);
2370
+ this._callbacks[callbackId] = { resolve, reject, onUpdate };
2371
+ this._sendMessage({
2372
+ isPluginCall: true,
2373
+ callbackId,
2374
+ service: pluginName,
2375
+ action: pluginAction,
2376
+ actionArgs: params,
2377
+ antiCSRFToken: this._antiCSRFToken
2378
+ });
2379
+ });
2380
+ }
2381
+ _sendMessage(message) {
2382
+ if (!this._postMessageSource) {
2383
+ this._postMessageQueue.push(message);
2384
+ } else {
2385
+ this._postMessageSource.postMessage(message);
2386
+ }
2387
+ }
2388
+ _getCallbackId(pluginName) {
2389
+ return "instanceId=" + this._instanceId + "_" + pluginName + this._currentCallbackId++;
2390
+ }
2391
+ };
2392
+
2393
+ // node_modules/@microsoft/power-apps/lib/internal/plugins/PluginBridge.js
2394
+ var bridgePromise;
2395
+ async function executePluginAsync(pluginName, pluginAction, params = [], update) {
2396
+ const powerAppsBridge = await getBridge();
2397
+ return powerAppsBridge.executePluginAsync(pluginName, pluginAction, params, update);
2398
+ }
2399
+ async function getBridge() {
2400
+ if (!bridgePromise) {
2401
+ bridgePromise = new Promise(async (resolve, reject) => {
2402
+ try {
2403
+ const bridge = window && window.powerAppsBridge ? window.powerAppsBridge : new DefaultPowerAppsBridge();
2404
+ await bridge.initialize();
2405
+ resolve(bridge);
2406
+ } catch (error) {
2407
+ reject(error);
2408
+ }
2409
+ });
2410
+ }
2411
+ return bridgePromise;
2412
+ }
2413
+
2414
+ // node_modules/@microsoft/power-apps/lib/internal/data/ConnectionUtils.js
2415
+ var connectionsLoaded = false;
2416
+ async function loadConnections() {
2417
+ if (connectionsLoaded) {
2418
+ return;
2419
+ }
2420
+ connectionsLoaded = true;
2421
+ await loadNonCompositeConnectionsAsync();
2422
+ await resolveCompositeConnectionsAsync();
2423
+ }
2424
+ async function loadNonCompositeConnectionsAsync() {
2425
+ return executePluginAsync("AppPowerAppsClientPlugin", "loadNonCompositeConnectionsAsync", []);
2426
+ }
2427
+ async function resolveCompositeConnectionsAsync() {
2428
+ return executePluginAsync("AppPowerAppsClientPlugin", "resolveCompositeConnectionsAsync", []);
2429
+ }
2430
+
2431
+ // node_modules/@microsoft/power-apps/lib/internal/data/OperationExecutor.js
2432
+ var loadConnectionsPromise;
2433
+ var OperationExecutor = class {
2434
+ /**
2435
+ * Executes an operation using the plugin.
2436
+ * @param operationName The name of the operation.
2437
+ * @param action The action to perform.
2438
+ * @param params The parameters for the operation.
2439
+ * @returns A promise resolving to the operation result.
2440
+ */
2441
+ async execute(operationName, action, params) {
2442
+ try {
2443
+ if (!loadConnectionsPromise) {
2444
+ loadConnectionsPromise = loadConnections();
2445
+ }
2446
+ await loadConnectionsPromise;
2447
+ const result = await executePluginAsync(operationName, action, params);
2448
+ return {
2449
+ success: true,
2450
+ data: result
2451
+ };
2452
+ } catch (error) {
2453
+ throw error;
2454
+ }
2455
+ }
2456
+ };
2457
+
2458
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/runtime/getRuntimeContext.js
2459
+ var _executor;
2460
+ function getExecutor() {
2461
+ if (!_executor) {
2462
+ _executor = new OperationExecutor();
2463
+ }
2464
+ return _executor;
2465
+ }
2466
+ async function getPowerSdkInstance(dataSourcesInfo) {
2467
+ const executor = getExecutor();
2468
+ const provider = powerDataSourcesInfoProvider_default.getInstance(dataSourcesInfo);
2469
+ return getPowerDataRuntime(provider, executor);
2470
+ }
2471
+
2472
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/api/createRecord.js
2473
+ async function createRecordAsync(dataSourcesInfo, tableName, record) {
2474
+ return await (await getPowerSdkInstance(dataSourcesInfo)).Data.createRecordAsync(tableName, record);
2475
+ }
2476
+
2477
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/api/updateRecord.js
2478
+ async function updateRecordAsync(dataSourcesInfo, tableName, recordId, changes) {
2479
+ return await (await getPowerSdkInstance(dataSourcesInfo)).Data.updateRecordAsync(tableName, recordId, changes);
2480
+ }
2481
+
2482
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/api/deleteRecord.js
2483
+ async function deleteRecordAsync(dataSourcesInfo, tableName, recordId) {
2484
+ return await (await getPowerSdkInstance(dataSourcesInfo)).Data.deleteRecordAsync(tableName, recordId);
2485
+ }
2486
+
2487
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/api/retrieveRecord.js
2488
+ async function retrieveRecordAsync(dataSourcesInfo, tableName, recordId, options) {
2489
+ return await (await getPowerSdkInstance(dataSourcesInfo)).Data.retrieveRecordAsync(tableName, recordId, options);
2490
+ }
2491
+
2492
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/api/retrieveMultipleRecords.js
2493
+ async function retrieveMultipleRecordsAsync(dataSourcesInfo, tableName, options) {
2494
+ return await (await getPowerSdkInstance(dataSourcesInfo)).Data.retrieveMultipleRecordsAsync(tableName, options);
2495
+ }
2496
+
2497
+ // node_modules/@microsoft/power-apps/lib/internal/data/core/api/execute.js
2498
+ async function executeAsync(dataSourcesInfo, operation) {
2499
+ return await (await getPowerSdkInstance(dataSourcesInfo)).Data.executeAsync(operation);
2500
+ }
2501
+
2502
+ // node_modules/@microsoft/power-apps/lib/data/powerAppsData.js
2503
+ var _dataOperationExecutor;
2504
+ function getDataOperationExecutor() {
2505
+ return _dataOperationExecutor;
2506
+ }
2507
+ function getClient(dataSourcesInfo) {
2508
+ return {
2509
+ createRecordAsync: (tableName, record) => {
2510
+ return createRecordAsync(dataSourcesInfo, tableName, record);
2511
+ },
2512
+ deleteRecordAsync: (tableName, recordId) => {
2513
+ return deleteRecordAsync(dataSourcesInfo, tableName, recordId);
2514
+ },
2515
+ executeAsync: (operation) => {
2516
+ return executeAsync(dataSourcesInfo, operation);
2517
+ },
2518
+ retrieveMultipleRecordsAsync: (tableName, options) => {
2519
+ return retrieveMultipleRecordsAsync(dataSourcesInfo, tableName, options);
2520
+ },
2521
+ retrieveRecordAsync: (tableName, recordId, options) => {
2522
+ return retrieveRecordAsync(dataSourcesInfo, tableName, recordId, options);
2523
+ },
2524
+ updateRecordAsync: (tableName, recordId, changes) => {
2525
+ return updateRecordAsync(dataSourcesInfo, tableName, recordId, changes);
2526
+ }
2527
+ };
2528
+ }
2529
+ export {
2530
+ getClient
2531
+ };