@lark-apaas/fullstack-cli 1.1.71-alpha.20261103174546 → 1.1.71-alpha.20261104083435

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.js +1068 -2348
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // src/index.ts
2
- import fs40 from "fs";
3
- import path35 from "path";
2
+ import fs32 from "fs";
3
+ import path27 from "path";
4
4
  import { fileURLToPath as fileURLToPath5 } from "url";
5
5
  import { config as dotenvConfig } from "dotenv";
6
6
 
@@ -2478,8 +2478,8 @@ var genDbSchemaCommand = {
2478
2478
  };
2479
2479
 
2480
2480
  // src/commands/sync/run.handler.ts
2481
- import path7 from "path";
2482
- import fs10 from "fs";
2481
+ import path6 from "path";
2482
+ import fs9 from "fs";
2483
2483
  import { fileURLToPath as fileURLToPath3 } from "url";
2484
2484
 
2485
2485
  // src/config/sync.ts
@@ -2549,7 +2549,10 @@ function buildDefaultRules(opts) {
2549
2549
  },
2550
2550
  // 5. 注册 postinstall 脚本,自动恢复 action plugins
2551
2551
  {
2552
- type: "action-plugin-lifecycle"
2552
+ type: "add-script",
2553
+ name: "postinstall",
2554
+ command: "fullstack-cli action-plugin init",
2555
+ overwrite: false
2553
2556
  },
2554
2557
  // 6. 替换 drizzle.config.ts(仅当文件存在时)
2555
2558
  {
@@ -2800,177 +2803,18 @@ function isNestjsProject(root, stack) {
2800
2803
  }
2801
2804
  }
2802
2805
 
2803
- // src/commands/action-plugin/lifecycle.ts
2804
- import fs9 from "fs";
2805
- import path6 from "path";
2806
- var ACTION_PLUGIN_RESTORE_COMMAND = "fullstack-cli action-plugin restore";
2807
- var LEGACY_ACTION_PLUGIN_INIT_COMMAND = "fullstack-cli action-plugin init";
2808
- var ACTION_PLUGIN_REENTRY_ENV = "FULLSTACK_CLI_ACTION_PLUGIN_REENTRY";
2809
- var ACTION_PLUGIN_REENTRY_VALUE = "1";
2810
- function normalizeManagedCommand(segment) {
2811
- return segment.trim().replace(/\s+/g, " ");
2812
- }
2813
- function isManagedLifecycleSegment(segment) {
2814
- const normalized = normalizeManagedCommand(segment);
2815
- return normalized === LEGACY_ACTION_PLUGIN_INIT_COMMAND || normalized === ACTION_PLUGIN_RESTORE_COMMAND;
2816
- }
2817
- function isShellWhitespace(character) {
2818
- return /\s/.test(character);
2819
- }
2820
- function findTopLevelAndOperators(command) {
2821
- const operators = [];
2822
- let quote = null;
2823
- let parenthesisDepth = 0;
2824
- let braceDepth = 0;
2825
- let inComment = false;
2826
- for (let index = 0; index < command.length; index++) {
2827
- const character = command[index];
2828
- if (inComment) {
2829
- if (character === "\n") inComment = false;
2830
- continue;
2831
- }
2832
- if (quote) {
2833
- if (quote !== "'" && character === "\\") {
2834
- index++;
2835
- continue;
2836
- }
2837
- if (character === quote) quote = null;
2838
- continue;
2839
- }
2840
- if (character === "\\") {
2841
- index++;
2842
- continue;
2843
- }
2844
- if (character === "'" || character === '"' || character === "`") {
2845
- quote = character;
2846
- continue;
2847
- }
2848
- if (character === "#" && (index === 0 || isShellWhitespace(command[index - 1]))) {
2849
- inComment = true;
2850
- continue;
2851
- }
2852
- if (character === "(") {
2853
- parenthesisDepth++;
2854
- continue;
2855
- }
2856
- if (character === ")") {
2857
- if (parenthesisDepth > 0) parenthesisDepth--;
2858
- continue;
2859
- }
2860
- if (character === "{") {
2861
- braceDepth++;
2862
- continue;
2863
- }
2864
- if (character === "}") {
2865
- if (braceDepth > 0) braceDepth--;
2866
- continue;
2867
- }
2868
- if (character === "&" && command[index + 1] === "&" && parenthesisDepth === 0 && braceDepth === 0) {
2869
- operators.push(index);
2870
- index++;
2871
- }
2872
- }
2873
- return operators;
2874
- }
2875
- function splitShellAndList(command) {
2876
- const segments = [];
2877
- const separators = [];
2878
- let cursor = 0;
2879
- for (const [index, operator] of findTopLevelAndOperators(command).entries()) {
2880
- let separatorStart = operator;
2881
- while (separatorStart > cursor && isShellWhitespace(command[separatorStart - 1])) {
2882
- separatorStart--;
2883
- }
2884
- let separatorEnd = operator + 2;
2885
- while (separatorEnd < command.length && isShellWhitespace(command[separatorEnd])) {
2886
- separatorEnd++;
2887
- }
2888
- segments.push({ text: command.slice(cursor, separatorStart), index });
2889
- separators.push({ text: command.slice(separatorStart, separatorEnd) });
2890
- cursor = separatorEnd;
2891
- }
2892
- segments.push({ text: command.slice(cursor), index: segments.length });
2893
- return { segments, separators };
2894
- }
2895
- function stripManagedLifecycleSegments(command) {
2896
- const { segments, separators } = splitShellAndList(command);
2897
- const customSegments = segments.filter(
2898
- (segment) => !isManagedLifecycleSegment(segment.text)
2899
- );
2900
- if (customSegments.length === segments.length) return command;
2901
- if (customSegments.length === 0) return "";
2902
- let result = customSegments[0].text;
2903
- for (const segment of customSegments.slice(1)) {
2904
- result += separators[segment.index - 1].text + segment.text;
2905
- }
2906
- return result;
2907
- }
2908
- function composeActionPluginLifecycle(pkg2) {
2909
- const scripts = pkg2.scripts ?? {};
2910
- const current = scripts.postinstall ?? "";
2911
- const custom = stripManagedLifecycleSegments(current);
2912
- const next = custom ? `${custom} && ${ACTION_PLUGIN_RESTORE_COMMAND}` : ACTION_PLUGIN_RESTORE_COMMAND;
2913
- if (current === next) return false;
2914
- pkg2.scripts = scripts;
2915
- scripts.postinstall = next;
2916
- return true;
2917
- }
2918
- function removeActionPluginLifecycle(pkg2) {
2919
- const scripts = pkg2.scripts;
2920
- if (!scripts?.postinstall) return false;
2921
- const current = scripts.postinstall;
2922
- const next = stripManagedLifecycleSegments(current);
2923
- if (current === next) return false;
2924
- if (next) scripts.postinstall = next;
2925
- else delete scripts.postinstall;
2926
- if (Object.keys(scripts).length === 0) delete pkg2.scripts;
2927
- return true;
2928
- }
2929
- function atomicWriteFile(filePath, content) {
2930
- const directory = path6.dirname(filePath);
2931
- const temporaryPath = path6.join(
2932
- directory,
2933
- `.${path6.basename(filePath)}.${process.pid}.${Date.now()}.${Math.random().toString(16).slice(2)}.tmp`
2934
- );
2935
- const mode = fs9.existsSync(filePath) ? fs9.statSync(filePath).mode : void 0;
2936
- try {
2937
- fs9.writeFileSync(
2938
- temporaryPath,
2939
- content,
2940
- mode === void 0 ? void 0 : { mode }
2941
- );
2942
- fs9.renameSync(temporaryPath, filePath);
2943
- } finally {
2944
- if (fs9.existsSync(temporaryPath)) {
2945
- fs9.rmSync(temporaryPath, { force: true });
2946
- }
2947
- }
2948
- }
2949
- function atomicWriteJson(filePath, value) {
2950
- atomicWriteFile(filePath, `${JSON.stringify(value, null, 2)}
2951
- `);
2952
- }
2953
- function ensureActionPluginLifecycle(packageJsonPath) {
2954
- const pkg2 = JSON.parse(
2955
- fs9.readFileSync(packageJsonPath, "utf-8")
2956
- );
2957
- if (!composeActionPluginLifecycle(pkg2)) return false;
2958
- atomicWriteJson(packageJsonPath, pkg2);
2959
- return true;
2960
- }
2961
-
2962
2806
  // src/commands/sync/run.handler.ts
