@amaster.ai/cli 1.1.30 → 1.1.32

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
@@ -3,7 +3,7 @@ import { readFileSync, existsSync, writeFileSync, readdirSync, statSync, rmSync,
3
3
  import { createInterface } from 'readline/promises';
4
4
  import { stdin, stdout } from 'process';
5
5
  import { Command, Option } from 'commander';
6
- import { readFile, mkdtemp, stat, rm, writeFile, readdir, unlink, copyFile, mkdir, access } from 'fs/promises';
6
+ import { readFile, mkdtemp, stat, rm, writeFile, readdir, access, unlink, copyFile, mkdir } from 'fs/promises';
7
7
  import { join, resolve, basename, dirname, relative, parse, extname } from 'path';
8
8
  import { randomBytes, createHash, randomUUID } from 'crypto';
9
9
  import { tmpdir, homedir } from 'os';
@@ -537,6 +537,7 @@ async function loadAddonManifestFromDirectory(directory) {
537
537
  const manifestText = await readFile(manifestPath, "utf8");
538
538
  const manifest = JSON.parse(manifestText);
539
539
  validateAddonManifest(manifest);
540
+ await assertDisplayAssetPathsExist(directory, manifest);
540
541
  return manifest;
541
542
  }
542
543
  function validateAddonManifest(manifest) {
@@ -555,9 +556,40 @@ function validateAddonManifest(manifest) {
555
556
  if (!Array.isArray(manifest.members)) {
556
557
  throw new Error("addon.json missing members");
557
558
  }
559
+ validateDisplayAssets(manifest);
558
560
  validateInstallRequirements(manifest);
559
561
  validateInstallNpm(manifest);
560
562
  }
563
+ function validateDisplayAssets(manifest) {
564
+ const image = manifest.display.image;
565
+ if (image !== void 0) {
566
+ if (typeof image !== "string") {
567
+ throw new Error("addon.json display.image must be a string");
568
+ }
569
+ normalizeRelativePath(image, "display.image");
570
+ }
571
+ const screenshots = manifest.display.screenshots;
572
+ if (screenshots !== void 0) {
573
+ if (!Array.isArray(screenshots)) {
574
+ throw new Error("addon.json display.screenshots must be an array");
575
+ }
576
+ screenshots.forEach((item, index) => {
577
+ if (typeof item !== "string") {
578
+ throw new Error(`addon.json display.screenshots[${index}] must be a string`);
579
+ }
580
+ normalizeRelativePath(item, `display.screenshots[${index}]`);
581
+ });
582
+ }
583
+ }
584
+ async function assertDisplayAssetPathsExist(directory, manifest) {
585
+ const paths = [
586
+ ...manifest.display.image ? [manifest.display.image] : [],
587
+ ...manifest.display.screenshots ?? []
588
+ ];
589
+ for (const assetPath of paths) {
590
+ await assertPathExists(directory, normalizeRelativePath(assetPath, "display asset path"));
591
+ }
592
+ }
561
593
  function validateInstallRequirements(manifest) {
562
594
  const requirements = manifest.install?.requirements;
563
595
  if (!requirements) {
@@ -624,21 +656,21 @@ function validateInstallNpm(manifest) {
624
656
  function resolveMemberSourcePath(member) {
625
657
  const sourcePath = member.source?.path;
626
658
  if (typeof sourcePath === "string" && sourcePath.trim()) {
627
- return normalizeRelativePath(sourcePath);
659
+ return normalizeRelativePath(sourcePath, "member source path");
628
660
  }
629
661
  const fallbackKeys = ["entry", "path", "contentPath"];
630
662
  for (const key of fallbackKeys) {
631
663
  const value = member[key];
632
664
  if (typeof value === "string" && value.trim()) {
633
- return normalizeRelativePath(value);
665
+ return normalizeRelativePath(value, "member source path");
634
666
  }
635
667
  }
636
668
  return null;
637
669
  }
638
- function normalizeRelativePath(value) {
670
+ function normalizeRelativePath(value, fieldName = "path") {
639
671
  const normalized = value.replace(/^\.?\//, "").replace(/\\/g, "/");
640
672
  if (!normalized || normalized.startsWith("../") || normalized.includes("/../")) {
641
- throw new Error(`Invalid member source path: ${value}`);
673
+ throw new Error(`Invalid addon.json ${fieldName}: ${value}`);
642
674
  }
643
675
  return normalized;
644
676
  }
@@ -754,13 +786,6 @@ function ensurePathInsideTarget(targetDir, relativePath) {
754
786
  }
755
787
  return absolute;
756
788
  }
757
- function removeFileExtension(input) {
758
- const extension = extname(input);
759
- return extension ? input.slice(0, -extension.length) : input;
760
- }
761
- function toPascalCase(input) {
762
- return input.split(/[^a-zA-Z0-9]+/).filter(Boolean).map((part) => part[0].toUpperCase() + part.slice(1)).join("");
763
- }
764
789
  function parseScalarValue(rawValue, expectedType, enumValues) {
765
790
  const primaryType = Array.isArray(expectedType) ? expectedType[0] : expectedType;
766
791
  if (enumValues?.length) {
@@ -852,6 +877,83 @@ function buildMissingRequirements(requirements) {
852
877
  secrets: requirements.secrets?.filter((item) => item.required !== false).map((item) => ({ ...item }))
853
878
  };
854
879
  }
880
+ function hasInstallRequirements(requirements) {
881
+ return Boolean(requirements.envs?.length || requirements.secrets?.length);
882
+ }
883
+ function hasNpmDependencies(npm) {
884
+ return Boolean(Object.keys(npm.dependencies ?? {}).length);
885
+ }
886
+ function buildAddonLlmGuidance(input) {
887
+ const pageMembers = input.meta.members.filter((member) => member.type === "page");
888
+ const componentMembers = input.meta.members.filter((member) => member.type === "component");
889
+ const settingsMembers = input.meta.members.filter((member) => member.type === "settings");
890
+ const webRoutes = input.meta.members.filter((member) => member.type === "page" && member.page?.web).map((member) => ({
891
+ route: member.page.web.route,
892
+ entry: member.page.web.entry.startsWith("src/") ? member.page.web.entry : `src/${member.page.web.entry}`,
893
+ title: member.page.web.title,
894
+ visible: member.page.web.visible,
895
+ suggestedFile: "src/routes.tsx"
896
+ }));
897
+ const miniPages = input.meta.members.filter((member) => member.type === "page" && member.page?.mini).map((member) => ({
898
+ pagePath: member.page.mini.pagePath,
899
+ suggestedFile: "src/app.config.ts",
900
+ tabBar: member.page.mini.tabBar
901
+ }));
902
+ const components = componentMembers.map((member) => ({
903
+ name: member.name,
904
+ importFrom: member.targetPaths[0] || "",
905
+ targetPaths: member.targetPaths
906
+ }));
907
+ const settings = settingsMembers.map((member) => ({
908
+ targetPath: member.settings?.targetPath || member.targetPaths[0] || "",
909
+ paths: member.settings?.paths.map((item) => item.path) || []
910
+ }));
911
+ const instructions = [
912
+ `Addon ${input.meta.name}@${input.meta.version} has been ${input.operation === "install" ? "installed" : "upgraded"} into the application files.`,
913
+ "Do not run the install command again to apply integration steps; edit the application source files directly."
914
+ ];
915
+ if (pageMembers.length > 0) {
916
+ instructions.push("Wire the installed page members into the application's existing routing/configuration style.");
917
+ }
918
+ if (componentMembers.length > 0) {
919
+ instructions.push("Use installed component members from their target paths where the application needs them.");
920
+ }
921
+ if (hasInstallRequirements(input.requirements)) {
922
+ instructions.push("Configure the declared env/secret requirements before running or deploying the application.");
923
+ }
924
+ if (hasNpmDependencies(input.npm)) {
925
+ instructions.push("NPM dependencies have been written to package.json; avoid adding duplicate dependency entries.");
926
+ }
927
+ return {
928
+ summary: input.meta.manifest.description || input.meta.manifest.title || `Installed addon ${input.meta.name}@${input.meta.version}.`,
929
+ instructions,
930
+ skill: input.skillContent ? { path: "SKILL.md", content: input.skillContent } : void 0,
931
+ webRoutes: webRoutes.length ? webRoutes : void 0,
932
+ miniPages: miniPages.length ? miniPages : void 0,
933
+ components: components.length ? components : void 0,
934
+ settings: settings.length ? settings : void 0,
935
+ requirements: hasInstallRequirements(input.requirements) ? input.requirements : void 0,
936
+ npm: hasNpmDependencies(input.npm) ? input.npm : void 0
937
+ };
938
+ }
939
+ async function readAddonSkillGuidance(extractedDir, manifest) {
940
+ const hasSkillMemberAtRoot = manifest.members.some((member) => {
941
+ if (member.type !== "skill") {
942
+ return false;
943
+ }
944
+ const sourcePath = resolveMemberSourcePath(member);
945
+ return sourcePath === "SKILL.md";
946
+ });
947
+ if (hasSkillMemberAtRoot) {
948
+ return void 0;
949
+ }
950
+ const skillPath = join(extractedDir, "SKILL.md");
951
+ if (!existsSync(skillPath)) {
952
+ return void 0;
953
+ }
954
+ const content = (await readFile(skillPath, "utf8")).trim();
955
+ return content || void 0;
956
+ }
855
957
  function getAddonMetaPath(targetDir, addonName) {
856
958
  return join(targetDir, "src", "addons", addonName, "meta.json");
857
959
  }
@@ -1610,119 +1712,6 @@ async function validateUpgradeConflicts(targetDir, plan, existingMetas, previous
1610
1712
  });
1611
1713
  }
1612
1714
  }
1613
- async function ensureWebRoutesPatched(targetDir) {
1614
- const routesFile = join(targetDir, "src", "routes.tsx");
1615
- const original = await readFile(routesFile, "utf8");
1616
- let next = original;
1617
- if (!next.includes("./amaster/registry/addon-routes.generated")) {
1618
- next = next.replace(
1619
- 'import type { ComponentType } from "react";',
1620
- 'import type { ComponentType } from "react";\nimport { addonRoutes } from "./amaster/registry/addon-routes.generated";'
1621
- );
1622
- }
1623
- if (!next.includes("...addonRoutes")) {
1624
- const routeArrayPattern = /const routes:\s*RouteConfig\[\]\s*=\s*\[([\s\S]*?)\];/;
1625
- const match = next.match(routeArrayPattern);
1626
- if (!match) {
1627
- throw new Error("Unable to patch src/routes.tsx for addon route registration");
1628
- }
1629
- const inner = match[1]?.trim() ?? "";
1630
- const replacement = inner ? `const routes: RouteConfig[] = [
1631
- ...addonRoutes,
1632
- ${match[1]}
1633
- ];` : "const routes: RouteConfig[] = [\n ...addonRoutes,\n];";
1634
- next = next.replace(routeArrayPattern, replacement);
1635
- }
1636
- if (next !== original) {
1637
- await writeFile(routesFile, next);
1638
- }
1639
- }
1640
- async function ensureMiniAppConfigPatched(targetDir, needsTabBarItems) {
1641
- const configFile = join(targetDir, "src", "app.config.ts");
1642
- const original = await readFile(configFile, "utf8");
1643
- let next = original;
1644
- if (!next.includes("./amaster/registry/addon-pages.generated")) {
1645
- next = `import { addonPages, addonTabBarItems } from "./amaster/registry/addon-pages.generated";
1646
- ${next}`;
1647
- }
1648
- if (!next.includes("...addonPages")) {
1649
- next = next.replace(/const pages\s*=\s*\[([\s\S]*?)\]/, (_full, inner) => {
1650
- const trimmed = inner.trim();
1651
- if (!trimmed) {
1652
- return "const pages = [...addonPages]";
1653
- }
1654
- return `const pages = [${inner}, ...addonPages]`;
1655
- });
1656
- }
1657
- if (needsTabBarItems && !next.includes("...addonTabBarItems")) {
1658
- const listPattern = /list:\s*\[([\s\S]*?)\]/;
1659
- const match = next.match(listPattern);
1660
- if (!match) {
1661
- throw new Error("Unable to patch src/app.config.ts for addon tabBar registration");
1662
- }
1663
- next = next.replace(listPattern, (_full, inner) => `list: [${inner}, ...addonTabBarItems]`);
1664
- }
1665
- if (next !== original) {
1666
- await writeFile(configFile, next);
1667
- }
1668
- }
1669
- async function rebuildRegistryFiles(targetDir, applicationType, metas) {
1670
- const registryDir = join(targetDir, "src", "amaster", "registry");
1671
- await mkdir(registryDir, { recursive: true });
1672
- if (applicationType === "web") {
1673
- const pageMembers2 = metas.flatMap(
1674
- (meta) => meta.members.filter((member) => member.type === "page" && member.page?.web).map((member) => ({ addonName: meta.name, member }))
1675
- ).sort((left, right) => `${left.addonName}:${left.member.name}`.localeCompare(`${right.addonName}:${right.member.name}`));
1676
- const imports = pageMembers2.map(({ addonName, member }) => {
1677
- const identifier = toPascalCase(`${addonName}-${member.name}-page`);
1678
- const entry = member.page.web.entry;
1679
- return {
1680
- identifier,
1681
- importPath: `../../${removeFileExtension(entry).replace(/\\/g, "/")}`,
1682
- route: member.page.web.route,
1683
- visible: member.page.web.visible,
1684
- name: member.name
1685
- };
1686
- });
1687
- const fileContent2 = [
1688
- 'import type { ComponentType } from "react";',
1689
- ...imports.map((item) => `import ${item.identifier} from "${item.importPath}";`),
1690
- "",
1691
- "type AddonRouteConfig = {",
1692
- " name: string;",
1693
- " path: string;",
1694
- " Component: ComponentType<Record<string, unknown>>;",
1695
- " visible?: boolean;",
1696
- "};",
1697
- "",
1698
- "export const addonRoutes: AddonRouteConfig[] = [",
1699
- ...imports.map(
1700
- (item) => ` { name: ${JSON.stringify(item.name)}, path: ${JSON.stringify(item.route)}, Component: ${item.identifier},${item.visible === void 0 ? "" : ` visible: ${item.visible},`} },`
1701
- ),
1702
- "];",
1703
- ""
1704
- ].join("\n");
1705
- await writeFile(join(registryDir, "addon-routes.generated.ts"), fileContent2);
1706
- await ensureWebRoutesPatched(targetDir);
1707
- return;
1708
- }
1709
- const pageMembers = metas.flatMap(
1710
- (meta) => meta.members.filter((member) => member.type === "page" && member.page?.mini).map((member) => member.page.mini)
1711
- ).sort((left, right) => left.pagePath.localeCompare(right.pagePath));
1712
- const addonPages = pageMembers.map((page) => page.pagePath);
1713
- const addonTabBarItems = pageMembers.filter((page) => page.tabBar).map((page) => ({
1714
- pagePath: page.pagePath,
1715
- ...page.tabBar
1716
- }));
1717
- const fileContent = [
1718
- `export const addonPages = ${JSON.stringify(addonPages, null, 2)};`,
1719
- "",
1720
- `export const addonTabBarItems = ${JSON.stringify(addonTabBarItems, null, 2)};`,
1721
- ""
1722
- ].join("\n");
1723
- await writeFile(join(registryDir, "addon-pages.generated.ts"), fileContent);
1724
- await ensureMiniAppConfigPatched(targetDir, addonTabBarItems.length > 0);
1725
- }
1726
1715
  async function materializeAddon(options) {
1727
1716
  const targetDir = resolve(options.targetDir);
1728
1717
  const existingMetas = await listInstalledAddons(targetDir);
@@ -1766,19 +1755,26 @@ async function materializeAddon(options) {
1766
1755
  });
1767
1756
  await ensureParentDirectory(plan.metaPath);
1768
1757
  await writeFile(plan.metaPath, JSON.stringify(meta, null, 2));
1769
- const nextMetas = existingMetas.filter((item) => item.name !== meta.name).concat(meta);
1770
- await rebuildRegistryFiles(targetDir, plan.applicationType, nextMetas.filter((item) => item.applicationType === plan.applicationType));
1771
1758
  if (options.installPackageDependencies && packageJsonFiles.length) {
1772
1759
  await installPackageDependencies(targetDir);
1773
1760
  }
1774
1761
  const requirements = resolveInstallRequirements(plan.manifest);
1762
+ const skillContent = await readAddonSkillGuidance(options.extractedDir, plan.manifest);
1763
+ const llmGuidance = buildAddonLlmGuidance({
1764
+ operation: options.mode,
1765
+ meta,
1766
+ requirements,
1767
+ npm,
1768
+ skillContent
1769
+ });
1775
1770
  return {
1776
1771
  meta,
1777
1772
  writtenFiles: installedFiles.map((file) => file.path).concat(packageJsonFiles, restoredSettingsFiles, settingsResult.writtenFiles),
1778
1773
  removedFiles,
1779
1774
  requirements,
1780
1775
  missingRequirements: buildMissingRequirements(requirements),
1781
- npm
1776
+ npm,
1777
+ llmGuidance
1782
1778
  };
1783
1779
  }
1784
1780
  async function installAddonFromExtractedDirectory(options) {
@@ -3412,6 +3408,47 @@ function formatLoginIdentity(user) {
3412
3408
  function resolveAddonTargetDir(target) {
3413
3409
  return target ? target : resolveNearestPackageRoot();
3414
3410
  }
3411
+ function renderAddonInstallResult(result, operation, options) {
3412
+ const output = {
3413
+ success: true,
3414
+ operation,
3415
+ addon: {
3416
+ name: result.meta.name,
3417
+ version: result.meta.version,
3418
+ applicationType: result.meta.applicationType
3419
+ },
3420
+ files: {
3421
+ written: result.writtenFiles,
3422
+ removed: result.removedFiles
3423
+ },
3424
+ npm: Object.keys(result.npm.dependencies ?? {}).length ? result.npm : void 0,
3425
+ missingRequirements: result.missingRequirements.envs?.length || result.missingRequirements.secrets?.length ? result.missingRequirements : void 0,
3426
+ llmGuidance: result.llmGuidance
3427
+ };
3428
+ if (options.json) {
3429
+ renderOutput(output, options);
3430
+ return;
3431
+ }
3432
+ const lines = [
3433
+ `Addon ${operation === "install" ? "installed" : "upgraded"}: ${result.meta.name}@${result.meta.version}`,
3434
+ `Application type: ${result.meta.applicationType}`,
3435
+ `Written files: ${result.writtenFiles.length}`
3436
+ ];
3437
+ if (result.removedFiles.length) {
3438
+ lines.push(`Removed files: ${result.removedFiles.length}`);
3439
+ }
3440
+ if (result.llmGuidance.webRoutes?.length) {
3441
+ lines.push("Next: wire web routes from llmGuidance.webRoutes.");
3442
+ }
3443
+ if (result.llmGuidance.miniPages?.length) {
3444
+ lines.push("Next: wire mini pages from llmGuidance.miniPages.");
3445
+ }
3446
+ if (output.missingRequirements) {
3447
+ lines.push("Next: configure missing env/secrets from llmGuidance.requirements.");
3448
+ }
3449
+ lines.push("Use --json for LLM-readable integration guidance.");
3450
+ renderOutput(lines.join("\n"), options);
3451
+ }
3415
3452
  function requireStack(value) {
3416
3453
  if (value === "react-vite" || value === "taro") {
3417
3454
  return value;
@@ -3574,7 +3611,7 @@ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("install <sp
3574
3611
  organizationCode: options.organizationCode,
3575
3612
  installParameters: parseKeyValuePairs(options.set)
3576
3613
  });
3577
- renderOutput(result, options);
3614
+ renderAddonInstallResult(result, "install", options);
3578
3615
  });
3579
3616
  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) => {
3580
3617
  const registry = resolveRegistryFromOptions(options);
@@ -3586,7 +3623,7 @@ addJsonOption(addOrganizationOption(addRegistryOption(addon.command("upgrade <sp
3586
3623
  organizationCode: options.organizationCode,
3587
3624
  installParameters: parseKeyValuePairs(options.set)
3588
3625
  });
3589
- renderOutput(result, options);
3626
+ renderAddonInstallResult(result, "upgrade", options);
3590
3627
  });
3591
3628
  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) => {
3592
3629
  const installed = await listInstalledAddons(resolveAddonTargetDir(options.target));