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