@supersdk/supercli 0.1.1-staging.3 → 0.1.1-staging.5

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 (36) hide show
  1. package/dist/commands/createApp.js +14 -58
  2. package/dist/commands/createApp.js.map +1 -1
  3. package/dist/commands/publishSite.js +288 -209
  4. package/dist/commands/publishSite.js.map +1 -1
  5. package/dist/config/environments.js +5 -3
  6. package/dist/config/environments.js.map +1 -1
  7. package/dist/createApp/copyTemplate.js +38 -53
  8. package/dist/createApp/copyTemplate.js.map +1 -1
  9. package/dist/publish/offlineVersion.js +33 -0
  10. package/dist/publish/offlineVersion.js.map +1 -0
  11. package/dist/publish/orgResolve.js +16 -17
  12. package/dist/publish/orgResolve.js.map +1 -1
  13. package/dist/publish/responseClassifier.js +17 -7
  14. package/dist/publish/responseClassifier.js.map +1 -1
  15. package/dist/publish/siteClient.js +19 -10
  16. package/dist/publish/siteClient.js.map +1 -1
  17. package/dist/publish/siteConfig.js +166 -124
  18. package/dist/publish/siteConfig.js.map +1 -1
  19. package/dist/template/README.md +11 -1
  20. package/dist/template/android/app/build.gradle.kts +6 -3
  21. package/dist/template/android/app/src/main/java/com/supersdk/simple/SimpleApplication.java +1 -1
  22. package/dist/template/android/gradle/supersdk-config-reader.gradle +2 -1
  23. package/dist/template/android/supersdk-default.config.json +3 -2
  24. package/dist/template/ios/MockSuperSDKPackage/Sources/SuperSDK/SuperSDK.swift +20 -4
  25. package/dist/template/ios/Sources/App/AppDelegate.swift +5 -1
  26. package/dist/template/ios/Sources/App/SimpleSDKBootstrap.swift +6 -2
  27. package/dist/template/ios/Sources/App/SimpleSDKProbe.swift +7 -4
  28. package/dist/template/ios/Tests/SimpleAppTests/SimpleSDKInitializationTests.swift +2 -1
  29. package/dist/template/scripts/build_ios.sh +13 -9
  30. package/dist/template/scripts/supersdk_template.py +15 -8
  31. package/dist/template/supersdk.yaml +3 -2
  32. package/dist/template/web/src/index.html +6 -2
  33. package/dist/template/web/src/js/app.js +6 -3
  34. package/dist/template/web/src/js/supersdk.js +229 -91
  35. package/dist/template/web/src/js/supersdk.provenance.json +3 -3
  36. package/package.json +1 -1
@@ -34,30 +34,21 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.defaultPublishSiteDeps = void 0;
37
- exports.isValidEnvName = isValidEnvName;
38
37
  exports.runPublishSite = runPublishSite;
39
38
  exports.registerPublishSiteCommand = registerPublishSiteCommand;
40
39
  const path = __importStar(require("node:path"));
41
40
  const consoleClient_1 = require("../api/consoleClient");
42
- const accountStore_1 = require("../store/accountStore");
43
- const credentialStore_1 = require("../store/credentialStore");
44
41
  const refresh_1 = require("../auth/refresh");
45
- const log_1 = require("../util/log");
46
- const prompt_1 = require("../util/prompt");
47
42
  const siteClient_1 = require("../publish/siteClient");
48
- const responseClassifier_1 = require("../publish/responseClassifier");
49
43
  const orgResolve_1 = require("../publish/orgResolve");
44
+ const responseClassifier_1 = require("../publish/responseClassifier");
50
45
  const siteConfig_1 = require("../publish/siteConfig");
51
46
  const siteZip_1 = require("../publish/siteZip");
