@amaster.ai/cli 1.1.27 → 1.1.29

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/dist/cli.cjs CHANGED
@@ -2,15 +2,1972 @@
2
2
  'use strict';
3
3
 
4
4
  var fs = require('fs');
5
- var child_process = require('child_process');
6
- var os = require('os');
5
+ var promises = require('readline/promises');
6
+ var process$1 = require('process');
7
+ var commander = require('commander');
8
+ var promises$1 = require('fs/promises');
7
9
  var path = require('path');
10
+ var crypto = require('crypto');
11
+ var os = require('os');
12
+ var tar = require('tar');
13
+ var http = require('http');
14
+ var child_process = require('child_process');
15
+ var YAML2 = require('yaml');
8
16
  var ts = require('typescript');
9
17
 
18
+ var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
10
19
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
11
20
 
12
- var ts__default = /*#__PURE__*/_interopDefault(ts);
21
+ function _interopNamespace(e) {
22
+ if (e && e.__esModule) return e;
23
+ var n = Object.create(null);
24
+ if (e) {
25
+ Object.keys(e).forEach(function (k) {
26
+ if (k !== 'default') {
27
+ var d = Object.getOwnPropertyDescriptor(e, k);
28
+ Object.defineProperty(n, k, d.get ? d : {
29
+ enumerable: true,
30
+ get: function () { return e[k]; }
31
+ });
32
+ }
33
+ });
34
+ }
35
+ n.default = e;
36
+ return Object.freeze(n);
37
+ }
38
+
39
+ var tar__namespace = /*#__PURE__*/_interopNamespace(tar);
40
+ var YAML2__default = /*#__PURE__*/_interopDefault(YAML2);
41
+ var ts__default = /*#__PURE__*/_interopDefault(ts);
42
+
43
+ var EXCLUDED_NAMES = /* @__PURE__ */ new Set([".git", "node_modules", ".DS_Store"]);
44
+ function sha256(buffer) {
45
+ return `sha256:${crypto.createHash("sha256").update(buffer).digest("hex")}`;
46
+ }
47
+ async function collectFiles(rootDir, currentDir = rootDir) {
48
+ const entries = await promises$1.readdir(currentDir, { withFileTypes: true });
49
+ const results = [];
50
+ for (const entry of entries) {
51
+ if (EXCLUDED_NAMES.has(entry.name)) {
52
+ continue;
53
+ }
54
+ const absolutePath = path.join(currentDir, entry.name);
55
+ if (entry.isDirectory()) {
56
+ results.push(...await collectFiles(rootDir, absolutePath));
57
+ continue;
58
+ }
59
+ results.push(path.relative(rootDir, absolutePath));
60
+ }
61
+ return results.sort();
62
+ }
63
+ async function packageAddonDirectory(sourceDir) {
64
+ const absoluteSourceDir = path.resolve(sourceDir);
65
+ const sourceStat = await promises$1.stat(absoluteSourceDir);
66
+ if (!sourceStat.isDirectory()) {
67
+ throw new Error(`Addon source is not a directory: ${sourceDir}`);
68
+ }
69
+ const files = await collectFiles(absoluteSourceDir);
70
+ if (!files.length) {
71
+ throw new Error(`Addon directory is empty: ${sourceDir}`);
72
+ }
73
+ const archiveDir = await promises$1.mkdtemp(path.join(os.tmpdir(), "amaster-addon-pack-"));
74
+ const archivePath = path.join(archiveDir, `${path.basename(absoluteSourceDir)}-${crypto.randomUUID()}.tgz`);
75
+ await tar__namespace.c(
76
+ {
77
+ cwd: absoluteSourceDir,
78
+ gzip: true,
79
+ file: archivePath,
80
+ portable: true
81
+ },
82
+ files
83
+ );
84
+ return {
85
+ archivePath,
86
+ buffer: await promises$1.readFile(archivePath)
87
+ };
88
+ }
89
+ async function extractAddonArchiveBuffer(buffer) {
90
+ const extractDir = await promises$1.mkdtemp(path.join(os.tmpdir(), "amaster-addon-extract-"));
91
+ const archivePath = path.join(extractDir, "addon.tgz");
92
+ await promises$1.writeFile(archivePath, buffer);
93
+ await tar__namespace.x({
94
+ cwd: extractDir,
95
+ file: archivePath,
96
+ gzip: true
97
+ });
98
+ return extractDir;
99
+ }
100
+ async function extractAddonArchiveFile(filePath) {
101
+ const absolutePath = path.resolve(filePath);
102
+ const extractDir = await promises$1.mkdtemp(path.join(os.tmpdir(), "amaster-addon-extract-"));
103
+ await tar__namespace.x({
104
+ cwd: extractDir,
105
+ file: absolutePath,
106
+ gzip: true
107
+ });
108
+ return extractDir;
109
+ }
110
+ async function removeTempDirectory(directory) {
111
+ await promises$1.rm(directory, { recursive: true, force: true });
112
+ }
113
+ var DEFAULT_CONFIG = {
114
+ sessions: {}
115
+ };
116
+ function getCliHome() {
117
+ const configured = process.env.AMASTER_CLI_HOME?.trim();
118
+ if (configured) {
119
+ return configured;
120
+ }
121
+ return path.join(os.homedir(), ".amaster", "cli");
122
+ }
123
+ function getConfigFilePath() {
124
+ return path.join(getCliHome(), "config.json");
125
+ }
126
+ function ensureCliHome() {
127
+ if (!fs.existsSync(getCliHome())) {
128
+ fs.mkdirSync(getCliHome(), { recursive: true, mode: 448 });
129
+ }
130
+ }
131
+ function getCliConfig() {
132
+ const filePath = getConfigFilePath();
133
+ if (!fs.existsSync(filePath)) {
134
+ return { ...DEFAULT_CONFIG };
135
+ }
136
+ try {
137
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
138
+ return {
139
+ sessions: parsed.sessions ?? {}
140
+ };
141
+ } catch {
142
+ return { ...DEFAULT_CONFIG };
143
+ }
144
+ }
145
+ function saveCliConfig(config) {
146
+ ensureCliHome();
147
+ fs.writeFileSync(getConfigFilePath(), JSON.stringify(config, null, 2), { mode: 384 });
148
+ }
149
+ function getStoredSession(registry) {
150
+ return getCliConfig().sessions[registry] ?? null;
151
+ }
152
+ function saveStoredSession(session) {
153
+ const config = getCliConfig();
154
+ config.sessions[session.registry] = session;
155
+ saveCliConfig(config);
156
+ }
157
+ function clearStoredSession(registry) {
158
+ const config = getCliConfig();
159
+ if (config.sessions[registry]) {
160
+ delete config.sessions[registry];
161
+ saveCliConfig(config);
162
+ }
163
+ }
164
+
165
+ // src/marketplace/http.ts
166
+ var CliError = class extends Error {
167
+ constructor(message, statusCode, details) {
168
+ super(message);
169
+ this.name = "CliError";
170
+ this.statusCode = statusCode;
171
+ this.details = details;
172
+ }
173
+ };
174
+ function buildUrl(baseUrl, path) {
175
+ return new URL(path, `${baseUrl}/`).toString();
176
+ }
177
+ async function parseResponseBody(response) {
178
+ const contentType = response.headers.get("content-type") ?? "";
179
+ if (contentType.includes("application/json")) {
180
+ return await response.json();
181
+ }
182
+ const text = await response.text();
183
+ return text || null;
184
+ }
185
+ function extractErrorMessage(body, fallback) {
186
+ if (!body) {
187
+ return fallback;
188
+ }
189
+ if (typeof body === "string") {
190
+ return body;
191
+ }
192
+ if (typeof body === "object") {
193
+ const candidate = body;
194
+ const errorDescription = candidate.error_description;
195
+ if (typeof errorDescription === "string" && errorDescription) {
196
+ return errorDescription;
197
+ }
198
+ const message = candidate.message;
199
+ if (typeof message === "string" && message) {
200
+ return message;
201
+ }
202
+ const error = candidate.error;
203
+ if (typeof error === "string" && error) {
204
+ return error;
205
+ }
206
+ }
207
+ return fallback;
208
+ }
209
+ async function requestJson(baseUrl, path, options = {}) {
210
+ const { body, unwrapData = false, headers, ...init } = options;
211
+ const response = await fetch(buildUrl(baseUrl, path), {
212
+ ...init,
213
+ headers: {
214
+ Accept: "application/json",
215
+ ...body !== void 0 && !(body instanceof FormData) ? { "Content-Type": "application/json" } : {},
216
+ ...headers ?? {}
217
+ },
218
+ body: body === void 0 ? void 0 : body instanceof FormData ? body : JSON.stringify(body)
219
+ });
220
+ const parsedBody = await parseResponseBody(response);
221
+ if (!response.ok) {
222
+ throw new CliError(
223
+ extractErrorMessage(parsedBody, `${response.status} ${response.statusText}`),
224
+ response.status,
225
+ parsedBody
226
+ );
227
+ }
228
+ if (unwrapData && typeof parsedBody === "object" && parsedBody !== null && "data" in parsedBody) {
229
+ return parsedBody.data;
230
+ }
231
+ return parsedBody;
232
+ }
233
+ async function requestBuffer(baseUrl, path, options = {}) {
234
+ const response = await fetch(buildUrl(baseUrl, path), options);
235
+ if (!response.ok) {
236
+ const parsedBody = await parseResponseBody(response);
237
+ throw new CliError(
238
+ extractErrorMessage(parsedBody, `${response.status} ${response.statusText}`),
239
+ response.status,
240
+ parsedBody
241
+ );
242
+ }
243
+ return Buffer.from(await response.arrayBuffer());
244
+ }
245
+
246
+ // src/marketplace/auth.ts
247
+ var OAUTH_CLIENT_ID = "amaster-cli";
248
+ var OAUTH_REDIRECT_URI = "http://127.0.0.1:18147/oauth/callback";
249
+ var REFRESH_AHEAD_MS = 60 * 1e3;
250
+ var BROWSER_LOGIN_TIMEOUT_MS = 5 * 60 * 1e3;
251
+ function buildPkcePair() {
252
+ const codeVerifier = crypto.randomBytes(32).toString("base64url");
253
+ const codeChallenge = crypto.createHash("sha256").update(codeVerifier).digest("base64url");
254
+ return { codeVerifier, codeChallenge };
255
+ }
256
+ function buildExpiresAt(expiresIn) {
257
+ if (!expiresIn || expiresIn <= 0) {
258
+ return void 0;
259
+ }
260
+ return new Date(Date.now() + expiresIn * 1e3).toISOString();
261
+ }
262
+ function isSessionFreshEnough(session) {
263
+ if (!session.expiresAt) {
264
+ return true;
265
+ }
266
+ return new Date(session.expiresAt).getTime() - Date.now() > REFRESH_AHEAD_MS;
267
+ }
268
+ function buildAuthorizationUrl(input) {
269
+ const authorizeUrl = new URL("/api/oauth/authorize", `${input.registry}/`);
270
+ authorizeUrl.searchParams.set("response_type", "code");
271
+ authorizeUrl.searchParams.set("client_id", OAUTH_CLIENT_ID);
272
+ authorizeUrl.searchParams.set("redirect_uri", OAUTH_REDIRECT_URI);
273
+ authorizeUrl.searchParams.set("scope", "openid profile email");
274
+ authorizeUrl.searchParams.set("state", input.state);
275
+ authorizeUrl.searchParams.set("code_challenge", input.codeChallenge);
276
+ authorizeUrl.searchParams.set("code_challenge_method", "S256");
277
+ if (input.responseMode) {
278
+ authorizeUrl.searchParams.set("response_mode", input.responseMode);
279
+ }
280
+ return authorizeUrl;
281
+ }
282
+ async function resolveBrowserLoginUrl(authorizeUrl) {
283
+ const response = await fetch(authorizeUrl, {
284
+ method: "GET",
285
+ redirect: "manual"
286
+ });
287
+ if (response.status >= 300 && response.status < 400) {
288
+ const location = response.headers.get("location");
289
+ if (location) {
290
+ return new URL(location, authorizeUrl).toString();
291
+ }
292
+ }
293
+ if (response.ok) {
294
+ return authorizeUrl.toString();
295
+ }
296
+ throw new CliError(`Failed to start browser login: ${response.status} ${response.statusText}`, response.status);
297
+ }
298
+ async function fetchOAuthUserInfo(registry, accessToken) {
299
+ return await requestJson(registry, "/api/oauth/userinfo", {
300
+ method: "GET",
301
+ headers: {
302
+ Authorization: `Bearer ${accessToken}`
303
+ },
304
+ unwrapData: true
305
+ });
306
+ }
307
+ async function exchangeAuthorizationCodeForOAuthToken(input) {
308
+ return await requestJson(input.registry, "/api/oauth/token", {
309
+ method: "POST",
310
+ body: {
311
+ grant_type: "authorization_code",
312
+ client_id: OAUTH_CLIENT_ID,
313
+ code: input.code,
314
+ redirect_uri: OAUTH_REDIRECT_URI,
315
+ code_verifier: input.codeVerifier
316
+ },
317
+ unwrapData: true
318
+ });
319
+ }
320
+ async function exchangePasswordLoginForOAuthToken(registry, platformAccessToken) {
321
+ const { codeVerifier, codeChallenge } = buildPkcePair();
322
+ const state = crypto.randomBytes(16).toString("hex");
323
+ const authorizeUrl = buildAuthorizationUrl({
324
+ registry,
325
+ state,
326
+ codeChallenge,
327
+ responseMode: "json"
328
+ });
329
+ const authorizeResponse = await requestJson(
330
+ registry,
331
+ `${authorizeUrl.pathname}${authorizeUrl.search}`,
332
+ {
333
+ method: "GET",
334
+ headers: {
335
+ Authorization: `Bearer ${platformAccessToken}`
336
+ },
337
+ unwrapData: false
338
+ }
339
+ );
340
+ const redirectUrl = authorizeResponse.redirectUrl ? new URL(authorizeResponse.redirectUrl) : (() => {
341
+ throw new Error("OAuth authorize response missing redirectUrl");
342
+ })();
343
+ const code = redirectUrl.searchParams.get("code");
344
+ if (!code) {
345
+ throw new Error("OAuth authorize response missing code");
346
+ }
347
+ return await exchangeAuthorizationCodeForOAuthToken({
348
+ registry,
349
+ code,
350
+ codeVerifier
351
+ });
352
+ }
353
+ function openUrlInBrowser(url) {
354
+ const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
355
+ const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
356
+ return new Promise((resolve6, reject) => {
357
+ const child = child_process.spawn(command, args, {
358
+ detached: true,
359
+ stdio: "ignore"
360
+ });
361
+ child.once("error", reject);
362
+ child.once("spawn", () => {
363
+ child.unref();
364
+ resolve6();
365
+ });
366
+ });
367
+ }
368
+ function waitForBrowserAuthorizationCode(input) {
369
+ const redirectUrl = new URL(OAUTH_REDIRECT_URI);
370
+ const timeoutMs = input.timeoutMs ?? BROWSER_LOGIN_TIMEOUT_MS;
371
+ return new Promise((resolve6, reject) => {
372
+ let closed = false;
373
+ const sockets = /* @__PURE__ */ new Set();
374
+ const server = http.createServer((request, response) => {
375
+ const requestUrl = new URL(request.url ?? "/", OAUTH_REDIRECT_URI);
376
+ if (requestUrl.pathname !== redirectUrl.pathname) {
377
+ response.writeHead(404, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
378
+ response.end("Not found");
379
+ return;
380
+ }
381
+ const code = requestUrl.searchParams.get("code");
382
+ const state = requestUrl.searchParams.get("state");
383
+ const error = requestUrl.searchParams.get("error");
384
+ const errorDescription = requestUrl.searchParams.get("error_description");
385
+ if (error) {
386
+ response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
387
+ response.end(`AMaster CLI login failed: ${errorDescription || error}`);
388
+ cleanup();
389
+ reject(new Error(errorDescription || error));
390
+ return;
391
+ }
392
+ if (!code) {
393
+ response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
394
+ response.end("AMaster CLI login failed: missing authorization code");
395
+ cleanup();
396
+ reject(new Error("OAuth callback missing code"));
397
+ return;
398
+ }
399
+ if (state !== input.expectedState) {
400
+ response.writeHead(400, { "Content-Type": "text/plain; charset=utf-8", Connection: "close" });
401
+ response.end("AMaster CLI login failed: invalid state");
402
+ cleanup();
403
+ reject(new Error("OAuth callback state mismatch"));
404
+ return;
405
+ }
406
+ response.writeHead(200, { "Content-Type": "text/html; charset=utf-8", Connection: "close" });
407
+ response.end(
408
+ "<!doctype html><title>AMaster CLI</title><script>window.close();</script><p>Login completed. You can close this window.</p>"
409
+ );
410
+ cleanup();
411
+ resolve6(code);
412
+ });
413
+ const timer = setTimeout(() => {
414
+ cleanup();
415
+ reject(new Error("Browser login timed out"));
416
+ }, timeoutMs);
417
+ function cleanup() {
418
+ clearTimeout(timer);
419
+ if (!closed && server.listening) {
420
+ closed = true;
421
+ server.close();
422
+ }
423
+ for (const socket of sockets) {
424
+ socket.destroy();
425
+ }
426
+ sockets.clear();
427
+ }
428
+ server.on("connection", (socket) => {
429
+ sockets.add(socket);
430
+ socket.once("close", () => {
431
+ sockets.delete(socket);
432
+ });
433
+ });
434
+ server.once("error", (error) => {
435
+ cleanup();
436
+ reject(error);
437
+ });
438
+ server.listen(Number(redirectUrl.port), redirectUrl.hostname);
439
+ });
440
+ }
441
+ async function loginWithBrowser(options) {
442
+ const { codeVerifier, codeChallenge } = buildPkcePair();
443
+ const state = crypto.randomBytes(16).toString("hex");
444
+ const authorizeUrl = buildAuthorizationUrl({
445
+ registry: options.registry,
446
+ state,
447
+ codeChallenge
448
+ });
449
+ const codePromise = options.waitForCode ? options.waitForCode(state) : waitForBrowserAuthorizationCode({
450
+ expectedState: state,
451
+ timeoutMs: options.timeoutMs
452
+ });
453
+ const browserUrl = await (options.resolveLoginUrl ?? resolveBrowserLoginUrl)(authorizeUrl);
454
+ await (options.openUrl ?? openUrlInBrowser)(browserUrl);
455
+ const code = await codePromise;
456
+ const oauthToken = await exchangeAuthorizationCodeForOAuthToken({
457
+ registry: options.registry,
458
+ code,
459
+ codeVerifier
460
+ });
461
+ const user = await fetchOAuthUserInfo(options.registry, oauthToken.access_token);
462
+ const session = {
463
+ registry: options.registry,
464
+ accessToken: oauthToken.access_token,
465
+ refreshToken: oauthToken.refresh_token,
466
+ expiresAt: buildExpiresAt(oauthToken.expires_in),
467
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString(),
468
+ user
469
+ };
470
+ saveStoredSession(session);
471
+ return session;
472
+ }
473
+ async function loginWithPassword(options) {
474
+ const { registry, email, username, password } = options;
475
+ if (!email && !username) {
476
+ throw new Error("Either email or username is required");
477
+ }
478
+ const platformLogin = await requestJson(registry, "/api/auth/login", {
479
+ method: "POST",
480
+ body: {
481
+ ...email ? { email } : {},
482
+ ...username ? { username } : {},
483
+ password
484
+ },
485
+ unwrapData: true
486
+ });
487
+ if (!platformLogin.accessToken) {
488
+ throw new Error("Password login succeeded but no platform access token was returned");
489
+ }
490
+ const oauthToken = await exchangePasswordLoginForOAuthToken(registry, platformLogin.accessToken);
491
+ const user = await fetchOAuthUserInfo(registry, oauthToken.access_token);
492
+ const session = {
493
+ registry,
494
+ accessToken: oauthToken.access_token,
495
+ refreshToken: oauthToken.refresh_token,
496
+ expiresAt: buildExpiresAt(oauthToken.expires_in),
497
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString(),
498
+ user
499
+ };
500
+ saveStoredSession(session);
501
+ return session;
502
+ }
503
+ async function refreshStoredSession(session) {
504
+ if (!session.refreshToken) {
505
+ throw new Error(`Session for ${session.registry} has expired and cannot be refreshed`);
506
+ }
507
+ const refreshed = await requestJson(session.registry, "/api/oauth/token", {
508
+ method: "POST",
509
+ body: {
510
+ grant_type: "refresh_token",
511
+ client_id: OAUTH_CLIENT_ID,
512
+ refresh_token: session.refreshToken
513
+ },
514
+ unwrapData: true
515
+ });
516
+ const nextSession = {
517
+ ...session,
518
+ accessToken: refreshed.access_token,
519
+ refreshToken: refreshed.refresh_token ?? session.refreshToken,
520
+ expiresAt: buildExpiresAt(refreshed.expires_in),
521
+ obtainedAt: (/* @__PURE__ */ new Date()).toISOString()
522
+ };
523
+ try {
524
+ nextSession.user = await fetchOAuthUserInfo(session.registry, nextSession.accessToken);
525
+ } catch {
526
+ nextSession.user = session.user;
527
+ }
528
+ saveStoredSession(nextSession);
529
+ return nextSession;
530
+ }
531
+ async function getActiveSession(registry) {
532
+ const stored = getStoredSession(registry);
533
+ if (!stored) {
534
+ throw new Error(`Not logged in for registry ${registry}. Run: amaster-cli login --registry ${registry}`);
535
+ }
536
+ if (isSessionFreshEnough(stored)) {
537
+ return stored;
538
+ }
539
+ return await refreshStoredSession(stored);
540
+ }
541
+ async function withAccessToken(registry, runner) {
542
+ let session = await getActiveSession(registry);
543
+ try {
544
+ return await runner(session.accessToken);
545
+ } catch (error) {
546
+ if (session.refreshToken && error instanceof CliError && (error.statusCode === 401 || error.statusCode === 403)) {
547
+ session = await refreshStoredSession(session);
548
+ return await runner(session.accessToken);
549
+ }
550
+ throw error;
551
+ }
552
+ }
553
+ async function getCurrentUser(registry) {
554
+ return await withAccessToken(registry, async (accessToken) => {
555
+ return await fetchOAuthUserInfo(registry, accessToken);
556
+ });
557
+ }
558
+ function logout(registry) {
559
+ clearStoredSession(registry);
560
+ }
561
+ async function loadAddonManifestFromDirectory(directory) {
562
+ const manifestPath = path.join(directory, "addon.json");
563
+ const manifestText = await promises$1.readFile(manifestPath, "utf8");
564
+ const manifest = JSON.parse(manifestText);
565
+ validateAddonManifest(manifest);
566
+ return manifest;
567
+ }
568
+ function validateAddonManifest(manifest) {
569
+ if (!manifest || typeof manifest !== "object") {
570
+ throw new Error("addon.json is invalid");
571
+ }
572
+ if (!manifest.name || !manifest.version) {
573
+ throw new Error("addon.json missing name or version");
574
+ }
575
+ if (!manifest.display?.title || !manifest.display?.description) {
576
+ throw new Error("addon.json missing display.title or display.description");
577
+ }
578
+ if (!manifest.compatibility?.applicationTypes?.length || !manifest.compatibility?.phases?.length) {
579
+ throw new Error("addon.json missing compatibility.applicationTypes or compatibility.phases");
580
+ }
581
+ if (!Array.isArray(manifest.members)) {
582
+ throw new Error("addon.json missing members");
583
+ }
584
+ validateInstallRequirements(manifest);
585
+ }
586
+ function validateInstallRequirements(manifest) {
587
+ const requirements = manifest.install?.requirements;
588
+ if (!requirements) {
589
+ return;
590
+ }
591
+ if (requirements.envs !== void 0 && !Array.isArray(requirements.envs)) {
592
+ throw new Error("addon.json install.requirements.envs must be an array");
593
+ }
594
+ if (requirements.secrets !== void 0 && !Array.isArray(requirements.secrets)) {
595
+ throw new Error("addon.json install.requirements.secrets must be an array");
596
+ }
597
+ for (const item of requirements.envs ?? []) {
598
+ validateRequirementItem(item, "env");
599
+ }
600
+ for (const item of requirements.secrets ?? []) {
601
+ validateRequirementItem(item, "secret");
602
+ if (item.defaultValue !== void 0) {
603
+ throw new Error("addon.json install.requirements.secrets cannot declare defaultValue");
604
+ }
605
+ }
606
+ }
607
+ function validateRequirementItem(item, kind) {
608
+ if (!item || typeof item !== "object" || Array.isArray(item)) {
609
+ throw new Error(`addon.json install.requirements.${kind}s item is invalid`);
610
+ }
611
+ const requirement = item;
612
+ if (typeof requirement.key !== "string" || !requirement.key.trim()) {
613
+ throw new Error(`addon.json install.requirements.${kind}s item missing key`);
614
+ }
615
+ if (requirement.required !== void 0 && typeof requirement.required !== "boolean") {
616
+ throw new Error(`addon.json install.requirements.${kind}s item required must be boolean`);
617
+ }
618
+ if (requirement.description !== void 0 && typeof requirement.description !== "string") {
619
+ throw new Error(`addon.json install.requirements.${kind}s item description must be string`);
620
+ }
621
+ if (requirement.defaultValue !== void 0 && typeof requirement.defaultValue !== "string") {
622
+ throw new Error(`addon.json install.requirements.${kind}s item defaultValue must be string`);
623
+ }
624
+ }
625
+ function resolveMemberSourcePath(member) {
626
+ const sourcePath = member.source?.path;
627
+ if (typeof sourcePath === "string" && sourcePath.trim()) {
628
+ return normalizeRelativePath(sourcePath);
629
+ }
630
+ const fallbackKeys = ["entry", "path", "contentPath"];
631
+ for (const key of fallbackKeys) {
632
+ const value = member[key];
633
+ if (typeof value === "string" && value.trim()) {
634
+ return normalizeRelativePath(value);
635
+ }
636
+ }
637
+ return null;
638
+ }
639
+ function normalizeRelativePath(value) {
640
+ const normalized = value.replace(/^\.?\//, "").replace(/\\/g, "/");
641
+ if (!normalized || normalized.startsWith("../") || normalized.includes("/../")) {
642
+ throw new Error(`Invalid member source path: ${value}`);
643
+ }
644
+ return normalized;
645
+ }
646
+ async function assertPathExists(rootDir, relativePath) {
647
+ await promises$1.access(path.join(rootDir, relativePath), fs.constants.F_OK);
648
+ }
649
+ function resolveNearestPackageRoot(startDir = process.cwd()) {
650
+ let current = path.resolve(startDir);
651
+ const root = path.parse(current).root;
652
+ while (true) {
653
+ if (fs.existsSync(path.join(current, "package.json"))) {
654
+ return current;
655
+ }
656
+ if (current === root) {
657
+ throw new Error(`Unable to find package.json from ${path.resolve(startDir)}. Pass --target <path> explicitly.`);
658
+ }
659
+ current = path.dirname(current);
660
+ }
661
+ }
662
+ function tryResolveNearestPackageRoot(startDir = process.cwd()) {
663
+ try {
664
+ return resolveNearestPackageRoot(startDir);
665
+ } catch {
666
+ return null;
667
+ }
668
+ }
669
+ async function readAppSettingsApplicationType(packageRoot) {
670
+ const appSettingsPath = path.join(packageRoot, "app.settings.yml");
671
+ if (!fs.existsSync(appSettingsPath)) {
672
+ return null;
673
+ }
674
+ const parsed = YAML2__default.default.parse(await promises$1.readFile(appSettingsPath, "utf8"));
675
+ if (parsed?.type === "web" || parsed?.type === "mini") {
676
+ return parsed.type;
677
+ }
678
+ return null;
679
+ }
680
+ async function detectApplicationType(targetDir, explicitType) {
681
+ if (explicitType) {
682
+ return explicitType;
683
+ }
684
+ const applicationType = await readAppSettingsApplicationType(targetDir);
685
+ if (applicationType) {
686
+ return applicationType;
687
+ }
688
+ if (fs.existsSync(path.join(targetDir, "src", "app.config.ts"))) {
689
+ return "mini";
690
+ }
691
+ if (fs.existsSync(path.join(targetDir, "src", "routes.tsx"))) {
692
+ return "web";
693
+ }
694
+ throw new Error("Unable to detect application type. Pass --application-type web|mini.");
695
+ }
696
+ async function tryDetectNearestApplicationType(startDir = process.cwd()) {
697
+ const packageRoot = tryResolveNearestPackageRoot(startDir);
698
+ if (!packageRoot) {
699
+ return void 0;
700
+ }
701
+ try {
702
+ return await detectApplicationType(packageRoot);
703
+ } catch {
704
+ return void 0;
705
+ }
706
+ }
707
+
708
+ // src/marketplace/install.ts
709
+ var AddonInstallConflictError = class extends Error {
710
+ constructor(input) {
711
+ super(`Addon ${input.operation} has ${input.conflicts.length} conflict(s)`);
712
+ this.code = "ADDON_INSTALL_CONFLICT";
713
+ this.name = "AddonInstallConflictError";
714
+ this.operation = input.operation;
715
+ this.addon = input.addon;
716
+ this.targetDir = input.targetDir;
717
+ this.conflicts = input.conflicts;
718
+ }
719
+ toJSON() {
720
+ return {
721
+ success: false,
722
+ code: this.code,
723
+ message: this.message,
724
+ operation: this.operation,
725
+ addon: this.addon,
726
+ targetDir: this.targetDir,
727
+ conflicts: this.conflicts
728
+ };
729
+ }
730
+ };
731
+ function isAddonInstallConflictError(error) {
732
+ return error instanceof AddonInstallConflictError;
733
+ }
734
+ function sha256Buffer(buffer) {
735
+ return `sha256:${crypto.createHash("sha256").update(buffer).digest("hex")}`;
736
+ }
737
+ function stableJsonStringify(value) {
738
+ if (Array.isArray(value)) {
739
+ return `[${value.map((item) => stableJsonStringify(item)).join(",")}]`;
740
+ }
741
+ if (isPlainObject(value)) {
742
+ return `{${Object.keys(value).sort().map((key) => `${JSON.stringify(key)}:${stableJsonStringify(value[key])}`).join(",")}}`;
743
+ }
744
+ return JSON.stringify(value);
745
+ }
746
+ function sha256Value(value) {
747
+ return sha256Buffer(Buffer.from(stableJsonStringify(value) ?? "undefined"));
748
+ }
749
+ function ensurePathInsideTarget(targetDir, relativePath) {
750
+ const absolute = path.resolve(targetDir, relativePath);
751
+ const normalizedTarget = path.resolve(targetDir);
752
+ if (!absolute.startsWith(`${normalizedTarget}/`) && absolute !== normalizedTarget) {
753
+ throw new Error(`Refusing to write outside target directory: ${relativePath}`);
754
+ }
755
+ return absolute;
756
+ }
757
+ function removeFileExtension(input) {
758
+ const extension = path.extname(input);
759
+ return extension ? input.slice(0, -extension.length) : input;
760
+ }
761
+ function toPascalCase(input) {
762
+ return input.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((part) => part[0].toUpperCase() + part.slice(1)).join("");
763
+ }
764
+ function parseScalarValue(rawValue, expectedType, enumValues) {
765
+ const primaryType = Array.isArray(expectedType) ? expectedType[0] : expectedType;
766
+ if (enumValues?.length) {
767
+ if (!enumValues.includes(rawValue)) {
768
+ throw new Error(`Invalid value "${rawValue}". Expected one of: ${enumValues.join(", ")}`);
769
+ }
770
+ return rawValue;
771
+ }
772
+ switch (primaryType) {
773
+ case "boolean":
774
+ if (rawValue === "true") return true;
775
+ if (rawValue === "false") return false;
776
+ throw new Error(`Invalid boolean value: ${rawValue}`);
777
+ case "number": {
778
+ const value = Number(rawValue);
779
+ if (Number.isNaN(value)) {
780
+ throw new Error(`Invalid number value: ${rawValue}`);
781
+ }
782
+ return value;
783
+ }
784
+ case "integer": {
785
+ const value = Number.parseInt(rawValue, 10);
786
+ if (Number.isNaN(value)) {
787
+ throw new Error(`Invalid integer value: ${rawValue}`);
788
+ }
789
+ return value;
790
+ }
791
+ case "object":
792
+ case "array":
793
+ return JSON.parse(rawValue);
794
+ default:
795
+ return rawValue;
796
+ }
797
+ }
798
+ function resolveInstallParameters(manifest, rawParameters) {
799
+ const schema = manifest.install?.parameters?.schema;
800
+ if (!schema?.properties) {
801
+ if (rawParameters && Object.keys(rawParameters).length) {
802
+ throw new Error("This addon does not declare install parameters");
803
+ }
804
+ return {};
805
+ }
806
+ const resolved = {};
807
+ const properties = schema.properties;
808
+ const provided = rawParameters ?? {};
809
+ for (const key of Object.keys(provided)) {
810
+ if (!properties[key]) {
811
+ throw new Error(`Unknown install parameter: ${key}`);
812
+ }
813
+ }
814
+ for (const [key, property] of Object.entries(properties)) {
815
+ if (key in provided) {
816
+ resolved[key] = parseScalarValue(provided[key], property.type, property.enum);
817
+ continue;
818
+ }
819
+ if (property.default !== void 0) {
820
+ resolved[key] = property.default;
821
+ }
822
+ }
823
+ for (const requiredKey of schema.required ?? []) {
824
+ if (!(requiredKey in resolved)) {
825
+ throw new Error(`Missing required install parameter: ${requiredKey}`);
826
+ }
827
+ }
828
+ return resolved;
829
+ }
830
+ function resolveInstallRequirements(manifest) {
831
+ const requirements = manifest.install?.requirements ?? {};
832
+ return {
833
+ envs: requirements.envs?.map((item) => ({ ...item })),
834
+ secrets: requirements.secrets?.map((item) => ({ ...item }))
835
+ };
836
+ }
837
+ function buildMissingRequirements(requirements) {
838
+ return {
839
+ envs: requirements.envs?.filter((item) => item.required !== false).map((item) => ({ ...item })),
840
+ secrets: requirements.secrets?.filter((item) => item.required !== false).map((item) => ({ ...item }))
841
+ };
842
+ }
843
+ function getAddonMetaPath(targetDir, addonName) {
844
+ return path.join(targetDir, "src", "addons", addonName, "meta.json");
845
+ }
846
+ async function readInstalledAddonMeta(metaPath) {
847
+ if (!fs.existsSync(metaPath)) {
848
+ return null;
849
+ }
850
+ return JSON.parse(await promises$1.readFile(metaPath, "utf8"));
851
+ }
852
+ async function listAddonMetaPaths(targetDir) {
853
+ const addonsDir = path.join(targetDir, "src", "addons");
854
+ if (!fs.existsSync(addonsDir)) {
855
+ return [];
856
+ }
857
+ const entries = await promises$1.readdir(addonsDir, { withFileTypes: true });
858
+ const paths = [];
859
+ for (const entry of entries) {
860
+ if (!entry.isDirectory()) {
861
+ continue;
862
+ }
863
+ const metaPath = path.join(addonsDir, entry.name, "meta.json");
864
+ if (fs.existsSync(metaPath)) {
865
+ paths.push(metaPath);
866
+ }
867
+ }
868
+ return paths.sort();
869
+ }
870
+ async function listInstalledAddons(targetDir) {
871
+ const metaPaths = await listAddonMetaPaths(path.resolve(targetDir));
872
+ const metas = await Promise.all(metaPaths.map((metaPath) => readInstalledAddonMeta(metaPath)));
873
+ return metas.filter((meta) => Boolean(meta));
874
+ }
875
+ function buildOwnershipMap(metas, excludeAddonName) {
876
+ const ownership = /* @__PURE__ */ new Map();
877
+ for (const meta of metas) {
878
+ if (excludeAddonName && meta.name === excludeAddonName) {
879
+ continue;
880
+ }
881
+ for (const file of meta.files) {
882
+ ownership.set(file.path, meta.name);
883
+ }
884
+ }
885
+ return ownership;
886
+ }
887
+ async function collectDirectoryFiles(sourceDir) {
888
+ const entries = await promises$1.readdir(sourceDir, { withFileTypes: true });
889
+ const files = [];
890
+ for (const entry of entries) {
891
+ const absolute = path.join(sourceDir, entry.name);
892
+ if (entry.isDirectory()) {
893
+ files.push(...await collectDirectoryFiles(absolute));
894
+ continue;
895
+ }
896
+ files.push(absolute);
897
+ }
898
+ return files.sort();
899
+ }
900
+ async function planCopyMember(sourceRoot, sourceRelativePath, targetBaseRelativeDir, member) {
901
+ const sourceAbsolutePath = path.join(sourceRoot, sourceRelativePath);
902
+ const sourceStat = await promises$1.stat(sourceAbsolutePath);
903
+ const plannedFiles = [];
904
+ const targetPaths = [];
905
+ if (sourceStat.isDirectory()) {
906
+ const sourceFiles = await collectDirectoryFiles(sourceAbsolutePath);
907
+ for (const sourceFile of sourceFiles) {
908
+ const nestedRelativePath = path.relative(sourceAbsolutePath, sourceFile);
909
+ const targetPath = path.join(targetBaseRelativeDir, path.basename(sourceRelativePath), nestedRelativePath).replace(/\\/g, "/");
910
+ const sourcePackagePath = path.join(sourceRelativePath, nestedRelativePath).replace(/\\/g, "/");
911
+ plannedFiles.push({
912
+ sourcePath: sourceFile,
913
+ sourceRelativePath: sourcePackagePath,
914
+ targetPath,
915
+ memberName: member.name,
916
+ memberType: member.type
917
+ });
918
+ targetPaths.push(targetPath);
919
+ }
920
+ } else {
921
+ const targetPath = path.join(targetBaseRelativeDir, path.basename(sourceRelativePath)).replace(/\\/g, "/");
922
+ plannedFiles.push({
923
+ sourcePath: sourceAbsolutePath,
924
+ sourceRelativePath,
925
+ targetPath,
926
+ memberName: member.name,
927
+ memberType: member.type
928
+ });
929
+ targetPaths.push(targetPath);
930
+ }
931
+ return { files: plannedFiles, targetPaths };
932
+ }
933
+ async function buildInstallPlan(options) {
934
+ const targetDir = path.resolve(options.targetDir);
935
+ const manifest = await loadAddonManifestFromDirectory(options.extractedDir);
936
+ const applicationType = await detectApplicationType(targetDir, options.applicationType);
937
+ if (!manifest.compatibility.applicationTypes.includes(applicationType)) {
938
+ throw new Error(`Addon ${manifest.name}@${manifest.version} does not support application type ${applicationType}`);
939
+ }
940
+ if (!manifest.compatibility.phases.includes("design")) {
941
+ throw new Error(`Addon ${manifest.name}@${manifest.version} is not a design-time addon`);
942
+ }
943
+ const installParameters = resolveInstallParameters(manifest, options.installParameters);
944
+ const files = [];
945
+ const settings = [];
946
+ const members = [];
947
+ for (const member of manifest.members) {
948
+ if (member.type === "skill") {
949
+ throw new Error(`Member ${member.name} is a runtime skill. Design-time CLI install does not support skill members yet.`);
950
+ }
951
+ const sourceRelativePath = resolveMemberSourcePath(member);
952
+ if (!sourceRelativePath) {
953
+ throw new Error(`Member ${member.name} is missing source.path`);
954
+ }
955
+ await assertPathExists(options.extractedDir, sourceRelativePath);
956
+ if (member.type === "settings") {
957
+ const sourcePath = path.join(options.extractedDir, sourceRelativePath);
958
+ const patch = await readYamlObject(sourcePath);
959
+ settings.push({
960
+ sourcePath,
961
+ sourceRelativePath,
962
+ targetPath: "app.settings.yml",
963
+ memberName: member.name,
964
+ memberType: "settings",
965
+ patch,
966
+ paths: flattenSettingsPatch(patch)
967
+ });
968
+ members.push({
969
+ name: member.name,
970
+ type: member.type,
971
+ sourcePath: sourceRelativePath,
972
+ targetPaths: ["app.settings.yml"]
973
+ });
974
+ continue;
975
+ }
976
+ let targetBaseRelativeDir;
977
+ switch (member.type) {
978
+ case "component":
979
+ targetBaseRelativeDir = path.join("src", "components", manifest.name);
980
+ break;
981
+ case "page":
982
+ targetBaseRelativeDir = path.join("src", "pages");
983
+ break;
984
+ case "theme":
985
+ targetBaseRelativeDir = path.join("src", "assets", manifest.name);
986
+ break;
987
+ case "workflow":
988
+ targetBaseRelativeDir = path.join("src", "workflow");
989
+ break;
990
+ case "bpmn":
991
+ targetBaseRelativeDir = path.join("src", "bpmn");
992
+ break;
993
+ case "entity":
994
+ targetBaseRelativeDir = path.join("src", "db", "entity");
995
+ break;
996
+ case "datasource":
997
+ targetBaseRelativeDir = path.join("src", "db", "datasource");
998
+ break;
999
+ default:
1000
+ throw new Error(`Unsupported addon member type: ${member.type}`);
1001
+ }
1002
+ const planned = await planCopyMember(options.extractedDir, sourceRelativePath, targetBaseRelativeDir, member);
1003
+ files.push(...planned.files);
1004
+ const installedMember = {
1005
+ name: member.name,
1006
+ type: member.type,
1007
+ sourcePath: sourceRelativePath,
1008
+ targetPaths: planned.targetPaths
1009
+ };
1010
+ if (member.type === "page") {
1011
+ if (applicationType === "web") {
1012
+ const pageWeb = member.page?.web;
1013
+ if (!pageWeb?.route || !pageWeb.entry) {
1014
+ throw new Error(`Page member ${member.name} is missing page.web.route or page.web.entry`);
1015
+ }
1016
+ installedMember.page = {
1017
+ web: {
1018
+ route: pageWeb.route,
1019
+ entry: pageWeb.entry,
1020
+ title: pageWeb.title,
1021
+ visible: pageWeb.visible
1022
+ }
1023
+ };
1024
+ } else {
1025
+ const pageMini = member.page?.mini;
1026
+ if (!pageMini?.pagePath) {
1027
+ throw new Error(`Page member ${member.name} is missing page.mini.pagePath`);
1028
+ }
1029
+ installedMember.page = {
1030
+ mini: {
1031
+ pagePath: pageMini.pagePath,
1032
+ tabBar: pageMini.tabBar
1033
+ }
1034
+ };
1035
+ }
1036
+ }
1037
+ members.push(installedMember);
1038
+ }
1039
+ return {
1040
+ files,
1041
+ settings,
1042
+ members,
1043
+ metaPath: getAddonMetaPath(targetDir, manifest.name),
1044
+ applicationType,
1045
+ installParameters,
1046
+ manifest
1047
+ };
1048
+ }
1049
+ async function readFileMeta(targetDir, relativePath, memberName, memberType) {
1050
+ const absolutePath = ensurePathInsideTarget(targetDir, relativePath);
1051
+ const buffer = await promises$1.readFile(absolutePath);
1052
+ return {
1053
+ path: relativePath,
1054
+ sha256: sha256Buffer(buffer),
1055
+ size: buffer.length,
1056
+ memberName,
1057
+ memberType
1058
+ };
1059
+ }
1060
+ function buildInstalledAddonMeta(options) {
1061
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1062
+ const installedAt = options.installedAt ?? now;
1063
+ return {
1064
+ apiVersion: "addon.amaster.io/meta",
1065
+ name: options.manifest.name,
1066
+ version: options.manifest.version,
1067
+ registry: options.registry,
1068
+ applicationType: options.applicationType,
1069
+ organizationCode: options.organizationCode,
1070
+ installedAt,
1071
+ updatedAt: now,
1072
+ manifest: {
1073
+ title: options.manifest.display.title,
1074
+ description: options.manifest.display.description,
1075
+ category: options.manifest.display.category,
1076
+ applicationTypes: options.manifest.compatibility.applicationTypes,
1077
+ phases: options.manifest.compatibility.phases,
1078
+ memberTypes: [...new Set(options.manifest.members.map((member) => member.type))]
1079
+ },
1080
+ installParameters: options.installParameters,
1081
+ requirements: resolveInstallRequirements(options.manifest),
1082
+ members: options.members,
1083
+ files: options.files
1084
+ };
1085
+ }
1086
+ async function ensureParentDirectory(filePath) {
1087
+ await promises$1.mkdir(path.dirname(filePath), { recursive: true });
1088
+ }
1089
+ async function writePlannedFiles(targetDir, planFiles) {
1090
+ for (const file of planFiles) {
1091
+ const absoluteTargetPath = ensurePathInsideTarget(targetDir, file.targetPath);
1092
+ await ensureParentDirectory(absoluteTargetPath);
1093
+ await promises$1.copyFile(file.sourcePath, absoluteTargetPath);
1094
+ }
1095
+ }
1096
+ function isPlainObject(value) {
1097
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1098
+ }
1099
+ async function readYamlObject(filePath) {
1100
+ const parsed = YAML2__default.default.parse(await promises$1.readFile(filePath, "utf8"));
1101
+ if (parsed == null) {
1102
+ return {};
1103
+ }
1104
+ if (!isPlainObject(parsed)) {
1105
+ throw new Error(`${filePath} must contain a YAML object`);
1106
+ }
1107
+ return parsed;
1108
+ }
1109
+ function flattenSettingsPatch(value, prefix = []) {
1110
+ const paths = [];
1111
+ for (const [key, child] of Object.entries(value)) {
1112
+ const segments = prefix.concat(key);
1113
+ if (isPlainObject(child)) {
1114
+ paths.push(...flattenSettingsPatch(child, segments));
1115
+ continue;
1116
+ }
1117
+ paths.push({
1118
+ path: segments.join("."),
1119
+ segments,
1120
+ value: child
1121
+ });
1122
+ }
1123
+ return paths;
1124
+ }
1125
+ async function readYamlDocument(targetPath) {
1126
+ const text = fs.existsSync(targetPath) ? await promises$1.readFile(targetPath, "utf8") : "";
1127
+ return YAML2__default.default.parseDocument(text);
1128
+ }
1129
+ function buildSettingsOwnershipMap(metas, excludeAddonName) {
1130
+ const ownership = /* @__PURE__ */ new Map();
1131
+ for (const meta of metas) {
1132
+ if (excludeAddonName && meta.name === excludeAddonName) {
1133
+ continue;
1134
+ }
1135
+ for (const member of meta.members) {
1136
+ for (const item of member.settings?.paths ?? []) {
1137
+ ownership.set(`${item.targetPath}#${item.path}`, meta.name);
1138
+ }
1139
+ }
1140
+ }
1141
+ return ownership;
1142
+ }
1143
+ function listPlannedSettingPaths(settings) {
1144
+ return settings.flatMap(
1145
+ (item) => item.paths.map((settingPath) => ({
1146
+ memberName: item.memberName,
1147
+ sourceRelativePath: item.sourceRelativePath,
1148
+ targetPath: item.targetPath,
1149
+ path: settingPath.path,
1150
+ segments: settingPath.segments,
1151
+ value: settingPath.value
1152
+ }))
1153
+ );
1154
+ }
1155
+ function getPlainYamlValue(document, segments) {
1156
+ const value = document.getIn(segments);
1157
+ if (value && typeof value === "object" && "toJSON" in value && typeof value.toJSON === "function") {
1158
+ return value.toJSON();
1159
+ }
1160
+ return value;
1161
+ }
1162
+ function attachAppliedSettings(members, appliedSettings) {
1163
+ return members.map((member) => {
1164
+ const applied = appliedSettings.find((item) => item.memberName === member.name);
1165
+ if (!applied) {
1166
+ return member;
1167
+ }
1168
+ return {
1169
+ ...member,
1170
+ settings: {
1171
+ targetPath: applied.targetPath,
1172
+ paths: applied.paths
1173
+ }
1174
+ };
1175
+ });
1176
+ }
1177
+ async function applyPlannedSettings(targetDir, settings) {
1178
+ const written = /* @__PURE__ */ new Set();
1179
+ const appliedSettings = [];
1180
+ for (const item of settings) {
1181
+ const targetPath = ensurePathInsideTarget(targetDir, item.targetPath);
1182
+ const document = await readYamlDocument(targetPath);
1183
+ const pathMetas = [];
1184
+ for (const settingPath of item.paths) {
1185
+ const previousValueExists = document.hasIn(settingPath.segments);
1186
+ const previousValue = previousValueExists ? getPlainYamlValue(document, settingPath.segments) : void 0;
1187
+ document.setIn(settingPath.segments, settingPath.value);
1188
+ pathMetas.push({
1189
+ targetPath: item.targetPath,
1190
+ path: settingPath.path,
1191
+ sha256: sha256Value(settingPath.value),
1192
+ previousValueExists,
1193
+ previousValue
1194
+ });
1195
+ }
1196
+ await ensureParentDirectory(targetPath);
1197
+ await promises$1.writeFile(targetPath, document.toString());
1198
+ written.add(item.targetPath);
1199
+ appliedSettings.push({
1200
+ memberName: item.memberName,
1201
+ targetPath: item.targetPath,
1202
+ paths: pathMetas
1203
+ });
1204
+ }
1205
+ return {
1206
+ writtenFiles: [...written],
1207
+ appliedSettings
1208
+ };
1209
+ }
1210
+ async function restoreObsoleteSettings(targetDir, previousMeta, nextSettings) {
1211
+ if (!previousMeta) {
1212
+ return [];
1213
+ }
1214
+ const nextSettingKeys = new Set(
1215
+ listPlannedSettingPaths(nextSettings).map((item) => `${item.targetPath}#${item.path}`)
1216
+ );
1217
+ const documents = /* @__PURE__ */ new Map();
1218
+ const written = /* @__PURE__ */ new Set();
1219
+ const getDocument = async (targetPath) => {
1220
+ const cached = documents.get(targetPath);
1221
+ if (cached) {
1222
+ return cached;
1223
+ }
1224
+ const document = await readYamlDocument(ensurePathInsideTarget(targetDir, targetPath));
1225
+ documents.set(targetPath, document);
1226
+ return document;
1227
+ };
1228
+ for (const member of previousMeta.members) {
1229
+ for (const settingPath of member.settings?.paths ?? []) {
1230
+ if (nextSettingKeys.has(`${settingPath.targetPath}#${settingPath.path}`)) {
1231
+ continue;
1232
+ }
1233
+ const document = await getDocument(settingPath.targetPath);
1234
+ const segments = settingPath.path.split(".");
1235
+ if (settingPath.previousValueExists) {
1236
+ document.setIn(segments, settingPath.previousValue);
1237
+ } else {
1238
+ document.deleteIn(segments);
1239
+ }
1240
+ written.add(settingPath.targetPath);
1241
+ }
1242
+ }
1243
+ for (const targetPath of written) {
1244
+ const document = documents.get(targetPath);
1245
+ if (document) {
1246
+ await promises$1.writeFile(ensurePathInsideTarget(targetDir, targetPath), document.toString());
1247
+ }
1248
+ }
1249
+ return [...written];
1250
+ }
1251
+ async function removeObsoleteFiles(targetDir, previousMeta, nextPaths) {
1252
+ const removed = [];
1253
+ for (const file of previousMeta.files) {
1254
+ if (nextPaths.has(file.path)) {
1255
+ continue;
1256
+ }
1257
+ const absolutePath = ensurePathInsideTarget(targetDir, file.path);
1258
+ if (fs.existsSync(absolutePath)) {
1259
+ await promises$1.unlink(absolutePath);
1260
+ removed.push(file.path);
1261
+ }
1262
+ }
1263
+ return removed;
1264
+ }
1265
+ async function validateInstallConflicts(targetDir, plan, existingMetas) {
1266
+ const ownership = buildOwnershipMap(existingMetas);
1267
+ const settingsOwnership = buildSettingsOwnershipMap(existingMetas);
1268
+ const conflicts = [];
1269
+ for (const file of plan.files) {
1270
+ const owner = ownership.get(file.targetPath);
1271
+ if (owner && owner !== plan.manifest.name) {
1272
+ conflicts.push({
1273
+ kind: "owned_by_other_addon",
1274
+ path: file.targetPath,
1275
+ sourcePath: file.sourceRelativePath,
1276
+ memberName: file.memberName,
1277
+ memberType: file.memberType,
1278
+ ownerAddon: owner,
1279
+ message: `${file.targetPath} is already managed by addon ${owner}`
1280
+ });
1281
+ continue;
1282
+ }
1283
+ const absoluteTargetPath = ensurePathInsideTarget(targetDir, file.targetPath);
1284
+ if (fs.existsSync(absoluteTargetPath) && !owner) {
1285
+ conflicts.push({
1286
+ kind: "target_exists",
1287
+ path: file.targetPath,
1288
+ sourcePath: file.sourceRelativePath,
1289
+ memberName: file.memberName,
1290
+ memberType: file.memberType,
1291
+ message: `${file.targetPath} already exists in target application`
1292
+ });
1293
+ }
1294
+ }
1295
+ for (const item of listPlannedSettingPaths(plan.settings)) {
1296
+ const owner = settingsOwnership.get(`${item.targetPath}#${item.path}`);
1297
+ if (owner && owner !== plan.manifest.name) {
1298
+ conflicts.push({
1299
+ kind: "owned_by_other_addon",
1300
+ path: `${item.targetPath}#${item.path}`,
1301
+ sourcePath: item.sourceRelativePath,
1302
+ memberName: item.memberName,
1303
+ memberType: "settings",
1304
+ ownerAddon: owner,
1305
+ settingPath: item.path,
1306
+ nextValue: item.value,
1307
+ message: `${item.targetPath}#${item.path} is already managed by addon ${owner}`
1308
+ });
1309
+ }
1310
+ }
1311
+ if (conflicts.length) {
1312
+ throw new AddonInstallConflictError({
1313
+ operation: "install",
1314
+ addon: {
1315
+ name: plan.manifest.name,
1316
+ version: plan.manifest.version,
1317
+ applicationType: plan.applicationType
1318
+ },
1319
+ targetDir,
1320
+ conflicts
1321
+ });
1322
+ }
1323
+ }
1324
+ async function validateUpgradeConflicts(targetDir, plan, existingMetas, previousMeta) {
1325
+ const ownership = buildOwnershipMap(existingMetas, previousMeta.name);
1326
+ const settingsOwnership = buildSettingsOwnershipMap(existingMetas, previousMeta.name);
1327
+ const previousFilesByPath = new Map(previousMeta.files.map((file) => [file.path, file]));
1328
+ const nextPaths = new Set(plan.files.map((file) => file.targetPath));
1329
+ const plannedSettings = listPlannedSettingPaths(plan.settings);
1330
+ const nextSettingKeys = new Set(plannedSettings.map((item) => `${item.targetPath}#${item.path}`));
1331
+ const plannedSettingsByKey = new Map(plannedSettings.map((item) => [`${item.targetPath}#${item.path}`, item]));
1332
+ const conflicts = [];
1333
+ for (const managedFile of previousMeta.files) {
1334
+ const absolutePath = ensurePathInsideTarget(targetDir, managedFile.path);
1335
+ if (!fs.existsSync(absolutePath)) {
1336
+ conflicts.push({
1337
+ kind: "managed_file_missing",
1338
+ path: managedFile.path,
1339
+ memberName: managedFile.memberName,
1340
+ memberType: managedFile.memberType,
1341
+ expectedSha256: managedFile.sha256,
1342
+ message: `managed file missing: ${managedFile.path}`
1343
+ });
1344
+ continue;
1345
+ }
1346
+ const currentBuffer = await promises$1.readFile(absolutePath);
1347
+ const actualSha256 = sha256Buffer(currentBuffer);
1348
+ if (actualSha256 !== managedFile.sha256 && nextPaths.has(managedFile.path)) {
1349
+ conflicts.push({
1350
+ kind: "managed_file_modified",
1351
+ path: managedFile.path,
1352
+ memberName: managedFile.memberName,
1353
+ memberType: managedFile.memberType,
1354
+ expectedSha256: managedFile.sha256,
1355
+ actualSha256,
1356
+ message: `managed file modified locally: ${managedFile.path}`
1357
+ });
1358
+ }
1359
+ }
1360
+ for (const file of plan.files) {
1361
+ const owner = ownership.get(file.targetPath);
1362
+ if (owner) {
1363
+ conflicts.push({
1364
+ kind: "owned_by_other_addon",
1365
+ path: file.targetPath,
1366
+ sourcePath: file.sourceRelativePath,
1367
+ memberName: file.memberName,
1368
+ memberType: file.memberType,
1369
+ ownerAddon: owner,
1370
+ message: `${file.targetPath} is already managed by addon ${owner}`
1371
+ });
1372
+ continue;
1373
+ }
1374
+ const absoluteTargetPath = ensurePathInsideTarget(targetDir, file.targetPath);
1375
+ if (fs.existsSync(absoluteTargetPath) && !previousFilesByPath.has(file.targetPath)) {
1376
+ conflicts.push({
1377
+ kind: "target_exists",
1378
+ path: file.targetPath,
1379
+ sourcePath: file.sourceRelativePath,
1380
+ memberName: file.memberName,
1381
+ memberType: file.memberType,
1382
+ message: `${file.targetPath} already exists in target application`
1383
+ });
1384
+ }
1385
+ }
1386
+ const settingsDocuments = /* @__PURE__ */ new Map();
1387
+ const getSettingsDocument = async (targetPath) => {
1388
+ const cached = settingsDocuments.get(targetPath);
1389
+ if (cached) {
1390
+ return cached;
1391
+ }
1392
+ const document = await readYamlDocument(ensurePathInsideTarget(targetDir, targetPath));
1393
+ settingsDocuments.set(targetPath, document);
1394
+ return document;
1395
+ };
1396
+ for (const member of previousMeta.members) {
1397
+ for (const settingPath of member.settings?.paths ?? []) {
1398
+ const document = await getSettingsDocument(settingPath.targetPath);
1399
+ const segments = settingPath.path.split(".");
1400
+ const currentValue = document.hasIn(segments) ? getPlainYamlValue(document, segments) : void 0;
1401
+ const actualSha256 = sha256Value(currentValue);
1402
+ if (actualSha256 === settingPath.sha256) {
1403
+ continue;
1404
+ }
1405
+ const settingKey = `${settingPath.targetPath}#${settingPath.path}`;
1406
+ const isStillManaged = nextSettingKeys.has(settingKey);
1407
+ const nextSetting = plannedSettingsByKey.get(settingKey);
1408
+ conflicts.push({
1409
+ kind: isStillManaged ? "managed_file_modified" : "obsolete_file_modified",
1410
+ path: settingKey,
1411
+ sourcePath: member.sourcePath,
1412
+ memberName: member.name,
1413
+ memberType: "settings",
1414
+ expectedSha256: settingPath.sha256,
1415
+ actualSha256,
1416
+ settingPath: settingPath.path,
1417
+ currentValue,
1418
+ nextValue: nextSetting?.value,
1419
+ previousValue: settingPath.previousValue,
1420
+ message: isStillManaged ? `managed setting modified locally: ${settingKey}` : `setting changed locally and would be restored: ${settingKey}`
1421
+ });
1422
+ }
1423
+ }
1424
+ for (const item of plannedSettings) {
1425
+ const owner = settingsOwnership.get(`${item.targetPath}#${item.path}`);
1426
+ if (owner) {
1427
+ conflicts.push({
1428
+ kind: "owned_by_other_addon",
1429
+ path: `${item.targetPath}#${item.path}`,
1430
+ sourcePath: item.sourceRelativePath,
1431
+ memberName: item.memberName,
1432
+ memberType: "settings",
1433
+ ownerAddon: owner,
1434
+ settingPath: item.path,
1435
+ nextValue: item.value,
1436
+ message: `${item.targetPath}#${item.path} is already managed by addon ${owner}`
1437
+ });
1438
+ }
1439
+ }
1440
+ for (const oldFile of previousMeta.files) {
1441
+ if (!nextPaths.has(oldFile.path)) {
1442
+ const absolutePath = ensurePathInsideTarget(targetDir, oldFile.path);
1443
+ if (!fs.existsSync(absolutePath)) {
1444
+ continue;
1445
+ }
1446
+ const currentBuffer = await promises$1.readFile(absolutePath);
1447
+ const actualSha256 = sha256Buffer(currentBuffer);
1448
+ if (actualSha256 !== oldFile.sha256) {
1449
+ conflicts.push({
1450
+ kind: "obsolete_file_modified",
1451
+ path: oldFile.path,
1452
+ memberName: oldFile.memberName,
1453
+ memberType: oldFile.memberType,
1454
+ expectedSha256: oldFile.sha256,
1455
+ actualSha256,
1456
+ message: `file changed locally and would be removed: ${oldFile.path}`
1457
+ });
1458
+ }
1459
+ }
1460
+ }
1461
+ if (conflicts.length) {
1462
+ throw new AddonInstallConflictError({
1463
+ operation: "upgrade",
1464
+ addon: {
1465
+ name: plan.manifest.name,
1466
+ version: plan.manifest.version,
1467
+ applicationType: plan.applicationType
1468
+ },
1469
+ targetDir,
1470
+ conflicts
1471
+ });
1472
+ }
1473
+ }
1474
+ async function ensureWebRoutesPatched(targetDir) {
1475
+ const routesFile = path.join(targetDir, "src", "routes.tsx");
1476
+ const original = await promises$1.readFile(routesFile, "utf8");
1477
+ let next = original;
1478
+ if (!next.includes("./amaster/registry/addon-routes.generated")) {
1479
+ next = next.replace(
1480
+ 'import type { ComponentType } from "react";',
1481
+ 'import type { ComponentType } from "react";\nimport { addonRoutes } from "./amaster/registry/addon-routes.generated";'
1482
+ );
1483
+ }
1484
+ if (!next.includes("...addonRoutes")) {
1485
+ const routeArrayPattern = /const routes:\s*RouteConfig\[\]\s*=\s*\[([\s\S]*?)\];/;
1486
+ const match = next.match(routeArrayPattern);
1487
+ if (!match) {
1488
+ throw new Error("Unable to patch src/routes.tsx for addon route registration");
1489
+ }
1490
+ const inner = match[1]?.trim() ?? "";
1491
+ const replacement = inner ? `const routes: RouteConfig[] = [
1492
+ ...addonRoutes,
1493
+ ${match[1]}
1494
+ ];` : "const routes: RouteConfig[] = [\n ...addonRoutes,\n];";
1495
+ next = next.replace(routeArrayPattern, replacement);
1496
+ }
1497
+ if (next !== original) {
1498
+ await promises$1.writeFile(routesFile, next);
1499
+ }
1500
+ }
1501
+ async function ensureMiniAppConfigPatched(targetDir, needsTabBarItems) {
1502
+ const configFile = path.join(targetDir, "src", "app.config.ts");
1503
+ const original = await promises$1.readFile(configFile, "utf8");
1504
+ let next = original;
1505
+ if (!next.includes("./amaster/registry/addon-pages.generated")) {
1506
+ next = `import { addonPages, addonTabBarItems } from "./amaster/registry/addon-pages.generated";
1507
+ ${next}`;
1508
+ }
1509
+ if (!next.includes("...addonPages")) {
1510
+ next = next.replace(/const pages\s*=\s*\[([\s\S]*?)\]/, (_full, inner) => {
1511
+ const trimmed = inner.trim();
1512
+ if (!trimmed) {
1513
+ return "const pages = [...addonPages]";
1514
+ }
1515
+ return `const pages = [${inner}, ...addonPages]`;
1516
+ });
1517
+ }
1518
+ if (needsTabBarItems && !next.includes("...addonTabBarItems")) {
1519
+ const listPattern = /list:\s*\[([\s\S]*?)\]/;
1520
+ const match = next.match(listPattern);
1521
+ if (!match) {
1522
+ throw new Error("Unable to patch src/app.config.ts for addon tabBar registration");
1523
+ }
1524
+ next = next.replace(listPattern, (_full, inner) => `list: [${inner}, ...addonTabBarItems]`);
1525
+ }
1526
+ if (next !== original) {
1527
+ await promises$1.writeFile(configFile, next);
1528
+ }
1529
+ }
1530
+ async function rebuildRegistryFiles(targetDir, applicationType, metas) {
1531
+ const registryDir = path.join(targetDir, "src", "amaster", "registry");
1532
+ await promises$1.mkdir(registryDir, { recursive: true });
1533
+ if (applicationType === "web") {
1534
+ const pageMembers2 = metas.flatMap(
1535
+ (meta) => meta.members.filter((member) => member.type === "page" && member.page?.web).map((member) => ({ addonName: meta.name, member }))
1536
+ ).sort((left, right) => `${left.addonName}:${left.member.name}`.localeCompare(`${right.addonName}:${right.member.name}`));
1537
+ const imports = pageMembers2.map(({ addonName, member }) => {
1538
+ const identifier = toPascalCase(`${addonName}-${member.name}-page`);
1539
+ const entry = member.page.web.entry;
1540
+ return {
1541
+ identifier,
1542
+ importPath: `../../${removeFileExtension(entry).replace(/\\/g, "/")}`,
1543
+ route: member.page.web.route,
1544
+ visible: member.page.web.visible,
1545
+ name: member.name
1546
+ };
1547
+ });
1548
+ const fileContent2 = [
1549
+ 'import type { ComponentType } from "react";',
1550
+ ...imports.map((item) => `import ${item.identifier} from "${item.importPath}";`),
1551
+ "",
1552
+ "type AddonRouteConfig = {",
1553
+ " name: string;",
1554
+ " path: string;",
1555
+ " Component: ComponentType<Record<string, unknown>>;",
1556
+ " visible?: boolean;",
1557
+ "};",
1558
+ "",
1559
+ "export const addonRoutes: AddonRouteConfig[] = [",
1560
+ ...imports.map(
1561
+ (item) => ` { name: ${JSON.stringify(item.name)}, path: ${JSON.stringify(item.route)}, Component: ${item.identifier},${item.visible === void 0 ? "" : ` visible: ${item.visible},`} },`
1562
+ ),
1563
+ "];",
1564
+ ""
1565
+ ].join("\n");
1566
+ await promises$1.writeFile(path.join(registryDir, "addon-routes.generated.ts"), fileContent2);
1567
+ await ensureWebRoutesPatched(targetDir);
1568
+ return;
1569
+ }
1570
+ const pageMembers = metas.flatMap(
1571
+ (meta) => meta.members.filter((member) => member.type === "page" && member.page?.mini).map((member) => member.page.mini)
1572
+ ).sort((left, right) => left.pagePath.localeCompare(right.pagePath));
1573
+ const addonPages = pageMembers.map((page) => page.pagePath);
1574
+ const addonTabBarItems = pageMembers.filter((page) => page.tabBar).map((page) => ({
1575
+ pagePath: page.pagePath,
1576
+ ...page.tabBar
1577
+ }));
1578
+ const fileContent = [
1579
+ `export const addonPages = ${JSON.stringify(addonPages, null, 2)};`,
1580
+ "",
1581
+ `export const addonTabBarItems = ${JSON.stringify(addonTabBarItems, null, 2)};`,
1582
+ ""
1583
+ ].join("\n");
1584
+ await promises$1.writeFile(path.join(registryDir, "addon-pages.generated.ts"), fileContent);
1585
+ await ensureMiniAppConfigPatched(targetDir, addonTabBarItems.length > 0);
1586
+ }
1587
+ async function materializeAddon(options) {
1588
+ const targetDir = path.resolve(options.targetDir);
1589
+ const existingMetas = await listInstalledAddons(targetDir);
1590
+ const plan = await buildInstallPlan(options);
1591
+ const previousMeta = existingMetas.find((meta2) => meta2.name === plan.manifest.name) ?? null;
1592
+ if (options.mode === "install" && previousMeta) {
1593
+ throw new Error(`Addon ${plan.manifest.name} is already installed. Use addon upgrade instead.`);
1594
+ }
1595
+ if (options.mode === "upgrade" && !previousMeta) {
1596
+ throw new Error(`Addon ${plan.manifest.name} is not installed yet. Use addon install instead.`);
1597
+ }
1598
+ if (previousMeta && previousMeta.applicationType !== plan.applicationType) {
1599
+ throw new Error(`Installed addon ${plan.manifest.name} uses application type ${previousMeta.applicationType}, not ${plan.applicationType}`);
1600
+ }
1601
+ if (options.mode === "install") {
1602
+ await validateInstallConflicts(targetDir, plan, existingMetas);
1603
+ } else if (previousMeta) {
1604
+ await validateUpgradeConflicts(targetDir, plan, existingMetas, previousMeta);
1605
+ }
1606
+ const removedFiles = previousMeta ? await removeObsoleteFiles(targetDir, previousMeta, new Set(plan.files.map((file) => file.targetPath))) : [];
1607
+ const restoredSettingsFiles = await restoreObsoleteSettings(targetDir, previousMeta, plan.settings);
1608
+ await writePlannedFiles(targetDir, plan.files);
1609
+ const settingsResult = await applyPlannedSettings(targetDir, plan.settings);
1610
+ const installedFiles = [];
1611
+ for (const plannedFile of plan.files) {
1612
+ installedFiles.push(
1613
+ await readFileMeta(targetDir, plannedFile.targetPath, plannedFile.memberName, plannedFile.memberType)
1614
+ );
1615
+ }
1616
+ const meta = buildInstalledAddonMeta({
1617
+ registry: options.registry,
1618
+ manifest: plan.manifest,
1619
+ applicationType: plan.applicationType,
1620
+ organizationCode: options.organizationCode,
1621
+ installParameters: plan.installParameters,
1622
+ members: attachAppliedSettings(plan.members, settingsResult.appliedSettings),
1623
+ files: installedFiles,
1624
+ installedAt: previousMeta?.installedAt
1625
+ });
1626
+ await ensureParentDirectory(plan.metaPath);
1627
+ await promises$1.writeFile(plan.metaPath, JSON.stringify(meta, null, 2));
1628
+ const nextMetas = existingMetas.filter((item) => item.name !== meta.name).concat(meta);
1629
+ await rebuildRegistryFiles(targetDir, plan.applicationType, nextMetas.filter((item) => item.applicationType === plan.applicationType));
1630
+ const requirements = resolveInstallRequirements(plan.manifest);
1631
+ return {
1632
+ meta,
1633
+ writtenFiles: installedFiles.map((file) => file.path).concat(restoredSettingsFiles, settingsResult.writtenFiles),
1634
+ removedFiles,
1635
+ requirements,
1636
+ missingRequirements: buildMissingRequirements(requirements)
1637
+ };
1638
+ }
1639
+ async function installAddonFromExtractedDirectory(options) {
1640
+ return await materializeAddon({
1641
+ ...options,
1642
+ mode: "install"
1643
+ });
1644
+ }
1645
+ async function upgradeAddonFromExtractedDirectory(options) {
1646
+ return await materializeAddon({
1647
+ ...options,
1648
+ mode: "upgrade"
1649
+ });
1650
+ }
1651
+
1652
+ // src/marketplace/addons.ts
1653
+ function createOrganizationHeaders(organizationCode) {
1654
+ if (!organizationCode) {
1655
+ return void 0;
1656
+ }
1657
+ return {
1658
+ "x-organization-code": organizationCode
1659
+ };
1660
+ }
1661
+ function parseAddonSpecifier(specifier) {
1662
+ const trimmed = specifier.trim();
1663
+ if (!trimmed) {
1664
+ throw new Error("Addon specifier cannot be empty");
1665
+ }
1666
+ const atIndex = trimmed.lastIndexOf("@");
1667
+ if (atIndex <= 0) {
1668
+ return { name: trimmed };
1669
+ }
1670
+ const name = trimmed.slice(0, atIndex);
1671
+ const version = trimmed.slice(atIndex + 1);
1672
+ if (!version) {
1673
+ return { name };
1674
+ }
1675
+ return { name, version };
1676
+ }
1677
+ async function searchAddons(registry, options) {
1678
+ const query = new URLSearchParams();
1679
+ if (options.query) query.set("query", options.query);
1680
+ if (options.applicationType) query.set("applicationType", options.applicationType);
1681
+ if (options.phase) query.set("phase", options.phase);
1682
+ if (options.memberType) query.set("memberType", options.memberType);
1683
+ if (options.scope) query.set("scope", options.scope);
1684
+ if (options.page) query.set("page", String(options.page));
1685
+ if (options.pageSize) query.set("pageSize", String(options.pageSize));
1686
+ return await requestJson(registry, `/api/addons?${query.toString()}`, {
1687
+ method: "GET",
1688
+ headers: createOrganizationHeaders(options.organizationCode),
1689
+ unwrapData: true
1690
+ });
1691
+ }
1692
+ async function getAddon(registry, name, organizationCode) {
1693
+ return await requestJson(registry, `/api/addons/${encodeURIComponent(name)}`, {
1694
+ method: "GET",
1695
+ headers: createOrganizationHeaders(organizationCode),
1696
+ unwrapData: true
1697
+ });
1698
+ }
1699
+ async function listAddonVersions(registry, name, organizationCode) {
1700
+ return await requestJson(registry, `/api/addons/${encodeURIComponent(name)}/versions`, {
1701
+ method: "GET",
1702
+ headers: createOrganizationHeaders(organizationCode),
1703
+ unwrapData: true
1704
+ });
1705
+ }
1706
+ async function getAddonVersion(registry, name, version, organizationCode) {
1707
+ return await requestJson(
1708
+ registry,
1709
+ `/api/addons/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}`,
1710
+ {
1711
+ method: "GET",
1712
+ headers: createOrganizationHeaders(organizationCode),
1713
+ unwrapData: true
1714
+ }
1715
+ );
1716
+ }
1717
+ async function listAddonMembers(registry, name, version, options = {}) {
1718
+ const query = new URLSearchParams();
1719
+ if (options.type) query.set("type", options.type);
1720
+ if (options.memberName) query.set("name", options.memberName);
1721
+ const suffix = query.toString() ? `?${query.toString()}` : "";
1722
+ return await requestJson(
1723
+ registry,
1724
+ `/api/addons/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}/members${suffix}`,
1725
+ {
1726
+ method: "GET",
1727
+ headers: createOrganizationHeaders(options.organizationCode),
1728
+ unwrapData: true
1729
+ }
1730
+ );
1731
+ }
1732
+ async function getAddonMemberContent(registry, name, version, memberName, organizationCode) {
1733
+ return await requestJson(
1734
+ registry,
1735
+ `/api/addons/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}/members/${encodeURIComponent(memberName)}/content`,
1736
+ {
1737
+ method: "GET",
1738
+ headers: createOrganizationHeaders(organizationCode),
1739
+ unwrapData: true
1740
+ }
1741
+ );
1742
+ }
1743
+ async function getAddonPackageUrl(registry, name, version, organizationCode) {
1744
+ return await requestJson(
1745
+ registry,
1746
+ `/api/addons/${encodeURIComponent(name)}/versions/${encodeURIComponent(version)}/package-url`,
1747
+ {
1748
+ method: "POST",
1749
+ headers: createOrganizationHeaders(organizationCode),
1750
+ unwrapData: true
1751
+ }
1752
+ );
1753
+ }
1754
+ async function downloadAddonArchiveBuffer(registry, name, version, organizationCode) {
1755
+ const packageUrl = await getAddonPackageUrl(registry, name, version, organizationCode);
1756
+ return await requestBuffer(registry, packageUrl.url, {
1757
+ method: "GET",
1758
+ headers: createOrganizationHeaders(organizationCode)
1759
+ });
1760
+ }
1761
+ async function publishAddon(options) {
1762
+ const sourcePath = path.resolve(options.sourcePath ?? process.cwd());
1763
+ const isArchive = sourcePath.endsWith(".tgz") || sourcePath.endsWith(".tar.gz");
1764
+ let archiveBuffer;
1765
+ let archiveName;
1766
+ let manifestDir = null;
1767
+ let tempArchiveDir = null;
1768
+ try {
1769
+ if (isArchive) {
1770
+ archiveBuffer = await promises$1.readFile(sourcePath);
1771
+ archiveName = path.basename(sourcePath);
1772
+ manifestDir = await extractAddonArchiveFile(sourcePath);
1773
+ } else {
1774
+ const packaged = await packageAddonDirectory(sourcePath);
1775
+ archiveBuffer = packaged.buffer;
1776
+ archiveName = path.basename(packaged.archivePath);
1777
+ manifestDir = sourcePath;
1778
+ tempArchiveDir = path.dirname(packaged.archivePath);
1779
+ }
1780
+ const manifest = await loadAddonManifestFromDirectory(manifestDir);
1781
+ const digest = sha256(archiveBuffer);
1782
+ return await withAccessToken(options.registry, async (accessToken) => {
1783
+ const headers = {
1784
+ Authorization: `Bearer ${accessToken}`,
1785
+ ...options.organizationCode ? { "x-organization-code": options.organizationCode } : {}
1786
+ };
1787
+ const session = await requestJson(options.registry, "/api/addons/publish-sessions", {
1788
+ method: "POST",
1789
+ headers,
1790
+ body: {
1791
+ name: manifest.name,
1792
+ version: manifest.version,
1793
+ fileName: archiveName,
1794
+ contentLength: archiveBuffer.length,
1795
+ digest
1796
+ },
1797
+ unwrapData: true
1798
+ });
1799
+ const formData = new FormData();
1800
+ formData.set("file", new Blob([archiveBuffer], { type: "application/gzip" }), archiveName);
1801
+ await requestJson(
1802
+ options.registry,
1803
+ `/api/addons/publish-sessions/${encodeURIComponent(session.sessionId)}/file`,
1804
+ {
1805
+ method: "POST",
1806
+ headers,
1807
+ body: formData,
1808
+ unwrapData: true
1809
+ }
1810
+ );
1811
+ return await requestJson(
1812
+ options.registry,
1813
+ `/api/addons/${encodeURIComponent(manifest.name)}/versions`,
1814
+ {
1815
+ method: "POST",
1816
+ headers,
1817
+ body: {
1818
+ sessionId: session.sessionId,
1819
+ ...options.scope ? { scope: options.scope } : {}
1820
+ },
1821
+ unwrapData: true
1822
+ }
1823
+ );
1824
+ });
1825
+ } finally {
1826
+ if (tempArchiveDir) {
1827
+ await removeTempDirectory(tempArchiveDir).catch(() => void 0);
1828
+ }
1829
+ if (isArchive && manifestDir) {
1830
+ await removeTempDirectory(manifestDir).catch(() => void 0);
1831
+ }
1832
+ }
1833
+ }
1834
+ async function updateAddonStatus(options) {
1835
+ return await withAccessToken(options.registry, async (accessToken) => {
1836
+ return await requestJson(
1837
+ options.registry,
1838
+ `/api/addons/${encodeURIComponent(options.name)}/status`,
1839
+ {
1840
+ method: "PATCH",
1841
+ headers: {
1842
+ Authorization: `Bearer ${accessToken}`,
1843
+ ...options.organizationCode ? { "x-organization-code": options.organizationCode } : {}
1844
+ },
1845
+ body: {
1846
+ status: options.status
1847
+ },
1848
+ unwrapData: true
1849
+ }
1850
+ );
1851
+ });
1852
+ }
1853
+ async function deleteAddon(options) {
1854
+ return await withAccessToken(options.registry, async (accessToken) => {
1855
+ return await requestJson(
1856
+ options.registry,
1857
+ `/api/addons/${encodeURIComponent(options.name)}`,
1858
+ {
1859
+ method: "DELETE",
1860
+ headers: {
1861
+ Authorization: `Bearer ${accessToken}`,
1862
+ ...options.organizationCode ? { "x-organization-code": options.organizationCode } : {}
1863
+ },
1864
+ unwrapData: true
1865
+ }
1866
+ );
1867
+ });
1868
+ }
1869
+ async function resolveInstallVersion(registry, name, requestedVersion, organizationCode) {
1870
+ if (requestedVersion) {
1871
+ return requestedVersion;
1872
+ }
1873
+ const detail = await getAddon(registry, name, organizationCode);
1874
+ const version = detail.latestVersion?.version;
1875
+ if (!version) {
1876
+ throw new Error(`Addon ${name} has no published version`);
1877
+ }
1878
+ return version;
1879
+ }
1880
+ async function installAddonFromRegistry(options) {
1881
+ const { name, version: requestedVersion } = parseAddonSpecifier(options.specifier);
1882
+ const version = await resolveInstallVersion(options.registry, name, requestedVersion, options.organizationCode);
1883
+ const archiveBuffer = await downloadAddonArchiveBuffer(options.registry, name, version, options.organizationCode);
1884
+ const extractedDir = await extractAddonArchiveBuffer(archiveBuffer);
1885
+ try {
1886
+ return await installAddonFromExtractedDirectory({
1887
+ registry: options.registry,
1888
+ targetDir: options.targetDir,
1889
+ extractedDir,
1890
+ applicationType: options.applicationType,
1891
+ organizationCode: options.organizationCode,
1892
+ installParameters: options.installParameters
1893
+ });
1894
+ } finally {
1895
+ await removeTempDirectory(extractedDir).catch(() => void 0);
1896
+ }
1897
+ }
1898
+ async function upgradeAddonFromRegistry(options) {
1899
+ const { name, version: requestedVersion } = parseAddonSpecifier(options.specifier);
1900
+ const version = await resolveInstallVersion(options.registry, name, requestedVersion, options.organizationCode);
1901
+ const archiveBuffer = await downloadAddonArchiveBuffer(options.registry, name, version, options.organizationCode);
1902
+ const extractedDir = await extractAddonArchiveBuffer(archiveBuffer);
1903
+ try {
1904
+ return await upgradeAddonFromExtractedDirectory({
1905
+ registry: options.registry,
1906
+ targetDir: options.targetDir,
1907
+ extractedDir,
1908
+ applicationType: options.applicationType,
1909
+ organizationCode: options.organizationCode,
1910
+ installParameters: options.installParameters
1911
+ });
1912
+ } finally {
1913
+ await removeTempDirectory(extractedDir).catch(() => void 0);
1914
+ }
1915
+ }
13
1916
 
1917
+ // src/marketplace/registry.ts
1918
+ var REGISTRY_ALIASES = {
1919
+ helige: "https://www.helige.cn",
1920
+ "helige-int": "https://www.helige-int.cn"
1921
+ };
1922
+ var DEFAULT_REGISTRY_ALIAS = "helige";
1923
+ var DEFAULT_REGISTRY_ENV = "AMASTER_CLI_REGISTRY";
1924
+ function normalizeRegistryUrl(input) {
1925
+ const trimmed = input.trim();
1926
+ if (!trimmed) {
1927
+ throw new Error("Registry cannot be empty");
1928
+ }
1929
+ const aliased = REGISTRY_ALIASES[trimmed] ?? trimmed;
1930
+ const hasProtocol = /^[a-z][a-z0-9+.-]*:\/\//i.test(aliased);
1931
+ const inferredProtocol = inferRegistryProtocol(aliased);
1932
+ const withProtocol = hasProtocol ? aliased : inferredProtocol ? `${inferredProtocol}://${aliased}` : "";
1933
+ if (!withProtocol) {
1934
+ const known = Object.keys(REGISTRY_ALIASES).join(", ");
1935
+ throw new Error(`Unsupported registry: ${trimmed}. Use one of: ${known}, or provide a full URL.`);
1936
+ }
1937
+ let url;
1938
+ try {
1939
+ url = new URL(withProtocol);
1940
+ } catch {
1941
+ throw new Error(`Invalid registry URL: ${trimmed}`);
1942
+ }
1943
+ if (url.protocol === "https:" && (url.hostname === "helige.cn" || url.hostname === "helige-int.cn")) {
1944
+ url.hostname = `www.${url.hostname}`;
1945
+ }
1946
+ url.pathname = url.pathname.replace(/\/+$/, "");
1947
+ url.search = "";
1948
+ url.hash = "";
1949
+ return url.toString().replace(/\/$/, "");
1950
+ }
1951
+ function inferRegistryProtocol(input) {
1952
+ const hostname = input.split("/")[0]?.toLowerCase() ?? "";
1953
+ if (hostname === "localhost" || hostname.startsWith("localhost:") || hostname === "127.0.0.1" || hostname.startsWith("127.0.0.1:") || hostname === "::1" || hostname.endsWith(".local")) {
1954
+ return "http";
1955
+ }
1956
+ if (!input.includes(".")) {
1957
+ return "";
1958
+ }
1959
+ return "https";
1960
+ }
1961
+ function resolveRegistry(input) {
1962
+ if (input) {
1963
+ return normalizeRegistryUrl(input);
1964
+ }
1965
+ const envRegistry = process.env[DEFAULT_REGISTRY_ENV];
1966
+ if (envRegistry?.trim()) {
1967
+ return normalizeRegistryUrl(envRegistry);
1968
+ }
1969
+ return normalizeRegistryUrl(DEFAULT_REGISTRY_ALIAS);
1970
+ }
14
1971
  var DEFAULT_ROUTES_FILE = "src/routes.tsx";
15
1972
  var REACT_VITE_DEV_TIMEOUT = 15e3;
16
1973
  var REACT_VITE_BUILD_TIMEOUT = 3e4;
@@ -245,7 +2202,7 @@ async function runAstCheck(options) {
245
2202
  if (options.stack !== "react-vite") {
246
2203
  throw new Error(`AST check is not supported for stack: ${options.stack}`);
247
2204
  }
248
- const { parse, Lang } = await import('@ast-grep/napi');
2205
+ const { parse: parse2, Lang } = await import('@ast-grep/napi');
249
2206
  const RED = "\x1B[31m";
250
2207
  const YELLOW = "\x1B[33m";
251
2208
  const GREEN = "\x1B[32m";
@@ -263,8 +2220,8 @@ async function runAstCheck(options) {
263
2220
  }
264
2221
  const full = path.join(dir, entry);
265
2222
  try {
266
- const stat = fs.statSync(full);
267
- if (stat.isDirectory()) {
2223
+ const stat3 = fs.statSync(full);
2224
+ if (stat3.isDirectory()) {
268
2225
  files2.push(...findFiles(full, extensions));
269
2226
  } else if (extensions.includes(path.extname(full))) {
270
2227
  files2.push(full);
@@ -518,7 +2475,7 @@ async function runAstCheck(options) {
518
2475
  for (const file of files) {
519
2476
  try {
520
2477
  const code = fs.readFileSync(file, "utf8");
521
- const ast = parse(Lang.Tsx, code);
2478
+ const ast = parse2(Lang.Tsx, code);
522
2479
  const root = ast.root();
523
2480
  const issues = [
524
2481
  ...checkSelectItemEmptyValue(root),
@@ -843,7 +2800,7 @@ function printBuildError(result) {
843
2800
  }
844
2801
  function runReactViteDevCheck(cwd) {
845
2802
  return new Promise((resolvePromise) => {
846
- let stdout = "";
2803
+ let stdout2 = "";
847
2804
  let stderr = "";
848
2805
  let lastOut = Date.now();
849
2806
  let interval = null;
@@ -856,8 +2813,8 @@ function runReactViteDevCheck(cwd) {
856
2813
  });
857
2814
  vite.stdout.on("data", (chunk) => {
858
2815
  const text = chunk.toString();
859
- if (stdout.length < REACT_VITE_MAX_OUTPUT) {
860
- stdout += text;
2816
+ if (stdout2.length < REACT_VITE_MAX_OUTPUT) {
2817
+ stdout2 += text;
861
2818
  }
862
2819
  lastOut = Date.now();
863
2820
  if (!scanning && (text.includes("VITE") || text.includes("vite") || /ready in \d+/i.test(text) || /Local:.*http/i.test(text))) {
@@ -899,13 +2856,13 @@ function runReactViteDevCheck(cwd) {
899
2856
  if (interval) {
900
2857
  clearInterval(interval);
901
2858
  }
902
- const output = stdout + stderr;
2859
+ const output = stdout2 + stderr;
903
2860
  const hasError = containsBuildError(stderr) || code !== 0 && code !== null && !timeoutReached;
904
2861
  if (timeoutReached) {
905
2862
  resolvePromise({ success: false, reason: "timeout", output });
906
2863
  } else if (hasError) {
907
2864
  resolvePromise({ success: false, reason: "error", output, stderr });
908
- } else if (scanning || /VITE|vite|ready|Local:/i.test(stdout)) {
2865
+ } else if (scanning || /VITE|vite|ready|Local:/i.test(stdout2)) {
909
2866
  resolvePromise({ success: true, output });
910
2867
  } else {
911
2868
  resolvePromise({ success: false, reason: "unknown", output });
@@ -922,7 +2879,7 @@ function runReactViteDevCheck(cwd) {
922
2879
  }
923
2880
  function runReactViteBuildCheckProcess(cwd) {
924
2881
  return new Promise((resolvePromise) => {
925
- let stdout = "";
2882
+ let stdout2 = "";
926
2883
  let stderr = "";
927
2884
  let timeoutReached = false;
928
2885
  const vite = child_process.spawn(
@@ -935,8 +2892,8 @@ function runReactViteBuildCheckProcess(cwd) {
935
2892
  }
936
2893
  );
937
2894
  vite.stdout.on("data", (chunk) => {
938
- if (stdout.length < REACT_VITE_MAX_OUTPUT) {
939
- stdout += chunk.toString();
2895
+ if (stdout2.length < REACT_VITE_MAX_OUTPUT) {
2896
+ stdout2 += chunk.toString();
940
2897
  }
941
2898
  });
942
2899
  vite.stderr.on("data", (chunk) => {
@@ -956,7 +2913,7 @@ function runReactViteBuildCheckProcess(cwd) {
956
2913
  }, REACT_VITE_BUILD_TIMEOUT);
957
2914
  vite.on("close", (code) => {
958
2915
  clearTimeout(timeout);
959
- const output = stdout + stderr;
2916
+ const output = stdout2 + stderr;
960
2917
  const hasStderrError = containsBuildError(stderr);
961
2918
  if (timeoutReached) {
962
2919
  resolvePromise({ success: false, reason: "timeout", output, stderr, code: null });
@@ -1011,7 +2968,7 @@ function runTaroBuildCheck(cwd) {
1011
2968
  console.log("Note: Taro build only checks files that are actually imported/referenced.\n");
1012
2969
  console.log("Running: taro build --type h5\n");
1013
2970
  return new Promise((resolvePromise, rejectPromise) => {
1014
- let stdout = "";
2971
+ let stdout2 = "";
1015
2972
  let stderr = "";
1016
2973
  let timeoutReached = false;
1017
2974
  const taro = child_process.spawn("npx", ["taro", "build", "--type", "h5"], {
@@ -1021,8 +2978,8 @@ function runTaroBuildCheck(cwd) {
1021
2978
  });
1022
2979
  taro.stdout.on("data", (chunk) => {
1023
2980
  const text = chunk.toString();
1024
- if (stdout.length < TARO_MAX_OUTPUT) {
1025
- stdout += text;
2981
+ if (stdout2.length < TARO_MAX_OUTPUT) {
2982
+ stdout2 += text;
1026
2983
  }
1027
2984
  process.stdout.write(text);
1028
2985
  });
@@ -1045,9 +3002,9 @@ function runTaroBuildCheck(cwd) {
1045
3002
  }, TARO_BUILD_TIMEOUT);
1046
3003
  taro.on("close", (code) => {
1047
3004
  clearTimeout(timeout);
1048
- const output = stdout + stderr;
3005
+ const output = stdout2 + stderr;
1049
3006
  const hasStderrError = containsBuildError(stderr);
1050
- const hasStdoutError = containsBuildError(stdout);
3007
+ const hasStdoutError = containsBuildError(stdout2);
1051
3008
  if (!timeoutReached && code === 0 && !hasStderrError && !hasStdoutError) {
1052
3009
  console.log("\n\u2705 No build errors detected\n");
1053
3010
  resolvePromise();
@@ -1191,91 +3148,342 @@ async function runPreCommitCheck(options) {
1191
3148
  }
1192
3149
 
1193
3150
  // src/cli.ts
1194
- function printUsage() {
1195
- console.error("Usage:");
1196
- console.error(" amaster-cli check route [--cwd <path>] [--routes-file <path>]");
1197
- console.error(" amaster-cli check ast --stack react-vite [--cwd <path>]");
1198
- console.error(" amaster-cli check type --stack <react-vite|taro> [--cwd <path>]");
1199
- console.error(" amaster-cli check build --stack <react-vite|taro> [--cwd <path>]");
1200
- console.error(" amaster-cli check all --stack <react-vite|taro> [--cwd <path>]");
1201
- }
1202
- function parseArgs(argv) {
1203
- const args = [...argv];
1204
- let cwd;
1205
- let routesFile;
1206
- let stack;
1207
- while (args.length > 0) {
1208
- const arg = args.shift();
1209
- if (arg === "--cwd") {
1210
- cwd = args.shift();
1211
- continue;
3151
+ function resolveCliVersion() {
3152
+ try {
3153
+ const packageJsonUrl = new URL("../package.json", (typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('cli.cjs', document.baseURI).href)));
3154
+ return JSON.parse(fs.readFileSync(packageJsonUrl, "utf-8")).version || "0.0.0";
3155
+ } catch {
3156
+ return "0.0.0";
3157
+ }
3158
+ }
3159
+ function renderOutput(data, options = {}) {
3160
+ if (options.json || typeof data === "string") {
3161
+ if (typeof data === "string") {
3162
+ console.log(data);
3163
+ return;
1212
3164
  }
1213
- if (arg === "--routes-file") {
1214
- routesFile = args.shift();
1215
- continue;
3165
+ console.log(JSON.stringify(data, null, 2));
3166
+ return;
3167
+ }
3168
+ console.dir(data, { depth: null, colors: true });
3169
+ }
3170
+ function shouldRenderJsonError(argv) {
3171
+ return argv.includes("--json");
3172
+ }
3173
+ function renderError(error, options = {}) {
3174
+ if (isAddonInstallConflictError(error)) {
3175
+ if (options.json) {
3176
+ console.log(JSON.stringify(error.toJSON(), null, 2));
3177
+ return;
1216
3178
  }
1217
- if (arg === "--stack") {
1218
- const value = args.shift();
1219
- if (value !== "react-vite" && value !== "taro") {
1220
- throw new Error(`Unsupported stack: ${value}`);
1221
- }
1222
- stack = value;
1223
- continue;
3179
+ console.error(`${error.message}:`);
3180
+ for (const conflict of error.conflicts) {
3181
+ const owner = conflict.ownerAddon ? ` owner=${conflict.ownerAddon}` : "";
3182
+ const member = conflict.memberName ? ` member=${conflict.memberName}` : "";
3183
+ console.error(`- [${conflict.kind}] ${conflict.path}${member}${owner}`);
1224
3184
  }
1225
- throw new Error(`Unknown argument: ${arg}`);
3185
+ console.error("Run again with --json for MCP/AI-readable conflict details.");
3186
+ return;
3187
+ }
3188
+ const message = error instanceof Error ? error.message : String(error);
3189
+ if (options.json) {
3190
+ console.log(JSON.stringify({ success: false, code: "CLI_ERROR", message }, null, 2));
3191
+ return;
1226
3192
  }
1227
- return { cwd, routesFile, stack };
3193
+ console.error(message);
1228
3194
  }
1229
- async function main() {
1230
- const [command, target, ...rest] = process.argv.slice(2);
3195
+ async function promptForMissingCredentials(input) {
3196
+ if ((input.email || input.username) && input.password) {
3197
+ return {
3198
+ email: input.email,
3199
+ username: input.username,
3200
+ password: input.password
3201
+ };
3202
+ }
3203
+ if (!process$1.stdin.isTTY || !process$1.stdout.isTTY) {
3204
+ throw new Error("Missing login credentials. Provide --email/--username and --password in non-interactive mode.");
3205
+ }
3206
+ const rl = promises.createInterface({ input: process$1.stdin, output: process$1.stdout });
1231
3207
  try {
1232
- if (command !== "check") {
1233
- printUsage();
1234
- process.exit(1);
1235
- }
1236
- const options = parseArgs(rest);
1237
- if (target === "route") {
1238
- checkRouteConfig(options);
1239
- console.log("\u2705 Home route found in the default-exported routes config");
1240
- return;
1241
- }
1242
- if (target === "all") {
1243
- if (!options.stack) {
1244
- throw new Error("Missing required argument: --stack <react-vite|taro>");
3208
+ let email = input.email;
3209
+ let username = input.username;
3210
+ if (!email && !username) {
3211
+ const login = (await rl.question("Email or username: ")).trim();
3212
+ if (login.includes("@")) {
3213
+ email = login;
3214
+ } else {
3215
+ username = login;
1245
3216
  }
1246
- await runPreCommitCheck({ cwd: options.cwd, stack: options.stack });
1247
- return;
1248
3217
  }
1249
- if (target === "type") {
1250
- if (!options.stack) {
1251
- throw new Error("Missing required argument: --stack <react-vite|taro>");
1252
- }
1253
- await runTypeCheck({ cwd: options.cwd, stack: options.stack });
1254
- return;
3218
+ const password = input.password ?? await rl.question("Password: ");
3219
+ if (!password) {
3220
+ throw new Error("Password is required");
1255
3221
  }
1256
- if (target === "ast") {
1257
- if (!options.stack) {
1258
- throw new Error("Missing required argument: --stack <react-vite|taro>");
1259
- }
1260
- runAstCheck({ cwd: options.cwd, stack: options.stack });
1261
- return;
3222
+ return { email, username, password };
3223
+ } finally {
3224
+ rl.close();
3225
+ }
3226
+ }
3227
+ function parseKeyValuePairs(values) {
3228
+ if (!values?.length) {
3229
+ return void 0;
3230
+ }
3231
+ const result = {};
3232
+ for (const value of values) {
3233
+ const separatorIndex = value.indexOf("=");
3234
+ if (separatorIndex <= 0) {
3235
+ throw new Error(`Invalid --set value: ${value}. Expected key=value.`);
1262
3236
  }
1263
- if (target === "build") {
1264
- if (!options.stack) {
1265
- throw new Error("Missing required argument: --stack <react-vite|taro>");
1266
- }
1267
- await runBuildCheck({ cwd: options.cwd, stack: options.stack });
1268
- return;
3237
+ const key = value.slice(0, separatorIndex).trim();
3238
+ const parsedValue = value.slice(separatorIndex + 1).trim();
3239
+ if (!key) {
3240
+ throw new Error(`Invalid --set value: ${value}. Key cannot be empty.`);
1269
3241
  }
1270
- printUsage();
1271
- process.exit(1);
1272
- } catch (error) {
1273
- console.error("\u274C Check failed.\n");
1274
- const message = error instanceof Error ? error.message : String(error);
1275
- console.error(message);
1276
- process.exit(1);
3242
+ result[key] = parsedValue;
3243
+ }
3244
+ return result;
3245
+ }
3246
+ function addRegistryOption(command) {
3247
+ return command.option("--registry <registry>", "Registry alias or URL, default: helige");
3248
+ }
3249
+ function addOrganizationOption(command) {
3250
+ return command.option("--organization-code <code>", "Organization code");
3251
+ }
3252
+ function addJsonOption(command) {
3253
+ return command.option("--json", "Output JSON");
3254
+ }
3255
+ function resolveRegistryFromOptions(options) {
3256
+ return resolveRegistry(options.registry);
3257
+ }
3258
+ function getUserStringField(user, key) {
3259
+ const value = user?.[key];
3260
+ return typeof value === "string" && value ? value : void 0;
3261
+ }
3262
+ function formatLoginIdentity(user) {
3263
+ return getUserStringField(user, "email") ?? getUserStringField(user, "username") ?? getUserStringField(user, "preferred_username") ?? getUserStringField(user, "name") ?? getUserStringField(user, "sub") ?? "unknown user";
3264
+ }
3265
+ function resolveAddonTargetDir(target) {
3266
+ return target ? target : resolveNearestPackageRoot();
3267
+ }
3268
+ function requireStack(value) {
3269
+ if (value === "react-vite" || value === "taro") {
3270
+ return value;
1277
3271
  }
3272
+ throw new Error("Missing required argument: --stack <react-vite|taro>");
1278
3273
  }
1279
- main();
3274
+ var program = new commander.Command();
3275
+ program.name("amaster-cli").description("AMaster CLI").version(resolveCliVersion()).showHelpAfterError();
3276
+ addJsonOption(addRegistryOption(program.command("login").description("Login to an AMaster registry"))).option("--browser", "Login with browser OAuth flow").option("-e, --email <email>", "Email").option("-u, --username <username>", "Username").option("-p, --password <password>", "Password").action(async (options) => {
3277
+ const registry = resolveRegistryFromOptions(options);
3278
+ const session = options.browser ? await loginWithBrowser({ registry }) : await (async () => {
3279
+ const credentials = await promptForMissingCredentials({
3280
+ email: options.email,
3281
+ username: options.username,
3282
+ password: options.password
3283
+ });
3284
+ return await loginWithPassword({
3285
+ registry,
3286
+ email: credentials.email,
3287
+ username: credentials.username,
3288
+ password: credentials.password
3289
+ });
3290
+ })();
3291
+ const result = {
3292
+ registry,
3293
+ user: session.user ?? null,
3294
+ expiresAt: session.expiresAt ?? null
3295
+ };
3296
+ renderOutput(options.json ? result : `Login succeeded: ${formatLoginIdentity(session.user)} (${registry})`, options);
3297
+ });
3298
+ addJsonOption(addRegistryOption(program.command("logout").description("Clear the local AMaster registry session"))).action(
3299
+ async (options) => {
3300
+ const registry = resolveRegistryFromOptions(options);
3301
+ logout(registry);
3302
+ renderOutput(
3303
+ {
3304
+ registry,
3305
+ loggedOut: true
3306
+ },
3307
+ options
3308
+ );
3309
+ }
3310
+ );
3311
+ addJsonOption(addRegistryOption(program.command("whoami").description("Show the current AMaster registry session"))).action(
3312
+ async (options) => {
3313
+ const registry = resolveRegistryFromOptions(options);
3314
+ const user = await getCurrentUser(registry);
3315
+ renderOutput(
3316
+ {
3317
+ registry,
3318
+ user
3319
+ },
3320
+ options
3321
+ );
3322
+ }
3323
+ );
3324
+ var addon = program.command("addon").description("Addon marketplace commands");
3325
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("search [query]").description("Search addons")))).option("--application-type <type>", "Application type").option("--phase <phase>", "Phase filter").option("--member-type <type>", "Member type filter").option("--scope <scope>", "Scope filter").option("--page <page>", "Page number", (value) => Number.parseInt(value, 10)).option("--page-size <pageSize>", "Page size", (value) => Number.parseInt(value, 10)).action(async (query, options) => {
3326
+ const registry = resolveRegistryFromOptions(options);
3327
+ const applicationType = options.applicationType ?? await tryDetectNearestApplicationType();
3328
+ const result = await searchAddons(registry, {
3329
+ query,
3330
+ applicationType,
3331
+ phase: options.phase,
3332
+ memberType: options.memberType,
3333
+ scope: options.scope,
3334
+ page: options.page,
3335
+ pageSize: options.pageSize,
3336
+ organizationCode: options.organizationCode
3337
+ });
3338
+ renderOutput(result, options);
3339
+ });
3340
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("view <specifier>").description("View addon or addon version details")))).action(async (specifier, options) => {
3341
+ const registry = resolveRegistryFromOptions(options);
3342
+ const { name, version } = parseAddonSpecifier(specifier);
3343
+ const result = version ? await getAddonVersion(registry, name, version, options.organizationCode) : await getAddon(registry, name, options.organizationCode);
3344
+ renderOutput(result, options);
3345
+ });
3346
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("versions <name>").description("List addon versions")))).action(
3347
+ async (name, options) => {
3348
+ const registry = resolveRegistryFromOptions(options);
3349
+ const result = await listAddonVersions(registry, name, options.organizationCode);
3350
+ renderOutput(result, options);
3351
+ }
3352
+ );
3353
+ addJsonOption(
3354
+ addOrganizationOption(addRegistryOption(addon.command("members <specifier>").description("List addon members")))
3355
+ ).option("--type <type>", "Member type filter").option("--name <memberName>", "Member name filter").action(async (specifier, options) => {
3356
+ const registry = resolveRegistryFromOptions(options);
3357
+ const { name, version } = parseAddonSpecifier(specifier);
3358
+ if (!version) {
3359
+ throw new Error("Member queries require an explicit version, e.g. addon members crm-pages@1.0.0");
3360
+ }
3361
+ const result = await listAddonMembers(registry, name, version, {
3362
+ type: options.type,
3363
+ memberName: options.name,
3364
+ organizationCode: options.organizationCode
3365
+ });
3366
+ renderOutput(result, options);
3367
+ });
3368
+ addJsonOption(
3369
+ addOrganizationOption(
3370
+ addRegistryOption(addon.command("content <specifier> <memberName>").description("Read addon member content"))
3371
+ )
3372
+ ).action(async (specifier, memberName, options) => {
3373
+ const registry = resolveRegistryFromOptions(options);
3374
+ const { name, version } = parseAddonSpecifier(specifier);
3375
+ if (!version) {
3376
+ throw new Error("Member content queries require an explicit version, e.g. addon content crm-pages@1.0.0 lead-summary");
3377
+ }
3378
+ const result = await getAddonMemberContent(registry, name, version, memberName, options.organizationCode);
3379
+ renderOutput(options.json ? result : result.content, options);
3380
+ });
3381
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("publish [sourcePath]").description("Publish an addon directory or .tgz archive")))).addOption(new commander.Option("--scope <scope>", "Publish scope").choices(["official", "organization"])).action(async (sourcePath, options) => {
3382
+ const registry = resolveRegistryFromOptions(options);
3383
+ const result = await publishAddon({
3384
+ registry,
3385
+ sourcePath,
3386
+ scope: options.scope,
3387
+ organizationCode: options.organizationCode
3388
+ });
3389
+ renderOutput(result, options);
3390
+ });
3391
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("activate <name>").description("Activate an addon")))).action(async (name, options) => {
3392
+ const registry = resolveRegistryFromOptions(options);
3393
+ const result = await updateAddonStatus({
3394
+ registry,
3395
+ name,
3396
+ status: "active",
3397
+ organizationCode: options.organizationCode
3398
+ });
3399
+ renderOutput(options.json ? result : `Addon activated: ${result.name}`, options);
3400
+ });
3401
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("deactivate <name>").description("Deactivate an addon")))).action(async (name, options) => {
3402
+ const registry = resolveRegistryFromOptions(options);
3403
+ const result = await updateAddonStatus({
3404
+ registry,
3405
+ name,
3406
+ status: "inactive",
3407
+ organizationCode: options.organizationCode
3408
+ });
3409
+ renderOutput(options.json ? result : `Addon deactivated: ${result.name}`, options);
3410
+ });
3411
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("delete <name>").description("Delete an addon")))).action(async (name, options) => {
3412
+ const registry = resolveRegistryFromOptions(options);
3413
+ const result = await deleteAddon({
3414
+ registry,
3415
+ name,
3416
+ organizationCode: options.organizationCode
3417
+ });
3418
+ renderOutput(options.json ? result : `Addon deleted: ${result.name}`, options);
3419
+ });
3420
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("install <specifier>").description("Install an addon into an application")))).option("--target <path>", "Application root directory, defaults to nearest package.json directory").addOption(new commander.Option("--application-type <type>", "Application type").choices(["web", "mini"])).option("--set <key=value>", "Install parameter", (value, previous = []) => previous.concat(value), []).action(async (specifier, options) => {
3421
+ const registry = resolveRegistryFromOptions(options);
3422
+ const result = await installAddonFromRegistry({
3423
+ registry,
3424
+ specifier,
3425
+ targetDir: resolveAddonTargetDir(options.target),
3426
+ applicationType: options.applicationType,
3427
+ organizationCode: options.organizationCode,
3428
+ installParameters: parseKeyValuePairs(options.set)
3429
+ });
3430
+ renderOutput(result, options);
3431
+ });
3432
+ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("upgrade <specifier>").description("Upgrade an installed addon")))).option("--target <path>", "Application root directory, defaults to nearest package.json directory").addOption(new commander.Option("--application-type <type>", "Application type").choices(["web", "mini"])).option("--set <key=value>", "Install parameter", (value, previous = []) => previous.concat(value), []).action(async (specifier, options) => {
3433
+ const registry = resolveRegistryFromOptions(options);
3434
+ const result = await upgradeAddonFromRegistry({
3435
+ registry,
3436
+ specifier,
3437
+ targetDir: resolveAddonTargetDir(options.target),
3438
+ applicationType: options.applicationType,
3439
+ organizationCode: options.organizationCode,
3440
+ installParameters: parseKeyValuePairs(options.set)
3441
+ });
3442
+ renderOutput(result, options);
3443
+ });
3444
+ addJsonOption(addon.command("list").description("List installed addons in an application")).option("--target <path>", "Application root directory, defaults to nearest package.json directory").action(async (options) => {
3445
+ const installed = await listInstalledAddons(resolveAddonTargetDir(options.target));
3446
+ renderOutput(installed, options);
3447
+ });
3448
+ var check = program.command("check").description("Template guard checks");
3449
+ check.command("route").option("--cwd <path>", "Working directory").option("--routes-file <path>", "Routes file path").action((options) => {
3450
+ checkRouteConfig({
3451
+ cwd: options.cwd,
3452
+ routesFile: options.routesFile
3453
+ });
3454
+ console.log("OK");
3455
+ });
3456
+ check.command("ast").requiredOption("--stack <stack>", "Stack: react-vite or taro").option("--cwd <path>", "Working directory").action((options) => {
3457
+ runAstCheck({
3458
+ cwd: options.cwd,
3459
+ stack: requireStack(options.stack)
3460
+ });
3461
+ console.log("OK");
3462
+ });
3463
+ check.command("type").requiredOption("--stack <stack>", "Stack: react-vite or taro").option("--cwd <path>", "Working directory").action(async (options) => {
3464
+ await runTypeCheck({
3465
+ cwd: options.cwd,
3466
+ stack: requireStack(options.stack)
3467
+ });
3468
+ console.log("OK");
3469
+ });
3470
+ check.command("build").requiredOption("--stack <stack>", "Stack: react-vite or taro").option("--cwd <path>", "Working directory").action(async (options) => {
3471
+ await runBuildCheck({
3472
+ cwd: options.cwd,
3473
+ stack: requireStack(options.stack)
3474
+ });
3475
+ console.log("OK");
3476
+ });
3477
+ check.command("all").requiredOption("--stack <stack>", "Stack: react-vite or taro").option("--cwd <path>", "Working directory").action(async (options) => {
3478
+ await runPreCommitCheck({
3479
+ cwd: options.cwd,
3480
+ stack: requireStack(options.stack)
3481
+ });
3482
+ console.log("OK");
3483
+ });
3484
+ program.parseAsync(process.argv).catch((error) => {
3485
+ renderError(error, { json: shouldRenderJsonError(process.argv) });
3486
+ process.exit(1);
3487
+ });
1280
3488
  //# sourceMappingURL=cli.cjs.map
1281
3489
  //# sourceMappingURL=cli.cjs.map