@microsoft/power-apps-cli 0.9.1 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/README.md +81 -10
  2. package/dist/ArgumentProvider.d.ts +61 -0
  3. package/dist/ArgumentProvider.d.ts.map +1 -0
  4. package/dist/ArgumentProvider.js +247 -0
  5. package/dist/ArgumentProvider.js.map +1 -0
  6. package/dist/Authentication/NodeMsalAuthenticationProvider.d.ts +17 -0
  7. package/dist/Authentication/NodeMsalAuthenticationProvider.d.ts.map +1 -0
  8. package/dist/Authentication/NodeMsalAuthenticationProvider.js +91 -0
  9. package/dist/Authentication/NodeMsalAuthenticationProvider.js.map +1 -0
  10. package/dist/Authentication/PacCliAuthenticationProvider.d.ts +15 -0
  11. package/dist/Authentication/PacCliAuthenticationProvider.d.ts.map +1 -0
  12. package/dist/Authentication/PacCliAuthenticationProvider.js +51 -0
  13. package/dist/Authentication/PacCliAuthenticationProvider.js.map +1 -0
  14. package/dist/Authentication/ServicePrincipalAuthenticationProvider.d.ts +20 -0
  15. package/dist/Authentication/ServicePrincipalAuthenticationProvider.d.ts.map +1 -0
  16. package/dist/Authentication/ServicePrincipalAuthenticationProvider.js +51 -0
  17. package/dist/Authentication/ServicePrincipalAuthenticationProvider.js.map +1 -0
  18. package/dist/Bin.d.ts +6 -0
  19. package/dist/Bin.d.ts.map +1 -0
  20. package/dist/Bin.js +2 -3357
  21. package/dist/Bin.js.map +1 -0
  22. package/dist/Cli.d.ts +2 -0
  23. package/dist/Cli.d.ts.map +1 -0
  24. package/dist/Cli.js +131 -0
  25. package/dist/Cli.js.map +1 -0
  26. package/dist/CliSettings.d.ts +14 -0
  27. package/dist/CliSettings.d.ts.map +1 -0
  28. package/dist/CliSettings.js +70 -0
  29. package/dist/CliSettings.js.map +1 -0
  30. package/dist/CliUtils.d.ts +21 -0
  31. package/dist/CliUtils.d.ts.map +1 -0
  32. package/dist/CliUtils.js +92 -0
  33. package/dist/CliUtils.js.map +1 -0
  34. package/dist/Constants/HelpStrings.d.ts +168 -0
  35. package/dist/Constants/HelpStrings.d.ts.map +1 -0
  36. package/dist/Constants/HelpStrings.js +216 -0
  37. package/dist/Constants/HelpStrings.js.map +1 -0
  38. package/dist/Constants/VerbRegistry.d.ts +79 -0
  39. package/dist/Constants/VerbRegistry.d.ts.map +1 -0
  40. package/dist/Constants/VerbRegistry.js +46 -0
  41. package/dist/Constants/VerbRegistry.js.map +1 -0
  42. package/dist/Constants.d.ts +10 -0
  43. package/dist/Constants.d.ts.map +1 -0
  44. package/dist/Constants.js +12 -0
  45. package/dist/Constants.js.map +1 -0
  46. package/dist/Errors/CliError.d.ts +11 -0
  47. package/dist/Errors/CliError.d.ts.map +1 -0
  48. package/dist/Errors/CliError.js +16 -0
  49. package/dist/Errors/CliError.js.map +1 -0
  50. package/dist/FS/CliFs.d.ts +41 -0
  51. package/dist/FS/CliFs.d.ts.map +1 -0
  52. package/dist/FS/CliFs.js +136 -0
  53. package/dist/FS/CliFs.js.map +1 -0
  54. package/dist/HttpClient/CliHttpClient.d.ts +21 -0
  55. package/dist/HttpClient/CliHttpClient.d.ts.map +1 -0
  56. package/dist/HttpClient/CliHttpClient.js +118 -0
  57. package/dist/HttpClient/CliHttpClient.js.map +1 -0
  58. package/dist/Logger/CliLogger.d.ts +27 -0
  59. package/dist/Logger/CliLogger.d.ts.map +1 -0
  60. package/dist/Logger/CliLogger.js +222 -0
  61. package/dist/Logger/CliLogger.js.map +1 -0
  62. package/dist/Logger/ConsoleWriter.d.ts +15 -0
  63. package/dist/Logger/ConsoleWriter.d.ts.map +1 -0
  64. package/dist/Logger/ConsoleWriter.js +45 -0
  65. package/dist/Logger/ConsoleWriter.js.map +1 -0
  66. package/dist/Logger/Constants.d.ts +6 -0
  67. package/dist/Logger/Constants.d.ts.map +1 -0
  68. package/dist/Logger/Constants.js +15 -0
  69. package/dist/Logger/Constants.js.map +1 -0
  70. package/dist/Logger/LoggerSettings.d.ts +18 -0
  71. package/dist/Logger/LoggerSettings.d.ts.map +1 -0
  72. package/dist/Logger/LoggerSettings.js +100 -0
  73. package/dist/Logger/LoggerSettings.js.map +1 -0
  74. package/dist/Logger/OneDSWriter.d.ts +22 -0
  75. package/dist/Logger/OneDSWriter.d.ts.map +1 -0
  76. package/dist/Logger/OneDSWriter.js +137 -0
  77. package/dist/Logger/OneDSWriter.js.map +1 -0
  78. package/dist/Logger/Scrubber/ScrubCustomDimensions.d.ts +5 -0
  79. package/dist/Logger/Scrubber/ScrubCustomDimensions.d.ts.map +1 -0
  80. package/dist/Logger/Scrubber/ScrubCustomDimensions.js +46 -0
  81. package/dist/Logger/Scrubber/ScrubCustomDimensions.js.map +1 -0
  82. package/dist/Logger/Scrubber/ScrubCustomDimensionsConfig.d.ts +27 -0
  83. package/dist/Logger/Scrubber/ScrubCustomDimensionsConfig.d.ts.map +1 -0
  84. package/dist/Logger/Scrubber/ScrubCustomDimensionsConfig.js +168 -0
  85. package/dist/Logger/Scrubber/ScrubCustomDimensionsConfig.js.map +1 -0
  86. package/dist/Logger/Scrubber/ScrubUtils.d.ts +8 -0
  87. package/dist/Logger/Scrubber/ScrubUtils.d.ts.map +1 -0
  88. package/dist/Logger/Scrubber/ScrubUtils.js +34 -0
  89. package/dist/Logger/Scrubber/ScrubUtils.js.map +1 -0
  90. package/dist/Types/Argument.types.d.ts +20 -0
  91. package/dist/Types/Argument.types.d.ts.map +1 -0
  92. package/dist/Types/Argument.types.js +5 -0
  93. package/dist/Types/Argument.types.js.map +1 -0
  94. package/dist/Types/Cli.types.d.ts +35 -0
  95. package/dist/Types/Cli.types.d.ts.map +1 -0
  96. package/dist/Types/Cli.types.js +5 -0
  97. package/dist/Types/Cli.types.js.map +1 -0
  98. package/dist/Types/Datasource.types.d.ts +43 -0
  99. package/dist/Types/Datasource.types.d.ts.map +1 -0
  100. package/dist/Types/Datasource.types.js +5 -0
  101. package/dist/Types/Datasource.types.js.map +1 -0
  102. package/dist/Types/LoggerTypes.types.d.ts +17 -0
  103. package/dist/Types/LoggerTypes.types.d.ts.map +1 -0
  104. package/dist/Types/LoggerTypes.types.js +5 -0
  105. package/dist/Types/LoggerTypes.types.js.map +1 -0
  106. package/dist/Utils/BuildVerbDescriptionTable.d.ts +9 -0
  107. package/dist/Utils/BuildVerbDescriptionTable.d.ts.map +1 -0
  108. package/dist/Utils/BuildVerbDescriptionTable.js +29 -0
  109. package/dist/Utils/BuildVerbDescriptionTable.js.map +1 -0
  110. package/dist/Utils/ConsoleOutput.d.ts +39 -0
  111. package/dist/Utils/ConsoleOutput.d.ts.map +1 -0
  112. package/dist/Utils/ConsoleOutput.js +111 -0
  113. package/dist/Utils/ConsoleOutput.js.map +1 -0
  114. package/dist/Utils/EnhanceNetworkError.d.ts +14 -0
  115. package/dist/Utils/EnhanceNetworkError.d.ts.map +1 -0
  116. package/dist/Utils/EnhanceNetworkError.js +59 -0
  117. package/dist/Utils/EnhanceNetworkError.js.map +1 -0
  118. package/dist/Verbs/AddDataSource.d.ts +19 -0
  119. package/dist/Verbs/AddDataSource.d.ts.map +1 -0
  120. package/dist/Verbs/AddDataSource.js +157 -0
  121. package/dist/Verbs/AddDataSource.js.map +1 -0
  122. package/dist/Verbs/AddDataverseApi.d.ts +13 -0
  123. package/dist/Verbs/AddDataverseApi.d.ts.map +1 -0
  124. package/dist/Verbs/AddDataverseApi.js +67 -0
  125. package/dist/Verbs/AddDataverseApi.js.map +1 -0
  126. package/dist/Verbs/AddFlow.d.ts +12 -0
  127. package/dist/Verbs/AddFlow.d.ts.map +1 -0
  128. package/dist/Verbs/AddFlow.js +66 -0
  129. package/dist/Verbs/AddFlow.js.map +1 -0
  130. package/dist/Verbs/DeleteDataSource.d.ts +6 -0
  131. package/dist/Verbs/DeleteDataSource.d.ts.map +1 -0
  132. package/dist/Verbs/DeleteDataSource.js +108 -0
  133. package/dist/Verbs/DeleteDataSource.js.map +1 -0
  134. package/dist/Verbs/FindDataverseApi.d.ts +12 -0
  135. package/dist/Verbs/FindDataverseApi.d.ts.map +1 -0
  136. package/dist/Verbs/FindDataverseApi.js +101 -0
  137. package/dist/Verbs/FindDataverseApi.js.map +1 -0
  138. package/dist/Verbs/Init.d.ts +6 -0
  139. package/dist/Verbs/Init.d.ts.map +1 -0
  140. package/dist/Verbs/Init.js +146 -0
  141. package/dist/Verbs/Init.js.map +1 -0
  142. package/dist/Verbs/ListCodeApps.d.ts +6 -0
  143. package/dist/Verbs/ListCodeApps.d.ts.map +1 -0
  144. package/dist/Verbs/ListCodeApps.js +31 -0
  145. package/dist/Verbs/ListCodeApps.js.map +1 -0
  146. package/dist/Verbs/ListConnectionReferences.d.ts +6 -0
  147. package/dist/Verbs/ListConnectionReferences.d.ts.map +1 -0
  148. package/dist/Verbs/ListConnectionReferences.js +80 -0
  149. package/dist/Verbs/ListConnectionReferences.js.map +1 -0
  150. package/dist/Verbs/ListDatasets.d.ts +6 -0
  151. package/dist/Verbs/ListDatasets.d.ts.map +1 -0
  152. package/dist/Verbs/ListDatasets.js +83 -0
  153. package/dist/Verbs/ListDatasets.js.map +1 -0
  154. package/dist/Verbs/ListEnvironmentVariables.d.ts +14 -0
  155. package/dist/Verbs/ListEnvironmentVariables.d.ts.map +1 -0
  156. package/dist/Verbs/ListEnvironmentVariables.js +82 -0
  157. package/dist/Verbs/ListEnvironmentVariables.js.map +1 -0
  158. package/dist/Verbs/ListFlows.d.ts +13 -0
  159. package/dist/Verbs/ListFlows.d.ts.map +1 -0
  160. package/dist/Verbs/ListFlows.js +88 -0
  161. package/dist/Verbs/ListFlows.js.map +1 -0
  162. package/dist/Verbs/ListSqlStoredProcedures.d.ts +6 -0
  163. package/dist/Verbs/ListSqlStoredProcedures.d.ts.map +1 -0
  164. package/dist/Verbs/ListSqlStoredProcedures.js +84 -0
  165. package/dist/Verbs/ListSqlStoredProcedures.js.map +1 -0
  166. package/dist/Verbs/ListTables.d.ts +6 -0
  167. package/dist/Verbs/ListTables.d.ts.map +1 -0
  168. package/dist/Verbs/ListTables.js +95 -0
  169. package/dist/Verbs/ListTables.js.map +1 -0
  170. package/dist/Verbs/Logout.d.ts +6 -0
  171. package/dist/Verbs/Logout.d.ts.map +1 -0
  172. package/dist/Verbs/Logout.js +28 -0
  173. package/dist/Verbs/Logout.js.map +1 -0
  174. package/dist/Verbs/Push.d.ts +6 -0
  175. package/dist/Verbs/Push.d.ts.map +1 -0
  176. package/dist/Verbs/Push.js +108 -0
  177. package/dist/Verbs/Push.js.map +1 -0
  178. package/dist/Verbs/RefreshDataSource.d.ts +6 -0
  179. package/dist/Verbs/RefreshDataSource.d.ts.map +1 -0
  180. package/dist/Verbs/RefreshDataSource.js +70 -0
  181. package/dist/Verbs/RefreshDataSource.js.map +1 -0
  182. package/dist/Verbs/RemoveFlow.d.ts +12 -0
  183. package/dist/Verbs/RemoveFlow.d.ts.map +1 -0
  184. package/dist/Verbs/RemoveFlow.js +98 -0
  185. package/dist/Verbs/RemoveFlow.js.map +1 -0
  186. package/dist/Verbs/Run.d.ts +6 -0
  187. package/dist/Verbs/Run.d.ts.map +1 -0
  188. package/dist/Verbs/Run.js +122 -0
  189. package/dist/Verbs/Run.js.map +1 -0
  190. package/dist/Verbs/TelemetrySettings.d.ts +12 -0
  191. package/dist/Verbs/TelemetrySettings.d.ts.map +1 -0
  192. package/dist/Verbs/TelemetrySettings.js +158 -0
  193. package/dist/Verbs/TelemetrySettings.js.map +1 -0
  194. package/dist/Verbs/VerbConstants.d.ts +203 -0
  195. package/dist/Verbs/VerbConstants.d.ts.map +1 -0
  196. package/dist/Verbs/VerbConstants.js +201 -0
  197. package/dist/Verbs/VerbConstants.js.map +1 -0
  198. package/dist/Verbs/index.d.ts +22 -0
  199. package/dist/Verbs/index.d.ts.map +1 -0
  200. package/dist/Verbs/index.js +22 -0
  201. package/dist/Verbs/index.js.map +1 -0
  202. package/package.json +5 -5
