@7k-inari/ui-plugin-sdk 0.1.8-38fba15 → 0.1.8-4f42c7d

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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
package/README.md CHANGED
@@ -9,8 +9,11 @@ Stack: TypeScript, npm package
9
9
  ```sh
10
10
  npm create inari-ui-extension my-extension
11
11
  cd my-extension && npm install && npm run dev
12
+ npm run typecheck && npm run build
12
13
  ```
13
14
 
15
+ The build uses the canonical `inari-ui-ext` CLI and emits `dist/remoteEntry.js`; no consumer webpack config or install-time SDK clone/build is needed.
16
+
14
17
  ## Writing an extension
15
18
 
16
19
  ```tsx
@@ -30,6 +33,7 @@ export default createExtension({
30
33
  - [Blueprint contract](docs/blueprints.md) — typed slots, zod manifests
31
34
  - [Host APIs](docs/host-apis.md) — auth/tenant contexts, API client, design tokens, testing mocks
32
35
  - [Dev harness](docs/harness.md) — standalone dev against a mock control plane
36
+ - [Production build](docs/build.md) — canonical Module Federation remoteEntry.js
33
37
  - [Shared dependencies](docs/shared-dependencies.md) — React singleton contract
34
38
 
35
39
  ## Package entry points
@@ -25,6 +25,40 @@ function init() {
25
25
  console.log('Next: cd into it, npm install, then: npx inari-ui-ext dev');
26
26
  }
27
27
 
28
+ async function build() {
29
+ let entry;
30
+ let name;
31
+ let outDir;
32
+ for (let i = 0; i < args.length; i++) {
33
+ const arg = args[i];
34
+ if (arg === '--name') {
35
+ name = args[++i];
36
+ } else if (arg === '--out-dir') {
37
+ outDir = args[++i];
38
+ } else if (arg.startsWith('--')) {
39
+ console.error(`unknown build option: ${arg}`);
40
+ process.exit(1);
41
+ } else if (entry === undefined) {
42
+ entry = arg;
43
+ } else {
44
+ console.error(`unexpected build argument: ${arg}`);
45
+ process.exit(1);
46
+ }
47
+ }
48
+ if (!name) {
49
+ console.error('inari-ui-ext build requires --name <registry-extension-name>');
50
+ process.exit(1);
51
+ }
52
+ try {
53
+ const { buildExtension } = await import(resolve(here, '../dist/harness/build.js'));
54
+ const result = await buildExtension({ entry, name, outDir });
55
+ console.log(`Built ${result.containerName}/extension → ${resolve(result.outDir, 'remoteEntry.js')}`);
56
+ } catch (error) {
57
+ console.error(error instanceof Error ? error.message : String(error));
58
+ process.exit(1);
59
+ }
60
+ }
61
+
28
62
  switch (command) {
29
63
  case 'dev':
30
64
  await dev();
@@ -32,7 +66,10 @@ switch (command) {
32
66
  case 'init':
33
67
  init();
34
68
  break;
69
+ case 'build':
70
+ await build();
71
+ break;
35
72
  default:
36
- console.log('Usage: inari-ui-ext <dev [entry] | init [dir]>');
73
+ console.log('Usage: inari-ui-ext <dev [entry] | init [dir] | build [entry] --name <name> [--out-dir dist]>');
37
74
  process.exit(command ? 1 : 0);
38
75
  }
@@ -0,0 +1,10 @@
1
+ // src/host/remote-name.ts
2
+ function extensionContainerName(name) {
3
+ if (name.length === 0) throw new Error("extension name is required");
4
+ return name.replace(/[^a-zA-Z0-9_$]/g, "_");
5
+ }
6
+
7
+ export {
8
+ extensionContainerName
9
+ };
10
+ //# sourceMappingURL=chunk-3OQNZ2DO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/host/remote-name.ts"],"sourcesContent":["export function extensionContainerName(name: string): string {\n if (name.length === 0) throw new Error('extension name is required');\n return name.replace(/[^a-zA-Z0-9_$]/g, '_');\n}\n"],"mappings":";AAAO,SAAS,uBAAuB,MAAsB;AAC3D,MAAI,KAAK,WAAW,EAAG,OAAM,IAAI,MAAM,4BAA4B;AACnE,SAAO,KAAK,QAAQ,mBAAmB,GAAG;AAC5C;","names":[]}
@@ -45,8 +45,10 @@ var CODE_TO_KIND = {
45
45
  session_expired: "session-expired",
46
46
  reauth_required: "session-expired",
47
47
  downstream_permission_denied: "downstream-denied",
48
+ inari_fga_denied: "fga-denied",
48
49
  fga_denied: "fga-denied",
49
50
  permission_denied: "fga-denied",
51
+ auth_unavailable: "exchange-failed",
50
52
  exchange_failed: "exchange-failed",
51
53
  auth_model_failure: "exchange-failed"
52
54
  };
@@ -89,22 +91,26 @@ var KIND_TO_CLASS = {
89
91
  function isExtensionApiError(err) {
90
92
  return err instanceof ExtensionApiError;
91
93
  }
94
+ function parseReauth(value) {
95
+ if (typeof value !== "object" || value === null) return void 0;
96
+ const rec = value;
97
+ const reauth = {};
98
+ if (typeof rec.provider === "string") reauth.provider = rec.provider;
99
+ if (typeof rec.hint === "string") reauth.hint = rec.hint;
100
+ return reauth;
101
+ }
92
102
  function parseBody(body) {
93
103
  if (typeof body !== "object" || body === null) return {};
94
- const err = body.error;
95
- if (typeof err !== "object" || err === null) return {};
96
- const rec = err;
104
+ const outer = body;
105
+ const nested = outer.error;
106
+ const rec = typeof nested === "object" && nested !== null ? nested : outer;
97
107
  const out = {};
98
108
  if (typeof rec.code === "string") out.code = rec.code;
99
109
  if (typeof rec.message === "string") out.message = rec.message;
110
+ else if (typeof rec.detail === "string") out.message = rec.detail;
100
111
  if (typeof rec.requestId === "string") out.requestId = rec.requestId;
101
- if (typeof rec.reauth === "object" && rec.reauth !== null) {
102
- const r = rec.reauth;
103
- const reauth = {};
104
- if (typeof r.provider === "string") reauth.provider = r.provider;
105
- if (typeof r.hint === "string") reauth.hint = r.hint;
106
- out.reauth = reauth;
107
- }
112
+ else if (typeof rec.request_id === "string") out.requestId = rec.request_id;
113
+ out.reauth = parseReauth(rec.reauth);
108
114
  return out;
109
115
  }
110
116
  function fallbackKind(status) {
@@ -113,10 +119,11 @@ function fallbackKind(status) {
113
119
  return "extension-failure";
114
120
  }
115
121
  var MAX_MESSAGE_LENGTH = 300;
122
+ var PROVIDER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
116
123
  function sanitizeMessage(message) {
117
124
  return message.length > MAX_MESSAGE_LENGTH ? `${message.slice(0, MAX_MESSAGE_LENGTH)}\u2026` : message;
118
125
  }
119
- function classifyExtensionError(status, body, extension) {
126
+ function classifyExtensionError(status, body, extension, headers) {
120
127
  const parsed = parseBody(body);
121
128
  const mapped = parsed.code ? CODE_TO_KIND[parsed.code] : void 0;
122
129
  const kind = mapped ?? fallbackKind(status);
@@ -124,7 +131,14 @@ function classifyExtensionError(status, body, extension) {
124
131
  const meta = {};
125
132
  if (parsed.requestId !== void 0) meta.requestId = parsed.requestId;
126
133
  if (extension !== void 0) meta.extension = extension;
127
- if (kind === "session-expired" && parsed.reauth !== void 0) meta.reauth = parsed.reauth;
134
+ if (kind === "session-expired") {
135
+ if (parsed.reauth !== void 0) {
136
+ meta.reauth = parsed.reauth;
137
+ } else {
138
+ const provider = headers?.get("X-Inari-Reauth");
139
+ if (provider && PROVIDER_PATTERN.test(provider)) meta.reauth = { provider };
140
+ }
141
+ }
128
142
  const Cls = KIND_TO_CLASS[kind];
129
143
  return new Cls(status, message, meta);
130
144
  }
@@ -182,9 +196,10 @@ var ApiClient = class {
182
196
  return this.request("POST", `/api/v1/approvals/${encodeURIComponent(id)}/approve`);
183
197
  }
184
198
  async invokeExtension(name, path, init = {}) {
199
+ const proxyPath = extensionProxyPath(name, path);
185
200
  const token = await this.getToken();
186
201
  const res = await this.fetchImpl(
187
- `${this.baseUrl}/api/extensions/${encodeURIComponent(name)}${path}`,
202
+ `${this.baseUrl}${proxyPath}`,
188
203
  {
189
204
  method: init.method ?? "GET",
190
205
  headers: {
@@ -204,7 +219,7 @@ var ApiClient = class {
204
219
  parseFailed = true;
205
220
  }
206
221
  if (!res.ok) {
207
- throw classifyExtensionError(res.status, parsed, name);
222
+ throw classifyExtensionError(res.status, parsed, name, res.headers);
208
223
  }
209
224
  if (parseFailed) {
210
225
  throw new ExtensionFailureError(
@@ -216,6 +231,37 @@ var ApiClient = class {
216
231
  return parsed;
217
232
  }
218
233
  };
234
+ function extensionProxyPath(name, path) {
235
+ if (name.length === 0) throw new Error("extension name is required");
236
+ if (!path.startsWith("/") || path.startsWith("//")) {
237
+ throw new Error("extension path must start with exactly one slash");
238
+ }
239
+ for (const character of path) {
240
+ const code = character.charCodeAt(0);
241
+ if (character === "\\" || code <= 31 || code === 127) {
242
+ throw new Error("extension path contains forbidden characters");
243
+ }
244
+ }
245
+ const pathname = path.split(/[?#]/, 1)[0];
246
+ for (const segment of pathname.split("/")) {
247
+ let decoded;
248
+ try {
249
+ decoded = decodeURIComponent(segment);
250
+ } catch {
251
+ throw new Error("extension path contains invalid percent encoding");
252
+ }
253
+ if (decoded === "." || decoded === "..") {
254
+ throw new Error("extension path must not contain dot segments");
255
+ }
256
+ for (const character of decoded) {
257
+ const code = character.charCodeAt(0);
258
+ if (character === "/" || character === "\\" || code <= 31 || code === 127) {
259
+ throw new Error("extension path contains forbidden encoded characters");
260
+ }
261
+ }
262
+ }
263
+ return `/api/extensions/${encodeURIComponent(name)}${path}`;
264
+ }
219
265
 
220
266
  export {
221
267
  TenantContext,
@@ -233,4 +279,4 @@ export {
233
279
  classifyExtensionError,
234
280
  ApiClient
235
281
  };
236
- //# sourceMappingURL=chunk-SEVFUJHN.js.map
282
+ //# sourceMappingURL=chunk-46DIN4CV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/host/tenant.ts","../src/host/api-error.ts","../src/host/extension-errors.ts","../src/host/api.ts"],"sourcesContent":["import { createContext, createElement, useContext, type ReactNode } from 'react';\n\nexport interface TenantRef {\n orgId: string;\n orgName: string;\n team?: string;\n}\n\nexport interface TenantChangeEvent {\n previous: TenantRef | null;\n current: TenantRef;\n}\n\nexport type TenantChangeListener = (event: TenantChangeEvent) => void;\n\nexport interface TenantState {\n current: TenantRef | null;\n available: TenantRef[];\n switchTenant: (orgId: string, team?: string) => void;\n onTenantChange: (listener: TenantChangeListener) => () => void;\n}\n\nexport const TenantContext = createContext<TenantState | null>(null);\n\nexport function TenantProvider(props: { value: TenantState; children: ReactNode }) {\n return createElement(TenantContext.Provider, { value: props.value }, props.children);\n}\n\nexport function useTenant(): TenantState {\n const ctx = useContext(TenantContext);\n if (!ctx) throw new Error('useTenant must be used within a TenantProvider');\n return ctx;\n}\n\nexport function createTenantState(available: TenantRef[]): TenantState & { _listeners: Set<TenantChangeListener> } {\n const listeners = new Set<TenantChangeListener>();\n const state = {\n current: available[0] ?? null,\n available,\n _listeners: listeners,\n switchTenant(orgId: string, team?: string) {\n const next = available.find((t) => t.orgId === orgId && (team === undefined || t.team === team));\n if (!next) throw new Error(`unknown tenant: ${orgId}${team ? `/${team}` : ''}`);\n const previous = state.current;\n state.current = next;\n listeners.forEach((l) => l({ previous, current: next }));\n },\n onTenantChange(listener: TenantChangeListener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n return state;\n}\n","export class ApiError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = 'ApiError';\n }\n}\n","import { ApiError } from './api-error';\n\nexport type ExtensionErrorKind =\n | 'session-expired'\n | 'downstream-denied'\n | 'fga-denied'\n | 'exchange-failed'\n | 'extension-failure';\n\nexport interface ExtensionReauthMeta {\n provider?: string;\n hint?: string;\n}\n\nconst CODE_TO_KIND: Record<string, ExtensionErrorKind> = {\n session_expired: 'session-expired',\n reauth_required: 'session-expired',\n downstream_permission_denied: 'downstream-denied',\n inari_fga_denied: 'fga-denied',\n fga_denied: 'fga-denied',\n permission_denied: 'fga-denied',\n auth_unavailable: 'exchange-failed',\n exchange_failed: 'exchange-failed',\n auth_model_failure: 'exchange-failed',\n};\n\nexport abstract class ExtensionApiError extends ApiError {\n abstract readonly kind: ExtensionErrorKind;\n readonly retryable: boolean = false;\n readonly requestId?: string;\n readonly extension?: string;\n readonly reauth?: ExtensionReauthMeta;\n\n constructor(\n status: number,\n message: string,\n meta: { requestId?: string; extension?: string; reauth?: ExtensionReauthMeta } = {},\n ) {\n super(status, message);\n this.name = new.target.name;\n if (meta.requestId !== undefined) this.requestId = meta.requestId;\n if (meta.extension !== undefined) this.extension = meta.extension;\n if (meta.reauth !== undefined) this.reauth = meta.reauth;\n }\n}\n\nexport class SessionExpiredError extends ExtensionApiError {\n readonly kind = 'session-expired' as const;\n readonly retryable = true;\n}\n\nexport class DownstreamDeniedError extends ExtensionApiError {\n readonly kind = 'downstream-denied' as const;\n}\n\nexport class FgaDeniedError extends ExtensionApiError {\n readonly kind = 'fga-denied' as const;\n}\n\nexport class ExchangeFailedError extends ExtensionApiError {\n readonly kind = 'exchange-failed' as const;\n}\n\nexport class ExtensionFailureError extends ExtensionApiError {\n readonly kind = 'extension-failure' as const;\n}\n\nexport type AnyExtensionApiError =\n | SessionExpiredError\n | DownstreamDeniedError\n | FgaDeniedError\n | ExchangeFailedError\n | ExtensionFailureError;\n\nconst KIND_TO_CLASS = {\n 'session-expired': SessionExpiredError,\n 'downstream-denied': DownstreamDeniedError,\n 'fga-denied': FgaDeniedError,\n 'exchange-failed': ExchangeFailedError,\n 'extension-failure': ExtensionFailureError,\n} as const;\n\nexport function isExtensionApiError(err: unknown): err is ExtensionApiError {\n return err instanceof ExtensionApiError;\n}\n\ninterface ParsedErrorBody {\n code?: string;\n message?: string;\n requestId?: string;\n reauth?: ExtensionReauthMeta;\n}\n\nfunction parseReauth(value: unknown): ExtensionReauthMeta | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const rec = value as Record<string, unknown>;\n const reauth: ExtensionReauthMeta = {};\n if (typeof rec.provider === 'string') reauth.provider = rec.provider;\n if (typeof rec.hint === 'string') reauth.hint = rec.hint;\n return reauth;\n}\n\nfunction parseBody(body: unknown): ParsedErrorBody {\n if (typeof body !== 'object' || body === null) return {};\n const outer = body as Record<string, unknown>;\n const nested = outer.error;\n const rec = typeof nested === 'object' && nested !== null\n ? nested as Record<string, unknown>\n : outer;\n const out: ParsedErrorBody = {};\n if (typeof rec.code === 'string') out.code = rec.code;\n if (typeof rec.message === 'string') out.message = rec.message;\n else if (typeof rec.detail === 'string') out.message = rec.detail;\n if (typeof rec.requestId === 'string') out.requestId = rec.requestId;\n else if (typeof rec.request_id === 'string') out.requestId = rec.request_id;\n out.reauth = parseReauth(rec.reauth);\n return out;\n}\n\nfunction fallbackKind(status: number): ExtensionErrorKind {\n if (status === 401) return 'session-expired';\n if (status === 403) return 'fga-denied';\n return 'extension-failure';\n}\n\nconst MAX_MESSAGE_LENGTH = 300;\nconst PROVIDER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\n\nfunction sanitizeMessage(message: string): string {\n return message.length > MAX_MESSAGE_LENGTH\n ? `${message.slice(0, MAX_MESSAGE_LENGTH)}…`\n : message;\n}\n\nexport function classifyExtensionError(\n status: number,\n body: unknown,\n extension?: string,\n headers?: Headers,\n): AnyExtensionApiError {\n const parsed = parseBody(body);\n const mapped = parsed.code ? CODE_TO_KIND[parsed.code] : undefined;\n const kind = mapped ?? fallbackKind(status);\n const message = parsed.message !== undefined\n ? sanitizeMessage(parsed.message)\n : `extension invocation failed: ${status}`;\n const meta: { requestId?: string; extension?: string; reauth?: ExtensionReauthMeta } = {};\n if (parsed.requestId !== undefined) meta.requestId = parsed.requestId;\n if (extension !== undefined) meta.extension = extension;\n if (kind === 'session-expired') {\n if (parsed.reauth !== undefined) {\n meta.reauth = parsed.reauth;\n } else {\n const provider = headers?.get('X-Inari-Reauth');\n if (provider && PROVIDER_PATTERN.test(provider)) meta.reauth = { provider };\n }\n }\n const Cls = KIND_TO_CLASS[kind];\n return new Cls(status, message, meta);\n}\n","import { ApiError } from './api-error';\nimport { classifyExtensionError, ExtensionFailureError } from './extension-errors';\n\nexport { ApiError } from './api-error';\n\nexport interface Cluster {\n id: string;\n name: string;\n tenantId: string;\n state: 'Pending' | 'Active' | 'Degraded' | 'Cordoned' | 'Decommissioned';\n kubernetesVersion?: string;\n labels?: Record<string, string>;\n}\n\nexport interface CatalogItem {\n id: string;\n name: string;\n source: 'discovered' | 'curated' | 'platform' | 'template';\n version: string;\n description?: string;\n schema?: Record<string, unknown>;\n uiHints?: Record<string, unknown>;\n}\n\nexport interface ResourceInstance {\n id: string;\n catalogItemId: string;\n clusterId: string;\n cloudAccountId?: string;\n name: string;\n namespace?: string;\n health?: string;\n status?: Record<string, unknown>;\n ownerTeam?: string;\n}\n\nexport interface ApprovalRequest {\n id: string;\n action: string;\n requester: string;\n state: 'pending' | 'approved' | 'rejected';\n}\n\nexport interface ApiClientOptions {\n baseUrl: string;\n getToken: () => Promise<string | undefined> | string | undefined;\n fetchImpl?: typeof fetch;\n}\n\nexport class ApiClient {\n private readonly baseUrl: string;\n private readonly getToken: ApiClientOptions['getToken'];\n private readonly fetchImpl: typeof fetch;\n\n constructor(options: ApiClientOptions) {\n this.baseUrl = options.baseUrl.replace(/\\/$/, '');\n this.getToken = options.getToken;\n this.fetchImpl = options.fetchImpl ?? fetch;\n }\n\n private async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const token = await this.getToken();\n const res = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method,\n headers: {\n 'content-type': 'application/json',\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n });\n if (!res.ok) {\n throw new ApiError(res.status, `${method} ${path} failed: ${res.status}`);\n }\n if (res.status === 204) return undefined as T;\n return (await res.json()) as T;\n }\n\n listClusters(): Promise<Cluster[]> {\n return this.request('GET', '/api/v1/clusters');\n }\n\n getCluster(id: string): Promise<Cluster> {\n return this.request('GET', `/api/v1/clusters/${encodeURIComponent(id)}`);\n }\n\n listCatalogItems(clusterId?: string): Promise<CatalogItem[]> {\n const q = clusterId ? `?clusterId=${encodeURIComponent(clusterId)}` : '';\n return this.request('GET', `/api/v1/catalog/items${q}`);\n }\n\n getCatalogItem(id: string): Promise<CatalogItem> {\n return this.request('GET', `/api/v1/catalog/items/${encodeURIComponent(id)}`);\n }\n\n listResourceInstances(clusterId?: string): Promise<ResourceInstance[]> {\n const q = clusterId ? `?clusterId=${encodeURIComponent(clusterId)}` : '';\n return this.request('GET', `/api/v1/resources${q}`);\n }\n\n getResourceInstance(id: string): Promise<ResourceInstance> {\n return this.request('GET', `/api/v1/resources/${encodeURIComponent(id)}`);\n }\n\n listApprovals(): Promise<ApprovalRequest[]> {\n return this.request('GET', '/api/v1/approvals');\n }\n\n approveApproval(id: string): Promise<ApprovalRequest> {\n return this.request('POST', `/api/v1/approvals/${encodeURIComponent(id)}/approve`);\n }\n\n async invokeExtension<T>(\n name: string,\n path: string,\n init: { method?: string; body?: unknown } = {},\n ): Promise<T> {\n const proxyPath = extensionProxyPath(name, path);\n const token = await this.getToken();\n const res = await this.fetchImpl(\n `${this.baseUrl}${proxyPath}`,\n {\n method: init.method ?? 'GET',\n headers: {\n 'content-type': 'application/json',\n ...(token ? { authorization: `Bearer ${token}` } : {}),\n },\n body: init.body === undefined ? undefined : JSON.stringify(init.body),\n },\n );\n const text = await res.text();\n let parsed: unknown;\n let parseFailed = false;\n try {\n parsed = text ? JSON.parse(text) : undefined;\n } catch {\n parsed = undefined;\n parseFailed = true;\n }\n if (!res.ok) {\n throw classifyExtensionError(res.status, parsed, name, res.headers);\n }\n if (parseFailed) {\n throw new ExtensionFailureError(\n res.status,\n `extension '${name}' returned a non-JSON response (${res.status})`,\n { extension: name },\n );\n }\n return parsed as T;\n }\n}\n\nfunction extensionProxyPath(name: string, path: string): string {\n if (name.length === 0) throw new Error('extension name is required');\n if (!path.startsWith('/') || path.startsWith('//')) {\n throw new Error('extension path must start with exactly one slash');\n }\n for (const character of path) {\n const code = character.charCodeAt(0);\n if (character === '\\\\' || code <= 0x1f || code === 0x7f) {\n throw new Error('extension path contains forbidden characters');\n }\n }\n const pathname = path.split(/[?#]/, 1)[0];\n for (const segment of pathname.split('/')) {\n let decoded: string;\n try {\n decoded = decodeURIComponent(segment);\n } catch {\n throw new Error('extension path contains invalid percent encoding');\n }\n if (decoded === '.' || decoded === '..') {\n throw new Error('extension path must not contain dot segments');\n }\n for (const character of decoded) {\n const code = character.charCodeAt(0);\n if (character === '/' || character === '\\\\' || code <= 0x1f || code === 0x7f) {\n throw new Error('extension path contains forbidden encoded characters');\n }\n }\n }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Q,MAAM,IAAI,OAAO;AAAA,IACpE;AACA,QAAI,aAAa;AACf,YAAM,IAAI;AAAA,QACR,IAAI;AAAA,QACJ,cAAc,IAAI,mCAAmC,IAAI,MAAM;AAAA,QAC/D,EAAE,WAAW,KAAK;AAAA,MACpB;AAAA,IACF;AACA,WAAO;AAAA,EACT;AACF;AAEA,SAAS,mBAAmB,MAAc,MAAsB;AAC9D,MAAI,KAAK,WAAW,EAAG,OAAM,IAAI,MAAM,4BAA4B;AACnE,MAAI,CAAC,KAAK,WAAW,GAAG,KAAK,KAAK,WAAW,IAAI,GAAG;AAClD,UAAM,IAAI,MAAM,kDAAkD;AAAA,EACpE;AACA,aAAW,aAAa,MAAM;AAC5B,UAAM,OAAO,UAAU,WAAW,CAAC;AACnC,QAAI,cAAc,QAAQ,QAAQ,MAAQ,SAAS,KAAM;AACvD,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AAAA,EACF;AACA,QAAM,WAAW,KAAK,MAAM,QAAQ,CAAC,EAAE,CAAC;AACxC,aAAW,WAAW,SAAS,MAAM,GAAG,GAAG;AACzC,QAAI;AACJ,QAAI;AACF,gBAAU,mBAAmB,OAAO;AAAA,IACtC,QAAQ;AACN,YAAM,IAAI,MAAM,kDAAkD;AAAA,IACpE;AACA,QAAI,YAAY,OAAO,YAAY,MAAM;AACvC,YAAM,IAAI,MAAM,8CAA8C;AAAA,IAChE;AACA,eAAW,aAAa,SAAS;AAC/B,YAAM,OAAO,UAAU,WAAW,CAAC;AACnC,UAAI,cAAc,OAAO,cAAc,QAAQ,QAAQ,MAAQ,SAAS,KAAM;AAC5E,cAAM,IAAI,MAAM,sDAAsD;AAAA,MACxE;AAAA,IACF;AAAA,EACF;AACA,SAAO,mBAAmB,mBAAmB,IAAI,CAAC,GAAG,IAAI;AAC3D;","names":[]}
@@ -188,7 +188,7 @@ declare class ExtensionFailureError extends ExtensionApiError {
188
188
  }
189
189
  type AnyExtensionApiError = SessionExpiredError | DownstreamDeniedError | FgaDeniedError | ExchangeFailedError | ExtensionFailureError;
190
190
  declare function isExtensionApiError(err: unknown): err is ExtensionApiError;
191
- declare function classifyExtensionError(status: number, body: unknown, extension?: string): AnyExtensionApiError;
191
+ declare function classifyExtensionError(status: number, body: unknown, extension?: string, headers?: Headers): AnyExtensionApiError;
192
192
 
193
193
  export { extensionManifestSchema as B, DownstreamDeniedError as D, FgaDeniedError as F, getAuthState as G, isExtensionApiError as H, parseExtensionManifest as J, useAuth as K, usePrincipal as L, useTenant as M, ApiClient as d, ApiError as f, AuthContext as h, AuthProvider as i, ExchangeFailedError as k, ExtensionApiError as l, ExtensionFailureError as n, SLOT_KINDS as q, SessionExpiredError as r, TenantContext as u, TenantProvider as v, classifyExtensionError as y, createTenantState as z };
194
194
  export type { AnySlotContribution as A, CatalogItem as C, ExtensionManifestInput as E, InariExtension as I, ParsedExtensionManifest as P, ResourceInstance as R, SlotContribution as S, TenantChangeEvent as T, Cluster as a, SlotContext as b, AnyExtensionApiError as c, ApiClientOptions as e, ApprovalRequest as g, AuthState as j, ExtensionErrorKind as m, ExtensionReauthMeta as o, Principal as p, SlotKind as s, TenantChangeListener as t, TenantRef as w, TenantState as x };
@@ -188,7 +188,7 @@ declare class ExtensionFailureError extends ExtensionApiError {
188
188
  }
189
189
  type AnyExtensionApiError = SessionExpiredError | DownstreamDeniedError | FgaDeniedError | ExchangeFailedError | ExtensionFailureError;
190
190
  declare function isExtensionApiError(err: unknown): err is ExtensionApiError;
191
- declare function classifyExtensionError(status: number, body: unknown, extension?: string): AnyExtensionApiError;
191
+ declare function classifyExtensionError(status: number, body: unknown, extension?: string, headers?: Headers): AnyExtensionApiError;
192
192
 
193
193
  export { extensionManifestSchema as B, DownstreamDeniedError as D, FgaDeniedError as F, getAuthState as G, isExtensionApiError as H, parseExtensionManifest as J, useAuth as K, usePrincipal as L, useTenant as M, ApiClient as d, ApiError as f, AuthContext as h, AuthProvider as i, ExchangeFailedError as k, ExtensionApiError as l, ExtensionFailureError as n, SLOT_KINDS as q, SessionExpiredError as r, TenantContext as u, TenantProvider as v, classifyExtensionError as y, createTenantState as z };
194
194
  export type { AnySlotContribution as A, CatalogItem as C, ExtensionManifestInput as E, InariExtension as I, ParsedExtensionManifest as P, ResourceInstance as R, SlotContribution as S, TenantChangeEvent as T, Cluster as a, SlotContext as b, AnyExtensionApiError as c, ApiClientOptions as e, ApprovalRequest as g, AuthState as j, ExtensionErrorKind as m, ExtensionReauthMeta as o, Principal as p, SlotKind as s, TenantChangeListener as t, TenantRef as w, TenantState as x };
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // harness/build.ts
31
+ var build_exports = {};
32
+ __export(build_exports, {
33
+ buildExtension: () => buildExtension
34
+ });
35
+ module.exports = __toCommonJS(build_exports);
36
+ var import_node_fs = require("fs");
37
+ var import_node_path = require("path");
38
+ var import_node_module = require("module");
39
+ var import_webpack = __toESM(require("webpack"), 1);
40
+
41
+ // src/host/remote-name.ts
42
+ function extensionContainerName(name) {
43
+ if (name.length === 0) throw new Error("extension name is required");
44
+ return name.replace(/[^a-zA-Z0-9_$]/g, "_");
45
+ }
46
+
47
+ // harness/build.ts
48
+ var import_meta = {};
49
+ async function buildExtension(options) {
50
+ const containerName = extensionContainerName(options.name);
51
+ const entry = (0, import_node_path.resolve)(process.cwd(), options.entry ?? "./src/index.tsx");
52
+ if (!(0, import_node_fs.existsSync)(entry)) throw new Error(`extension entry not found: ${entry}`);
53
+ const outDir = (0, import_node_path.resolve)(process.cwd(), options.outDir ?? "dist");
54
+ const tsconfig = (0, import_node_path.resolve)(process.cwd(), options.tsconfig ?? "tsconfig.json");
55
+ if (!(0, import_node_fs.existsSync)(tsconfig)) throw new Error(`extension tsconfig not found: ${tsconfig}`);
56
+ if (containsPath(outDir, process.cwd()) || containsPath(outDir, entry) || containsPath(outDir, tsconfig)) {
57
+ throw new Error("extension output directory must not contain the project, entry, or tsconfig");
58
+ }
59
+ const require2 = (0, import_node_module.createRequire)(import_meta.url);
60
+ const shared = {
61
+ react: { singleton: true, requiredVersion: false, import: false },
62
+ "react/jsx-runtime": { singleton: true, requiredVersion: false, import: false },
63
+ "react-dom": { singleton: true, requiredVersion: false, import: false },
64
+ "react-dom/client": { singleton: true, requiredVersion: false, import: false },
65
+ "react-router-dom": { singleton: true, requiredVersion: false, import: false },
66
+ zod: { singleton: true, requiredVersion: false, import: false },
67
+ "@7k-inari/ui-plugin-sdk": { singleton: true, requiredVersion: false, import: false }
68
+ };
69
+ const config = {
70
+ entry,
71
+ mode: "production",
72
+ devtool: false,
73
+ output: { path: outDir, publicPath: "auto", clean: true, uniqueName: containerName },
74
+ resolve: { extensions: [".tsx", ".ts", ".js"] },
75
+ module: {
76
+ rules: [{
77
+ test: /\.tsx?$/,
78
+ use: [{
79
+ loader: require2.resolve("ts-loader"),
80
+ options: {
81
+ configFile: tsconfig,
82
+ onlyCompileBundledFiles: true,
83
+ compilerOptions: { noEmit: false, declaration: false, declarationMap: false }
84
+ }
85
+ }],
86
+ exclude: /node_modules/
87
+ }]
88
+ },
89
+ plugins: [
90
+ new import_webpack.default.container.ModuleFederationPlugin({
91
+ name: containerName,
92
+ filename: "remoteEntry.js",
93
+ exposes: { "./extension": entry },
94
+ shared
95
+ })
96
+ ]
97
+ };
98
+ const stats = await compile(config);
99
+ if (stats.hasErrors()) {
100
+ throw new Error(`extension build failed:
101
+ ${stats.toString({
102
+ colors: false,
103
+ all: false,
104
+ errors: true,
105
+ errorDetails: true
106
+ })}`);
107
+ }
108
+ return { containerName, outDir, stats };
109
+ }
110
+ function containsPath(parent, candidate) {
111
+ const child = (0, import_node_path.relative)(parent, candidate);
112
+ return child === "" || child !== ".." && !child.startsWith(`..${import_node_path.sep}`) && !(0, import_node_path.isAbsolute)(child);
113
+ }
114
+ function compile(config) {
115
+ return new Promise((resolve2, reject) => {
116
+ (0, import_webpack.default)(config, (error, stats) => {
117
+ if (error) {
118
+ reject(error);
119
+ return;
120
+ }
121
+ if (!stats) {
122
+ reject(new Error("extension build returned no webpack stats"));
123
+ return;
124
+ }
125
+ resolve2(stats);
126
+ });
127
+ });
128
+ }
129
+ // Annotate the CommonJS export names for ESM import in node:
130
+ 0 && (module.exports = {
131
+ buildExtension
132
+ });
133
+ //# sourceMappingURL=build.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../harness/build.ts","../../src/host/remote-name.ts"],"sourcesContent":["import { existsSync } from 'node:fs';\nimport { isAbsolute, relative, resolve, sep } from 'node:path';\nimport { createRequire } from 'node:module';\nimport webpack, { type Configuration, type Stats } from 'webpack';\nimport { extensionContainerName } from '../src/host/remote-name.js';\n\nexport interface BuildExtensionOptions {\n entry?: string;\n name: string;\n outDir?: string;\n tsconfig?: string;\n}\n\nexport interface BuildExtensionResult {\n containerName: string;\n outDir: string;\n stats: Stats;\n}\n\nexport async function buildExtension(options: BuildExtensionOptions): Promise<BuildExtensionResult> {\n const containerName = extensionContainerName(options.name);\n const entry = resolve(process.cwd(), options.entry ?? './src/index.tsx');\n if (!existsSync(entry)) throw new Error(`extension entry not found: ${entry}`);\n const outDir = resolve(process.cwd(), options.outDir ?? 'dist');\n const tsconfig = resolve(process.cwd(), options.tsconfig ?? 'tsconfig.json');\n if (!existsSync(tsconfig)) throw new Error(`extension tsconfig not found: ${tsconfig}`);\n if (containsPath(outDir, process.cwd()) || containsPath(outDir, entry) || containsPath(outDir, tsconfig)) {\n throw new Error('extension output directory must not contain the project, entry, or tsconfig');\n }\n\n const require = createRequire(import.meta.url);\n const shared = {\n react: { singleton: true, requiredVersion: false, import: false },\n 'react/jsx-runtime': { singleton: true, requiredVersion: false, import: false },\n 'react-dom': { singleton: true, requiredVersion: false, import: false },\n 'react-dom/client': { singleton: true, requiredVersion: false, import: false },\n 'react-router-dom': { singleton: true, requiredVersion: false, import: false },\n zod: { singleton: true, requiredVersion: false, import: false },\n '@7k-inari/ui-plugin-sdk': { singleton: true, requiredVersion: false, import: false },\n } as const;\n const config: Configuration = {\n entry,\n mode: 'production',\n devtool: false,\n output: { path: outDir, publicPath: 'auto', clean: true, uniqueName: containerName },\n resolve: { extensions: ['.tsx', '.ts', '.js'] },\n module: {\n rules: [{\n test: /\\.tsx?$/,\n use: [{\n loader: require.resolve('ts-loader'),\n options: {\n configFile: tsconfig,\n onlyCompileBundledFiles: true,\n compilerOptions: { noEmit: false, declaration: false, declarationMap: false },\n },\n }],\n exclude: /node_modules/,\n }],\n },\n plugins: [\n new webpack.container.ModuleFederationPlugin({\n name: containerName,\n filename: 'remoteEntry.js',\n exposes: { './extension': entry },\n shared,\n }),\n ],\n };\n\n const stats = await compile(config);\n if (stats.hasErrors()) {\n throw new Error(`extension build failed:\\n${stats.toString({\n colors: false,\n all: false,\n errors: true,\n errorDetails: true,\n })}`);\n }\n return { containerName, outDir, stats };\n}\n\nfunction containsPath(parent: string, candidate: string): boolean {\n const child = relative(parent, candidate);\n return child === '' || (child !== '..' && !child.startsWith(`..${sep}`) && !isAbsolute(child));\n}\n\nfunction compile(config: Configuration): Promise<Stats> {\n return new Promise((resolve, reject) => {\n webpack(config, (error, stats) => {\n if (error) {\n reject(error);\n return;\n }\n if (!stats) {\n reject(new Error('extension build returned no webpack stats'));\n return;\n }\n resolve(stats);\n });\n });\n}\n","export function extensionContainerName(name: string): string {\n if (name.length === 0) throw new Error('extension name is required');\n return name.replace(/[^a-zA-Z0-9_$]/g, '_');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,qBAA2B;AAC3B,uBAAmD;AACnD,yBAA8B;AAC9B,qBAAwD;;;ACHjD,SAAS,uBAAuB,MAAsB;AAC3D,MAAI,KAAK,WAAW,EAAG,OAAM,IAAI,MAAM,4BAA4B;AACnE,SAAO,KAAK,QAAQ,mBAAmB,GAAG;AAC5C;;;ADHA;AAmBA,eAAsB,eAAe,SAA+D;AAClG,QAAM,gBAAgB,uBAAuB,QAAQ,IAAI;AACzD,QAAM,YAAQ,0BAAQ,QAAQ,IAAI,GAAG,QAAQ,SAAS,iBAAiB;AACvE,MAAI,KAAC,2BAAW,KAAK,EAAG,OAAM,IAAI,MAAM,8BAA8B,KAAK,EAAE;AAC7E,QAAM,aAAS,0BAAQ,QAAQ,IAAI,GAAG,QAAQ,UAAU,MAAM;AAC9D,QAAM,eAAW,0BAAQ,QAAQ,IAAI,GAAG,QAAQ,YAAY,eAAe;AAC3E,MAAI,KAAC,2BAAW,QAAQ,EAAG,OAAM,IAAI,MAAM,iCAAiC,QAAQ,EAAE;AACtF,MAAI,aAAa,QAAQ,QAAQ,IAAI,CAAC,KAAK,aAAa,QAAQ,KAAK,KAAK,aAAa,QAAQ,QAAQ,GAAG;A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