@microsoft/power-apps-native-host 0.2.22

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 (104) hide show
  1. package/LICENSE +112 -0
  2. package/README.md +59 -0
  3. package/app.plugin.js +4 -0
  4. package/lib/NOTICE.txt +1659 -0
  5. package/lib/commonjs/ErrorBoundary.js +128 -0
  6. package/lib/commonjs/auth/AuthContext.js +281 -0
  7. package/lib/commonjs/bridge/NativePowerAppsBridge.js +279 -0
  8. package/lib/commonjs/bridge/setupNativeHost.js +65 -0
  9. package/lib/commonjs/connections/ConnectionSetupScreen.js +531 -0
  10. package/lib/commonjs/connections/disambiguate.js +88 -0
  11. package/lib/commonjs/connections/types.js +58 -0
  12. package/lib/commonjs/connections/useConnectionSetup.js +236 -0
  13. package/lib/commonjs/controls/FilePicker.js +183 -0
  14. package/lib/commonjs/controls/ImagePicker.js +236 -0
  15. package/lib/commonjs/index.js +246 -0
  16. package/lib/commonjs/logger.js +27 -0
  17. package/lib/commonjs/package.json +1 -0
  18. package/lib/commonjs/platform/PowerPlatformConnectionApi.js +606 -0
  19. package/lib/commonjs/platform/PowerPlatformEnvironmentApi.js +194 -0
  20. package/lib/commonjs/platform/resolveConnections.js +264 -0
  21. package/lib/commonjs/platform/useConnectionRefs.js +270 -0
  22. package/lib/commonjs/provider/PowerAppsHostProvider.js +336 -0
  23. package/lib/commonjs/provider/PowerAppsProvider.js +351 -0
  24. package/lib/commonjs/telemetry/index.js +70 -0
  25. package/lib/commonjs/theme/ThemeProvider.js +80 -0
  26. package/lib/commonjs/theme/tokens.js +50 -0
  27. package/lib/commonjs/utils/dataverseUtils.js +98 -0
  28. package/lib/commonjs/utils/isDevPlayer.js +27 -0
  29. package/lib/module/ErrorBoundary.js +122 -0
  30. package/lib/module/auth/AuthContext.js +276 -0
  31. package/lib/module/bridge/NativePowerAppsBridge.js +273 -0
  32. package/lib/module/bridge/setupNativeHost.js +62 -0
  33. package/lib/module/connections/ConnectionSetupScreen.js +526 -0
  34. package/lib/module/connections/disambiguate.js +83 -0
  35. package/lib/module/connections/types.js +60 -0
  36. package/lib/module/connections/useConnectionSetup.js +233 -0
  37. package/lib/module/controls/FilePicker.js +178 -0
  38. package/lib/module/controls/ImagePicker.js +231 -0
  39. package/lib/module/index.js +41 -0
  40. package/lib/module/logger.js +22 -0
  41. package/lib/module/package.json +1 -0
  42. package/lib/module/platform/PowerPlatformConnectionApi.js +595 -0
  43. package/lib/module/platform/PowerPlatformEnvironmentApi.js +186 -0
  44. package/lib/module/platform/resolveConnections.js +259 -0
  45. package/lib/module/platform/useConnectionRefs.js +267 -0
  46. package/lib/module/provider/PowerAppsHostProvider.js +332 -0
  47. package/lib/module/provider/PowerAppsProvider.js +345 -0
  48. package/lib/module/telemetry/index.js +55 -0
  49. package/lib/module/theme/ThemeProvider.js +63 -0
  50. package/lib/module/theme/tokens.js +46 -0
  51. package/lib/module/utils/dataverseUtils.js +90 -0
  52. package/lib/module/utils/isDevPlayer.js +23 -0
  53. package/lib/typescript/commonjs/ErrorBoundary.d.ts +30 -0
  54. package/lib/typescript/commonjs/auth/AuthContext.d.ts +57 -0
  55. package/lib/typescript/commonjs/bridge/NativePowerAppsBridge.d.ts +112 -0
  56. package/lib/typescript/commonjs/bridge/setupNativeHost.d.ts +39 -0
  57. package/lib/typescript/commonjs/connections/ConnectionSetupScreen.d.ts +107 -0
  58. package/lib/typescript/commonjs/connections/disambiguate.d.ts +43 -0
  59. package/lib/typescript/commonjs/connections/types.d.ts +91 -0
  60. package/lib/typescript/commonjs/connections/useConnectionSetup.d.ts +96 -0
  61. package/lib/typescript/commonjs/controls/FilePicker.d.ts +65 -0
  62. package/lib/typescript/commonjs/controls/ImagePicker.d.ts +76 -0
  63. package/lib/typescript/commonjs/index.d.ts +42 -0
  64. package/lib/typescript/commonjs/logger.d.ts +11 -0
  65. package/lib/typescript/commonjs/package.json +1 -0
  66. package/lib/typescript/commonjs/platform/PowerPlatformConnectionApi.d.ts +205 -0
  67. package/lib/typescript/commonjs/platform/PowerPlatformEnvironmentApi.d.ts +108 -0
  68. package/lib/typescript/commonjs/platform/resolveConnections.d.ts +86 -0
  69. package/lib/typescript/commonjs/platform/useConnectionRefs.d.ts +126 -0
  70. package/lib/typescript/commonjs/provider/PowerAppsHostProvider.d.ts +123 -0
  71. package/lib/typescript/commonjs/provider/PowerAppsProvider.d.ts +148 -0
  72. package/lib/typescript/commonjs/telemetry/index.d.ts +48 -0
  73. package/lib/typescript/commonjs/theme/ThemeProvider.d.ts +30 -0
  74. package/lib/typescript/commonjs/theme/tokens.d.ts +27 -0
  75. package/lib/typescript/commonjs/utils/dataverseUtils.d.ts +39 -0
  76. package/lib/typescript/commonjs/utils/isDevPlayer.d.ts +19 -0
  77. package/lib/typescript/module/ErrorBoundary.d.ts +30 -0
  78. package/lib/typescript/module/auth/AuthContext.d.ts +57 -0
  79. package/lib/typescript/module/bridge/NativePowerAppsBridge.d.ts +112 -0
  80. package/lib/typescript/module/bridge/setupNativeHost.d.ts +39 -0
  81. package/lib/typescript/module/connections/ConnectionSetupScreen.d.ts +107 -0
  82. package/lib/typescript/module/connections/disambiguate.d.ts +43 -0
  83. package/lib/typescript/module/connections/types.d.ts +91 -0
  84. package/lib/typescript/module/connections/useConnectionSetup.d.ts +96 -0
  85. package/lib/typescript/module/controls/FilePicker.d.ts +65 -0
  86. package/lib/typescript/module/controls/ImagePicker.d.ts +76 -0
  87. package/lib/typescript/module/index.d.ts +42 -0
  88. package/lib/typescript/module/logger.d.ts +11 -0
  89. package/lib/typescript/module/package.json +1 -0
  90. package/lib/typescript/module/platform/PowerPlatformConnectionApi.d.ts +205 -0
  91. package/lib/typescript/module/platform/PowerPlatformEnvironmentApi.d.ts +108 -0
  92. package/lib/typescript/module/platform/resolveConnections.d.ts +86 -0
  93. package/lib/typescript/module/platform/useConnectionRefs.d.ts +126 -0
  94. package/lib/typescript/module/provider/PowerAppsHostProvider.d.ts +123 -0
  95. package/lib/typescript/module/provider/PowerAppsProvider.d.ts +148 -0
  96. package/lib/typescript/module/telemetry/index.d.ts +48 -0
  97. package/lib/typescript/module/theme/ThemeProvider.d.ts +30 -0
  98. package/lib/typescript/module/theme/tokens.d.ts +27 -0
  99. package/lib/typescript/module/utils/dataverseUtils.d.ts +39 -0
  100. package/lib/typescript/module/utils/isDevPlayer.d.ts +19 -0
  101. package/package.json +119 -0
  102. package/scripts/build-ios-base.js +96 -0
  103. package/scripts/bundle.js +95 -0
  104. package/scripts/generate-connector-schemas.js +75 -0
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.POWER_PLATFORM_API_SCOPE = void 0;
7
+ exports.buildCdsDataSources = buildCdsDataSources;
8
+ exports.buildEnvironmentEndpoint = buildEnvironmentEndpoint;
9
+ exports.fetchInstanceUrl = fetchInstanceUrl;
10
+ exports.powerPlatformScope = powerPlatformScope;
11
+ var _index = require("../telemetry/index.js");
12
+ /*!
13
+ * power-apps-native-host — PowerPlatformEnvironmentApi
14
+ *
15
+ * Mirrors the Host SDK's DefaultAppMetadataProvider.fetchAppMetadataFromPowerConfig
16
+ * pattern: resolves the Power Platform environment-scoped API endpoint from the
17
+ * environment GUID and region, then fetches linkedEnvironmentMetadata to obtain
18
+ * the Dataverse instanceUrl.
19
+ *
20
+ * Reference (Host SDK):
21
+ * packages/power-apps-host/src/providers/defaults/DefaultAppMetadataProvider.ts
22
+ * packages/power-apps-common/src/services/PowerPlatformApiDiscovery.ts
23
+ */
24
+
25
+ // ---------------------------------------------------------------------------
26
+ // Region → API hostname suffix
27
+ // Mirrors PowerPlatformApiDiscovery.getHostNameSuffix / getHexApiSuffixLength
28
+ // ---------------------------------------------------------------------------
29
+
30
+ const HOST_NAME_SUFFIX = {
31
+ local: 'api.powerplatform.localhost',
32
+ dev: 'api.dev.powerplatform.com',
33
+ test: 'api.test.powerplatform.com',
34
+ preprod: 'api.preprod.powerplatform.com',
35
+ preview: 'api.powerplatform.com',
36
+ // preview ring → prod endpoints
37
+ firstrelease: 'api.powerplatform.com',
38
+ prod: 'api.powerplatform.com',
39
+ gccmoderate: 'api.gov.powerplatform.microsoft.us',
40
+ gov: 'api.gov.powerplatform.microsoft.us',
41
+ gcchigh: 'api.high.powerplatform.microsoft.us',
42
+ high: 'api.high.powerplatform.microsoft.us',
43
+ dod: 'api.appsplatform.us',
44
+ mooncake: 'api.powerplatform.partner.microsoftonline.cn',
45
+ ex: 'api.powerplatform.eaglex.ic.gov',
46
+ rx: 'api.powerplatform.microsoft.scloud'
47
+ };
48
+
49
+ /** prod / firstrelease / preview use a 2-char hex suffix; all others use 1. */
50
+ function hexSuffixLength(region) {
51
+ return region === 'prod' || region === 'firstrelease' || region === 'preview' ? 2 : 1;
52
+ }
53
+
54
+ /**
55
+ * Build the Power Platform environment-scoped API base URL.
56
+ *
57
+ * Algorithm (mirrors PowerPlatformApiDiscovery.generateDomain):
58
+ * 1. Strip dashes from the environment GUID to get a hex string.
59
+ * 2. Split into prefix (all but last N chars) and suffix (last N chars),
60
+ * where N = 2 for prod/firstrelease, 1 for all other regions.
61
+ * 3. Compose: `{prefix}.{suffix}.environment.{hostNameSuffix}`
62
+ *
63
+ * Example (prod, environmentId = "d909aac0-59d0-e5b1-900d-c082ef5774d7"):
64
+ * hexName = "d909aac059d0e5b1900dc082ef5774d7"
65
+ * suffix = "d7"
66
+ * prefix = "d909aac059d0e5b1900dc082ef5774"
67
+ * → "d909aac059d0e5b1900dc082ef5774.d7.environment.api.powerplatform.com"
68
+ */
69
+ function buildEnvironmentEndpoint(environmentId, region) {
70
+ const hostNameSuffix = HOST_NAME_SUFFIX[region] ?? HOST_NAME_SUFFIX['prod'];
71
+ const hexName = environmentId.toLowerCase().replace(/-/g, '');
72
+ const suffixLen = hexSuffixLength(region);
73
+ if (suffixLen >= hexName.length) {
74
+ throw new Error(`Cannot build Power Platform API endpoint: environment identifier too short after normalisation: "${hexName}"`);
75
+ }
76
+ const hexSuffix = hexName.substring(hexName.length - suffixLen);
77
+ const hexPrefix = hexName.substring(0, hexName.length - suffixLen);
78
+ return `https://${hexPrefix}.${hexSuffix}.environment.${hostNameSuffix}`;
79
+ }
80
+
81
+ // ---------------------------------------------------------------------------
82
+ // Public API
83
+ // ---------------------------------------------------------------------------
84
+
85
+ /**
86
+ * Token scope for the Power Platform management API (prod cluster).
87
+ * Non-prod clusters (test, gov, high, dev, mooncake, etc.) host the management
88
+ * API on their own audience, so prod-scope tokens are rejected with 401 by
89
+ * those clusters. Prefer {@link powerPlatformScope} when the region is known.
90
+ */
91
+ const POWER_PLATFORM_API_SCOPE = exports.POWER_PLATFORM_API_SCOPE = 'https://api.powerplatform.com/.default';
92
+
93
+ /**
94
+ * Region-aware Power Platform management API scope. The audience must match the
95
+ * cluster the request is sent to; reuses the same region → hostname table as
96
+ * {@link buildEnvironmentEndpoint}.
97
+ */
98
+ function powerPlatformScope(region) {
99
+ const host = HOST_NAME_SUFFIX[region] ?? HOST_NAME_SUFFIX['prod'];
100
+ return `https://${host}/.default`;
101
+ }
102
+ function getSafeErrorName(error) {
103
+ return error instanceof Error ? error.constructor.name : typeof error;
104
+ }
105
+
106
+ /**
107
+ * Fetch the Dataverse instanceUrl for a Power Platform environment by calling
108
+ * the environment-scoped Power Platform management API — the same call that
109
+ * the Host SDK's DefaultAppMetadataProvider makes to populate
110
+ * `databaseReferences[*].databaseDetails.linkedEnvironmentMetadata`.
111
+ *
112
+ * @param environmentId - Environment GUID (from power.config.json `environmentId`).
113
+ * @param region - Cluster region string (from power.config.json `region`, default "prod").
114
+ * @param acquireToken - Callback to obtain a bearer token for the given scopes.
115
+ * Scope will be {@link powerPlatformScope}`(region)`.
116
+ * @param bearerToken - Optional pre-fetched bearer token for {@link powerPlatformScope}`(region)`.
117
+ * Pass this to avoid a redundant `acquireToken` round-trip when the
118
+ * caller has already obtained a token for the same audience.
119
+ * @returns The Dataverse org URL (e.g. "https://org12345.crm.dynamics.com"), or
120
+ * `undefined` if the environment has no linked CDS database.
121
+ */
122
+ async function fetchInstanceUrl(environmentId, region, acquireToken, bearerToken) {
123
+ const scenario = (0, _index.getAppLogger)().trackScenario(_index.HostOperationNames.PlatformFetchInstanceUrl, {
124
+ environmentId,
125
+ region
126
+ });
127
+ try {
128
+ const baseUrl = buildEnvironmentEndpoint(environmentId, region);
129
+ const url = `${baseUrl}/powerapps/environment?api-version=1&%24filter=name+eq+%27${encodeURIComponent(environmentId)}%27`;
130
+ const token = bearerToken ?? (await acquireToken([powerPlatformScope(region)]));
131
+ if (!token) {
132
+ throw new Error('fetchInstanceUrl: failed to acquire Power Platform API token');
133
+ }
134
+ const response = await fetch(url, {
135
+ method: 'GET',
136
+ headers: {
137
+ Authorization: `Bearer ${token}`,
138
+ 'Content-Type': 'application/json'
139
+ }
140
+ });
141
+ if (!response.ok) {
142
+ throw new Error(`fetchInstanceUrl: environment API returned ${response.status} ${response.statusText}`);
143
+ }
144
+ const env = await response.json();
145
+ const instanceUrl = env.properties?.linkedEnvironmentMetadata?.instanceUrl;
146
+ scenario.complete({
147
+ hasInstanceUrl: instanceUrl !== undefined
148
+ });
149
+ return instanceUrl;
150
+ } catch (e) {
151
+ scenario.fail(undefined, {
152
+ errorName: getSafeErrorName(e)
153
+ });
154
+ throw e;
155
+ }
156
+ }
157
+
158
+ // ---------------------------------------------------------------------------
159
+ // buildCdsDataSources
160
+ // ---------------------------------------------------------------------------
161
+
162
+ /**
163
+ * Shape of a single Dataverse table entry inside power.config.json
164
+ * `databaseReferences[*].dataSources[*]`.
165
+ */
166
+
167
+ /**
168
+ * Shape of a single database reference entry inside power.config.json
169
+ * `databaseReferences`.
170
+ */
171
+
172
+ /**
173
+ * Build the CDS data source config array that the SDK reads via
174
+ * AppPowerAppsClientPlugin.getAppCdsDataSourceConfigsAsync.
175
+ *
176
+ * Pass the resolved Dataverse org URL (from useConnectionRefs) and the
177
+ * databaseReferences map from power.config.json. The resulting array is
178
+ * passed directly to <PowerAppsHostProvider dataSources={...} />.
179
+ *
180
+ * @param databaseReferences - The `databaseReferences` map from power.config.json.
181
+ * @param dataverseOrgUrl - The resolved Dataverse org URL
182
+ * (connectionRefs['commondataserviceforapps']?.datasetName).
183
+ * Pass an empty string before the org URL is known;
184
+ * the host provider will receive empty runtimeUrl entries
185
+ * and the SDK will not attempt Dataverse calls.
186
+ */
187
+ function buildCdsDataSources(databaseReferences, dataverseOrgUrl) {
188
+ return Object.values(databaseReferences).flatMap(dbRef => Object.values(dbRef.dataSources ?? {}).map(ds => ({
189
+ runtimeUrl: dataverseOrgUrl ? `${dataverseOrgUrl}/api/data/v9.0/` : '',
190
+ entitySetName: ds.entitySetName ?? '',
191
+ logicalName: ds.logicalName ?? '',
192
+ version: '9.2'
193
+ })));
194
+ }
@@ -0,0 +1,264 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.applyAclGrants = applyAclGrants;
7
+ exports.resolveViaStaticRefs = resolveViaStaticRefs;
8
+ var _PowerPlatformConnectionApi = require("./PowerPlatformConnectionApi.js");
9
+ var _PowerPlatformEnvironmentApi = require("./PowerPlatformEnvironmentApi.js");
10
+ var _disambiguate = require("../connections/disambiguate.js");
11
+ var _types = require("../connections/types.js");
12
+ /*!
13
+ * power-apps-native-host — resolveConnections
14
+ *
15
+ * Pure async helpers for the two connection-resolution strategies used by
16
+ * useConnectionRefs:
17
+ *
18
+ * • resolveViaStaticRefs — per-connector resolution using the static
19
+ * connectionReferences map from power.config.json. Used by the Dev Player
20
+ * and during local development (no appId) or when the launch API is
21
+ * unavailable. Handles pre-disambiguation ACL grants so inaccessible
22
+ * connections are excluded before the user is asked to pick.
23
+ *
24
+ * • applyAclGrants — post-resolution ACL grants used by the fast path
25
+ * (production APKs via fetchAppLaunchData).
26
+ *
27
+ * Both helpers return / consume the shared AppLaunchResult shape so the
28
+ * hook orchestrator can handle them uniformly.
29
+ */
30
+
31
+ const API_VERSION = '1';
32
+
33
+ // ---------------------------------------------------------------------------
34
+ // ConnectorSchema
35
+ // ---------------------------------------------------------------------------
36
+
37
+ /**
38
+ * Connector schema entry generated by `generate-connector-schemas`.
39
+ * Keyed by data source name in the `schemaMap` passed to `useConnectionRefs`.
40
+ */
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // resolveViaStaticRefs
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /**
47
+ * Resolve connections from the static `connectionReferences` map.
48
+ *
49
+ * Steps:
50
+ * 1. Build an apiId → schema lookup.
51
+ * 2. In parallel: fetch the Dataverse instanceUrl and all connection instances
52
+ * for every connector.
53
+ * 3. If `isvClientId` is set, run pre-disambiguation ACL grants — connections
54
+ * where the grant fails are marked `NeedsAclGrant` and excluded from
55
+ * resolution, prompting the user to create a new connection.
56
+ * 4. Disambiguate: resolve single matches, invoke callbacks for ambiguous /
57
+ * missing cases, perform one-shot retries when `onMissingConnection` returns
58
+ * `true`.
59
+ * 5. Build and return an `AppLaunchResult`-shaped object.
60
+ */
61
+ async function resolveViaStaticRefs({
62
+ connectionReferences,
63
+ schemaMap,
64
+ environmentId,
65
+ region,
66
+ acquireToken,
67
+ token,
68
+ isvClientId,
69
+ onDisambiguationNeeded,
70
+ onMissingConnection
71
+ }) {
72
+ // Build apiId → schema lookup from the static refs.
73
+ const schemaByApiId = Object.fromEntries(Object.values(connectionReferences).map(ref => {
74
+ const schema = ref.dataSources.map(ds => schemaMap[ds]).find(Boolean);
75
+ return schema ? [ref.id, schema] : null;
76
+ }).filter(entry => entry !== null));
77
+ const base = (0, _PowerPlatformEnvironmentApi.buildEnvironmentEndpoint)(environmentId, region);
78
+ const headers = {
79
+ Authorization: `Bearer ${token}`
80
+ };
81
+
82
+ // Fetch Dataverse instanceUrl and all connection instances in parallel.
83
+ const [instanceUrl, ...connResults] = await Promise.all([(0, _PowerPlatformEnvironmentApi.fetchInstanceUrl)(environmentId, region, acquireToken, token), ...Object.entries(connectionReferences).map(async ([localRefId, ref]) => {
84
+ const schema = schemaByApiId[ref.id];
85
+ if (!schema) {
86
+ return {
87
+ localRefId,
88
+ apiId: ref.id,
89
+ dataSources: ref.dataSources,
90
+ instances: []
91
+ };
92
+ }
93
+ const url = `${base}/connectivity/apis/${schema.name}/connections` + `?api-version=${API_VERSION}&$filter=environment eq '${environmentId}'`;
94
+ try {
95
+ const res = await fetch(url, {
96
+ headers
97
+ });
98
+ if (!res.ok) {
99
+ return {
100
+ localRefId,
101
+ apiId: ref.id,
102
+ dataSources: ref.dataSources,
103
+ instances: []
104
+ };
105
+ }
106
+ const body = await res.json();
107
+ const instances = (body.value ?? []).map(c => ({
108
+ id: (0, _disambiguate.extractConnectionId)(c.name),
109
+ name: c.name,
110
+ apiId: ref.id,
111
+ status: c.properties?.statuses?.[0]?.status === 'Connected' ? _types.ConnectionStatus.Connected : _types.ConnectionStatus.NotConnected,
112
+ displayName: c.properties?.displayName
113
+ }));
114
+ return {
115
+ localRefId,
116
+ apiId: ref.id,
117
+ dataSources: ref.dataSources,
118
+ instances
119
+ };
120
+ } catch {
121
+ return {
122
+ localRefId,
123
+ apiId: ref.id,
124
+ dataSources: ref.dataSources,
125
+ instances: []
126
+ };
127
+ }
128
+ })]);
129
+
130
+ // Pre-disambiguation ACL grants (ISV apps only).
131
+ //
132
+ // Connections where the grant fails are marked NeedsAclGrant so
133
+ // disambiguation treats them as unavailable and surfaces the
134
+ // "missing connection" flow, steering the user to create a new one.
135
+ if (isvClientId) {
136
+ const paToken = await acquireToken([_PowerPlatformConnectionApi.SERVICE_POWERAPPS_SCOPE]);
137
+ const paOid = paToken ? (0, _PowerPlatformConnectionApi.parseJwtOid)(paToken) : null;
138
+ if (paToken && paOid) {
139
+ await Promise.all(connResults.map(async r => {
140
+ const connId = schemaByApiId[r.apiId]?.name;
141
+ if (!connId) return;
142
+ await Promise.all(r.instances.map(async inst => {
143
+ if (inst.status !== _types.ConnectionStatus.Connected) return;
144
+ const ok = await (0, _PowerPlatformConnectionApi.addAadAppToConnectionAcl)(connId, inst.id, environmentId, isvClientId, paOid, paToken);
145
+ if (!ok) inst.status = _types.ConnectionStatus.NeedsAclGrant;
146
+ }));
147
+ }));
148
+ }
149
+ }
150
+
151
+ // Disambiguation.
152
+ const allConnectionsByApiId = {};
153
+ for (const r of connResults) {
154
+ allConnectionsByApiId[r.apiId] = r.instances;
155
+ }
156
+ const disambiguationResults = (0, _disambiguate.disambiguateConnections)(connectionReferences, allConnectionsByApiId);
157
+ const resolvedIds = {};
158
+ const unresolvedApiIds = [];
159
+ for (const dr of disambiguationResults) {
160
+ if (dr.result.kind === 'resolved') {
161
+ resolvedIds[dr.localRefId] = dr.result.connectionId;
162
+ } else if (dr.result.kind === 'ambiguous') {
163
+ const picked = onDisambiguationNeeded ? await onDisambiguationNeeded({
164
+ localRefId: dr.localRefId,
165
+ apiId: dr.apiId,
166
+ candidates: dr.result.candidates
167
+ }) : null;
168
+ // Fall back to the first Connected candidate so the app can still start.
169
+ resolvedIds[dr.localRefId] = picked ?? dr.result.candidates[0]?.id ?? '';
170
+ } else {
171
+ // kind === 'missing'
172
+ let retried = false;
173
+ if (onMissingConnection) {
174
+ retried = await onMissingConnection({
175
+ localRefId: dr.localRefId,
176
+ apiId: dr.apiId
177
+ });
178
+ }
179
+ if (retried) {
180
+ // One-shot retry for this specific connector.
181
+ const schema = schemaByApiId[dr.apiId];
182
+ if (schema) {
183
+ try {
184
+ const url = `${base}/connectivity/apis/${schema.name}/connections` + `?api-version=${API_VERSION}&$filter=environment eq '${environmentId}'`;
185
+ const res = await fetch(url, {
186
+ headers
187
+ });
188
+ if (res.ok) {
189
+ const body = await res.json();
190
+ const retryInstances = (body.value ?? []).map(c => ({
191
+ id: (0, _disambiguate.extractConnectionId)(c.name),
192
+ name: c.name,
193
+ apiId: dr.apiId,
194
+ status: c.properties?.statuses?.[0]?.status === 'Connected' ? _types.ConnectionStatus.Connected : _types.ConnectionStatus.NotConnected
195
+ }));
196
+ const connected = retryInstances.find(i => i.status === _types.ConnectionStatus.Connected);
197
+ if (connected) {
198
+ resolvedIds[dr.localRefId] = connected.id;
199
+ continue;
200
+ }
201
+ }
202
+ } catch {
203
+ // Fall through to missing.
204
+ }
205
+ }
206
+ }
207
+ resolvedIds[dr.localRefId] = '';
208
+ unresolvedApiIds.push(dr.apiId);
209
+ }
210
+ }
211
+ const dataverseOrgUrl = (instanceUrl ?? '').replace(/\/$/, '');
212
+
213
+ // Build the final AppConnectionReference map.
214
+ const connectionRefs = {};
215
+ for (const [localRefId, ref] of Object.entries(connectionReferences)) {
216
+ const schema = schemaByApiId[ref.id];
217
+ const connectionName = resolvedIds[localRefId] ?? '';
218
+ const isDataverse = ref.id.includes('commondataserviceforapps');
219
+ const entry = {
220
+ apiId: ref.id,
221
+ runtimeUrl: schema?.properties.primaryRuntimeUrl ?? '',
222
+ connectionName,
223
+ datasetName: isDataverse ? dataverseOrgUrl : ''
224
+ };
225
+ for (const ds of ref.dataSources) {
226
+ connectionRefs[ds] = entry;
227
+ }
228
+ }
229
+ return {
230
+ connectionRefs,
231
+ dataverseOrgUrl,
232
+ missingConnectors: unresolvedApiIds
233
+ };
234
+ }
235
+
236
+ // ---------------------------------------------------------------------------
237
+ // applyAclGrants
238
+ // ---------------------------------------------------------------------------
239
+
240
+ /**
241
+ * Run idempotent post-resolution ACL grants on behalf of the ISV app.
242
+ *
243
+ * Used by the fast path (production APKs via `fetchAppLaunchData`) where the
244
+ * launch API has already resolved the user's connections — grants are applied
245
+ * after the fact so APIM accepts tokens issued to the ISV's AAD app.
246
+ *
247
+ * For the slow path the grants run before disambiguation inside
248
+ * `resolveViaStaticRefs`, where they can still influence which connections
249
+ * are considered available.
250
+ *
251
+ * Failures are swallowed — a failed grant will surface as a 403 at runtime
252
+ * when the connector is called.
253
+ */
254
+ async function applyAclGrants(connectionRefs, environmentId, isvClientId, acquireToken) {
255
+ const paToken = await acquireToken([_PowerPlatformConnectionApi.SERVICE_POWERAPPS_SCOPE]);
256
+ const paOid = paToken ? (0, _PowerPlatformConnectionApi.parseJwtOid)(paToken) : null;
257
+ if (!paToken || !paOid) return;
258
+ const seen = new Set();
259
+ await Promise.all(Object.values(connectionRefs).map(async ref => {
260
+ if (!ref.connectionName || seen.has(ref.connectionName)) return;
261
+ seen.add(ref.connectionName);
262
+ await (0, _PowerPlatformConnectionApi.addAadAppToConnectionAcl)(ref.apiId, ref.connectionName, environmentId, isvClientId, paOid, paToken);
263
+ }));
264
+ }