package/dist/Bin.js CHANGED
@@ -1,3362 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { createRequire } from "node:module";
3
- var __defProp = Object.defineProperty;
4
- var __export = (target, all) => {
5
- for (var name in all)
6
- __defProp(target, name, {
7
- get: all[name],
8
- enumerable: true,
9
- configurable: true,
10
- set: (newValue) => all[name] = () => newValue
11
- });
12
- };
13
- var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
14
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
15
-
16
- // src/Constants.ts
17
- import * as os from "os";
18
- import * as path from "path";
19
- var APP_CONFIG_FILE = "power.config.json", WORKING_DIRECTORY, CLI_CONFIG_DIRECTORY, AUTH_CACHE_DIRECTORY, MS_CLIENT_REQUESTID = "x-ms-client-request-id", USER_SETTINGS_FILE = "userSettings.json";
20
- var init_Constants = __esm(() => {
21
- /*!
22
- * Copyright (C) Microsoft Corporation. All rights reserved.
23
- */
24
- WORKING_DIRECTORY = process.env.WORKING_DIRECTORY || process.cwd();
25
- CLI_CONFIG_DIRECTORY = path.join(os.homedir(), ".powerapps-cli");
26
- AUTH_CACHE_DIRECTORY = path.join(CLI_CONFIG_DIRECTORY, "cache", "auth");
27
- });
28
-
29
- // src/CliUtils.ts
30
- import * as prompts from "@clack/prompts";
31
- import { isCancel } from "@clack/prompts";
32
- async function promptText(options) {
33
- const result = await prompts.text(options);
34
- if (isCancel(result)) {
35
- console.log("Operation cancelled by user.");
36
- process.exit(0);
37
- }
38
- return result;
39
- }
40
- async function promptConfirm(options) {
41
- const result = await prompts.confirm(options);
42
- if (isCancel(result)) {
43
- console.log("Operation cancelled by user.");
44
- process.exit(0);
45
- }
46
- return result;
47
- }
48
- function createDefaultStringOption(options) {
49
- const { flags, env, message, initialValue, description, default: defaultValue } = options;
50
- return {
51
- flags,
52
- env,
53
- description,
54
- default: defaultValue,
55
- customPrompt: async () => {
56
- return await promptText({ message, initialValue });
57
- }
58
- };
59
- }
60
- function isGuid(value) {
61
- const guidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
62
- return guidRegex.test(value);
63
- }
64
- function createPlayUrl(region, environmentId, appId, localAppUrl, localConnectionsUrl) {
65
- const baseUrl = _getBaseUrl(region);
66
- const playUrl = `${baseUrl}/play/e/${environmentId}/app/${appId}`;
67
- const queryParams = [];
68
- if (localAppUrl) {
69
- queryParams.push(`_localAppUrl=${localAppUrl}`);
70
- }
71
- if (localConnectionsUrl) {
72
- queryParams.push(`_localConnectionUrl=${localConnectionsUrl}`);
73
- }
74
- return queryParams.length > 0 ? `${playUrl}?${queryParams.join("&")}` : playUrl;
75
- }
76
- function getAuthority(region, tenantId) {
77
- switch (region) {
78
- case "gcchigh":
79
- case "dod":
80
- return `https://login.microsoftonline.us/${tenantId || "organizations"}`;
81
- case "mooncake":
82
- return `https://login.partner.microsoftonline.cn/${tenantId || "organizations"}`;
83
- default:
84
- return `https://login.microsoftonline.com/${tenantId || "organizations"}`;
85
- }
86
- }
87
- function _getBaseUrl(region) {
88
- switch (region) {
89
- case "dev":
90
- return "https://apps.dev.powerapps.com";
91
- case "test":
92
- return "https://apps.test.powerapps.com";
93
- case "preprod":
94
- return "https://apps.preprod.powerapps.com";
95
- case "preview":
96
- return "https://apps.preview.powerapps.com";
97
- case "prod":
98
- return "https://apps.powerapps.com";
99
- case "gccmoderate":
100
- return "https://apps.gov.powerapps.us";
101
- case "gcchigh":
102
- return "https://apps.high.powerapps.us";
103
- case "dod":
104
- return "https://play.apps.appsplatform.us";
105
- case "mooncake":
106
- return "https://apps.powerapps.cn";
107
- default:
108
- return "";
109
- }
110
- }
111
- var init_CliUtils = __esm(() => {
112
- /*!
113
- * Copyright (C) Microsoft Corporation. All rights reserved.
114
- */
115
- });
116
-
117
- // src/Authentication/ServicePrincipalAuthenticationProvider.ts
118
- var exports_ServicePrincipalAuthenticationProvider = {};
119
- __export(exports_ServicePrincipalAuthenticationProvider, {
120
- ServicePrincipalAuthenticationProvider: () => ServicePrincipalAuthenticationProvider
121
- });
122
- import { ConfidentialClientApplication } from "@azure/msal-node";
123
-
124
- class ServicePrincipalAuthenticationProvider {
125
- _msalClient;
126
- _clientId;
127
- _clientSecret;
128
- _tenantId;
129
- _region;
130
- constructor() {
131
- if (!process.env.SP_CLIENT_ID || !process.env.SP_CLIENT_SECRET || !process.env.SP_TENANT_ID) {
132
- throw new Error("Service Principal environment variables SP_CLIENT_ID, SP_CLIENT_SECRET, and SP_TENANT_ID must be set");
133
- }
134
- this._clientId = process.env.SP_CLIENT_ID;
135
- this._clientSecret = process.env.SP_CLIENT_SECRET;
136
- this._tenantId = process.env.SP_TENANT_ID;
137
- }
138
- async initAsync(region) {
139
- this._region = region;
140
- const authConfig = {
141
- auth: {
142
- clientId: this._clientId,
143
- clientSecret: this._clientSecret,
144
- authority: getAuthority(this._region, this._tenantId)
145
- }
146
- };
147
- this._msalClient = new ConfidentialClientApplication(authConfig);
148
- }
149
- async getAccessTokenForResource(resource) {
150
- if (!this._msalClient) {
151
- throw new Error("Authentication not initialized yet");
152
- }
153
- const clientCredentialRequest = {
154
- scopes: [resource + "/.default"]
155
- };
156
- const result = await this._msalClient.acquireTokenByClientCredential(clientCredentialRequest);
157
- if (!result?.accessToken) {
158
- throw new Error("Failed to acquire token using service principal");
159
- }
160
- return result.accessToken;
161
- }
162
- getUserTenantId() {
163
- return this._tenantId;
164
- }
165
- }
166
- var init_ServicePrincipalAuthenticationProvider = __esm(() => {
167
- init_CliUtils();
168
- /*!
169
- * Copyright (C) Microsoft Corporation. All rights reserved.
170
- */
171
- });
172
-
173
- // src/Authentication/NodeMsalAuthenticationProvider.ts
174
- var exports_NodeMsalAuthenticationProvider = {};
175
- __export(exports_NodeMsalAuthenticationProvider, {
176
- NodeMsalAuthenticationProvider: () => NodeMsalAuthenticationProvider
177
- });
178
- import { InteractionRequiredAuthError, PublicClientApplication } from "@azure/msal-node";
179
- import open from "open";
180
-
181
- class NodeMsalAuthenticationProvider {
182
- _msalClient;
183
- _tenantId;
184
- _region;
185
- constructor() {}
186
- async initAsync(region) {
187
- this._region = region;
188
- const { DataProtectionScope, PersistenceCachePlugin, PersistenceCreator } = await import("@azure/msal-node-extensions");
189
- const persistenceConfiguration = {
190
- cachePath: AUTH_CACHE_DIRECTORY + "/msal_cache.json",
191
- dataProtectionScope: DataProtectionScope.CurrentUser,
192
- serviceName: "power-apps",
193
- accountName: "power-apps",
194
- usePlaintextFileOnLinux: false
195
- };
196
- const persistence = await PersistenceCreator.createPersistence(persistenceConfiguration);
197
- const authConfig = {
198
- auth: {
199
- authority: getAuthority(this._region, this._tenantId),
200
- clientId: "9cee029c-6210-4654-90bb-17e6e9d36617"
201
- },
202
- cache: {
203
- cachePlugin: new PersistenceCachePlugin(persistence)
204
- }
205
- };
206
- this._msalClient = new PublicClientApplication(authConfig);
207
- }
208
- async getAccessTokenForResource(resource) {
209
- const result = await this._acquireTokenInternal(resource + "/.default");
210
- this._tenantId = result.tenantId;
211
- return result.accessToken;
212
- }
213
- getUserTenantId() {
214
- return this._tenantId;
215
- }
216
- async _acquireTokenInternal(resource) {
217
- if (!this._msalClient) {
218
- throw new Error("Authentication not initialized yet");
219
- }
220
- const accounts = await this._msalClient.getTokenCache().getAllAccounts();
221
- if (accounts.length === 1) {
222
- const silentRequest = {
223
- account: accounts[0],
224
- scopes: [resource]
225
- };
226
- try {
227
- const result = await this._msalClient.acquireTokenSilent(silentRequest);
228
- return result;
229
- } catch (error2) {
230
- if (error2 instanceof InteractionRequiredAuthError) {
231
- return this._msalClient.acquireTokenInteractive(this._getInteractiveLoginRequest(resource));
232
- }
233
- throw error2;
234
- }
235
- } else if (accounts.length > 1) {
236
- accounts.forEach((account) => {
237
- console.log(account.username);
238
- });
239
- return Promise.reject("Multiple accounts found. Please use the logout command to remove existing accounts.");
240
- } else {
241
- return this._msalClient.acquireTokenInteractive(this._getInteractiveLoginRequest(resource));
242
- }
243
- }
244
- _getInteractiveLoginRequest(resource) {
245
- const openBrowser = async (url) => {
246
- try {
247
- await open(url, { wait: false });
248
- } catch (error2) {
249
- console.error("Failed to open browser:", error2);
250
- }
251
- };
252
- return {
253
- scopes: [resource],
254
- openBrowser,
255
- successTemplate: "You can close this window now."
256
- };
257
- }
258
- }
259
- var init_NodeMsalAuthenticationProvider = __esm(() => {
260
- init_CliUtils();
261
- init_Constants();
262
- /*!
263
- * Copyright (C) Microsoft Corporation. All rights reserved.
264
- */
265
- });
266
-
267
- // src/ArgumentProvider.ts
268
- import {
269
- initializePlayerServices,
270
- updateEnvironmentName,
271
- updateRegion
272
- } from "@microsoft/power-apps-actions";
273
- import { Command } from "commander";
274
- // package.json
275
- var package_default = {
276
- name: "@microsoft/power-apps-cli",
277
- version: "0.9.1",
278
- type: "module",
279
- description: "CLI for Power Apps code apps",
280
- license: "See license in LICENSE file",
281
- bin: {
282
- "power-apps": "./dist/Bin.js"
283
- },
284
- files: [
285
- "dist",
286
- "LICENSE",
287
- "README.md"
288
- ],
289
- scripts: {
290
- build: "bun run check-types && bun ../../scripts/bundle.ts --bin src/Bin.ts",
291
- "build:bundle": "bun run check-types && bun ../../scripts/bundle.ts --bin src/Bin.ts --self-contained",
292
- dev: "tsc -p tsconfig.json --watch",
293
- "check-types": "tsc --noEmit",
294
- lint: "eslint src/",
295
- test: "bun test src/",
296
- "test:e2e": "bun test src/__tests__/e2e/",
297
- clean: "bun ../../scripts/clean.ts dist .turbo tsconfig.tsbuildinfo tsconfig.build.tsbuildinfo"
298
- },
299
- dependencies: {
300
- "@microsoft/power-apps-actions": "workspace:*",
301
- "@microsoft/power-apps-common": "workspace:*",
302
- "@azure/msal-node": "3.6.3",
303
- "@azure/msal-node-extensions": "1.5.17",
304
- "@clack/prompts": "0.6.3",
305
- "@microsoft/1ds-core-js": "4.3.11",
306
- "@microsoft/1ds-post-js": "4.3.11",
307
- chalk: "4.1.2",
308
- commander: "10.0.1",
309
- open: "8.4.0"
310
- },
311
- engines: {
312
- node: ">=22"
313
- },
314
- devDependencies: {
315
- "@repo/repo-config": "workspace:*",
316
- "@types/bun": "1.3.9",
317
- "@types/node": "22.19.9",
318
- typescript: "5.9.3"
319
- }
320
- };
321
-
322
- // src/CliSettings.ts
323
- init_Constants();
324
- import { readRepoConfig } from "@microsoft/power-apps-actions";
325
- import { setVfs } from "@microsoft/power-apps-actions";
326
-
327
- // src/FS/CliFs.ts
328
- import fs from "fs";
329
- import path2 from "path";
330
- /*!
331
- * Copyright (C) Microsoft Corporation. All rights reserved.
332
- */
333
-
334
- class CliFS {
335
- cwd;
336
- constructor(config) {
337
- this.cwd = path2.resolve(config.cwd);
338
- if (!fs.existsSync(this.cwd)) {
339
- throw new Error(`Current working directory does not exist: ${this.cwd}`);
340
- }
341
- }
342
- async rmdir(dirPath) {
343
- const normalizedPath = this.validateWritePath(dirPath);
344
- await fs.promises.rm(normalizedPath, { recursive: true });
345
- }
346
- normalizePath(inputPath) {
347
- if (path2.isAbsolute(inputPath)) {
348
- return path2.resolve(inputPath);
349
- }
350
- return path2.resolve(this.cwd, inputPath);
351
- }
352
- validateReadPath(inputPath) {
353
- const normalizedPath = this.normalizePath(inputPath);
354
- return normalizedPath;
355
- }
356
- validateWritePath(inputPath) {
357
- const normalizedPath = this.normalizePath(inputPath);
358
- return normalizedPath;
359
- }
360
- getCwd() {
361
- return this.cwd;
362
- }
363
- getAbsolutePath(relativePath) {
364
- return this.normalizePath(relativePath);
365
- }
366
- async readFile(inputPath, encoding = "utf-8") {
367
- const normalizedPath = this.validateReadPath(inputPath);
368
- try {
369
- return await fs.promises.readFile(normalizedPath, encoding);
370
- } catch (error) {
371
- if (error instanceof Error) {
372
- if (error.code === "ENOENT") {
373
- throw new Error(`File not found: ${normalizedPath}`);
374
- }
375
- throw new Error(`Failed to read file: ${error.message}`);
376
- }
377
- throw new Error("Unknown error occurred while reading file");
378
- }
379
- }
380
- async writeFile(inputPath, content, options = {}) {
381
- const normalizedPath = this.validateWritePath(inputPath);
382
- const { createDirectories = true, encoding = "utf-8" } = options;
383
- if (createDirectories) {
384
- const parentDir = path2.dirname(normalizedPath);
385
- if (!fs.existsSync(parentDir)) {
386
- await fs.promises.mkdir(parentDir, { recursive: true });
387
- }
388
- }
389
- await fs.promises.writeFile(normalizedPath, content, { encoding });
390
- }
391
- async appendFile(inputPath, content) {
392
- const normalizedPath = this.validateWritePath(inputPath);
393
- await fs.promises.appendFile(normalizedPath, content, "utf-8");
394
- }
395
- async readdir(inputPath) {
396
- const normalizedPath = this.validateReadPath(inputPath);
397
- return await fs.promises.readdir(normalizedPath);
398
- }
399
- async mkdir(inputPath, options = {}) {
400
- const normalizedPath = this.validateWritePath(inputPath);
401
- await fs.promises.mkdir(normalizedPath, options);
402
- }
403
- async exists(inputPath) {
404
- const normalizedPath = this.normalizePath(inputPath);
405
- try {
406
- await fs.promises.stat(normalizedPath);
407
- return true;
408
- } catch {
409
- return false;
410
- }
411
- }
412
- async stat(inputPath) {
413
- const normalizedPath = this.validateReadPath(inputPath);
414
- const stats = await fs.promises.stat(normalizedPath);
415
- return {
416
- isFile: () => stats.isFile(),
417
- isDirectory: () => stats.isDirectory(),
418
- size: stats.size,
419
- mtime: stats.mtime,
420
- ctime: stats.ctime
421
- };
422
- }
423
- async isFile(inputPath) {
424
- const stats = await this.stat(inputPath);
425
- return stats.isFile();
426
- }
427
- async isDirectory(inputPath) {
428
- const stats = await this.stat(inputPath);
429
- return stats.isDirectory();
430
- }
431
- resolve(...paths) {
432
- return path2.resolve(...paths);
433
- }
434
- join(...paths) {
435
- return path2.join(...paths);
436
- }
437
- relative(from, to) {
438
- return path2.relative(from, to);
439
- }
440
- basename(inputPath) {
441
- return path2.basename(inputPath);
442
- }
443
- dirname(inputPath) {
444
- return path2.dirname(inputPath);
445
- }
446
- unlink(inputPath) {
447
- const normalizedPath = this.validateWritePath(inputPath);
448
- return fs.promises.unlink(normalizedPath);
449
- }
450
- }
451
-
452
- // src/CliSettings.ts
453
- /*!
454
- * Copyright (C) Microsoft Corporation. All rights reserved.
455
- */
456
- var _cliSettings;
457
- var _logger;
458
- async function initializeCliSettings({
459
- source,
460
- interactive,
461
- fileConfig = {
462
- powerConfigPath: `${WORKING_DIRECTORY}/${APP_CONFIG_FILE}`,
463
- schemaPath: `${WORKING_DIRECTORY}/.power/schemas`,
464
- codeGenPath: `${WORKING_DIRECTORY}/src`
465
- }
466
- }) {
467
- const cliFs = new CliFS({
468
- cwd: process.cwd(),
469
- allowCwdRead: true,
470
- allowCwdWrite: true
471
- });
472
- setVfs(cliFs);
473
- let appConfig;
474
- try {
475
- appConfig = await readRepoConfig(fileConfig.powerConfigPath);
476
- } catch (error) {}
477
- _cliSettings = {
478
- source,
479
- interactive,
480
- fileConfig,
481
- cliFs,
482
- appConfig
483
- };
484
- return _cliSettings;
485
- }
486
- function setCliLogger(logger) {
487
- _logger = logger;
488
- }
489
- function getCliLogger() {
490
- if (!_logger) {
491
- return {
492
- trackActivityEvent: (_eventName, _eventData) => {},
493
- trackErrorEvent: (_eventName, _eventData) => {},
494
- trackScenario: (_name, _scenarioData) => {
495
- return {
496
- scenarioId: "",
497
- complete: (_endScenarioData) => {},
498
- failure: (_failureData) => {},
499
- completeWithError: (_completeWithErrorData) => {}
500
- };
501
- },
502
- stringifyError: (_err) => {
503
- return null;
504
- }
505
- };
506
- }
507
- return _logger;
508
- }
509
- function getSettings() {
510
- if (!_cliSettings) {
511
- throw new Error("CLI settings have not been initialized. Please call initializeCliSettings first.");
512
- }
513
- return _cliSettings;
514
- }
515
-
516
- // src/ArgumentProvider.ts
517
- init_CliUtils();
518
-
519
- // src/Constants/HelpStrings.ts
520
- /*!
521
- * Copyright (C) Microsoft Corporation. All rights reserved.
522
- */
523
- var HelpStrings = {
524
- Global: {
525
- ProgramDescription: "Power Apps CLI for managing Power Apps code apps.",
526
- Cloud: "Cloud instance to use (e.g., prod, test, etc.).",
527
- EnvironmentId: "Environment ID to connect to."
528
- },
529
- Verbs: {
530
- "Add-data-source": {
531
- Description: "Add a data source to the current Power Apps code app.",
532
- Options: {
533
- ApiId: "API identifier.",
534
- ConnectionId: "Connection identifier.",
535
- ConnectionRef: "Connection reference name.",
536
- ResourceName: "Table or resource name.",
537
- Dataset: "Dataset identifier.",
538
- OrgUrl: "Organization URL.",
539
- SqlStoredProcedure: "SQL stored procedure name.",
540
- SolutionId: "Solution identifier."
541
- },
542
- Examples: [
543
- "npx power-apps add-data-source --api-id dataverse --resource-name contact",
544
- "npx power-apps add-data-source --api-id shared_sql --connection-id <id> --dataset <db> --resource-name <table>"
545
- ]
546
- },
547
- "Delete-data-source": {
548
- Description: "Remove a data source from the Power Apps code app.",
549
- Options: {
550
- ApiId: "API identifier associated with the data source.",
551
- DataSourceName: "Data source or table name to remove.",
552
- SqlStoredProcedure: "SQL stored procedure name to remove.",
553
- Force: "Skip confirmation prompt."
554
- },
555
- Examples: [
556
- "npx power-apps delete-data-source --api-id dataverse --data-source-name contact",
557
- "npx power-apps delete-data-source --api-id shared_sql --data-source-name <table>",
558
- "npx power-apps delete-data-source --api-id dataverse --data-source-name contact --force"
559
- ]
560
- },
561
- Init: {
562
- Description: "Initialize a new Power Apps code app.",
563
- Options: {
564
- EnvironmentId: "Environment ID to connect to.",
565
- Cloud: "Cloud instance to use (e.g., prod, test, etc.).",
566
- DisplayName: "Display name for the app.",
567
- Description: "App description.",
568
- BuildPath: "Build output path (default: ./dist).",
569
- FileEntryPoint: "Entry point file for the app.",
570
- AppUrl: "Local URL where the app is hosted.",
571
- LogoPath: "Path to the app logo file."
572
- },
573
- Examples: [
574
- 'npx power-apps init --environment-id <id> --display-name "My App"',
575
- 'npx power-apps init --cloud test --environment-id <id> --display-name "My App" --build-path ./build'
576
- ]
577
- },
578
- "List-codeapps": {
579
- Description: "List all code apps in the environment.",
580
- Examples: ["npx power-apps list-codeapps", "npx power-apps list-codeapps --json"]
581
- },
582
- "List-connection-references": {
583
- Description: "List all connection references in the environment.",
584
- Options: {
585
- SolutionId: "Solution identifier to filter by.",
586
- OrgUrl: "Organization URL."
587
- },
588
- Examples: [
589
- "npx power-apps list-connection-references --org-url https://org.crm.dynamics.com",
590
- "npx power-apps list-connection-references --json"
591
- ]
592
- },
593
- "List-datasets": {
594
- Description: "List all datasets for a connection.",
595
- Options: {
596
- ApiId: "API identifier.",
597
- ConnectionId: "Connection identifier."
598
- },
599
- Examples: [
600
- "npx power-apps list-datasets --api-id shared_sql --connection-id <id>",
601
- "npx power-apps list-datasets --api-id shared_sql --connection-id <id> --json"
602
- ]
603
- },
604
- "List-environment-variables": {
605
- Description: "List all environment variables in the environment.",
606
- Options: {
607
- OrgUrl: "Organization URL."
608
- },
609
- Examples: [
610
- "npx power-apps list-environment-variables",
611
- "npx power-apps list-environment-variables --json"
612
- ]
613
- },
614
- "List-flows": {
615
- Description: "List all solution cloud flows that are invokable from Power Apps.",
616
- Options: {
617
- Search: "Filter flows by name (case-insensitive substring match)"
618
- },
619
- Examples: [
620
- "npx power-apps list-flows",
621
- 'npx power-apps list-flows --search "approval" --json'
622
- ]
623
- },
624
- "List-sqlStoredProcedures": {
625
- Description: "List all SQL stored procedures for a dataset.",
626
- Options: {
627
- ConnectionId: "Connection identifier.",
628
- Dataset: "Dataset name."
629
- },
630
- Examples: [
631
- "npx power-apps list-sqlStoredProcedures --connection-id <id> --dataset <db>",
632
- "npx power-apps list-sqlStoredProcedures --connection-id <id> --dataset <db> --json"
633
- ]
634
- },
635
- "List-tables": {
636
- Description: "List all tables for a dataset.",
637
- Options: {
638
- ApiId: "API identifier.",
639
- ConnectionId: "Connection identifier.",
640
- Dataset: "Dataset name."
641
- },
642
- Examples: [
643
- "npx power-apps list-tables --api-id shared_sql --connection-id <id> --dataset <db>",
644
- "npx power-apps list-tables --api-id shared_sql --connection-id <id> --dataset <db> --json"
645
- ]
646
- },
647
- Logout: {
648
- Description: "Log out the current user.",
649
- Examples: ["npx power-apps logout"]
650
- },
651
- Push: {
652
- Description: "Push the code app to the Power Apps environment.",
653
- Options: {
654
- SolutionName: "Solution name to add the app to."
655
- },
656
- Examples: ["npx power-apps push", 'npx power-apps push --solution-name "MySolution"']
657
- },
658
- Run: {
659
- Description: "Run the code app locally.",
660
- Options: {
661
- Port: "Port number for the local server.",
662
- LocalAppUrl: "Local URL where the app is hosted."
663
- },
664
- Examples: [
665
- "npx power-apps run",
666
- "npx power-apps run --port 8080 --local-app-url http://localhost:3000"
667
- ]
668
- },
669
- Telemetry: {
670
- Description: "Manage telemetry settings.",
671
- Options: {
672
- Enable: "Enable telemetry.",
673
- Disable: "Disable telemetry.",
674
- ShowSettings: "Show current telemetry settings.",
675
- ConsoleOnly: "Output telemetry to console only.",
676
- OutputToConsole: "Output telemetry to console in addition to sending it."
677
- },
678
- Examples: [
679
- "npx power-apps telemetry --show-settings",
680
- "npx power-apps telemetry --enable",
681
- "npx power-apps telemetry --show-settings --json"
682
- ]
683
- }
684
- }
685
- };
686
-
687
- // src/Errors/CliError.ts
688
- /*!
689
- * Copyright (C) Microsoft Corporation. All rights reserved.
690
- */
691
-
692
- class CliError extends Error {
693
- exitCode;
694
- constructor(message, exitCode = 1) {
695
- super(message);
696
- this.exitCode = exitCode;
697
- }
698
- }
699
-
700
- class UsageError extends CliError {
701
- constructor(message) {
702
- super(message, 2);
703
- }
704
- }
705
-
706
- // src/Constants/VerbRegistry.ts
707
- /*!
708
- * Copyright (C) Microsoft Corporation. All rights reserved.
709
- */
710
- var VERB_HELP_REGISTRY = {
711
- init: { description: HelpStrings.Verbs.Init.Description },
712
- push: { description: HelpStrings.Verbs.Push.Description },
713
- run: { description: HelpStrings.Verbs.Run.Description },
714
- "add-data-source": { description: HelpStrings.Verbs["Add-data-source"].Description },
715
- "list-codeapps": { description: HelpStrings.Verbs["List-codeapps"].Description },
716
- "list-datasets": { description: HelpStrings.Verbs["List-datasets"].Description },
717
- "list-tables": { description: HelpStrings.Verbs["List-tables"].Description },
718
- "list-sqlStoredProcedures": {
719
- description: HelpStrings.Verbs["List-sqlStoredProcedures"].Description
720
- },
721
- "delete-data-source": { description: HelpStrings.Verbs["Delete-data-source"].Description },
722
- "list-environment-variables": {
723
- description: HelpStrings.Verbs["List-environment-variables"].Description
724
- },
725
- "list-connection-references": {
726
- description: HelpStrings.Verbs["List-connection-references"].Description
727
- },
728
- "list-flows": { description: HelpStrings.Verbs["List-flows"].Description },
729
- logout: { description: HelpStrings.Verbs.Logout.Description },
730
- telemetry: { description: HelpStrings.Verbs.Telemetry.Description }
731
- };
732
-
733
- // src/Utils/BuildVerbDescriptionTable.ts
734
- /*!
735
- * Copyright (C) Microsoft Corporation. All rights reserved.
736
- */
737
- function buildVerbDescriptionTable() {
738
- const verbEntries = Object.entries(VERB_HELP_REGISTRY);
739
- if (verbEntries.length === 0) {
740
- return "";
741
- }
742
- const maxVerbLength = Math.max(...verbEntries.map(([verb]) => verb.length));
743
- const verbColumnWidth = Math.max(maxVerbLength + 2, 10);
744
- const lines = [];
745
- lines.push("Available Commands:");
746
- lines.push("");
747
- lines.push(` ${"Command".padEnd(verbColumnWidth)} Description`);
748
- lines.push(` ${"-".repeat(verbColumnWidth)} ${"-".repeat(60)}`);
749
- verbEntries.forEach(([verb, verbMetadata]) => {
750
- const verbColumn = verb.padEnd(verbColumnWidth);
751
- lines.push(` ${verbColumn} ${verbMetadata.description}`);
752
- });
753
- return lines.join(`
754
- `);
755
- }
756
-
757
- // src/Verbs/VerbConstants.ts
758
- /*!
759
- * Copyright (C) Microsoft Corporation. All rights reserved.
760
- */
761
- var SharedArguments = {
762
- Help: {
763
- name: "help",
764
- alias: "h"
765
- },
766
- ApiId: {
767
- name: "api-id",
768
- alias: "a",
769
- promptMessage: "Please provide the API ID:",
770
- envVar: "API_ID"
771
- },
772
- SolutionId: {
773
- name: "solution-id",
774
- alias: "s",
775
- promptMessage: "Please provide the Solution ID:",
776
- envVar: "SOLUTION_ID"
777
- },
778
- OrgUrl: {
779
- name: "org-url",
780
- alias: "u",
781
- promptMessage: "Please provide the organization URL:",
782
- envVar: "ENV_URL"
783
- },
784
- ConnectionId: {
785
- name: "connection-id",
786
- alias: "c",
787
- promptMessage: "Please provide the Connection ID:",
788
- envVar: "CONNECTION_ID"
789
- },
790
- Dataset: {
791
- name: "dataset",
792
- alias: "d",
793
- promptMessage: "Please provide the dataset:",
794
- envVar: "DATASET"
795
- },
796
- SqlStoredProcedure: {
797
- name: "sql-stored-procedure",
798
- alias: "sp",
799
- promptMessage: "Please provide the SQL stored procedure name:",
800
- envVar: "SQL_STORED_PROCEDURE"
801
- },
802
- ResourceName: {
803
- name: "resource-name",
804
- alias: "t",
805
- promptMessage: "Please provide the resource name:",
806
- envVar: "TABLE"
807
- }
808
- };
809
- var AddDataSourceArguments = {
810
- ConnectionRef: {
811
- name: "connection-ref",
812
- alias: "cr",
813
- promptMessage: "Please provide the Connection Reference:",
814
- envVar: "CONNECTION_REF"
815
- }
816
- };
817
- var DeleteDataSourceArguments = {
818
- DataSourceName: {
819
- name: "data-source-name",
820
- alias: "n",
821
- promptMessage: "Please provide the data source or table name:",
822
- envVar: "DATA_SOURCE_NAME"
823
- }
824
- };
825
- var GlobalArguments = {
826
- EnvironmentId: {
827
- name: "environment-id",
828
- alias: "e",
829
- promptMessage: "Please provide the environment ID:",
830
- envVar: "ENVIRONMENT_ID"
831
- },
832
- Cloud: {
833
- name: "cloud",
834
- promptMessage: "Please select the cloud instance:",
835
- envVar: "CLOUD_INSTANCE"
836
- }
837
- };
838
- var InitArguments = {
839
- DisplayName: {
840
- name: "display-name",
841
- alias: "n",
842
- promptMessage: "Please provide the display name for the app:",
843
- envVar: "APP_DISPLAY_NAME"
844
- },
845
- Description: {
846
- name: "description",
847
- alias: "d",
848
- promptMessage: "Please provide a description for the app:",
849
- envVar: "APP_DESCRIPTION"
850
- },
851
- BuildPath: {
852
- name: "build-path",
853
- alias: "b",
854
- promptMessage: "Please provide the build path for the app:",
855
- envVar: "APP_BUILD_PATH",
856
- initialValue: "./dist"
857
- },
858
- FileEntryPoint: {
859
- name: "file-entry-point",
860
- alias: "f",
861
- promptMessage: "Please provide the file entry point for the app:",
862
- envVar: "APP_FILE_ENTRY_POINT",
863
- initialValue: "index.html"
864
- },
865
- AppUrl: {
866
- name: "app-url",
867
- alias: "a",
868
- promptMessage: "Please provide the local app URL:",
869
- envVar: "APP_URL",
870
- initialValue: "http://localhost:3000"
871
- },
872
- LogoPath: {
873
- name: "logo-path",
874
- alias: "l",
875
- promptMessage: "Please provide the logo path for the app:",
876
- envVar: "APP_LOGO_PATH",
877
- initialValue: "Default"
878
- }
879
- };
880
- var RunArguments = {
881
- Port: {
882
- name: "port",
883
- alias: "p",
884
- promptMessage: "Please provide the port number:",
885
- envVar: "PORT",
886
- initialValue: "8080"
887
- },
888
- LocalAppUrl: {
889
- name: "local-app-url",
890
- alias: "l",
891
- promptMessage: "Please provide the local app URL:",
892
- envVar: "LOCAL_APP_URL",
893
- initialValue: "http://localhost:3000"
894
- }
895
- };
896
- var ListFlowsArguments = {
897
- Search: {
898
- name: "search",
899
- alias: "s",
900
- promptMessage: "Please provide a search term to filter flows by name:",
901
- envVar: "FLOW_SEARCH"
902
- }
903
- };
904
-
905
- // src/ArgumentProvider.ts
906
- /*!
907
- * Copyright (C) Microsoft Corporation. All rights reserved.
908
- */
909
-
910
- class ArgumentProvider {
911
- _httpClient;
912
- _logger;
913
- _authenticationProvider;
914
- _environmentId;
915
- _region;
916
- _verb;
917
- _program;
918
- _options = {};
919
- constructor(_httpClient, _logger2, _authenticationProvider) {
920
- this._httpClient = _httpClient;
921
- this._logger = _logger2;
922
- this._authenticationProvider = _authenticationProvider;
923
- this._verb = process.argv[2] || process.env.VERB;
924
- this._program = new Command;
925
- this._program.option("--non-interactive", "Run in non-interactive mode (no prompts, all parameters must be provided via flags or environment variables)");
926
- this._program.option("--json", "Format output as JSON");
927
- this._program.option("--no-color", "Disable colored output");
928
- if (this._verb && !this._verb.startsWith("-")) {
929
- this._program.name(`power-apps ${this._verb}`);
930
- } else {
931
- this._program.name("power-apps");
932
- this._program.usage("[option] [command] [<args>]");
933
- }
934
- this._program.version(package_default.version, "-v, --version", "output the current version");
935
- this._program.description(HelpStrings.Global.ProgramDescription);
936
- this._program.addHelpText("after", (_context) => {
937
- if (!this._verb || this._verb.startsWith("-")) {
938
- return `
939
- ` + buildVerbDescriptionTable() + `
940
- `;
941
- }
942
- return "";
943
- });
944
- const settings = getSettings();
945
- this._environmentId = settings.appConfig?.environmentId;
946
- this._region = settings.appConfig?.region;
947
- if (!this._region) {
948
- this.addOption({
949
- flags: {
950
- key: GlobalArguments.Cloud.name
951
- },
952
- env: GlobalArguments.Cloud.envVar,
953
- default: "prod",
954
- description: HelpStrings.Global.Cloud
955
- });
956
- }
957
- if (!this._environmentId) {
958
- this.addOption(createDefaultStringOption({
959
- flags: {
960
- key: GlobalArguments.EnvironmentId.name,
961
- alias: GlobalArguments.EnvironmentId.alias
962
- },
963
- env: GlobalArguments.EnvironmentId.envVar,
964
- message: "Please provide the environment ID:",
965
- description: HelpStrings.Global.EnvironmentId
966
- }));
967
- }
968
- initializePlayerServices({
969
- httpClient: this._httpClient,
970
- logger: this._logger,
971
- region: this._region || "prod",
972
- environmentName: this._environmentId || "default"
973
- });
974
- }
975
- addSwitch(cliOption) {
976
- this._createOption(cliOption, false);
977
- }
978
- addSwitches(cliOptions) {
979
- cliOptions.forEach((cliOption) => this._createOption(cliOption, false));
980
- }
981
- addOption(cliOption) {
982
- this._createOption(cliOption);
983
- }
984
- addOptions(cliOptions) {
985
- cliOptions.forEach((cliOption) => this._createOption(cliOption));
986
- }
987
- async runVerb() {
988
- if (this._verb && !this._verb.startsWith("-") && process.argv[2] === this._verb) {
989
- const args = [process.argv[0], process.argv[1], ...process.argv.slice(3)];
990
- this._program.parse(args);
991
- } else {
992
- this._program.parse();
993
- }
994
- await this._getRequiredVariables();
995
- if (!this._region) {
996
- throw new UsageError("Region is not set. Use --cloud or set the CLOUD_INSTANCE environment variable.");
997
- }
998
- await this._authenticationProvider.initAsync(this._region);
999
- await this._logger.initializeTelemetry(this._authenticationProvider);
1000
- this._logger.trackActivityEvent("Initialize", {
1001
- verb: this._verb
1002
- });
1003
- }
1004
- handleGlobalHelpOrFlagsAndExit() {
1005
- if (!this._verb) {
1006
- this._program.help();
1007
- }
1008
- if (this._verb.startsWith("-")) {
1009
- this._program.parse(process.argv);
1010
- }
1011
- }
1012
- getVerb() {
1013
- if (!this._verb || this._verb.startsWith("-")) {
1014
- throw new UsageError('No command specified. Run "power-apps --help" for available commands.');
1015
- }
1016
- return this._verb;
1017
- }
1018
- async getOption(key, ignorePrompt) {
1019
- const settings = getSettings();
1020
- let value = this._program.getOptionValue(key);
1021
- const option = this._options[key];
1022
- if (value === undefined && option && option.env) {
1023
- value = process.env[option.env];
1024
- }
1025
- if (value === undefined && option && option.default !== undefined) {
1026
- value = option.default;
1027
- }
1028
- if (!value && !ignorePrompt && option?.customPrompt) {
1029
- if (!settings.interactive) {
1030
- if (option.optionalInNonInteractive) {} else {
1031
- const flagName = option.flags.key;
1032
- const alias = option.flags.alias;
1033
- const flagHint = alias ? `--${flagName} (-${alias})` : `--${flagName}`;
1034
- const envHint = option.env ? ` or environment variable (${option.env})` : "";
1035
- throw new UsageError(`Missing required option ${flagHint}${envHint}. In non-interactive mode, all parameters must be provided via flags or environment variables.`);
1036
- }
1037
- } else {
1038
- value = await option.customPrompt();
1039
- }
1040
- }
1041
- return value;
1042
- }
1043
- getAuthenticationProvider() {
1044
- return this._authenticationProvider;
1045
- }
1046
- setDescription(description) {
1047
- this._program.description(description);
1048
- }
1049
- isJsonMode() {
1050
- return this._program.opts().json === true;
1051
- }
1052
- addExamples(examples) {
1053
- if (!examples || examples.length === 0)
1054
- return;
1055
- this._program.addHelpText("after", () => {
1056
- const lines = ["", "Examples:"];
1057
- examples.forEach((example) => {
1058
- lines.push(` $ ${example}`);
1059
- });
1060
- return lines.join(`
1061
- `);
1062
- });
1063
- }
1064
- getEnvironmentId() {
1065
- return this._environmentId;
1066
- }
1067
- async _getRequiredVariables() {
1068
- if (this._verb !== "telemetry" && this._verb !== "logout") {
1069
- if (!this._environmentId) {
1070
- const environmentId = await this.getOption("environmentId");
1071
- if (environmentId) {
1072
- this._environmentId = environmentId;
1073
- updateEnvironmentName(this._environmentId);
1074
- }
1075
- }
1076
- }
1077
- if (!this._region) {
1078
- const region = await this.getOption("cloud");
1079
- if (region) {
1080
- this._region = region;
1081
- updateRegion(region);
1082
- }
1083
- }
1084
- }
1085
- _createOption(cliOption, hasValue = true) {
1086
- const option = this._program.createOption(hasValue ? this._createFlags(cliOption.flags) : this._createSwitchFlags(cliOption.flags), cliOption.description);
1087
- if (!this._verb || this._verb.startsWith("-")) {
1088
- option.hideHelp();
1089
- }
1090
- this._program.addOption(option);
1091
- this._options[option.attributeName()] = cliOption;
1092
- }
1093
- _createFlags(flags) {
1094
- const { key, alias } = flags;
1095
- return alias ? `-${alias}, --${key} <${key}>` : `--${key} <${key}>`;
1096
- }
1097
- _createSwitchFlags(flags) {
1098
- const { key, alias } = flags;
1099
- return alias ? `-${alias}, --${key}` : `--${key}`;
1100
- }
1101
- }
1102
-
1103
- // src/Authentication/PacCliAuthenticationProvider.ts
1104
- import * as readline from "readline";
1105
- /*!
1106
- * Copyright (C) Microsoft Corporation. All rights reserved.
1107
- */
1108
-
1109
- class PacCliAuthenticationProvider {
1110
- _tokenCache = {};
1111
- async initAsync(_region) {}
1112
- async getAccessTokenForResource(resource) {
1113
- return this._getAccessTokenFromResourceInternal(resource);
1114
- }
1115
- getUserTenantId() {
1116
- return;
1117
- }
1118
- async _getAccessTokenFromResourceInternal(resource) {
1119
- if (this._tokenCache[resource]) {
1120
- return this._tokenCache[resource];
1121
- }
1122
- this._requestToken(resource);
1123
- const token = await this._readStdIn();
1124
- if (!token) {
1125
- throw new Error("No token provided");
1126
- }
1127
- this._tokenCache[resource] = token;
1128
- return token;
1129
- }
1130
- _requestToken(resource) {
1131
- console.log("REQUEST_TOKEN " + resource);
1132
- }
1133
- async _readStdIn() {
1134
- return new Promise((resolve, reject) => {
1135
- const rl = readline.createInterface({
1136
- input: process.stdin,
1137
- output: process.stdout,
1138
- terminal: false
1139
- });
1140
- const timeout = setTimeout(() => {
1141
- rl.close();
1142
- reject(new Error("Token input timeout: No token received within 10 seconds"));
1143
- }, 1e4);
1144
- rl.once("line", (line) => {
1145
- clearTimeout(timeout);
1146
- rl.close();
1147
- resolve(line.trim());
1148
- });
1149
- });
1150
- }
1151
- }
1152
-
1153
- // src/HttpClient/CliHttpClient.ts
1154
- import { spinner } from "@clack/prompts";
1155
- import { randomUUID } from "crypto";
1156
- init_Constants();
1157
-
1158
- // src/Utils/EnhanceNetworkError.ts
1159
- /*!
1160
- * Copyright (C) Microsoft Corporation. All rights reserved.
1161
- */
1162
- function enhanceNetworkError(error, method, url) {
1163
- if (!(error instanceof TypeError) || !error.message.includes("fetch failed")) {
1164
- return error instanceof Error ? error : new Error(String(error));
1165
- }
1166
- let detailedMessage = `Network request failed for ${method} ${url}.`;
1167
- const cause = error.cause;
1168
- if (cause) {
1169
- const errorCode = cause.code || cause.errno;
1170
- if (errorCode === "ENOTFOUND") {
1171
- detailedMessage += ` DNS lookup failed - unable to resolve hostname.`;
1172
- } else if (errorCode === "ECONNREFUSED") {
1173
- detailedMessage += ` Connection refused - server is not accepting connections.`;
1174
- } else if (errorCode === "ETIMEDOUT") {
1175
- detailedMessage += ` Connection timed out - server did not respond in time.`;
1176
- } else if (errorCode === "ECONNRESET") {
1177
- detailedMessage += ` Connection reset - server closed the connection unexpectedly.`;
1178
- } else if (errorCode === "UNABLE_TO_VERIFY_LEAF_SIGNATURE" || errorCode === "CERT_HAS_EXPIRED" || String(errorCode).startsWith("CERT_")) {
1179
- detailedMessage += ` Certificate validation failed (${errorCode}).`;
1180
- } else if (errorCode) {
1181
- detailedMessage += ` System error: ${errorCode}.`;
1182
- }
1183
- if (cause.message && cause.message !== error.message) {
1184
- detailedMessage += ` Details: ${cause.message}`;
1185
- }
1186
- }
1187
- if (!cause || !cause.code) {
1188
- detailedMessage += ` Possible causes: network connectivity issues, DNS resolution failure, ` + `VPN/proxy configuration, firewall/certificate issues, or server not reachable.`;
1189
- }
1190
- const enhancedError = new Error(detailedMessage);
1191
- enhancedError.cause = error;
1192
- return enhancedError;
1193
- }
1194
-
1195
- // src/HttpClient/CliHttpClient.ts
1196
- /*!
1197
- * Copyright (C) Microsoft Corporation. All rights reserved.
1198
- */
1199
-
1200
- class CliHttpClient {
1201
- _authenticationProvider;
1202
- _inflight = 0;
1203
- _spinner = spinner();
1204
- constructor(_authenticationProvider) {
1205
- this._authenticationProvider = _authenticationProvider;
1206
- }
1207
- async get(url, config) {
1208
- return this._sendRequestAsync(url, "GET", config);
1209
- }
1210
- async post(url, config) {
1211
- return this._sendRequestAsync(url, "POST", config);
1212
- }
1213
- async patch(url, config) {
1214
- return this._sendRequestAsync(url, "PATCH", config);
1215
- }
1216
- async put(url, config) {
1217
- return this._sendRequestAsync(url, "PUT", config);
1218
- }
1219
- async _sendRequestAsync(url, method, config) {
1220
- this._startSpinner();
1221
- try {
1222
- const headers = config?.headers || {};
1223
- if (config?.authResource) {
1224
- const token = await this._authenticationProvider.getAccessTokenForResource(config.authResource);
1225
- headers.Authorization = `Bearer ${token}`;
1226
- }
1227
- if (!headers["Content-Type"]) {
1228
- headers["Content-Type"] = "application/json";
1229
- }
1230
- headers[MS_CLIENT_REQUESTID] = randomUUID();
1231
- let bodyContent;
1232
- if (config?.body !== undefined) {
1233
- const isJsonContentType = headers["Content-Type"] === "application/json";
1234
- bodyContent = typeof config.body === "string" && !isJsonContentType ? config.body : JSON.stringify(config.body);
1235
- }
1236
- const requestOptions = {
1237
- method,
1238
- headers,
1239
- body: bodyContent
1240
- };
1241
- const response = await fetch(url, requestOptions);
1242
- if (!response.ok) {
1243
- throw new Error(`HTTP error status: ${response.status} for ${method} ${url}: ${await response.text()}`);
1244
- }
1245
- const data = await this._parseResponse(response);
1246
- return {
1247
- data,
1248
- status: response.status,
1249
- headers: await this._transformHeaders(response.headers)
1250
- };
1251
- } catch (error) {
1252
- throw enhanceNetworkError(error, method, url);
1253
- } finally {
1254
- this._stopSpinner();
1255
- }
1256
- }
1257
- _startSpinner() {
1258
- this._inflight++;
1259
- if (this._inflight === 1 && getSettings().interactive) {
1260
- this._spinner.start("Loading...");
1261
- }
1262
- }
1263
- _stopSpinner() {
1264
- this._inflight--;
1265
- if (this._inflight === 0 && getSettings().interactive) {
1266
- this._spinner.stop("");
1267
- if (process.stdin.isTTY && process.stdin.setRawMode) {
1268
- process.stdin.setRawMode(false);
1269
- }
1270
- }
1271
- }
1272
- async _parseResponse(response) {
1273
- const contentType = response.headers.get("content-type");
1274
- const responseText = await response.text();
1275
- if (!responseText || responseText.trim() === "") {
1276
- return null;
1277
- } else if (contentType && contentType.includes("application/json")) {
1278
- try {
1279
- return JSON.parse(responseText);
1280
- } catch (parseError) {
1281
- throw new Error(`Failed to parse JSON response: ${parseError}`);
1282
- }
1283
- } else {
1284
- return responseText;
1285
- }
1286
- }
1287
- async _transformHeaders(headers) {
1288
- const result = {};
1289
- headers.forEach((value, key) => {
1290
- result[key] = value;
1291
- });
1292
- return result;
1293
- }
1294
- }
1295
-
1296
- // src/Logger/CliLogger.ts
1297
- import { getEnvironmentByName, initializePlayerServices as initializePlayerServices2 } from "@microsoft/power-apps-actions";
1298
- import { randomUUID as randomUUID2 } from "crypto";
1299
-
1300
- // src/Logger/ConsoleWriter.ts
1301
- import chalk from "chalk";
1302
- /*!
1303
- * Copyright (C) Microsoft Corporation. All rights reserved.
1304
- */
1305
- function loggerFn(color, log = console.log.bind(console)) {
1306
- return (scenarioName, ...data) => {
1307
- const time = new Date().toISOString().split("T")[1];
1308
- const prefix = `${chalk.gray(time)}: [${color(scenarioName)}]: `;
1309
- log(prefix, ...data);
1310
- };
1311
- }
1312
- var activity = loggerFn(chalk.white.bold);
1313
- var scenario = loggerFn(chalk.cyan.bold);
1314
- var error = loggerFn(chalk.red.bold, console.error.bind(console));
1315
- var warn = loggerFn(chalk.yellow.bold);
1316
-
1317
- class ConsoleWriter {
1318
- trackActivityEvent(eventName, eventData) {
1319
- activity(eventName, eventData || {});
1320
- }
1321
- trackErrorEvent(eventName, eventData) {
1322
- error(eventName, eventData || {});
1323
- }
1324
- startScenario(scenarioName, startData) {
1325
- scenario(`[scenario:start] ${scenarioName}`, startData || {});
1326
- }
1327
- completeScenario(scenarioName, completeData) {
1328
- scenario(`[scenario:complete] ${scenarioName}`, completeData || {});
1329
- }
1330
- scenarioFailed(scenarioName, failureData) {
1331
- error(`[scenario:failure] ${scenarioName}`, failureData || {});
1332
- }
1333
- scenarioCompletedWithError(scenarioName, completeWithErrorData) {
1334
- warn(`[scenario:completeWithError] ${scenarioName}`, completeWithErrorData || {});
1335
- }
1336
- flush() {}
1337
- setCustomDimension(_key, _value) {}
1338
- }
1339
-
1340
- // src/Logger/Constants.ts
1341
- /*!
1342
- * Copyright (C) Microsoft Corporation. All rights reserved.
1343
- */
1344
- var EUGeoRegions = new Set([
1345
- "europe",
1346
- "france",
1347
- "germany",
1348
- "italy",
1349
- "poland",
1350
- "norway",
1351
- "sweden",
1352
- "switzerland",
1353
- "unitedkingdom"
1354
- ]);
1355
-
1356
- // src/Logger/LoggerSettings.ts
1357
- init_Constants();
1358
- import * as fs2 from "fs";
1359
- import * as path3 from "path";
1360
- /*!
1361
- * Copyright (C) Microsoft Corporation. All rights reserved.
1362
- */
1363
- function isTruthy(value) {
1364
- if (!value) {
1365
- return false;
1366
- }
1367
- const normalized = value.trim().toLowerCase();
1368
- return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
1369
- }
1370
- function isFalsy(value) {
1371
- if (!value) {
1372
- return false;
1373
- }
1374
- const normalized = value.trim().toLowerCase();
1375
- return normalized === "0" || normalized === "false" || normalized === "no" || normalized === "off";
1376
- }
1377
- function isPacCliTelemetryEnabled() {
1378
- if (isTruthy(process.env.PAC_CLI_TELEMETRY_OPTOUT)) {
1379
- return false;
1380
- }
1381
- const localAppData = process.env.LOCALAPPDATA;
1382
- if (!localAppData) {
1383
- return;
1384
- }
1385
- const userSettingsPath = path3.join(localAppData, "Microsoft", "PowerAppsCli", "usersettings.json");
1386
- if (!fs2.existsSync(userSettingsPath)) {
1387
- return;
1388
- }
1389
- try {
1390
- const raw = fs2.readFileSync(userSettingsPath, "utf-8");
1391
- const parsed = JSON.parse(raw);
1392
- return typeof parsed.telemetryEnabled === "boolean" ? parsed.telemetryEnabled : undefined;
1393
- } catch (error2) {
1394
- console.warn("Failed to read PAC CLI telemetry settings:", error2.message);
1395
- return;
1396
- }
1397
- }
1398
- function resolveUserTelemetrySettings() {
1399
- const resolved = {
1400
- enabled: true,
1401
- consoleOnly: false,
1402
- outputToConsole: false
1403
- };
1404
- const cliUserSettingsPath = path3.join(CLI_CONFIG_DIRECTORY, USER_SETTINGS_FILE);
1405
- if (fs2.existsSync(cliUserSettingsPath)) {
1406
- try {
1407
- const fileContents = fs2.readFileSync(cliUserSettingsPath, "utf-8");
1408
- const parsed = JSON.parse(fileContents);
1409
- resolved.enabled = parsed.enabled ?? resolved.enabled;
1410
- resolved.consoleOnly = parsed.consoleOnly ?? resolved.consoleOnly;
1411
- resolved.outputToConsole = parsed.outputToConsole ?? resolved.outputToConsole;
1412
- } catch (error2) {
1413
- console.warn("Failed to read CLI telemetry settings:", error2.message);
1414
- }
1415
- }
1416
- if (process.env.POWERAPPS_CLI_TELEMETRY !== undefined && isFalsy(process.env.POWERAPPS_CLI_TELEMETRY)) {
1417
- resolved.enabled = false;
1418
- }
1419
- const pacCliSetting = isPacCliTelemetryEnabled();
1420
- if (typeof pacCliSetting === "boolean" && pacCliSetting === false) {
1421
- resolved.enabled = false;
1422
- }
1423
- return resolved;
1424
- }
1425
-
1426
- // src/Logger/OneDSWriter.ts
1427
- import {
1428
- OneDsTelemetryProvider,
1429
- ScenarioResults,
1430
- TelemetryEventNames
1431
- } from "@microsoft/power-apps-common/telemetry";
1432
-
1433
- // src/Logger/Scrubber/ScrubUtils.ts
1434
- /*!
1435
- * Copyright (C) Microsoft Corporation. All rights reserved.
1436
- */
1437
- var GoogleApiKeyRegex = /AIza[a-z0-9_\\-]{35}/i;
1438
- var SymmKey256Regex = /[a-z0-9\/+]{43}=/i;
1439
- var SasKeyRegex = /(?:dsas_secret|sig)=[^#\)\(<>\r\n\s'",\\_&]{8}/i;
1440
- var emailRegExp = new RegExp(/[a-zA-Z0-9\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFF\u20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF\.!#$%&'*+?^_{|}~\-\d]+(@|%40)[a-zA-Z0-9\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFF\u20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF\-\.\d]+\.[a-zA-Z\u0080-\u00FF\u0100-\u017F\u0180-\u024F\u0250-\u02AF\u0300-\u036F\u0370-\u03FF\u0400-\u04FF\u0500-\u052F\u0530-\u058F\u0590-\u05FF\u0600-\u06FF\u0700-\u074F\u0750-\u077F\u0780-\u07BF\u07C0-\u07FF\u0900-\u097F\u0980-\u09FF\u0A00-\u0A7F\u0A80-\u0AFF\u0B00-\u0B7F\u0B80-\u0BFF\u0C00-\u0C7F\u0C80-\u0CFF\u0D00-\u0D7F\u0D80-\u0DFF\u0E00-\u0E7F\u0E80-\u0EFF\u0F00-\u0FFF\u1000-\u109F\u10A0-\u10FF\u1100-\u11FF\u1200-\u137F\u1380-\u139F\u13A0-\u13FF\u1400-\u167F\u1680-\u169F\u16A0-\u16FF\u1700-\u171F\u1720-\u173F\u1740-\u175F\u1760-\u177F\u1780-\u17FF\u1800-\u18AF\u1900-\u194F\u1950-\u197F\u1980-\u19DF\u19E0-\u19FF\u1A00-\u1A1F\u1B00-\u1B7F\u1D00-\u1D7F\u1D80-\u1DBF\u1DC0-\u1DFF\u1E00-\u1EFF\u1F00-\u1FFF\u20D0-\u20FF\u2100-\u214F\u2C00-\u2C5F\u2C60-\u2C7F\u2C80-\u2CFF\u2D00-\u2D2F\u2D30-\u2D7F\u2D80-\u2DDF\u2F00-\u2FDF\u2FF0-\u2FFF\u3040-\u309F\u30A0-\u30FF\u3100-\u312F\u3130-\u318F\u3190-\u319F\u31C0-\u31EF\u31F0-\u31FF\u3200-\u32FF\u3300-\u33FF\u3400-\u4DBF\u4DC0-\u4DFF\u4E00-\u9FFF\uA000-\uA48F\uA490-\uA4CF\uA700-\uA71F\uA800-\uA82F\uA840-\uA87F\uAC00-\uD7AF\uF900-\uFAFF]{2,63}/);
1441
- function containsEmail(value) {
1442
- return emailRegExp.test(value);
1443
- }
1444
- function containsGoogleApiKey(value) {
1445
- return GoogleApiKeyRegex.test(value);
1446
- }
1447
- function containsSasKeySig(value) {
1448
- return SasKeyRegex.test(value);
1449
- }
1450
- function containsSymmKey256(value) {
1451
- return SymmKey256Regex.test(value);
1452
- }
1453
-
1454
- // src/Logger/Scrubber/ScrubCustomDimensionsConfig.ts
1455
- /*!
1456
- * Copyright (C) Microsoft Corporation. All rights reserved.
1457
- */
1458
- var EmailScrubConfig = {
1459
- scrubberName: "email",
1460
- shouldScrubValue: containsEmail
1461
- };
1462
- var GoogleApiKeyScrubConfig = {
1463
- scrubberName: "googleApiKey",
1464
- shouldScrubValue: containsGoogleApiKey
1465
- };
1466
- var SasKeySigScrubConfig = {
1467
- scrubberName: "sasKeySig",
1468
- shouldScrubValue: containsSasKeySig
1469
- };
1470
- var SymmKey256ScrubConfig = {
1471
- scrubberName: "symmKey256",
1472
- shouldScrubValue: containsSymmKey256
1473
- };
1474
- var SasKeyScrubConfigList = [SasKeySigScrubConfig];
1475
- var EventsToScrubConfig = {
1476
- "AppHostClientSDK.getCanvasAppMetadataAsync": {
1477
- "*": SasKeyScrubConfigList
1478
- },
1479
- "AppModuleMetadataProvider.getCanvasAppMetadataAsync.Failure": {
1480
- "*": SasKeyScrubConfigList
1481
- },
1482
- "AppModuleMetadataProvider.getRootAppMetadataAsync.Failure": {
1483
- "*": SasKeyScrubConfigList
1484
- },
1485
- CustomPageInlineRendering: {
1486
- "*": SasKeyScrubConfigList
1487
- },
1488
- "DefaultCanvasAppContainer.renderAsync": {
1489
- "*": SasKeyScrubConfigList
1490
- },
1491
- "FilePluginService.GetFileOrDirectory": {
1492
- "*": SasKeyScrubConfigList
1493
- },
1494
- "Player.CanvasAppGlue.openErrorDialog": {
1495
- "*": SasKeyScrubConfigList
1496
- },
1497
- "PlayerCordovaPlugin.onPluginRequestFailure": {
1498
- "*": SasKeyScrubConfigList
1499
- },
1500
- "PowerAppsClient.Activity": {
1501
- operations: {
1502
- "App.disposeAsync": SasKeyScrubConfigList,
1503
- "GlobalControlProperty.setModelValueInternal": SasKeyScrubConfigList,
1504
- "IDataRuntime.reportRuntimeError": SasKeyScrubConfigList,
1505
- "IDataRuntime.tryCreateGatedReportRuntimeError": [
1506
- GoogleApiKeyScrubConfig,
1507
- SasKeySigScrubConfig
1508
- ],
1509
- "PassThroughWebUriResolver.getAsBinaryAsync": SasKeyScrubConfigList,
1510
- "PerEndpointRetryPipeline._xhrWithRetryAsync": SasKeyScrubConfigList,
1511
- "Player.AppCatalog.GetAppDetailByIDSuccess": SasKeyScrubConfigList,
1512
- "Player.CanvasAppGlue.exitAppHost": SasKeyScrubConfigList,
1513
- "Player.CustomBranding.RPResponse": SasKeyScrubConfigList,
1514
- "Player.CustomBranding.Save": SasKeyScrubConfigList,
1515
- "Player.PublishedApp.Open.AppInfo": SasKeyScrubConfigList,
1516
- "Player.PublishedApp.WebServer.Start": SasKeyScrubConfigList,
1517
- "PlayerLifecycle.WebPlayer.Play.ErrorPage": SasKeyScrubConfigList,
1518
- "PowerAppsClient.PcfComponent.Failure": SasKeyScrubConfigList,
1519
- "PowerAppsClient.Performance.PerformanceObserver": SasKeyScrubConfigList,
1520
- "PowerAppsEmbedding.Automation.Player": SasKeyScrubConfigList,
1521
- "CachedQueryDataProvider._onDataDownloaded": [EmailScrubConfig],
1522
- "CachedQueryDataProvider._getDataForExpiredCacheAsync": [EmailScrubConfig]
1523
- }
1524
- },
1525
- "PowerAppsClient.AllApps.App.DismissedWithError": {
1526
- "*": SasKeyScrubConfigList
1527
- },
1528
- "PowerAppsClient.App.GalleryPagingManagerError": {
1529
- "*": SasKeyScrubConfigList
1530
- },
1531
- "PowerAppsClient.ControlsActivity": {
1532
- operations: {
1533
- "Attachments.OnView": SasKeyScrubConfigList
1534
- }
1535
- },
1536
- "PowerAppsClient.EndScenario": {
1537
- scenarios: {
1538
- "PowerAppsClient.Scenario.ContextLoadApp": SasKeyScrubConfigList,
1539
- "PowerAppsClient.Scenario.DocumentVmInitialize": SasKeyScrubConfigList,
1540
- "PowerAppsClient.Scenario.ScreenCreation": SasKeyScrubConfigList,
1541
- "PlayerLifecycle.PlayerSDK.PlayApp.LoadApp.CreateAppFrame": SasKeyScrubConfigList,
1542
- "PlayerLifecycle.PlayerSDK.PlayApp.LoadApp": SasKeyScrubConfigList,
1543
- "PlayerLifecycle.PlayerSDK.PlayApp.LoadMetadata.FetchAppPackageMetadata": SasKeyScrubConfigList,
1544
- "PlayerLifecycle.PlayerSDK.PlayApp": SasKeyScrubConfigList,
1545
- "PlayerLifecycle.WebPlayer.Play.PlayApp": SasKeyScrubConfigList,
1546
- "PlayerLifecycle.WebPlayer.Play": SasKeyScrubConfigList,
1547
- "PowerAppsClient.Scenario.CachedQueryDataProviderNotify": [EmailScrubConfig]
1548
- }
1549
- },
1550
- "PowerAppsClient.Error": {
1551
- operations: {
1552
- "AppInfoParser.parseAppInfo": SasKeyScrubConfigList,
1553
- "AppLifecyclePlugin.notifyAppFailed": SasKeyScrubConfigList,
1554
- "AttachmentsView._viewItem": SasKeyScrubConfigList,
1555
- "BaseWebPlayerHost._onAppFailure": SasKeyScrubConfigList,
1556
- "Context.loadAppAsync": SasKeyScrubConfigList,
1557
- "DocumentViewModel.initializeAsync": SasKeyScrubConfigList,
1558
- "GeneratedCode.ReportAndContinue": SasKeyScrubConfigList,
1559
- "MediaRuntime.getMediaAsBinaryAsync": SasKeyScrubConfigList,
1560
- "NestedAppModuleMetadataProvider.getCanvasAppMetadataAsync.Failure": SasKeyScrubConfigList,
1561
- "Player.SessionSummary.Failure": SasKeyScrubConfigList,
1562
- "PlayerLaunchService.playerLaunchAppAsync": SasKeyScrubConfigList,
1563
- "PlayerPublishedApp._onInitializationError": SasKeyScrubConfigList,
1564
- "PowerAppsClient.PublishedApp.ErrorLoadingScript": SasKeyScrubConfigList,
1565
- "PublishedAppHostActions.handleErrorDuringInstall": SasKeyScrubConfigList,
1566
- "PublishedAppInstance.runAllScreensInitFnsAsync": SasKeyScrubConfigList,
1567
- "RNSendHttpPipeline._performXhrRequestAsync": [SymmKey256ScrubConfig],
1568
- "RequirementsManager.loadRequirement": SasKeyScrubConfigList,
1569
- "runtimebase._onCallFailed": SasKeyScrubConfigList,
1570
- "Text._validateTextWithCharacters": SasKeyScrubConfigList,
1571
- "Url.constructor": SasKeyScrubConfigList
1572
- }
1573
- },
1574
- "PowerAppsClient.Functions.InternalError": {
1575
- "*": SasKeyScrubConfigList
1576
- },
1577
- "PowerAppsClient.MessageDialog.Dismissed": {
1578
- operations: {
1579
- "Studio.Reducers.STUDIO_UPDATE_CONNECTION_TABLES_LOADING_ERROR_INFO": SasKeyScrubConfigList
1580
- }
1581
- },
1582
- "PowerAppsClient.MessageDialog.ShowAsync": {
1583
- operations: {
1584
- "Studio.Reducers.STUDIO_UPDATE_CONNECTION_TABLES_LOADING_ERROR_INFO": SasKeyScrubConfigList
1585
- }
1586
- },
1587
- "PowerAppsClient.StartScenario": {
1588
- scenarios: {
1589
- "PowerAppsClient.Scenario.CachedQueryDataProviderNotify": [EmailScrubConfig]
1590
- }
1591
- },
1592
- "PowerAppsClient.Verbose": {
1593
- operations: {
1594
- "ReactRedux.HandleActionsWithReset": SasKeyScrubConfigList
1595
- }
1596
- },
1597
- "PowerAppsClient.WebPlayer.Load": {
1598
- operations: {
1599
- "PowerAppsClient._notifyAppFailed": SasKeyScrubConfigList,
1600
- "PowerAppsClient.AppDetailsRetriever._getAppDetailsInternal.Failure": SasKeyScrubConfigList,
1601
- "PowerAppsClient.ResourcePathResolution": SasKeyScrubConfigList
1602
- }
1603
- },
1604
- "PublishedAppLoader.ScriptError": {
1605
- operations: {
1606
- "GlobalErrorHandler:UnhandledError": SasKeyScrubConfigList,
1607
- "PowerAppsClient.AppDetailsRetriever._getAppDetailsInternal.Failure": SasKeyScrubConfigList
1608
- }
1609
- },
1610
- "RuntimeTelemetry.logException": {
1611
- "*": SasKeyScrubConfigList
1612
- },
1613
- "TestOrchestrator.setupTestsAsync": {
1614
- "*": SasKeyScrubConfigList
1615
- }
1616
- };
1617
-
1618
- // src/Logger/Scrubber/ScrubCustomDimensions.ts
1619
- /*!
1620
- * Copyright (C) Microsoft Corporation. All rights reserved.
1621
- */
1622
- function getScrubbedCustomDimensions(eventName, operationName, customDimensions) {
1623
- const eventConfig = EventsToScrubConfig[eventName];
1624
- if (eventConfig) {
1625
- const scenarioName = customDimensions.scenarioName || "";
1626
- const scrubConfigList = eventConfig["*"] || eventConfig.operations?.[operationName] || eventConfig.scenarios?.[scenarioName];
1627
- if (scrubConfigList) {
1628
- let currentScrubberName;
1629
- try {
1630
- const value = JSON.stringify(customDimensions);
1631
- for (const { scrubberName, shouldScrubValue } of scrubConfigList) {
1632
- currentScrubberName = scrubberName;
1633
- if (shouldScrubValue(value)) {
1634
- return {
1635
- eventName,
1636
- operationName,
1637
- scenarioName,
1638
- scrubber: currentScrubberName,
1639
- message: "_scrubbedByPowerAppsTelemetryUtils_: Custom dimensions were scrubbed by host"
1640
- };
1641
- }
1642
- }
1643
- } catch (error2) {
1644
- return {
1645
- eventName,
1646
- operationName,
1647
- scenarioName,
1648
- scrubber: currentScrubberName,
1649
- message: "_scrubbedByPowerAppsTelemetryUtils_: Failed to parse custom dimensions while scrubbing"
1650
- };
1651
- }
1652
- }
1653
- }
1654
- return customDimensions;
1655
- }
1656
-
1657
- // src/Logger/OneDSWriter.ts
1658
- /*!
1659
- * Copyright (C) Microsoft Corporation. All rights reserved.
1660
- */
1661
- function regionToClusterCategory(region) {
1662
- switch (region) {
1663
- case "preview":
1664
- return "prod";
1665
- case "gccmoderate":
1666
- return "gov";
1667
- case "gcchigh":
1668
- return "high";
1669
- default:
1670
- return region;
1671
- }
1672
- }
1673
-
1674
- class OneDSWriter {
1675
- _provider;
1676
- _sequenceNumber = 1;
1677
- constructor(sessionId, region, telemetryLocation, environmentId, appId, geoLocation, cliVersion, cliSource) {
1678
- const commonProperties = {
1679
- environmentId,
1680
- isOnePlayer: "false",
1681
- webPlayerScenario: "CodeApp_CLI_Authoring",
1682
- cloud: region === "preview" ? "prod" : region,
1683
- sessionStartTime: new Date().toISOString(),
1684
- station: "Unknown",
1685
- telemetryLocation,
1686
- cliVersion,
1687
- cliSource
1688
- };
1689
- if (appId) {
1690
- commonProperties.playerAppId = `/providers/Microsoft.PowerApps/apps/${appId}`;
1691
- }
1692
- if (geoLocation) {
1693
- commonProperties.geoLocation = geoLocation;
1694
- }
1695
- this._provider = new OneDsTelemetryProvider({
1696
- clientType: cliSource === "pac-cli" ? "PacCLI" : "NodeCLI",
1697
- clusterCategory: regionToClusterCategory(region),
1698
- telemetryLocation,
1699
- commonProperties,
1700
- propertyColumnMap: {
1701
- latencyInMs: "duration",
1702
- elapsedTime: "duration",
1703
- updateCadence: "updateCadence",
1704
- requestedUrl: "url",
1705
- status: "httpStatus",
1706
- statusCode: "httpStatus"
1707
- },
1708
- channelConfig: {
1709
- maxEvtPerBatch: 500,
1710
- maxEventRetryAttempts: 6,
1711
- eventsLimitInMem: 1e4
1712
- }
1713
- });
1714
- this._provider.sessionId = sessionId;
1715
- this._provider.addTelemetryInitializer((envelope) => {
1716
- const ext = envelope.ext = envelope.ext ?? {};
1717
- const app = ext.app = ext.app ?? {};
1718
- app.sesId = sessionId;
1719
- });
1720
- }
1721
- trackActivityEvent(operationName, eventData) {
1722
- this._trackEvent(TelemetryEventNames.Activity, {
1723
- ...eventData,
1724
- operationName
1725
- });
1726
- }
1727
- trackErrorEvent(operationName, eventData) {
1728
- this._trackEvent(TelemetryEventNames.Error, {
1729
- ...eventData,
1730
- operationName
1731
- });
1732
- }
1733
- startScenario(scenarioName, startData) {
1734
- this._trackEvent(TelemetryEventNames.StartScenario, {
1735
- operationName: scenarioName,
1736
- ...startData,
1737
- scenarioName
1738
- });
1739
- }
1740
- completeScenario(scenarioName, completeData) {
1741
- this._trackEvent(TelemetryEventNames.EndScenario, {
1742
- operationName: scenarioName,
1743
- ...completeData,
1744
- scenarioName,
1745
- scenarioResult: ScenarioResults.Success
1746
- });
1747
- }
1748
- scenarioFailed(scenarioName, failureData) {
1749
- this._trackEvent(TelemetryEventNames.EndScenario, {
1750
- operationName: scenarioName,
1751
- ...failureData,
1752
- scenarioName,
1753
- scenarioResult: ScenarioResults.Failed
1754
- });
1755
- }
1756
- scenarioCompletedWithError(scenarioName, completeWithErrorData) {
1757
- this._trackEvent(TelemetryEventNames.EndScenario, {
1758
- operationName: scenarioName,
1759
- ...completeWithErrorData,
1760
- scenarioName,
1761
- scenarioResult: ScenarioResults.SuccessWithErrors
1762
- });
1763
- }
1764
- flush() {
1765
- this._provider.flush();
1766
- }
1767
- setCustomDimension(_key, _value) {
1768
- this._provider.setDefaultProperty(_key, _value);
1769
- }
1770
- static _EVENT_PREFIX = "CodeAppsCLI.";
1771
- _trackEvent(eventName, eventData) {
1772
- const operationName = eventData.operationName || "";
1773
- const scrubbed = getScrubbedCustomDimensions(eventName, operationName, eventData);
1774
- const properties = {};
1775
- for (const [key, value] of Object.entries(scrubbed)) {
1776
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1777
- properties[key] = value;
1778
- } else {
1779
- properties[key] = String(value);
1780
- }
1781
- }
1782
- if (operationName) {
1783
- properties.operationName = `${OneDSWriter._EVENT_PREFIX}${operationName}`;
1784
- }
1785
- this._provider.track({
1786
- eventName,
1787
- timestamp: new Date().toISOString(),
1788
- severity: "info",
1789
- sequenceNumber: this._sequenceNumber++,
1790
- properties
1791
- });
1792
- }
1793
- }
1794
-
1795
- // src/Logger/CliLogger.ts
1796
- /*!
1797
- * Copyright (C) Microsoft Corporation. All rights reserved.
1798
- */
1799
- function createScenarioLogger(telemetryWriters, name, data) {
1800
- const scenarioGuid = randomUUID2();
1801
- const _start = Date.now();
1802
- try {
1803
- telemetryWriters.forEach((writer) => writer.startScenario(name, { scenarioGuid, ...data, scenarioStartTime: _start }));
1804
- } catch {}
1805
- const base = {
1806
- scenarioId: scenarioGuid,
1807
- complete: (completeData) => {
1808
- try {
1809
- telemetryWriters.forEach((writer) => writer.completeScenario(name, {
1810
- scenarioGuid,
1811
- elapsedTime: Date.now() - _start,
1812
- totalElapsedTime: Date.now() - _start,
1813
- ...completeData
1814
- }));
1815
- } catch {}
1816
- },
1817
- failure: (failureData) => {
1818
- try {
1819
- telemetryWriters.forEach((writer) => writer.scenarioFailed(name, {
1820
- scenarioGuid,
1821
- elapsedTime: Date.now() - _start,
1822
- totalElapsedTime: Date.now() - _start,
1823
- ...failureData
1824
- }));
1825
- } catch {}
1826
- },
1827
- completeWithError: (dataWithErr) => {
1828
- try {
1829
- telemetryWriters.forEach((writer) => writer.scenarioCompletedWithError(name, {
1830
- scenarioGuid,
1831
- elapsedTime: Date.now() - _start,
1832
- totalElapsedTime: Date.now() - _start,
1833
- ...dataWithErr
1834
- }));
1835
- } catch {}
1836
- }
1837
- };
1838
- base._start = _start;
1839
- return base;
1840
- }
1841
-
1842
- class CliLogger {
1843
- _telemetryWriters = [];
1844
- _oneDSConfig;
1845
- constructor(telemetryWriters) {
1846
- this._telemetryWriters = telemetryWriters;
1847
- }
1848
- static async create(cliSettings, httpClient) {
1849
- const environmentId = cliSettings.appConfig?.environmentId;
1850
- const region = cliSettings.appConfig?.region;
1851
- const appId = cliSettings.appConfig?.appId;
1852
- const sessionId = randomUUID2();
1853
- const telemetryWriters = [];
1854
- const userTelemetrySettings = resolveUserTelemetrySettings();
1855
- const addConsoleWriter = () => telemetryWriters.push(new ConsoleWriter);
1856
- if (userTelemetrySettings.consoleOnly) {
1857
- addConsoleWriter();
1858
- return new CliLogger(telemetryWriters);
1859
- }
1860
- if (userTelemetrySettings.outputToConsole) {
1861
- addConsoleWriter();
1862
- }
1863
- const instance = new CliLogger(telemetryWriters);
1864
- if (userTelemetrySettings.enabled && region && environmentId) {
1865
- instance._oneDSConfig = {
1866
- sessionId,
1867
- region,
1868
- environmentId,
1869
- appId,
1870
- httpClient,
1871
- cliSettings
1872
- };
1873
- }
1874
- return instance;
1875
- }
1876
- async initializeTelemetry(authenticationProvider) {
1877
- if (!this._oneDSConfig) {
1878
- return;
1879
- }
1880
- const { sessionId, region, environmentId, appId, httpClient, cliSettings } = this._oneDSConfig;
1881
- this._oneDSConfig = undefined;
1882
- try {
1883
- initializePlayerServices2({
1884
- httpClient,
1885
- environmentName: cliSettings.appConfig?.environmentId || "default",
1886
- region: cliSettings.appConfig?.region || "prod"
1887
- });
1888
- const metadata = await getEnvironmentByName(environmentId);
1889
- let telemetryLocation = "global";
1890
- if (metadata?.properties?.location && EUGeoRegions.has(metadata.properties.location)) {
1891
- telemetryLocation = "eu";
1892
- }
1893
- this._telemetryWriters.push(new OneDSWriter(sessionId, region, telemetryLocation, environmentId, appId ?? "", metadata?.properties?.cluster?.geoShortName, package_default.version, cliSettings.source));
1894
- } catch (error2) {
1895
- console.error("CliLogger: failed to initialize OneDS telemetry writer", error2);
1896
- }
1897
- if (authenticationProvider.getUserTenantId()) {
1898
- this.setCustomDimension("tenantId", authenticationProvider.getUserTenantId());
1899
- }
1900
- }
1901
- setCustomDimension(_key, _value) {
1902
- try {
1903
- if (!_key || !_value) {
1904
- return;
1905
- }
1906
- this._telemetryWriters.forEach((writer) => {
1907
- writer.setCustomDimension(_key, _value);
1908
- });
1909
- } catch {}
1910
- }
1911
- trackActivityEvent(eventName, eventData) {
1912
- try {
1913
- if (this._telemetryWriters.length === 0) {
1914
- return;
1915
- }
1916
- this._telemetryWriters.forEach((writer) => writer.trackActivityEvent(eventName, eventData));
1917
- } catch {}
1918
- }
1919
- trackErrorEvent(eventName, eventData) {
1920
- try {
1921
- if (this._telemetryWriters.length === 0) {
1922
- return;
1923
- }
1924
- this._telemetryWriters.forEach((writer) => writer.trackErrorEvent(eventName, eventData));
1925
- } catch {}
1926
- }
1927
- trackScenario(eventName, eventData) {
1928
- try {
1929
- if (this._telemetryWriters.length === 0) {
1930
- return {
1931
- scenarioId: "disabled",
1932
- complete: () => {
1933
- return;
1934
- },
1935
- failure: () => {
1936
- return;
1937
- },
1938
- completeWithError: () => {
1939
- return;
1940
- }
1941
- };
1942
- }
1943
- return createScenarioLogger(this._telemetryWriters, eventName, eventData);
1944
- } catch {
1945
- return {
1946
- scenarioId: "error",
1947
- complete: () => {
1948
- return;
1949
- },
1950
- failure: () => {
1951
- return;
1952
- },
1953
- completeWithError: () => {
1954
- return;
1955
- }
1956
- };
1957
- }
1958
- }
1959
- stringifyError(err) {
1960
- if (!err) {
1961
- return;
1962
- }
1963
- if (err instanceof Error) {
1964
- return `${err.name}: ${err.message}${err.stack ? `
1965
- ` + err.stack : ""}`;
1966
- }
1967
- try {
1968
- return JSON.stringify(err);
1969
- } catch {
1970
- return String(err);
1971
- }
1972
- }
1973
- flush() {
1974
- return Promise.all(this._telemetryWriters.map((writer) => writer.flush())).then(() => {
1975
- return;
1976
- });
1977
- }
1978
- }
1979
-
1980
- // src/Verbs/AddDataSource.ts
1981
- import {
1982
- addDataSourceAsync as addDataSourceActionsAsync,
1983
- getPlayerServiceConfig
1984
- } from "@microsoft/power-apps-actions";
1985
- init_CliUtils();
1986
- /*!
1987
- * Copyright (C) Microsoft Corporation. All rights reserved.
1988
- */
1989
- async function addDataSourceAsync(argumentProvider) {
1990
- const settings = getSettings();
1991
- const { fileConfig, cliFs } = settings;
1992
- createOptionSchema(argumentProvider);
1993
- await argumentProvider.runVerb();
1994
- const playerServiceConfig = getPlayerServiceConfig();
1995
- const authenticationProvider = argumentProvider.getAuthenticationProvider();
1996
- const dsConfig = {
1997
- vfs: cliFs,
1998
- authProvider: authenticationProvider,
1999
- region: playerServiceConfig.region,
2000
- environmentName: playerServiceConfig.environmentName,
2001
- actionsParams: {
2002
- apiId: () => argumentProvider.getOption("apiId"),
2003
- connectionId: () => argumentProvider.getOption("connectionId"),
2004
- tableName: () => argumentProvider.getOption("resourceName"),
2005
- dataset: () => argumentProvider.getOption("dataset"),
2006
- sqlStoredProcedure: () => argumentProvider.getOption("sqlStoredProcedure"),
2007
- envUrl: () => argumentProvider.getOption("orgUrl"),
2008
- solutionId: () => argumentProvider.getOption("solutionId"),
2009
- connectionRef: () => argumentProvider.getOption("connectionRef")
2010
- },
2011
- localFilePaths: {
2012
- powerConfigPath: fileConfig.powerConfigPath,
2013
- schemaPath: fileConfig.schemaPath,
2014
- codeGenPath: fileConfig.codeGenPath
2015
- },
2016
- logger: getCliLogger()
2017
- };
2018
- await addDataSourceActionsAsync(dsConfig);
2019
- console.log("Data source added successfully.");
2020
- console.log("Hint: Run 'npx power-apps run' to test locally, or 'npx power-apps push' to deploy.");
2021
- }
2022
- function createOptionSchema(argumentProvider) {
2023
- argumentProvider.setDescription(HelpStrings.Verbs["Add-data-source"].Description);
2024
- argumentProvider.addExamples(HelpStrings.Verbs["Add-data-source"].Examples);
2025
- argumentProvider.addOptions([
2026
- createDefaultStringOption({
2027
- flags: {
2028
- key: SharedArguments.ApiId.name,
2029
- alias: SharedArguments.ApiId.alias
2030
- },
2031
- env: SharedArguments.ApiId.envVar,
2032
- message: SharedArguments.ApiId.promptMessage,
2033
- description: HelpStrings.Verbs["Add-data-source"].Options.ApiId
2034
- }),
2035
- createDefaultStringOption({
2036
- flags: {
2037
- key: SharedArguments.ConnectionId.name,
2038
- alias: SharedArguments.ConnectionId.alias
2039
- },
2040
- env: SharedArguments.ConnectionId.envVar,
2041
- message: SharedArguments.ConnectionId.promptMessage,
2042
- description: HelpStrings.Verbs["Add-data-source"].Options.ConnectionId
2043
- }),
2044
- {
2045
- flags: {
2046
- key: AddDataSourceArguments.ConnectionRef.name,
2047
- alias: AddDataSourceArguments.ConnectionRef.alias
2048
- },
2049
- env: AddDataSourceArguments.ConnectionRef.envVar,
2050
- description: HelpStrings.Verbs["Add-data-source"].Options.ConnectionRef,
2051
- optionalInNonInteractive: true,
2052
- customPrompt: async () => {
2053
- const hasConnectionRef = await promptConfirm({
2054
- message: "Are you using a connection reference instead of a connection ID?"
2055
- });
2056
- if (hasConnectionRef) {
2057
- return await promptText({
2058
- message: AddDataSourceArguments.ConnectionRef.promptMessage
2059
- });
2060
- }
2061
- return "";
2062
- }
2063
- },
2064
- createDefaultStringOption({
2065
- flags: {
2066
- key: SharedArguments.ResourceName.name,
2067
- alias: SharedArguments.ResourceName.alias
2068
- },
2069
- env: SharedArguments.ResourceName.envVar,
2070
- message: SharedArguments.ResourceName.promptMessage,
2071
- description: HelpStrings.Verbs["Add-data-source"].Options.ResourceName
2072
- }),
2073
- createDefaultStringOption({
2074
- flags: {
2075
- key: SharedArguments.Dataset.name,
2076
- alias: SharedArguments.Dataset.alias
2077
- },
2078
- env: SharedArguments.Dataset.envVar,
2079
- message: SharedArguments.Dataset.promptMessage,
2080
- description: HelpStrings.Verbs["Add-data-source"].Options.Dataset
2081
- }),
2082
- createDefaultStringOption({
2083
- flags: {
2084
- key: SharedArguments.OrgUrl.name,
2085
- alias: SharedArguments.OrgUrl.alias
2086
- },
2087
- env: SharedArguments.OrgUrl.envVar,
2088
- message: SharedArguments.OrgUrl.promptMessage,
2089
- description: HelpStrings.Verbs["Add-data-source"].Options.OrgUrl
2090
- }),
2091
- {
2092
- flags: {
2093
- key: SharedArguments.SqlStoredProcedure.name,
2094
- alias: SharedArguments.SqlStoredProcedure.alias
2095
- },
2096
- env: SharedArguments.SqlStoredProcedure.envVar,
2097
- description: HelpStrings.Verbs["Add-data-source"].Options.SqlStoredProcedure,
2098
- optionalInNonInteractive: true,
2099
- customPrompt: async () => {
2100
- const hasSqlProcedure = await promptConfirm({
2101
- message: "Are you trying to add an SQL stored procedure?"
2102
- });
2103
- if (hasSqlProcedure) {
2104
- return await promptText({
2105
- message: SharedArguments.SqlStoredProcedure.promptMessage
2106
- });
2107
- }
2108
- return "";
2109
- }
2110
- },
2111
- createDefaultStringOption({
2112
- flags: {
2113
- key: SharedArguments.SolutionId.name,
2114
- alias: SharedArguments.SolutionId.alias
2115
- },
2116
- env: SharedArguments.SolutionId.envVar,
2117
- message: SharedArguments.SolutionId.promptMessage,
2118
- description: HelpStrings.Verbs["Add-data-source"].Options.SolutionId
2119
- })
2120
- ]);
2121
- }
2122
- // src/Verbs/DeleteDataSource.ts
2123
- import {
2124
- deleteDataSourceAsync as deleteDataSourceActionAsync,
2125
- getPlayerServiceConfig as getPlayerServiceConfig2
2126
- } from "@microsoft/power-apps-actions";
2127
- init_CliUtils();
2128
- /*!
2129
- * Copyright (C) Microsoft Corporation. All rights reserved.
2130
- */
2131
- async function deleteDataSourceAsync(argumentProvider) {
2132
- const settings = getSettings();
2133
- const { fileConfig, cliFs } = settings;
2134
- createOptionSchema2(argumentProvider);
2135
- await argumentProvider.runVerb();
2136
- const force = await argumentProvider.getOption("force", true);
2137
- if (!force && settings.interactive) {
2138
- const confirmed = await promptConfirm({
2139
- message: "Are you sure you want to delete this data source?"
2140
- });
2141
- if (!confirmed) {
2142
- console.log("Delete cancelled.");
2143
- return false;
2144
- }
2145
- }
2146
- const playerServiceConfig = getPlayerServiceConfig2();
2147
- const authenticationProvider = argumentProvider.getAuthenticationProvider();
2148
- const memo = (fn) => {
2149
- let promise;
2150
- return () => promise ??= fn();
2151
- };
2152
- const getApiId = memo(() => argumentProvider.getOption("apiId"));
2153
- const getDataSourceName = memo(() => argumentProvider.getOption("dataSourceName"));
2154
- const getSqlStoredProcedure = memo(() => argumentProvider.getOption("sqlStoredProcedure"));
2155
- const config = {
2156
- vfs: cliFs,
2157
- authProvider: authenticationProvider,
2158
- region: playerServiceConfig.region,
2159
- environmentName: playerServiceConfig.environmentName,
2160
- localFilePaths: fileConfig,
2161
- actionsParams: {
2162
- apiId: getApiId,
2163
- dataSourceName: getDataSourceName,
2164
- sqlStoredProcedure: getSqlStoredProcedure
2165
- },
2166
- logger: getCliLogger()
2167
- };
2168
- const returnValue = await deleteDataSourceActionAsync(config);
2169
- if (returnValue) {
2170
- const apiId = await getApiId();
2171
- const isSql = apiId.replace("shared_", "").toLowerCase() === "sql";
2172
- const dataSourceLabel = isSql ? await getSqlStoredProcedure() : await getDataSourceName();
2173
- console.log(`${dataSourceLabel} from API ${apiId} deleted successfully.`);
2174
- }
2175
- return returnValue;
2176
- }
2177
- function createOptionSchema2(argumentProvider) {
2178
- argumentProvider.setDescription(HelpStrings.Verbs["Delete-data-source"].Description);
2179
- argumentProvider.addExamples(HelpStrings.Verbs["Delete-data-source"].Examples);
2180
- argumentProvider.addSwitch({
2181
- flags: { key: "force", alias: "f" },
2182
- env: "",
2183
- description: HelpStrings.Verbs["Delete-data-source"].Options.Force
2184
- });
2185
- argumentProvider.addOptions([
2186
- createDefaultStringOption({
2187
- flags: {
2188
- key: DeleteDataSourceArguments.DataSourceName.name,
2189
- alias: DeleteDataSourceArguments.DataSourceName.alias
2190
- },
2191
- env: DeleteDataSourceArguments.DataSourceName.envVar ? DeleteDataSourceArguments.DataSourceName.envVar : SharedArguments.ResourceName.envVar,
2192
- message: DeleteDataSourceArguments.DataSourceName.promptMessage,
2193
- description: HelpStrings.Verbs["Delete-data-source"].Options.DataSourceName
2194
- }),
2195
- createDefaultStringOption({
2196
- flags: {
2197
- key: SharedArguments.ApiId.name,
2198
- alias: SharedArguments.ApiId.alias
2199
- },
2200
- env: SharedArguments.ApiId.envVar,
2201
- message: SharedArguments.ApiId.promptMessage,
2202
- description: HelpStrings.Verbs["Delete-data-source"].Options.ApiId
2203
- }),
2204
- {
2205
- flags: {
2206
- key: SharedArguments.SqlStoredProcedure.name,
2207
- alias: SharedArguments.SqlStoredProcedure.alias
2208
- },
2209
- env: SharedArguments.SqlStoredProcedure.envVar,
2210
- description: HelpStrings.Verbs["Delete-data-source"].Options.SqlStoredProcedure,
2211
- optionalInNonInteractive: true,
2212
- customPrompt: async () => {
2213
- const hasSqlProcedure = await promptConfirm({
2214
- message: "Do you have an SQL procedure?"
2215
- });
2216
- if (hasSqlProcedure) {
2217
- return await promptText({
2218
- message: SharedArguments.SqlStoredProcedure.promptMessage
2219
- });
2220
- }
2221
- return "";
2222
- }
2223
- }
2224
- ]);
2225
- }
2226
- // src/Verbs/Init.ts
2227
- import { getEnvironmentByName as getEnvironmentByName2 } from "@microsoft/power-apps-actions";
2228
- import { VERSION, writeRepoConfig } from "@microsoft/power-apps-actions";
2229
- init_CliUtils();
2230
- /*!
2231
- * Copyright (C) Microsoft Corporation. All rights reserved.
2232
- */
2233
- async function initAsync(argumentProvider) {
2234
- const settings = getSettings();
2235
- if (settings.appConfig) {
2236
- throw new UsageError("power.config.json already exists in this directory. Use a new directory or delete the existing config.");
2237
- }
2238
- createOptionSchema3(argumentProvider);
2239
- await argumentProvider.runVerb();
2240
- const environmentId = argumentProvider.getEnvironmentId() || await argumentProvider.getOption("environmentId");
2241
- const region = await argumentProvider.getOption("cloud");
2242
- if (!environmentId) {
2243
- throw new UsageError("Argument environmentId is required. Use --environmentId or -e to specify it.");
2244
- }
2245
- const environmentExists = await validateEnvironmentExists(environmentId);
2246
- if (!environmentExists) {
2247
- throw new Error(`Environment '${environmentId}' not found. Please verify the environment ID and ensure you have access to it.`);
2248
- }
2249
- const displayName = await argumentProvider.getOption("displayName");
2250
- const description = await argumentProvider.getOption("description");
2251
- const buildPath = await argumentProvider.getOption("buildPath");
2252
- const fileEntryPoint = await argumentProvider.getOption("fileEntryPoint");
2253
- const appUrl = await argumentProvider.getOption("appUrl");
2254
- const logoPath = await argumentProvider.getOption("logoPath");
2255
- const appConfig = {
2256
- version: VERSION,
2257
- appId: null,
2258
- appDisplayName: displayName,
2259
- region,
2260
- environmentId,
2261
- description,
2262
- buildPath,
2263
- buildEntryPoint: fileEntryPoint,
2264
- localAppUrl: appUrl,
2265
- logoPath,
2266
- connectionReferences: {},
2267
- databaseReferences: {}
2268
- };
2269
- await writeRepoConfig(settings.fileConfig.powerConfigPath, appConfig);
2270
- console.log(`Created power.config.json for ${displayName}.`);
2271
- console.log("Hint: Run 'npx power-apps add-data-source' to connect data, or 'npx power-apps run' to start locally.");
2272
- }
2273
- function createOptionSchema3(argumentProvider) {
2274
- argumentProvider.setDescription(HelpStrings.Verbs.Init.Description);
2275
- argumentProvider.addExamples(HelpStrings.Verbs.Init.Examples);
2276
- argumentProvider.addOptions([
2277
- createDefaultStringOption({
2278
- flags: {
2279
- key: InitArguments.DisplayName.name,
2280
- alias: InitArguments.DisplayName.alias
2281
- },
2282
- env: InitArguments.DisplayName.envVar,
2283
- message: InitArguments.DisplayName.promptMessage,
2284
- description: HelpStrings.Verbs.Init.Options.DisplayName
2285
- }),
2286
- createDefaultStringOption({
2287
- flags: {
2288
- key: InitArguments.Description.name,
2289
- alias: InitArguments.Description.alias
2290
- },
2291
- env: InitArguments.Description.envVar,
2292
- default: " ",
2293
- message: InitArguments.Description.promptMessage,
2294
- description: HelpStrings.Verbs.Init.Options.Description
2295
- }),
2296
- createDefaultStringOption({
2297
- flags: {
2298
- key: InitArguments.BuildPath.name,
2299
- alias: InitArguments.BuildPath.alias
2300
- },
2301
- env: InitArguments.BuildPath.envVar,
2302
- message: InitArguments.BuildPath.promptMessage,
2303
- initialValue: InitArguments.BuildPath.initialValue,
2304
- default: "./dist",
2305
- description: HelpStrings.Verbs.Init.Options.BuildPath
2306
- }),
2307
- createDefaultStringOption({
2308
- flags: {
2309
- key: InitArguments.FileEntryPoint.name,
2310
- alias: InitArguments.FileEntryPoint.alias
2311
- },
2312
- env: InitArguments.FileEntryPoint.envVar,
2313
- message: InitArguments.FileEntryPoint.promptMessage,
2314
- initialValue: InitArguments.FileEntryPoint.initialValue,
2315
- default: "index.html",
2316
- description: HelpStrings.Verbs.Init.Options.FileEntryPoint
2317
- }),
2318
- createDefaultStringOption({
2319
- flags: {
2320
- key: InitArguments.AppUrl.name,
2321
- alias: InitArguments.AppUrl.alias
2322
- },
2323
- env: InitArguments.AppUrl.envVar,
2324
- message: InitArguments.AppUrl.promptMessage,
2325
- initialValue: InitArguments.AppUrl.initialValue,
2326
- default: "http://localhost:3000",
2327
- description: HelpStrings.Verbs.Init.Options.AppUrl
2328
- }),
2329
- createDefaultStringOption({
2330
- flags: {
2331
- key: InitArguments.LogoPath.name,
2332
- alias: InitArguments.LogoPath.alias
2333
- },
2334
- env: InitArguments.LogoPath.envVar,
2335
- message: InitArguments.LogoPath.promptMessage,
2336
- initialValue: InitArguments.LogoPath.initialValue,
2337
- default: "Default",
2338
- description: HelpStrings.Verbs.Init.Options.LogoPath
2339
- })
2340
- ]);
2341
- }
2342
- async function validateEnvironmentExists(environmentId) {
2343
- try {
2344
- const environment = await getEnvironmentByName2(environmentId);
2345
- return !!environment?.properties;
2346
- } catch {
2347
- return false;
2348
- }
2349
- }
2350
- // src/Verbs/ListCodeApps.ts
2351
- import { listAppsAsync } from "@microsoft/power-apps-actions";
2352
- /*!
2353
- * Copyright (C) Microsoft Corporation. All rights reserved.
2354
- */
2355
- async function getCodeAppsAsync(argumentProvider) {
2356
- argumentProvider.setDescription(HelpStrings.Verbs["List-codeapps"].Description);
2357
- argumentProvider.addExamples(HelpStrings.Verbs["List-codeapps"].Examples);
2358
- await argumentProvider.runVerb();
2359
- const codeApps = await listAppsAsync();
2360
- const filteredCodeApps = codeApps.filter((app) => app.appType === "CodeApp").map((app) => ({
2361
- appId: app.name,
2362
- name: app.properties.displayName
2363
- }));
2364
- if (argumentProvider.isJsonMode()) {
2365
- console.log(JSON.stringify(filteredCodeApps, null, 2));
2366
- return;
2367
- }
2368
- if (filteredCodeApps.length === 0) {
2369
- console.log("No code apps found.");
2370
- return;
2371
- }
2372
- console.log(`
2373
- Code Apps:`);
2374
- console.log("─".repeat(80));
2375
- console.log("App ID".padEnd(40) + "Display Name");
2376
- console.log("─".repeat(80));
2377
- filteredCodeApps.forEach((app) => {
2378
- const appId = app.appId.length > 38 ? app.appId.substring(0, 35) + "..." : app.appId;
2379
- const displayName = app.name || "<No Name>";
2380
- console.log(appId.padEnd(40) + displayName);
2381
- });
2382
- console.log("─".repeat(80));
2383
- console.log(`Total: ${filteredCodeApps.length} code app(s) found
2384
- `);
2385
- }
2386
- // src/Verbs/ListConnectionReferences.ts
2387
- import {
2388
- getPlayerServiceConfig as getPlayerServiceConfig3,
2389
- listConnectionReferences as listConnectionReferencesActions
2390
- } from "@microsoft/power-apps-actions";
2391
- init_CliUtils();
2392
- /*!
2393
- * Copyright (C) Microsoft Corporation. All rights reserved.
2394
- */
2395
- async function listConnectionReferences(argumentProvider) {
2396
- const settings = getSettings();
2397
- const { fileConfig } = settings;
2398
- createOptionSchema4(argumentProvider);
2399
- await argumentProvider.runVerb();
2400
- const cliFs = new CliFS({
2401
- cwd: process.cwd(),
2402
- allowCwdRead: true,
2403
- allowCwdWrite: true
2404
- });
2405
- const playerServiceConfig = getPlayerServiceConfig3();
2406
- const authenticationProvider = argumentProvider.getAuthenticationProvider();
2407
- const dsConfig = {
2408
- vfs: cliFs,
2409
- authProvider: authenticationProvider,
2410
- region: playerServiceConfig.region,
2411
- environmentName: playerServiceConfig.environmentName,
2412
- actionsParams: {
2413
- envUrl: await argumentProvider.getOption("orgUrl"),
2414
- solutionId: await argumentProvider.getOption("solutionId")
2415
- },
2416
- localFilePaths: {
2417
- powerConfigPath: fileConfig.powerConfigPath,
2418
- schemaPath: fileConfig.schemaPath,
2419
- codeGenPath: fileConfig.codeGenPath
2420
- },
2421
- logger: getCliLogger()
2422
- };
2423
- const connectionReferences = await listConnectionReferencesActions(dsConfig);
2424
- if (argumentProvider.isJsonMode()) {
2425
- console.log(JSON.stringify(connectionReferences, null, 2));
2426
- return;
2427
- }
2428
- if (connectionReferences.length === 0) {
2429
- console.log("No connection references found.");
2430
- return;
2431
- }
2432
- console.log(`
2433
- Connection References:`);
2434
- console.log("─".repeat(100));
2435
- connectionReferences.forEach((connectionRef) => {
2436
- console.log(`Display Name: ${connectionRef.msdyn_displayname}`);
2437
- console.log(`Logical Name: ${connectionRef.msdyn_name}`);
2438
- console.log(`Description: ${connectionRef.msdyn_description}`);
2439
- console.log("─".repeat(100));
2440
- });
2441
- console.log("─".repeat(100));
2442
- }
2443
- function createOptionSchema4(argumentProvider) {
2444
- argumentProvider.setDescription(HelpStrings.Verbs["List-connection-references"].Description);
2445
- argumentProvider.addExamples(HelpStrings.Verbs["List-connection-references"].Examples);
2446
- argumentProvider.addOptions([
2447
- createDefaultStringOption({
2448
- flags: {
2449
- key: SharedArguments.SolutionId.name,
2450
- alias: SharedArguments.SolutionId.alias
2451
- },
2452
- env: SharedArguments.SolutionId.envVar,
2453
- message: SharedArguments.SolutionId.promptMessage,
2454
- description: HelpStrings.Verbs["List-connection-references"].Options.SolutionId
2455
- }),
2456
- createDefaultStringOption({
2457
- flags: {
2458
- key: SharedArguments.OrgUrl.name,
2459
- alias: SharedArguments.OrgUrl.alias
2460
- },
2461
- env: SharedArguments.OrgUrl.envVar,
2462
- message: SharedArguments.OrgUrl.promptMessage,
2463
- description: HelpStrings.Verbs["List-connection-references"].Options.OrgUrl
2464
- })
2465
- ]);
2466
- }
2467
- // src/Verbs/ListDatasets.ts
2468
- import {
2469
- getPlayerServiceConfig as getPlayerServiceConfig4,
2470
- listDatasetsAsync as listDatasetsActionAsync
2471
- } from "@microsoft/power-apps-actions";
2472
- init_CliUtils();
2473
- /*!
2474
- * Copyright (C) Microsoft Corporation. All rights reserved.
2475
- */
2476
- async function listDatasetsAsync(argumentProvider) {
2477
- const settings = getSettings();
2478
- const { fileConfig } = settings;
2479
- createOptionSchema5(argumentProvider);
2480
- await argumentProvider.runVerb();
2481
- const cliFs = new CliFS({
2482
- cwd: process.cwd(),
2483
- allowCwdRead: true,
2484
- allowCwdWrite: true
2485
- });
2486
- const playerServiceConfig = getPlayerServiceConfig4();
2487
- const authenticationProvider = argumentProvider.getAuthenticationProvider();
2488
- const dsConfig = {
2489
- vfs: cliFs,
2490
- authProvider: authenticationProvider,
2491
- region: playerServiceConfig.region,
2492
- environmentName: playerServiceConfig.environmentName,
2493
- actionsParams: {
2494
- apiId: await argumentProvider.getOption("apiId"),
2495
- connectionId: await argumentProvider.getOption("connectionId")
2496
- },
2497
- localFilePaths: {
2498
- powerConfigPath: fileConfig.powerConfigPath,
2499
- schemaPath: fileConfig.schemaPath,
2500
- codeGenPath: fileConfig.codeGenPath
2501
- },
2502
- logger: getCliLogger()
2503
- };
2504
- const datasets = await listDatasetsActionAsync(dsConfig);
2505
- if (argumentProvider.isJsonMode()) {
2506
- console.log(JSON.stringify(datasets?.value ?? [], null, 2));
2507
- return;
2508
- }
2509
- console.log(`
2510
- ` + "=".repeat(80));
2511
- console.log(`Datasets for ${dsConfig.actionsParams.apiId}`);
2512
- console.log(`Connection: ${dsConfig.actionsParams.connectionId}`);
2513
- console.log("=".repeat(80));
2514
- console.log(`
2515
- ` + "Display Name".padEnd(40) + "Name");
2516
- console.log("-".repeat(80));
2517
- datasets.value.forEach((dataset) => {
2518
- const name = dataset.Name;
2519
- const displayName = (dataset.DisplayName || "<No Display Name>").substring(0, 38).padEnd(40);
2520
- console.log(displayName + name);
2521
- });
2522
- console.log("-".repeat(80));
2523
- }
2524
- function createOptionSchema5(argumentProvider) {
2525
- argumentProvider.setDescription(HelpStrings.Verbs["List-datasets"].Description);
2526
- argumentProvider.addExamples(HelpStrings.Verbs["List-datasets"].Examples);
2527
- argumentProvider.addOptions([
2528
- createDefaultStringOption({
2529
- flags: {
2530
- key: SharedArguments.ApiId.name,
2531
- alias: SharedArguments.ApiId.alias
2532
- },
2533
- env: SharedArguments.ApiId.envVar,
2534
- message: SharedArguments.ApiId.promptMessage,
2535
- description: HelpStrings.Verbs["List-datasets"].Options.ApiId
2536
- }),
2537
- createDefaultStringOption({
2538
- flags: {
2539
- key: SharedArguments.ConnectionId.name,
2540
- alias: SharedArguments.ConnectionId.alias
2541
- },
2542
- env: SharedArguments.ConnectionId.envVar,
2543
- message: SharedArguments.ConnectionId.promptMessage,
2544
- description: HelpStrings.Verbs["List-datasets"].Options.ConnectionId
2545
- })
2546
- ]);
2547
- }
2548
- // src/Verbs/ListEnvironmentVariables.ts
2549
- import {
2550
- getPlayerServiceConfig as getPlayerServiceConfig5,
2551
- listAllEnvironmentVariablesAsync as listAllEnvironmentVariablesActionAsync
2552
- } from "@microsoft/power-apps-actions";
2553
- init_CliUtils();
2554
- /*!
2555
- * Copyright (C) Microsoft Corporation. All rights reserved.
2556
- */
2557
- async function listAllEnvironmentVariablesAsync(argumentProvider) {
2558
- const settings = getSettings();
2559
- const { fileConfig } = settings;
2560
- createOptionSchema6(argumentProvider);
2561
- await argumentProvider.runVerb();
2562
- const cliFs = new CliFS({
2563
- cwd: process.cwd(),
2564
- allowCwdRead: true,
2565
- allowCwdWrite: true
2566
- });
2567
- const playerServiceConfig = getPlayerServiceConfig5();
2568
- const authenticationProvider = argumentProvider.getAuthenticationProvider();
2569
- const dsConfig = {
2570
- vfs: cliFs,
2571
- authProvider: authenticationProvider,
2572
- region: playerServiceConfig.region,
2573
- environmentName: playerServiceConfig.environmentName,
2574
- actionsParams: {
2575
- envUrl: await argumentProvider.getOption("orgUrl")
2576
- },
2577
- localFilePaths: {
2578
- powerConfigPath: fileConfig.powerConfigPath,
2579
- schemaPath: fileConfig.schemaPath,
2580
- codeGenPath: fileConfig.codeGenPath
2581
- },
2582
- logger: getCliLogger()
2583
- };
2584
- const environmentVariableDefinitions = await listAllEnvironmentVariablesActionAsync(dsConfig);
2585
- if (argumentProvider.isJsonMode()) {
2586
- console.log(JSON.stringify(environmentVariableDefinitions, null, 2));
2587
- return;
2588
- }
2589
- console.log(`
2590
- Environment Variables:`);
2591
- console.log("─".repeat(100));
2592
- environmentVariableDefinitions.forEach((envVar) => {
2593
- console.log(`Schema Name: ${envVar.schemaname}`);
2594
- console.log(`Display Name: ${envVar.displayname}`);
2595
- console.log(`Type: ${envVar.type}`);
2596
- console.log(`Value: ${envVar.environmentvariabledefinition_environmentvariablevalue[0]?.value ?? "<No Value>"}`);
2597
- console.log("─".repeat(100));
2598
- });
2599
- }
2600
- function createOptionSchema6(argumentProvider) {
2601
- argumentProvider.setDescription(HelpStrings.Verbs["List-environment-variables"].Description);
2602
- argumentProvider.addExamples(HelpStrings.Verbs["List-environment-variables"].Examples);
2603
- argumentProvider.addOptions([
2604
- createDefaultStringOption({
2605
- flags: {
2606
- key: SharedArguments.OrgUrl.name,
2607
- alias: SharedArguments.OrgUrl.alias
2608
- },
2609
- env: SharedArguments.OrgUrl.envVar,
2610
- message: SharedArguments.OrgUrl.promptMessage,
2611
- default: "",
2612
- description: HelpStrings.Verbs["List-environment-variables"].Options.OrgUrl
2613
- })
2614
- ]);
2615
- }
2616
- // src/Verbs/ListFlows.ts
2617
- import { getPlayerServiceConfig as getPlayerServiceConfig6 } from "@microsoft/power-apps-actions";
2618
- import { listFlowsAsync as listFlowsActionAsync } from "@microsoft/power-apps-actions";
2619
- init_CliUtils();
2620
- /*!
2621
- * Copyright (C) Microsoft Corporation. All rights reserved.
2622
- */
2623
- async function listFlowsAsync(argumentProvider) {
2624
- const settings = getSettings();
2625
- const { fileConfig } = settings;
2626
- createOptionSchema7(argumentProvider);
2627
- await argumentProvider.runVerb();
2628
- const cliFs = new CliFS({
2629
- cwd: process.cwd(),
2630
- allowCwdRead: true,
2631
- allowCwdWrite: true
2632
- });
2633
- const playerServiceConfig = getPlayerServiceConfig6();
2634
- const authenticationProvider = argumentProvider.getAuthenticationProvider();
2635
- const search = await argumentProvider.getOption(ListFlowsArguments.Search.name, true);
2636
- const context = {
2637
- vfs: cliFs,
2638
- authProvider: authenticationProvider,
2639
- region: playerServiceConfig.region,
2640
- environmentName: playerServiceConfig.environmentName,
2641
- actionsParams: {
2642
- search
2643
- },
2644
- localFilePaths: {
2645
- powerConfigPath: fileConfig.powerConfigPath,
2646
- schemaPath: fileConfig.schemaPath,
2647
- codeGenPath: fileConfig.codeGenPath
2648
- },
2649
- logger: getCliLogger()
2650
- };
2651
- const flows = await listFlowsActionAsync(context);
2652
- if (argumentProvider.isJsonMode()) {
2653
- console.log(JSON.stringify(flows, null, 2));
2654
- return;
2655
- }
2656
- console.log(`
2657
- ` + "=".repeat(100));
2658
- console.log("Cloud Flows");
2659
- console.log("=".repeat(100));
2660
- if (flows.length === 0) {
2661
- console.log(`
2662
- No flows found.`);
2663
- console.log("=".repeat(100));
2664
- return;
2665
- }
2666
- console.log(`
2667
- ` + "Name".padEnd(40) + "Status".padEnd(12) + "Modified On".padEnd(25) + "Flow ID");
2668
- console.log("-".repeat(100));
2669
- flows.forEach((flow) => {
2670
- const name = [...flow.name].slice(0, 38).join("").padEnd(40);
2671
- const status = (flow.statecode === 1 ? "Active" : "Inactive").padEnd(12);
2672
- const modifiedOn = new Date(flow.modifiedOn).toLocaleString().padEnd(25);
2673
- const flowId = flow.workflowId;
2674
- console.log(name + status + modifiedOn + flowId);
2675
- });
2676
- console.log("-".repeat(100));
2677
- console.log(`Total: ${flows.length} flow(s)`);
2678
- console.log("=".repeat(100));
2679
- }
2680
- function createOptionSchema7(argumentProvider) {
2681
- argumentProvider.setDescription(HelpStrings.Verbs["List-flows"].Description);
2682
- argumentProvider.addExamples(HelpStrings.Verbs["List-flows"].Examples);
2683
- argumentProvider.addOptions([
2684
- createDefaultStringOption({
2685
- flags: {
2686
- key: ListFlowsArguments.Search.name,
2687
- alias: ListFlowsArguments.Search.alias
2688
- },
2689
- env: ListFlowsArguments.Search.envVar,
2690
- message: ListFlowsArguments.Search.promptMessage,
2691
- description: HelpStrings.Verbs["List-flows"].Options.Search
2692
- })
2693
- ]);
2694
- }
2695
- // src/Verbs/ListSqlStoredProcedures.ts
2696
- import {
2697
- getPlayerServiceConfig as getPlayerServiceConfig7,
2698
- listSqlStoredProceduresAsync as listSqlStoredProceduresActionAsync
2699
- } from "@microsoft/power-apps-actions";
2700
- init_CliUtils();
2701
- /*!
2702
- * Copyright (C) Microsoft Corporation. All rights reserved.
2703
- */
2704
- async function listSqlStoredProceduresAsync(argumentProvider) {
2705
- const settings = getSettings();
2706
- const { fileConfig } = settings;
2707
- createOptionSchema8(argumentProvider);
2708
- await argumentProvider.runVerb();
2709
- const cliFs = new CliFS({
2710
- cwd: process.cwd(),
2711
- allowCwdRead: true,
2712
- allowCwdWrite: true
2713
- });
2714
- const playerServiceConfig = getPlayerServiceConfig7();
2715
- const authenticationProvider = argumentProvider.getAuthenticationProvider();
2716
- const dsConfig = {
2717
- vfs: cliFs,
2718
- authProvider: authenticationProvider,
2719
- region: playerServiceConfig.region,
2720
- environmentName: playerServiceConfig.environmentName,
2721
- actionsParams: {
2722
- connectionId: await argumentProvider.getOption("connectionId"),
2723
- dataset: await argumentProvider.getOption("dataset")
2724
- },
2725
- localFilePaths: {
2726
- powerConfigPath: fileConfig.powerConfigPath,
2727
- schemaPath: fileConfig.schemaPath,
2728
- codeGenPath: fileConfig.codeGenPath
2729
- },
2730
- logger: getCliLogger()
2731
- };
2732
- const storedProcedures = await listSqlStoredProceduresActionAsync(dsConfig);
2733
- if (argumentProvider.isJsonMode()) {
2734
- console.log(JSON.stringify(storedProcedures?.value ?? [], null, 2));
2735
- return;
2736
- }
2737
- if (!storedProcedures || !storedProcedures.value || storedProcedures.value.length === 0) {
2738
- console.log("No stored procedures found.");
2739
- return;
2740
- }
2741
- console.log(`
2742
- ` + "=".repeat(80));
2743
- console.log(`Stored Procedures for dataset: ${dsConfig.actionsParams.dataset}`);
2744
- console.log(`Connection: ${dsConfig.actionsParams.connectionId}`);
2745
- console.log("=".repeat(80));
2746
- console.log(`
2747
- ` + "Display Name".padEnd(40) + "Name");
2748
- console.log("-".repeat(80));
2749
- storedProcedures.value.forEach((sp) => {
2750
- const name = sp.Name;
2751
- const displayName = (sp.DisplayName || "<No Display Name>").substring(0, 38).padEnd(40);
2752
- console.log(displayName + name);
2753
- });
2754
- console.log("-".repeat(80));
2755
- console.log(`Total: ${storedProcedures.value.length} stored procedure(s) found
2756
- `);
2757
- }
2758
- function createOptionSchema8(argumentProvider) {
2759
- argumentProvider.setDescription(HelpStrings.Verbs["List-sqlStoredProcedures"].Description);
2760
- argumentProvider.addExamples(HelpStrings.Verbs["List-sqlStoredProcedures"].Examples);
2761
- argumentProvider.addOptions([
2762
- createDefaultStringOption({
2763
- flags: {
2764
- key: SharedArguments.ConnectionId.name,
2765
- alias: SharedArguments.ConnectionId.alias
2766
- },
2767
- env: SharedArguments.ConnectionId.envVar,
2768
- message: SharedArguments.ConnectionId.promptMessage,
2769
- description: HelpStrings.Verbs["List-sqlStoredProcedures"].Options.ConnectionId
2770
- }),
2771
- createDefaultStringOption({
2772
- flags: {
2773
- key: SharedArguments.Dataset.name,
2774
- alias: SharedArguments.Dataset.alias
2775
- },
2776
- env: SharedArguments.Dataset.envVar,
2777
- message: SharedArguments.Dataset.promptMessage,
2778
- description: HelpStrings.Verbs["List-sqlStoredProcedures"].Options.Dataset
2779
- })
2780
- ]);
2781
- }
2782
- // src/Verbs/ListTables.ts
2783
- import {
2784
- getPlayerServiceConfig as getPlayerServiceConfig8,
2785
- listTablesAsync as listTablesActionAsync
2786
- } from "@microsoft/power-apps-actions";
2787
- init_CliUtils();
2788
- /*!
2789
- * Copyright (C) Microsoft Corporation. All rights reserved.
2790
- */
2791
- async function listTablesAsync(argumentProvider) {
2792
- const settings = getSettings();
2793
- const { fileConfig } = settings;
2794
- createOptionSchema9(argumentProvider);
2795
- await argumentProvider.runVerb();
2796
- const cliFs = new CliFS({
2797
- cwd: process.cwd(),
2798
- allowCwdRead: true,
2799
- allowCwdWrite: true
2800
- });
2801
- const playerServiceConfig = getPlayerServiceConfig8();
2802
- const authenticationProvider = argumentProvider.getAuthenticationProvider();
2803
- const dsConfig = {
2804
- vfs: cliFs,
2805
- authProvider: authenticationProvider,
2806
- region: playerServiceConfig.region,
2807
- environmentName: playerServiceConfig.environmentName,
2808
- actionsParams: {
2809
- apiId: await argumentProvider.getOption("apiId"),
2810
- connectionId: await argumentProvider.getOption("connectionId"),
2811
- dataset: await argumentProvider.getOption("dataset")
2812
- },
2813
- localFilePaths: {
2814
- powerConfigPath: fileConfig.powerConfigPath,
2815
- schemaPath: fileConfig.schemaPath,
2816
- codeGenPath: fileConfig.codeGenPath
2817
- },
2818
- logger: getCliLogger()
2819
- };
2820
- const tables = await listTablesActionAsync(dsConfig);
2821
- if (argumentProvider.isJsonMode()) {
2822
- console.log(JSON.stringify(tables?.value ?? [], null, 2));
2823
- return;
2824
- }
2825
- if (!tables || !tables.value || tables.value.length === 0) {
2826
- console.log("No tables found.");
2827
- return;
2828
- }
2829
- console.log(`
2830
- ` + "=".repeat(80));
2831
- console.log(`Tables for dataset: ${dsConfig.actionsParams.dataset}`);
2832
- console.log(`Connector: ${dsConfig.actionsParams.apiId}`);
2833
- console.log(`Connection: ${dsConfig.actionsParams.connectionId}`);
2834
- console.log("=".repeat(80));
2835
- console.log(`
2836
- ` + "Display Name".padEnd(40) + "Name");
2837
- console.log("-".repeat(80));
2838
- tables.value.forEach((table) => {
2839
- const name = table.Name;
2840
- const displayName = (table.DisplayName || "<No Display Name>").substring(0, 38).padEnd(40);
2841
- console.log(displayName + name);
2842
- });
2843
- console.log("-".repeat(80));
2844
- console.log(`Total: ${tables.value.length} table(s) found
2845
- `);
2846
- }
2847
- function createOptionSchema9(argumentProvider) {
2848
- argumentProvider.setDescription(HelpStrings.Verbs["List-tables"].Description);
2849
- argumentProvider.addExamples(HelpStrings.Verbs["List-tables"].Examples);
2850
- argumentProvider.addOptions([
2851
- createDefaultStringOption({
2852
- flags: {
2853
- key: SharedArguments.ApiId.name,
2854
- alias: SharedArguments.ApiId.alias
2855
- },
2856
- env: SharedArguments.ApiId.envVar,
2857
- message: SharedArguments.ApiId.promptMessage,
2858
- description: HelpStrings.Verbs["List-tables"].Options.ApiId
2859
- }),
2860
- createDefaultStringOption({
2861
- flags: {
2862
- key: SharedArguments.ConnectionId.name,
2863
- alias: SharedArguments.ConnectionId.alias
2864
- },
2865
- env: SharedArguments.ConnectionId.envVar,
2866
- message: SharedArguments.ConnectionId.promptMessage,
2867
- description: HelpStrings.Verbs["List-tables"].Options.ConnectionId
2868
- }),
2869
- createDefaultStringOption({
2870
- flags: {
2871
- key: SharedArguments.Dataset.name,
2872
- alias: SharedArguments.Dataset.alias
2873
- },
2874
- env: SharedArguments.Dataset.envVar,
2875
- message: SharedArguments.Dataset.promptMessage,
2876
- description: HelpStrings.Verbs["List-tables"].Options.Dataset
2877
- })
2878
- ]);
2879
- }
2880
- // src/Verbs/Logout.ts
2881
- init_Constants();
2882
- import * as fs3 from "fs";
2883
- /*!
2884
- * Copyright (C) Microsoft Corporation. All rights reserved.
2885
- */
2886
- async function logoutAsync(argumentProvider) {
2887
- argumentProvider.setDescription(HelpStrings.Verbs.Logout.Description);
2888
- argumentProvider.addExamples(HelpStrings.Verbs.Logout.Examples);
2889
- await argumentProvider.runVerb();
2890
- const cacheDir = AUTH_CACHE_DIRECTORY;
2891
- try {
2892
- if (fs3.existsSync(cacheDir)) {
2893
- fs3.rmSync(cacheDir, { recursive: true, force: true });
2894
- console.log("Successfully logged out. Cached credentials have been cleared.");
2895
- console.log("On next command, you will be prompted to sign in via the browser. If your browser has a single account session, it will be used automatically.");
2896
- } else {
2897
- console.log("No user found.");
2898
- }
2899
- } catch (error2) {
2900
- console.error("Failed to log out the user:", error2);
2901
- throw error2;
2902
- }
2903
- }
2904
- // src/Verbs/Push.ts
2905
- import { pushApp } from "@microsoft/power-apps-actions";
2906
- import {
2907
- DataverseSystemDataService,
2908
- getEnvironmentByName as getEnvironmentByName3,
2909
- getPlayerServiceConfig as getPlayerServiceConfig9
2910
- } from "@microsoft/power-apps-actions";
2911
- init_CliUtils();
2912
- /*!
2913
- * Copyright (C) Microsoft Corporation. All rights reserved.
2914
- */
2915
- async function pushAsync(argumentProvider) {
2916
- const settings = getSettings();
2917
- const { appConfig, fileConfig, cliFs } = settings;
2918
- argumentProvider.setDescription(HelpStrings.Verbs.Push.Description);
2919
- argumentProvider.addExamples(HelpStrings.Verbs.Push.Examples);
2920
- createOptionSchema10(argumentProvider, appConfig?.environmentId, appConfig?.appId);
2921
- await argumentProvider.runVerb();
2922
- if (!appConfig) {
2923
- throw new Error("power.config.json is required to push an app");
2924
- }
2925
- if (!appConfig.environmentId) {
2926
- throw new Error("Environment ID is required in power.config.json to push an app");
2927
- }
2928
- if (!appConfig.region) {
2929
- appConfig.region = "prod";
2930
- }
2931
- const authenticationProvider = argumentProvider.getAuthenticationProvider();
2932
- const pushConfig = {
2933
- vfs: cliFs,
2934
- actionsParams: {
2935
- solutionId: await argumentProvider.getOption("solutionId", true),
2936
- appName: appConfig.appId
2937
- },
2938
- environmentName: appConfig.environmentId,
2939
- region: appConfig.region || "prod",
2940
- authProvider: authenticationProvider,
2941
- localFilePaths: fileConfig,
2942
- logger: getCliLogger(),
2943
- httpClient: getPlayerServiceConfig9().httpClient
2944
- };
2945
- const app = await pushApp(pushConfig);
2946
- console.log(`App pushed successfully. You can play your app at ${app.properties.appPlayUri}`);
2947
- console.log("Hint: Run 'npx power-apps run' to test locally.");
2948
- }
2949
- function createOptionSchema10(argumentProvider, environmentId, appId) {
2950
- argumentProvider.addOption({
2951
- flags: {
2952
- key: SharedArguments.SolutionId.name,
2953
- alias: SharedArguments.SolutionId.alias
2954
- },
2955
- env: SharedArguments.SolutionId.envVar,
2956
- description: HelpStrings.Verbs.Push.Options.SolutionName,
2957
- optionalInNonInteractive: true,
2958
- customPrompt: async () => {
2959
- if (!environmentId) {
2960
- throw new Error("Environment ID is required");
2961
- }
2962
- if (!appId) {
2963
- const useSpecificSolution = await promptConfirm({
2964
- message: "Would you like to specify a solution to push the app into?"
2965
- });
2966
- if (!useSpecificSolution) {
2967
- const environmentDetails = await getEnvironmentByName3(environmentId);
2968
- const dvService = new DataverseSystemDataService(getPlayerServiceConfig9().httpClient);
2969
- const orgUrl = environmentDetails.properties.linkedEnvironmentMetadata?.instanceUrl;
2970
- if (!orgUrl) {
2971
- throw new Error("Organization URL is not available for the specified environment.");
2972
- }
2973
- const preferredSolutionId = await dvService.getPreferredSolution(orgUrl);
2974
- if (!preferredSolutionId) {
2975
- console.log("No preferred solution found. App will not be put in a solution. We recommended setting a preferred solution for your environment in the future.");
2976
- return "";
2977
- }
2978
- return preferredSolutionId;
2979
- } else {
2980
- const solutionName = await promptText({
2981
- message: "Please enter the solution name or ID:"
2982
- });
2983
- if (!solutionName) {
2984
- return "";
2985
- }
2986
- if (isGuid(solutionName)) {
2987
- return solutionName;
2988
- }
2989
- const environmentDetails = await getEnvironmentByName3(environmentId);
2990
- const dvService = new DataverseSystemDataService(getPlayerServiceConfig9().httpClient);
2991
- const orgUrl = environmentDetails.properties.linkedEnvironmentMetadata?.instanceUrl;
2992
- if (!orgUrl) {
2993
- throw new Error("Organization URL is not available for the specified environment.");
2994
- }
2995
- const solutions = await dvService.getSolutions(orgUrl);
2996
- const solutionId = solutions.find((solution) => solution.friendlyname.toLowerCase() === solutionName.toLowerCase() || solution.uniquename.toLowerCase() === solutionName.toLowerCase())?.solutionid;
2997
- if (!solutionId) {
2998
- throw new Error(`Solution with name '${solutionName}' not found.`);
2999
- }
3000
- return solutionId;
3001
- }
3002
- }
3003
- return "";
3004
- }
3005
- });
3006
- }
3007
- // src/Verbs/Run.ts
3008
- import * as fs4 from "fs";
3009
- import * as http from "http";
3010
- init_CliUtils();
3011
- /*!
3012
- * Copyright (C) Microsoft Corporation. All rights reserved.
3013
- */
3014
- async function runAsync(argumentProvider) {
3015
- const settings = getSettings();
3016
- const { appConfig, fileConfig } = settings;
3017
- createOptionSchema11(argumentProvider, appConfig?.localAppUrl);
3018
- await argumentProvider.runVerb();
3019
- if (!appConfig) {
3020
- throw new Error("power.config.json is required to run an app");
3021
- }
3022
- if (!appConfig.environmentId) {
3023
- throw new Error("Environment ID is required in power.config.json to run an app");
3024
- }
3025
- if (!appConfig.region) {
3026
- appConfig.region = "prod";
3027
- }
3028
- const powerConfigPath = fileConfig.powerConfigPath;
3029
- const port = await argumentProvider.getOption("port");
3030
- const appUrl = await argumentProvider.getOption("localAppUrl");
3031
- await startLocalServer(powerConfigPath, parseInt(port, 10), appConfig, appUrl);
3032
- }
3033
- async function startLocalServer(powerConfigPath, port, appConfig, localAppUrl) {
3034
- return new Promise((resolve, reject) => {
3035
- const server = http.createServer((req, res) => {
3036
- res.setHeader("Access-Control-Allow-Origin", "*");
3037
- res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
3038
- res.setHeader("Access-Control-Allow-Headers", "*");
3039
- if (req.method === "OPTIONS") {
3040
- res.writeHead(200);
3041
- res.end();
3042
- return;
3043
- }
3044
- try {
3045
- if (!fs4.existsSync(powerConfigPath)) {
3046
- res.writeHead(404, { "Content-Type": "application/json" });
3047
- res.end(JSON.stringify({ error: "power.config.json not found" }));
3048
- return;
3049
- }
3050
- const fileContent = fs4.readFileSync(powerConfigPath, "utf8");
3051
- res.writeHead(200, { "Content-Type": "application/json" });
3052
- res.end(fileContent);
3053
- } catch (error2) {
3054
- console.error("Error serving power.config.json:", error2);
3055
- res.writeHead(500, { "Content-Type": "application/json" });
3056
- res.end(JSON.stringify({ error: "Internal server error" }));
3057
- }
3058
- });
3059
- server.listen(port, "localhost", async () => {
3060
- console.log(`Your power.config.json to setup connections is available at http://localhost:${port}`);
3061
- console.log(`
3062
- You can play your app locally at ${createPlayUrl(appConfig.region, appConfig.environmentId, "local", localAppUrl, `http://localhost:${port}`)}`);
3063
- await checkLocalAppUrl(localAppUrl);
3064
- });
3065
- server.on("error", (error2) => {
3066
- console.error("Server error:", error2);
3067
- reject(error2);
3068
- });
3069
- process.on("SIGINT", () => {
3070
- console.log(`
3071
- Shutting down server...`);
3072
- server.close(() => {
3073
- console.log("Server stopped");
3074
- process.exit(0);
3075
- });
3076
- });
3077
- });
3078
- }
3079
- function createOptionSchema11(argumentProvider, localAppUrl) {
3080
- argumentProvider.setDescription(HelpStrings.Verbs.Run.Description);
3081
- argumentProvider.addExamples(HelpStrings.Verbs.Run.Examples);
3082
- argumentProvider.addOptions([
3083
- {
3084
- flags: {
3085
- key: RunArguments.Port.name,
3086
- alias: RunArguments.Port.alias
3087
- },
3088
- env: RunArguments.Port.envVar,
3089
- default: RunArguments.Port.initialValue,
3090
- description: HelpStrings.Verbs.Run.Options.Port
3091
- },
3092
- {
3093
- flags: {
3094
- key: RunArguments.LocalAppUrl.name,
3095
- alias: RunArguments.LocalAppUrl.alias
3096
- },
3097
- env: RunArguments.LocalAppUrl.envVar,
3098
- default: localAppUrl || RunArguments.LocalAppUrl.initialValue,
3099
- description: HelpStrings.Verbs.Run.Options.LocalAppUrl
3100
- }
3101
- ]);
3102
- }
3103
- async function checkLocalAppUrl(localAppUrl) {
3104
- try {
3105
- const controller = new AbortController;
3106
- const timeoutId = setTimeout(() => controller.abort(), 5000);
3107
- const response = await fetch(localAppUrl, {
3108
- method: "HEAD",
3109
- signal: controller.signal
3110
- });
3111
- clearTimeout(timeoutId);
3112
- if (response.ok || response.status < 500) {
3113
- return;
3114
- } else {
3115
- console.warn(`
3116
- Warning: Your local app running at ${localAppUrl} returned status ${response.status}, which is unexpected. Check your app code for exceptions.`);
3117
- }
3118
- } catch (error2) {
3119
- console.warn(`
3120
- Warning: Your local app is NOT currently running at ${localAppUrl}`);
3121
- }
3122
- }
3123
-
3124
- // src/Verbs/index.ts
3125
- /*!
3126
- * Copyright (C) Microsoft Corporation. All rights reserved.
3127
- */
3128
-
3129
- // src/Verbs/TelemetrySettings.ts
3130
- init_Constants();
3131
- import * as fs5 from "fs";
3132
- import * as path4 from "path";
3133
- /*!
3134
- * Copyright (C) Microsoft Corporation. All rights reserved.
3135
- */
3136
- async function modifyTelemetrySettings(argumentProvider) {
3137
- createOptionSchema12(argumentProvider);
3138
- await argumentProvider.runVerb();
3139
- const enableTelemetry = await argumentProvider.getOption("enable", true);
3140
- const disableTelemetry = await argumentProvider.getOption("disable", true);
3141
- const showSettings = await argumentProvider.getOption("showSettings", true);
3142
- const consoleOnly = await argumentProvider.getOption("consoleOnly", true);
3143
- const outputToConsole = await argumentProvider.getOption("outputToConsole", true);
3144
- const jsonMode = argumentProvider.isJsonMode();
3145
- if (enableTelemetry === undefined && disableTelemetry === undefined && consoleOnly === undefined && outputToConsole === undefined && showSettings === undefined) {
3146
- displayUserTelemetrySettings(jsonMode);
3147
- return;
3148
- }
3149
- if (enableTelemetry && disableTelemetry) {
3150
- throw new Error("Cannot enable and disable telemetry at the same time.");
3151
- }
3152
- if (showSettings) {
3153
- displayUserTelemetrySettings(jsonMode);
3154
- } else {
3155
- const telemetryEnabled = enableTelemetry ? true : disableTelemetry ? false : undefined;
3156
- updateUserTelemetrySettings(telemetryEnabled, consoleOnly, outputToConsole);
3157
- }
3158
- }
3159
- function createOptionSchema12(argumentProvider) {
3160
- argumentProvider.setDescription(HelpStrings.Verbs.Telemetry.Description);
3161
- argumentProvider.addExamples(HelpStrings.Verbs.Telemetry.Examples);
3162
- argumentProvider.addSwitches([
3163
- {
3164
- flags: {
3165
- key: "enable",
3166
- alias: "te"
3167
- },
3168
- env: "POWERAPPS_CLI_ENABLE_TELEMETRY",
3169
- description: HelpStrings.Verbs.Telemetry.Options.Enable
3170
- },
3171
- {
3172
- flags: {
3173
- key: "disable",
3174
- alias: "td"
3175
- },
3176
- env: "POWERAPPS_CLI_DISABLE_TELEMETRY",
3177
- description: HelpStrings.Verbs.Telemetry.Options.Disable
3178
- },
3179
- {
3180
- flags: {
3181
- key: "show-settings",
3182
- alias: "ts"
3183
- },
3184
- env: "POWERAPPS_CLI_SHOW_SETTINGS",
3185
- description: HelpStrings.Verbs.Telemetry.Options.ShowSettings
3186
- }
3187
- ]);
3188
- argumentProvider.addOptions([
3189
- {
3190
- flags: {
3191
- key: "console-only",
3192
- alias: "tc"
3193
- },
3194
- env: "POWERAPPS_CLI_CONSOLE_ONLY",
3195
- description: HelpStrings.Verbs.Telemetry.Options.ConsoleOnly
3196
- },
3197
- {
3198
- flags: {
3199
- key: "output-to-console",
3200
- alias: "to"
3201
- },
3202
- env: "POWERAPPS_CLI_OUTPUT_TO_CONSOLE",
3203
- description: HelpStrings.Verbs.Telemetry.Options.OutputToConsole
3204
- }
3205
- ]);
3206
- }
3207
- function displayUserTelemetrySettings(jsonMode) {
3208
- try {
3209
- const userSettingsPath = path4.join(CLI_CONFIG_DIRECTORY, USER_SETTINGS_FILE);
3210
- if (fs5.existsSync(userSettingsPath)) {
3211
- const fileContent = fs5.readFileSync(userSettingsPath, "utf-8");
3212
- const existingSettings = JSON.parse(fileContent);
3213
- if (jsonMode) {
3214
- console.log(JSON.stringify(existingSettings, null, 2));
3215
- return;
3216
- }
3217
- console.log("Current Telemetry Settings:");
3218
- console.log(` Enabled: ${existingSettings.enabled}`);
3219
- console.log(` Console Only: ${existingSettings.consoleOnly}`);
3220
- console.log(` Output To Console: ${existingSettings.outputToConsole}`);
3221
- } else {
3222
- if (jsonMode) {
3223
- console.log(JSON.stringify(null));
3224
- return;
3225
- }
3226
- console.log("No telemetry settings found. Using default settings.");
3227
- }
3228
- } catch (error2) {
3229
- console.error(`Failed to display telemetry settings: ${error2.message}`);
3230
- }
3231
- }
3232
- function updateUserTelemetrySettings(telemetryEnabled, consoleOnly, outputToConsole) {
3233
- try {
3234
- if (fs5.existsSync(CLI_CONFIG_DIRECTORY) === false) {
3235
- fs5.mkdirSync(CLI_CONFIG_DIRECTORY, { recursive: true });
3236
- }
3237
- const userSettingsPath = path4.join(CLI_CONFIG_DIRECTORY, USER_SETTINGS_FILE);
3238
- let userSettings;
3239
- if (fs5.existsSync(userSettingsPath)) {
3240
- const fileContent = fs5.readFileSync(userSettingsPath, "utf-8");
3241
- const existingSettings = JSON.parse(fileContent);
3242
- userSettings = {
3243
- enabled: telemetryEnabled ?? existingSettings.enabled,
3244
- consoleOnly: consoleOnly !== undefined ? consoleOnly === "true" : existingSettings.consoleOnly,
3245
- outputToConsole: outputToConsole !== undefined ? outputToConsole === "true" : existingSettings.outputToConsole
3246
- };
3247
- } else {
3248
- userSettings = {
3249
- enabled: telemetryEnabled ?? true,
3250
- consoleOnly: consoleOnly !== undefined ? consoleOnly === "true" : false,
3251
- outputToConsole: outputToConsole !== undefined ? outputToConsole === "true" : false
3252
- };
3253
- }
3254
- fs5.writeFileSync(userSettingsPath, JSON.stringify(userSettings, null, 2), "utf-8");
3255
- } catch (error2) {
3256
- throw new Error(`Failed to update telemetry settings: ${error2.message}`);
3257
- }
3258
- }
3259
-
3260
- // src/Cli.ts
3261
- /*!
3262
- * Copyright (C) Microsoft Corporation. All rights reserved.
3263
- */
3264
- var logger;
3265
- var exitCode = 0;
3266
- async function boot() {
3267
- try {
3268
- if (process.argv.includes("--no-color")) {
3269
- process.env.NO_COLOR = "1";
3270
- }
3271
- const isPacCli = process.env.IS_PAC_CLI === "true";
3272
- const isTestRun = process.env.CI === "true";
3273
- const hasNonInteractiveFlag = process.argv.includes("--non-interactive");
3274
- const source = isPacCli ? "pac-cli" : "standalone";
3275
- const interactive = !isPacCli && !isTestRun && !hasNonInteractiveFlag && process.stdin.isTTY === true;
3276
- const cliSettings = await initializeCliSettings({ source, interactive });
3277
- let authenticationProvider;
3278
- if (isPacCli) {
3279
- authenticationProvider = new PacCliAuthenticationProvider;
3280
- } else if (isTestRun) {
3281
- const { ServicePrincipalAuthenticationProvider: ServicePrincipalAuthenticationProvider2 } = await Promise.resolve().then(() => (init_ServicePrincipalAuthenticationProvider(), exports_ServicePrincipalAuthenticationProvider));
3282
- authenticationProvider = new ServicePrincipalAuthenticationProvider2;
3283
- } else {
3284
- const { NodeMsalAuthenticationProvider: NodeMsalAuthenticationProvider2 } = await Promise.resolve().then(() => (init_NodeMsalAuthenticationProvider(), exports_NodeMsalAuthenticationProvider));
3285
- authenticationProvider = new NodeMsalAuthenticationProvider2;
3286
- }
3287
- const httpClient = new CliHttpClient(authenticationProvider);
3288
- logger = await CliLogger.create(cliSettings, httpClient);
3289
- setCliLogger(logger);
3290
- const argumentProvider = new ArgumentProvider(httpClient, logger, authenticationProvider);
3291
- argumentProvider.handleGlobalHelpOrFlagsAndExit();
3292
- const verb = argumentProvider.getVerb();
3293
- await executeVerb({ verb, argumentProvider });
3294
- } catch (err) {
3295
- const message = err instanceof Error ? err.message : String(err);
3296
- console.error(message);
3297
- exitCode = err instanceof CliError ? err.exitCode : 1;
3298
- } finally {
3299
- if (logger) {
3300
- await logger.flush();
3301
- }
3302
- process.exit(exitCode);
3303
- }
3304
- }
3305
- async function executeVerb(config) {
3306
- const { verb, argumentProvider } = config;
3307
- switch (verb) {
3308
- case "init":
3309
- await initAsync(argumentProvider);
3310
- break;
3311
- case "list-codeapps":
3312
- await getCodeAppsAsync(argumentProvider);
3313
- break;
3314
- case "add-data-source":
3315
- await addDataSourceAsync(argumentProvider);
3316
- break;
3317
- case "list-datasets":
3318
- await listDatasetsAsync(argumentProvider);
3319
- break;
3320
- case "list-tables":
3321
- await listTablesAsync(argumentProvider);
3322
- break;
3323
- case "list-sqlStoredProcedures":
3324
- await listSqlStoredProceduresAsync(argumentProvider);
3325
- break;
3326
- case "delete-data-source":
3327
- await deleteDataSourceAsync(argumentProvider);
3328
- break;
3329
- case "logout":
3330
- await logoutAsync(argumentProvider);
3331
- break;
3332
- case "list-environment-variables":
3333
- await listAllEnvironmentVariablesAsync(argumentProvider);
3334
- break;
3335
- case "list-connection-references":
3336
- await listConnectionReferences(argumentProvider);
3337
- break;
3338
- case "list-flows":
3339
- await listFlowsAsync(argumentProvider);
3340
- break;
3341
- case "push":
3342
- await pushAsync(argumentProvider);
3343
- break;
3344
- case "run":
3345
- await runAsync(argumentProvider);
3346
- break;
3347
- case "telemetry":
3348
- await modifyTelemetrySettings(argumentProvider);
3349
- break;
3350
- default:
3351
- unsupportedVerb(verb);
3352
- }
3353
- }
3354
- function unsupportedVerb(verb) {
3355
- throw new Error(`The verb "${verb}" is not supported.`);
3356
- }
3357
-
3358
- // src/Bin.ts
3359
2
  /*!
3360
3
  * Copyright (C) Microsoft Corporation. All rights reserved.
3361
4
  */
5
+ import { boot } from './Cli.js';
3362
6
  boot();
7
+ //# sourceMappingURL=Bin.js.map