@supersdk/supercli 0.2.1-staging.20 → 0.3.0-staging.22

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 (91) hide show
  1. package/dist/api/consoleClient.js +17 -12
  2. package/dist/api/consoleClient.js.map +1 -1
  3. package/dist/auth/browserAuth.js +42 -44
  4. package/dist/auth/browserAuth.js.map +1 -1
  5. package/dist/auth/tokenAuth.js +46 -0
  6. package/dist/auth/tokenAuth.js.map +1 -0
  7. package/dist/cli.js +70 -8
  8. package/dist/cli.js.map +1 -1
  9. package/dist/commands/accounts.js +89 -31
  10. package/dist/commands/accounts.js.map +1 -1
  11. package/dist/commands/add.js +519 -0
  12. package/dist/commands/add.js.map +1 -0
  13. package/dist/commands/init.js +234 -0
  14. package/dist/commands/init.js.map +1 -0
  15. package/dist/commands/login.js +75 -48
  16. package/dist/commands/login.js.map +1 -1
  17. package/dist/commands/logout.js +20 -25
  18. package/dist/commands/logout.js.map +1 -1
  19. package/dist/commands/publishSite.js +491 -149
  20. package/dist/commands/publishSite.js.map +1 -1
  21. package/dist/commands/switchaccount.js +36 -24
  22. package/dist/commands/switchaccount.js.map +1 -1
  23. package/dist/config/appConfig.js +160 -45
  24. package/dist/config/appConfig.js.map +1 -1
  25. package/dist/config/environments.js +17 -1
  26. package/dist/config/environments.js.map +1 -1
  27. package/dist/exit/exitCodes.js +55 -0
  28. package/dist/exit/exitCodes.js.map +1 -0
  29. package/dist/output/envelope.js +104 -0
  30. package/dist/output/envelope.js.map +1 -0
  31. package/dist/output/resultPrinter.js +70 -0
  32. package/dist/output/resultPrinter.js.map +1 -0
  33. package/dist/publish/siteClient.js +14 -4
  34. package/dist/publish/siteClient.js.map +1 -1
  35. package/dist/publish/siteConfig.js +278 -63
  36. package/dist/publish/siteConfig.js.map +1 -1
  37. package/dist/store/accountStore.js +2 -2
  38. package/dist/store/accountStore.js.map +1 -1
  39. package/dist/store/backends/encryptedFile.js +4 -1
  40. package/dist/store/backends/encryptedFile.js.map +1 -1
  41. package/dist/store/backends/osKeyring.js +4 -8
  42. package/dist/store/backends/osKeyring.js.map +1 -1
  43. package/dist/store/credentialStore.js +22 -0
  44. package/dist/store/credentialStore.js.map +1 -1
  45. package/dist/template/README.md +144 -85
  46. package/dist/template/android/app/build.gradle.kts +0 -3
  47. package/dist/template/android/app/src/main/java/com/supersdk/simple/EnvironmentStore.java +41 -0
  48. package/dist/template/android/app/src/main/java/com/supersdk/simple/MainActivity.java +57 -4
  49. package/dist/template/android/app/src/main/java/com/supersdk/simple/SimpleApplication.java +3 -1
  50. package/dist/template/android/gradle/supersdk-config-reader.gradle +5 -3
  51. package/dist/template/android/supersdk-default.config.json +4 -3
  52. package/dist/template/ios/Sources/App/EnvironmentStore.swift +35 -0
  53. package/dist/template/ios/Sources/App/SimpleSDKBootstrap.swift +2 -1
  54. package/dist/template/ios/Sources/App/SimpleSDKProbe.swift +15 -0
  55. package/dist/template/ios/Sources/App/SimpleViewController.swift +52 -8
  56. package/dist/template/ios/Tests/SimpleAppTests/SimpleSDKInitializationTests.swift +12 -1
  57. package/dist/template/scripts/android_snapshot_canary.py +17 -8
  58. package/dist/template/scripts/build_android.sh +36 -9
  59. package/dist/template/scripts/build_ios.sh +63 -24
  60. package/dist/template/scripts/build_site.sh +43 -0
  61. package/dist/template/scripts/lib/workspace.sh +43 -0
  62. package/dist/template/scripts/serve_web.py +26 -9
  63. package/dist/template/scripts/super_build_orchestrator.py +49 -28
  64. package/dist/template/scripts/supersdk_template.py +759 -240
  65. package/dist/template/scripts/web_package.py +44 -20
  66. package/dist/template/super_build.sh +40 -12
  67. package/dist/template/supersdk.json +25 -13
  68. package/dist/template/template_manifest.json +25 -0
  69. package/dist/template/web/src/css/style.css +28 -0
  70. package/dist/template/web/src/index.html +8 -0
  71. package/dist/template/web/src/js/app.js +92 -19
  72. package/dist/util/log.js +10 -1
  73. package/dist/util/log.js.map +1 -1
  74. package/dist/util/prompt.js +25 -0
  75. package/dist/util/prompt.js.map +1 -1
  76. package/dist/workspace/config.js +440 -0
  77. package/dist/workspace/config.js.map +1 -0
  78. package/dist/workspace/identity.js +106 -0
  79. package/dist/workspace/identity.js.map +1 -0
  80. package/dist/workspace/interactive.js +96 -0
  81. package/dist/workspace/interactive.js.map +1 -0
  82. package/dist/workspace/template.js +357 -0
  83. package/dist/workspace/template.js.map +1 -0
  84. package/package.json +1 -1
  85. package/dist/auth/refresh.js +0 -32
  86. package/dist/auth/refresh.js.map +0 -1
  87. package/dist/commands/createApp.js +0 -448
  88. package/dist/commands/createApp.js.map +0 -1
  89. package/dist/createApp/copyTemplate.js +0 -561
  90. package/dist/createApp/copyTemplate.js.map +0 -1
  91. package/dist/template/scripts/build_web.sh +0 -12
@@ -34,37 +34,39 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.defaultPublishSiteDeps = void 0;
37
+ exports.registerSiteProjectHint = registerSiteProjectHint;
37
38
  exports.runPublishSite = runPublishSite;
38
39
  exports.registerPublishSiteCommand = registerPublishSiteCommand;
40
+ const crypto = __importStar(require("node:crypto"));
39
41
  const fs = __importStar(require("node:fs"));
40
42
  const path = __importStar(require("node:path"));
41
43
  const consoleClient_1 = require("../api/consoleClient");
42
- const refresh_1 = require("../auth/refresh");
43
44
  const siteClient_1 = require("../publish/siteClient");
44
45
  const orgResolve_1 = require("../publish/orgResolve");
45
46
  const responseClassifier_1 = require("../publish/responseClassifier");
46
47
  const siteConfig_1 = require("../publish/siteConfig");
48
+ const appConfig_1 = require("../config/appConfig");
47
49
  const siteZip_1 = require("../publish/siteZip");
48
50
  const offlineVersion_1 = require("../publish/offlineVersion");
49
51
  const credentialStore_1 = require("../store/credentialStore");
50
52
  const accountStore_1 = require("../store/accountStore");
51
- const log_1 = require("../util/log");
53
+ const environments_1 = require("../config/environments");
54
+ const tokenAuth_1 = require("../auth/tokenAuth");
55
+ const resultPrinter_1 = require("../output/resultPrinter");
52
56
  const prompt_1 = require("../util/prompt");
57
+ const shell_1 = require("../util/shell");
53
58
  function resolveBackend(account) {
54
59
  return (0, credentialStore_1.backendForAccount)(account.backend, {
55
60
  passphraseProvider: account.backend === 'encrypted-file'
56
- ? () => (0, prompt_1.promptHiddenSync)(`Encryption passphrase for ${account.email}: `)
61
+ ? () => (0, prompt_1.promptHiddenSync)(`Encryption passphrase for ${account.email ?? account.accountKey}: `)
57
62
  : undefined,
58
63
  });
59
64
  }
60
65
  exports.defaultPublishSiteDeps = {
61
66
  getCurrentAccount: accountStore_1.getCurrentAccount,
62
- getAccessToken: (account) => resolveBackend(account).get(account.accountKey)?.accessToken ?? null,
63
- refreshToken: (account) => (0, refresh_1.refreshAccessToken)(new consoleClient_1.ConsoleClient(account.apiOrigin), resolveBackend(account), account.accountKey),
67
+ getStoredToken: (account) => resolveBackend(account).get(account.accountKey)?.token ?? null,
64
68
  markNeedsLogin: accountStore_1.markAccountNeedsLogin,
65
- fetchMe: (apiOrigin, accessToken) => new consoleClient_1.ConsoleClient(apiOrigin).me(accessToken),
66
- // The concrete client is upgraded in the publish layer; this cast preserves
67
- // the command's injectable boundary while those modules evolve independently.
69
+ fetchWhoami: (apiOrigin, token) => new consoleClient_1.ConsoleClient(apiOrigin).whoami(token),
68
70
  createSiteClient: (apiOrigin) => new siteClient_1.SiteClient(apiOrigin),
69
71
  readConfig: siteConfig_1.findConfig,
70
72
  updateConfig: siteConfig_1.updateConfig,
@@ -78,29 +80,32 @@ exports.defaultPublishSiteDeps = {
78
80
  }
79
81
  },