52
- /**
53
- * Mirrors the backend `validate_environment_name` (service.rs): a non-empty name
54
- * of at most 10 characters, all ASCII lowercase letters or digits. Kept as a
55
- * local fail-fast so an invalid --env never reaches an irreversible create call.
56
- */
57
- const ENV_NAME_PATTERN = /^[a-z0-9]{1,10}$/;
58
- function isValidEnvName(env) {
59
- return ENV_NAME_PATTERN.test(env);
60
- }
47
+ const offlineVersion_1 = require("../publish/offlineVersion");
48
+ const credentialStore_1 = require("../store/credentialStore");
49
+ const accountStore_1 = require("../store/accountStore");
50
+ const log_1 = require("../util/log");
51
+ const prompt_1 = require("../util/prompt");
61
52
  function resolveBackend(account) {
62
53
  return (0, credentialStore_1.backendForAccount)(account.backend, {
63
54
  passphraseProvider: account.backend === 'encrypted-file'
@@ -66,30 +57,29 @@ function resolveBackend(account) {
66
57
  });
67
58
  }
68
59
  exports.defaultPublishSiteDeps = {
69
- getCurrentAccount: () => (0, accountStore_1.getCurrentAccount)(),
60
+ getCurrentAccount: accountStore_1.getCurrentAccount,
70
61
  getAccessToken: (account) => resolveBackend(account).get(account.accountKey)?.accessToken ?? null,
71
62
  refreshToken: (account) => (0, refresh_1.refreshAccessToken)(new consoleClient_1.ConsoleClient(account.apiOrigin), resolveBackend(account), account.accountKey),
72
- markNeedsLogin: (accountKey) => (0, accountStore_1.markAccountNeedsLogin)(accountKey),
63
+ markNeedsLogin: accountStore_1.markAccountNeedsLogin,
73
64
  fetchMe: (apiOrigin, accessToken) => new consoleClient_1.ConsoleClient(apiOrigin).me(accessToken),
65
+ // The concrete client is upgraded in the publish layer; this cast preserves
66
+ // the command's injectable boundary while those modules evolve independently.
74
67
  createSiteClient: (apiOrigin) => new siteClient_1.SiteClient(apiOrigin),
75
68
  readSiteConfig: siteConfig_1.readSiteConfig,
76
69
  writeSiteConfig: siteConfig_1.writeSiteConfig,
77
- buildZip: (dir) => (0, siteZip_1.buildSiteZip)(dir),
70
+ buildZip: siteZip_1.buildSiteZip,
78
71
  };
79
72
  async function withAuth(account, deps, tokenRef, call) {
80
73
  let outcome = await call(tokenRef.value);
81
74
  if (outcome.kind !== 'auth_invalid')
82
75
  return { kind: 'outcome', outcome };
83
- // 401 → refresh exactly once, then retry exactly once.
84
76
  const refreshed = await deps.refreshToken(account);
85
77
  if (refreshed.kind === 'needs_login') {
86
78
  deps.markNeedsLogin(account.accountKey);
87
79
  return { kind: 'needs_login' };
88
80
  }
89
- if (refreshed.kind === 'infra_error') {
90
- // Refresh itself failed on network/5xx — NOT a credential-invalid signal.
81
+ if (refreshed.kind === 'infra_error')
91
82
  return { kind: 'refresh_failed', message: refreshed.message };
92
- }
93
83
  tokenRef.value = refreshed.secret.accessToken;
94
84
  outcome = await call(tokenRef.value);
95
85
  if (outcome.kind === 'auth_invalid') {
@@ -98,17 +88,17 @@ async function withAuth(account, deps, tokenRef, call) {
98
88
  }
99
89
  return { kind: 'outcome', outcome };
100
90
  }
101
- function terminalMessage(t) {
102
- if (t.kind === 'needs_login')
103
- return '凭据已失效,请重新登录:supercli login';
104
- return `无法刷新凭据(网络/服务异常,本地凭据未改动):${t.message}`;
91
+ function terminalMessage(result) {
92
+ return result.kind === 'needs_login'
93
+ ? '凭据已失效,请重新登录:supercli login'
94
+ : `无法刷新凭据(网络/服务异常,本地凭据未改动):${result.message}`;
105
95
  }
106
96
  function nonSuccessMessage(outcome, context) {
107
97
  switch (outcome.kind) {
108
98
  case 'business_error':
109
99
  return (0, responseClassifier_1.describeSiteError)(outcome.code, outcome.message);
110
100
  case 'forbidden':
111
- return `${outcome.message} — 需要目标 org 的 admin 权限`;
101
+ return `${outcome.message} — 请核对 --org 或目标 org 的 admin 权限`;
112
102
  case 'rate_limited':
113
103
  return `${outcome.message} — 请求过频,请稍后重试`;
114
104
  case 'infra_error':
@@ -117,239 +107,328 @@ function nonSuccessMessage(outcome, context) {
117
107
  return `${context}失败`;
118
108
  }
119
109
  }
120
- function detailFromOutcome(outcome) {
110
+ function valueFromOutcome(outcome) {
121
111
  if (outcome.kind === 'success')
122
112
  return outcome.data;
123
113
  if (outcome.kind === 'soft_success')
124
114
  return outcome.resource;
125
115
  return undefined;
126
116
  }
127
- function toSiteConfig(detail, fallbackSlug) {
128
- const slug = detail?.slug !== undefined ? String(detail.slug) : fallbackSlug;
129
- return {
130
- id: detail?.id !== undefined && detail?.id !== null ? String(detail.id) : '',
131
- slug,
132
- name: detail?.name !== undefined && detail?.name !== null ? String(detail.name) : slug,
133
- };
117
+ function asRecord(value) {
118
+ return value !== null && typeof value === 'object' ? value : undefined;
119
+ }
120
+ function siteFrom(value) {
121
+ const record = asRecord(value);
122
+ return record ? record : undefined;
123
+ }
124
+ function isSiteForTarget(detail, spid, slug) {
125
+ return Boolean(detail &&
126
+ typeof detail.id === 'number' &&
127
+ Number.isSafeInteger(detail.id) &&
128
+ detail.id > 0 &&
129
+ detail.spid === spid &&
130
+ detail.slug === slug &&
131
+ typeof detail.name === 'string' &&
132
+ detail.name.length > 0 &&
133
+ Array.isArray(detail.environments));
134
134
  }
135
- function envNames(detail) {
136
- if (!detail?.environments)
137
- return [];
138
- return detail.environments
139
- .map((e) => (typeof e.name === 'string' ? e.name : undefined))
140
- .filter((v) => v !== undefined);
135
+ function isTerminal(value) {
136
+ return Boolean(value && typeof value === 'object' && 'kind' in value && (value.kind === 'needs_login' || value.kind === 'refresh_failed'));
141
137
  }
142
- function domainForEnv(detail, env) {
143
- const match = detail?.environments?.find((e) => e.name === env);
144
- return match && typeof match.domain === 'string' ? match.domain : undefined;
138
+ function listContainsEnvironment(value, env) {
139
+ if (!Array.isArray(value))
140
+ return false;
141
+ return value.some((item) => asRecord(item)?.name === env);
142
+ }
143
+ function environmentViews(detail) {
144
+ return Array.isArray(detail.environments) ? detail.environments.filter((item) => Boolean(asRecord(item))) : [];
145
+ }
146
+ function domainFromSite(detail, env) {
147
+ const found = environmentViews(detail).find((item) => item.env === env);
148
+ return typeof found?.domain === 'string' && found.domain.length > 0 ? found.domain : undefined;
149
+ }
150
+ function domainFromDeploy(value) {
151
+ const record = asRecord(value);
152
+ return typeof record?.domain === 'string' && record.domain.length > 0 ? record.domain : undefined;
153
+ }
154
+ function isValidSpid(value) {
155
+ return /^[a-z0-9]{8}$/.test(value);
156
+ }
157
+ function isValidSlug(value) {
158
+ return /^[a-z0-9]{1,32}$/.test(value) && value !== 'stg';
159
+ }
160
+ function isValidEnvironment(value) {
161
+ return /^[a-z0-9]{1,10}$/.test(value);
162
+ }
163
+ function trimFlag(value) {
164
+ const trimmed = value?.trim();
165
+ return trimmed ? trimmed : undefined;
166
+ }
167
+ function normalizeBinding(value) {
168
+ if (value === null || value === undefined)
169
+ return { kind: 'absent' };
170
+ const record = asRecord(value);
171
+ if (!record || typeof record.kind !== 'string')
172
+ return { kind: 'invalid' };
173
+ if (record.kind === 'absent')
174
+ return { kind: 'absent' };
175
+ if (record.kind === 'legacy-v1') {
176
+ const site = asRecord(record.site);
177
+ return typeof site?.slug === 'string' && typeof site.name === 'string'
178
+ ? { kind: 'legacy-v1', site: { slug: site.slug, name: site.name } }
179
+ : { kind: 'legacy-v1' };
180
+ }
181
+ if (record.kind !== 'valid-v2')
182
+ return { kind: 'invalid' };
183
+ const config = asRecord(record.config);
184
+ const project = asRecord(config?.project);
185
+ const site = asRecord(config?.site);
186
+ if (typeof config?.schemaVersion !== 'number' ||
187
+ config.schemaVersion !== 2 ||
188
+ typeof project?.spid !== 'string' ||
189
+ typeof project.orgId !== 'string' ||
190
+ typeof site?.slug !== 'string' ||
191
+ typeof site.name !== 'string' ||
192
+ typeof config.environment !== 'string') {
193
+ return { kind: 'invalid' };
194
+ }
195
+ return { kind: 'valid-v2', config: config };
196
+ }
197
+ function legacyMigrationMessage(dir, site) {
198
+ const quotedDir = path.resolve(dir);
199
+ const slug = site?.slug && isValidSlug(site.slug) ? site.slug : '<slug>';
200
+ const name = site?.name?.trim();
201
+ const nameFlag = name ? ` --name ${JSON.stringify(name)}` : '';
202
+ return ('检测到已退役 schema v1 super-site.yml,已保留原文件。请从 Console 获取项目身份后重新发布:' +
203
+ ` supercli publish-site ${JSON.stringify(quotedDir)} --spid <spid> --slug ${slug} --env <env> --org <org>${nameFlag}`);
204
+ }
205
+ async function oneEnvironmentRecheck(account, deps, tokenRef, client, context, spid, env) {
206
+ const recheck = await withAuth(account, deps, tokenRef, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
207
+ if (recheck.kind !== 'outcome')
208
+ return recheck;
209
+ return (recheck.outcome.kind === 'success' || recheck.outcome.kind === 'soft_success') && listContainsEnvironment(valueFromOutcome(recheck.outcome), env);
210
+ }
211
+ async function oneSiteRecheck(account, deps, tokenRef, client, context, spid, slug) {
212
+ const recheck = await withAuth(account, deps, tokenRef, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
213
+ if (recheck.kind !== 'outcome')
214
+ return recheck;
215
+ const detail = siteFrom(valueFromOutcome(recheck.outcome));
216
+ return isSiteForTarget(detail, spid, slug) ? detail : undefined;
145
217
  }
146
218
  async function runPublishSite(dir, opts, deps = exports.defaultPublishSiteDeps) {
147
- // --env is REQUIRED and has NO default; it never touches super-site.yml. Fail
148
- // before any HTTP call (and without persisting anything) when it is missing.
149
- const env = opts.env?.trim();
150
- if (!env) {
151
- return { ok: false, message: '必须通过 --env 指定站点环境(如 --env prod),该值无默认值' };
219
+ // Local parse and target conflict checks deliberately precede account lookup,
220
+ // HTTP, config writes and zip construction.
221
+ const binding = normalizeBinding(deps.readSiteConfig(dir));
222
+ if (binding.kind === 'legacy-v1')
223
+ return { ok: false, message: legacyMigrationMessage(dir, binding.site) };
224
+ if (binding.kind === 'invalid')
225
+ return { ok: false, message: 'super-site.yml 非法或不完整;已保留原文件,请修正或按迁移命令重新建立 schema v2 绑定' };
226
+ const explicit = {
227
+ spid: trimFlag(opts.spid),
228
+ slug: trimFlag(opts.slug),
229
+ env: trimFlag(opts.env),
230
+ org: trimFlag(opts.org),
231
+ };
232
+ let spid;
233
+ let slug;
234
+ let env;
235
+ let boundOrgId;
236
+ let siteName;
237
+ let mustWriteBinding = false;
238
+ if (binding.kind === 'absent') {
239
+ if (!explicit.spid || !explicit.slug || !explicit.env) {
240
+ return { ok: false, message: '首次发布必须同时提供合法的 --spid、--slug、--env;不会猜测项目、站点或环境' };
241
+ }
242
+ spid = explicit.spid;
243
+ slug = explicit.slug;
244
+ env = explicit.env;
245
+ siteName = trimFlag(opts.name) ?? slug;
246
+ mustWriteBinding = true;
152
247
  }
153
- // Validate --env LOCALLY (mirrors backend service.rs validate_environment_name:
154
- // 1-10 lowercase letters/digits) BEFORE any HTTP. A typo like "Staging" would
155
- // otherwise sail past create-site + super-site.yml write and only fail at the
156
- // create-env call with INVALID_ENV_NAME — after an irreversible side effect.
157
- if (!isValidEnvName(env)) {
158
- return {
159
- ok: false,
160
- message: `--env "${env}" 非法:需为 1-10 位小写字母或数字(如 prod、stg1),不能含大写/连字符/其他字符`,
161
- };
248
+ else {
249
+ const config = binding.config;
250
+ if ((explicit.spid && explicit.spid !== config.project.spid) ||
251
+ (explicit.slug && explicit.slug !== config.site.slug) ||
252
+ (explicit.env && explicit.env !== config.environment) ||
253
+ (explicit.org && explicit.org !== config.project.orgId)) {
254
+ return { ok: false, message: '显式发布参数与 schema v2 super-site.yml 绑定冲突;不会静默覆盖目标' };
255
+ }
256
+ spid = config.project.spid;
257
+ slug = config.site.slug;
258
+ env = config.environment;
259
+ boundOrgId = config.project.orgId;
260
+ siteName = config.site.name;
261
+ }
262
+ if (!isValidSpid(spid))
263
+ return { ok: false, message: '--spid 非法:必须为 8 位小写字母或数字' };
264
+ if (!isValidSlug(slug))
265
+ return { ok: false, message: '--slug 非法:必须为 1-32 位小写字母或数字,且不能为 stg' };
266
+ if (!isValidEnvironment(env))
267
+ return { ok: false, message: '--env 非法:必须为 1-10 位小写字母或数字' };
268
+ siteName = siteName.trim();
269
+ const siteNameLength = Array.from(siteName).length;
270
+ if (siteNameLength < 1 || siteNameLength > 50)
271
+ return { ok: false, message: '--name 非法:必须为 1-50 个字符' };
272
+ const parsedVersion = (0, offlineVersion_1.parseOfflineVersion)(trimFlag(opts.version));
273
+ if (!parsedVersion) {
274
+ return { ok: false, message: '--version 必填,且必须是最多 64 bytes 的 x.y.z(major ≤ 2147483647,minor/patch ≤ 99;前导零按数值比较)' };
162
275
  }
276
+ const version = parsedVersion.raw;
163
277
  const account = deps.getCurrentAccount();
164
- if (!account) {
278
+ if (!account)
165
279
  return { ok: false, message: '当前没有登录账号,请先运行:supercli login' };
166
- }
167
280
  const accessToken = deps.getAccessToken(account);
168
281
  if (!accessToken) {
169
282
  deps.markNeedsLogin(account.accountKey);
170
283
  return { ok: false, message: '本地未找到有效凭据,请重新登录:supercli login' };
171
284
  }
172
285
  const tokenRef = { value: accessToken };
173
- const apiOrigin = account.apiOrigin;
174
- const siteClient = deps.createSiteClient(apiOrigin);
175
- // ---- determine slug + mode LOCALLY, before any HTTP (TC-S27) ----
176
- // super-site.yml read + default-slug derivation are pure/local, so an invalid
177
- // default slug (uppercase/underscore/reserved dir name) fails before /me.
178
- const bound = deps.readSiteConfig(dir);
179
- let mode;
180
- if (bound) {
181
- mode = { kind: 'bound', slug: bound.slug };
182
- }
183
- else if (opts.slug && opts.slug.trim().length > 0) {
184
- mode = { kind: 'explicit', slug: opts.slug.trim() };
286
+ let orgId;
287
+ if (explicit.org) {
288
+ const resolution = (0, orgResolve_1.resolveOrgId)([], explicit.org);
289
+ if (resolution.kind !== 'resolved')
290
+ return { ok: false, message: '--org 必须为正整数' };
291
+ orgId = resolution.orgId;
185
292
  }
186
293
  else {
187
- const derived = (0, siteConfig_1.deriveDefaultSlug)(path.basename(path.resolve(dir)));
188
- if (!derived) {
189
- return {
190
- ok: false,
191
- message: '无法从目录名派生出合法 slug(需 1-40 位小写字母/数字/内部连字符、非保留字),请显式传入 --slug',
192
- };
193
- }
194
- mode = { kind: 'create', slug: derived, name: opts.name && opts.name.trim().length > 0 ? opts.name.trim() : derived };
294
+ const me = await withAuth(account, deps, tokenRef, (token) => deps.fetchMe(account.apiOrigin, token));
295
+ if (me.kind !== 'outcome')
296
+ return { ok: false, message: terminalMessage(me) };
297
+ if (me.outcome.kind !== 'success')
298
+ return { ok: false, message: `无法获取当前用户组织:${'message' in me.outcome ? me.outcome.message : me.outcome.kind}` };
299
+ const resolution = (0, orgResolve_1.resolveOrgId)(me.outcome.data.orgs ?? undefined);
300
+ if (resolution.kind === 'none')
301
+ return { ok: false, message: '当前账号未归属任何 org,无法发布' };
302
+ if (resolution.kind === 'ambiguous')
303
+ return { ok: false, message: `当前账号归属多个 org(${resolution.orgIds.join(', ')}),请通过 --org <id> 指定` };
304
+ if (resolution.kind !== 'resolved')
305
+ return { ok: false, message: '无法解析当前 org' };
306
+ orgId = resolution.orgId;
195
307
  }
196
- // ---- resolve org (X-Org-Id) ----
197
- let orgId;
198
- if (opts.org && opts.org.trim().length > 0) {
199
- orgId = opts.org.trim();
308
+ if (boundOrgId && boundOrgId !== orgId) {
309
+ return { ok: false, message: '当前解析的 org 与 schema v2 绑定冲突;不会向其他组织发布' };
200
310
  }
201
- else {
202
- const meAttempt = await withAuth(account, deps, tokenRef, (token) => deps.fetchMe(apiOrigin, token));
203
- if (meAttempt.kind !== 'outcome') {
204
- return { ok: false, message: terminalMessage(meAttempt) };
311
+ const client = deps.createSiteClient(account.apiOrigin);
312
+ const context = { accessToken: tokenRef.value, orgId };
313
+ // env-before-site: unavailable environments never leave a new site behind.
314
+ const listed = await withAuth(account, deps, tokenRef, (token) => client.listEnvironments({ ...context, accessToken: token }, spid));
315
+ if (listed.kind !== 'outcome')
316
+ return { ok: false, message: terminalMessage(listed) };
317
+ let environmentAvailable = (listed.outcome.kind === 'success' || listed.outcome.kind === 'soft_success') && listContainsEnvironment(valueFromOutcome(listed.outcome), env);
318
+ if (!environmentAvailable) {
319
+ if (listed.outcome.kind !== 'success' && listed.outcome.kind !== 'soft_success') {
320
+ return { ok: false, message: nonSuccessMessage(listed.outcome, '查询项目环境') };
205
321
  }
206
- const me = meAttempt.outcome;
207
- if (me.kind !== 'success') {
208
- return { ok: false, message: `无法获取当前用户信息:${'message' in me ? me.message : me.kind}` };
322
+ if (env === 'prod')
323
+ return { ok: false, message: '项目 prod 环境不存在,请前往控制台检查项目状态' };
324
+ if (!opts.createEnvironment)
325
+ return { ok: false, message: `项目环境 "${env}" 不存在;如确认要创建共享环境,请显式传入 --create-environment` };
326
+ const created = await withAuth(account, deps, tokenRef, (token) => client.createEnvironment({ ...context, accessToken: token }, spid, { name: env }));
327
+ if (created.kind !== 'outcome')
328
+ return { ok: false, message: terminalMessage(created) };
329
+ if (created.outcome.kind === 'success' && asRecord(created.outcome.data)?.name === env) {
330
+ environmentAvailable = true;
209
331
  }
210
- // opts.org is already known empty in this branch (the non-empty case is
211
- // handled above), so it is intentionally NOT forwarded here.
212
- const resolution = (0, orgResolve_1.resolveOrgId)(me.data.orgs ?? undefined);
213
- if (resolution.kind === 'none') {
214
- return { ok: false, message: '当前账号未归属任何 org,无法发布' };
332
+ else if (created.outcome.kind === 'success' ||
333
+ created.outcome.kind === 'soft_success' ||
334
+ created.outcome.kind === 'infra_error' ||
335
+ (created.outcome.kind === 'business_error' && created.outcome.code === 'ENV_NAME_DUPLICATE')) {
336
+ const rechecked = await oneEnvironmentRecheck(account, deps, tokenRef, client, context, spid, env);
337
+ if (typeof rechecked !== 'boolean')
338
+ return { ok: false, message: terminalMessage(rechecked) };
339
+ environmentAvailable = rechecked;
215
340
  }
216
- if (resolution.kind === 'ambiguous') {
217
- return {
218
- ok: false,
219
- message: `当前账号归属多个 org(${resolution.orgIds.join(', ')}),请通过 --org <id> 指定`,
220
- };
341
+ else {
342
+ return { ok: false, message: nonSuccessMessage(created.outcome, '创建项目环境') };
221
343
  }
222
- orgId = resolution.orgId;
344
+ if (!environmentAvailable)
345
+ return { ok: false, message: `无法确认项目环境 "${env}" 已创建;不会重放写请求,请稍后在控制台核对` };
223
346
  }
224
- // ---- resolve site detail per mode ----
225
- const slug = mode.slug;
226
347
  let detail;
227
- let wroteConfig = false;
228
- if (mode.kind === 'bound') {
229
- // AC-S1: bound yml → use its slug, GET detail (single detail fetch), publish.
230
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.getSite({ accessToken: t, orgId }, slug));
231
- if (attempt.kind !== 'outcome')
232
- return { ok: false, message: terminalMessage(attempt) };
233
- const outcome = attempt.outcome;
234
- if (outcome.kind !== 'success' && outcome.kind !== 'soft_success') {
235
- if (outcome.kind === 'business_error' && outcome.code === 'NOT_FOUND') {
236
- return { ok: false, message: `已绑定的 slug "${slug}" 不存在或不属当前 org,请核对 super-site.yml/--org` };
237
- }
238
- return { ok: false, message: nonSuccessMessage(outcome, '查询站点详情') };
239
- }
240
- detail = detailFromOutcome(outcome);
348
+ const lookedUp = await withAuth(account, deps, tokenRef, (token) => client.getSite({ ...context, accessToken: token }, spid, slug));
349
+ if (lookedUp.kind !== 'outcome')
350
+ return { ok: false, message: terminalMessage(lookedUp) };
351
+ const existing = siteFrom(valueFromOutcome(lookedUp.outcome));
352
+ if (isSiteForTarget(existing, spid, slug)) {
353
+ detail = existing;
241
354
  }
242
- else if (mode.kind === 'explicit') {
243
- // AC-S9: no yml but explicit --slug → GET; NOT_FOUND is a hard error (backend
244
- // org-filters, so "not found" and "owned by another org" are indistinguishable
245
- // — never auto-create here).
246
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.getSite({ accessToken: t, orgId }, slug));
247
- if (attempt.kind !== 'outcome')
248
- return { ok: false, message: terminalMessage(attempt) };
249
- const outcome = attempt.outcome;
250
- if (outcome.kind === 'business_error' && outcome.code === 'NOT_FOUND') {
251
- return { ok: false, message: `slug "${slug}" 不存在或不属当前 org,请核对 --slug/--org` };
355
+ else if (lookedUp.outcome.kind === 'business_error' && lookedUp.outcome.code === 'NOT_FOUND') {
356
+ const created = await withAuth(account, deps, tokenRef, (token) => client.createSite({ ...context, accessToken: token }, spid, { name: siteName, slug }));
357
+ if (created.kind !== 'outcome')
358
+ return { ok: false, message: terminalMessage(created) };
359
+ const createdDetail = siteFrom(valueFromOutcome(created.outcome));
360
+ if (created.outcome.kind === 'success' && isSiteForTarget(createdDetail, spid, slug)) {
361
+ detail = createdDetail;
252
362
  }
253
- if (outcome.kind !== 'success' && outcome.kind !== 'soft_success') {
254
- return { ok: false, message: nonSuccessMessage(outcome, '查询站点详情') };
363
+ else if (created.outcome.kind === 'soft_success' ||
364
+ created.outcome.kind === 'infra_error' ||
365
+ (created.outcome.kind === 'business_error' && created.outcome.code === 'SITE_SLUG_DUPLICATE') ||
366
+ (created.outcome.kind === 'success' && !isSiteForTarget(createdDetail, spid, slug))) {
367
+ const rechecked = await oneSiteRecheck(account, deps, tokenRef, client, context, spid, slug);
368
+ if (isTerminal(rechecked))
369
+ return { ok: false, message: terminalMessage(rechecked) };
370
+ detail = rechecked;
371
+ }
372
+ else {
373
+ return { ok: false, message: nonSuccessMessage(created.outcome, '创建项目站点') };
255
374
  }
256
- detail = detailFromOutcome(outcome);
257
- deps.writeSiteConfig(dir, toSiteConfig(detail, slug));
258
- wroteConfig = true;
375
+ if (!detail)
376
+ return { ok: false, message: '无法确认项目站点已创建;不会重放写请求、写绑定或发布,请稍后核对' };
259
377
  }
260
378
  else {
261
- // AC-S2: no yml, no --slug → the ONLY auto-create entry point.
262
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.createSite({ accessToken: t, orgId }, { name: mode.name, slug }));
263
- if (attempt.kind !== 'outcome')
264
- return { ok: false, message: terminalMessage(attempt) };
265
- const outcome = attempt.outcome;
266
- if (outcome.kind === 'soft_success') {
267
- log_1.log.warn('建站已提交,边缘指针同步进行中(软成功)', { slug, org: orgId });
268
- }
269
- else if (outcome.kind !== 'success') {
270
- return { ok: false, message: nonSuccessMessage(outcome, '建站') };
271
- }
272
- detail = detailFromOutcome(outcome);
273
- deps.writeSiteConfig(dir, toSiteConfig(detail, slug));
274
- wroteConfig = true;
379
+ return { ok: false, message: nonSuccessMessage(lookedUp.outcome, '查询项目站点') };
275
380
  }
276
- // ---- ensure target env exists (reuse the detail already fetched) ----
277
- let envJustCreated = false;
278
- if (!envNames(detail).includes(env)) {
279
- if (env === 'prod') {
280
- return { ok: false, message: `站点 "${slug}" 的 prod 环境不存在,请前往控制台检查` };
281
- }
282
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.createEnv({ accessToken: t, orgId }, slug, { name: env }));
283
- if (attempt.kind !== 'outcome')
284
- return { ok: false, message: terminalMessage(attempt) };
285
- const outcome = attempt.outcome;
286
- if (outcome.kind === 'soft_success') {
287
- log_1.log.warn('环境创建已提交,边缘指针同步进行中(软成功)', { slug, env, org: orgId });
288
- }
289
- else if (outcome.kind !== 'success') {
290
- return { ok: false, message: nonSuccessMessage(outcome, '创建环境') };
291
- }
292
- envJustCreated = true;
381
+ if (mustWriteBinding) {
382
+ deps.writeSiteConfig(dir, {
383
+ schemaVersion: 2,
384
+ project: { spid, orgId },
385
+ site: { slug, name: detail.name },
386
+ environment: env,
387
+ });
293
388
  }
294
- // ---- package the directory (local prechecks; no upload on failure) ----
295
389
  let zip;
296
390
  try {
297
391
  zip = await deps.buildZip(dir);
298
392
  }
299
- catch (err) {
300
- if (err instanceof siteZip_1.ZipBuildError) {
301
- return { ok: false, message: `打包失败:${err.message}` };
302
- }
303
- log_1.log.error('publishSite.buildZip error: ' + err.message, { slug, env });
304
- return { ok: false, message: `打包失败:${err.message}` };
393
+ catch (error) {
394
+ const message = error instanceof siteZip_1.ZipBuildError ? error.message : error.message;
395
+ return { ok: false, message: `打包失败:${message}` };
305
396
  }
306
- // ---- deploy (multipart) ----
307
- const deployAttempt = await withAuth(account, deps, tokenRef, (t) => siteClient.deploy({ accessToken: t, orgId }, slug, env, {
397
+ const deployed = await withAuth(account, deps, tokenRef, (token) => client.deploy({ ...context, accessToken: token }, spid, slug, env, {
308
398
  zip: zip.buffer,
309
- version: opts.version,
399
+ version,
310
400
  description: opts.description,
401
+ expectedSiteId: detail.id,
311
402
  }));
312
- if (deployAttempt.kind !== 'outcome')
313
- return { ok: false, message: terminalMessage(deployAttempt) };
314
- const deployOutcome = deployAttempt.outcome;
315
- let pending = false;
316
- if (deployOutcome.kind === 'soft_success') {
317
- pending = true;
318
- log_1.log.warn('发布已提交,边缘同步进行中(软成功)', { slug, env, org: orgId });
319
- }
320
- else if (deployOutcome.kind !== 'success') {
321
- return { ok: false, message: nonSuccessMessage(deployOutcome, '发布') };
322
- }
323
- // ---- resolve access domain (re-GET only if a new env was just created) ----
324
- if (envJustCreated) {
325
- const attempt = await withAuth(account, deps, tokenRef, (t) => siteClient.getSite({ accessToken: t, orgId }, slug));
326
- if (attempt.kind === 'outcome' && (attempt.outcome.kind === 'success' || attempt.outcome.kind === 'soft_success')) {
327
- detail = detailFromOutcome(attempt.outcome) ?? detail;
328
- }
329
- else {
330
- log_1.log.warn('无法刷新站点详情以获取新环境域名', { slug, env });
331
- }
403
+ if (deployed.kind !== 'outcome')
404
+ return { ok: false, message: terminalMessage(deployed) };
405
+ if (deployed.outcome.kind !== 'success' && deployed.outcome.kind !== 'soft_success') {
406
+ return { ok: false, message: nonSuccessMessage(deployed.outcome, '发布') };
332
407
  }
333
- const domain = domainForEnv(detail, env);
334
- const pendingNote = pending ? '(边缘同步进行中,稍后生效)' : '';
335
- const configNote = wroteConfig ? ',已写入 super-site.yml' : '';
336
- const message = domain
337
- ? `发布成功${configNote},可访问域名:https://${domain.replace(/^https?:\/\//, '')}${pendingNote}`
338
- : `发布成功${configNote}${pendingNote}(未获取到环境域名)`;
339
- return { ok: true, message };
408
+ const pending = deployed.outcome.kind === 'soft_success';
409
+ // 域名的 zone 是平台部署配置(生产 supersdk.site / staging supersdk.top),CLI 不掌握也不该
410
+ // 猜——只用服务端返回的 domain;两处都没有就让用户去 Console 看,绝不编造一个不存在的域名。
411
+ const domain = domainFromDeploy(valueFromOutcome(deployed.outcome)) ?? domainFromSite(detail, env);
412
+ const pendingNote = pending ? '(已受理、同步中,稍后生效)' : '';
413
+ const domainNote = domain
414
+ ? `,可访问域名:https://${domain.replace(/^https?:\/\//, '')}`
415
+ : ',可访问域名请在 Console 的 Hosting 页查看';
416
+ return { ok: true, message: `发布成功${mustWriteBinding ? ',已写入 super-site.yml' : ''}${domainNote}${pendingNote}` };
340
417
  }
341
418
  function registerPublishSiteCommand(program) {
342
419
  program
343
420
  .command('publish-site <dir>')
344
- .description('Package a directory and publish it as a SuperSite deploy.')
345
- .option('--env <env>', 'target site environment (e.g. prod); REQUIRED, no default')
346
- .option('--slug <slug>', 'site slug to bind/publish to')
347
- .option('--name <name>', 'display name used when creating a new site')
348
- .option('--org <id>', 'organization id (required when the account has multiple orgs)')
349
- .option('--version <version>', 'deploy version label')
421
+ .description('Publish a project-scoped SuperSite deploy.')
422
+ .option('--spid <spid>', 'project spid (required for a first publish)')
423
+ .option('--slug <slug>', 'site slug (required for a first publish)')
424
+ .option('--env <env>', 'project environment (required for a first publish)')
425
+ .option('--org <id>', 'organization id; required when the account has multiple orgs')
426
+ .option('--name <name>', 'display name used only when creating a new site')
427
+ .option('--create-environment', 'explicitly authorize creating a missing non-prod project environment')
428
+ .requiredOption('--version <version>', 'required offline package version: x.y.z (major <= 2147483647; minor/patch <= 99)')
350
429
  .option('--description <description>', 'deploy description')
351
- .action(async (dir, opts) => {
352
- const result = await runPublishSite(dir, opts);
430
+ .action(async (dir, options) => {
431
+ const result = await runPublishSite(dir, options);
353
432
  if (!result.ok) {
354
433
  log_1.log.error(result.message ?? 'publish-site failed');
355
434
  process.exitCode = 1;