2963
2807
  async function run2(options) {
2964
2808
  const userProjectRoot = process.env.INIT_CWD || process.cwd();
2965
2809
  const __filename = fileURLToPath3(import.meta.url);
2966
- const __dirname2 = path7.dirname(__filename);
2967
- const pluginRoot = path7.resolve(__dirname2, "..");
2810
+ const __dirname2 = path6.dirname(__filename);
2811
+ const pluginRoot = path6.resolve(__dirname2, "..");
2968
2812
  if (userProjectRoot === pluginRoot) {
2969
2813
  console.log("[fullstack-cli] Skip syncing (installing plugin itself)");
2970
2814
  process.exit(0);
2971
2815
  }
2972
- const userPackageJson = path7.join(userProjectRoot, "package.json");
2973
- if (!fs10.existsSync(userPackageJson)) {
2816
+ const userPackageJson = path6.join(userProjectRoot, "package.json");
2817
+ if (!fs9.existsSync(userPackageJson)) {
2974
2818
  console.log("[fullstack-cli] Skip syncing (not a valid npm project)");
2975
2819
  process.exit(0);
2976
2820
  }
@@ -3009,11 +2853,11 @@ async function run2(options) {
3009
2853
  }
3010
2854
  async function syncRule(rule, pluginRoot, userProjectRoot) {
3011
2855
  if (rule.type === "typescript-exclude") {
3012
- excludeTypeScriptPath(path7.join(userProjectRoot, rule.to), rule.path);
2856
+ excludeTypeScriptPath(path6.join(userProjectRoot, rule.to), rule.path);
3013
2857
  return;
3014
2858
  }
3015
2859
  if (rule.type === "delete-file" || rule.type === "delete-directory") {
3016
- const destPath2 = path7.join(userProjectRoot, rule.to);
2860
+ const destPath2 = path6.join(userProjectRoot, rule.to);
3017
2861
  if (rule.type === "delete-file") {
3018
2862
  deleteFile(destPath2);
3019
2863
  } else {
@@ -3022,45 +2866,37 @@ async function syncRule(rule, pluginRoot, userProjectRoot) {
3022
2866
  return;
3023
2867
  }
3024
2868
  if (rule.type === "remove-line") {
3025
- const destPath2 = path7.join(userProjectRoot, rule.to);
2869
+ const destPath2 = path6.join(userProjectRoot, rule.to);
3026
2870
  removeLineFromFile(destPath2, rule.pattern);
3027
2871
  return;
3028
2872
  }
3029
- if (rule.type === "action-plugin-lifecycle") {
3030
- const packageJsonPath = path7.join(userProjectRoot, "package.json");
3031
- const changed = ensureActionPluginLifecycle(packageJsonPath);
3032
- console.log(
3033
- changed ? "[fullstack-cli] \u2713 scripts.postinstall" : "[fullstack-cli] \u25CB scripts.postinstall (already registered)"
3034
- );
3035
- return;
3036
- }
3037
2873
  if (rule.type === "add-script") {
3038
- const packageJsonPath = path7.join(userProjectRoot, "package.json");
2874
+ const packageJsonPath = path6.join(userProjectRoot, "package.json");
3039
2875
  addScript(packageJsonPath, rule.name, rule.command, rule.overwrite ?? false);
3040
2876
  return;
3041
2877
  }
3042
2878
  if (rule.type === "patch-script") {
3043
- const packageJsonPath = path7.join(userProjectRoot, "package.json");
2879
+ const packageJsonPath = path6.join(userProjectRoot, "package.json");
3044
2880
  patchScript(packageJsonPath, rule.name, rule.to, rule.ifStartsWith);
3045
2881
  return;
3046
2882
  }
3047
2883
  if (rule.type === "add-line") {
3048
- const destPath2 = path7.join(userProjectRoot, rule.to);
2884
+ const destPath2 = path6.join(userProjectRoot, rule.to);
3049
2885
  addLineToFile(destPath2, rule.line);
3050
2886
  return;
3051
2887
  }
3052
2888
  if (rule.type === "merge-json") {
3053
- const srcPath2 = path7.join(pluginRoot, rule.from);
3054
- const destPath2 = path7.join(userProjectRoot, rule.to);
2889
+ const srcPath2 = path6.join(pluginRoot, rule.from);
2890
+ const destPath2 = path6.join(userProjectRoot, rule.to);
3055
2891
  mergeJsonFile(srcPath2, destPath2, rule.arrayMerge);
3056
2892
  return;
3057
2893
  }
3058
2894
  if (!("from" in rule)) {
3059
2895
  return;
3060
2896
  }
3061
- const srcPath = path7.join(pluginRoot, rule.from);
3062
- const destPath = path7.join(userProjectRoot, rule.to);
3063
- if (!fs10.existsSync(srcPath)) {
2897
+ const srcPath = path6.join(pluginRoot, rule.from);
2898
+ const destPath = path6.join(userProjectRoot, rule.to);
2899
+ if (!fs9.existsSync(srcPath)) {
3064
2900
  console.warn(`[fullstack-cli] Source not found: ${rule.from}`);
3065
2901
  return;
3066
2902
  }
@@ -3077,68 +2913,68 @@ async function syncRule(rule, pluginRoot, userProjectRoot) {
3077
2913
  }
3078
2914
  }
3079
2915
  function syncFile(src, dest, overwrite = true, onlyIfExists = false) {
3080
- if (onlyIfExists && !fs10.existsSync(dest)) {
3081
- console.log(`[fullstack-cli] \u25CB ${path7.basename(dest)} (skipped, target not exists)`);
2916
+ if (onlyIfExists && !fs9.existsSync(dest)) {
2917
+ console.log(`[fullstack-cli] \u25CB ${path6.basename(dest)} (skipped, target not exists)`);
3082
2918
  return;
3083
2919
  }
3084
- const destDir = path7.dirname(dest);
3085
- if (!fs10.existsSync(destDir)) {
3086
- fs10.mkdirSync(destDir, { recursive: true });
2920
+ const destDir = path6.dirname(dest);
2921
+ if (!fs9.existsSync(destDir)) {
2922
+ fs9.mkdirSync(destDir, { recursive: true });
3087
2923
  }
3088
- if (fs10.existsSync(dest) && !overwrite) {
3089
- console.log(`[fullstack-cli] \u25CB ${path7.basename(dest)} (skipped, already exists)`);
2924
+ if (fs9.existsSync(dest) && !overwrite) {
2925
+ console.log(`[fullstack-cli] \u25CB ${path6.basename(dest)} (skipped, already exists)`);
3090
2926
  return;
3091
2927
  }
3092
- fs10.copyFileSync(src, dest);
3093
- console.log(`[fullstack-cli] \u2713 ${path7.basename(dest)}`);
2928
+ fs9.copyFileSync(src, dest);
2929
+ console.log(`[fullstack-cli] \u2713 ${path6.basename(dest)}`);
3094
2930
  }
3095
2931
  function syncDirectory(src, dest, overwrite = true) {
3096
- if (!fs10.existsSync(dest)) {
3097
- fs10.mkdirSync(dest, { recursive: true });
2932
+ if (!fs9.existsSync(dest)) {
2933
+ fs9.mkdirSync(dest, { recursive: true });
3098
2934
  }
3099
- const files = fs10.readdirSync(src);
2935
+ const files = fs9.readdirSync(src);
3100
2936
  let count = 0;
3101
2937
  files.forEach((file) => {
3102
- const srcFile = path7.join(src, file);
3103
- const destFile = path7.join(dest, file);
3104
- const stats = fs10.statSync(srcFile);
2938
+ const srcFile = path6.join(src, file);
2939
+ const destFile = path6.join(dest, file);
2940
+ const stats = fs9.statSync(srcFile);
3105
2941
  if (stats.isDirectory()) {
3106
2942
  syncDirectory(srcFile, destFile, overwrite);
3107
2943
  } else {
3108
- if (overwrite || !fs10.existsSync(destFile)) {
3109
- fs10.copyFileSync(srcFile, destFile);
3110
- console.log(`[fullstack-cli] \u2713 ${path7.relative(dest, destFile)}`);
2944
+ if (overwrite || !fs9.existsSync(destFile)) {
2945
+ fs9.copyFileSync(srcFile, destFile);
2946
+ console.log(`[fullstack-cli] \u2713 ${path6.relative(dest, destFile)}`);
3111
2947
  count++;
3112
2948
  }
3113
2949
  }
3114
2950
  });
3115
2951
  if (count > 0) {
3116
- console.log(`[fullstack-cli] Synced ${count} files to ${path7.basename(dest)}/`);
2952
+ console.log(`[fullstack-cli] Synced ${count} files to ${path6.basename(dest)}/`);
3117
2953
  }
3118
2954
  }
3119
2955
  function appendToFile(src, dest) {
3120
- const content = fs10.readFileSync(src, "utf-8");
2956
+ const content = fs9.readFileSync(src, "utf-8");
3121
2957
  let existingContent = "";
3122
- if (fs10.existsSync(dest)) {
3123
- existingContent = fs10.readFileSync(dest, "utf-8");
2958
+ if (fs9.existsSync(dest)) {
2959
+ existingContent = fs9.readFileSync(dest, "utf-8");
3124
2960
  }
3125
2961
  if (existingContent.includes(content.trim())) {
3126
- console.log(`[fullstack-cli] \u25CB ${path7.basename(dest)} (already contains content)`);
2962
+ console.log(`[fullstack-cli] \u25CB ${path6.basename(dest)} (already contains content)`);
3127
2963
  return;
3128
2964
  }
3129
- fs10.appendFileSync(dest, content);
3130
- console.log(`[fullstack-cli] \u2713 ${path7.basename(dest)} (appended)`);
2965
+ fs9.appendFileSync(dest, content);
2966
+ console.log(`[fullstack-cli] \u2713 ${path6.basename(dest)} (appended)`);
3131
2967
  }
3132
2968
  function setPermissions(permissions, projectRoot) {
3133
2969
  for (const [pattern, mode] of Object.entries(permissions)) {
3134
2970
  if (pattern === "**/*.sh") {
3135
- const scriptsDir = path7.join(projectRoot, "scripts");
3136
- if (fs10.existsSync(scriptsDir)) {
3137
- const files = fs10.readdirSync(scriptsDir);
2971
+ const scriptsDir = path6.join(projectRoot, "scripts");
2972
+ if (fs9.existsSync(scriptsDir)) {
2973
+ const files = fs9.readdirSync(scriptsDir);
3138
2974
  files.forEach((file) => {
3139
2975
  if (file.endsWith(".sh")) {
3140
- const filePath = path7.join(scriptsDir, file);
3141
- fs10.chmodSync(filePath, mode);
2976
+ const filePath = path6.join(scriptsDir, file);
2977
+ fs9.chmodSync(filePath, mode);
3142
2978
  }
3143
2979
  });
3144
2980
  }
@@ -3146,27 +2982,27 @@ function setPermissions(permissions, projectRoot) {
3146
2982
  }
3147
2983
  }
3148
2984
  function deleteFile(filePath) {
3149
- if (fs10.existsSync(filePath)) {
3150
- fs10.unlinkSync(filePath);
3151
- console.log(`[fullstack-cli] \u2713 ${path7.basename(filePath)} (deleted)`);
2985
+ if (fs9.existsSync(filePath)) {
2986
+ fs9.unlinkSync(filePath);
2987
+ console.log(`[fullstack-cli] \u2713 ${path6.basename(filePath)} (deleted)`);
3152
2988
  } else {
3153
- console.log(`[fullstack-cli] \u25CB ${path7.basename(filePath)} (not found)`);
2989
+ console.log(`[fullstack-cli] \u25CB ${path6.basename(filePath)} (not found)`);
3154
2990
  }
3155
2991
  }
3156
2992
  function deleteDirectory(dirPath) {
3157
- if (fs10.existsSync(dirPath)) {
3158
- fs10.rmSync(dirPath, { recursive: true });
3159
- console.log(`[fullstack-cli] \u2713 ${path7.basename(dirPath)} (deleted)`);
2993
+ if (fs9.existsSync(dirPath)) {
2994
+ fs9.rmSync(dirPath, { recursive: true });
2995
+ console.log(`[fullstack-cli] \u2713 ${path6.basename(dirPath)} (deleted)`);
3160
2996
  } else {
3161
- console.log(`[fullstack-cli] \u25CB ${path7.basename(dirPath)} (not found)`);
2997
+ console.log(`[fullstack-cli] \u25CB ${path6.basename(dirPath)} (not found)`);
3162
2998
  }
3163
2999
  }
3164
3000
  function addScript(packageJsonPath, name, command, overwrite) {
3165
- if (!fs10.existsSync(packageJsonPath)) {
3001
+ if (!fs9.existsSync(packageJsonPath)) {
3166
3002
  console.log(`[fullstack-cli] \u25CB package.json (not found)`);
3167
3003
  return;
3168
3004
  }
3169
- const content = fs10.readFileSync(packageJsonPath, "utf-8");
3005
+ const content = fs9.readFileSync(packageJsonPath, "utf-8");
3170
3006
  const pkg2 = JSON.parse(content);
3171
3007
  if (!pkg2.scripts) {
3172
3008
  pkg2.scripts = {};
@@ -3178,16 +3014,16 @@ function addScript(packageJsonPath, name, command, overwrite) {
3178
3014
  }
3179
3015
  }
3180
3016
  pkg2.scripts[name] = command;
3181
- fs10.writeFileSync(packageJsonPath, JSON.stringify(pkg2, null, 2) + "\n");
3017
+ fs9.writeFileSync(packageJsonPath, JSON.stringify(pkg2, null, 2) + "\n");
3182
3018
  console.log(`[fullstack-cli] \u2713 scripts.${name}`);
3183
3019
  }
3184
3020
  function patchScript(packageJsonPath, name, to, ifStartsWith) {
3185
- if (!fs10.existsSync(packageJsonPath)) {
3021
+ if (!fs9.existsSync(packageJsonPath)) {
3186
3022
  console.log(`[fullstack-cli] \u25CB package.json (not found)`);
3187
3023
  return;
3188
3024
  }
3189
3025
  try {
3190
- const content = fs10.readFileSync(packageJsonPath, "utf-8");
3026
+ const content = fs9.readFileSync(packageJsonPath, "utf-8");
3191
3027
  const pkg2 = JSON.parse(content);
3192
3028
  const current = pkg2.scripts?.[name];
3193
3029
  if (!current) {
@@ -3205,7 +3041,7 @@ function patchScript(packageJsonPath, name, to, ifStartsWith) {
3205
3041
  return;
3206
3042
  }
3207
3043
  pkg2.scripts[name] = to;
3208
- fs10.writeFileSync(packageJsonPath, JSON.stringify(pkg2, null, 2) + "\n");
3044
+ fs9.writeFileSync(packageJsonPath, JSON.stringify(pkg2, null, 2) + "\n");
3209
3045
  console.log(`[fullstack-cli] \u2713 Patched scripts.${name}`);
3210
3046
  } catch (error) {
3211
3047
  const message = error instanceof Error ? error.message : String(error);
@@ -3213,38 +3049,38 @@ function patchScript(packageJsonPath, name, to, ifStartsWith) {
3213
3049
  }
3214
3050
  }
3215
3051
  function addLineToFile(filePath, line) {
3216
- const fileName = path7.basename(filePath);
3217
- if (!fs10.existsSync(filePath)) {
3052
+ const fileName = path6.basename(filePath);
3053
+ if (!fs9.existsSync(filePath)) {
3218
3054
  console.log(`[fullstack-cli] \u25CB ${fileName} (not found, skipped)`);
3219
3055
  return;
3220
3056
  }
3221
- const content = fs10.readFileSync(filePath, "utf-8");
3057
+ const content = fs9.readFileSync(filePath, "utf-8");
3222
3058
  const lines = content.split("\n").map((l) => l.trim());
3223
3059
  if (lines.includes(line)) {
3224
3060
  console.log(`[fullstack-cli] \u25CB ${fileName} (line already exists: ${line})`);
3225
3061
  return;
3226
3062
  }
3227
3063
  const appendContent = (content.endsWith("\n") ? "" : "\n") + line + "\n";
3228
- fs10.appendFileSync(filePath, appendContent);
3064
+ fs9.appendFileSync(filePath, appendContent);
3229
3065
  console.log(`[fullstack-cli] \u2713 ${fileName} (added: ${line})`);
3230
3066
  }
3231
3067
  function mergeJsonFile(src, dest, arrayMerge) {
3232
- const fileName = path7.basename(dest);
3233
- if (!fs10.existsSync(src)) {
3068
+ const fileName = path6.basename(dest);
3069
+ if (!fs9.existsSync(src)) {
3234
3070
  console.warn(`[fullstack-cli] Source not found: ${src}`);
3235
3071
  return;
3236
3072
  }
3237
- const templateContent = JSON.parse(fs10.readFileSync(src, "utf-8"));
3238
- if (!fs10.existsSync(dest)) {
3239
- const destDir = path7.dirname(dest);
3240
- if (!fs10.existsSync(destDir)) {
3241
- fs10.mkdirSync(destDir, { recursive: true });
3073
+ const templateContent = JSON.parse(fs9.readFileSync(src, "utf-8"));
3074
+ if (!fs9.existsSync(dest)) {
3075
+ const destDir = path6.dirname(dest);
3076
+ if (!fs9.existsSync(destDir)) {
3077
+ fs9.mkdirSync(destDir, { recursive: true });
3242
3078
  }
3243
- fs10.writeFileSync(dest, JSON.stringify(templateContent, null, 2) + "\n");
3079
+ fs9.writeFileSync(dest, JSON.stringify(templateContent, null, 2) + "\n");
3244
3080
  console.log(`[fullstack-cli] \u2713 ${fileName} (created)`);
3245
3081
  return;
3246
3082
  }
3247
- const userContent = JSON.parse(fs10.readFileSync(dest, "utf-8"));
3083
+ const userContent = JSON.parse(fs9.readFileSync(dest, "utf-8"));
3248
3084
  const merged = deepMergeJson(userContent, templateContent, arrayMerge ?? {});
3249
3085
  const userStr = JSON.stringify(userContent, null, 2);
3250
3086
  const mergedStr = JSON.stringify(merged, null, 2);
@@ -3252,7 +3088,7 @@ function mergeJsonFile(src, dest, arrayMerge) {
3252
3088
  console.log(`[fullstack-cli] \u25CB ${fileName} (already up to date)`);
3253
3089
  return;
3254
3090
  }
3255
- fs10.writeFileSync(dest, mergedStr + "\n");
3091
+ fs9.writeFileSync(dest, mergedStr + "\n");
3256
3092
  console.log(`[fullstack-cli] \u2713 ${fileName} (merged)`);
3257
3093
  }
3258
3094
 
@@ -3411,12 +3247,12 @@ async function reportCreateInstanceEvent(pluginKey, version) {
3411
3247
 
3412
3248
  // src/utils/git.ts
3413
3249
  import { execSync, spawnSync as spawnSync3 } from "child_process";
3414
- import fs11 from "fs";
3415
- import path8 from "path";
3250
+ import fs10 from "fs";
3251
+ import path7 from "path";
3416
3252
  function isGitRepository(cwd = process.cwd()) {
3417
3253
  try {
3418
- const gitDir = path8.join(cwd, ".git");
3419
- if (fs11.existsSync(gitDir)) {
3254
+ const gitDir = path7.join(cwd, ".git");
3255
+ if (fs10.existsSync(gitDir)) {
3420
3256
  return true;
3421
3257
  }
3422
3258
  const result = spawnSync3("git", ["rev-parse", "--git-dir"], {
@@ -3445,7 +3281,7 @@ function getChangedFiles(cwd = process.cwd()) {
3445
3281
  function gitAddUpgradeFiles(cwd = process.cwd(), filesToStage) {
3446
3282
  const filteredFiles = [];
3447
3283
  for (const filePath of filesToStage) {
3448
- if (fs11.existsSync(path8.join(cwd, filePath))) {
3284
+ if (fs10.existsSync(path7.join(cwd, filePath))) {
3449
3285
  filteredFiles.push(filePath);
3450
3286
  continue;
3451
3287
  }
@@ -3530,20 +3366,20 @@ Auto-committed by fullstack-cli`;
3530
3366
  }
3531
3367
 
3532
3368
  // src/utils/package-json.ts
3533
- import fs12 from "fs";
3534
- import path9 from "path";
3369
+ import fs11 from "fs";
3370
+ import path8 from "path";
3535
3371
  function readPackageJson(cwd = process.cwd()) {
3536
- const pkgPath = path9.join(cwd, "package.json");
3537
- if (!fs12.existsSync(pkgPath)) {
3372
+ const pkgPath = path8.join(cwd, "package.json");
3373
+ if (!fs11.existsSync(pkgPath)) {
3538
3374
  throw new Error(`package.json not found at ${pkgPath}`);
3539
3375
  }
3540
- const content = fs12.readFileSync(pkgPath, "utf-8");
3376
+ const content = fs11.readFileSync(pkgPath, "utf-8");
3541
3377
  return JSON.parse(content);
3542
3378
  }
3543
3379
  function writePackageJson(pkg2, cwd = process.cwd()) {
3544
- const pkgPath = path9.join(cwd, "package.json");
3380
+ const pkgPath = path8.join(cwd, "package.json");
3545
3381
  const content = JSON.stringify(pkg2, null, 2) + "\n";
3546
- fs12.writeFileSync(pkgPath, content, "utf-8");
3382
+ fs11.writeFileSync(pkgPath, content, "utf-8");
3547
3383
  }
3548
3384
  function removeUpgradeScript(pkg2) {
3549
3385
  if (!pkg2.scripts?.upgrade) {
@@ -3588,15 +3424,15 @@ function cleanupPackageJson(cwd = process.cwd()) {
3588
3424
  }
3589
3425
 
3590
3426
  // src/commands/upgrade/shared/utils.ts
3591
- import path10 from "path";
3592
- import fs13 from "fs";
3427
+ import path9 from "path";
3428
+ import fs12 from "fs";
3593
3429
  import { fileURLToPath as fileURLToPath4 } from "url";
3594
3430
  function getCliVersion() {
3595
3431
  try {
3596
3432
  const __filename = fileURLToPath4(import.meta.url);
3597
- const __dirname2 = path10.dirname(__filename);
3598
- const pkgPath = path10.resolve(__dirname2, "../../../package.json");
3599
- const pkgContent = fs13.readFileSync(pkgPath, "utf-8");
3433
+ const __dirname2 = path9.dirname(__filename);
3434
+ const pkgPath = path9.resolve(__dirname2, "../../../package.json");
3435
+ const pkgContent = fs12.readFileSync(pkgPath, "utf-8");
3600
3436
  const pkg2 = JSON.parse(pkgContent);
3601
3437
  return pkg2.version || "unknown";
3602
3438
  } catch {
@@ -3657,7 +3493,7 @@ async function run3(options = {}) {
3657
3493
  }
3658
3494
 
3659
3495
  // src/commands/upgrade/deps/run.handler.ts
3660
- import { spawnSync as spawnSync4 } from "child_process";
3496
+ import { spawnSync as spawnSync5 } from "child_process";
3661
3497
  import fs14 from "fs";
3662
3498
  import path11 from "path";
3663
3499
 
@@ -3820,11 +3656,240 @@ function resolveGrayscaleVersions(_cwd, configJson) {
3820
3656
  return versions;
3821
3657
  }
3822
3658
 
3659
+ // src/commands/upgrade/deps/drizzle-peer-migration.ts
3660
+ import { spawnSync as spawnSync4 } from "child_process";
3661
+ import fs13 from "fs";
3662
+ import path10 from "path";
3663
+ var DRIZZLE_SDKS = /* @__PURE__ */ new Set([
3664
+ "@lark-apaas/fullstack-nestjs-core",
3665
+ "@lark-apaas/nestjs-datapaas",
3666
+ "@lark-apaas/express-core",
3667
+ "@lark-apaas/express-datapaas"
3668
+ ]);
3669
+ var DEP_FIELDS = [
3670
+ "dependencies",
3671
+ "devDependencies",
3672
+ "optionalDependencies",
3673
+ "peerDependencies"
3674
+ ];
3675
+ var TRANSACTION_FILES = [
3676
+ "package.json",
3677
+ "package-lock.json",
3678
+ "npm-shrinkwrap.json"
3679
+ ];
3680
+ function readJson(file) {
3681
+ return JSON.parse(fs13.readFileSync(file, "utf8"));
3682
+ }
3683
+ function installedVersion(cwd, name) {
3684
+ const file = path10.join(cwd, "node_modules", name, "package.json");
3685
+ return fs13.existsSync(file) ? readJson(file).version : void 0;
3686
+ }
3687
+ function readSdkMetadata(cwd, name, spec) {
3688
+ const result = spawnSync4(
3689
+ "npm",
3690
+ [
3691
+ "view",
3692
+ `${name}@${spec}`,
3693
+ "version",
3694
+ "peerDependencies",
3695
+ "dist-tags",
3696
+ "--json"
3697
+ ],
3698
+ {
3699
+ cwd,
3700
+ encoding: "utf8",
3701
+ timeout: 3e4
3702
+ }
3703
+ );
3704
+ if (result.error || result.status !== 0) {
3705
+ throw new Error(
3706
+ `Cannot read Drizzle peer for ${name}@${spec}: ${result.error?.message || result.stderr}`
3707
+ );
3708
+ }
3709
+ const response = JSON.parse(result.stdout);
3710
+ let metadata;
3711
+ if (Array.isArray(response)) {
3712
+ const config = spawnSync4("npm", ["config", "get", "tag"], {
3713
+ cwd,
3714
+ encoding: "utf8",
3715
+ timeout: 3e4
3716
+ });
3717
+ if (config.error || config.status !== 0 || !config.stdout.trim()) {
3718
+ throw new Error(
3719
+ "Cannot determine the application npm tag; no files changed"
3720
+ );
3721
+ }
3722
+ const tag = config.stdout.trim();
3723
+ metadata = response.find((meta) => meta.version === meta["dist-tags"]?.[tag]) || response[response.length - 1];
3724
+ } else {
3725
+ metadata = response;
3726
+ }
3727
+ const peer = metadata?.peerDependencies?.["drizzle-orm"];
3728
+ if (!metadata?.version || !peer || !/^\d+\.\d+\.\d+$/.test(peer)) {
3729
+ throw new Error(
3730
+ `${name}@${spec} has no verifiable exact drizzle-orm peer; no files changed`
3731
+ );
3732
+ }
3733
+ return metadata;
3734
+ }
3735
+ function lockMatches(pkg2, lock, sdks, drizzleVersion) {
3736
+ if (lock.packages?.["node_modules/drizzle-orm"]?.version !== drizzleVersion)
3737
+ return false;
3738
+ for (const field of DEP_FIELDS) {
3739
+ for (const name of [...sdks.keys(), "drizzle-orm"]) {
3740
+ const spec = pkg2[field]?.[name];
3741
+ if (spec !== void 0) {
3742
+ const rootDeps = lock.packages?.[""]?.[field];
3743
+ if (rootDeps?.[name] !== spec) return false;
3744
+ }
3745
+ }
3746
+ }
3747
+ for (const [name, metadata] of sdks) {
3748
+ if (lock.packages?.[`node_modules/${name}`]?.version !== metadata.version)
3749
+ return false;
3750
+ }
3751
+ return true;
3752
+ }
3753
+ function runNpm(cwd, args) {
3754
+ console.log(`[fullstack-cli] npm ${args.join(" ")}`);
3755
+ const result = spawnSync4("npm", args, { cwd, stdio: "inherit" });
3756
+ if (result.error || result.status !== 0) {
3757
+ throw new Error(
3758
+ `npm ${args[0]} failed: ${result.error?.message || `exit ${result.status}`}`
3759
+ );
3760
+ }
3761
+ }
3762
+ function upgradeDrizzlePeers(options) {
3763
+ const { cwd, sdkTargets, npmArgs, dryRun, skipInstall } = options;
3764
+ if (![...sdkTargets.keys()].some((name) => DRIZZLE_SDKS.has(name)))
3765
+ return false;
3766
+ const pkgFile = path10.join(cwd, "package.json");
3767
+ const pkg2 = readJson(pkgFile);
3768
+ const lockFile = path10.join(
3769
+ cwd,
3770
+ fs13.existsSync(path10.join(cwd, "npm-shrinkwrap.json")) ? "npm-shrinkwrap.json" : "package-lock.json"
3771
+ );
3772
+ const beforeLock = fs13.existsSync(lockFile) ? readJson(lockFile) : {};
3773
+ const sdks = /* @__PURE__ */ new Map();
3774
+ for (const field of DEP_FIELDS) {
3775
+ for (const [name, spec] of Object.entries(pkg2[field] || {})) {
3776
+ if (!DRIZZLE_SDKS.has(name) || sdks.has(name)) continue;
3777
+ const target = sdkTargets.get(name) || beforeLock.packages?.[`node_modules/${name}`]?.version || installedVersion(cwd, name) || spec;
3778
+ sdks.set(name, readSdkMetadata(cwd, name, target));
3779
+ }
3780
+ }
3781
+ const peers = new Set(
3782
+ [...sdks.values()].map((meta) => meta.peerDependencies["drizzle-orm"])
3783
+ );
3784
+ if (peers.size !== 1) {
3785
+ throw new Error(
3786
+ `SDK Drizzle peers conflict; upgrade these SDKs together: ${[...sdks].map(
3787
+ ([name, meta]) => `${name}@${meta.version} \u2192 ${meta.peerDependencies["drizzle-orm"]}`
3788
+ ).join(", ")}`
3789
+ );
3790
+ }
3791
+ const drizzleVersion = [...peers][0];
3792
+ for (const [name, metadata] of sdks) {
3793
+ console.log(
3794
+ `[fullstack-cli] ${name} \u2192 ${metadata.version}${sdkTargets.has(name) ? "" : " (retained)"}`
3795
+ );
3796
+ }
3797
+ const fields = DEP_FIELDS.filter(
3798
+ (field) => pkg2[field]?.["drizzle-orm"] !== void 0
3799
+ );
3800
+ if (fields.length === 0) fields.push("dependencies");
3801
+ for (const field of fields) {
3802
+ console.log(
3803
+ `[fullstack-cli] ${field}.drizzle-orm: ${pkg2[field]?.["drizzle-orm"] || "(missing)"} \u2192 ${drizzleVersion}`
3804
+ );
3805
+ pkg2[field] ?? (pkg2[field] = {});
3806
+ pkg2[field]["drizzle-orm"] = drizzleVersion;
3807
+ }
3808
+ if (dryRun) {
3809
+ console.log(
3810
+ "[fullstack-cli] Dry run: SDK + Drizzle + lock migration; no files changed"
3811
+ );
3812
+ return true;
3813
+ }
3814
+ if (skipInstall && lockMatches(pkg2, beforeLock, sdks, drizzleVersion) && installedVersion(cwd, "drizzle-orm") === drizzleVersion && fields.every(
3815
+ (field) => readJson(pkgFile)[field]?.["drizzle-orm"] === drizzleVersion
3816
+ )) {
3817
+ console.log(
3818
+ "[fullstack-cli] SDK, Drizzle and lock already match; skip installation"
3819
+ );
3820
+ return true;
3821
+ }
3822
+ const snapshots = TRANSACTION_FILES.map((name) => {
3823
+ const file = path10.join(cwd, name);
3824
+ return {
3825
+ file,
3826
+ content: fs13.existsSync(file) ? fs13.readFileSync(file) : null
3827
+ };
3828
+ });
3829
+ const resolutionArgs = [...npmArgs];
3830
+ if (resolutionArgs[0] === "install") {
3831
+ for (const [name, meta] of sdks) {
3832
+ if (sdkTargets.has(name) && beforeLock.packages?.[`node_modules/${name}`]?.version !== meta.version && !resolutionArgs.some((arg) => arg.startsWith(`${name}@`))) {
3833
+ resolutionArgs.push(`${name}@${meta.version}`);
3834
+ }
3835
+ }
3836
+ }
3837
+ try {
3838
+ fs13.writeFileSync(pkgFile, `${JSON.stringify(pkg2, null, 2)}
3839
+ `);
3840
+ runNpm(cwd, [
3841
+ ...resolutionArgs,
3842
+ "--package-lock-only",
3843
+ "--ignore-scripts",
3844
+ "--no-audit",
3845
+ "--no-fund"
3846
+ ]);
3847
+ const resolvedPkg = readJson(pkgFile);
3848
+ if (!lockMatches(
3849
+ resolvedPkg,
3850
+ readJson(lockFile),
3851
+ sdks,
3852
+ drizzleVersion
3853
+ )) {
3854
+ throw new Error(
3855
+ "Resolved SDK/Drizzle versions or lock root do not match the migration plan"
3856
+ );
3857
+ }
3858
+ runNpm(cwd, ["install", "--no-audit", "--no-fund"]);
3859
+ if (!lockMatches(
3860
+ readJson(pkgFile),
3861
+ readJson(lockFile),
3862
+ sdks,
3863
+ drizzleVersion
3864
+ ) || installedVersion(cwd, "drizzle-orm") !== drizzleVersion || [...sdks].some(
3865
+ ([name, meta]) => installedVersion(cwd, name) !== meta.version
3866
+ )) {
3867
+ throw new Error(
3868
+ "Installed SDK/Drizzle tree does not match the resolved lock"
3869
+ );
3870
+ }
3871
+ } catch (error) {
3872
+ for (const snapshot of snapshots) {
3873
+ if (snapshot.content !== null)
3874
+ fs13.writeFileSync(snapshot.file, snapshot.content);
3875
+ else if (fs13.existsSync(snapshot.file)) fs13.unlinkSync(snapshot.file);
3876
+ }
3877
+ throw new Error(
3878
+ `Drizzle migration failed; package.json and npm lockfiles restored. Run npm ci before retrying if installation started. ${error instanceof Error ? error.message : String(error)}`
3879
+ );
3880
+ }
3881
+ return true;
3882
+ }
3883
+
3823
3884
  // src/commands/upgrade/deps/run.handler.ts
3824
3885
  function parseSemver(version) {
3825
3886
  const match = version.match(/^(\d+)\.(\d+)\.(\d+)/);
3826
3887
  if (!match) return null;
3827
- return [parseInt(match[1], 10), parseInt(match[2], 10), parseInt(match[3], 10)];
3888
+ return [
3889
+ parseInt(match[1], 10),
3890
+ parseInt(match[2], 10),
3891
+ parseInt(match[3], 10)
3892
+ ];
3828
3893
  }
3829
3894
  function compareSemver(a, b) {
3830
3895
  const va = parseSemver(a);
@@ -3872,13 +3937,28 @@ function findLarkAapaasPackages(cwd, filterPackages) {
3872
3937
  }
3873
3938
  return packages;
3874
3939
  }
3875
- function upgradePackages(packages, version, cwd) {
3940
+ function upgradePackages(packages, version, cwd, dryRun = false) {
3941
+ const pkg2 = readPackageJson(cwd);
3942
+ const sdkTargets = new Map(
3943
+ packages.map((name) => [
3944
+ name,
3945
+ version || pkg2.dependencies?.[name] || pkg2.devDependencies?.[name] || "latest"
3946
+ ])
3947
+ );
3948
+ const npmArgs = version ? ["install", ...packages.map((name) => `${name}@${version}`)] : ["update", ...packages];
3949
+ if (upgradeDrizzlePeers({ cwd, sdkTargets, npmArgs, dryRun })) return;
3950
+ if (dryRun) {
3951
+ packages.forEach(
3952
+ (name) => console.log(` - ${name} -> ${version || "latest compatible"}`)
3953
+ );
3954
+ return;
3955
+ }
3876
3956
  if (version) {
3877
3957
  console.log(`[fullstack-cli] Upgrading to version ${version}...`);
3878
- packages.forEach((pkg2) => {
3879
- const target = `${pkg2}@${version}`;
3958
+ packages.forEach((pkg3) => {
3959
+ const target = `${pkg3}@${version}`;
3880
3960
  console.log(`[fullstack-cli] Installing ${target}...`);
3881
- const result = spawnSync4("npm", ["install", target], {
3961
+ const result = spawnSync5("npm", ["install", target], {
3882
3962
  cwd,
3883
3963
  stdio: "inherit"
3884
3964
  });
@@ -3888,48 +3968,66 @@ function upgradePackages(packages, version, cwd) {
3888
3968
  });
3889
3969
  } else {
3890
3970
  console.log("[fullstack-cli] Upgrading to latest compatible versions...");
3891
- packages.forEach((pkg2) => {
3892
- console.log(`[fullstack-cli] Updating ${pkg2}...`);
3893
- const result = spawnSync4("npm", ["update", pkg2], {
3971
+ packages.forEach((pkg3) => {
3972
+ console.log(`[fullstack-cli] Updating ${pkg3}...`);
3973
+ const result = spawnSync5("npm", ["update", pkg3], {
3894
3974
  cwd,
3895
3975
  stdio: "inherit"
3896
3976
  });
3897
3977
  if (result.error || result.status !== 0) {
3898
- throw new Error(`Failed to update ${pkg2}`);
3978
+ throw new Error(`Failed to update ${pkg3}`);
3899
3979
  }
3900
3980
  });
3901
3981
  }
3902
3982
  }
3903
3983
  function installGrayscaleVersions(packages, grayscaleVersions, cwd, dryRun, mode) {
3904
3984
  const upgradePlan = [];
3985
+ const sdkTargets = /* @__PURE__ */ new Map();
3905
3986
  for (const pkg2 of packages) {
3906
3987
  const version = grayscaleVersions.get(pkg2);
3907
3988
  if (version) {
3989
+ sdkTargets.set(pkg2, version);
3908
3990
  let current = "";
3909
3991
  try {
3910
- const installedPkgPath = path11.join(cwd, "node_modules", pkg2, "package.json");
3911
- const installedPkg = JSON.parse(fs14.readFileSync(installedPkgPath, "utf-8"));
3992
+ const installedPkgPath = path11.join(
3993
+ cwd,
3994
+ "node_modules",
3995
+ pkg2,
3996
+ "package.json"
3997
+ );
3998
+ const installedPkg = JSON.parse(
3999
+ fs14.readFileSync(installedPkgPath, "utf-8")
4000
+ );
3912
4001
  current = installedPkg.version || "";
3913
4002
  } catch (err) {
3914
4003
  const code = err?.code;
3915
4004
  if (code !== "ENOENT") {
3916
- console.warn(`[fullstack-cli] Failed to read installed version of ${pkg2}: ${err instanceof Error ? err.message : String(err)}`);
4005
+ console.warn(
4006
+ `[fullstack-cli] Failed to read installed version of ${pkg2}: ${err instanceof Error ? err.message : String(err)}`
4007
+ );
3917
4008
  }
3918
4009
  }
3919
4010
  if (mode === "destroy") {
3920
4011
  if (!isRangeVersion(version) && current === version) {
3921
- console.log(`[fullstack-cli] ${pkg2}@${version} (already installed, skip)`);
4012
+ console.log(
4013
+ `[fullstack-cli] ${pkg2}@${version} (already installed, skip)`
4014
+ );
3922
4015
  continue;
3923
4016
  }
3924
4017
  } else {
3925
4018
  if (isRangeVersion(version)) {
3926
4019
  if (current && satisfiesCaret(current, version)) {
3927
- console.log(`[fullstack-cli] ${pkg2}@${current} satisfies ${version} (skip)`);
4020
+ sdkTargets.set(pkg2, current);
4021
+ console.log(
4022
+ `[fullstack-cli] ${pkg2}@${current} satisfies ${version} (skip)`
4023
+ );
3928
4024
  continue;
3929
4025
  }
3930
4026
  } else {
3931
4027
  if (current === version) {
3932
- console.log(`[fullstack-cli] ${pkg2}@${version} (already installed, skip)`);
4028
+ console.log(
4029
+ `[fullstack-cli] ${pkg2}@${version} (already installed, skip)`
4030
+ );
3933
4031
  continue;
3934
4032
  }
3935
4033
  }
@@ -3937,11 +4035,26 @@ function installGrayscaleVersions(packages, grayscaleVersions, cwd, dryRun, mode
3937
4035
  upgradePlan.push({ pkg: pkg2, version, current });
3938
4036
  }
3939
4037
  }
4038
+ if (upgradeDrizzlePeers({
4039
+ cwd,
4040
+ sdkTargets,
4041
+ npmArgs: [
4042
+ "install",
4043
+ ...upgradePlan.map(({ pkg: pkg2, version }) => `${pkg2}@${version}`)
4044
+ ],
4045
+ dryRun,
4046
+ skipInstall: upgradePlan.length === 0
4047
+ }))
4048
+ return;
3940
4049
  if (upgradePlan.length === 0) {
3941
- console.log("[fullstack-cli] No grayscale versions matched current packages");
4050
+ console.log(
4051
+ "[fullstack-cli] No grayscale versions matched current packages"
4052
+ );
3942
4053
  return;
3943
4054
  }
3944
- console.log(`[fullstack-cli] Grayscale upgrade plan (${upgradePlan.length} package(s)):`);
4055
+ console.log(
4056
+ `[fullstack-cli] Grayscale upgrade plan (${upgradePlan.length} package(s)):`
4057
+ );
3945
4058
  upgradePlan.forEach(({ pkg: pkg2, version, current }) => {
3946
4059
  console.log(` - ${pkg2} ${current} -> ${version}`);
3947
4060
  });
@@ -3951,61 +4064,98 @@ function installGrayscaleVersions(packages, grayscaleVersions, cwd, dryRun, mode
3951
4064
  }
3952
4065
  const targets = upgradePlan.map(({ pkg: pkg2, version }) => `${pkg2}@${version}`);
3953
4066
  console.log(`[fullstack-cli] Installing ${targets.join(" ")}...`);
3954
- const result = spawnSync4("npm", ["install", ...targets], {
4067
+ const result = spawnSync5("npm", ["install", ...targets], {
3955
4068
  cwd,
3956
4069
  stdio: "inherit"
3957
4070
  });
3958
4071
  if (result.error || result.status !== 0) {
3959
- console.warn(`[fullstack-cli] npm install failed: ${result.error?.message ?? `exit ${result.status}`}`);
4072
+ throw new Error(
4073
+ `npm install failed: ${result.error?.message ?? `exit ${result.status}`}`
4074
+ );
3960
4075
  }
3961
4076
  }
3962
4077
  async function run4(options = {}) {
3963
4078
  const cwd = process.env.INIT_CWD || process.cwd();
3964
4079
  console.log("[fullstack-cli] Starting dependencies upgrade...");
3965
4080
  try {
3966
- console.log("[fullstack-cli] Step 1/3: Scanning @lark-apaas dependencies...");
4081
+ console.log(
4082
+ "[fullstack-cli] Step 1/3: Scanning @lark-apaas dependencies..."
4083
+ );
3967
4084
  const packages = findLarkAapaasPackages(cwd, options.packages);
3968
4085
  if (packages.length === 0) {
3969
4086
  console.log("[fullstack-cli] No @lark-apaas packages found");
3970
4087
  return;
3971
4088
  }
3972
- console.log(`[fullstack-cli] Found ${packages.length} @lark-apaas package(s):`);
4089
+ console.log(
4090
+ `[fullstack-cli] Found ${packages.length} @lark-apaas package(s):`
4091
+ );
3973
4092
  packages.forEach((p) => console.log(` - ${p}`));
3974
4093
  if (options.skipGrayscale) {
3975
- console.log("[fullstack-cli] Step 2/3: Skipping grayscale check (--skip-grayscale)");
4094
+ console.log(
4095
+ "[fullstack-cli] Step 2/3: Skipping grayscale check (--skip-grayscale)"
4096
+ );
3976
4097
  } else if (options.version) {
3977
- console.log("[fullstack-cli] Step 2/3: Skipping grayscale check (explicit --version provided)");
4098
+ console.log(
4099
+ "[fullstack-cli] Step 2/3: Skipping grayscale check (explicit --version provided)"
4100
+ );
3978
4101
  } else if (!options.grayscaleConfig) {
3979
- console.log("[fullstack-cli] Step 2/3: No grayscale config, falling back to default upgrade");
4102
+ console.log(
4103
+ "[fullstack-cli] Step 2/3: No grayscale config, falling back to default upgrade"
4104
+ );
3980
4105
  } else {
3981
4106
  console.log("[fullstack-cli] Step 2/3: Checking grayscale config...");
4107
+ let grayscaleVersions;
3982
4108
  try {
3983
- const grayscaleVersions = resolveGrayscaleVersions(cwd, options.grayscaleConfig);
3984
- if (grayscaleVersions) {
3985
- console.log("[fullstack-cli] Step 3/3: Applying grayscale versions...");
3986
- installGrayscaleVersions(packages, grayscaleVersions, cwd, !!options.dryRun, options.mode || "rebuild");
3987
- if (!options.dryRun) {
3988
- console.log(`[fullstack-cli] \u2713 Successfully upgraded ${packages.length} package(s) via grayscale`);
3989
- console.log("[fullstack-cli] Dependencies upgrade completed successfully \u2705");
3990
- }
3991
- } else {
3992
- console.log("[fullstack-cli] Grayscale config provided but not available, skip upgrade");
3993
- }
4109
+ grayscaleVersions = resolveGrayscaleVersions(
4110
+ cwd,
4111
+ options.grayscaleConfig
4112
+ );
3994
4113
  } catch (error) {
3995
4114
  const msg = error instanceof Error ? error.message : String(error);
3996
- console.warn(`[fullstack-cli] Grayscale check failed: ${msg}, skip upgrade`);
4115
+ console.warn(
4116
+ `[fullstack-cli] Grayscale check failed: ${msg}, skip upgrade`
4117
+ );
4118
+ return;
4119
+ }
4120
+ if (grayscaleVersions) {
4121
+ console.log("[fullstack-cli] Step 3/3: Applying grayscale versions...");
4122
+ installGrayscaleVersions(
4123
+ packages,
4124
+ grayscaleVersions,
4125
+ cwd,
4126
+ !!options.dryRun,
4127
+ options.mode || "rebuild"
4128
+ );
4129
+ if (!options.dryRun) {
4130
+ console.log(
4131
+ `[fullstack-cli] \u2713 Successfully upgraded ${packages.length} package(s) via grayscale`
4132
+ );
4133
+ console.log(
4134
+ "[fullstack-cli] Dependencies upgrade completed successfully \u2705"
4135
+ );
4136
+ }
4137
+ } else {
4138
+ console.log(
4139
+ "[fullstack-cli] Grayscale config provided but not available, skip upgrade"
4140
+ );
3997
4141
  }
3998
4142
  return;
3999
4143
  }
4000
4144
  if (options.dryRun) {
4001
- console.log("[fullstack-cli] Dry run mode: would upgrade via npm update (no grayscale)");
4002
- packages.forEach((p) => console.log(` - ${p} -> ${options.version || "latest compatible"}`));
4145
+ console.log(
4146
+ "[fullstack-cli] Dry run mode: would upgrade via npm update (no grayscale)"
4147
+ );
4148
+ upgradePackages(packages, options.version, cwd, true);
4003
4149
  return;
4004
4150
  }
4005
4151
  console.log("[fullstack-cli] Step 3/3: Upgrading packages...");
4006
4152
  upgradePackages(packages, options.version, cwd);
4007
- console.log(`[fullstack-cli] \u2713 Successfully upgraded ${packages.length} package(s)`);
4008
- console.log("[fullstack-cli] Dependencies upgrade completed successfully \u2705");
4153
+ console.log(
4154
+ `[fullstack-cli] \u2713 Successfully upgraded ${packages.length} package(s)`
4155
+ );
4156
+ console.log(
4157
+ "[fullstack-cli] Dependencies upgrade completed successfully \u2705"
4158
+ );
4009
4159
  } catch (error) {
4010
4160
  const message = error instanceof Error ? error.message : String(error);
4011
4161
  console.error("[fullstack-cli] Failed to upgrade dependencies:", message);
@@ -4018,14 +4168,30 @@ var depsCommand = {
4018
4168
  name: "deps",
4019
4169
  description: "Upgrade @lark-apaas dependencies",
4020
4170
  register(parentCommand) {
4021
- parentCommand.command(this.name).description(this.description).option("--version <version>", "Upgrade to specific version").option("--packages <packages>", "Only upgrade specific packages (comma-separated)").option("--skip-grayscale", "Skip grayscale version check").option("--grayscale-config <json>", "Grayscale config JSON (injected by sandbox_console)").option("--dry-run", "Show upgrade plan without executing").option("--mode <mode>", "Execution mode: rebuild (default) or destroy", "rebuild").action(async (options) => {
4022
- await run4(options);
4171
+ parentCommand.command(this.name).description(this.description).option("--version <version>", "Upgrade to specific version").option(
4172
+ "--target-version <version>",
4173
+ "Upgrade SDKs to specific version (avoids global --version)"
4174
+ ).option(
4175
+ "--packages <packages>",
4176
+ "Only upgrade specific packages (comma-separated)"
4177
+ ).option("--skip-grayscale", "Skip grayscale version check").option(
4178
+ "--grayscale-config <json>",
4179
+ "Grayscale config JSON (injected by sandbox_console)"
4180
+ ).option("--dry-run", "Show upgrade plan without executing").option(
4181
+ "--mode <mode>",
4182
+ "Execution mode: rebuild (default) or destroy",
4183
+ "rebuild"
4184
+ ).action(async (options) => {
4185
+ await run4({
4186
+ ...options,
4187
+ version: options.targetVersion ?? options.version
4188
+ });
4023
4189
  });
4024
4190
  }
4025
4191
  };
4026
4192
 
4027
4193
  // src/commands/upgrade/global-deps/run.handler.ts
4028
- import { spawnSync as spawnSync5 } from "child_process";
4194
+ import { spawnSync as spawnSync6 } from "child_process";
4029
4195
  import fs15 from "fs";
4030
4196
  import path12 from "path";
4031
4197
  var MANAGED_GLOBAL_CLIS = [
@@ -4104,7 +4270,7 @@ async function run5(options = {}) {
4104
4270
  npmArgs.push("--registry", options.registry);
4105
4271
  }
4106
4272
  console.log(`[fullstack-cli] Running: npm ${npmArgs.join(" ")}`);
4107
- const result = spawnSync5("npm", npmArgs, { stdio: "inherit" });
4273
+ const result = spawnSync6("npm", npmArgs, { stdio: "inherit" });
4108
4274
  if (result.error || result.status !== 0) {
4109
4275
  console.warn(
4110
4276
  `[fullstack-cli] npm install -g failed: ${result.error?.message ?? `exit ${result.status}`}`
@@ -4142,87 +4308,174 @@ var upgradeCommand = {
4142
4308
  }
4143
4309
  };
4144
4310
 
4145
- // src/commands/action-plugin/install-engine.ts
4146
- import fs23 from "fs";
4147
- import path20 from "path";
4148
- import { spawnSync as spawnSync7 } from "child_process";
4149
-
4150
- // src/commands/action-plugin/plugin-files.ts
4311
+ // src/commands/action-plugin/utils.ts
4151
4312
  import fs16 from "fs";
4152
- import os from "os";
4153
4313
  import path13 from "path";
4154
- import { execFileSync } from "child_process";
4155
- function createStagingRoot() {
4156
- return fs16.mkdtempSync(path13.join(os.tmpdir(), "fullstack-cli-action-plugin-"));
4157
- }
4158
- function replaceDirectory(sourcePath, targetPath) {
4159
- fs16.mkdirSync(path13.dirname(targetPath), { recursive: true });
4160
- const incomingPath = `${targetPath}.fullstack-cli-${process.pid}-${Date.now()}`;
4161
- try {
4162
- if (fs16.existsSync(incomingPath)) {
4163
- fs16.rmSync(incomingPath, { recursive: true, force: true });
4164
- }
4165
- fs16.cpSync(sourcePath, incomingPath, { recursive: true, force: true });
4166
- if (fs16.existsSync(targetPath)) {
4167
- fs16.rmSync(targetPath, { recursive: true, force: true });
4168
- }
4169
- fs16.renameSync(incomingPath, targetPath);
4170
- } finally {
4171
- if (fs16.existsSync(incomingPath)) {
4172
- fs16.rmSync(incomingPath, { recursive: true, force: true });
4173
- }
4174
- }
4175
- }
4176
- function extractTgzToDirectory(tgzPath, targetPath) {
4177
- fs16.mkdirSync(path13.dirname(targetPath), { recursive: true });
4178
- const unpackRoot = fs16.mkdtempSync(
4179
- path13.join(path13.dirname(targetPath), "unpack-")
4180
- );
4181
- try {
4182
- execFileSync("tar", ["-xzf", tgzPath, "-C", unpackRoot], { stdio: "pipe" });
4183
- const packageDirectory = path13.join(unpackRoot, "package");
4184
- let extractedPath = packageDirectory;
4185
- if (!fs16.existsSync(packageDirectory)) {
4186
- const entries = fs16.readdirSync(unpackRoot);
4187
- if (entries.length !== 1) throw new Error("Unexpected tgz structure");
4188
- extractedPath = path13.join(unpackRoot, entries[0]);
4189
- }
4190
- if (fs16.existsSync(targetPath)) {
4191
- fs16.rmSync(targetPath, { recursive: true, force: true });
4192
- }
4193
- fs16.renameSync(extractedPath, targetPath);
4194
- } finally {
4195
- if (fs16.existsSync(unpackRoot)) {
4196
- fs16.rmSync(unpackRoot, { recursive: true, force: true });
4197
- }
4198
- }
4199
- }
4200
- function readPluginManifest(pluginPath) {
4201
- const manifestPath = path13.join(pluginPath, "package.json");
4202
- if (!fs16.existsSync(manifestPath)) {
4203
- throw new Error(`Plugin manifest not found: ${manifestPath}`);
4204
- }
4205
- const manifest = JSON.parse(
4206
- fs16.readFileSync(manifestPath, "utf-8")
4207
- );
4208
- if (!manifest.name || !manifest.version) {
4209
- throw new Error(`Invalid plugin manifest: ${manifestPath}`);
4210
- }
4211
- return manifest;
4212
- }
4213
- function assertPluginIdentity(pluginPath, expectedName, expectedVersion) {
4214
- const manifest = readPluginManifest(pluginPath);
4215
- if (manifest.name !== expectedName || manifest.version !== expectedVersion) {
4314
+ import { spawnSync as spawnSync7, execSync as execSync2 } from "child_process";
4315
+ function parsePluginName(input) {
4316
+ const match = input.match(/^(@[^/]+\/[^@]+)(?:@(.+))?$/);
4317
+ if (!match) {
4216
4318
  throw new Error(
4217
- `Plugin identity mismatch: expected ${expectedName}@${expectedVersion}, got ${manifest.name}@${manifest.version}`
4319
+ `Invalid plugin name format: ${input}. Expected format: @scope/name or @scope/name@version`
4218
4320
  );
4219
4321
  }
4220
- return manifest;
4221
- }
4222
-
4223
- // src/commands/action-plugin/plugin-preparation.ts
4224
- import fs20 from "fs";
4225
- import path17 from "path";
4322
+ return {
4323
+ name: match[1],
4324
+ version: match[2] || "latest"
4325
+ };
4326
+ }
4327
+ function getProjectRoot() {
4328
+ return process.cwd();
4329
+ }
4330
+ function getPackageJsonPath() {
4331
+ return path13.join(getProjectRoot(), "package.json");
4332
+ }
4333
+ function getPluginPath(pluginName) {
4334
+ return path13.join(getProjectRoot(), "node_modules", pluginName);
4335
+ }
4336
+ function readPackageJson2() {
4337
+ const pkgPath = getPackageJsonPath();
4338
+ if (!fs16.existsSync(pkgPath)) {
4339
+ throw new Error("package.json not found in current directory");
4340
+ }
4341
+ try {
4342
+ const content = fs16.readFileSync(pkgPath, "utf-8");
4343
+ return JSON.parse(content);
4344
+ } catch {
4345
+ throw new Error("Failed to parse package.json");
4346
+ }
4347
+ }
4348
+ function writePackageJson2(pkg2) {
4349
+ const pkgPath = getPackageJsonPath();
4350
+ fs16.writeFileSync(pkgPath, JSON.stringify(pkg2, null, 2) + "\n", "utf-8");
4351
+ }
4352
+ function readActionPlugins() {
4353
+ const pkg2 = readPackageJson2();
4354
+ return pkg2.actionPlugins || {};
4355
+ }
4356
+ function writeActionPlugins(plugins) {
4357
+ const pkg2 = readPackageJson2();
4358
+ pkg2.actionPlugins = plugins;
4359
+ writePackageJson2(pkg2);
4360
+ }
4361
+ function isPluginInstalled(pluginName) {
4362
+ const plugins = readActionPlugins();
4363
+ return pluginName in plugins;
4364
+ }
4365
+ function getInstalledPluginVersion(pluginName) {
4366
+ const plugins = readActionPlugins();
4367
+ return plugins[pluginName] || null;
4368
+ }
4369
+ function npmInstall(tgzPath) {
4370
+ console.log(`[action-plugin] Running npm install ${tgzPath}...`);
4371
+ const result = spawnSync7("npm", ["install", tgzPath, "--no-save", "--no-package-lock", "--ignore-scripts"], {
4372
+ cwd: getProjectRoot(),
4373
+ stdio: "inherit"
4374
+ });
4375
+ if (result.error) {
4376
+ throw new Error(`npm install failed: ${result.error.message}`);
4377
+ }
4378
+ if (result.status !== 0) {
4379
+ throw new Error(`npm install failed with exit code ${result.status}`);
4380
+ }
4381
+ }
4382
+ function getPackageVersion(pluginName) {
4383
+ const pkgJsonPath = path13.join(getPluginPath(pluginName), "package.json");
4384
+ if (!fs16.existsSync(pkgJsonPath)) {
4385
+ return null;
4386
+ }
4387
+ try {
4388
+ const content = fs16.readFileSync(pkgJsonPath, "utf-8");
4389
+ const pkg2 = JSON.parse(content);
4390
+ return pkg2.version || null;
4391
+ } catch {
4392
+ return null;
4393
+ }
4394
+ }
4395
+ function readPluginPackageJson(pluginPath) {
4396
+ const pkgJsonPath = path13.join(pluginPath, "package.json");
4397
+ if (!fs16.existsSync(pkgJsonPath)) {
4398
+ return null;
4399
+ }
4400
+ try {
4401
+ const content = fs16.readFileSync(pkgJsonPath, "utf-8");
4402
+ return JSON.parse(content);
4403
+ } catch {
4404
+ return null;
4405
+ }
4406
+ }
4407
+ function extractTgzToNodeModules(tgzPath, pluginName) {
4408
+ const nodeModulesPath = path13.join(getProjectRoot(), "node_modules");
4409
+ const targetDir = path13.join(nodeModulesPath, pluginName);
4410
+ const scopeDir = path13.dirname(targetDir);
4411
+ if (!fs16.existsSync(scopeDir)) {
4412
+ fs16.mkdirSync(scopeDir, { recursive: true });
4413
+ }
4414
+ if (fs16.existsSync(targetDir)) {
4415
+ fs16.rmSync(targetDir, { recursive: true });
4416
+ }
4417
+ const tempDir = path13.join(nodeModulesPath, ".cache", "fullstack-cli", "extract-temp");
4418
+ if (fs16.existsSync(tempDir)) {
4419
+ fs16.rmSync(tempDir, { recursive: true });
4420
+ }
4421
+ fs16.mkdirSync(tempDir, { recursive: true });
4422
+ try {
4423
+ execSync2(`tar -xzf "${tgzPath}" -C "${tempDir}"`, { stdio: "pipe" });
4424
+ const extractedDir = path13.join(tempDir, "package");
4425
+ if (fs16.existsSync(extractedDir)) {
4426
+ fs16.renameSync(extractedDir, targetDir);
4427
+ } else {
4428
+ const files = fs16.readdirSync(tempDir);
4429
+ if (files.length === 1) {
4430
+ fs16.renameSync(path13.join(tempDir, files[0]), targetDir);
4431
+ } else {
4432
+ throw new Error("Unexpected tgz structure");
4433
+ }
4434
+ }
4435
+ return targetDir;
4436
+ } finally {
4437
+ if (fs16.existsSync(tempDir)) {
4438
+ fs16.rmSync(tempDir, { recursive: true });
4439
+ }
4440
+ }
4441
+ }
4442
+ function checkMissingPeerDeps(peerDeps) {
4443
+ if (!peerDeps || Object.keys(peerDeps).length === 0) {
4444
+ return [];
4445
+ }
4446
+ const missing = [];
4447
+ const nodeModulesPath = path13.join(getProjectRoot(), "node_modules");
4448
+ for (const [depName, _version] of Object.entries(peerDeps)) {
4449
+ const depPath = path13.join(nodeModulesPath, depName);
4450
+ if (!fs16.existsSync(depPath)) {
4451
+ missing.push(depName);
4452
+ }
4453
+ }
4454
+ return missing;
4455
+ }
4456
+ function installMissingDeps(deps) {
4457
+ if (deps.length === 0) {
4458
+ return;
4459
+ }
4460
+ console.log(`[action-plugin] Installing missing dependencies: ${deps.join(", ")}`);
4461
+ const result = spawnSync7("npm", ["install", ...deps, "--no-save", "--no-package-lock"], {
4462
+ cwd: getProjectRoot(),
4463
+ stdio: "inherit"
4464
+ });
4465
+ if (result.error) {
4466
+ throw new Error(`npm install failed: ${result.error.message}`);
4467
+ }
4468
+ if (result.status !== 0) {
4469
+ throw new Error(`npm install failed with exit code ${result.status}`);
4470
+ }
4471
+ }
4472
+ function removePluginDirectory(pluginName) {
4473
+ const pluginPath = getPluginPath(pluginName);
4474
+ if (fs16.existsSync(pluginPath)) {
4475
+ fs16.rmSync(pluginPath, { recursive: true });
4476
+ console.log(`[action-plugin] Removed ${pluginName}`);
4477
+ }
4478
+ }
4226
4479
 
4227
4480
  // src/commands/action-plugin/api-client.ts
4228
4481
  import { HttpClient as HttpClient2 } from "@lark-apaas/http-client";
@@ -4349,1609 +4602,118 @@ async function downloadPlugin(pluginKey, requestedVersion) {
4349
4602
  pluginInfo
4350
4603
  };
4351
4604
  }
4605
+ function cleanupTempFile(tgzPath) {
4606
+ }
4352
4607
  function getCachePath(pluginKey, version) {
4353
4608
  ensureCacheDir();
4354
4609
  const safeKey = pluginKey.replace(/[/@]/g, "_");
4355
- const filename = `${safeKey}@${version}.tgz`;
4356
- return path14.join(getPluginCacheDir(), filename);
4357
- }
4358
- function hasCachedPlugin(pluginKey, version) {
4359
- const cachePath = getCachePath(pluginKey, version);
4360
- return fs17.existsSync(cachePath);
4361
- }
4362
- function listCachedPlugins() {
4363
- const cacheDir = getPluginCacheDir();
4364
- if (!fs17.existsSync(cacheDir)) {
4365
- return [];
4366
- }
4367
- const files = fs17.readdirSync(cacheDir);
4368
- const result = [];
4369
- for (const file of files) {
4370
- if (!file.endsWith(".tgz")) continue;
4371
- const match = file.match(/^(.+)@(.+)\.tgz$/);
4372
- if (!match) continue;
4373
- const [, rawName, version] = match;
4374
- const name = rawName.replace(/^_/, "@").replace(/_/, "/");
4375
- const filePath = path14.join(cacheDir, file);
4376
- const stat = fs17.statSync(filePath);
4377
- result.push({
4378
- name,
4379
- version,
4380
- filePath,
4381
- size: stat.size,
4382
- mtime: stat.mtime
4383
- });
4384
- }
4385
- return result;
4386
- }
4387
- function cleanAllCache() {
4388
- const cacheDir = getPluginCacheDir();
4389
- if (!fs17.existsSync(cacheDir)) {
4390
- return 0;
4391
- }
4392
- const files = fs17.readdirSync(cacheDir);
4393
- let count = 0;
4394
- for (const file of files) {
4395
- if (file.endsWith(".tgz")) {
4396
- fs17.unlinkSync(path14.join(cacheDir, file));
4397
- count++;
4398
- }
4399
- }
4400
- return count;
4401
- }
4402
- function cleanPluginCache(pluginKey, version) {
4403
- const cacheDir = getPluginCacheDir();
4404
- if (!fs17.existsSync(cacheDir)) {
4405
- return 0;
4406
- }
4407
- const safeKey = pluginKey.replace(/[/@]/g, "_");
4408
- const files = fs17.readdirSync(cacheDir);
4409
- let count = 0;
4410
- for (const file of files) {
4411
- if (version) {
4412
- if (file === `${safeKey}@${version}.tgz`) {
4413
- fs17.unlinkSync(path14.join(cacheDir, file));
4414
- count++;
4415
- }
4416
- } else {
4417
- if (file.startsWith(`${safeKey}@`) && file.endsWith(".tgz")) {
4418
- fs17.unlinkSync(path14.join(cacheDir, file));
4419
- count++;
4420
- }
4421
- }
4422
- }
4423
- return count;
4424
- }
4425
-
4426
- // src/commands/action-plugin/graph-state.ts
4427
- import fs18 from "fs";
4428
- import path15 from "path";
4429
- import { createRequire as createRequire2 } from "module";
4430
- var ACTION_PLUGIN_STORE = ".action-plugins";
4431
- var ACTION_PLUGIN_GITIGNORE_ENTRY = `${ACTION_PLUGIN_STORE}/`;
4432
- function validatePluginName(name) {
4433
- if (!/^@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*$/i.test(name)) {
4434
- throw new Error(`Invalid scoped plugin name: ${name}`);
4435
- }
4436
- }
4437
- function resolveProjectRoot(projectRoot) {
4438
- const resolved = fs18.realpathSync(projectRoot);
4439
- if (!fs18.statSync(resolved).isDirectory()) {
4440
- throw new Error(`Project root is not a directory: ${projectRoot}`);
4441
- }
4442
- return resolved;
4443
- }
4444
- function isWithin(root, candidate) {
4445
- const relative = path15.relative(root, candidate);
4446
- return relative === "" || !relative.startsWith(`..${path15.sep}`) && relative !== ".." && !path15.isAbsolute(relative);
4447
- }
4448
- function assertProjectPath(projectRoot, targetPath) {
4449
- const root = resolveProjectRoot(projectRoot);
4450
- const resolvedTarget = path15.resolve(targetPath);
4451
- if (!isWithin(root, resolvedTarget)) {
4452
- throw new Error(`Action plugin path escapes project root: ${targetPath}`);
4453
- }
4454
- let existing = resolvedTarget;
4455
- const targetStats = lstatOrNull(existing);
4456
- if (targetStats?.isSymbolicLink()) {
4457
- existing = path15.resolve(path15.dirname(existing), fs18.readlinkSync(existing));
4458
- if (!isWithin(root, existing)) {
4459
- throw new Error(`Action plugin link escapes project root: ${targetPath}`);
4460
- }
4461
- }
4462
- while (!lstatOrNull(existing)) {
4463
- const parent = path15.dirname(existing);
4464
- if (parent === existing) break;
4465
- existing = parent;
4466
- }
4467
- const realExisting = fs18.realpathSync(existing);
4468
- if (!isWithin(root, realExisting)) {
4469
- throw new Error(
4470
- `Action plugin path resolves outside project root: ${targetPath}`
4471
- );
4472
- }
4473
- }
4474
- function lstatOrNull(targetPath) {
4475
- try {
4476
- return fs18.lstatSync(targetPath);
4477
- } catch (error) {
4478
- if (error.code === "ENOENT") return null;
4479
- throw error;
4480
- }
4481
- }
4482
- function managedRootPath(projectRoot) {
4483
- return path15.join(projectRoot, ACTION_PLUGIN_STORE);
4484
- }
4485
- function managedPluginPath(projectRoot, pluginName) {
4486
- validatePluginName(pluginName);
4487
- const result = path15.join(
4488
- managedRootPath(projectRoot),
4489
- "node_modules",
4490
- pluginName
4491
- );
4492
- assertProjectPath(projectRoot, result);
4493
- return result;
4494
- }
4495
- function nodePluginPath(projectRoot, pluginName) {
4496
- validatePluginName(pluginName);
4497
- const result = path15.join(projectRoot, "node_modules", pluginName);
4498
- assertProjectPath(projectRoot, result);
4499
- return result;
4500
- }
4501
- function localDependencySpec(pluginName) {
4502
- validatePluginName(pluginName);
4503
- return `file:${ACTION_PLUGIN_STORE}/node_modules/${pluginName}`;
4504
- }
4505
- function sourceLockKey(pluginName) {
4506
- validatePluginName(pluginName);
4507
- return `${ACTION_PLUGIN_STORE}/node_modules/${pluginName}`;
4508
- }
4509
- function nodeLockKey(pluginName) {
4510
- validatePluginName(pluginName);
4511
- return `node_modules/${pluginName}`;
4512
- }
4513
- function assertManagedRoot(projectRoot) {
4514
- const root = managedRootPath(projectRoot);
4515
- assertProjectPath(projectRoot, root);
4516
- const stats = lstatOrNull(root);
4517
- if (stats?.isSymbolicLink()) {
4518
- throw new Error(`${ACTION_PLUGIN_STORE} must not be a symbolic link`);
4519
- }
4520
- }
4521
- function assertPluginDependencyOwnership(pkg2, pluginName) {
4522
- const expected = localDependencySpec(pluginName);
4523
- const dependency = pkg2.dependencies?.[pluginName];
4524
- if (dependency !== void 0 && dependency !== expected) {
4525
- throw new Error(
4526
- `Dependency ${pluginName} is not managed by action-plugin (expected ${expected}, got ${dependency})`
4527
- );
4528
- }
4529
- for (const section of ["devDependencies", "optionalDependencies"]) {
4530
- const value = pkg2[section]?.[pluginName];
4531
- if (value !== void 0) {
4532
- throw new Error(
4533
- `Dependency ${pluginName} is declared in ${section} and is not managed by action-plugin`
4534
- );
4535
- }
4536
- }
4537
- }
4538
- function assertManagedSourcePath(projectRoot, pluginName) {
4539
- assertManagedRoot(projectRoot);
4540
- const source = managedPluginPath(projectRoot, pluginName);
4541
- const stats = lstatOrNull(source);
4542
- if (!stats) return;
4543
- if (stats.isSymbolicLink() || !stats.isDirectory()) {
4544
- throw new Error(
4545
- `Managed plugin source must be a real directory: ${source}`
4546
- );
4547
- }
4548
- const realSource = fs18.realpathSync(source);
4549
- if (realSource !== source) {
4550
- throw new Error(`Managed plugin source resolves unexpectedly: ${source}`);
4551
- }
4552
- }
4553
- function ensureActionPluginGitignore(projectRoot) {
4554
- const gitignorePath = path15.join(projectRoot, ".gitignore");
4555
- assertProjectPath(projectRoot, gitignorePath);
4556
- const original = fs18.existsSync(gitignorePath) ? fs18.readFileSync(gitignorePath, "utf-8") : "";
4557
- const hadTrailingNewline = original.endsWith("\n");
4558
- const lines = original.split(/\r?\n/).filter((line, index, all) => {
4559
- if (index === all.length - 1 && line === "") return false;
4560
- return line !== ACTION_PLUGIN_GITIGNORE_ENTRY;
4561
- });
4562
- lines.push(ACTION_PLUGIN_GITIGNORE_ENTRY);
4563
- const next = `${lines.join("\n")}
4564
- `;
4565
- if (original !== next || !hadTrailingNewline)
4566
- atomicWriteFile(gitignorePath, next);
4567
- }
4568
- function removeActionPluginGitignore(projectRoot) {
4569
- const gitignorePath = path15.join(projectRoot, ".gitignore");
4570
- if (!fs18.existsSync(gitignorePath)) return;
4571
- const original = fs18.readFileSync(gitignorePath, "utf-8");
4572
- const lines = original.split(/\r?\n/);
4573
- const filtered = lines.filter((line) => line !== ACTION_PLUGIN_GITIGNORE_ENTRY);
4574
- if (filtered.length === lines.length) return;
4575
- let next = filtered.join("\n");
4576
- if (next && !next.endsWith("\n")) next += "\n";
4577
- if (next === "") fs18.rmSync(gitignorePath, { force: true });
4578
- else atomicWriteFile(gitignorePath, next);
4579
- }
4580
- function requiredPeerDependencies(manifest) {
4581
- const required = {};
4582
- for (const [name, range] of Object.entries(manifest.peerDependencies ?? {})) {
4583
- if (!manifest.peerDependenciesMeta?.[name]?.optional)
4584
- required[name] = range;
4585
- }
4586
- return required;
4587
- }
4588
- function findLockfilePath(projectRoot) {
4589
- const shrinkwrap = path15.join(projectRoot, "npm-shrinkwrap.json");
4590
- return fs18.existsSync(shrinkwrap) ? shrinkwrap : path15.join(projectRoot, "package-lock.json");
4591
- }
4592
- function readLockDocument(projectRoot) {
4593
- const lockPath = findLockfilePath(projectRoot);
4594
- if (!fs18.existsSync(lockPath)) {
4595
- throw new Error("npm did not produce a package lock");
4596
- }
4597
- const lock = JSON.parse(fs18.readFileSync(lockPath, "utf-8"));
4598
- if (lock.lockfileVersion !== 3 || !lock.packages) {
4599
- throw new Error("Action plugins require an npm lockfile v3 graph");
4600
- }
4601
- return { lockPath, lock };
4602
- }
4603
- function verifyPluginGraph(projectRoot, pluginName, version) {
4604
- const packagePath = path15.join(projectRoot, "package.json");
4605
- const pkg2 = JSON.parse(
4606
- fs18.readFileSync(packagePath, "utf-8")
4607
- );
4608
- const expectedSpec = localDependencySpec(pluginName);
4609
- if (pkg2.actionPlugins?.[pluginName] !== version) {
4610
- throw new Error(
4611
- `Desired plugin identity is inconsistent for ${pluginName}`
4612
- );
4613
- }
4614
- if (pkg2.dependencies?.[pluginName] !== expectedSpec) {
4615
- throw new Error(`Managed dependency is inconsistent for ${pluginName}`);
4616
- }
4617
- assertManagedSourcePath(projectRoot, pluginName);
4618
- const sourcePath = managedPluginPath(projectRoot, pluginName);
4619
- const manifest = assertPluginIdentity(sourcePath, pluginName, version);
4620
- const { lock } = readLockDocument(projectRoot);
4621
- const packages = lock.packages;
4622
- const rootDependencies = packages[""]?.dependencies;
4623
- if (rootDependencies?.[pluginName] !== expectedSpec) {
4624
- throw new Error(`Lock root is inconsistent for ${pluginName}`);
4625
- }
4626
- const sourceEntry = packages[sourceLockKey(pluginName)];
4627
- if (!sourceEntry || sourceEntry.version !== version) {
4628
- throw new Error(`Lock source is inconsistent for ${pluginName}`);
4629
- }
4630
- if (sourceEntry.name !== void 0 && sourceEntry.name !== pluginName) {
4631
- throw new Error(`Lock source identity is inconsistent for ${pluginName}`);
4632
- }
4633
- const linkEntry = packages[nodeLockKey(pluginName)];
4634
- if (!linkEntry || linkEntry.link !== true || linkEntry.resolved !== sourceLockKey(pluginName)) {
4635
- throw new Error(`Lock link is inconsistent for ${pluginName}`);
4636
- }
4637
- const nodePath = nodePluginPath(projectRoot, pluginName);
4638
- const nodeStats = lstatOrNull(nodePath);
4639
- if (!nodeStats?.isSymbolicLink()) {
4640
- throw new Error(`npm link is missing for ${pluginName}`);
4641
- }
4642
- const realNodePath = fs18.realpathSync(nodePath);
4643
- if (realNodePath !== sourcePath) {
4644
- throw new Error(`npm link escapes managed source for ${pluginName}`);
4645
- }
4646
- assertPluginIdentity(nodePath, pluginName, version);
4647
- const resolvedEntry = createRequire2(packagePath).resolve(pluginName);
4648
- const realResolvedEntry = fs18.realpathSync(resolvedEntry);
4649
- if (!isWithin(sourcePath, realResolvedEntry)) {
4650
- throw new Error(
4651
- `Runtime resolution escapes managed source for ${pluginName}`
4652
- );
4653
- }
4654
- const missingPeers = Object.keys(requiredPeerDependencies(manifest)).filter(
4655
- (peer) => !lstatOrNull(path15.join(projectRoot, "node_modules", peer))
4656
- );
4657
- if (missingPeers.length > 0) {
4658
- throw new Error(`Missing peer dependencies: ${missingPeers.join(", ")}`);
4659
- }
4660
- }
4661
- function assertNoInstallLifecycle(projectRoot, dependencyNames) {
4662
- for (const dependency of dependencyNames) {
4663
- const manifestPath = path15.join(
4664
- projectRoot,
4665
- "node_modules",
4666
- dependency,
4667
- "package.json"
4668
- );
4669
- if (!fs18.existsSync(manifestPath)) continue;
4670
- const manifest = JSON.parse(fs18.readFileSync(manifestPath, "utf-8"));
4671
- const lifecycle = ["preinstall", "install", "postinstall"].find(
4672
- (script) => Boolean(manifest.scripts?.[script]?.trim())
4673
- );
4674
- if (lifecycle) {
4675
- throw new Error(
4676
- `Dependency ${dependency} requires ${lifecycle}; install it with the normal package manager before retrying action-plugin`
4677
- );
4678
- }
4679
- }
4680
- }
4681
- function removePluginLockEntries(projectRoot, pluginName) {
4682
- const lockPath = findLockfilePath(projectRoot);
4683
- if (!fs18.existsSync(lockPath)) return;
4684
- const lock = JSON.parse(fs18.readFileSync(lockPath, "utf-8"));
4685
- if (lock.lockfileVersion !== 3 || !lock.packages) {
4686
- throw new Error(
4687
- "Cannot safely remove action plugin from a non-v3 npm lockfile"
4688
- );
4689
- }
4690
- const rootDependencies = lock.packages[""]?.dependencies;
4691
- if (rootDependencies) delete rootDependencies[pluginName];
4692
- delete lock.packages[sourceLockKey(pluginName)];
4693
- delete lock.packages[nodeLockKey(pluginName)];
4694
- if (lock.dependencies) delete lock.dependencies[pluginName];
4695
- atomicWriteJson(lockPath, lock);
4696
- }
4697
- function removePathAndEmptyParents(targetPath, stopAt) {
4698
- const stats = lstatOrNull(targetPath);
4699
- if (stats?.isDirectory() && !stats.isSymbolicLink()) {
4700
- fs18.rmSync(targetPath, { recursive: true, force: true });
4701
- } else if (stats) {
4702
- fs18.unlinkSync(targetPath);
4703
- }
4704
- let current = path15.dirname(targetPath);
4705
- while (current !== stopAt && isWithin(stopAt, current)) {
4706
- if (!fs18.existsSync(current) || fs18.readdirSync(current).length > 0) break;
4707
- fs18.rmdirSync(current);
4708
- current = path15.dirname(current);
4709
- }
4710
- }
4711
-
4712
- // src/commands/action-plugin/workspace-dependencies.ts
4713
- import fs19 from "fs";
4714
- import path16 from "path";
4715
- var WORKSPACE_SECTIONS = [
4716
- "dependencies",
4717
- "optionalDependencies",
4718
- "peerDependencies"
4719
- ];
4720
- function parseExactVersion(value) {
4721
- const match = value.match(
4722
- /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/
4723
- );
4724
- if (!match) return null;
4725
- return {
4726
- value,
4727
- major: Number(match[1]),
4728
- minor: Number(match[2]),
4729
- patch: Number(match[3]),
4730
- prerelease: match[4]?.split(".") ?? []
4731
- };
4732
- }
4733
- function exactVersionFromDeclaration(spec) {
4734
- return parseExactVersion(spec.startsWith("=") ? spec.slice(1) : spec);
4735
- }
4736
- function comparePrerelease(left, right) {
4737
- if (left.length === 0 || right.length === 0) {
4738
- if (left.length === right.length) return 0;
4739
- return left.length === 0 ? 1 : -1;
4740
- }
4741
- const length = Math.max(left.length, right.length);
4742
- for (let index = 0; index < length; index += 1) {
4743
- const leftPart = left[index];
4744
- const rightPart = right[index];
4745
- if (leftPart === void 0) return -1;
4746
- if (rightPart === void 0) return 1;
4747
- if (leftPart === rightPart) continue;
4748
- const leftNumeric = /^\d+$/.test(leftPart);
4749
- const rightNumeric = /^\d+$/.test(rightPart);
4750
- if (leftNumeric && rightNumeric)
4751
- return Number(leftPart) - Number(rightPart);
4752
- if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
4753
- return leftPart < rightPart ? -1 : 1;
4754
- }
4755
- return 0;
4756
- }
4757
- function compareVersions(left, right) {
4758
- for (const key of ["major", "minor", "patch"]) {
4759
- if (left[key] !== right[key]) return left[key] - right[key];
4760
- }
4761
- return comparePrerelease(left.prerelease, right.prerelease);
4762
- }
4763
- function satisfiesSupportedRange(version, range) {
4764
- const exactRange = exactVersionFromDeclaration(range);
4765
- if (exactRange) return compareVersions(version, exactRange) === 0;
4766
- const operator = range[0];
4767
- if (operator !== "^" && operator !== "~") return null;
4768
- const lower = parseExactVersion(range.slice(1));
4769
- if (!lower) return null;
4770
- if (compareVersions(version, lower) < 0) return false;
4771
- if (lower.prerelease.length > 0 && version.prerelease.length > 0) {
4772
- const sameRelease = version.major === lower.major && version.minor === lower.minor && version.patch === lower.patch;
4773
- if (!sameRelease) return false;
4774
- }
4775
- if (operator === "~") {
4776
- return version.major === lower.major && version.minor === lower.minor;
4777
- }
4778
- if (lower.major > 0) return version.major === lower.major;
4779
- if (lower.minor > 0) {
4780
- return version.major === 0 && version.minor === lower.minor;
4781
- }
4782
- return version.major === 0 && version.minor === 0 && version.patch === lower.patch;
4783
- }
4784
- function validateDependencyName(name) {
4785
- if (!/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i.test(name)) {
4786
- throw new Error(`unsafe dependency name ${JSON.stringify(name)}`);
4787
- }
4788
- }
4789
- function hostDeclarations(hostPackage, dependency) {
4790
- const declarations = [];
4791
- for (const section of [
4792
- "dependencies",
4793
- "devDependencies",
4794
- "optionalDependencies",
4795
- "peerDependencies"
4796
- ]) {
4797
- const spec = hostPackage[section]?.[dependency];
4798
- if (typeof spec === "string") declarations.push({ section, spec });
4799
- }
4800
- return declarations;
4801
- }
4802
- function readInstalledExactVersion(projectRoot, dependency) {
4803
- const manifestPath = path16.join(
4804
- projectRoot,
4805
- "node_modules",
4806
- dependency,
4807
- "package.json"
4808
- );
4809
- if (!fs19.existsSync(manifestPath)) return null;
4810
- let manifest;
4811
- try {
4812
- manifest = JSON.parse(fs19.readFileSync(manifestPath, "utf-8"));
4813
- } catch (error) {
4814
- throw new Error(
4815
- `installed manifest is unreadable at ${manifestPath}: ${error instanceof Error ? error.message : String(error)}`
4816
- );
4817
- }
4818
- if (manifest.name !== dependency) {
4819
- throw new Error(
4820
- `installed package identity mismatch at ${manifestPath}: expected ${dependency}, got ${String(manifest.name)}`
4821
- );
4822
- }
4823
- if (typeof manifest.version !== "string") {
4824
- throw new Error(
4825
- `installed package has no exact version at ${manifestPath}`
4826
- );
4827
- }
4828
- const exact = parseExactVersion(manifest.version);
4829
- if (!exact) {
4830
- throw new Error(
4831
- `installed package has a non-semver version at ${manifestPath}: ${manifest.version}`
4832
- );
4833
- }
4834
- return exact;
4835
- }
4836
- function resolveTrustedExactVersion(dependency, hostPackage, projectRoot) {
4837
- const declaredExactVersions = hostDeclarations(hostPackage, dependency).map(({ spec }) => exactVersionFromDeclaration(spec)).filter((version) => version !== null);
4838
- const distinctDeclaredVersions = new Map(
4839
- declaredExactVersions.map((version) => [version.value, version])
4840
- );
4841
- if (distinctDeclaredVersions.size > 1) {
4842
- throw new Error(
4843
- `conflicting exact host declarations: ${[...distinctDeclaredVersions].join(", ")}`
4844
- );
4845
- }
4846
- if (distinctDeclaredVersions.size === 1) {
4847
- return [...distinctDeclaredVersions.values()][0];
4848
- }
4849
- return readInstalledExactVersion(projectRoot, dependency);
4850
- }
4851
- function formatContext(plugin, reference) {
4852
- return `${reference.section}.${reference.dependency} of ${plugin.name}@${plugin.version} (${reference.spec})`;
4853
- }
4854
- function normalizeReference(plugin, reference, hostPackage, projectRoot) {
4855
- validateDependencyName(reference.dependency);
4856
- const workspaceRange = reference.spec.slice("workspace:".length);
4857
- if (!workspaceRange) {
4858
- throw new Error(
4859
- `Cannot normalize workspace dependency ${formatContext(plugin, reference)}: empty workspace range`
4860
- );
4861
- }
4862
- let exactVersion = null;
4863
- const getExactVersion = () => {
4864
- if (exactVersion === null) {
4865
- exactVersion = resolveTrustedExactVersion(
4866
- reference.dependency,
4867
- hostPackage,
4868
- projectRoot
4869
- );
4870
- }
4871
- return exactVersion;
4872
- };
4873
- if (workspaceRange === "*" || workspaceRange === "^" || workspaceRange === "~") {
4874
- const exact2 = getExactVersion();
4875
- if (!exact2) {
4876
- throw new Error(
4877
- `Cannot normalize workspace dependency ${formatContext(plugin, reference)}: no exact host declaration or matching installed identity`
4878
- );
4879
- }
4880
- return workspaceRange === "*" ? exact2.value : `${workspaceRange}${exact2.value}`;
4881
- }
4882
- const supportedExplicitRange = exactVersionFromDeclaration(workspaceRange) ?? (workspaceRange.startsWith("^") || workspaceRange.startsWith("~") ? parseExactVersion(workspaceRange.slice(1)) : null);
4883
- if (!supportedExplicitRange) {
4884
- throw new Error(
4885
- `Cannot normalize workspace dependency ${formatContext(plugin, reference)}: unsupported workspace range ${workspaceRange}`
4886
- );
4887
- }
4888
- const declarations = hostDeclarations(hostPackage, reference.dependency);
4889
- if (declarations.some(({ spec }) => spec === workspaceRange)) {
4890
- return workspaceRange;
4891
- }
4892
- const exact = getExactVersion();
4893
- if (!exact) {
4894
- throw new Error(
4895
- `Cannot normalize workspace dependency ${formatContext(plugin, reference)}: host does not declare ${workspaceRange} and no matching installed identity exists`
4896
- );
4897
- }
4898
- const satisfies = satisfiesSupportedRange(exact, workspaceRange);
4899
- if (satisfies === null) {
4900
- throw new Error(
4901
- `Cannot normalize workspace dependency ${formatContext(plugin, reference)}: unsupported workspace range ${workspaceRange}`
4902
- );
4903
- }
4904
- if (!satisfies) {
4905
- throw new Error(
4906
- `Cannot normalize workspace dependency ${formatContext(plugin, reference)}: installed or host identity ${exact.value} does not satisfy workspace range ${workspaceRange}`
4907
- );
4908
- }
4909
- return workspaceRange;
4910
- }
4911
- function hasWorkspaceDependencies(manifest) {
4912
- return WORKSPACE_SECTIONS.some(
4913
- (section) => Object.values(manifest[section] ?? {}).some(
4914
- (spec) => typeof spec === "string" && spec.startsWith("workspace:")
4915
- )
4916
- );
4917
- }
4918
- function normalizePluginWorkspaceDependencies(pluginPath, hostPackage, projectRoot) {
4919
- const manifest = readPluginManifest(pluginPath);
4920
- const nextManifest = JSON.parse(
4921
- JSON.stringify(manifest)
4922
- );
4923
- let changed = false;
4924
- for (const section of WORKSPACE_SECTIONS) {
4925
- const dependencies = nextManifest[section];
4926
- if (!dependencies) continue;
4927
- for (const [dependency, spec] of Object.entries(dependencies)) {
4928
- if (typeof spec !== "string" || !spec.startsWith("workspace:")) continue;
4929
- dependencies[dependency] = normalizeReference(
4930
- manifest,
4931
- { section, dependency, spec },
4932
- hostPackage,
4933
- projectRoot
4934
- );
4935
- changed = true;
4936
- }
4937
- }
4938
- if (changed) {
4939
- atomicWriteJson(path16.join(pluginPath, "package.json"), nextManifest);
4940
- }
4941
- return nextManifest;
4942
- }
4943
-
4944
- // src/commands/action-plugin/plugin-preparation.ts
4945
- function readPackageDocument(packageJsonPath) {
4946
- return JSON.parse(
4947
- fs20.readFileSync(packageJsonPath, "utf-8")
4948
- );
4949
- }
4950
- function rootDeclaresDependency(pkg2, dependency) {
4951
- return Boolean(
4952
- pkg2.dependencies?.[dependency] || pkg2.devDependencies?.[dependency] || pkg2.optionalDependencies?.[dependency]
4953
- );
4954
- }
4955
- async function defaultMaterializePlugin(name, version, destination) {
4956
- let tgzPath;
4957
- let source;
4958
- if (hasCachedPlugin(name, version)) {
4959
- tgzPath = getCachePath(name, version);
4960
- source = "cache";
4961
- } else {
4962
- const downloaded = await downloadPlugin(name, version);
4963
- if (downloaded.version !== version) {
4964
- throw new Error(
4965
- `Downloaded version mismatch for ${name}: expected ${version}, got ${downloaded.version}`
4966
- );
4967
- }
4968
- tgzPath = downloaded.tgzPath;
4969
- source = "download";
4970
- }
4971
- fs20.mkdirSync(path17.dirname(destination), { recursive: true });
4972
- extractTgzToDirectory(tgzPath, destination);
4973
- return source;
4974
- }
4975
- function copyLegacyPlugin(source, destination) {
4976
- fs20.mkdirSync(path17.dirname(destination), { recursive: true });
4977
- fs20.cpSync(source, destination, {
4978
- recursive: true,
4979
- force: true,
4980
- verbatimSymlinks: true
4981
- });
4982
- }
4983
- function readManagedManifest(projectRoot, pluginName) {
4984
- assertManagedSourcePath(projectRoot, pluginName);
4985
- const sourcePath = managedPluginPath(projectRoot, pluginName);
4986
- if (!lstatOrNull(sourcePath)) return null;
4987
- const manifest = readPluginManifest(sourcePath);
4988
- if (manifest.name !== pluginName) {
4989
- throw new Error(
4990
- `Plugin identity mismatch: expected ${pluginName}, got ${manifest.name}`
4991
- );
4992
- }
4993
- return manifest;
4994
- }
4995
- function findLegacyPlugin(projectRoot, pluginName, version, initialPackage) {
4996
- if (initialPackage.dependencies?.[pluginName] === localDependencySpec(pluginName)) {
4997
- return null;
4998
- }
4999
- const legacyPath = nodePluginPath(projectRoot, pluginName);
5000
- const stats = lstatOrNull(legacyPath);
5001
- if (!stats || stats.isSymbolicLink() || !stats.isDirectory()) return null;
5002
- const manifest = readPluginManifest(legacyPath);
5003
- if (manifest.name !== pluginName) {
5004
- throw new Error(
5005
- `Plugin identity mismatch: expected ${pluginName}, got ${manifest.name}`
5006
- );
5007
- }
5008
- const desiredVersion = initialPackage.actionPlugins?.[pluginName];
5009
- if (manifest.version !== version && manifest.version !== desiredVersion) {
5010
- throw new Error(
5011
- `Plugin identity mismatch: expected ${pluginName}@${desiredVersion ?? version}, got ${manifest.name}@${manifest.version}`
5012
- );
5013
- }
5014
- return manifest.version === version ? legacyPath : null;
5015
- }
5016
- async function preparePlugin(request, index, initialPackage, projectRoot, stagingRoot, options) {
5017
- validatePluginName(request.name);
5018
- assertPluginDependencyOwnership(initialPackage, request.name);
5019
- const version = request.requestedVersion === "latest" ? await (options.resolveLatestVersion ?? (async (name) => (await getPluginVersion(name, "latest")).version))(request.name) : request.requestedVersion;
5020
- if (!version || version === "latest") {
5021
- throw new Error(
5022
- `Plugin version did not resolve to an exact value: ${request.name}`
5023
- );
5024
- }
5025
- let manifest;
5026
- let stagedPath = null;
5027
- let source;
5028
- const managedManifest = readManagedManifest(projectRoot, request.name);
5029
- const desiredVersion = initialPackage.actionPlugins?.[request.name];
5030
- if (managedManifest && managedManifest.version !== version && managedManifest.version !== desiredVersion) {
5031
- throw new Error(
5032
- `Plugin identity mismatch: expected ${request.name}@${desiredVersion ?? version}, got ${managedManifest.name}@${managedManifest.version}`
5033
- );
5034
- }
5035
- if (managedManifest?.version === version) {
5036
- const managedPath = managedPluginPath(projectRoot, request.name);
5037
- manifest = assertPluginIdentity(managedPath, request.name, version);
5038
- if (hasWorkspaceDependencies(manifest)) {
5039
- stagedPath = path17.join(stagingRoot, "prepared", String(index));
5040
- copyLegacyPlugin(managedPath, stagedPath);
5041
- manifest = normalizePluginWorkspaceDependencies(
5042
- stagedPath,
5043
- initialPackage,
5044
- projectRoot
5045
- );
5046
- }
5047
- source = "managed";
5048
- } else {
5049
- const legacyPath = findLegacyPlugin(
5050
- projectRoot,
5051
- request.name,
5052
- version,
5053
- initialPackage
5054
- );
5055
- stagedPath = path17.join(stagingRoot, "prepared", String(index));
5056
- if (legacyPath) {
5057
- copyLegacyPlugin(legacyPath, stagedPath);
5058
- source = "legacy";
5059
- } else {
5060
- source = await (options.materializePlugin ?? defaultMaterializePlugin)(
5061
- request.name,
5062
- version,
5063
- stagedPath
5064
- );
5065
- }
5066
- manifest = assertPluginIdentity(stagedPath, request.name, version);
5067
- manifest = normalizePluginWorkspaceDependencies(
5068
- stagedPath,
5069
- initialPackage,
5070
- projectRoot
5071
- );
5072
- }
5073
- const missingUndeclaredPeers = {};
5074
- for (const [dependency, range] of Object.entries(
5075
- requiredPeerDependencies(manifest)
5076
- )) {
5077
- if (!lstatOrNull(path17.join(projectRoot, "node_modules", dependency)) && !rootDeclaresDependency(initialPackage, dependency)) {
5078
- missingUndeclaredPeers[dependency] = range;
5079
- }
5080
- }
5081
- return {
5082
- ...request,
5083
- version,
5084
- manifest,
5085
- stagedPath,
5086
- missingUndeclaredPeers,
5087
- source,
5088
- wasDesired: initialPackage.actionPlugins?.[request.name] === version
5089
- };
5090
- }
5091
- function findPeerRangeConflict(prepared) {
5092
- const ranges = /* @__PURE__ */ new Map();
5093
- for (const plugin of prepared) {
5094
- for (const [dependency, range] of Object.entries(
5095
- plugin.missingUndeclaredPeers
5096
- )) {
5097
- const existing = ranges.get(dependency);
5098
- if (existing && existing !== range) {
5099
- return `Conflicting peer dependency ranges for ${dependency}: ${existing} and ${range}`;
5100
- }
5101
- ranges.set(dependency, range);
5102
- }
5103
- }
5104
- return null;
5105
- }
5106
- function collectPeerRanges(prepared) {
5107
- const peers = /* @__PURE__ */ new Map();
5108
- for (const plugin of prepared) {
5109
- for (const [dependency, range] of Object.entries(
5110
- plugin.missingUndeclaredPeers
5111
- )) {
5112
- peers.set(dependency, range);
5113
- }
5114
- }
5115
- return peers;
5116
- }
5117
-
5118
- // src/commands/action-plugin/transaction-journal.ts
5119
- import fs21 from "fs";
5120
- import path18 from "path";
5121
- import { randomUUID } from "crypto";
5122
- var JOURNAL_FILE = ".transaction-journal.json";
5123
- var TRANSACTION_DIRECTORY = ".transactions";
5124
- function journalPath(projectRoot) {
5125
- return path18.join(managedRootPath(projectRoot), JOURNAL_FILE);
5126
- }
5127
- function isTransactionId(value) {
5128
- return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
5129
- value
5130
- );
5131
- }
5132
- function transactionRoot(projectRoot, transactionId) {
5133
- if (!isTransactionId(transactionId)) {
5134
- throw new Error("Action-plugin transaction id is invalid");
5135
- }
5136
- const result = path18.join(
5137
- managedRootPath(projectRoot),
5138
- TRANSACTION_DIRECTORY,
5139
- transactionId
5140
- );
5141
- assertProjectPath(projectRoot, result);
5142
- return result;
5143
- }
5144
- function snapshotFile(projectRoot, relativePath) {
5145
- const filePath = path18.join(projectRoot, relativePath);
5146
- assertProjectPath(projectRoot, filePath);
5147
- const stats = lstatOrNull(filePath);
5148
- if (!stats) return { relativePath, content: null, mode: null };
5149
- if (!stats.isFile()) throw new Error(`Expected a regular file: ${filePath}`);
5150
- return {
5151
- relativePath,
5152
- content: fs21.readFileSync(filePath).toString("base64"),
5153
- mode: stats.mode
5154
- };
5155
- }
5156
- function snapshotEntry(projectRoot, transactionId, name, location, index) {
5157
- const targetPath = location === "source" ? managedPluginPath(projectRoot, name) : nodePluginPath(projectRoot, name);
5158
- const stats = lstatOrNull(targetPath);
5159
- if (!stats) {
5160
- return {
5161
- name,
5162
- location,
5163
- kind: "missing",
5164
- backupRelativePath: null,
5165
- linkTarget: null
5166
- };
5167
- }
5168
- if (stats.isSymbolicLink()) {
5169
- return {
5170
- name,
5171
- location,
5172
- kind: "symlink",
5173
- backupRelativePath: null,
5174
- linkTarget: fs21.readlinkSync(targetPath)
5175
- };
5176
- }
5177
- const relativeBackup = path18.join(
5178
- TRANSACTION_DIRECTORY,
5179
- transactionId,
5180
- "entries",
5181
- String(index)
5182
- );
5183
- const backupPath = path18.join(managedRootPath(projectRoot), relativeBackup);
5184
- assertProjectPath(projectRoot, backupPath);
5185
- fs21.mkdirSync(path18.dirname(backupPath), { recursive: true });
5186
- if (stats.isDirectory()) {
5187
- fs21.cpSync(targetPath, backupPath, {
5188
- recursive: true,
5189
- force: true,
5190
- verbatimSymlinks: true
5191
- });
5192
- return {
5193
- name,
5194
- location,
5195
- kind: "directory",
5196
- backupRelativePath: relativeBackup,
5197
- linkTarget: null
5198
- };
5199
- }
5200
- if (stats.isFile()) {
5201
- fs21.copyFileSync(targetPath, backupPath);
5202
- return {
5203
- name,
5204
- location,
5205
- kind: "file",
5206
- backupRelativePath: relativeBackup,
5207
- linkTarget: null
5208
- };
5209
- }
5210
- throw new Error(`Unsupported action plugin entry: ${targetPath}`);
5211
- }
5212
- function beginActionPluginTransaction(projectRootInput, pluginNames) {
5213
- const projectRoot = resolveProjectRoot(projectRootInput);
5214
- assertManagedRoot(projectRoot);
5215
- if (lstatOrNull(journalPath(projectRoot))) {
5216
- throw new Error("An action-plugin transaction journal already exists");
5217
- }
5218
- const managedRootExisted = Boolean(lstatOrNull(managedRootPath(projectRoot)));
5219
- const transactionId = randomUUID();
5220
- fs21.mkdirSync(transactionRoot(projectRoot, transactionId), {
5221
- recursive: true
5222
- });
5223
- try {
5224
- const names = [...new Set(pluginNames)];
5225
- names.forEach(validatePluginName);
5226
- const entries = [];
5227
- let index = 0;
5228
- for (const name of names) {
5229
- entries.push(
5230
- snapshotEntry(projectRoot, transactionId, name, "source", index++)
5231
- );
5232
- entries.push(
5233
- snapshotEntry(projectRoot, transactionId, name, "node", index++)
5234
- );
5235
- }
5236
- const journal = {
5237
- schemaVersion: 1,
5238
- transactionId,
5239
- projectRoot,
5240
- managedRootExisted,
5241
- files: [
5242
- snapshotFile(projectRoot, "package.json"),
5243
- snapshotFile(projectRoot, "package-lock.json"),
5244
- snapshotFile(projectRoot, "npm-shrinkwrap.json"),
5245
- snapshotFile(projectRoot, ".gitignore")
5246
- ],
5247
- entries
5248
- };
5249
- atomicWriteJson(journalPath(projectRoot), journal);
5250
- return journal;
5251
- } catch (error) {
5252
- fs21.rmSync(transactionRoot(projectRoot, transactionId), {
5253
- recursive: true,
5254
- force: true
5255
- });
5256
- const transactionsPath = path18.join(
5257
- managedRootPath(projectRoot),
5258
- TRANSACTION_DIRECTORY
5259
- );
5260
- if (fs21.existsSync(transactionsPath) && fs21.readdirSync(transactionsPath).length === 0) {
5261
- fs21.rmdirSync(transactionsPath);
5262
- }
5263
- if (!managedRootExisted && fs21.existsSync(managedRootPath(projectRoot)) && fs21.readdirSync(managedRootPath(projectRoot)).length === 0) {
5264
- fs21.rmdirSync(managedRootPath(projectRoot));
5265
- }
5266
- throw error;
5267
- }
5268
- }
5269
- function restoreFile(projectRoot, snapshot) {
5270
- const filePath = path18.join(projectRoot, snapshot.relativePath);
5271
- assertProjectPath(projectRoot, filePath);
5272
- if (snapshot.content === null) {
5273
- if (lstatOrNull(filePath))
5274
- fs21.rmSync(filePath, { recursive: true, force: true });
5275
- return;
5276
- }
5277
- atomicWriteFile(filePath, Buffer.from(snapshot.content, "base64"));
5278
- if (snapshot.mode !== null) fs21.chmodSync(filePath, snapshot.mode);
5279
- }
5280
- function removeEntry(targetPath) {
5281
- const stats = lstatOrNull(targetPath);
5282
- if (!stats) return;
5283
- if (stats.isDirectory() && !stats.isSymbolicLink()) {
5284
- fs21.rmSync(targetPath, { recursive: true, force: true });
5285
- } else {
5286
- fs21.unlinkSync(targetPath);
5287
- }
5288
- }
5289
- function restoreEntry(projectRoot, journal, snapshot) {
5290
- validatePluginName(snapshot.name);
5291
- const targetPath = snapshot.location === "source" ? managedPluginPath(projectRoot, snapshot.name) : nodePluginPath(projectRoot, snapshot.name);
5292
- removeEntry(targetPath);
5293
- if (snapshot.kind === "missing") return;
5294
- fs21.mkdirSync(path18.dirname(targetPath), { recursive: true });
5295
- if (snapshot.kind === "symlink") {
5296
- if (snapshot.linkTarget === null)
5297
- throw new Error("Journal symlink target is missing");
5298
- fs21.symlinkSync(snapshot.linkTarget, targetPath);
5299
- return;
5300
- }
5301
- if (snapshot.backupRelativePath === null) {
5302
- throw new Error("Journal entry backup is missing");
5303
- }
5304
- const expectedPrefix = path18.join(
5305
- TRANSACTION_DIRECTORY,
5306
- journal.transactionId,
5307
- "entries"
5308
- );
5309
- if (snapshot.backupRelativePath !== expectedPrefix && !snapshot.backupRelativePath.startsWith(`${expectedPrefix}${path18.sep}`)) {
5310
- throw new Error("Journal entry backup path is invalid");
5311
- }
5312
- const backupPath = path18.join(
5313
- managedRootPath(projectRoot),
5314
- snapshot.backupRelativePath
5315
- );
5316
- assertProjectPath(projectRoot, backupPath);
5317
- if (snapshot.kind === "directory") {
5318
- fs21.cpSync(backupPath, targetPath, {
5319
- recursive: true,
5320
- force: true,
5321
- verbatimSymlinks: true
5322
- });
5323
- } else {
5324
- fs21.copyFileSync(backupPath, targetPath);
5325
- }
5326
- }
5327
- function removeTransactionArtifacts(projectRoot, journal) {
5328
- fs21.rmSync(journalPath(projectRoot), { force: true });
5329
- fs21.rmSync(transactionRoot(projectRoot, journal.transactionId), {
5330
- recursive: true,
5331
- force: true
5332
- });
5333
- const transactionsPath = path18.join(
5334
- managedRootPath(projectRoot),
5335
- TRANSACTION_DIRECTORY
5336
- );
5337
- if (fs21.existsSync(transactionsPath) && fs21.readdirSync(transactionsPath).length === 0) {
5338
- fs21.rmdirSync(transactionsPath);
5339
- }
5340
- if (!journal.managedRootExisted && fs21.existsSync(managedRootPath(projectRoot)) && fs21.readdirSync(managedRootPath(projectRoot)).length === 0) {
5341
- fs21.rmdirSync(managedRootPath(projectRoot));
5342
- }
5343
- }
5344
- function rollbackActionPluginTransaction(journal) {
5345
- const projectRoot = resolveProjectRoot(journal.projectRoot);
5346
- if (journal.schemaVersion !== 1 || projectRoot !== journal.projectRoot || !isTransactionId(journal.transactionId)) {
5347
- throw new Error("Action-plugin transaction journal is invalid");
5348
- }
5349
- for (const snapshot of journal.files) restoreFile(projectRoot, snapshot);
5350
- for (const snapshot of journal.entries) {
5351
- restoreEntry(projectRoot, journal, snapshot);
5352
- }
5353
- if (!journal.managedRootExisted) {
5354
- fs21.rmSync(managedRootPath(projectRoot), { recursive: true, force: true });
5355
- } else {
5356
- removeTransactionArtifacts(projectRoot, journal);
5357
- }
5358
- }
5359
- function commitActionPluginTransaction(journal) {
5360
- const projectRoot = resolveProjectRoot(journal.projectRoot);
5361
- removeTransactionArtifacts(projectRoot, journal);
5362
- }
5363
- function recoverInterruptedActionPluginTransaction(projectRootInput) {
5364
- const projectRoot = resolveProjectRoot(projectRootInput);
5365
- assertManagedRoot(projectRoot);
5366
- const currentJournalPath = journalPath(projectRoot);
5367
- if (!lstatOrNull(currentJournalPath)) return false;
5368
- const journal = JSON.parse(
5369
- fs21.readFileSync(currentJournalPath, "utf-8")
5370
- );
5371
- if (journal.schemaVersion !== 1 || journal.projectRoot !== projectRoot || !isTransactionId(journal.transactionId)) {
5372
- throw new Error("Action-plugin transaction journal is invalid");
5373
- }
5374
- rollbackActionPluginTransaction(journal);
5375
- return true;
5376
- }
5377
-
5378
- // src/commands/action-plugin/utils.ts
5379
- import fs22 from "fs";
5380
- import path19 from "path";
5381
- import { spawnSync as spawnSync6, execSync as execSync2 } from "child_process";
5382
- function parsePluginName(input) {
5383
- const match = input.match(
5384
- /^(@[a-z0-9][a-z0-9._-]*\/[a-z0-9][a-z0-9._-]*)(?:@([^\s]+))?$/i
5385
- );
5386
- if (!match) {
5387
- throw new Error(
5388
- `Invalid plugin name format: ${input}. Expected format: @scope/name or @scope/name@version`
5389
- );
5390
- }
5391
- return {
5392
- name: match[1],
5393
- version: match[2] || "latest"
5394
- };
5395
- }
5396
- function getProjectRoot() {
5397
- return process.cwd();
5398
- }
5399
- function getPackageJsonPath() {
5400
- return path19.join(getProjectRoot(), "package.json");
5401
- }
5402
- function readPackageJson2() {
5403
- const pkgPath = getPackageJsonPath();
5404
- if (!fs22.existsSync(pkgPath)) {
5405
- throw new Error("package.json not found in current directory");
5406
- }
5407
- try {
5408
- const content = fs22.readFileSync(pkgPath, "utf-8");
5409
- return JSON.parse(content);
5410
- } catch {
5411
- throw new Error("Failed to parse package.json");
5412
- }
5413
- }
5414
- function readActionPlugins() {
5415
- const pkg2 = readPackageJson2();
5416
- return pkg2.actionPlugins || {};
5417
- }
5418
-
5419
- // src/commands/action-plugin/install-engine.ts
5420
- var NPM_REIFY_ARGUMENTS = [
5421
- "install",
5422
- "--ignore-scripts",
5423
- "--install-links=false"
5424
- ];
5425
- function defaultRunNpmInstall(projectRoot, env) {
5426
- const result = spawnSync7("npm", [...NPM_REIFY_ARGUMENTS], {
5427
- cwd: projectRoot,
5428
- stdio: "inherit",
5429
- env
5430
- });
5431
- if (result.error) {
5432
- throw new Error(`npm install failed: ${result.error.message}`);
5433
- }
5434
- if (result.status !== 0) {
5435
- throw new Error(`npm install failed with exit code ${result.status}`);
5436
- }
5437
- }
5438
- function formatPreparationFailure(request, error) {
5439
- return {
5440
- name: request.name,
5441
- version: request.requestedVersion,
5442
- success: false,
5443
- error: error instanceof Error ? error.message : String(error)
5444
- };
5445
- }
5446
- function clonePackage(pkg2) {
5447
- return JSON.parse(JSON.stringify(pkg2));
5448
- }
5449
- function markPreparedFailed(publicPrepared, results, message) {
5450
- for (const [index, plugin] of publicPrepared) {
5451
- results.set(index, {
5452
- name: plugin.name,
5453
- version: plugin.version,
5454
- oldVersion: plugin.wasDesired ? plugin.version : void 0,
5455
- success: false,
5456
- error: message
5457
- });
5458
- }
5459
- }
5460
- async function executePluginBatch(requests, mode, options = {}) {
5461
- const projectRoot = resolveProjectRoot(options.projectRoot ?? process.cwd());
5462
- assertManagedRoot(projectRoot);
5463
- recoverInterruptedActionPluginTransaction(projectRoot);
5464
- const packageJsonPath = path20.join(projectRoot, "package.json");
5465
- const initialPackage = readPackageDocument(packageJsonPath);
5466
- const stagingRoot = createStagingRoot();
5467
- const results = /* @__PURE__ */ new Map();
5468
- const publicPrepared = /* @__PURE__ */ new Map();
5469
- const implicitPrepared = /* @__PURE__ */ new Map();
5470
- try {
5471
- const duplicateNames = /* @__PURE__ */ new Set();
5472
- const seenNames = /* @__PURE__ */ new Set();
5473
- for (const request of requests) {
5474
- if (seenNames.has(request.name)) duplicateNames.add(request.name);
5475
- seenNames.add(request.name);
5476
- }
5477
- if (duplicateNames.size > 0) {
5478
- const message = `Duplicate plugin requests: ${[...duplicateNames].join(", ")}`;
5479
- return requests.map((request) => ({
5480
- name: request.name,
5481
- version: request.requestedVersion,
5482
- success: false,
5483
- error: message
5484
- }));
5485
- }
5486
- const publicPreparation = requests.map(async (request, index) => {
5487
- if (mode === "update" && !initialPackage.actionPlugins?.[request.name]) {
5488
- results.set(index, {
5489
- name: request.name,
5490
- version: request.requestedVersion,
5491
- success: false,
5492
- notInstalled: true,
5493
- error: `Plugin ${request.name} is not installed`
5494
- });
5495
- return;
5496
- }
5497
- try {
5498
- publicPrepared.set(
5499
- index,
5500
- await preparePlugin(
5501
- request,
5502
- index,
5503
- initialPackage,
5504
- projectRoot,
5505
- stagingRoot,
5506
- options
5507
- )
5508
- );
5509
- } catch (error) {
5510
- results.set(index, formatPreparationFailure(request, error));
5511
- }
5512
- });
5513
- const implicitRequests = Object.entries(
5514
- initialPackage.actionPlugins ?? {}
5515
- ).filter(([name]) => !seenNames.has(name));
5516
- const implicitPreparation = implicitRequests.map(
5517
- async ([name, version], offset) => {
5518
- const index = requests.length + offset;
5519
- try {
5520
- implicitPrepared.set(
5521
- index,
5522
- await preparePlugin(
5523
- { name, requestedVersion: version },
5524
- index,
5525
- initialPackage,
5526
- projectRoot,
5527
- stagingRoot,
5528
- options
5529
- )
5530
- );
5531
- } catch (error) {
5532
- throw new Error(
5533
- `Failed to prepare existing desired plugin ${name}: ${error instanceof Error ? error.message : String(error)}`
5534
- );
5535
- }
5536
- }
5537
- );
5538
- const preparationResults = await Promise.allSettled([
5539
- ...publicPreparation,
5540
- ...implicitPreparation
5541
- ]);
5542
- const rejectedPreparation = preparationResults.find(
5543
- (result) => result.status === "rejected"
5544
- );
5545
- if (rejectedPreparation?.status === "rejected") {
5546
- const error = rejectedPreparation.reason;
5547
- const message = error instanceof Error ? error.message : String(error);
5548
- markPreparedFailed(publicPrepared, results, message);
5549
- return requests.map(
5550
- (request, index) => results.get(index) ?? formatPreparationFailure(request, error)
5551
- );
5552
- }
5553
- const failedDesiredRequest = [...results].find(
5554
- ([index, result]) => !result.notInstalled && Boolean(initialPackage.actionPlugins?.[requests[index].name])
5555
- );
5556
- if (failedDesiredRequest) {
5557
- const message = failedDesiredRequest[1].error ?? "Desired plugin preparation failed";
5558
- markPreparedFailed(publicPrepared, results, message);
5559
- return requests.map(
5560
- (request, index) => results.get(index) ?? {
5561
- name: request.name,
5562
- version: request.requestedVersion,
5563
- success: false,
5564
- error: message
5565
- }
5566
- );
5567
- }
5568
- if (publicPrepared.size === 0) {
5569
- return requests.map(
5570
- (request, index) => results.get(index) ?? {
5571
- name: request.name,
5572
- version: request.requestedVersion,
5573
- success: false,
5574
- error: "Plugin was not prepared"
5575
- }
5576
- );
5577
- }
5578
- const allPrepared = [...publicPrepared, ...implicitPrepared].sort(([left], [right]) => left - right).map(([, plugin]) => plugin);
5579
- const conflict = findPeerRangeConflict(allPrepared);
5580
- if (conflict) {
5581
- markPreparedFailed(publicPrepared, results, conflict);
5582
- return requests.map(
5583
- (request, index) => results.get(index) ?? {
5584
- name: request.name,
5585
- version: request.requestedVersion,
5586
- success: false,
5587
- error: conflict
5588
- }
5589
- );
5590
- }
5591
- const nextPackage = clonePackage(initialPackage);
5592
- nextPackage.actionPlugins = { ...initialPackage.actionPlugins ?? {} };
5593
- nextPackage.dependencies = { ...initialPackage.dependencies ?? {} };
5594
- const peerRanges = collectPeerRanges(allPrepared);
5595
- for (const plugin of allPrepared) {
5596
- nextPackage.actionPlugins[plugin.name] = plugin.version;
5597
- nextPackage.dependencies[plugin.name] = localDependencySpec(plugin.name);
5598
- }
5599
- for (const [dependency, range] of peerRanges) {
5600
- if (!rootDeclaresDependency(nextPackage, dependency)) {
5601
- nextPackage.dependencies[dependency] = range;
5602
- }
5603
- }
5604
- composeActionPluginLifecycle(nextPackage);
5605
- const transactionNames = /* @__PURE__ */ new Set([
5606
- ...Object.keys(initialPackage.actionPlugins ?? {}),
5607
- ...allPrepared.map((plugin) => plugin.name)
5608
- ]);
5609
- let journal;
5610
- try {
5611
- journal = beginActionPluginTransaction(projectRoot, transactionNames);
5612
- } catch (error) {
5613
- const message = error instanceof Error ? error.message : String(error);
5614
- markPreparedFailed(publicPrepared, results, message);
5615
- return requests.map(
5616
- (request, index) => results.get(index) ?? {
5617
- name: request.name,
5618
- version: request.requestedVersion,
5619
- success: false,
5620
- error: message
5621
- }
5622
- );
5623
- }
5624
- try {
5625
- for (const [index, plugin] of [
5626
- ...publicPrepared,
5627
- ...implicitPrepared
5628
- ].sort(([left], [right]) => left - right)) {
5629
- if (plugin.stagedPath) {
5630
- replaceDirectory(
5631
- plugin.stagedPath,
5632
- managedPluginPath(projectRoot, plugin.name)
5633
- );
5634
- }
5635
- options.beforeCommit?.(plugin, index);
5636
- }
5637
- atomicWriteJson(packageJsonPath, nextPackage);
5638
- ensureActionPluginGitignore(projectRoot);
5639
- const env = {
5640
- ...process.env,
5641
- [ACTION_PLUGIN_REENTRY_ENV]: ACTION_PLUGIN_REENTRY_VALUE
5642
- };
5643
- const peerSpecifiers = [...peerRanges].map(
5644
- ([name, range]) => `${name}@${range}`
5645
- );
5646
- if (options.runNpmInstall) {
5647
- options.runNpmInstall(peerSpecifiers, env, [...NPM_REIFY_ARGUMENTS]);
5648
- } else {
5649
- defaultRunNpmInstall(projectRoot, env);
5650
- }
5651
- assertNoInstallLifecycle(projectRoot, peerRanges.keys());
5652
- for (const [name, version] of Object.entries(nextPackage.actionPlugins)) {
5653
- verifyPluginGraph(projectRoot, name, version);
5654
- }
5655
- for (const [index, plugin] of [
5656
- ...publicPrepared,
5657
- ...implicitPrepared
5658
- ].sort(([left], [right]) => left - right)) {
5659
- options.afterCommit?.(plugin, index);
5660
- }
5661
- commitActionPluginTransaction(journal);
5662
- } catch (error) {
5663
- let message = error instanceof Error ? error.message : String(error);
5664
- try {
5665
- rollbackActionPluginTransaction(journal);
5666
- } catch (rollbackError) {
5667
- message = `${message}; rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`;
5668
- }
5669
- markPreparedFailed(publicPrepared, results, message);
5670
- return requests.map(
5671
- (request, index) => results.get(index) ?? {
5672
- name: request.name,
5673
- version: request.requestedVersion,
5674
- success: false,
5675
- error: message
5676
- }
5677
- );
5678
- }
5679
- for (const [index, plugin] of publicPrepared) {
5680
- const oldVersion = initialPackage.actionPlugins?.[plugin.name];
5681
- const skipped = oldVersion === plugin.version && initialPackage.dependencies?.[plugin.name] === localDependencySpec(plugin.name) && plugin.source === "managed" && plugin.stagedPath === null;
5682
- results.set(index, {
5683
- name: plugin.name,
5684
- version: plugin.version,
5685
- oldVersion,
5686
- success: true,
5687
- skipped
5688
- });
5689
- if (options.reportEvents !== false && mode === "install") {
5690
- if (!skipped) {
5691
- reportInstallEvent(plugin.name, plugin.version).catch(() => {
5692
- });
5693
- }
5694
- reportCreateInstanceEvent(plugin.name, plugin.version).catch(() => {
5695
- });
5696
- }
5697
- }
5698
- return requests.map(
5699
- (request, index) => results.get(index) ?? {
5700
- name: request.name,
5701
- version: request.requestedVersion,
5702
- success: false,
5703
- error: "Plugin was not processed"
5704
- }
5705
- );
5706
- } finally {
5707
- fs23.rmSync(stagingRoot, { recursive: true, force: true });
5708
- }
5709
- }
5710
- async function installPluginBatch(namesWithVersions, options = {}) {
5711
- const requests = namesWithVersions.map((value) => parsePluginName(value));
5712
- return executePluginBatch(
5713
- requests.map(({ name, version }) => ({
5714
- name,
5715
- requestedVersion: version
5716
- })),
5717
- "install",
5718
- options
5719
- );
5720
- }
5721
- async function initPluginBatch(plugins, options = {}) {
5722
- return executePluginBatch(
5723
- Object.entries(plugins).map(([name, version]) => ({
5724
- name,
5725
- requestedVersion: version
5726
- })),
5727
- "init",
5728
- options
5729
- );
5730
- }
5731
- async function updatePluginBatch(names, options = {}) {
5732
- const requests = names.map((value) => parsePluginName(value));
5733
- return executePluginBatch(
5734
- requests.map(({ name, version }) => ({
5735
- name,
5736
- requestedVersion: version
5737
- })),
5738
- "update",
5739
- options
5740
- );
5741
- }
5742
-
5743
- // src/commands/action-plugin/restore.handler.ts
5744
- import fs24 from "fs";
5745
- import path21 from "path";
5746
- async function defaultMaterializePlugin2(name, version, destination) {
5747
- let tgzPath;
5748
- if (hasCachedPlugin(name, version)) {
5749
- tgzPath = getCachePath(name, version);
5750
- } else {
5751
- const downloaded = await downloadPlugin(name, version);
5752
- if (downloaded.version !== version) {
5753
- throw new Error(
5754
- `Downloaded version mismatch for ${name}: expected ${version}, got ${downloaded.version}`
5755
- );
5756
- }
5757
- tgzPath = downloaded.tgzPath;
5758
- }
5759
- fs24.mkdirSync(path21.dirname(destination), { recursive: true });
5760
- extractTgzToDirectory(tgzPath, destination);
5761
- }
5762
- function assertRequiredPeers(projectRoot, pluginPath) {
5763
- const manifest = readPluginManifest(pluginPath);
5764
- const missing = Object.keys(requiredPeerDependencies(manifest)).filter(
5765
- (peer) => !lstatOrNull(path21.join(projectRoot, "node_modules", peer))
5766
- );
5767
- if (missing.length > 0) {
5768
- throw new Error(`Missing peer dependencies: ${missing.join(", ")}`);
5769
- }
5770
- }
5771
- async function restoreActionPlugins(plugins, options = {}) {
5772
- const projectRoot = resolveProjectRoot(options.projectRoot ?? process.cwd());
5773
- assertManagedRoot(projectRoot);
5774
- recoverInterruptedActionPluginTransaction(projectRoot);
5775
- const packageDocument = readPackageDocument(
5776
- path21.join(projectRoot, "package.json")
5777
- );
5778
- const stagingRoot = createStagingRoot();
5779
- const entries = Object.entries(plugins);
5780
- const results = /* @__PURE__ */ new Map();
5781
- const prepared = [];
5782
- try {
5783
- for (const [index, [name, version]] of entries.entries()) {
5784
- try {
5785
- assertPluginDependencyOwnership(packageDocument, name);
5786
- const graphBacked = packageDocument.dependencies?.[name] === localDependencySpec(name);
5787
- const targetPath = graphBacked ? managedPluginPath(projectRoot, name) : nodePluginPath(projectRoot, name);
5788
- if (graphBacked) assertManagedSourcePath(projectRoot, name);
5789
- if (lstatOrNull(targetPath)) {
5790
- try {
5791
- const existingManifest2 = readPluginManifest(targetPath);
5792
- if (existingManifest2.name !== name) {
5793
- throw new Error(
5794
- `Plugin identity mismatch: expected ${name}, got ${existingManifest2.name}`
5795
- );
5796
- }
5797
- } catch (error) {
5798
- if (error instanceof Error && error.message.startsWith("Plugin identity mismatch:")) {
5799
- throw error;
5800
- }
5801
- }
5802
- }
5803
- let existingManifest = null;
5804
- try {
5805
- const exactManifest = assertPluginIdentity(targetPath, name, version);
5806
- assertRequiredPeers(projectRoot, targetPath);
5807
- existingManifest = exactManifest;
5808
- } catch {
5809
- }
5810
- const stagedPath = path21.join(stagingRoot, "prepared", String(index));
5811
- if (existingManifest) {
5812
- if (graphBacked && hasWorkspaceDependencies(existingManifest)) {
5813
- fs24.mkdirSync(path21.dirname(stagedPath), { recursive: true });
5814
- fs24.cpSync(targetPath, stagedPath, {
5815
- recursive: true,
5816
- force: true,
5817
- verbatimSymlinks: true
5818
- });
5819
- normalizePluginWorkspaceDependencies(
5820
- stagedPath,
5821
- packageDocument,
5822
- projectRoot
5823
- );
5824
- prepared.push({ index, name, version, stagedPath, targetPath });
5825
- } else {
5826
- results.set(index, {
5827
- name,
5828
- version,
5829
- success: true,
5830
- skipped: true
5831
- });
5832
- }
5833
- continue;
5834
- }
5835
- await (options.materializePlugin ?? defaultMaterializePlugin2)(
5836
- name,
5837
- version,
5838
- stagedPath
5839
- );
5840
- assertPluginIdentity(stagedPath, name, version);
5841
- if (graphBacked) {
5842
- normalizePluginWorkspaceDependencies(
5843
- stagedPath,
5844
- packageDocument,
5845
- projectRoot
5846
- );
5847
- }
5848
- assertRequiredPeers(projectRoot, stagedPath);
5849
- prepared.push({ index, name, version, stagedPath, targetPath });
5850
- } catch (error) {
5851
- results.set(index, {
5852
- name,
5853
- version,
5854
- success: false,
5855
- error: error instanceof Error ? error.message : String(error)
5856
- });
5857
- }
5858
- }
5859
- if (prepared.length > 0) {
5860
- let journal;
5861
- try {
5862
- journal = beginActionPluginTransaction(
5863
- projectRoot,
5864
- prepared.map((plugin) => plugin.name)
5865
- );
5866
- } catch (error) {
5867
- const message = error instanceof Error ? error.message : String(error);
5868
- for (const plugin of prepared) {
5869
- results.set(plugin.index, {
5870
- name: plugin.name,
5871
- version: plugin.version,
5872
- success: false,
5873
- error: message
5874
- });
5875
- }
5876
- return entries.map(
5877
- ([name, version], index) => results.get(index) ?? {
5878
- name,
5879
- version,
5880
- success: false,
5881
- error: message
5882
- }
5883
- );
5884
- }
5885
- try {
5886
- for (const plugin of prepared) {
5887
- replaceDirectory(plugin.stagedPath, plugin.targetPath);
5888
- assertPluginIdentity(plugin.targetPath, plugin.name, plugin.version);
5889
- assertRequiredPeers(projectRoot, plugin.targetPath);
5890
- }
5891
- commitActionPluginTransaction(journal);
5892
- for (const plugin of prepared) {
5893
- results.set(plugin.index, {
5894
- name: plugin.name,
5895
- version: plugin.version,
5896
- success: true
5897
- });
5898
- }
5899
- } catch (error) {
5900
- let message = error instanceof Error ? error.message : String(error);
5901
- try {
5902
- rollbackActionPluginTransaction(journal);
5903
- } catch (rollbackError) {
5904
- message = `${message}; rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`;
5905
- }
5906
- for (const plugin of prepared) {
5907
- results.set(plugin.index, {
5908
- name: plugin.name,
5909
- version: plugin.version,
5910
- success: false,
5911
- error: message
5912
- });
5913
- }
5914
- }
4610
+ const filename = `${safeKey}@${version}.tgz`;
4611
+ return path14.join(getPluginCacheDir(), filename);
4612
+ }
4613
+ function hasCachedPlugin(pluginKey, version) {
4614
+ const cachePath = getCachePath(pluginKey, version);
4615
+ return fs17.existsSync(cachePath);
4616
+ }
4617
+ function listCachedPlugins() {
4618
+ const cacheDir = getPluginCacheDir();
4619
+ if (!fs17.existsSync(cacheDir)) {
4620
+ return [];
4621
+ }
4622
+ const files = fs17.readdirSync(cacheDir);
4623
+ const result = [];
4624
+ for (const file of files) {
4625
+ if (!file.endsWith(".tgz")) continue;
4626
+ const match = file.match(/^(.+)@(.+)\.tgz$/);
4627
+ if (!match) continue;
4628
+ const [, rawName, version] = match;
4629
+ const name = rawName.replace(/^_/, "@").replace(/_/, "/");
4630
+ const filePath = path14.join(cacheDir, file);
4631
+ const stat = fs17.statSync(filePath);
4632
+ result.push({
4633
+ name,
4634
+ version,
4635
+ filePath,
4636
+ size: stat.size,
4637
+ mtime: stat.mtime
4638
+ });
4639
+ }
4640
+ return result;
4641
+ }
4642
+ function cleanAllCache() {
4643
+ const cacheDir = getPluginCacheDir();
4644
+ if (!fs17.existsSync(cacheDir)) {
4645
+ return 0;
4646
+ }
4647
+ const files = fs17.readdirSync(cacheDir);
4648
+ let count = 0;
4649
+ for (const file of files) {
4650
+ if (file.endsWith(".tgz")) {
4651
+ fs17.unlinkSync(path14.join(cacheDir, file));
4652
+ count++;
5915
4653
  }
5916
- return entries.map(
5917
- ([name, version], index) => results.get(index) ?? {
5918
- name,
5919
- version,
5920
- success: false,
5921
- error: "Plugin was not restored"
5922
- }
5923
- );
5924
- } finally {
5925
- fs24.rmSync(stagingRoot, { recursive: true, force: true });
5926
4654
  }
4655
+ return count;
5927
4656
  }
5928
- async function restore(options = {}) {
5929
- console.log("[action-plugin] Restoring plugins from package.json...");
5930
- const results = await restoreActionPlugins(readActionPlugins(), options);
5931
- const failed = results.filter((result) => !result.success);
5932
- for (const result of results) {
5933
- if (result.success && !result.skipped) {
5934
- console.log(
5935
- `[action-plugin] \u2713 Restored ${result.name}@${result.version}`
5936
- );
5937
- } else if (!result.success) {
5938
- console.error(
5939
- `[action-plugin] \u2717 Failed to restore ${result.name}: ${result.error}`
5940
- );
4657
+ function cleanPluginCache(pluginKey, version) {
4658
+ const cacheDir = getPluginCacheDir();
4659
+ if (!fs17.existsSync(cacheDir)) {
4660
+ return 0;
4661
+ }
4662
+ const safeKey = pluginKey.replace(/[/@]/g, "_");
4663
+ const files = fs17.readdirSync(cacheDir);
4664
+ let count = 0;
4665
+ for (const file of files) {
4666
+ if (version) {
4667
+ if (file === `${safeKey}@${version}.tgz`) {
4668
+ fs17.unlinkSync(path14.join(cacheDir, file));
4669
+ count++;
4670
+ }
4671
+ } else {
4672
+ if (file.startsWith(`${safeKey}@`) && file.endsWith(".tgz")) {
4673
+ fs17.unlinkSync(path14.join(cacheDir, file));
4674
+ count++;
4675
+ }
5941
4676
  }
5942
4677
  }
5943
- if (failed.length > 0) process.exit(1);
4678
+ return count;
5944
4679
  }
5945
4680
 
5946
4681
  // src/commands/action-plugin/init.handler.ts
5947
- async function init(options = {}) {
5948
- recoverInterruptedActionPluginTransaction(
5949
- options.projectRoot ?? options.restoreOptions?.projectRoot ?? process.cwd()
5950
- );
5951
- if (process.env[ACTION_PLUGIN_REENTRY_ENV] === ACTION_PLUGIN_REENTRY_VALUE) {
5952
- await restore(options.restoreOptions);
5953
- return;
4682
+ async function installOneForInit(name, version) {
4683
+ try {
4684
+ const installedVersion2 = getPackageVersion(name);
4685
+ if (installedVersion2 === version) {
4686
+ return { name, version, success: true, skipped: true };
4687
+ }
4688
+ let tgzPath;
4689
+ let fromCache = false;
4690
+ if (hasCachedPlugin(name, version)) {
4691
+ console.log(`[action-plugin] \u21BB Restoring ${name}@${version} from cache...`);
4692
+ tgzPath = getCachePath(name, version);
4693
+ fromCache = true;
4694
+ } else {
4695
+ console.log(`[action-plugin] \u2193 Downloading ${name}@${version}...`);
4696
+ const downloadResult = await downloadPlugin(name, version);
4697
+ tgzPath = downloadResult.tgzPath;
4698
+ }
4699
+ const pluginDir = extractTgzToNodeModules(tgzPath, name);
4700
+ const pluginPkg = readPluginPackageJson(pluginDir);
4701
+ if (pluginPkg?.peerDependencies) {
4702
+ const missingDeps = checkMissingPeerDeps(pluginPkg.peerDependencies);
4703
+ if (missingDeps.length > 0) {
4704
+ installMissingDeps(missingDeps);
4705
+ }
4706
+ }
4707
+ const source = fromCache ? "from cache" : "downloaded";
4708
+ console.log(`[action-plugin] \u2713 Installed ${name}@${version} (${source})`);
4709
+ return { name, version, success: true };
4710
+ } catch (error) {
4711
+ const message = error instanceof Error ? error.message : String(error);
4712
+ console.error(`[action-plugin] \u2717 Failed to install ${name}: ${message}`);
4713
+ return { name, version, success: false, error: message };
5954
4714
  }
4715
+ }
4716
+ async function init() {
5955
4717
  console.log("[action-plugin] Reading plugins from package.json...");
5956
4718
  const plugins = readActionPlugins();
5957
4719
  const entries = Object.entries(plugins);
@@ -5961,234 +4723,219 @@ async function init(options = {}) {
5961
4723
  }
5962
4724
  console.log(`[action-plugin] Found ${entries.length} plugin(s) to install
5963
4725
  `);
5964
- const results = await initPluginBatch(plugins, options);
5965
- const failed = results.filter((result) => !result.success);
5966
- const skipped = results.filter((result) => result.success && result.skipped);
5967
- for (const result of results) {
5968
- if (result.success && !result.skipped) {
5969
- console.log(
5970
- `[action-plugin] \u2713 Installed ${result.name}@${result.version}`
5971
- );
5972
- } else if (!result.success) {
5973
- console.error(
5974
- `[action-plugin] \u2717 Failed to install ${result.name}: ${result.error}`
5975
- );
5976
- }
4726
+ const results = [];
4727
+ for (const [name, version] of entries) {
4728
+ const result = await installOneForInit(name, version);
4729
+ results.push(result);
5977
4730
  }
5978
- if (failed.length === 0) {
4731
+ console.log("");
4732
+ const successful = results.filter((r) => r.success && !r.skipped);
4733
+ const skipped = results.filter((r) => r.skipped);
4734
+ const failed = results.filter((r) => !r.success);
4735
+ if (successful.length > 0 || skipped.length > 0) {
5979
4736
  console.log(
5980
- `[action-plugin] \u2713 All plugins installed successfully (${results.length}/${entries.length})`
4737
+ `[action-plugin] \u2713 All plugins installed successfully (${successful.length + skipped.length}/${entries.length})`
5981
4738
  );
5982
4739
  if (skipped.length > 0) {
5983
- console.log(
5984
- ` Skipped (already installed): ${skipped.map((result) => result.name).join(", ")}`
5985
- );
4740
+ console.log(` Skipped (already installed): ${skipped.map((r) => r.name).join(", ")}`);
5986
4741
  }
5987
- return;
5988
4742
  }
5989
- console.log(
5990
- `[action-plugin] \u2717 Failed to install ${failed.length} plugin(s): ${failed.map((result) => result.name).join(", ")}`
5991
- );
5992
- process.exit(1);
4743
+ if (failed.length > 0) {
4744
+ console.log(`[action-plugin] \u2717 Failed to install ${failed.length} plugin(s): ${failed.map((r) => r.name).join(", ")}`);
4745
+ process.exit(1);
4746
+ }
5993
4747
  }
5994
4748
 
5995
4749
  // src/commands/action-plugin/install.handler.ts
5996
- async function install(namesWithVersion, options = {}) {
5997
- recoverInterruptedActionPluginTransaction(
5998
- options.projectRoot ?? process.cwd()
5999
- );
4750
+ function syncActionPluginsRecord(name, version) {
4751
+ const plugins = readActionPlugins();
4752
+ if (plugins[name] !== version) {
4753
+ plugins[name] = version;
4754
+ writeActionPlugins(plugins);
4755
+ console.log(`[action-plugin] Synced actionPlugins record: ${name}@${version}`);
4756
+ }
4757
+ }
4758
+ async function installOne(nameWithVersion) {
4759
+ const { name, version: requestedVersion } = parsePluginName(nameWithVersion);
4760
+ try {
4761
+ console.log(`[action-plugin] Installing ${name}@${requestedVersion}...`);
4762
+ const actualVersion = getPackageVersion(name);
4763
+ if (actualVersion && requestedVersion !== "latest") {
4764
+ if (actualVersion === requestedVersion) {
4765
+ console.log(`[action-plugin] Plugin ${name}@${requestedVersion} is already installed`);
4766
+ syncActionPluginsRecord(name, actualVersion);
4767
+ reportCreateInstanceEvent(name, actualVersion).catch(() => {
4768
+ });
4769
+ return { name, version: actualVersion, success: true, skipped: true };
4770
+ }
4771
+ }
4772
+ let targetVersion = requestedVersion;
4773
+ if (requestedVersion === "latest") {
4774
+ const latestInfo = await getPluginVersion(name, "latest");
4775
+ targetVersion = latestInfo.version;
4776
+ if (actualVersion === targetVersion) {
4777
+ console.log(`[action-plugin] Plugin ${name} is already up to date (version: ${actualVersion})`);
4778
+ syncActionPluginsRecord(name, actualVersion);
4779
+ reportCreateInstanceEvent(name, actualVersion).catch(() => {
4780
+ });
4781
+ return { name, version: actualVersion, success: true, skipped: true };
4782
+ }
4783
+ console.log(`[action-plugin] Found newer version: ${targetVersion} (installed: ${actualVersion || "none"})`);
4784
+ }
4785
+ let tgzPath;
4786
+ let fromCache = false;
4787
+ if (hasCachedPlugin(name, targetVersion)) {
4788
+ console.log(`[action-plugin] \u21BB Using cached ${name}@${targetVersion}...`);
4789
+ tgzPath = getCachePath(name, targetVersion);
4790
+ fromCache = true;
4791
+ } else {
4792
+ console.log(`[action-plugin] \u2193 Downloading ${name}@${targetVersion}...`);
4793
+ const downloadResult = await downloadPlugin(name, requestedVersion);
4794
+ tgzPath = downloadResult.tgzPath;
4795
+ }
4796
+ console.log(`[action-plugin] Extracting to node_modules...`);
4797
+ const pluginDir = extractTgzToNodeModules(tgzPath, name);
4798
+ const pluginPkg = readPluginPackageJson(pluginDir);
4799
+ if (pluginPkg?.peerDependencies) {
4800
+ const missingDeps = checkMissingPeerDeps(pluginPkg.peerDependencies);
4801
+ if (missingDeps.length > 0) {
4802
+ installMissingDeps(missingDeps);
4803
+ }
4804
+ }
4805
+ const installedVersion2 = getPackageVersion(name) || targetVersion;
4806
+ const plugins = readActionPlugins();
4807
+ plugins[name] = installedVersion2;
4808
+ writeActionPlugins(plugins);
4809
+ const source = fromCache ? "from cache" : "downloaded";
4810
+ console.log(`[action-plugin] Successfully installed ${name}@${installedVersion2} (${source})`);
4811
+ reportInstallEvent(name, installedVersion2).catch(() => {
4812
+ });
4813
+ reportCreateInstanceEvent(name, installedVersion2).catch(() => {
4814
+ });
4815
+ return { name, version: installedVersion2, success: true };
4816
+ } catch (error) {
4817
+ const message = error instanceof Error ? error.message : String(error);
4818
+ console.error(`[action-plugin] Failed to install ${name}: ${message}`);
4819
+ return { name, version: requestedVersion, success: false, error: message };
4820
+ }
4821
+ }
4822
+ async function install(namesWithVersion) {
6000
4823
  if (namesWithVersion.length === 0) {
6001
4824
  console.error("[action-plugin] No plugin names provided");
6002
4825
  process.exit(1);
6003
- return;
6004
4826
  }
6005
- const results = await installPluginBatch(namesWithVersion, options);
6006
- for (const result of results) {
6007
- if (result.success && result.skipped) {
6008
- console.log(
6009
- `[action-plugin] Plugin ${result.name}@${result.version} is already installed`
6010
- );
6011
- } else if (result.success) {
6012
- console.log(
6013
- `[action-plugin] Successfully installed ${result.name}@${result.version}`
6014
- );
6015
- } else {
6016
- console.error(
6017
- `[action-plugin] Failed to install ${result.name}: ${result.error}`
6018
- );
6019
- }
4827
+ const results = [];
4828
+ for (const nameWithVersion of namesWithVersion) {
4829
+ console.log(`[action-plugin] Processing ${nameWithVersion}...`);
4830
+ const result = await installOne(nameWithVersion);
4831
+ results.push(result);
6020
4832
  }
6021
4833
  if (namesWithVersion.length > 1) {
6022
- const successful = results.filter(
6023
- (result) => result.success && !result.skipped
6024
- );
6025
- const skipped = results.filter((result) => result.success && result.skipped);
6026
- const failed = results.filter((result) => !result.success);
6027
4834
  console.log("\n[action-plugin] Installation summary:");
4835
+ const successful = results.filter((r) => r.success && !r.skipped);
4836
+ const skipped = results.filter((r) => r.skipped);
4837
+ const failed = results.filter((r) => !r.success);
6028
4838
  if (successful.length > 0) {
6029
- console.log(
6030
- ` \u2713 Installed: ${successful.map((result) => `${result.name}@${result.version}`).join(", ")}`
6031
- );
4839
+ console.log(` \u2713 Installed: ${successful.map((r) => `${r.name}@${r.version}`).join(", ")}`);
6032
4840
  }
6033
4841
  if (skipped.length > 0) {
6034
- console.log(
6035
- ` \u25CB Skipped (up to date): ${skipped.map((result) => result.name).join(", ")}`
6036
- );
4842
+ console.log(` \u25CB Skipped (up to date): ${skipped.map((r) => r.name).join(", ")}`);
6037
4843
  }
6038
4844
  if (failed.length > 0) {
6039
- console.log(
6040
- ` \u2717 Failed: ${failed.map((result) => result.name).join(", ")}`
6041
- );
4845
+ console.log(` \u2717 Failed: ${failed.map((r) => r.name).join(", ")}`);
6042
4846
  }
6043
4847
  }
6044
- if (results.some((result) => !result.success)) process.exit(1);
4848
+ if (results.some((r) => !r.success)) {
4849
+ process.exit(1);
4850
+ }
6045
4851
  }
6046
4852
 
6047
4853
  // src/commands/action-plugin/update.handler.ts
6048
- async function update(names, options = {}) {
6049
- recoverInterruptedActionPluginTransaction(
6050
- options.projectRoot ?? process.cwd()
6051
- );
6052
- if (names.length === 0) {
6053
- console.error("[action-plugin] No plugin names provided");
6054
- process.exit(1);
6055
- return;
6056
- }
6057
- const results = await updatePluginBatch(names, options);
6058
- for (const result of results) {
6059
- if (result.notInstalled) {
6060
- console.error(`[action-plugin] Plugin ${result.name} is not installed`);
6061
- } else if (result.success && result.skipped) {
6062
- console.log(
6063
- `[action-plugin] Plugin ${result.name} is already up to date (version: ${result.version})`
6064
- );
6065
- } else if (result.success) {
6066
- console.log(
6067
- `[action-plugin] Successfully updated ${result.name} to ${result.version}`
6068
- );
6069
- } else {
6070
- console.error(
6071
- `[action-plugin] Failed to update ${result.name}: ${result.error}`
6072
- );
4854
+ async function updateOne(nameWithVersion) {
4855
+ let tgzPath;
4856
+ const { name } = parsePluginName(nameWithVersion);
4857
+ try {
4858
+ console.log(`[action-plugin] Updating ${name}...`);
4859
+ if (!isPluginInstalled(name)) {
4860
+ console.error(`[action-plugin] Plugin ${name} is not installed`);
4861
+ return { name, success: false, notInstalled: true };
4862
+ }
4863
+ const oldVersion = getInstalledPluginVersion(name) || "unknown";
4864
+ console.log(`[action-plugin] Current version: ${oldVersion}`);
4865
+ const downloadResult = await downloadPlugin(name, "latest");
4866
+ tgzPath = downloadResult.tgzPath;
4867
+ if (oldVersion === downloadResult.version) {
4868
+ console.log(`[action-plugin] Plugin ${name} is already up to date (version: ${downloadResult.version})`);
4869
+ return { name, oldVersion, newVersion: downloadResult.version, success: true, skipped: true };
4870
+ }
4871
+ npmInstall(tgzPath);
4872
+ const installedVersion2 = getPackageVersion(name) || downloadResult.version;
4873
+ const plugins = readActionPlugins();
4874
+ plugins[name] = installedVersion2;
4875
+ writeActionPlugins(plugins);
4876
+ console.log(`[action-plugin] Successfully updated ${name} to ${installedVersion2}`);
4877
+ return { name, oldVersion, newVersion: installedVersion2, success: true };
4878
+ } catch (error) {
4879
+ const message = error instanceof Error ? error.message : String(error);
4880
+ console.error(`[action-plugin] Failed to update ${name}: ${message}`);
4881
+ return { name, success: false, error: message };
4882
+ } finally {
4883
+ if (tgzPath) {
4884
+ cleanupTempFile(tgzPath);
6073
4885
  }
6074
4886
  }
6075
- if (names.length > 1) printSummary(results);
6076
- if (results.some((result) => !result.success && !result.notInstalled)) {
6077
- process.exit(1);
6078
- }
6079
4887
  }
6080
- function printSummary(results) {
6081
- const updated = results.filter((result) => result.success && !result.skipped);
6082
- const skipped = results.filter((result) => result.success && result.skipped);
6083
- const notInstalled = results.filter((result) => result.notInstalled);
6084
- const failed = results.filter(
6085
- (result) => !result.success && !result.notInstalled
6086
- );
6087
- console.log("\n[action-plugin] Update summary:");
6088
- if (updated.length > 0) {
6089
- console.log(
6090
- ` \u2713 Updated: ${updated.map(
6091
- (result) => `${result.name} (${result.oldVersion ?? "unknown"} \u2192 ${result.version})`
6092
- ).join(", ")}`
6093
- );
6094
- }
6095
- if (skipped.length > 0) {
6096
- console.log(
6097
- ` \u25CB Skipped (up to date): ${skipped.map((result) => result.name).join(", ")}`
6098
- );
6099
- }
6100
- if (notInstalled.length > 0) {
6101
- console.log(
6102
- ` \u26A0 Not installed: ${notInstalled.map((result) => result.name).join(", ")}`
6103
- );
6104
- }
6105
- if (failed.length > 0) {
6106
- console.log(` \u2717 Failed: ${failed.map((result) => result.name).join(", ")}`);
4888
+ async function update(names) {
4889
+ if (names.length === 0) {
4890
+ console.error("[action-plugin] No plugin names provided");
4891
+ process.exit(1);
6107
4892
  }
6108
- }
6109
-
6110
- // src/commands/action-plugin/remove.handler.ts
6111
- import fs25 from "fs";
6112
- import path22 from "path";
6113
- async function removePluginGraph(nameWithVersion, options = {}) {
6114
- const projectRoot = resolveProjectRoot(options.projectRoot ?? process.cwd());
6115
- assertManagedRoot(projectRoot);
6116
- recoverInterruptedActionPluginTransaction(projectRoot);
6117
- const { name } = parsePluginName(nameWithVersion);
6118
- const packageJsonPath = path22.join(projectRoot, "package.json");
6119
- const initialPackage = readPackageDocument(packageJsonPath);
6120
- if (!initialPackage.actionPlugins?.[name]) {
6121
- throw new Error(`Plugin ${name} is not installed`);
4893
+ const results = [];
4894
+ for (const name of names) {
4895
+ const result = await updateOne(name);
4896
+ results.push(result);
6122
4897
  }
6123
- assertPluginDependencyOwnership(initialPackage, name);
6124
- const journal = beginActionPluginTransaction(projectRoot, [name]);
6125
- try {
6126
- const nextPackage = JSON.parse(
6127
- JSON.stringify(initialPackage)
6128
- );
6129
- nextPackage.actionPlugins = { ...nextPackage.actionPlugins ?? {} };
6130
- delete nextPackage.actionPlugins[name];
6131
- if (nextPackage.dependencies?.[name] === localDependencySpec(name)) {
6132
- nextPackage.dependencies = { ...nextPackage.dependencies };
6133
- delete nextPackage.dependencies[name];
6134
- }
6135
- if (Object.keys(nextPackage.actionPlugins).length === 0) {
6136
- removeActionPluginLifecycle(nextPackage);
6137
- }
6138
- atomicWriteJson(packageJsonPath, nextPackage);
6139
- removePluginLockEntries(projectRoot, name);
6140
- removePathAndEmptyParents(
6141
- nodePluginPath(projectRoot, name),
6142
- path22.join(projectRoot, "node_modules")
6143
- );
6144
- removePathAndEmptyParents(
6145
- managedPluginPath(projectRoot, name),
6146
- managedRootPath(projectRoot)
6147
- );
6148
- if (Object.keys(nextPackage.actionPlugins).length === 0) {
6149
- removeActionPluginGitignore(projectRoot);
4898
+ if (names.length > 1) {
4899
+ console.log("\n[action-plugin] Update summary:");
4900
+ const updated = results.filter((r) => r.success && !r.skipped);
4901
+ const skipped = results.filter((r) => r.skipped);
4902
+ const notInstalled = results.filter((r) => r.notInstalled);
4903
+ const failed = results.filter((r) => !r.success && !r.notInstalled);
4904
+ if (updated.length > 0) {
4905
+ console.log(` \u2713 Updated: ${updated.map((r) => `${r.name} (${r.oldVersion} \u2192 ${r.newVersion})`).join(", ")}`);
6150
4906
  }
6151
- options.afterChange?.();
6152
- const committedPackage2 = readPackageDocument(packageJsonPath);
6153
- if (committedPackage2.actionPlugins?.[name] || committedPackage2.dependencies?.[name] || lstatOrNull(nodePluginPath(projectRoot, name)) || lstatOrNull(managedPluginPath(projectRoot, name))) {
6154
- throw new Error(`Plugin removal left managed state for ${name}`);
4907
+ if (skipped.length > 0) {
4908
+ console.log(` \u25CB Skipped (up to date): ${skipped.map((r) => r.name).join(", ")}`);
6155
4909
  }
6156
- const lockPath = findLockfilePath(projectRoot);
6157
- if (fs25.existsSync(lockPath)) {
6158
- const lock = JSON.parse(fs25.readFileSync(lockPath, "utf-8"));
6159
- if (lock.packages?.[sourceLockKey(name)] || lock.packages?.[nodeLockKey(name)]) {
6160
- throw new Error(`Plugin removal left lock state for ${name}`);
6161
- }
4910
+ if (notInstalled.length > 0) {
4911
+ console.log(` \u26A0 Not installed: ${notInstalled.map((r) => r.name).join(", ")}`);
6162
4912
  }
6163
- commitActionPluginTransaction(journal);
6164
- } catch (error) {
6165
- try {
6166
- rollbackActionPluginTransaction(journal);
6167
- } catch (rollbackError) {
6168
- throw new Error(
6169
- `${error instanceof Error ? error.message : String(error)}; rollback failed: ${rollbackError instanceof Error ? rollbackError.message : String(rollbackError)}`
6170
- );
4913
+ if (failed.length > 0) {
4914
+ console.log(` \u2717 Failed: ${failed.map((r) => r.name).join(", ")}`);
6171
4915
  }
6172
- throw error;
6173
4916
  }
6174
- const committedPackage = readPackageDocument(packageJsonPath);
6175
- if (Object.keys(committedPackage.actionPlugins ?? {}).length === 0 && fs25.existsSync(managedRootPath(projectRoot))) {
6176
- fs25.rmSync(managedRootPath(projectRoot), { recursive: true, force: true });
4917
+ if (results.some((r) => !r.success && !r.notInstalled)) {
4918
+ process.exit(1);
6177
4919
  }
6178
4920
  }
6179
- async function remove(nameWithVersion, options = {}) {
4921
+
4922
+ // src/commands/action-plugin/remove.handler.ts
4923
+ async function remove(nameWithVersion) {
6180
4924
  try {
6181
4925
  const { name } = parsePluginName(nameWithVersion);
6182
4926
  console.log(`[action-plugin] Removing ${name}...`);
6183
- await removePluginGraph(nameWithVersion, options);
4927
+ if (!isPluginInstalled(name)) {
4928
+ console.error(`[action-plugin] Plugin ${name} is not installed`);
4929
+ process.exit(1);
4930
+ }
4931
+ removePluginDirectory(name);
4932
+ const plugins = readActionPlugins();
4933
+ delete plugins[name];
4934
+ writeActionPlugins(plugins);
6184
4935
  console.log(`[action-plugin] Successfully removed ${name}`);
6185
4936
  } catch (error) {
6186
4937
  const message = error instanceof Error ? error.message : String(error);
6187
- if (message.includes("is not installed")) {
6188
- console.error(`[action-plugin] ${message}`);
6189
- } else {
6190
- console.error(`[action-plugin] Failed to remove: ${message}`);
6191
- }
4938
+ console.error(`[action-plugin] Failed to remove: ${message}`);
6192
4939
  process.exit(1);
6193
4940
  }
6194
4941
  }
@@ -6196,22 +4943,23 @@ async function remove(nameWithVersion, options = {}) {
6196
4943
  // src/commands/action-plugin/list.handler.ts
6197
4944
  async function list() {
6198
4945
  try {
6199
- recoverInterruptedActionPluginTransaction(process.cwd());
6200
4946
  const plugins = Object.entries(readActionPlugins());
6201
4947
  if (plugins.length === 0) {
6202
4948
  console.log("[action-plugin] No plugins installed");
6203
- console.log(
6204
- '[action-plugin] Use "action-plugin install <name>" to install a plugin'
6205
- );
4949
+ console.log('[action-plugin] Use "action-plugin install <name>" to install a plugin');
6206
4950
  return;
6207
4951
  }
6208
4952
  console.log("[action-plugin] Installed plugins:\n");
6209
4953
  const nameWidth = Math.max(40, ...plugins.map(([name]) => name.length + 2));
6210
4954
  const versionWidth = 15;
6211
- console.log(" " + "Plugin".padEnd(nameWidth) + "Version");
4955
+ console.log(
4956
+ " " + "Plugin".padEnd(nameWidth) + "Version"
4957
+ );
6212
4958
  console.log(" " + "-".repeat(nameWidth + versionWidth));
6213
4959
  for (const [name, version] of plugins) {
6214
- console.log(" " + name.padEnd(nameWidth) + version);
4960
+ console.log(
4961
+ " " + name.padEnd(nameWidth) + version
4962
+ );
6215
4963
  }
6216
4964
  console.log(`
6217
4965
  Total: ${plugins.length} plugin(s)`);
@@ -6223,25 +4971,15 @@ async function list() {
6223
4971
  }
6224
4972
 
6225
4973
  // src/commands/action-plugin/cache.handler.ts
6226
- function recoverBeforeCacheOperation(options) {
6227
- recoverInterruptedActionPluginTransaction(
6228
- options.projectRoot ?? process.cwd()
6229
- );
6230
- }
6231
- async function cacheList(options = {}) {
6232
- recoverBeforeCacheOperation(options);
4974
+ async function cacheList() {
6233
4975
  const cached = listCachedPlugins();
6234
4976
  if (cached.length === 0) {
6235
4977
  console.log("[action-plugin] No cached plugins found");
6236
4978
  return;
6237
4979
  }
6238
4980
  console.log("[action-plugin] Cached plugins:\n");
6239
- console.log(
6240
- " Name Version Size Modified"
6241
- );
6242
- console.log(
6243
- " \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"
6244
- );
4981
+ console.log(" Name Version Size Modified");
4982
+ console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
6245
4983
  let totalSize = 0;
6246
4984
  for (const plugin of cached) {
6247
4985
  const name = plugin.name.padEnd(38);
@@ -6251,25 +4989,16 @@ async function cacheList(options = {}) {
6251
4989
  console.log(` ${name} ${version} ${size} ${mtime}`);
6252
4990
  totalSize += plugin.size;
6253
4991
  }
6254
- console.log(
6255
- " \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"
6256
- );
6257
- console.log(
6258
- ` Total: ${cached.length} cached file(s), ${formatSize(totalSize)}`
6259
- );
4992
+ console.log(" \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
4993
+ console.log(` Total: ${cached.length} cached file(s), ${formatSize(totalSize)}`);
6260
4994
  }
6261
- async function cacheClean(pluginName, version, options = {}) {
6262
- recoverBeforeCacheOperation(options);
4995
+ async function cacheClean(pluginName, version) {
6263
4996
  let count;
6264
4997
  if (pluginName) {
6265
- console.log(
6266
- `[action-plugin] Cleaning cache for ${pluginName}${version ? `@${version}` : ""}...`
6267
- );
4998
+ console.log(`[action-plugin] Cleaning cache for ${pluginName}${version ? `@${version}` : ""}...`);
6268
4999
  count = cleanPluginCache(pluginName, version);
6269
5000
  if (count === 0) {
6270
- console.log(
6271
- `[action-plugin] No cached files found for ${pluginName}${version ? `@${version}` : ""}`
6272
- );
5001
+ console.log(`[action-plugin] No cached files found for ${pluginName}${version ? `@${version}` : ""}`);
6273
5002
  } else {
6274
5003
  console.log(`[action-plugin] Cleaned ${count} cached file(s)`);
6275
5004
  }
@@ -6303,15 +5032,6 @@ var initCommand = {
6303
5032
  });
6304
5033
  }
6305
5034
  };
6306
- var restoreCommand = {
6307
- name: "restore",
6308
- description: "Restore action plugins without changing npm dependencies",
6309
- register(program) {
6310
- program.command(this.name).description(this.description).action(async () => {
6311
- await restore();
6312
- });
6313
- }
6314
- };
6315
5035
  var installCommand = {
6316
5036
  name: "install",
6317
5037
  description: "Install action plugin(s) (default: latest version)",
@@ -6373,49 +5093,49 @@ var cacheCleanCommand = {
6373
5093
  var actionPluginCommandGroup = {
6374
5094
  name: "action-plugin",
6375
5095
  description: "Manage action plugins",
6376
- commands: [initCommand, restoreCommand, installCommand, updateCommand, removeCommand, listCommand, cacheListCommand, cacheCleanCommand]
5096
+ commands: [initCommand, installCommand, updateCommand, removeCommand, listCommand, cacheListCommand, cacheCleanCommand]
6377
5097
  };
6378
5098
 
6379
5099
  // src/commands/capability/utils.ts
6380
- import fs26 from "fs";
6381
- import { createRequire as createRequire3 } from "module";
6382
- import path23 from "path";
5100
+ import fs18 from "fs";
5101
+ import { createRequire as createRequire2 } from "module";
5102
+ import path15 from "path";
6383
5103
  var CAPABILITIES_DIR = "server/capabilities";
6384
5104
  var SHARED_CAPABILITIES_DIR = "shared/capabilities";
6385
5105
  function getProjectRoot2() {
6386
5106
  return process.cwd();
6387
5107
  }
6388
5108
  function getCapabilitiesDir() {
6389
- const sharedDir = path23.join(getProjectRoot2(), SHARED_CAPABILITIES_DIR);
6390
- if (fs26.existsSync(sharedDir)) {
5109
+ const sharedDir = path15.join(getProjectRoot2(), SHARED_CAPABILITIES_DIR);
5110
+ if (fs18.existsSync(sharedDir)) {
6391
5111
  return sharedDir;
6392
5112
  }
6393
- return path23.join(getProjectRoot2(), CAPABILITIES_DIR);
5113
+ return path15.join(getProjectRoot2(), CAPABILITIES_DIR);
6394
5114
  }
6395
5115
  function getCapabilityPath(id) {
6396
- return path23.join(getCapabilitiesDir(), `${id}.json`);
5116
+ return path15.join(getCapabilitiesDir(), `${id}.json`);
6397
5117
  }
6398
5118
  function getPluginManifestPath(pluginKey) {
6399
- return path23.join(getProjectRoot2(), "node_modules", pluginKey, "manifest.json");
5119
+ return path15.join(getProjectRoot2(), "node_modules", pluginKey, "manifest.json");
6400
5120
  }
6401
5121
  function capabilitiesDirExists() {
6402
- return fs26.existsSync(getCapabilitiesDir());
5122
+ return fs18.existsSync(getCapabilitiesDir());
6403
5123
  }
6404
5124
  function listCapabilityIds() {
6405
5125
  const dir = getCapabilitiesDir();
6406
- if (!fs26.existsSync(dir)) {
5126
+ if (!fs18.existsSync(dir)) {
6407
5127
  return [];
6408
5128
  }
6409
- const files = fs26.readdirSync(dir);
5129
+ const files = fs18.readdirSync(dir);
6410
5130
  return files.filter((f) => f.endsWith(".json") && f !== "capabilities.json").map((f) => f.replace(/\.json$/, ""));
6411
5131
  }
6412
5132
  function readCapability(id) {
6413
5133
  const filePath = getCapabilityPath(id);
6414
- if (!fs26.existsSync(filePath)) {
5134
+ if (!fs18.existsSync(filePath)) {
6415
5135
  throw new Error(`Capability not found: ${id}`);
6416
5136
  }
6417
5137
  try {
6418
- const content = fs26.readFileSync(filePath, "utf-8");
5138
+ const content = fs18.readFileSync(filePath, "utf-8");
6419
5139
  return JSON.parse(content);
6420
5140
  } catch (error) {
6421
5141
  if (error instanceof SyntaxError) {
@@ -6440,13 +5160,13 @@ function readAllCapabilities() {
6440
5160
  }
6441
5161
  return capabilities;
6442
5162
  }
6443
- function readPluginManifest3(pluginKey) {
5163
+ function readPluginManifest(pluginKey) {
6444
5164
  const manifestPath = getPluginManifestPath(pluginKey);
6445
- if (!fs26.existsSync(manifestPath)) {
5165
+ if (!fs18.existsSync(manifestPath)) {
6446
5166
  throw new Error(`Plugin not installed: ${pluginKey} (manifest.json not found)`);
6447
5167
  }
6448
5168
  try {
6449
- const content = fs26.readFileSync(manifestPath, "utf-8");
5169
+ const content = fs18.readFileSync(manifestPath, "utf-8");
6450
5170
  return JSON.parse(content);
6451
5171
  } catch (error) {
6452
5172
  if (error instanceof SyntaxError) {
@@ -6463,7 +5183,7 @@ function hasValidParamsSchema(paramsSchema) {
6463
5183
  }
6464
5184
  async function loadPlugin(pluginKey) {
6465
5185
  try {
6466
- const userRequire = createRequire3(path23.join(getProjectRoot2(), "package.json"));
5186
+ const userRequire = createRequire2(path15.join(getProjectRoot2(), "package.json"));
6467
5187
  const resolvedPath = userRequire.resolve(pluginKey);
6468
5188
  const pluginModule = await import(resolvedPath);
6469
5189
  const pluginPackage = pluginModule.default ?? pluginModule;
@@ -6482,7 +5202,7 @@ async function loadPlugin(pluginKey) {
6482
5202
  }
6483
5203
  async function hydrateCapability(capability) {
6484
5204
  try {
6485
- const manifest = readPluginManifest3(capability.pluginKey);
5205
+ const manifest = readPluginManifest(capability.pluginKey);
6486
5206
  if (!manifest.actions || manifest.actions.length === 0) {
6487
5207
  throw new Error(`Plugin ${capability.pluginKey} has no actions defined`);
6488
5208
  }
@@ -6626,9 +5346,9 @@ var capabilityCommandGroup = {
6626
5346
  import { execFile } from "child_process";
6627
5347
 
6628
5348
  // src/commands/component/registry-preparer.ts
6629
- import fs27 from "fs";
6630
- import path24 from "path";
6631
- import os2 from "os";
5349
+ import fs19 from "fs";
5350
+ import path16 from "path";
5351
+ import os from "os";
6632
5352
 
6633
5353
  // src/commands/component/service.ts
6634
5354
  import { mapValues } from "es-toolkit";
@@ -6687,7 +5407,7 @@ async function sendInstallEvent(key) {
6687
5407
  }
6688
5408
 
6689
5409
  // src/commands/component/registry-preparer.ts
6690
- var REGISTRY_TEMP_DIR = path24.join(os2.tmpdir(), "miaoda-registry");
5410
+ var REGISTRY_TEMP_DIR = path16.join(os.tmpdir(), "miaoda-registry");
6691
5411
  function parseComponentKey(key) {
6692
5412
  const match = key.match(/^@([^/]+)\/(.+)$/);
6693
5413
  if (!match) {
@@ -6699,11 +5419,11 @@ function parseComponentKey(key) {
6699
5419
  }
6700
5420
  function getLocalRegistryPath(key) {
6701
5421
  const { scope, name } = parseComponentKey(key);
6702
- return path24.join(REGISTRY_TEMP_DIR, scope, `${name}.json`);
5422
+ return path16.join(REGISTRY_TEMP_DIR, scope, `${name}.json`);
6703
5423
  }
6704
5424
  function ensureDir(dirPath) {
6705
- if (!fs27.existsSync(dirPath)) {
6706
- fs27.mkdirSync(dirPath, { recursive: true });
5425
+ if (!fs19.existsSync(dirPath)) {
5426
+ fs19.mkdirSync(dirPath, { recursive: true });
6707
5427
  }
6708
5428
  }
6709
5429
  async function prepareRecursive(key, visited) {
@@ -6736,8 +5456,8 @@ async function prepareRecursive(key, visited) {
6736
5456
  registryDependencies: deps.map((dep) => getLocalRegistryPath(dep))
6737
5457
  };
6738
5458
  const localPath = getLocalRegistryPath(key);
6739
- ensureDir(path24.dirname(localPath));
6740
- fs27.writeFileSync(localPath, JSON.stringify(rewrittenItem, null, 2), "utf-8");
5459
+ ensureDir(path16.dirname(localPath));
5460
+ fs19.writeFileSync(localPath, JSON.stringify(rewrittenItem, null, 2), "utf-8");
6741
5461
  debug("\u4FDD\u5B58\u5230: %s", localPath);
6742
5462
  }
6743
5463
  async function prepareComponentRegistryItems(id) {
@@ -6747,18 +5467,18 @@ async function prepareComponentRegistryItems(id) {
6747
5467
  }
6748
5468
  function cleanupTempDir() {
6749
5469
  try {
6750
- if (fs27.existsSync(REGISTRY_TEMP_DIR)) {
6751
- fs27.rmSync(REGISTRY_TEMP_DIR, { recursive: true, force: true });
5470
+ if (fs19.existsSync(REGISTRY_TEMP_DIR)) {
5471
+ fs19.rmSync(REGISTRY_TEMP_DIR, { recursive: true, force: true });
6752
5472
  }
6753
5473
  } catch {
6754
5474
  }
6755
5475
  }
6756
5476
  function getDownloadedRegistryItem(itemId) {
6757
5477
  const localPath = getLocalRegistryPath(itemId);
6758
- if (!fs27.existsSync(localPath)) {
5478
+ if (!fs19.existsSync(localPath)) {
6759
5479
  return null;
6760
5480
  }
6761
- const content = fs27.readFileSync(localPath, "utf-8");
5481
+ const content = fs19.readFileSync(localPath, "utf-8");
6762
5482
  return JSON.parse(content);
6763
5483
  }
6764
5484
 
@@ -6926,58 +5646,58 @@ var componentCommandGroup = {
6926
5646
  };
6927
5647
 
6928
5648
  // src/commands/migration/version-manager.ts
6929
- import fs28 from "fs";
6930
- import path25 from "path";
5649
+ import fs20 from "fs";
5650
+ import path17 from "path";
6931
5651
  var PACKAGE_JSON = "package.json";
6932
5652
  var VERSION_FIELD = "migrationVersion";
6933
5653
  function getPackageJsonPath2() {
6934
- return path25.join(process.cwd(), PACKAGE_JSON);
5654
+ return path17.join(process.cwd(), PACKAGE_JSON);
6935
5655
  }
6936
5656
  function getCurrentVersion() {
6937
5657
  const pkgPath = getPackageJsonPath2();
6938
- if (!fs28.existsSync(pkgPath)) {
5658
+ if (!fs20.existsSync(pkgPath)) {
6939
5659
  throw new Error("package.json not found");
6940
5660
  }
6941
- const pkg2 = JSON.parse(fs28.readFileSync(pkgPath, "utf-8"));
5661
+ const pkg2 = JSON.parse(fs20.readFileSync(pkgPath, "utf-8"));
6942
5662
  return pkg2[VERSION_FIELD] ?? 0;
6943
5663
  }
6944
5664
  function setCurrentVersion(version) {
6945
5665
  const pkgPath = getPackageJsonPath2();
6946
- const pkg2 = JSON.parse(fs28.readFileSync(pkgPath, "utf-8"));
5666
+ const pkg2 = JSON.parse(fs20.readFileSync(pkgPath, "utf-8"));
6947
5667
  pkg2[VERSION_FIELD] = version;
6948
- fs28.writeFileSync(pkgPath, JSON.stringify(pkg2, null, 2) + "\n", "utf-8");
5668
+ fs20.writeFileSync(pkgPath, JSON.stringify(pkg2, null, 2) + "\n", "utf-8");
6949
5669
  }
6950
5670
 
6951
5671
  // src/commands/migration/versions/v001_capability/json-migrator/detector.ts
6952
- import fs30 from "fs";
6953
- import path27 from "path";
5672
+ import fs22 from "fs";
5673
+ import path19 from "path";
6954
5674
 
6955
5675
  // src/commands/migration/versions/v001_capability/utils.ts
6956
- import fs29 from "fs";
6957
- import path26 from "path";
5676
+ import fs21 from "fs";
5677
+ import path18 from "path";
6958
5678
  var CAPABILITIES_DIR2 = "server/capabilities";
6959
5679
  function getProjectRoot3() {
6960
5680
  return process.cwd();
6961
5681
  }
6962
5682
  function getCapabilitiesDir2() {
6963
- return path26.join(getProjectRoot3(), CAPABILITIES_DIR2);
5683
+ return path18.join(getProjectRoot3(), CAPABILITIES_DIR2);
6964
5684
  }
6965
5685
  function getPluginManifestPath2(pluginKey) {
6966
- return path26.join(getProjectRoot3(), "node_modules", pluginKey, "manifest.json");
5686
+ return path18.join(getProjectRoot3(), "node_modules", pluginKey, "manifest.json");
6967
5687
  }
6968
5688
 
6969
5689
  // src/commands/migration/versions/v001_capability/json-migrator/detector.ts
6970
5690
  function detectJsonMigration() {
6971
5691
  const capabilitiesDir = getCapabilitiesDir2();
6972
- const oldFilePath = path27.join(capabilitiesDir, "capabilities.json");
6973
- if (!fs30.existsSync(oldFilePath)) {
5692
+ const oldFilePath = path19.join(capabilitiesDir, "capabilities.json");
5693
+ if (!fs22.existsSync(oldFilePath)) {
6974
5694
  return {
6975
5695
  needsMigration: false,
6976
5696
  reason: "capabilities.json not found"
6977
5697
  };
6978
5698
  }
6979
5699
  try {
6980
- const content = fs30.readFileSync(oldFilePath, "utf-8");
5700
+ const content = fs22.readFileSync(oldFilePath, "utf-8");
6981
5701
  const parsed = JSON.parse(content);
6982
5702
  if (!Array.isArray(parsed)) {
6983
5703
  return {
@@ -7028,8 +5748,8 @@ async function check(options) {
7028
5748
  }
7029
5749
 
7030
5750
  // src/commands/migration/versions/v001_capability/json-migrator/index.ts
7031
- import fs31 from "fs";
7032
- import path28 from "path";
5751
+ import fs23 from "fs";
5752
+ import path20 from "path";
7033
5753
 
7034
5754
  // src/commands/migration/versions/v001_capability/mapping.ts
7035
5755
  var DEFAULT_PLUGIN_VERSION = "1.0.0";
@@ -7259,18 +5979,18 @@ function transformCapabilities(oldCapabilities) {
7259
5979
  // src/commands/migration/versions/v001_capability/json-migrator/index.ts
7260
5980
  function loadExistingCapabilities() {
7261
5981
  const capabilitiesDir = getCapabilitiesDir2();
7262
- if (!fs31.existsSync(capabilitiesDir)) {
5982
+ if (!fs23.existsSync(capabilitiesDir)) {
7263
5983
  return [];
7264
5984
  }
7265
- const files = fs31.readdirSync(capabilitiesDir);
5985
+ const files = fs23.readdirSync(capabilitiesDir);
7266
5986
  const capabilities = [];
7267
5987
  for (const file of files) {
7268
5988
  if (file === "capabilities.json" || !file.endsWith(".json")) {
7269
5989
  continue;
7270
5990
  }
7271
5991
  try {
7272
- const filePath = path28.join(capabilitiesDir, file);
7273
- const content = fs31.readFileSync(filePath, "utf-8");
5992
+ const filePath = path20.join(capabilitiesDir, file);
5993
+ const content = fs23.readFileSync(filePath, "utf-8");
7274
5994
  const capability = JSON.parse(content);
7275
5995
  if (capability.id && capability.pluginKey) {
7276
5996
  capabilities.push(capability);
@@ -7328,9 +6048,9 @@ async function migrateJsonFiles(options) {
7328
6048
  }
7329
6049
  const capabilitiesDir = getCapabilitiesDir2();
7330
6050
  for (const cap of newCapabilities) {
7331
- const filePath = path28.join(capabilitiesDir, `${cap.id}.json`);
6051
+ const filePath = path20.join(capabilitiesDir, `${cap.id}.json`);
7332
6052
  const content = JSON.stringify(cap, null, 2);
7333
- fs31.writeFileSync(filePath, content, "utf-8");
6053
+ fs23.writeFileSync(filePath, content, "utf-8");
7334
6054
  console.log(` \u2713 Created: ${cap.id}.json`);
7335
6055
  }
7336
6056
  return {
@@ -7342,11 +6062,11 @@ async function migrateJsonFiles(options) {
7342
6062
  }
7343
6063
 
7344
6064
  // src/commands/migration/versions/v001_capability/plugin-installer/detector.ts
7345
- import fs32 from "fs";
7346
- function isPluginInstalled(pluginKey) {
6065
+ import fs24 from "fs";
6066
+ function isPluginInstalled2(pluginKey) {
7347
6067
  const actionPlugins = readActionPlugins();
7348
6068
  const manifestPath = getPluginManifestPath2(pluginKey);
7349
- return fs32.existsSync(manifestPath) && !!actionPlugins[pluginKey];
6069
+ return fs24.existsSync(manifestPath) && !!actionPlugins[pluginKey];
7350
6070
  }
7351
6071
  function detectPluginsToInstall(capabilities) {
7352
6072
  const pluginKeys = /* @__PURE__ */ new Set();
@@ -7356,7 +6076,7 @@ function detectPluginsToInstall(capabilities) {
7356
6076
  const toInstall = [];
7357
6077
  const alreadyInstalled = [];
7358
6078
  for (const pluginKey of pluginKeys) {
7359
- if (isPluginInstalled(pluginKey)) {
6079
+ if (isPluginInstalled2(pluginKey)) {
7360
6080
  alreadyInstalled.push(pluginKey);
7361
6081
  } else {
7362
6082
  toInstall.push(pluginKey);
@@ -7422,12 +6142,12 @@ async function installPlugins(capabilities, options) {
7422
6142
  }
7423
6143
 
7424
6144
  // src/commands/migration/versions/v001_capability/code-migrator/index.ts
7425
- import path30 from "path";
6145
+ import path22 from "path";
7426
6146
  import { Project as Project3 } from "ts-morph";
7427
6147
 
7428
6148
  // src/commands/migration/versions/v001_capability/code-migrator/scanner.ts
7429
- import fs33 from "fs";
7430
- import path29 from "path";
6149
+ import fs25 from "fs";
6150
+ import path21 from "path";
7431
6151
  var EXCLUDED_DIRS = [
7432
6152
  "node_modules",
7433
6153
  "dist",
@@ -7442,9 +6162,9 @@ var EXCLUDED_PATTERNS = [
7442
6162
  /\.d\.ts$/
7443
6163
  ];
7444
6164
  function scanDirectory(dir, files = []) {
7445
- const entries = fs33.readdirSync(dir, { withFileTypes: true });
6165
+ const entries = fs25.readdirSync(dir, { withFileTypes: true });
7446
6166
  for (const entry of entries) {
7447
- const fullPath = path29.join(dir, entry.name);
6167
+ const fullPath = path21.join(dir, entry.name);
7448
6168
  if (entry.isDirectory()) {
7449
6169
  if (EXCLUDED_DIRS.includes(entry.name)) {
7450
6170
  continue;
@@ -7460,14 +6180,14 @@ function scanDirectory(dir, files = []) {
7460
6180
  return files;
7461
6181
  }
7462
6182
  function scanServerFiles() {
7463
- const serverDir = path29.join(getProjectRoot3(), "server");
7464
- if (!fs33.existsSync(serverDir)) {
6183
+ const serverDir = path21.join(getProjectRoot3(), "server");
6184
+ if (!fs25.existsSync(serverDir)) {
7465
6185
  return [];
7466
6186
  }
7467
6187
  return scanDirectory(serverDir);
7468
6188
  }
7469
6189
  function hasCapabilityImport(filePath) {
7470
- const content = fs33.readFileSync(filePath, "utf-8");
6190
+ const content = fs25.readFileSync(filePath, "utf-8");
7471
6191
  return /import\s+.*from\s+['"][^'"]*capabilities[^'"]*['"]/.test(content);
7472
6192
  }
7473
6193
  function scanFilesToMigrate() {
@@ -7844,7 +6564,7 @@ function analyzeFile(project, filePath, actionNameMap) {
7844
6564
  const callSites = analyzeCallSites(sourceFile, imports);
7845
6565
  const classInfo = analyzeClass(sourceFile);
7846
6566
  const { canMigrate, reason } = canAutoMigrate(classInfo);
7847
- const relativePath = path30.relative(getProjectRoot3(), filePath);
6567
+ const relativePath = path22.relative(getProjectRoot3(), filePath);
7848
6568
  return {
7849
6569
  filePath: relativePath,
7850
6570
  imports,
@@ -7855,7 +6575,7 @@ function analyzeFile(project, filePath, actionNameMap) {
7855
6575
  };
7856
6576
  }
7857
6577
  function migrateFile(project, analysis, dryRun) {
7858
- const absolutePath = path30.join(getProjectRoot3(), analysis.filePath);
6578
+ const absolutePath = path22.join(getProjectRoot3(), analysis.filePath);
7859
6579
  if (!analysis.canAutoMigrate) {
7860
6580
  return {
7861
6581
  filePath: analysis.filePath,
@@ -7958,17 +6678,17 @@ function getSuggestion(analysis) {
7958
6678
  }
7959
6679
 
7960
6680
  // src/commands/migration/versions/v001_capability/cleanup.ts
7961
- import fs34 from "fs";
7962
- import path31 from "path";
6681
+ import fs26 from "fs";
6682
+ import path23 from "path";
7963
6683
  function cleanupOldFiles(capabilities, dryRun) {
7964
6684
  const deletedFiles = [];
7965
6685
  const errors = [];
7966
6686
  const capabilitiesDir = getCapabilitiesDir2();
7967
- const oldJsonPath = path31.join(capabilitiesDir, "capabilities.json");
7968
- if (fs34.existsSync(oldJsonPath)) {
6687
+ const oldJsonPath = path23.join(capabilitiesDir, "capabilities.json");
6688
+ if (fs26.existsSync(oldJsonPath)) {
7969
6689
  try {
7970
6690
  if (!dryRun) {
7971
- fs34.unlinkSync(oldJsonPath);
6691
+ fs26.unlinkSync(oldJsonPath);
7972
6692
  }
7973
6693
  deletedFiles.push("capabilities.json");
7974
6694
  } catch (error) {
@@ -7976,11 +6696,11 @@ function cleanupOldFiles(capabilities, dryRun) {
7976
6696
  }
7977
6697
  }
7978
6698
  for (const cap of capabilities) {
7979
- const tsFilePath = path31.join(capabilitiesDir, `${cap.id}.ts`);
7980
- if (fs34.existsSync(tsFilePath)) {
6699
+ const tsFilePath = path23.join(capabilitiesDir, `${cap.id}.ts`);
6700
+ if (fs26.existsSync(tsFilePath)) {
7981
6701
  try {
7982
6702
  if (!dryRun) {
7983
- fs34.unlinkSync(tsFilePath);
6703
+ fs26.unlinkSync(tsFilePath);
7984
6704
  }
7985
6705
  deletedFiles.push(`${cap.id}.ts`);
7986
6706
  } catch (error) {
@@ -7996,10 +6716,10 @@ function cleanupOldFiles(capabilities, dryRun) {
7996
6716
  }
7997
6717
 
7998
6718
  // src/commands/migration/versions/v001_capability/report-generator.ts
7999
- import fs35 from "fs";
8000
- import path32 from "path";
6719
+ import fs27 from "fs";
6720
+ import path24 from "path";
8001
6721
  var REPORT_FILE = "capability-migration-report.md";
8002
- function printSummary2(result) {
6722
+ function printSummary(result) {
8003
6723
  const { jsonMigration, pluginInstallation, codeMigration, cleanup } = result;
8004
6724
  console.log("\u{1F4CA} Migration Summary");
8005
6725
  console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
@@ -8160,15 +6880,15 @@ async function generateReport(result) {
8160
6880
  }
8161
6881
  lines.push("");
8162
6882
  const logDir = process.env.LOG_DIR || "logs";
8163
- if (!fs35.existsSync(logDir)) {
6883
+ if (!fs27.existsSync(logDir)) {
8164
6884
  return;
8165
6885
  }
8166
- const reportDir = path32.join(logDir, "migration");
8167
- if (!fs35.existsSync(reportDir)) {
8168
- fs35.mkdirSync(reportDir, { recursive: true });
6886
+ const reportDir = path24.join(logDir, "migration");
6887
+ if (!fs27.existsSync(reportDir)) {
6888
+ fs27.mkdirSync(reportDir, { recursive: true });
8169
6889
  }
8170
- const reportPath = path32.join(reportDir, REPORT_FILE);
8171
- fs35.writeFileSync(reportPath, lines.join("\n"), "utf-8");
6890
+ const reportPath = path24.join(reportDir, REPORT_FILE);
6891
+ fs27.writeFileSync(reportPath, lines.join("\n"), "utf-8");
8172
6892
  console.log(`\u{1F4C4} Report generated: ${reportPath}`);
8173
6893
  }
8174
6894
 
@@ -8325,7 +7045,7 @@ async function runCapabilityMigration(options = {}) {
8325
7045
  };
8326
7046
  }
8327
7047
  const result = buildResult(jsonResult, pluginResult, codeResult, cleanupResult);
8328
- printSummary2(result);
7048
+ printSummary(result);
8329
7049
  if (!fullOptions.dryRun) {
8330
7050
  try {
8331
7051
  await generateReport(result);
@@ -8492,7 +7212,7 @@ async function executeSingle(migration, options) {
8492
7212
  };
8493
7213
  }
8494
7214
  }
8495
- function printSummary3(summary, dryRun) {
7215
+ function printSummary2(summary, dryRun) {
8496
7216
  console.log("");
8497
7217
  console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
8498
7218
  console.log(dryRun ? "Dry-run Summary:" : "Migration Summary:");
@@ -8556,7 +7276,7 @@ async function runMigrations(options) {
8556
7276
  summary.failed.push(result);
8557
7277
  hasAnyMigration = true;
8558
7278
  log("Migration aborted due to failure.");
8559
- printSummary3(summary, !!options.dryRun);
7279
+ printSummary2(summary, !!options.dryRun);
8560
7280
  return summary;
8561
7281
  }
8562
7282
  console.log("");
@@ -8569,7 +7289,7 @@ async function runMigrations(options) {
8569
7289
  } else if (!options.dryRun && summary.completed.length > 0) {
8570
7290
  log(`Migration complete. Updated to version ${getCurrentVersion()}.`);
8571
7291
  }
8572
- printSummary3(summary, !!options.dryRun);
7292
+ printSummary2(summary, !!options.dryRun);
8573
7293
  return summary;
8574
7294
  }
8575
7295
  function printMigrationResult(result) {
@@ -8700,10 +7420,10 @@ var migrationCommand = {
8700
7420
  };
8701
7421
 
8702
7422
  // src/commands/read-logs/index.ts
8703
- import path33 from "path";
7423
+ import path25 from "path";
8704
7424
 
8705
7425
  // src/commands/read-logs/std-utils.ts
8706
- import fs36 from "fs";
7426
+ import fs28 from "fs";
8707
7427
  function formatStdPrefixTime(localTime) {
8708
7428
  const match = localTime.match(/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/);
8709
7429
  if (!match) return localTime;
@@ -8733,11 +7453,11 @@ function stripPrefixFromStdLine(line) {
8733
7453
  return `[${time}] ${content}`;
8734
7454
  }
8735
7455
  function readStdLinesTailFromLastMarkerPaged(filePath, maxLines, offset, isMarker) {
8736
- const stat = fs36.statSync(filePath);
7456
+ const stat = fs28.statSync(filePath);
8737
7457
  if (stat.size === 0) {
8738
7458
  return { lines: [], markerFound: false, totalLinesCount: 0 };
8739
7459
  }
8740
- const fd = fs36.openSync(filePath, "r");
7460
+ const fd = fs28.openSync(filePath, "r");
8741
7461
  const chunkSize = 64 * 1024;
8742
7462
  let position = stat.size;
8743
7463
  let remainder = "";
@@ -8751,7 +7471,7 @@ function readStdLinesTailFromLastMarkerPaged(filePath, maxLines, offset, isMarke
8751
7471
  const length = Math.min(chunkSize, position);
8752
7472
  position -= length;
8753
7473
  const buffer = Buffer.alloc(length);
8754
- fs36.readSync(fd, buffer, 0, length, position);
7474
+ fs28.readSync(fd, buffer, 0, length, position);
8755
7475
  let chunk = buffer.toString("utf8");
8756
7476
  if (remainder) {
8757
7477
  chunk += remainder;
@@ -8793,7 +7513,7 @@ function readStdLinesTailFromLastMarkerPaged(filePath, maxLines, offset, isMarke
8793
7513
  }
8794
7514
  }
8795
7515
  } finally {
8796
- fs36.closeSync(fd);
7516
+ fs28.closeSync(fd);
8797
7517
  }
8798
7518
  return { lines: collected.reverse(), markerFound, totalLinesCount };
8799
7519
  }
@@ -8814,21 +7534,21 @@ function readServerStdSegment(filePath, maxLines, offset) {
8814
7534
  }
8815
7535
 
8816
7536
  // src/commands/read-logs/tail.ts
8817
- import fs37 from "fs";
7537
+ import fs29 from "fs";
8818
7538
  function fileExists(filePath) {
8819
7539
  try {
8820
- fs37.accessSync(filePath, fs37.constants.F_OK | fs37.constants.R_OK);
7540
+ fs29.accessSync(filePath, fs29.constants.F_OK | fs29.constants.R_OK);
8821
7541
  return true;
8822
7542
  } catch {
8823
7543
  return false;
8824
7544
  }
8825
7545
  }
8826
7546
  function readFileTailLines(filePath, maxLines) {
8827
- const stat = fs37.statSync(filePath);
7547
+ const stat = fs29.statSync(filePath);
8828
7548
  if (stat.size === 0) {
8829
7549
  return [];
8830
7550
  }
8831
- const fd = fs37.openSync(filePath, "r");
7551
+ const fd = fs29.openSync(filePath, "r");
8832
7552
  const chunkSize = 64 * 1024;
8833
7553
  const chunks = [];
8834
7554
  let position = stat.size;
@@ -8838,13 +7558,13 @@ function readFileTailLines(filePath, maxLines) {
8838
7558
  const length = Math.min(chunkSize, position);
8839
7559
  position -= length;
8840
7560
  const buffer = Buffer.alloc(length);
8841
- fs37.readSync(fd, buffer, 0, length, position);
7561
+ fs29.readSync(fd, buffer, 0, length, position);
8842
7562
  chunks.unshift(buffer.toString("utf8"));
8843
7563
  const chunkLines = buffer.toString("utf8").split("\n").length - 1;
8844
7564
  collectedLines += chunkLines;
8845
7565
  }
8846
7566
  } finally {
8847
- fs37.closeSync(fd);
7567
+ fs29.closeSync(fd);
8848
7568
  }
8849
7569
  const content = chunks.join("");
8850
7570
  const allLines = content.split("\n");
@@ -8860,11 +7580,11 @@ function readFileTailLines(filePath, maxLines) {
8860
7580
  return allLines.slice(allLines.length - maxLines);
8861
7581
  }
8862
7582
  function readFileTailNonEmptyLinesWithOffset(filePath, maxLines, offset) {
8863
- const stat = fs37.statSync(filePath);
7583
+ const stat = fs29.statSync(filePath);
8864
7584
  if (stat.size === 0) {
8865
7585
  return { lines: [], totalLinesCount: 0 };
8866
7586
  }
8867
- const fd = fs37.openSync(filePath, "r");
7587
+ const fd = fs29.openSync(filePath, "r");
8868
7588
  const chunkSize = 64 * 1024;
8869
7589
  let position = stat.size;
8870
7590
  let remainder = "";
@@ -8876,7 +7596,7 @@ function readFileTailNonEmptyLinesWithOffset(filePath, maxLines, offset) {
8876
7596
  const length = Math.min(chunkSize, position);
8877
7597
  position -= length;
8878
7598
  const buffer = Buffer.alloc(length);
8879
- fs37.readSync(fd, buffer, 0, length, position);
7599
+ fs29.readSync(fd, buffer, 0, length, position);
8880
7600
  let chunk = buffer.toString("utf8");
8881
7601
  if (remainder) {
8882
7602
  chunk += remainder;
@@ -8907,7 +7627,7 @@ function readFileTailNonEmptyLinesWithOffset(filePath, maxLines, offset) {
8907
7627
  }
8908
7628
  }
8909
7629
  } finally {
8910
- fs37.closeSync(fd);
7630
+ fs29.closeSync(fd);
8911
7631
  }
8912
7632
  return { lines: collected.reverse(), totalLinesCount };
8913
7633
  }
@@ -9049,7 +7769,7 @@ function readDevStdSegment(filePath, maxLines, offset) {
9049
7769
  }
9050
7770
 
9051
7771
  // src/commands/read-logs/json-lines.ts
9052
- import fs38 from "fs";
7772
+ import fs30 from "fs";
9053
7773
 
9054
7774
  // src/commands/read-logs/structured-log.ts
9055
7775
  function normalizeLevelName(value) {
@@ -9125,11 +7845,11 @@ function buildWantedLevelSet(levels) {
9125
7845
  return set.size > 0 ? set : null;
9126
7846
  }
9127
7847
  function readJsonLinesLastPid(filePath, maxLines, offset, levels) {
9128
- const stat = fs38.statSync(filePath);
7848
+ const stat = fs30.statSync(filePath);
9129
7849
  if (stat.size === 0) {
9130
7850
  return { lines: [], totalLinesCount: 0 };
9131
7851
  }
9132
- const fd = fs38.openSync(filePath, "r");
7852
+ const fd = fs30.openSync(filePath, "r");
9133
7853
  const chunkSize = 64 * 1024;
9134
7854
  let position = stat.size;
9135
7855
  let remainder = "";
@@ -9144,7 +7864,7 @@ function readJsonLinesLastPid(filePath, maxLines, offset, levels) {
9144
7864
  const length = Math.min(chunkSize, position);
9145
7865
  position -= length;
9146
7866
  const buffer = Buffer.alloc(length);
9147
- fs38.readSync(fd, buffer, 0, length, position);
7867
+ fs30.readSync(fd, buffer, 0, length, position);
9148
7868
  let chunk = buffer.toString("utf8");
9149
7869
  if (remainder) {
9150
7870
  chunk += remainder;
@@ -9206,7 +7926,7 @@ function readJsonLinesLastPid(filePath, maxLines, offset, levels) {
9206
7926
  }
9207
7927
  }
9208
7928
  } finally {
9209
- fs38.closeSync(fd);
7929
+ fs30.closeSync(fd);
9210
7930
  }
9211
7931
  return { lines: collected.reverse(), totalLinesCount };
9212
7932
  }
@@ -9249,11 +7969,11 @@ function extractTraceId(obj) {
9249
7969
  function readJsonLinesByTraceId(filePath, traceId, maxLines, offset, levels) {
9250
7970
  const wanted = traceId.trim();
9251
7971
  if (!wanted) return { lines: [], totalLinesCount: 0 };
9252
- const stat = fs38.statSync(filePath);
7972
+ const stat = fs30.statSync(filePath);
9253
7973
  if (stat.size === 0) {
9254
7974
  return { lines: [], totalLinesCount: 0 };
9255
7975
  }
9256
- const fd = fs38.openSync(filePath, "r");
7976
+ const fd = fs30.openSync(filePath, "r");
9257
7977
  const chunkSize = 64 * 1024;
9258
7978
  let position = stat.size;
9259
7979
  let remainder = "";
@@ -9266,7 +7986,7 @@ function readJsonLinesByTraceId(filePath, traceId, maxLines, offset, levels) {
9266
7986
  const length = Math.min(chunkSize, position);
9267
7987
  position -= length;
9268
7988
  const buffer = Buffer.alloc(length);
9269
- fs38.readSync(fd, buffer, 0, length, position);
7989
+ fs30.readSync(fd, buffer, 0, length, position);
9270
7990
  let chunk = buffer.toString("utf8");
9271
7991
  if (remainder) {
9272
7992
  chunk += remainder;
@@ -9319,7 +8039,7 @@ function readJsonLinesByTraceId(filePath, traceId, maxLines, offset, levels) {
9319
8039
  }
9320
8040
  }
9321
8041
  } finally {
9322
- fs38.closeSync(fd);
8042
+ fs30.closeSync(fd);
9323
8043
  }
9324
8044
  return { lines: collected.reverse(), totalLinesCount };
9325
8045
  }
@@ -9328,11 +8048,11 @@ function readJsonLinesTailByLevel(filePath, maxLines, offset, levels) {
9328
8048
  if (!wantedLevelSet) {
9329
8049
  return { lines: [], totalLinesCount: 0 };
9330
8050
  }
9331
- const stat = fs38.statSync(filePath);
8051
+ const stat = fs30.statSync(filePath);
9332
8052
  if (stat.size === 0) {
9333
8053
  return { lines: [], totalLinesCount: 0 };
9334
8054
  }
9335
- const fd = fs38.openSync(filePath, "r");
8055
+ const fd = fs30.openSync(filePath, "r");
9336
8056
  const chunkSize = 64 * 1024;
9337
8057
  let position = stat.size;
9338
8058
  let remainder = "";
@@ -9344,7 +8064,7 @@ function readJsonLinesTailByLevel(filePath, maxLines, offset, levels) {
9344
8064
  const length = Math.min(chunkSize, position);
9345
8065
  position -= length;
9346
8066
  const buffer = Buffer.alloc(length);
9347
- fs38.readSync(fd, buffer, 0, length, position);
8067
+ fs30.readSync(fd, buffer, 0, length, position);
9348
8068
  let chunk = buffer.toString("utf8");
9349
8069
  if (remainder) {
9350
8070
  chunk += remainder;
@@ -9391,7 +8111,7 @@ function readJsonLinesTailByLevel(filePath, maxLines, offset, levels) {
9391
8111
  }
9392
8112
  }
9393
8113
  } finally {
9394
- fs38.closeSync(fd);
8114
+ fs30.closeSync(fd);
9395
8115
  }
9396
8116
  return { lines: collected.reverse(), totalLinesCount };
9397
8117
  }
@@ -9884,30 +8604,30 @@ async function readLogsJsonResult(options) {
9884
8604
  };
9885
8605
  }
9886
8606
  function resolveLogFilePath(logDir, type) {
9887
- const base = path33.isAbsolute(logDir) ? logDir : path33.join(process.cwd(), logDir);
8607
+ const base = path25.isAbsolute(logDir) ? logDir : path25.join(process.cwd(), logDir);
9888
8608
  if (type === "server") {
9889
- return path33.join(base, "server.log");
8609
+ return path25.join(base, "server.log");
9890
8610
  }
9891
8611
  if (type === "trace") {
9892
- return path33.join(base, "trace.log");
8612
+ return path25.join(base, "trace.log");
9893
8613
  }
9894
8614
  if (type === "server-std") {
9895
- return path33.join(base, "server.std.log");
8615
+ return path25.join(base, "server.std.log");
9896
8616
  }
9897
8617
  if (type === "client-std") {
9898
- return path33.join(base, "client.std.log");
8618
+ return path25.join(base, "client.std.log");
9899
8619
  }
9900
8620
  if (type === "dev") {
9901
- return path33.join(base, "dev.log");
8621
+ return path25.join(base, "dev.log");
9902
8622
  }
9903
8623
  if (type === "dev-std") {
9904
- return path33.join(base, "dev.std.log");
8624
+ return path25.join(base, "dev.std.log");
9905
8625
  }
9906
8626
  if (type === "install-dep-std") {
9907
- return path33.join(base, "install-dep.std.log");
8627
+ return path25.join(base, "install-dep.std.log");
9908
8628
  }
9909
8629
  if (type === "browser") {
9910
- return path33.join(base, "browser.log");
8630
+ return path25.join(base, "browser.log");
9911
8631
  }
9912
8632
  throw new Error(`Unsupported log type: ${type}`);
9913
8633
  }
@@ -10077,10 +8797,10 @@ function camelToKebab(str) {
10077
8797
  }
10078
8798
 
10079
8799
  // src/commands/build/upload-static.handler.ts
10080
- import * as fs39 from "fs";
10081
- import * as os3 from "os";
10082
- import * as path34 from "path";
10083
- import { execFileSync as execFileSync2 } from "child_process";
8800
+ import * as fs31 from "fs";
8801
+ import * as os2 from "os";
8802
+ import * as path26 from "path";
8803
+ import { execFileSync } from "child_process";
10084
8804
  function readCredentialsFromEnv() {
10085
8805
  const uploadPrefix = process.env.STATIC_UPLOAD_PREFIX;
10086
8806
  const uploadID = process.env.STATIC_UPLOAD_ID;
@@ -10103,8 +8823,8 @@ async function uploadStatic(options) {
10103
8823
  endpoint = UPLOAD_STATIC_DEFAULTS.endpoint,
10104
8824
  region = UPLOAD_STATIC_DEFAULTS.region
10105
8825
  } = options;
10106
- const resolvedStaticDir = path34.resolve(staticDir);
10107
- if (!fs39.existsSync(resolvedStaticDir)) {
8826
+ const resolvedStaticDir = path26.resolve(staticDir);
8827
+ if (!fs31.existsSync(resolvedStaticDir)) {
10108
8828
  console.error(`${LOG_PREFIX} \u76EE\u5F55\u4E0D\u5B58\u5728: ${resolvedStaticDir}\uFF0C\u8DF3\u8FC7\u4E0A\u4F20`);
10109
8829
  return;
10110
8830
  }
@@ -10137,8 +8857,8 @@ async function uploadStatic(options) {
10137
8857
  ({ AccessKeyID: accessKeyID, SecretAccessKey: secretAccessKey, SessionToken: sessionToken } = uploadCredential);
10138
8858
  }
10139
8859
  console.error(`${LOG_PREFIX} \u4E0A\u4F20\u76EE\u6807: ${uploadPrefix}`);
10140
- const confPath = path34.join(os3.tmpdir(), `.tosutilconfig-static-${process.pid}`);
10141
- fs39.writeFileSync(confPath, "");
8860
+ const confPath = path26.join(os2.tmpdir(), `.tosutilconfig-static-${process.pid}`);
8861
+ fs31.writeFileSync(confPath, "");
10142
8862
  try {
10143
8863
  console.error(`${LOG_PREFIX} \u914D\u7F6E tosutil...`);
10144
8864
  configureTosutil(resolvedTosutil, confPath, {
@@ -10152,7 +8872,7 @@ async function uploadStatic(options) {
10152
8872
  uploadToTos(resolvedTosutil, confPath, resolvedStaticDir, uploadPrefix);
10153
8873
  } finally {
10154
8874
  try {
10155
- fs39.unlinkSync(confPath);
8875
+ fs31.unlinkSync(confPath);
10156
8876
  } catch {
10157
8877
  }
10158
8878
  }
@@ -10172,11 +8892,11 @@ async function uploadStatic(options) {
10172
8892
  }
10173
8893
  }
10174
8894
  function resolveTosutilPath(tosutilPath) {
10175
- if (path34.isAbsolute(tosutilPath)) {
10176
- return fs39.existsSync(tosutilPath) ? tosutilPath : null;
8895
+ if (path26.isAbsolute(tosutilPath)) {
8896
+ return fs31.existsSync(tosutilPath) ? tosutilPath : null;
10177
8897
  }
10178
8898
  try {
10179
- const resolved = execFileSync2("which", [tosutilPath], { encoding: "utf-8" }).trim();
8899
+ const resolved = execFileSync("which", [tosutilPath], { encoding: "utf-8" }).trim();
10180
8900
  return resolved || null;
10181
8901
  } catch {
10182
8902
  return null;
@@ -10198,14 +8918,14 @@ async function fetchPreUpload(appId, bucketId) {
10198
8918
  }
10199
8919
  function configureTosutil(tosutilPath, confPath, config) {
10200
8920
  const { endpoint, region, accessKeyID, secretAccessKey, sessionToken } = config;
10201
- execFileSync2(
8921
+ execFileSync(
10202
8922
  tosutilPath,
10203
8923
  ["config", "-conf", confPath, "-e", endpoint, "-i", accessKeyID, "-k", secretAccessKey, "-t", sessionToken, "-re", region],
10204
8924
  { stdio: "pipe" }
10205
8925
  );
10206
8926
  }
10207
8927
  function uploadToTos(tosutilPath, confPath, sourceDir, destUrl) {
10208
- execFileSync2(
8928
+ execFileSync(
10209
8929
  tosutilPath,
10210
8930
  ["cp", "-conf", confPath, sourceDir, destUrl, "-r", "-flat", "-j", "5", "-p", "3", "-ps", "10485760", "-f"],
10211
8931
  { stdio: "inherit" }
@@ -10218,7 +8938,7 @@ async function resolveBucketId(appId) {
10218
8938
  return bucketId;
10219
8939
  }
10220
8940
  function isDirEmpty(dirPath) {
10221
- const entries = fs39.readdirSync(dirPath);
8941
+ const entries = fs31.readdirSync(dirPath);
10222
8942
  return entries.length === 0;
10223
8943
  }
10224
8944
 
@@ -10314,13 +9034,13 @@ var commands = [
10314
9034
 
10315
9035
  // src/index.ts
10316
9036
  for (const filename of [".env.local", ".env"]) {
10317
- const envPath = path35.join(process.cwd(), filename);
10318
- if (fs40.existsSync(envPath)) {
9037
+ const envPath = path27.join(process.cwd(), filename);
9038
+ if (fs32.existsSync(envPath)) {
10319
9039
  dotenvConfig({ path: envPath });
10320
9040
  }
10321
9041
  }
10322
- var __dirname = path35.dirname(fileURLToPath5(import.meta.url));
10323
- var pkg = JSON.parse(fs40.readFileSync(path35.join(__dirname, "../package.json"), "utf-8"));
9042
+ var __dirname = path27.dirname(fileURLToPath5(import.meta.url));
9043
+ var pkg = JSON.parse(fs32.readFileSync(path27.join(__dirname, "../package.json"), "utf-8"));
10324
9044
  var cli = new FullstackCLI(pkg.version);
10325
9045
  cli.useAll(commands);
10326
9046
  cli.run();