80
82
  };
81
- async function withAuth(account, deps, tokenRef, call) {
82
- let outcome = await call(tokenRef.value);
83
- if (outcome.kind !== 'auth_invalid')
84
- return { kind: 'outcome', outcome };
85
- const refreshed = await deps.refreshToken(account);
86
- if (refreshed.kind === 'needs_login') {
87
- deps.markNeedsLogin(account.accountKey);
88
- return { kind: 'needs_login' };
89
- }
90
- if (refreshed.kind === 'infra_error')
91
- return { kind: 'refresh_failed', message: refreshed.message };
92
- tokenRef.value = refreshed.secret.accessToken;
93
- outcome = await call(tokenRef.value);
83
+ async function withAuth(auth, deps, call) {
84
+ const outcome = await call(auth.token);
94
85
  if (outcome.kind === 'auth_invalid') {
95
- deps.markNeedsLogin(account.accountKey);
86
+ if (auth.accountKey)
87
+ deps.markNeedsLogin(auth.accountKey);
96
88
  return { kind: 'needs_login' };
97
89
  }
98
90
  return { kind: 'outcome', outcome };
99
91
  }
100
- function terminalMessage(result) {
101
- return result.kind === 'needs_login'
102
- ? 'credentials are no longer valid — run `supercli login` again'
103
- : `cannot refresh credentials (network/service error; local credentials untouched): ${result.message}`;
92
+ function terminalResult() {
93
+ return { ok: false, kind: 'needs_login', message: 'credentials are no longer valid — run `supercli login` again' };
94
+ }
95
+ /** Maps an outcome kind (Site or Client) to its failure classification kind. */
96
+ function failureKind(kind) {
97
+ switch (kind) {
98
+ case 'forbidden':
99
+ return 'forbidden';
100
+ case 'rate_limited':
101
+ return 'rate_limited';
102
+ case 'infra_error':
103
+ return 'infra_error';
104
+ case 'auth_invalid':
105
+ return 'auth_invalid';
106
+ default:
107
+ return 'business_error';
108
+ }
104
109
  }
105
110
  function nonSuccessMessage(outcome, context) {
106
111
  switch (outcome.kind) {
@@ -142,7 +147,7 @@ function isSiteForTarget(detail, spid, slug) {
142
147
  Array.isArray(detail.environments));
143
148
  }
144
149
  function isTerminal(value) {
145
- return Boolean(value && typeof value === 'object' && 'kind' in value && (value.kind === 'needs_login' || value.kind === 'refresh_failed'));
150
+ return Boolean(value && typeof value === 'object' && value.kind === 'needs_login');
146
151
  }
147
152
  function listContainsEnvironment(value, env) {
148
153
  if (!Array.isArray(value))
@@ -160,6 +165,22 @@ function domainFromDeploy(value) {
160
165
  const record = asRecord(value);
161
166
  return typeof record?.domain === 'string' && record.domain.length > 0 ? record.domain : undefined;
162
167
  }
168
+ /**
169
+ * 服务端返回的 domain → 规范化的 host(`offline.host` 的落盘形态,也是展示形态)。
170
+ *
171
+ * 服务端今天返回的是裸 host,但「今天碰巧」不构成保证:`offline.host` 一旦写进配置就是字节
172
+ * 比对的绑定(updateConfig 对不同值抛错、绝不静默改绑定),所以带 scheme / 带尾斜杠 / 大小写
173
+ * 不同的同一个域名必须先收敛成一种形态,否则第二次 prod 发布就会撞上「拒绝覆盖已有
174
+ * offline.host」。host 大小写不敏感,小写是它的规范形态。
175
+ */
176
+ function canonicalHost(value) {
177
+ if (value === undefined)
178
+ return undefined;
179
+ const withoutScheme = value.trim().replace(/^https?:\/\//i, '');
180
+ // path/query/fragment 都不是 host 的一部分:真出现了也切掉,绝不把它们写进配置。
181
+ const host = withoutScheme.split(/[/?#]/)[0].trim().toLowerCase();
182
+ return host.length > 0 ? host : undefined;
183
+ }
163
184
  function isValidSpid(value) {
164
185
  return /^[a-z0-9]{8}$/.test(value);
165
186
  }
@@ -173,22 +194,46 @@ function trimFlag(value) {
173
194
  const trimmed = value?.trim();
174
195
  return trimmed ? trimmed : undefined;
175
196
  }
176
- function normalizeSites(value) {
197
+ function normalizeDeploy(value) {
198
+ if (value === undefined)
199
+ return [];
177
200
  if (!Array.isArray(value))
178
201
  return undefined;
179
- const sites = [];
202
+ const entries = [];
180
203
  for (const item of value) {
181
204
  const record = asRecord(item);
182
205
  if (typeof record?.slug !== 'string' || typeof record.env !== 'string')
183
206
  return undefined;
184
- sites.push({
207
+ entries.push({
185
208
  slug: record.slug,
186
209
  name: typeof record.name === 'string' ? record.name : record.slug,
187
210
  env: record.env,
188
211
  dir: typeof record.dir === 'string' ? record.dir : '',
189
212
  });
190
213
  }
191
- return sites;
214
+ return entries;
215
+ }
216
+ function normalizeSiteProjects(value) {
217
+ if (!Array.isArray(value))
218
+ return undefined;
219
+ const projects = [];
220
+ for (const item of value) {
221
+ const record = asRecord(item);
222
+ if (!record || typeof record.index !== 'number' || typeof record.dir !== 'string')
223
+ return undefined;
224
+ const deploy = normalizeDeploy(record.deploy);
225
+ if (!deploy)
226
+ return undefined;
227
+ projects.push({
228
+ index: record.index,
229
+ dir: record.dir,
230
+ ...(typeof record.name === 'string' ? { name: record.name } : {}),
231
+ ...(typeof record.versionName === 'string' ? { versionName: record.versionName } : {}),
232
+ deploy,
233
+ ...(typeof record.offlineHost === 'string' ? { offlineHost: record.offlineHost } : {}),
234
+ });
235
+ }
236
+ return projects;
192
237
  }
193
238
  /** 注入边界的兜底:任何不认识的形状都当 invalid,绝不退化成「没有绑定,随便发」。 */
194
239
  function normalizeConfig(value) {
@@ -208,68 +253,164 @@ function normalizeConfig(value) {
208
253
  const existing = typeof record.existingConfigPath === 'string' ? record.existingConfigPath : undefined;
209
254
  return { kind: record.kind, path: record.path, ...(existing ? { existingConfigPath: existing } : {}) };
210
255
  }
256
+ if (record.kind === 'unsupported-schema') {
257
+ if (typeof record.path !== 'string')
258
+ return { kind: 'invalid' };
259
+ return { kind: 'unsupported-schema', path: record.path, found: record.found };
260
+ }
211
261
  if (record.kind === 'invalid') {
212
262
  return { kind: 'invalid', path: typeof record.path === 'string' ? record.path : undefined, reason: typeof record.reason === 'string' ? record.reason : undefined };
213
263
  }
214
264
  if (record.kind !== 'valid')
215
265
  return { kind: 'invalid' };
216
266
  const config = asRecord(record.config);
217
- const sites = normalizeSites(config?.sites);
218
- if (typeof config?.path !== 'string' || typeof config.spid !== 'string' || !sites)
267
+ const siteProjects = normalizeSiteProjects(config?.siteProjects);
268
+ if (typeof config?.path !== 'string' || typeof config.spid !== 'string' || !siteProjects)
219
269
  return { kind: 'invalid' };
220
270
  if (config.orgId !== undefined && typeof config.orgId !== 'string')
221
271
  return { kind: 'invalid' };
222
272
  return {
223
273
  kind: 'valid',
224
- config: { path: config.path, spid: config.spid, orgId: config.orgId, sites },
274
+ config: {
275
+ path: config.path,
276
+ spid: config.spid,
277
+ orgId: config.orgId,
278
+ ...(typeof config.versionName === 'string' ? { versionName: config.versionName } : {}),
279
+ siteProjects,
280
+ projectDirs: Array.isArray(config.projectDirs)
281
+ ? config.projectDirs.filter((item) => typeof item === 'string')
282
+ : [],
283
+ },
225
284
  };
226
285
  }
286
+ /**
287
+ * **散文**里指认一个路径:`"…/supersdk.json"`。JSON 引号在这里是对的(它读起来就是一个值),
288
+ * 但它**不能**出现在命令位置 —— 见 shellArg。
289
+ */
227
290
  function quotePath(value) {
228
291
  return JSON.stringify(value);
229
292
  }
230
293
  /**
231
- * 用户刚敲过的这条命令原样回显 —— 迁移提示里给的命令**必须自洽可执行**:四个必填参数
232
- * (--spid/--slug/--env/--version)一个都不能少,否则照抄下去只会被 commander 直接拦下,
233
- * 用户在「按提示做 → 撞回同一句提示」之间死循环。本仓刚修过一模一样的 bug。
294
+ * **命令**里的一个参数。凡是要被照抄进 shell 的位置一律走这里。
295
+ *
296
+ * 🔴 不能用 JSON.stringify:双引号里 shell 会展开 `$VAR`/`` `cmd` ``,而 Windows 路径
297
+ * (`C:\repo\web`)被 JSON 转义成 `"C:\\repo\\web"` 之后,粘进 cmd/PowerShell 就是另一个
298
+ * 路径 —— supercli 的 CI 有 Windows 这条腿,这不是理论问题。shellQuote 是权威侧
299
+ * supersdk_template.py 里 shlex.quote 的移植,两边同一套。
300
+ *
301
+ * 占位符同样要走这里:`--config <path>/supersdk.json` 粘进 bash 会被当成重定向
302
+ * (`bash: path: No such file or directory`),命令根本没跑;引号一加,它就变成
303
+ * 「被 supercli 自己的校验拦下」。
304
+ */
305
+ function shellArg(value) {
306
+ return (0, shell_1.shellQuote)(value);
307
+ }
308
+ /**
309
+ * 发布目录(相对配置文件所在目录)落在哪个站点项目里:等于项目目录,或在它之下。
310
+ *
311
+ * `projects[].dir` 互不为祖先由解析期保证,所以命中至多一个。以 `..` 开头的路径是工作空间
312
+ * **之外**的目录,任何项目都不认领它(包括 dir 为 `.` 的项目)。
313
+ */
314
+ function projectCovering(projects, relativeDir) {
315
+ if (relativeDir === '..' || relativeDir.startsWith('../'))
316
+ return undefined;
317
+ return projects.find((project) => project.dir === relativeDir || project.dir === '.' || relativeDir.startsWith(`${project.dir}/`));
318
+ }
319
+ /**
320
+ * 用户刚敲过的这条命令原样回显 —— 迁移提示里给的命令**必须自洽可执行**:三个必填参数
321
+ * (--spid/--slug/--env)一个都不能少,否则照抄下去只会被 commander 直接拦下,用户在
322
+ * 「按提示做 → 撞回同一句提示」之间死循环。本仓刚修过一模一样的 bug。
323
+ *
324
+ * `--version` 只在用户**真的传过**时回显:它现在可以从配置里的 version.name 取默认值,
325
+ * 而这些提示的收尾动作恰恰就是「写出一份带 version.name 的配置」—— 硬塞一个我们自己编的
326
+ * 版本号进去,等于教用户绕开刚刚建好的单一信源。
234
327
  */
235
328
  function reissueCommand(dir, opts, identity) {
236
329
  const parts = [
237
- `supercli publish-site ${quotePath(path.resolve(dir))}`,
330
+ `supercli publish-site ${shellArg(path.resolve(dir))}`,
238
331
  `--spid ${identity.spid}`,
239
332
  `--slug ${identity.slug}`,
240
333
  `--env ${identity.env}`,
241
- `--version ${identity.version}`,
242
334
  ];
335
+ const version = trimFlag(opts.version);
336
+ if (version)
337
+ parts.push(`--version ${version}`);
243
338
  const config = trimFlag(opts.config);
244
339
  if (config)
245
- parts.push(`--config ${quotePath(path.resolve(config))}`);
340
+ parts.push(`--config ${shellArg(path.resolve(config))}`);
246
341
  const org = trimFlag(opts.org);
247
342
  if (org)
248
343
  parts.push(`--org ${org}`);
249
344
  const name = trimFlag(opts.name);
250
345
  if (name)
251
- parts.push(`--name ${JSON.stringify(name)}`);
346
+ parts.push(`--name ${shellArg(name)}`);
252
347
  if (opts.createEnvironment)
253
348
  parts.push('--create-environment');
254
349
  const description = trimFlag(opts.description);
255
350
  if (description)
256
- parts.push(`--description ${JSON.stringify(description)}`);
351
+ parts.push(`--description ${shellArg(description)}`);
352
+ if (opts.dryRun)
353
+ parts.push('--dry-run');
354
+ const idempotencyKey = trimFlag(opts.idempotencyKey);
355
+ if (idempotencyKey)
356
+ parts.push(`--idempotency-key ${shellArg(idempotencyKey)}`);
257
357
  return parts.join(' ');
258
358
  }
259
359
  /**
260
- * 「写一份新配置」这一步。骨架来自 config/appConfig.ts,字段齐全
261
- * (name/environment/android/ios/web/version/sdk)—— 少任何一个,照抄的人拿到的都是一份
262
- * `./super_build.sh --build` 过不了的配置,等于把人送进另一个死循环。
360
+ * 「写一份新配置」这一步。骨架来自 config/appConfig.ts,字段齐全(workspace 身份 +
361
+ * version/sdk + projects[])—— 少任何一个,照抄的人拿到的都是一份构建过不了的配置,
362
+ * 等于把人送进另一个死循环。
263
363
  */
264
364
  function createConfigStep(step, configPath, spid, carryHint) {
265
- const carry = carryHint ?? 'a project generated by `supercli create-app` already ships this file';
365
+ const carry = carryHint ?? 'a workspace created by `supercli init` already ships this file';
266
366
  return `${step}) write the following into ${quotePath(configPath)} (${carry}):\n${(0, siteConfig_1.configTemplate)(spid)}`;
267
367
  }
368
+ /** 一条可以直接贴进 `projects[]` 的站点项目条目。键序与 config/appConfig.ts 的写盘键序一致。 */
369
+ function siteProjectEntry(projectDir, deploy) {
370
+ const deployEntry = `{ "slug": ${JSON.stringify(deploy.slug)}, "name": ${JSON.stringify(deploy.name)}, ` +
371
+ `"env": ${JSON.stringify(deploy.env)}, "dir": ${JSON.stringify(deploy.dir)} }`;
372
+ return (`{ "type": "site", "dir": ${JSON.stringify(projectDir)}, "name": ${JSON.stringify(deploy.name)}, ` +
373
+ `"deploy": [${deployEntry}] }`);
374
+ }
375
+ /**
376
+ * 「把这个发布目录登记进 supersdk.json」的指引。
377
+ *
378
+ * 🔴 这里**绝不能**写 `supercli add site <dir>`:`add` 是「从内置模板生成一个新项目」的命令,
379
+ * 它对非空目录硬失败("target directory … is not empty. `supercli add` never merges into an
380
+ * existing tree"),而一个正在被发布的目录必然非空 —— 照着提示做只会撞回同一句提示,正是
381
+ * reissueCommand 的注释里写着要消灭的那个死循环。所以给的是能直接照抄落盘的那一条 JSON。
382
+ *
383
+ * 导出仅为可测:这条提示的三个分支里有两个只在「发布成功之后」才可达,离线到不了。
384
+ */
385
+ function registerSiteProjectHint(configPath, deploy, existingProjectDirs) {
386
+ // 🔴 先跑一遍 parseConfig 自己对 projects[].dir 的两条硬约束。拼不出合法 entry 却照发,
387
+ // 用户粘贴之后配置立刻变非法 —— 而且是**他手动粘出来的**,此后该工作空间每一次
388
+ // publish-site 都失败。给不出可执行的建议时,宁可说清为什么,也不要给一条会砸脚的。
389
+ const normalized = (0, siteConfig_1.normalizeProjectDir)(deploy.dir);
390
+ if (normalized === undefined) {
391
+ return (`not registrable as a project: ${quotePath(deploy.dir)} resolves outside the workspace rooted at ` +
392
+ `${quotePath(path.dirname(configPath))} (a "projects[].dir" may not be absolute nor contain a ".." segment). ` +
393
+ 'publish the directory from a workspace that contains it, or move the build output inside this one.');
394
+ }
395
+ const clash = existingProjectDirs.find((other) => other === normalized || (0, siteConfig_1.isAncestorDir)(other, normalized) || (0, siteConfig_1.isAncestorDir)(normalized, other));
396
+ if (clash !== undefined) {
397
+ return (`not registrable as a project: ${quotePath(normalized)} overlaps the existing project ${quotePath(clash)} ` +
398
+ '(project dirs must not nest inside one another). give this site its own directory outside ' +
399
+ `${quotePath(clash)}, then register that one.`);
400
+ }
401
+ return [
402
+ `add this entry to the "projects" array in ${quotePath(configPath)} (\`supercli add site\` scaffolds a NEW project from the built-in template and refuses a non-empty directory, so it cannot register a directory you are already publishing):`,
403
+ ` ${siteProjectEntry(normalized, deploy)}`,
404
+ // 这句只在合法分支成立:工作空间外的目录,它的任何祖先都得靠 `..` 才能表达,
405
+ // 而 `..` 恰恰是非法的 —— 所以上面两个 refuse 分支绝不能带上它。
406
+ ` (if ${quotePath(normalized)} is build output, put the source project directory in "dir" instead — any ancestor of the publish dir covers it, and only "deploy[].dir" has to be the directory you publish)`,
407
+ ].join('\n');
408
+ }
268
409
  /**
269
410
  * 迁移提示的两条硬规则(两个旧文件共用):
270
411
  *
271
412
  * 1. 已经有一份合法的 supersdk.json → **只发 `rm`**。让用户再写一遍已经就位的配置,
272
- * 轻则困惑,重则真的照抄覆盖掉自己 sites[]/orgId 的记录。
413
+ * 轻则困惑,重则真的照抄覆盖掉自己 deploy[]/orgId 的记录。
273
414
  * 2. 没有 → **先写新文件、再删旧文件**。旧文件是字段来源,先 `rm` 掉再让人「把字段搬进
274
415
  * 新文件」,字段就已经没了。
275
416
  */
@@ -280,13 +421,13 @@ function legacyMigrationMessage(args) {
280
421
  args.headline,
281
422
  ];
282
423
  if (args.existingConfigPath) {
283
- lines.push(`your ${quotePath(args.existingConfigPath)} is already in place (schemaVersion ${siteConfig_1.SCHEMA_VERSION}) and publish bindings come from it — there is no new config to write. run these in order:`, `1) delete the retired file: rm ${quotePath(args.legacyPath)}`, `2) re-run: ${args.rerun}`);
424
+ lines.push(`your ${quotePath(args.existingConfigPath)} is already in place (schemaVersion ${siteConfig_1.SCHEMA_VERSION}) and publish bindings come from it — there is no new config to write. run these in order:`, `1) delete the retired file: rm ${shellArg(args.legacyPath)}`, `2) re-run: ${args.rerun}`);
284
425
  return lines.join('\n');
285
426
  }
286
427
  lines.push('run these in order — write the new file first, delete the old one after: the old file is where these values come from, deleting it early leaves nothing to copy:', createConfigStep(1, args.newConfigPath, args.spid, args.carryHint));
287
428
  if (args.newConfigHint)
288
429
  lines.push(` (${args.newConfigHint})`);
289
- lines.push(`2) delete the retired file: rm ${quotePath(args.legacyPath)}`, `3) re-run: ${args.rerun}`);
430
+ lines.push(`2) delete the retired file: rm ${shellArg(args.legacyPath)}`, `3) re-run: ${args.rerun}`);
290
431
  return lines.join('\n');
291
432
  }
292
433
  /** 发布目录里的旧站点绑定:补齐配置 + 删文件 + 原样重跑,三步一次说完。 */
@@ -296,56 +437,121 @@ function legacySiteYmlMessage(legacyPath, existingConfigPath, spid, rerun) {
296
437
  existingConfigPath,
297
438
  spid,
298
439
  rerun,
299
- headline: `site bindings now live in ${siteConfig_1.CONFIG_FILENAME} at the repo root (plain JSON, schemaVersion: 2).`,
300
- newConfigPath: path.join('<repo-root>', siteConfig_1.CONFIG_FILENAME),
301
- newConfigHint: 'the publish dir is build output — keep the config at the repo root; the command searches upwards from the publish dir',
302
- // super-site.yml 只装站点绑定,从来没有 android/ios/web/version/sdk 这些键 ——
440
+ headline: `site bindings now live in ${siteConfig_1.CONFIG_FILENAME} at the workspace root (plain JSON, schemaVersion: ${siteConfig_1.SCHEMA_VERSION}), inside the "deploy" array of the "type": "site" project.`,
441
+ newConfigPath: path.join('<workspace-root>', siteConfig_1.CONFIG_FILENAME),
442
+ newConfigHint: 'the publish dir is build output — keep the config at the workspace root; the command searches upwards from the publish dir',
443
+ // super-site.yml 只装站点绑定,从来没有 projects/version/sdk 这些键 ——
303
444
  // 让人从那里「抄」不存在的字段是把人往沟里带。
304
- carryHint: `copy project.org_id from ${path.basename(legacyPath)} into orgId, and ` +
305
- 'site.slug/site.name/environment into one sites[] entry; fill the App-side fields from your own project',
445
+ carryHint: `copy project.org_id from ${path.basename(legacyPath)} into orgId, and site.slug/site.name/environment into ` +
446
+ 'one deploy[] entry of the "type": "site" project; fill the App-side projects from your own repo',
306
447
  });
307
448
  }
308
- /** 仓库根的旧 App 配置:同样 fail-closed,绝不把 YAML 方言「尽力解释」成发布目标。 */
449
+ /** 工作空间根的旧 App 配置:同样 fail-closed,绝不把 YAML 方言「尽力解释」成发布目标。 */
309
450
  function legacyAppYamlMessage(legacyPath, existingConfigPath, spid, rerun) {
310
451
  return legacyMigrationMessage({
311
452
  legacyPath,
312
453
  existingConfigPath,
313
454
  spid,
314
455
  rerun,
315
- headline: `the SuperSDK project config is now ${siteConfig_1.CONFIG_FILENAME} in the same directory (plain JSON, no comments).`,
456
+ headline: `the SuperSDK workspace config is now ${siteConfig_1.CONFIG_FILENAME} in the same directory (plain JSON, no comments).`,
316
457
  newConfigPath: path.join(path.dirname(legacyPath), siteConfig_1.CONFIG_FILENAME),
317
- // 旧的 supersdk.yaml 确实装着这些 App 字段,值得逐个搬。
318
- carryHint: `copy the name/environment/android/ios/web/version/sdk values you already have in ` +
319
- `${path.basename(legacyPath)} into the matching fields; leave the rest as placeholders`,
458
+ // 旧的 supersdk.yaml 装着 App 字段,值得逐个搬 —— 但落点变了(根上的 android/ios/web
459
+ // 变成 projects[] 里的条目),不说清楚照抄的人只会原样贴回根上,而那是硬失败。
460
+ carryHint: `copy the values you already have in ${path.basename(legacyPath)} into the matching places: name/version/sdk stay at the ` +
461
+ 'root, android/ios/web become one "projects" entry each (their package/bundleId/name move onto that entry), ' +
462
+ 'and drop "environment" entirely — it is a runtime argument of SuperSDK.init(), not a config field',
320
463
  });
321
464
  }
322
- function absentConfigMessage(dir, read, spid, rerun) {
465
+ /**
466
+ * schemaVersion 不是 3。v2 → v3 是破坏性变更,**不做向后兼容**,所以这条提示必须自己就是
467
+ * 一条完整的迁移路径:
468
+ *
469
+ * - 配置这半边:把「什么搬到了哪里」逐条说清 + 给出完整骨架;
470
+ * - 引擎那半边:生成仓库里 vendored 的 supersdk_template.py 有 `migrate` 子命令,
471
+ * 提示必须把人引到它 —— 只改配置、不迁引擎,下一步构建照样炸。
472
+ */
473
+ function unsupportedSchemaMessage(configPath, found, spid, rerun) {
474
+ const version = typeof found === 'number' ? String(found) : JSON.stringify(found);
475
+ const head = `${configPath} is schemaVersion ${version}; supercli reads schemaVersion ${siteConfig_1.SCHEMA_VERSION} only — the file is left untouched and nothing was published.`;
476
+ if (typeof found === 'number' && found > siteConfig_1.SCHEMA_VERSION) {
477
+ return [
478
+ head,
479
+ 'this config was written by a newer supercli. do NOT hand-edit it down: run `supercli update` and retry.',
480
+ `then re-run: ${rerun}`,
481
+ ].join('\n');
482
+ }
483
+ return [
484
+ head,
485
+ `schemaVersion ${siteConfig_1.SCHEMA_VERSION} is the workspace model: one workspace = one spid, and every app or site is an entry in "projects" identified by "type" + "dir". what moved:`,
486
+ ' - "environment" is gone entirely — the SDK environment is a runtime argument of SuperSDK.init() (omitting it means prod), so nothing at build time needs it',
487
+ ' - "android" / "ios" / "web" are no longer root sections — each becomes one "projects" entry, and package/bundleId/name/spmMode move onto that entry',
488
+ ' - "sites" is no longer a root section — each entry moves, unchanged ({slug, name, env, dir}), into the "deploy" array of the "type": "site" project that owns it',
489
+ ' - "orgId", "version" and "sdk" stay exactly where they are',
490
+ 'run these in order:',
491
+ '1) migrate the vendored build engine and this config, from the directory that holds the file:',
492
+ // 🔴 命令形式来自 config/appConfig.ts 的 engineMigrateCommand(`--config` 在权威侧是
493
+ // required=True,漏掉它 argparse 直接 exit 2)—— 不要在这里就地拼第二份。
494
+ ` cd ${shellArg(path.dirname(configPath))} && ${(0, appConfig_1.engineMigrateCommand)(path.basename(configPath))}`,
495
+ `2) if you would rather do it by hand, this is the complete shape (replace the placeholders with your own values, keep your existing orgId/deploy entries):\n${(0, siteConfig_1.configTemplate)(spid)}`,
496
+ `3) re-run: ${rerun}`,
497
+ ].join('\n');
498
+ }
499
+ function absentConfigMessage(dir, read, identity, rerun) {
323
500
  if (read.explicit) {
324
501
  return `the file given to --config does not exist: ${read.searched[0] ?? ''} — no fallback to the upward search, and no guessing of the publish target`;
325
502
  }
326
503
  const from = read.searched[0] ?? path.resolve(dir);
327
504
  const upTo = read.searched[read.searched.length - 1] ?? from;
505
+ const configPath = path.join(upTo, siteConfig_1.CONFIG_FILENAME);
328
506
  return [
329
507
  `no ${siteConfig_1.CONFIG_FILENAME} found: searched upwards from ${quotePath(from)} to ${quotePath(upTo)} (stopping at the repo root / home directory / filesystem root); nothing was published.`,
330
- 'publish bindings are read from the config file only — the project, site and environment are never guessed. run these in order:',
331
- createConfigStep(1, path.join(upTo, siteConfig_1.CONFIG_FILENAME), spid),
332
- `2) re-run: ${rerun}`,
333
- ` or point at an existing config directly: ${rerun} --config <path>/${siteConfig_1.CONFIG_FILENAME}`,
508
+ 'publish bindings are read from the config file only — the workspace, site and environment are never guessed. run these in order:',
509
+ // 🔴 --spid 是 init 的必填参数,而这个函数手上就有它:非交互终端(CI / SUPERCLI_TOKEN)
510
+ // 下漏掉它,照抄的人拿到的是 "these are required: --spid",白跑一趟。参数一个不能少。
511
+ `1) create the workspace in place: cd ${shellArg(upTo)} && supercli init --spid ${identity.spid}`,
512
+ ` (\`init\` writes the file for you; to write ${quotePath(configPath)} by hand instead, this is the complete shape:)`,
513
+ (0, siteConfig_1.configTemplate)(identity.spid),
514
+ `2) register the site project: ${registerSiteProjectHint(configPath, {
515
+ slug: identity.slug,
516
+ name: identity.name,
517
+ env: identity.env,
518
+ dir: (0, siteConfig_1.relativeSiteDir)(configPath, dir),
519
+ // 🔴 传骨架自带的 dir:第 1 步打印的模板里已经有 apps/android|ios|web,
520
+ // 两步都照抄时第 2 步不能拼出与它们嵌套的条目 —— 否则老实照做反而得到非法配置。
521
+ }, (0, siteConfig_1.configTemplateDirs)(identity.spid))}`,
522
+ `3) re-run: ${rerun}`,
523
+ ` or point at an existing config directly: ${rerun} --config ${shellArg(`<path>/${siteConfig_1.CONFIG_FILENAME}`)}`,
334
524
  ].join('\n');
335
525
  }
336
- async function oneEnvironmentRecheck(account, deps, tokenRef, client, context, spid, env) {
337
- const recheck = await withAuth(account, deps, tokenRef, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
526
+ async function oneEnvironmentRecheck(auth, deps, client, context, spid, env) {
527
+ const recheck = await withAuth(auth, deps, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
338
528
  if (recheck.kind !== 'outcome')
339
529
  return recheck;
340
530
  return (recheck.outcome.kind === 'success' || recheck.outcome.kind === 'soft_success') && listContainsEnvironment(valueFromOutcome(recheck.outcome), env);
341
531
  }
342
- async function oneSiteRecheck(account, deps, tokenRef, client, context, spid, slug) {
343
- const recheck = await withAuth(account, deps, tokenRef, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
532
+ async function oneSiteRecheck(auth, deps, client, context, spid, slug) {
533
+ const recheck = await withAuth(auth, deps, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
344
534
  if (recheck.kind !== 'outcome')
345
535
  return recheck;
346
536
  const detail = siteFrom(valueFromOutcome(recheck.outcome));
347
537
  return isSiteForTarget(detail, spid, slug) ? detail : undefined;
348
538
  }
539
+ /** Resolves the effective token + apiOrigin (env token wins; TC-020/050 clean machine). */
540
+ function resolveAuth(deps) {
541
+ const envToken = (0, tokenAuth_1.resolveEnvToken)();
542
+ if (envToken) {
543
+ return { token: envToken, apiOrigin: (0, environments_1.resolveApiOrigin)().apiOrigin };
544
+ }
545
+ const account = deps.getCurrentAccount();
546
+ if (!account)
547
+ return { ok: false, kind: 'needs_login', message: 'no account is logged in — run `supercli login` first' };
548
+ const stored = deps.getStoredToken(account);
549
+ if (!stored) {
550
+ deps.markNeedsLogin(account.accountKey);
551
+ return { ok: false, kind: 'needs_login', message: 'no valid credential found locally — run `supercli login` again' };
552
+ }
553
+ return { token: stored, apiOrigin: account.apiOrigin, accountKey: account.accountKey };
554
+ }
349
555
  async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps) {
350
556
  // 本地参数校验与目标冲突比对一律先于账号查找、HTTP、配置写入与打包。
351
557
  const explicit = {
@@ -354,13 +560,14 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
354
560
  env: trimFlag(opts.env),
355
561
  org: trimFlag(opts.org),
356
562
  config: trimFlag(opts.config),
563
+ version: trimFlag(opts.version),
357
564
  };
358
- // 发布目标必须每次都显式说明:--spid/--slug/--env/--version 恒为必填(commander 层已是
565
+ // 发布目标必须每次都显式说明:--spid/--slug/--env 恒为必填(commander 层已是
359
566
  // requiredOption,这里是给直接调用 runPublishSite 的调用方兜底)。配置文件不再是「取值
360
567
  // 来源」,而是与命令行逐项比对的一致性护栏 —— 目的是让「cd 错目录」这类事故在本地就
361
568
  // 失败,而不是把内容发到另一个站点去。
362
569
  if (!explicit.spid || !explicit.slug || !explicit.env) {
363
- return { ok: false, message: '--spid, --slug and --env are all required — the project, site and environment are never guessed' };
570
+ return { ok: false, message: '--spid, --slug and --env are all required — the workspace, site and environment are never guessed' };
364
571
  }
365
572
  const spid = explicit.spid;
366
573
  const slug = explicit.slug;
@@ -371,11 +578,12 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
371
578
  return { ok: false, message: 'invalid --slug: must be 1-32 lowercase letters or digits, and must not be stg' };
372
579
  if (!isValidEnvironment(env))
373
580
  return { ok: false, message: 'invalid --env: must be 1-10 lowercase letters or digits' };
374
- const parsedVersion = (0, offlineVersion_1.parseOfflineVersion)(trimFlag(opts.version));
375
- if (!parsedVersion) {
376
- return { ok: false, message: '--version is required and must be an x.y.z of at most 64 bytes (major <= 2147483647, minor/patch <= 99; leading zeros compare numerically)' };
581
+ // 显式传入的 --version 就地判掉,不去读盘:一个写错的版本号跟配置没有任何关系。
582
+ // 缺省的那条路要等配置读出来才有默认值(见下方 version 解析)。
583
+ const explicitVersion = explicit.version ? (0, offlineVersion_1.parseOfflineVersion)(explicit.version) : undefined;
584
+ if (explicit.version && !explicitVersion) {
585
+ return { ok: false, message: 'invalid --version: must be an x.y.z of at most 64 bytes (major <= 2147483647, minor/patch <= 99; leading zeros compare numerically)' };
377
586
  }
378
- const version = parsedVersion.raw;
379
587
  // 🔴 发布目录的存在性/类型必须在**任何网络请求之前**判掉。
380
588
  // 打包(buildZip)本身会校验根级 index.html,但它排在 createSite 之后 —— 于是敲错一个
381
589
  // 目录名的后果是:服务端已经把站点建出来了,才在一个纯本地、零成本就能判定的步骤上失败,
@@ -389,17 +597,20 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
389
597
  }
390
598
  // 参数先于读盘校验,是为了让迁移/创建提示里能回显用户真正敲过的那条命令。
391
599
  const read = normalizeConfig(deps.readConfig(dir, explicit.config));
392
- const rerun = () => reissueCommand(dir, opts, { spid, slug, env, version });
600
+ const rerun = () => reissueCommand(dir, opts, { spid, slug, env });
393
601
  if (read.kind === 'legacy-site-yml')
394
602
  return { ok: false, message: legacySiteYmlMessage(read.path, read.existingConfigPath, spid, rerun()) };
395
603
  if (read.kind === 'legacy-app-yaml')
396
604
  return { ok: false, message: legacyAppYamlMessage(read.path, read.existingConfigPath, spid, rerun()) };
605
+ if (read.kind === 'unsupported-schema')
606
+ return { ok: false, message: unsupportedSchemaMessage(read.path, read.found, spid, rerun()) };
397
607
  if (read.kind === 'invalid') {
398
608
  const where = read.path ? ` (${read.path})` : '';
399
- return { ok: false, message: `${siteConfig_1.CONFIG_FILENAME} is invalid or incomplete${where}: ${read.reason ?? 'the shape does not match schemaVersion 2'} — the file is left untouched; fix it and retry` };
609
+ return { ok: false, message: `${siteConfig_1.CONFIG_FILENAME} is invalid or incomplete${where}: ${read.reason ?? `the shape does not match schemaVersion ${siteConfig_1.SCHEMA_VERSION}`} — the file is left untouched; fix it and retry` };
610
+ }
611
+ if (read.kind === 'absent') {
612
+ return { ok: false, message: absentConfigMessage(dir, read, { spid, slug, env, name: trimFlag(opts.name) ?? slug }, rerun()) };
400
613
  }
401
- if (read.kind === 'absent')
402
- return { ok: false, message: absentConfigMessage(dir, read, spid, rerun()) };
403
614
  const config = read.config;
404
615
  if (config.spid !== spid) {
405
616
  return { ok: false, message: `--spid ${spid} conflicts with the spid ${config.spid} recorded in ${config.path} — the binding is never silently rebound, nor the publish target overridden` };
@@ -407,25 +618,66 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
407
618
  if (explicit.org && config.orgId && explicit.org !== config.orgId) {
408
619
  return { ok: false, message: `--org ${explicit.org} conflicts with the orgId ${config.orgId} recorded in ${config.path} — refusing to publish to a different org` };
409
620
  }
410
- // 🔴 顶层 environment 是 App 自身的 SDK 运行环境,与 sites[].env(站点发到项目的哪个
411
- // 环境)是正交的两件事,这里**刻意不做相等断言** —— 用 staging 配置构建却发 prod 站点
412
- // 是合法组合。
413
- const bound = config.sites.find((site) => site.slug === slug && site.env === env);
414
- const mustAppendSite = !bound;
621
+ // 定位站点项目:
622
+ // 1. 先按 (slug, env) 找已登记的 deploy[] 条目 —— 它是这次发布的权威绑定,名字从它来;
623
+ // 2. 没有登记过,就看发布目录落在哪个 "type": "site" 项目里,新条目回填到那一条。
624
+ //
625
+ // 🔴 两条都没命中时**不拒绝发布**:v2 的 publish-site 对发布目录没有任何要求(只比对
626
+ // spid),把它收紧成「必须先注册」是破坏性变更。这里保持可发布,但明确告诉用户这次没有
627
+ // 被记录、以及用哪条命令补上 —— 不静默。
628
+ const relativeDir = (0, siteConfig_1.relativeSiteDir)(config.path, dir);
629
+ const bound = (() => {
630
+ for (const project of config.siteProjects) {
631
+ const entry = project.deploy.find((item) => item.slug === slug && item.env === env);
632
+ if (entry)
633
+ return { project, entry };
634
+ }
635
+ return undefined;
636
+ })();
637
+ const owner = bound?.project ?? projectCovering(config.siteProjects, relativeDir);
638
+ const mustAppendDeploy = !bound && owner !== undefined;
415
639
  const mustBackfillOrgId = !config.orgId;
416
- const siteName = (bound?.name ?? trimFlag(opts.name) ?? slug).trim();
640
+ // --version 缺省值:站点项目的覆盖优先,否则用 workspace 级默认。
641
+ //
642
+ // 🔴 这里是**整值替换**,不是深合并:站点项目一旦写了 `version`,就再也不借 workspace 的
643
+ // 任何一半。parseConfig 保证了这条不变式(项目级 version 必须同时带 name 与 code,否则
644
+ // 整份配置 fail-closed),所以 `owner?.versionName ?? config.versionName` 只会在项目**没有**
645
+ // version 时才落到 workspace 上。放宽那条校验,这一行立刻退化成静默深合并 —— publish-site
646
+ // 会用 workspace 的 version.name 补上项目缺的那一半,把一份 super_build.sh 当场拒绝的配置
647
+ // 发出去。
648
+ let version;
649
+ if (explicitVersion) {
650
+ version = explicitVersion.raw;
651
+ }
652
+ else {
653
+ const fallback = owner?.versionName ?? config.versionName;
654
+ if (!fallback) {
655
+ return {
656
+ ok: false,
657
+ message: `--version is not set and no version.name is recorded in ${config.path} — pass --version x.y.z, or add "version": { "name": "1.0.0", "code": 1 } to the workspace root (or to the site project, which overrides it)`,
658
+ };
659
+ }
660
+ const parsed = (0, offlineVersion_1.parseOfflineVersion)(fallback);
661
+ if (!parsed) {
662
+ return {
663
+ ok: false,
664
+ message: `the version.name recorded in ${config.path} ("${fallback}") is not a usable offline package version — it must be an x.y.z of at most 64 bytes (major <= 2147483647, minor/patch <= 99); fix it there or pass --version explicitly`,
665
+ };
666
+ }
667
+ version = parsed.raw;
668
+ }
669
+ // 🔴 显式 `--name` 排在**最前**:`add site` 现在会预写一条 deploy[](v2 时代那条只在首次
670
+ // 发布成功后才出现),把已登记的 name 排在 flag 前面,等于用户敲的 `--name 'Acme Web'` 被
671
+ // 静默吞掉、站点用 slug 建出来还返回 ok。配置只在用户**没说**时兜底。
672
+ const siteName = (trimFlag(opts.name) ?? bound?.entry.name ?? slug).trim();
417
673
  const siteNameLength = Array.from(siteName).length;
418
674
  if (siteNameLength < 1 || siteNameLength > 50)
419
675
  return { ok: false, message: 'invalid --name: must be 1-50 characters' };
420
- const account = deps.getCurrentAccount();
421
- if (!account)
422
- return { ok: false, message: 'no account is logged in — run `supercli login` first' };
423
- const accessToken = deps.getAccessToken(account);
424
- if (!accessToken) {
425
- deps.markNeedsLogin(account.accountKey);
426
- return { ok: false, message: 'no valid credential found locally — run `supercli login` again' };
427
- }
428
- const tokenRef = { value: accessToken };
676
+ // token-wins 鉴权:SUPERCLI_TOKEN 优先于落盘账号;401 = 终态 needs-login,不再 refresh 重试。
677
+ const auth = resolveAuth(deps);
678
+ if ('ok' in auth)
679
+ return auth; // resolveAuth returned a PublishSiteResult failure
680
+ // Resolve the org: explicit --org, else the token's bound org via whoami.
429
681
  let orgId;
430
682
  if (explicit.org) {
431
683
  const resolution = (0, orgResolve_1.resolveOrgId)([], explicit.org);
@@ -434,41 +686,79 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
434
686
  orgId = resolution.orgId;
435
687
  }
436
688
  else {
437
- const me = await withAuth(account, deps, tokenRef, (token) => deps.fetchMe(account.apiOrigin, token));
438
- if (me.kind !== 'outcome')
439
- return { ok: false, message: terminalMessage(me) };
440
- if (me.outcome.kind !== 'success')
441
- return { ok: false, message: `cannot read the current user's orgs: ${'message' in me.outcome ? me.outcome.message : me.outcome.kind}` };
442
- const resolution = (0, orgResolve_1.resolveOrgId)(me.outcome.data.orgs ?? undefined);
443
- if (resolution.kind === 'none')
444
- return { ok: false, message: 'the current account belongs to no org — nothing to publish to' };
445
- if (resolution.kind === 'ambiguous')
446
- return { ok: false, message: `the current account belongs to several orgs (${resolution.orgIds.join(', ')}) — pick one with --org <id>` };
447
- if (resolution.kind !== 'resolved')
448
- return { ok: false, message: 'cannot resolve the current org' };
449
- orgId = resolution.orgId;
689
+ // token-scoped identity: the token's bound org comes from /api/open/whoami (org_id).
690
+ const who = await withAuth(auth, deps, (token) => deps.fetchWhoami(auth.apiOrigin, token));
691
+ if (who.kind !== 'outcome')
692
+ return terminalResult();
693
+ if (who.outcome.kind !== 'success') {
694
+ return {
695
+ ok: false,
696
+ kind: failureKind(who.outcome.kind),
697
+ message: `cannot resolve the org bound to the current token: ${'message' in who.outcome ? who.outcome.message : who.outcome.kind}`,
698
+ };
699
+ }
700
+ orgId = String(who.outcome.data.org_id ?? '');
701
+ if (!orgId || orgId === '0')
702
+ return { ok: false, message: 'the current token is not bound to any org — nothing to publish to' };
450
703
  }
451
704
  if (config.orgId && config.orgId !== orgId) {
452
705
  return { ok: false, message: `the resolved org ${orgId} conflicts with the orgId ${config.orgId} recorded in ${config.path} — refusing to publish to a different org` };
453
706
  }
454
- const client = deps.createSiteClient(account.apiOrigin);
455
- const context = { accessToken: tokenRef.value, orgId };
707
+ const client = deps.createSiteClient(auth.apiOrigin);
708
+ const context = { accessToken: auth.token, orgId };
709
+ const idempotencyKey = trimFlag(opts.idempotencyKey) ?? crypto.randomUUID();
710
+ // ---- dry-run (AC-7): read-only checks + server validation, create nothing ----
711
+ if (opts.dryRun) {
712
+ const lookedUp = await withAuth(auth, deps, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
713
+ if (lookedUp.kind !== 'outcome')
714
+ return terminalResult();
715
+ const existing = siteFrom(valueFromOutcome(lookedUp.outcome));
716
+ const siteExists = isSiteForTarget(existing, spid, slug);
717
+ const expectedSiteId = siteExists ? existing.id : 0;
718
+ let zip;
719
+ try {
720
+ zip = await deps.buildZip(dir);
721
+ }
722
+ catch (error) {
723
+ const message = error instanceof siteZip_1.ZipBuildError ? error.message : error.message;
724
+ return { ok: false, message: `packaging failed: ${message}` };
725
+ }
726
+ const dryDeploy = await withAuth(auth, deps, (token) => client.deploy({ ...context, accessToken: token }, spid, slug, env, {
727
+ zip: zip.buffer,
728
+ version,
729
+ description: opts.description,
730
+ expectedSiteId,
731
+ idempotencyKey,
732
+ dryRun: true,
733
+ }));
734
+ if (dryDeploy.kind !== 'outcome')
735
+ return terminalResult();
736
+ if (dryDeploy.outcome.kind !== 'success' && dryDeploy.outcome.kind !== 'soft_success') {
737
+ return { ok: false, kind: failureKind(dryDeploy.outcome.kind), message: nonSuccessMessage(dryDeploy.outcome, 'deploy validation') };
738
+ }
739
+ return {
740
+ ok: true,
741
+ message: `dry-run validated: ${spid}/${slug}/${env} version=${version} (no deployment created)`,
742
+ // 🔴 dry-run 一个字节都不写盘:它只报告「这次发布会不会被记录」,绝不预先登记。
743
+ result: { dryRun: true, spid, slug, env, version, siteExists, wouldRecordDeploy: mustAppendDeploy, plan: valueFromOutcome(dryDeploy.outcome) },
744
+ };
745
+ }
456
746
  // env-before-site: unavailable environments never leave a new site behind.
457
- const listed = await withAuth(account, deps, tokenRef, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
747
+ const listed = await withAuth(auth, deps, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
458
748
  if (listed.kind !== 'outcome')
459
- return { ok: false, message: terminalMessage(listed) };
749
+ return terminalResult();
460
750
  let environmentAvailable = (listed.outcome.kind === 'success' || listed.outcome.kind === 'soft_success') && listContainsEnvironment(valueFromOutcome(listed.outcome), env);
461
751
  if (!environmentAvailable) {
462
752
  if (listed.outcome.kind !== 'success' && listed.outcome.kind !== 'soft_success') {
463
- return { ok: false, message: nonSuccessMessage(listed.outcome, 'listing project environments') };
753
+ return { ok: false, kind: failureKind(listed.outcome.kind), message: nonSuccessMessage(listed.outcome, 'listing project environments') };
464
754
  }
465
755
  if (env === 'prod')
466
756
  return { ok: false, message: 'the project has no prod environment — check the project state in the Console' };
467
757
  if (!opts.createEnvironment)
468
758
  return { ok: false, message: `project environment "${env}" does not exist — pass --create-environment explicitly to create this shared environment` };
469
- const created = await withAuth(account, deps, tokenRef, (token) => client.createEnvironment({ ...context, accessToken: token }, spid, { name: env }));
759
+ const created = await withAuth(auth, deps, (token) => client.createEnvironment({ ...context, accessToken: token }, spid, { name: env }));
470
760
  if (created.kind !== 'outcome')
471
- return { ok: false, message: terminalMessage(created) };
761
+ return terminalResult();
472
762
  if (created.outcome.kind === 'success' && asRecord(created.outcome.data)?.name === env) {
473
763
  environmentAvailable = true;
474
764
  }
@@ -476,29 +766,29 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
476
766
  created.outcome.kind === 'soft_success' ||
477
767
  created.outcome.kind === 'infra_error' ||
478
768
  (created.outcome.kind === 'business_error' && created.outcome.code === 'ENV_NAME_DUPLICATE')) {
479
- const rechecked = await oneEnvironmentRecheck(account, deps, tokenRef, client, context, spid, env);
769
+ const rechecked = await oneEnvironmentRecheck(auth, deps, client, context, spid, env);
480
770
  if (typeof rechecked !== 'boolean')
481
- return { ok: false, message: terminalMessage(rechecked) };
771
+ return terminalResult();
482
772
  environmentAvailable = rechecked;
483
773
  }
484
774
  else {
485
- return { ok: false, message: nonSuccessMessage(created.outcome, 'creating the project environment') };
775
+ return { ok: false, kind: failureKind(created.outcome.kind), message: nonSuccessMessage(created.outcome, 'creating the project environment') };
486
776
  }
487
777
  if (!environmentAvailable)
488
778
  return { ok: false, message: `cannot confirm project environment "${env}" was created — the write is never replayed; check the Console shortly` };
489
779
  }
490
780
  let detail;
491
- const lookedUp = await withAuth(account, deps, tokenRef, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
781
+ const lookedUp = await withAuth(auth, deps, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
492
782
  if (lookedUp.kind !== 'outcome')
493
- return { ok: false, message: terminalMessage(lookedUp) };
783
+ return terminalResult();
494
784
  const existing = siteFrom(valueFromOutcome(lookedUp.outcome));
495
785
  if (isSiteForTarget(existing, spid, slug)) {
496
786
  detail = existing;
497
787
  }
498
788
  else if (lookedUp.outcome.kind === 'business_error' && lookedUp.outcome.code === 'NOT_FOUND') {
499
- const created = await withAuth(account, deps, tokenRef, (token) => client.createSite({ ...context, accessToken: token }, spid, { name: siteName, slug }));
789
+ const created = await withAuth(auth, deps, (token) => client.createSite({ ...context, accessToken: token }, spid, { name: siteName, slug }));
500
790
  if (created.kind !== 'outcome')
501
- return { ok: false, message: terminalMessage(created) };
791
+ return terminalResult();
502
792
  const createdDetail = siteFrom(valueFromOutcome(created.outcome));
503
793
  if (created.outcome.kind === 'success' && isSiteForTarget(createdDetail, spid, slug)) {
504
794
  detail = createdDetail;
@@ -507,24 +797,24 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
507
797
  created.outcome.kind === 'infra_error' ||
508
798
  (created.outcome.kind === 'business_error' && created.outcome.code === 'SITE_SLUG_DUPLICATE') ||
509
799
  (created.outcome.kind === 'success' && !isSiteForTarget(createdDetail, spid, slug))) {
510
- const rechecked = await oneSiteRecheck(account, deps, tokenRef, client, context, spid, slug);
800
+ const rechecked = await oneSiteRecheck(auth, deps, client, context, spid, slug);
511
801
  if (isTerminal(rechecked))
512
- return { ok: false, message: terminalMessage(rechecked) };
802
+ return terminalResult();
513
803
  detail = rechecked;
514
804
  }
515
805
  else {
516
- return { ok: false, message: nonSuccessMessage(created.outcome, 'creating the project site') };
806
+ return { ok: false, kind: failureKind(created.outcome.kind), message: nonSuccessMessage(created.outcome, 'creating the project site') };
517
807
  }
518
808
  if (!detail)
519
809
  return { ok: false, message: 'cannot confirm the project site was created — no write is replayed, no binding recorded and nothing published; check again shortly' };
520
810
  }
521
811
  else {
522
- return { ok: false, message: nonSuccessMessage(lookedUp.outcome, 'looking up the project site') };
812
+ return { ok: false, kind: failureKind(lookedUp.outcome.kind), message: nonSuccessMessage(lookedUp.outcome, 'looking up the project site') };
523
813
  }
524
814
  // 🔴 打包必须排在写配置之前:它是纯本地校验(根级 index.html、体积/条目上限、符号链接
525
815
  // 等),零网络成本。反过来的顺序会留下一个永远无人纠正的错误记录 —— 首次对一个没有
526
- // index.html 的目录发布时,sites[] 已经把这个 dir 记下、打包才失败,而回填是「只增不改」、
527
- // sites[].dir 也从不与实际发布目录比对,之后没有任何代码路径会去修正它。
816
+ // index.html 的目录发布时,deploy[] 已经把这个 dir 记下、打包才失败,而回填是「只增不改」、
817
+ // deploy[].dir 也从不与实际发布目录比对,之后没有任何代码路径会去修正它。
528
818
  let zip;
529
819
  try {
530
820
  zip = await deps.buildZip(dir);
@@ -533,64 +823,116 @@ async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps)
533
823
  const message = error instanceof siteZip_1.ZipBuildError ? error.message : error.message;
534
824
  return { ok: false, message: `packaging failed: ${message}` };
535
825
  }
536
- // 回填只发生在服务端已确认站点身份、且本地打包已经通过之后,且只增不改:sites[] 里没有
826
+ // 回填只发生在服务端已确认站点身份、且本地打包已经通过之后,且只增不改:deploy[] 里没有
537
827
  // 对应条目才 append,orgId 只在缺失时补写。任何一处与既有记录冲突,siteConfig 会抛错而
538
828
  // 不是覆盖。
539
- const wroteConfig = mustAppendSite || mustBackfillOrgId;
829
+ const wroteConfig = mustAppendDeploy || mustBackfillOrgId;
540
830
  if (wroteConfig) {
541
831
  try {
542
832
  deps.updateConfig(config.path, {
543
833
  ...(mustBackfillOrgId ? { orgId } : {}),
544
- ...(mustAppendSite ? { appendSite: { slug, name: detail.name, env, dir: (0, siteConfig_1.relativeSiteDir)(config.path, dir) } } : {}),
834
+ ...(mustAppendDeploy && owner
835
+ ? { siteProjectIndex: owner.index, appendDeploy: { slug, name: detail.name, env, dir: relativeDir } }
836
+ : {}),
545
837
  });
546
838
  }
547
839
  catch (error) {
548
840
  return { ok: false, message: `writing ${siteConfig_1.CONFIG_FILENAME} failed, nothing published: ${error.message}` };
549
841
  }
550
842
  }
551
- const deployed = await withAuth(account, deps, tokenRef, (token) => client.deploy({ ...context, accessToken: token }, spid, slug, env, {
843
+ const deployed = await withAuth(auth, deps, (token) => client.deploy({ ...context, accessToken: token }, spid, slug, env, {
552
844
  zip: zip.buffer,
553
845
  version,
554
846
  description: opts.description,
555
847
  expectedSiteId: detail.id,
848
+ idempotencyKey,
556
849
  }));
557
850
  if (deployed.kind !== 'outcome')
558
- return { ok: false, message: terminalMessage(deployed) };
851
+ return terminalResult();
559
852
  if (deployed.outcome.kind !== 'success' && deployed.outcome.kind !== 'soft_success') {
560
- return { ok: false, message: nonSuccessMessage(deployed.outcome, 'deploy') };
853
+ return { ok: false, kind: failureKind(deployed.outcome.kind), message: nonSuccessMessage(deployed.outcome, 'deploy') };
561
854
  }
562
855
  const pending = deployed.outcome.kind === 'soft_success';
563
856
  // 域名的 zone 是平台部署配置(生产 supersdk.site / staging supersdk.top),CLI 不掌握也不该
564
857
  // 猜——只用服务端返回的 domain;两处都没有就让用户去 Console 看,绝不编造一个不存在的域名。
565
- const domain = domainFromDeploy(valueFromOutcome(deployed.outcome)) ?? domainFromSite(detail, env);
858
+ //
859
+ // 🔴 归一化只做这一次,展示与落盘用的是**同一个值**:之前展示侧剥 scheme、存储侧原样落盘,
860
+ // 服务端哪天返回 "https://acme.supersdk.site" 就会把一个非规范化的 host 写进 offline.host,
861
+ // 而 updateConfig 对它是字节比对(不同即抛错),之后每次 prod 发布都要报一次「拒绝覆盖」。
862
+ const domain = canonicalHost(domainFromDeploy(valueFromOutcome(deployed.outcome)) ?? domainFromSite(detail, env));
863
+ const notes = [];
864
+ if (wroteConfig)
865
+ notes.push(`updated ${mustAppendDeploy ? 'the site project deploy[]' : 'orgId'} in ${config.path}`);
866
+ if (!bound && !owner) {
867
+ notes.push(`not recorded in ${siteConfig_1.CONFIG_FILENAME}: no "type": "site" project covers ${quotePath(relativeDir)}, so later deploys stay untracked — ` +
868
+ registerSiteProjectHint(config.path, { slug, name: detail.name, env, dir: relativeDir }, config.projectDirs));
869
+ }
870
+ notes.push(...offlineHostNotes({ deps, config, owner, env, domain }));
871
+ const domainNote = domain ? `reachable at https://${domain}` : 'find the public domain on the Hosting page in the Console';
566
872
  const pendingNote = pending ? ' (accepted; pointer sync in progress, live shortly)' : '';
567
- const domainNote = domain
568
- ? `; reachable at https://${domain.replace(/^https?:\/\//, '')}`
569
- : '; find the public domain on the Hosting page in the Console';
570
- const configNote = wroteConfig ? `; updated ${mustAppendSite ? 'sites[]' : 'orgId'} in ${config.path}` : '';
571
- return { ok: true, message: `published${configNote}${domainNote}${pendingNote}` };
873
+ return {
874
+ ok: true,
875
+ soft: pending,
876
+ message: `published; ${[domainNote, ...notes].join('; ')}${pendingNote}`,
877
+ result: { dryRun: false, spid, slug, env, version, pending, domain, notes, deploy: valueFromOutcome(deployed.outcome) },
878
+ };
879
+ }
880
+ /**
881
+ * `offline.host` 回填 —— 发布成功之后才做,因为域名只能来自服务端响应。
882
+ *
883
+ * 三条纪律:
884
+ * 1. **CLI 绝不自己拼域名**:zone 随平台部署环境而变(生产 supersdk.site / staging
885
+ * supersdk.top),域名只用服务端返回值;没有就跳过并**显式说明**,不静默;
886
+ * 2. **只认 prod 那次发布**:offline.host 是 App 离线包要指向的线上域名,把一次 preview
887
+ * 发布的域名钉进去,等于让发布版 App 去连预览站点;
888
+ * 3. 只在缺失时补写,已有值不同 → siteConfig 抛错,永不静默改绑定。
889
+ *
890
+ * 这一步失败**不能**让整条命令报失败:deploy 已经成功了,回一个 ok:false 会让 CI 以为内容
891
+ * 没发出去而重跑。所以只追加一条说明。
892
+ */
893
+ function offlineHostNotes(args) {
894
+ const { deps, config, owner, env, domain } = args;
895
+ if (!owner || owner.offlineHost !== undefined)
896
+ return [];
897
+ if (env !== 'prod') {
898
+ return [`offline.host left unset: only a prod deploy records the host the app's offline package points at`];
899
+ }
900
+ if (!domain) {
901
+ return ['offline.host left unset: the server returned no domain for this deploy — find it on the Hosting page in the Console'];
902
+ }
903
+ try {
904
+ deps.updateConfig(config.path, { siteProjectIndex: owner.index, offlineHost: domain });
905
+ return [`recorded offline.host in ${config.path}`];
906
+ }
907
+ catch (error) {
908
+ return [`the deploy succeeded but offline.host could not be recorded: ${error.message}`];
909
+ }
572
910
  }
573
911
  function registerPublishSiteCommand(program) {
574
912
  program
575
913
  .command('publish-site <dir>')
576
914
  .description('Publish a project-scoped SuperSite deploy.')
577
- .requiredOption('--spid <spid>', `project spid; must match the spid recorded in ${siteConfig_1.CONFIG_FILENAME}`)
578
- .requiredOption('--slug <slug>', `site slug; looked up in ${siteConfig_1.CONFIG_FILENAME} sites[] together with --env`)
579
- .requiredOption('--env <env>', `site environment; looked up in ${siteConfig_1.CONFIG_FILENAME} sites[] together with --slug`)
915
+ .requiredOption('--spid <spid>', `workspace spid; must match the spid recorded in ${siteConfig_1.CONFIG_FILENAME}`)
916
+ .requiredOption('--slug <slug>', `site slug; looked up in the site project's deploy[] together with --env`)
917
+ .requiredOption('--env <env>', `site environment; looked up in the site project's deploy[] together with --slug`)
580
918
  .option('--config <path>', `path to ${siteConfig_1.CONFIG_FILENAME}; defaults to the nearest one found upwards from <dir>`)
581
919
  .option('--org <id>', 'organization id; required when the account has multiple orgs')
582
920
  .option('--name <name>', 'display name used only when creating a new site')
583
921
  .option('--create-environment', 'explicitly authorize creating a missing non-prod project environment')
584
- .requiredOption('--version <version>', 'required offline package version: x.y.z (major <= 2147483647; minor/patch <= 99)')
922
+ .option('--version <version>', `offline package version x.y.z (major <= 2147483647; minor/patch <= 99); defaults to version.name from ${siteConfig_1.CONFIG_FILENAME}`)
585
923
  .option('--description <description>', 'deploy description')
586
- .action(async (dir, options) => {
924
+ .option('--dry-run', 'validate locally + server-side without creating a deployment; print a plan')
925
+ .option('--idempotency-key <key>', 'client idempotency key; replaying the same key returns the first deploy')
926
+ .action(async (dir, options, cmd) => {
927
+ const mode = cmd.optsWithGlobals?.()?.output === 'json' ? 'json' : 'human';
928
+ const printer = new resultPrinter_1.ResultPrinter(mode);
587
929
  const result = await runPublishSite(dir, options);
588
- if (!result.ok) {
589
- log_1.log.error(result.message ?? 'publish-site failed');
590
- process.exitCode = 1;
591
- return;
930
+ if (result.ok) {
931
+ printer.success(result.result ?? {}, { soft: result.soft, humanMessage: result.message });
932
+ }
933
+ else {
934
+ printer.failure(result.kind ?? 'business_error', result.message ?? 'publish-site failed');
592
935
  }
593
- log_1.log.info(result.message ?? 'published');
594
936
  });
595
937
  }
596
938
  //# sourceMappingURL=publishSite.js.map