@supersdk/supercli 0.3.2 → 0.3.3-staging.47

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