@supersdk/supercli 0.3.2-staging.44 → 0.3.2

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 (93) hide show
  1. package/dist/cli.js +11 -22
  2. package/dist/cli.js.map +1 -1
  3. package/dist/commands/add.js +31 -79
  4. package/dist/commands/add.js.map +1 -1
  5. package/dist/commands/analytics.js +9 -15
  6. package/dist/commands/analytics.js.map +1 -1
  7. package/dist/commands/db.js +19 -24
  8. package/dist/commands/db.js.map +1 -1
  9. package/dist/commands/deploy.js +751 -434
  10. package/dist/commands/deploy.js.map +1 -1
  11. package/dist/commands/env.js +8 -8
  12. package/dist/commands/env.js.map +1 -1
  13. package/dist/commands/image.js +20 -31
  14. package/dist/commands/image.js.map +1 -1
  15. package/dist/commands/init.js +37 -68
  16. package/dist/commands/init.js.map +1 -1
  17. package/dist/commands/logs.js +7 -16
  18. package/dist/commands/logs.js.map +1 -1
  19. package/dist/commands/publishSite.js +943 -28
  20. package/dist/commands/publishSite.js.map +1 -1
  21. package/dist/commands/register.js +30 -51
  22. package/dist/commands/register.js.map +1 -1
  23. package/dist/commands/settings.js +6 -10
  24. package/dist/commands/settings.js.map +1 -1
  25. package/dist/config/appConfig.js +36 -40
  26. package/dist/config/appConfig.js.map +1 -1
  27. package/dist/docker/dockerCli.js +1 -63
  28. package/dist/docker/dockerCli.js.map +1 -1
  29. package/dist/output/envelope.js +1 -5
  30. package/dist/output/envelope.js.map +1 -1
  31. package/dist/output/resultPrinter.js +0 -3
  32. package/dist/output/resultPrinter.js.map +1 -1
  33. package/dist/publish/responseClassifier.js +4 -4
  34. package/dist/publish/responseClassifier.js.map +1 -1
  35. package/dist/publish/runClient.js +11 -11
  36. package/dist/publish/runClient.js.map +1 -1
  37. package/dist/publish/siteConfig.js +649 -0
  38. package/dist/publish/siteConfig.js.map +1 -0
  39. package/dist/publish/siteZip.js +5 -4
  40. package/dist/publish/siteZip.js.map +1 -1
  41. package/dist/template/README.md +227 -64
  42. package/dist/template/android/app/src/main/java/com/supersdk/simple/EnvironmentStore.java +1 -1
  43. package/dist/template/android/app/src/main/java/com/supersdk/simple/SimpleApplication.java +2 -2
  44. package/dist/template/android/gradle/supersdk-config-reader.gradle +5 -6
  45. package/dist/template/android/supersdk-default.config.json +2 -3
  46. package/dist/template/ios/Sources/App/AppDelegate.swift +1 -1
  47. package/dist/template/ios/Sources/App/SimpleSDKBootstrap.swift +1 -1
  48. package/dist/template/scripts/build_android.sh +10 -26
  49. package/dist/template/scripts/build_ios.sh +9 -41
  50. package/dist/template/scripts/build_site.sh +26 -40
  51. package/dist/template/scripts/lib/workspace.sh +4 -4
  52. package/dist/template/scripts/serve_web.py +4 -2
  53. package/dist/template/scripts/super_build_orchestrator.py +355 -278
  54. package/dist/template/scripts/supersdk_template.py +181 -414
  55. package/dist/template/scripts/web_package.py +8 -9
  56. package/dist/template/super_build.sh +113 -39
  57. package/dist/template/{super.json → supersdk.json} +1 -20
  58. package/dist/template/template_manifest.json +4 -5
  59. package/dist/workspace/config.js +119 -81
  60. package/dist/workspace/config.js.map +1 -1
  61. package/dist/workspace/identity.js +14 -15
  62. package/dist/workspace/identity.js.map +1 -1
  63. package/dist/workspace/inspect.js +0 -1
  64. package/dist/workspace/inspect.js.map +1 -1
  65. package/dist/workspace/projectIdentity.js +96 -53
  66. package/dist/workspace/projectIdentity.js.map +1 -1
  67. package/dist/workspace/template.js +8 -5
  68. package/dist/workspace/template.js.map +1 -1
  69. package/package.json +2 -2
  70. package/dist/build/artifactIntegrity.js +0 -119
  71. package/dist/build/artifactIntegrity.js.map +0 -1
  72. package/dist/commands/build.js +0 -231
  73. package/dist/commands/build.js.map +0 -1
  74. package/dist/commands/config.js +0 -170
  75. package/dist/commands/config.js.map +0 -1
  76. package/dist/config/superConfig.js +0 -429
  77. package/dist/config/superConfig.js.map +0 -1
  78. package/dist/deploy/adapterTypes.js +0 -3
  79. package/dist/deploy/adapterTypes.js.map +0 -1
  80. package/dist/deploy/manifest.js +0 -381
  81. package/dist/deploy/manifest.js.map +0 -1
  82. package/dist/deploy/preflight.js +0 -202
  83. package/dist/deploy/preflight.js.map +0 -1
  84. package/dist/deploy/resultWriter.js +0 -178
  85. package/dist/deploy/resultWriter.js.map +0 -1
  86. package/dist/deploy/runAdapter.js +0 -299
  87. package/dist/deploy/runAdapter.js.map +0 -1
  88. package/dist/deploy/siteAdapter.js +0 -182
  89. package/dist/deploy/siteAdapter.js.map +0 -1
  90. package/dist/template/scripts/build_service.sh +0 -89
  91. package/dist/template/service/Dockerfile +0 -2
  92. package/dist/workspace/projectContext.js +0 -93
  93. package/dist/workspace/projectContext.js.map +0 -1
@@ -7,7 +7,6 @@ import re
7
7
  import shlex
8
8
  import sys
9
9
  import uuid
10
- import hashlib
11
10
  from pathlib import Path
12
11
  from urllib.parse import urlparse
13
12
 
@@ -20,18 +19,17 @@ from web_host_validator import HostValidationError, normalize_host
20
19
  # `supercli add`,CLI 写出新 schema、仓库自带的老引擎报「schemaVersion 必须是 N」——
21
20
  # 那条错指向用户自己的配置文件,完全指不到真正的原因(工程模板过期了)。
22
21
  # 版本号写进 managed config 纯为溯源;`engine-check` 子命令据此给出可执行的升级提示。
23
- ENGINE_VERSION = "4.0.0"
22
+ ENGINE_VERSION = "3.0.0"
24
23
 
25
24
  MANAGED_BY = "supersdk-template"
26
25
  # 每个项目目录下的 `.supersdk/managed/config.json` 有自己的 snake_case `schema_version`,
27
26
  # 与根配置文件的 `schemaVersion` 是**两份**契约,各自独立演进。
28
- MANAGED_CONFIG_SCHEMA_VERSION = 4
27
+ MANAGED_CONFIG_SCHEMA_VERSION = 3
29
28
  MANAGED_CONFIG_KEYS = (
30
29
  "managed_by",
31
30
  "schema_version",
32
31
  "engine_version",
33
32
  "spid",
34
- "project_id",
35
33
  "name",
36
34
  "platform",
37
35
  "dir",
@@ -40,48 +38,38 @@ MANAGED_CONFIG_KEYS = (
40
38
  "platform_config",
41
39
  )
42
40
 
43
- # 工作空间根配置:一个 workspace = 一个 spid,`super.json` 所在目录即工作空间根。
44
- CONFIG_FILENAME = "super.json"
45
- CONFIG_SCHEMA_VERSION = 4
46
- LEGACY_CONFIG_FILENAMES = ("supersdk.json", "supersdk.yaml", "supersdk.yml", "super-site.yml")
41
+ # 工作空间根配置:一个 workspace = 一个 spid,`supersdk.json` 所在目录即工作空间根。
42
+ CONFIG_FILENAME = "supersdk.json"
43
+ CONFIG_SCHEMA_VERSION = 3
44
+ LEGACY_CONFIG_FILENAMES = ("supersdk.yaml", "supersdk.yml", "super-site.yml")
47
45
 
48
46
  # 首批项目类型。`type` 是普通字符串字段,加新类型只要加一个 build_<type>.sh 与一段投影,
49
47
  # 不需要动 schema 版本;但**未知类型一律 fail-closed**,否则 plan 会给出一个根本不存在的
50
48
  # helper 路径,直到 build 阶段才炸。
51
- PROJECT_TYPES = ("android", "ios", "site", "service")
49
+ PROJECT_TYPES = ("android", "ios", "site")
52
50
  TYPE_ORDER = {name: index for index, name in enumerate(PROJECT_TYPES)}
53
51
 
54
52
  # 每个项目条目允许的键。身份键(package / bundleId)只出现在项目里:
55
53
  # 永不继承、永不推导,推导出来的身份等于把第三方 App 发到别人的反向域名下。
56
- COMMON_PROJECT_KEYS = {"projectId", "type", "dir", "name", "version", "sdk"}
54
+ COMMON_PROJECT_KEYS = {"type", "dir", "name", "version", "sdk"}
57
55
  TYPE_PROJECT_KEYS = {
58
56
  "android": {"package"},
59
57
  "ios": {"bundleId", "spmMode"},
60
- "site": {"deploy", "offline", "build"},
61
- "service": {"deploy", "build"},
58
+ "site": {"deploy", "offline"},
62
59
  }
63
60
  # 打错的身份键必须给定向诊断,而不是泛泛的 "unknown key"。
64
61
  PROJECT_KEY_ALIASES = {
65
62
  "ios": {"bundle_id": "bundleId", "bundleID": "bundleId", "bundle-id": "bundleId"},
66
63
  "android": {"applicationId": "package", "package_name": "package", "packageName": "package"},
67
64
  "site": {"host": "offline.host", "sites": "deploy"},
68
- "service": {},
69
65
  }
70
66
  SITE_OFFLINE_KEYS = {"host"}
71
- SITE_BUILD_KEYS = {"outputDir"}
72
- SERVICE_BUILD_KEYS = {"context", "dockerfile", "platform", "argsFromEnv"}
73
- DEPLOY_COMMON_KEYS = {"envTarget", "slug", "env", "name"}
74
- SERVICE_DEPLOY_KEYS = {
75
- "port", "cpuMilli", "memoryMiB", "maxScale", "databaseConnection", "runtimeEnvFromEnv", "secretsFromEnv"
76
- }
77
- ENV_REFERENCE_KEYS = {"name", "sourceEnv"}
78
67
  VERSION_KEYS = {"name", "code"}
79
68
  SDK_KEYS = {"androidVersion", "iosPackageUrl", "iosVersion"}
80
69
  SDK_PROJECTION = {
81
70
  "android": {"mock": ("androidVersion",), "real": ("androidVersion",)},
82
71
  "ios": {"mock": (), "real": ("iosPackageUrl", "iosVersion")},
83
72
  "site": {"mock": (), "real": ()},
84
- "service": {"mock": (), "real": ()},
85
73
  }
86
74
 
87
75
  ANDROID_NAMESPACE = "com.supersdk.simple"
@@ -93,7 +81,6 @@ JAVA_PACKAGE_PATTERN = r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+"
93
81
 
94
82
  DEFAULT_VERSION_NAME = "1.0.0"
95
83
  DEFAULT_VERSION_CODE = 1
96
- MISSING = object()
97
84
 
98
85
  # 退役根键。每一条都给**定向**诊断,而不是被「未知键原样保留」的规则带过去。
99
86
  # v1 关键字先于 schemaVersion 检查(它们的诊断与 schemaVersion 无关);
@@ -107,7 +94,7 @@ RETIRED_ROOT_KEYS = {
107
94
  RETIRED_V2_ROOT_KEYS = {
108
95
  "environment": (
109
96
  "retired key; environment is a runtime init parameter, not build configuration. "
110
- "Delete it from super.json: SuperSDK.init(context, spid, provider) defaults to prod, "
97
+ "Delete it from supersdk.json: SuperSDK.init(context, spid, provider) defaults to prod, "
111
98
  "and the bundled demo apps switch environment at runtime"
112
99
  ),
113
100
  "android": 'retired schema v2 key; it is now an entry in projects[]: {"type": "android", "dir": "android", ...}',
@@ -118,7 +105,7 @@ RETIRED_V2_ROOT_KEYS = {
118
105
 
119
106
  # 每个必填字段都在:少一个字段的迁移提示,对照抄的人就是死路。
120
107
  MIGRATION_TEMPLATE = """{
121
- "schemaVersion": 4,
108
+ "schemaVersion": 3,
122
109
  "spid": "demo0001",
123
110
  "name": "SuperSDK Simple",
124
111
  "version": {
@@ -130,14 +117,12 @@ MIGRATION_TEMPLATE = """{
130
117
  },
131
118
  "projects": [
132
119
  {
133
- "projectId": "android",
134
120
  "type": "android",
135
121
  "dir": "android",
136
122
  "name": "SuperSDK Simple",
137
123
  "package": "com.example.app"
138
124
  },
139
125
  {
140
- "projectId": "ios",
141
126
  "type": "ios",
142
127
  "dir": "ios",
143
128
  "name": "SuperSDK Simple",
@@ -145,7 +130,6 @@ MIGRATION_TEMPLATE = """{
145
130
  "spmMode": "mock"
146
131
  },
147
132
  {
148
- "projectId": "web",
149
133
  "type": "site",
150
134
  "dir": "web",
151
135
  "name": "SuperSDK Simple Web",
@@ -168,25 +152,13 @@ MIGRATION_TEMPLATE = """{
168
152
  # 项目条目键序的语义:先身份(type/dir/name),再平台身份字段,再站点侧的 deploy/offline,
169
153
  # 最后是可覆盖的默认值(version/sdk)。
170
154
  ROOT_KEY_ORDER = ("schemaVersion", "spid", "orgId", "name", "version", "sdk", "projects")
171
- PROJECT_KEY_ORDER = (
172
- "projectId", "type", "dir", "name", "package", "bundleId", "spmMode", "build", "deploy", "offline", "version", "sdk"
173
- )
155
+ PROJECT_KEY_ORDER = ("type", "dir", "name", "package", "bundleId", "spmMode", "deploy", "offline", "version", "sdk")
174
156
  NESTED_KEY_ORDER = {
175
157
  "version": ("name", "code"),
176
158
  "sdk": ("androidVersion", "iosPackageUrl", "iosVersion"),
177
159
  "offline": ("host",),
178
- "build": ("outputDir", "context", "dockerfile", "platform", "argsFromEnv"),
179
160
  }
180
- DEPLOY_KEY_ORDER = (
181
- "envTarget", "slug", "name", "env", "port", "cpuMilli", "memoryMiB", "maxScale", "databaseConnection",
182
- "runtimeEnvFromEnv", "secretsFromEnv",
183
- )
184
- PROJECT_ID_PATTERN = r"[a-z][a-z0-9-]{0,63}"
185
- ENV_TARGET_PATTERN = r"[a-z][a-z0-9-]{0,31}"
186
- ENV_NAME_PATTERN = r"[A-Za-z_][A-Za-z0-9_]*"
187
- DEPLOY_SLUG_PATTERN = r"[a-z0-9]{1,32}"
188
- DEPLOY_ENV_PATTERN = r"[a-z0-9]{1,10}"
189
- RESERVED_DEPLOY_SLUGS = {"stg", "site"}
161
+ DEPLOY_KEY_ORDER = ("slug", "name", "env", "dir")
190
162
 
191
163
 
192
164
  class ConfigError(Exception):
@@ -200,11 +172,10 @@ def helper_path():
200
172
  return Path(__file__).resolve()
201
173
 
202
174
 
203
- def migrate_command(source=None, target=None):
204
- """Return the real, copy-pasteable v3 -> v4 migration command."""
205
- source_arg = shlex.quote(str(source)) if source is not None else "supersdk.json"
206
- target_arg = shlex.quote(str(target)) if target is not None else "super.json"
207
- return f"python3 {shlex.quote(str(helper_path()))} migrate --from {source_arg} --to {target_arg}"
175
+ def migrate_command(config_path=None):
176
+ """可照抄执行的迁移命令。路径未知时也给出一条完整命令,而不是半句话。"""
177
+ target = shlex.quote(str(config_path)) if config_path is not None else "path/to/supersdk.json"
178
+ return f"python3 {shlex.quote(str(helper_path()))} migrate --config {target}"
208
179
 
209
180
 
210
181
  def config_file_state(target_path):
@@ -306,6 +277,8 @@ def load_config(path):
306
277
 
307
278
 
308
279
  def require_mapping(value, field):
280
+ if value is None:
281
+ return {}
309
282
  if not isinstance(value, dict):
310
283
  raise ConfigError(field, "must be a JSON object")
311
284
  return value
@@ -370,8 +343,6 @@ def validate_ios_version(value, field="sdk.iosVersion"):
370
343
 
371
344
  def validate_sdk_namespace(raw_sdk, field):
372
345
  """只做**形状**校验(键名/标量),值的合法性留给按项目的 scope。"""
373
- if raw_sdk is MISSING:
374
- raw_sdk = {}
375
346
  sdk = require_mapping(raw_sdk, field)
376
347
  for key, value in sdk.items():
377
348
  if not isinstance(key, str):
@@ -384,32 +355,27 @@ def validate_sdk_namespace(raw_sdk, field):
384
355
 
385
356
 
386
357
  def validate_version_namespace(raw_version, field):
387
- if raw_version is MISSING:
388
- raw_version = {}
389
358
  version = require_mapping(raw_version, field)
390
359
  for key in version:
391
360
  if key not in VERSION_KEYS:
392
361
  raise ConfigError(f"{field}.{key}", "unknown key")
393
- if "name" in version:
394
- require_string(version["name"], f"{field}.name")
395
- if "code" in version:
396
- validate_version_code(version["code"], f"{field}.code")
397
362
  return version
398
363
 
399
364
 
400
365
  def resolve_version(version, field):
401
366
  """把一份 version 对象归一成 {name, code}。整值替换后的兜底默认值在这里生效。"""
402
367
  version_name = version.get("name", DEFAULT_VERSION_NAME)
368
+ if isinstance(version_name, (int, float)) and not isinstance(version_name, bool):
369
+ version_name = str(version_name)
403
370
  version_name = require_string(version_name, f"{field}.name")
404
371
  version_code = validate_version_code(version.get("code", DEFAULT_VERSION_CODE), f"{field}.code")
405
372
  return {"name": version_name, "code": version_code}
406
373
 
407
374
 
408
375
  def validate_cli_owned_keys(raw):
409
- if "orgId" in raw and (
410
- not isinstance(raw["orgId"], str) or not re.fullmatch(r"[1-9][0-9]*", raw["orgId"])
411
- ):
412
- raise ConfigError("orgId", "must be a positive decimal string")
376
+ # `orgId` 归 supercli。模板只做类型校验,保证站点侧的 schema 变更永远不会打断 App 构建。
377
+ if "orgId" in raw and not isinstance(raw["orgId"], str):
378
+ raise ConfigError("orgId", "must be a string")
413
379
 
414
380
 
415
381
  def normalize_project_dir(value, field):
@@ -419,8 +385,8 @@ def normalize_project_dir(value, field):
419
385
  raise ConfigError(field, "must use forward slashes")
420
386
  if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
421
387
  raise ConfigError(field, "must be relative to the workspace root")
422
- parts = raw.split("/")
423
- if not parts or any(part == "" for part in parts):
388
+ parts = [part for part in raw.split("/") if part != ""]
389
+ if not parts:
424
390
  raise ConfigError(field, "must name a subdirectory of the workspace root")
425
391
  for part in parts:
426
392
  if part in (".", ".."):
@@ -454,53 +420,39 @@ def assert_dirs_are_disjoint(entries):
454
420
  )
455
421
 
456
422
 
457
- def assert_project_ids_unique(shapes):
458
- seen = {}
459
- for shape in shapes:
460
- project_id = shape["projectId"]
461
- if project_id in seen:
462
- raise ConfigError(
463
- f"projects[{shape['index']}].projectId",
464
- f"duplicates projects[{seen[project_id]}].projectId ({project_id})",
465
- )
466
- seen[project_id] = shape["index"]
467
-
468
-
469
423
  def read_project_shape(entry, index):
470
- """只读出选择所需的最小信息(projectId / type / dir),其余校验按 selected 分流。"""
424
+ """只读出选择所需的最小信息(type / dir),其余校验按 selected 分流。"""
471
425
  if not isinstance(entry, dict):
472
426
  raise ConfigError(f"projects[{index}]", "must be a JSON object")
473
427
  project_type = entry.get("type")
474
428
  if project_type is None:
475
429
  raise ConfigError(f"projects[{index}].type", f"is required; one of {', '.join(PROJECT_TYPES)}")
476
430
  project_type = require_string(project_type, f"projects[{index}].type")
477
- project_id = require_string(entry.get("projectId"), f"projects[{index}].projectId")
478
- if not re.fullmatch(PROJECT_ID_PATTERN, project_id):
479
- raise ConfigError(f"projects[{index}].projectId", f"must match ^{PROJECT_ID_PATTERN}$")
480
431
  directory = normalize_project_dir(entry.get("dir"), f"projects[{index}].dir")
481
- return {"index": index, "projectId": project_id, "type": project_type, "dir": directory, "raw": entry}
432
+ return {"index": index, "type": project_type, "dir": directory, "raw": entry}
482
433
 
483
434
 
484
435
  def select_project_shapes(shapes, platform="all", project=None):
485
436
  selected = shapes
486
437
  if project is not None:
487
- wanted = require_string(project, "--project")
488
- selected = [shape for shape in selected if shape["projectId"] == wanted]
438
+ # 先按目录挑,再核对类型:否则 `--platform android --project web` 会报
439
+ # 「没有这个目录」,而真正的问题是「这个目录不是 android 项目」。
440
+ wanted = normalize_project_dir(project, "--project")
441
+ selected = [shape for shape in selected if shape["dir"] == wanted]
489
442
  if not selected:
490
- known = ", ".join(shape["projectId"] for shape in shapes) or "<none>"
491
- raise ConfigError("--project", f"no project with projectId {wanted}; configured projectIds: {known}")
443
+ known = ", ".join(shape["dir"] for shape in shapes) or "<none>"
444
+ raise ConfigError("--project", f"no project with dir {wanted}; configured directories: {known}")
492
445
  if platform != "all" and selected[0]["type"] != platform:
493
446
  raise ConfigError("--project", f"{wanted} is a {selected[0]['type']} project, not {platform}")
494
447
  if platform != "all":
495
448
  selected = [shape for shape in selected if shape["type"] == platform]
496
- return selected
449
+ return sorted(selected, key=lambda shape: (TYPE_ORDER.get(shape["type"], len(TYPE_ORDER)), shape["index"]))
497
450
 
498
451
 
499
452
  def validate_project(shape, root_name, workspace_version, workspace_sdk):
500
453
  entry = shape["raw"]
501
454
  index = shape["index"]
502
455
  directory = shape["dir"]
503
- project_id = shape["projectId"]
504
456
  project_type = shape["type"]
505
457
  label = f"projects[{directory}]"
506
458
 
@@ -534,26 +486,18 @@ def validate_project(shape, root_name, workspace_version, workspace_sdk):
534
486
  name = entry.get("name")
535
487
  if name is not None:
536
488
  name = require_string(name, f"{label}.name")
537
- if name != name.strip():
538
- raise ConfigError(f"{label}.name", "must not have leading or trailing whitespace")
539
- maximum = 50 if project_type in {"site", "service"} else 100
540
- if len(name) > maximum:
541
- raise ConfigError(f"{label}.name", f"must be 1..{maximum} characters")
542
489
 
543
490
  if project_type == "android":
544
491
  platform_config = validate_android_project(label, entry, name, root_name, sdk)
545
492
  elif project_type == "ios":
546
493
  platform_config = validate_ios_project(label, entry, name, root_name, sdk)
547
- elif project_type == "site":
548
- platform_config = validate_site_project(label, entry)
549
494
  else:
550
- platform_config = validate_service_project(label, entry)
495
+ platform_config = validate_site_project(label, entry)
551
496
 
552
497
  mode = platform_config.get("spmMode", "mock")
553
498
  projected_sdk = {key: sdk[key] for key in project_sdk(project_type, mode) if key in sdk}
554
499
 
555
500
  return {
556
- "projectId": project_id,
557
501
  "type": project_type,
558
502
  "dir": directory,
559
503
  "name": name,
@@ -569,9 +513,6 @@ def require_project_name(label, name, root_name, project_type, target):
569
513
  raise ConfigError(f"{label}.name", "must not have leading or trailing whitespace")
570
514
  if any(ord(char) < 32 for char in name):
571
515
  raise ConfigError(f"{label}.name", f"must be a {target} without control characters")
572
- maximum = 50 if project_type in {"site", "service"} else 100
573
- if len(name) > maximum:
574
- raise ConfigError(f"{label}.name", f"must be 1..{maximum} characters")
575
516
  return name
576
517
  hint = (
577
518
  "the workspace-level name is a description and is never projected as an App label, "
@@ -619,13 +560,17 @@ def validate_ios_project(label, entry, name, root_name, sdk):
619
560
 
620
561
 
621
562
  def validate_site_project(label, entry):
622
- validate_deploy_targets(label, entry.get("deploy", MISSING), "site")
623
-
624
- build = require_mapping(entry.get("build", {}), f"{label}.build")
625
- reject_unknown_keys(build, SITE_BUILD_KEYS, f"{label}.build")
626
- output_dir = normalize_project_relative_path(build.get("outputDir", "dist"), f"{label}.build.outputDir")
627
-
628
- offline = require_mapping(entry.get("offline", {}), f"{label}.offline")
563
+ # deploy[] 归 supercli(每条逐字等于旧 sites[] 条目)。模板只做类型校验后整块忽略,
564
+ # 保证站点侧的 schema 变更永远不会打断构建。
565
+ deploy = entry.get("deploy")
566
+ if deploy is not None:
567
+ if not isinstance(deploy, list):
568
+ raise ConfigError(f"{label}.deploy", "must be an array")
569
+ for position, item in enumerate(deploy):
570
+ if not isinstance(item, dict):
571
+ raise ConfigError(f"{label}.deploy[{position}]", "must be a JSON object")
572
+
573
+ offline = require_mapping(entry.get("offline"), f"{label}.offline")
629
574
  for key in offline:
630
575
  if key not in SITE_OFFLINE_KEYS:
631
576
  raise ConfigError(f"{label}.offline.{key}", "unknown key")
@@ -636,112 +581,7 @@ def validate_site_project(label, entry):
636
581
  host = normalize_host(host)
637
582
  except HostValidationError as exc:
638
583
  raise ConfigError(f"{label}.offline.host", str(exc)) from exc
639
- return {"host": host, "outputDir": output_dir}
640
-
641
-
642
- def reject_unknown_keys(value, allowed, field):
643
- for key in value:
644
- if key not in allowed:
645
- raise ConfigError(f"{field}.{key}", "unknown key")
646
-
647
-
648
- def normalize_project_relative_path(value, field, allow_dot=False):
649
- raw = require_string(value, field)
650
- if raw == "." and allow_dot:
651
- return raw
652
- if "\\" in raw or raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
653
- raise ConfigError(field, "must be a relative POSIX path")
654
- parts = raw.split("/")
655
- if not parts or any(part in ("", ".", "..") for part in parts):
656
- raise ConfigError(field, "must stay within the project directory")
657
- return "/".join(parts)
658
-
659
-
660
- def validate_env_references(raw, field):
661
- if raw is MISSING:
662
- return []
663
- if not isinstance(raw, list):
664
- raise ConfigError(field, "must be an array")
665
- seen = set()
666
- result = []
667
- for index, item in enumerate(raw):
668
- item_field = f"{field}[{index}]"
669
- item = require_mapping(item, item_field)
670
- reject_unknown_keys(item, ENV_REFERENCE_KEYS, item_field)
671
- name = require_string(item.get("name"), f"{item_field}.name")
672
- source = require_string(item.get("sourceEnv"), f"{item_field}.sourceEnv")
673
- if not re.fullmatch(ENV_NAME_PATTERN, name) or not re.fullmatch(ENV_NAME_PATTERN, source):
674
- raise ConfigError(item_field, "name and sourceEnv must be environment variable names")
675
- if name in seen:
676
- raise ConfigError(f"{item_field}.name", "duplicates a platform environment variable name")
677
- seen.add(name)
678
- result.append({"name": name, "sourceEnv": source})
679
- return result
680
-
681
-
682
- def validate_deploy_targets(label, raw, project_type):
683
- if raw is MISSING:
684
- return []
685
- if not isinstance(raw, list):
686
- raise ConfigError(f"{label}.deploy", "must be an array")
687
- result = []
688
- seen = set()
689
- for index, target in enumerate(raw):
690
- field = f"{label}.deploy[{index}]"
691
- target = require_mapping(target, field)
692
- allowed = DEPLOY_COMMON_KEYS | (SERVICE_DEPLOY_KEYS if project_type == "service" else set())
693
- reject_unknown_keys(target, allowed, field)
694
- env_target = require_string(target.get("envTarget"), f"{field}.envTarget")
695
- if not re.fullmatch(ENV_TARGET_PATTERN, env_target):
696
- raise ConfigError(f"{field}.envTarget", f"must match ^{ENV_TARGET_PATTERN}$")
697
- if env_target in seen:
698
- raise ConfigError(f"{field}.envTarget", "must be unique within the project")
699
- seen.add(env_target)
700
- slug = require_string(target.get("slug"), f"{field}.slug")
701
- if not re.fullmatch(DEPLOY_SLUG_PATTERN, slug) or slug in RESERVED_DEPLOY_SLUGS:
702
- raise ConfigError(f"{field}.slug", "must be 1..32 lowercase letters or digits and not a reserved slug")
703
- env = require_string(target.get("env"), f"{field}.env")
704
- if not re.fullmatch(DEPLOY_ENV_PATTERN, env):
705
- raise ConfigError(f"{field}.env", "must be 1..10 lowercase letters or digits")
706
- if "name" in target:
707
- target_name = require_string(target["name"], f"{field}.name")
708
- if target_name != target_name.strip() or len(target_name) > 50:
709
- raise ConfigError(f"{field}.name", "must be 1..50 characters without surrounding whitespace")
710
- for key, upper in (("port", 65535), ("cpuMilli", 4000), ("memoryMiB", 8192), ("maxScale", 10)):
711
- if key in target and (not is_positive_int(target[key]) or target[key] > upper):
712
- raise ConfigError(f"{field}.{key}", f"must be an integer from 1 to {upper}")
713
- if "databaseConnection" in target and target["databaseConnection"] is not None:
714
- require_string(target["databaseConnection"], f"{field}.databaseConnection")
715
- if project_type == "service":
716
- runtime_refs = validate_env_references(target.get("runtimeEnvFromEnv", MISSING), f"{field}.runtimeEnvFromEnv")
717
- secret_refs = validate_env_references(target.get("secretsFromEnv", MISSING), f"{field}.secretsFromEnv")
718
- runtime_names = {reference["name"] for reference in runtime_refs}
719
- duplicate_names = sorted(runtime_names & {reference["name"] for reference in secret_refs})
720
- if duplicate_names:
721
- raise ConfigError(field, "duplicates platform environment variable name across runtimeEnvFromEnv/secretsFromEnv: " + ", ".join(duplicate_names))
722
- result.append(target)
723
- return result
724
-
725
-
726
- def validate_service_project(label, entry):
727
- if "build" not in entry:
728
- raise ConfigError(f"{label}.build", "is required for service projects")
729
- build = require_mapping(entry["build"], f"{label}.build")
730
- reject_unknown_keys(build, SERVICE_BUILD_KEYS, f"{label}.build")
731
- context = normalize_project_relative_path(build.get("context", "."), f"{label}.build.context", allow_dot=True)
732
- dockerfile = normalize_project_relative_path(build.get("dockerfile", "Dockerfile"), f"{label}.build.dockerfile")
733
- platform = require_string(build.get("platform", "linux/amd64"), f"{label}.build.platform")
734
- if platform != "linux/amd64":
735
- raise ConfigError(f"{label}.build.platform", "must be linux/amd64 for this engine version")
736
- args_from_env = build.get("argsFromEnv", [])
737
- if not isinstance(args_from_env, list) or any(
738
- not isinstance(item, str) or not re.fullmatch(ENV_NAME_PATTERN, item) for item in args_from_env
739
- ):
740
- raise ConfigError(f"{label}.build.argsFromEnv", "must be an array of environment variable names")
741
- if len(set(args_from_env)) != len(args_from_env):
742
- raise ConfigError(f"{label}.build.argsFromEnv", "must not contain duplicates")
743
- validate_deploy_targets(label, entry.get("deploy", MISSING), "service")
744
- return {"context": context, "dockerfile": dockerfile, "platform": platform, "argsFromEnv": args_from_env}
584
+ return {"host": host}
745
585
 
746
586
 
747
587
  def check_root_envelope(raw, config_path=None):
@@ -753,18 +593,15 @@ def check_root_envelope(raw, config_path=None):
753
593
  if key in raw:
754
594
  raise ConfigError(key, reason)
755
595
 
756
- allowed_root = set(ROOT_KEY_ORDER)
757
- for key in raw:
758
- if key not in allowed_root:
759
- raise ConfigError(key, "unknown key")
760
-
761
596
  schema_version = raw.get("schemaVersion")
762
597
  if isinstance(schema_version, bool) or not isinstance(schema_version, int) or schema_version != CONFIG_SCHEMA_VERSION:
763
598
  message = f"must be {CONFIG_SCHEMA_VERSION}"
764
- if schema_version == 3 and not isinstance(schema_version, bool):
599
+ if schema_version == 2 and not isinstance(schema_version, bool):
765
600
  message += (
766
- f"; this file is schema v3. schemaVersion {CONFIG_SCHEMA_VERSION} is breaking and there is no "
767
- "backward compatibility. Run `supercli config migrate --from supersdk.json --to super.json`."
601
+ f"; this file is schema v2. schemaVersion {CONFIG_SCHEMA_VERSION} is breaking and there is no "
602
+ "backward compatibility. Migrate it in place (projects[] replaces android/ios/web/sites, "
603
+ "environment is dropped because it is a runtime init parameter):\n"
604
+ + migrate_command(config_path)
768
605
  )
769
606
  raise ConfigError("schemaVersion", message)
770
607
 
@@ -782,7 +619,6 @@ def read_project_shapes(raw):
782
619
  raise ConfigError("projects", "must be an array")
783
620
  shapes = [read_project_shape(entry, index) for index, entry in enumerate(entries)]
784
621
  assert_dirs_are_disjoint([(shape["index"], shape) for shape in shapes])
785
- assert_project_ids_unique(shapes)
786
622
  return shapes
787
623
 
788
624
 
@@ -829,42 +665,22 @@ def validate_config(raw, selected=None, project=None, config_path=None):
829
665
  root_name = raw.get("name")
830
666
  if root_name is not None:
831
667
  root_name = require_string(root_name, "name")
832
- if root_name != root_name.strip() or len(root_name) > 100:
833
- raise ConfigError("name", "must be 1..100 characters without surrounding whitespace")
834
668
 
835
669
  # workspace 级 version/sdk 的**形状**无条件校验(它是工作空间级字段,与选谁无关);
836
670
  # sdk 里各个值的合法性(androidVersion 格式、real 模式的 url/version)因类型而异,
837
671
  # 留给按项目的 scope。
838
- workspace_version = resolve_version(validate_version_namespace(raw.get("version", MISSING), "version"), "version")
839
- workspace_sdk = validate_sdk_namespace(raw.get("sdk", MISSING), "sdk")
672
+ workspace_version = resolve_version(validate_version_namespace(raw.get("version"), "version"), "version")
673
+ workspace_sdk = validate_sdk_namespace(raw.get("sdk"), "sdk")
840
674
 
841
675
  shapes = read_project_shapes(raw)
842
676
  selected_shapes = select_project_shapes(shapes, platform, project)
843
- all_projects = [validate_project(shape, root_name, workspace_version, workspace_sdk) for shape in shapes]
844
- selected_ids = {shape["projectId"] for shape in selected_shapes}
845
- projects = [item for item in all_projects if item["projectId"] in selected_ids]
846
-
847
- target_owners = {}
848
- for index, entry in enumerate(raw["projects"]):
849
- for target_index, target in enumerate(entry.get("deploy", [])):
850
- if not isinstance(target, dict) or "slug" not in target or "env" not in target:
851
- continue
852
- key = (target["slug"], target["env"])
853
- if key in target_owners:
854
- raise ConfigError(
855
- f"projects[{index}].deploy[{target_index}]",
856
- f"duplicates platform target slug/env owned by {target_owners[key]}",
857
- )
858
- target_owners[key] = f"projects[{index}].deploy[{target_index}]"
677
+ projects = [validate_project(shape, root_name, workspace_version, workspace_sdk) for shape in selected_shapes]
859
678
 
860
679
  return {
861
680
  "schemaVersion": CONFIG_SCHEMA_VERSION,
862
681
  "engineVersion": ENGINE_VERSION,
863
682
  "spid": spid,
864
- "orgId": raw.get("orgId"),
865
683
  "name": root_name,
866
- "version": workspace_version,
867
- "sdk": dict(workspace_sdk),
868
684
  "projects": projects,
869
685
  "projectDirs": [shape["dir"] for shape in shapes],
870
686
  }
@@ -898,7 +714,6 @@ def target_content(normalized, project):
898
714
  "schema_version": MANAGED_CONFIG_SCHEMA_VERSION,
899
715
  "engine_version": ENGINE_VERSION,
900
716
  "spid": normalized["spid"],
901
- "project_id": project["projectId"],
902
717
  "name": project["name"],
903
718
  "platform": project["type"],
904
719
  "dir": project["dir"],
@@ -1053,7 +868,7 @@ def print_plan(root, config, platform, project):
1053
868
  require_selection(normalized, platform, project)
1054
869
  for item in normalized["projects"]:
1055
870
  helper = Path(root) / "scripts" / ("build_" + item["type"] + ".sh")
1056
- print(f"projectId={item['projectId']} type={item['type']} dir={item['dir']} helper={helper} mode=plan")
871
+ print(f"platform={item['type']} dir={item['dir']} helper={helper} mode=plan")
1057
872
 
1058
873
 
1059
874
  def print_resolve(config, platform, project):
@@ -1064,10 +879,10 @@ def print_resolve(config, platform, project):
1064
879
  def resolve_single(config, platform, project):
1065
880
  projects = resolve_shapes(config, platform, project)
1066
881
  if len(projects) > 1:
1067
- ids = ", ".join(item["projectId"] for item in projects)
882
+ dirs = ", ".join(item["dir"] for item in projects)
1068
883
  raise ConfigError(
1069
884
  "--project",
1070
- f"{len(projects)} {platform} projects are configured ({ids}); pass --project <projectId> to pick one",
885
+ f"{len(projects)} {platform} projects are configured ({dirs}); pass --project <dir> to pick one",
1071
886
  )
1072
887
  return projects[0]["dir"]
1073
888
 
@@ -1138,190 +953,143 @@ def serialize_project(entry):
1138
953
  if key in NESTED_KEY_ORDER and isinstance(value, dict):
1139
954
  out[key] = order_keys(value, NESTED_KEY_ORDER[key])
1140
955
  elif key == "deploy" and isinstance(value, list):
1141
- out[key] = [serialize_deploy_target(item) for item in value]
956
+ out[key] = [order_keys(item, DEPLOY_KEY_ORDER) if isinstance(item, dict) else item for item in value]
1142
957
  else:
1143
958
  out[key] = value
1144
959
  return out
1145
960
 
1146
961
 
1147
- def serialize_deploy_target(item):
1148
- if not isinstance(item, dict):
1149
- return item
1150
- ordered = order_keys(item, DEPLOY_KEY_ORDER)
1151
- for key in ("runtimeEnvFromEnv", "secretsFromEnv"):
1152
- if isinstance(ordered.get(key), list):
1153
- ordered[key] = [order_keys(ref, ("name", "sourceEnv")) if isinstance(ref, dict) else ref for ref in ordered[key]]
1154
- return ordered
1155
-
962
+ def migrate_document(raw, config_dir):
963
+ """v2 -> v3,零信息损失。
1156
964
 
1157
- def collect_v3_unknown_paths(raw):
1158
- """Enumerate every v3 field that cannot be represented by the strict v4 schema."""
1159
- unknown = []
1160
- if not isinstance(raw, dict):
1161
- return ["$"]
1162
- root_allowed = {"schemaVersion", "spid", "orgId", "name", "version", "sdk", "projects"}
1163
- unknown.extend(f"$.{key}" for key in raw if key not in root_allowed)
1164
- for field, allowed in (("version", VERSION_KEYS), ("sdk", SDK_KEYS)):
1165
- value = raw.get(field)
1166
- if isinstance(value, dict):
1167
- unknown.extend(f"$.{field}.{key}" for key in value if key not in allowed)
1168
- projects = raw.get("projects")
1169
- if not isinstance(projects, list):
1170
- return unknown
1171
- for index, project in enumerate(projects):
1172
- if not isinstance(project, dict):
1173
- continue
1174
- project_type = project.get("type")
1175
- allowed = (COMMON_PROJECT_KEYS - {"projectId", "build"}) | TYPE_PROJECT_KEYS.get(project_type, set())
1176
- if project_type == "site":
1177
- allowed -= {"build"}
1178
- unknown.extend(f"$.projects[{index}].{key}" for key in project if key not in allowed)
1179
- for field, nested_allowed in (("version", VERSION_KEYS), ("sdk", SDK_KEYS)):
1180
- value = project.get(field)
1181
- if isinstance(value, dict):
1182
- unknown.extend(
1183
- f"$.projects[{index}].{field}.{key}" for key in value if key not in nested_allowed
1184
- )
1185
- offline = project.get("offline")
1186
- if isinstance(offline, dict):
1187
- unknown.extend(f"$.projects[{index}].offline.{key}" for key in offline if key not in SITE_OFFLINE_KEYS)
1188
- deploy = project.get("deploy")
1189
- if isinstance(deploy, list):
1190
- for target_index, target in enumerate(deploy):
1191
- if isinstance(target, dict):
1192
- allowed_target = {"slug", "name", "env", "dir"}
1193
- unknown.extend(
1194
- f"$.projects[{index}].deploy[{target_index}].{key}"
1195
- for key in target if key not in allowed_target
1196
- )
1197
- build = project.get("build")
1198
- if "build" in allowed and isinstance(build, dict):
1199
- nested_allowed = SERVICE_BUILD_KEYS if project_type == "service" else SITE_BUILD_KEYS
1200
- unknown.extend(
1201
- f"$.projects[{index}].build.{key}" for key in build if key not in nested_allowed
1202
- )
1203
- return sorted(unknown)
1204
-
1205
-
1206
- def migrate_document(raw, config_dir=None):
1207
- """Convert a strict schema-v3 document to schema v4 without guessing identities."""
1208
- del config_dir
965
+ 🔴 结构性事实:v2 的模板目录就是 `android/ ios/ web/`,v3 可以原样保留
966
+ (`{"type": "site", "dir": "web"}`)—— **迁移不移动任何文件**,只改配置。
967
+ v2 的 `sites[]` 每条 `{slug,name,env,dir}` 逐字搬进 site 项目的 `deploy[]`。
968
+ """
1209
969
  if not isinstance(raw, dict):
1210
970
  raise ConfigError(CONFIG_FILENAME, "top-level document must be a JSON object")
1211
971
  version = raw.get("schemaVersion")
1212
- if isinstance(version, bool) or not isinstance(version, int) or version != 3:
1213
- raise ConfigError("schemaVersion", "migrate reads schemaVersion 3 documents only")
1214
- unknown = collect_v3_unknown_paths(raw)
1215
- if unknown:
1216
- raise ConfigError("migration", "unknown field(s): " + ", ".join(unknown))
972
+ if version == CONFIG_SCHEMA_VERSION:
973
+ return None, ["already schemaVersion 3; nothing to migrate"]
974
+ if isinstance(version, bool) or not isinstance(version, int) or version != 2:
975
+ raise ConfigError("schemaVersion", "migrate reads schemaVersion 2 documents only")
976
+
977
+ # 🔴 fail closed:v2 文档里已经带了根级 projects,说明有人手工迁到一半。
978
+ # 两份身份来源同时在场,合并语义是未定义的 —— 旧实现更糟:下面「保留未知根键」的
979
+ # 循环会把刚算出来的 projects 整个盖掉,exit 0、零告警、身份全丢。所以这里一个字
980
+ # 都不写,让用户先删掉一边。
981
+ if "projects" in raw:
982
+ legacy_sections = [key for key in ("android", "ios", "web", "sites") if key in raw]
983
+ if legacy_sections:
984
+ raise ConfigError(
985
+ "projects",
986
+ 'this schemaVersion 2 document carries a root "projects" key next to the v2 sections ('
987
+ + ", ".join(legacy_sections)
988
+ + "); the two are different identity sources and merging them is undefined, so nothing was "
989
+ 'written. Remove one side first: delete "projects" to migrate from the v2 sections, or delete '
990
+ "the v2 sections to keep the projects[] you wrote by hand.",
991
+ )
992
+ raise ConfigError(
993
+ "projects",
994
+ 'this schemaVersion 2 document carries a root "projects" key, which is the schemaVersion 3 identity '
995
+ "list; migrate will neither merge into it nor drop it, so nothing was written. If that projects[] is "
996
+ 'your hand-written v3 list, set "schemaVersion": 3 in the file and run validate instead of migrate; '
997
+ "if the key means something else, rename it and re-run migrate.",
998
+ )
1217
999
 
1218
- migrated = {"schemaVersion": 4}
1000
+ notes = []
1001
+ # v2 的 name 是 App label(缺省 "SuperSDK Simple");v3 里根 name 只是描述,
1002
+ # 真身份在项目条目上,所以要把**生效值**抄进每个 android/ios 项目。
1003
+ app_label = raw.get("name") if isinstance(raw.get("name"), str) and raw.get("name").strip() else "SuperSDK Simple"
1004
+
1005
+ migrated = {"schemaVersion": CONFIG_SCHEMA_VERSION}
1219
1006
  for key in ("spid", "orgId", "name", "version", "sdk"):
1220
1007
  if key in raw:
1221
1008
  migrated[key] = raw[key]
1222
- projects = raw.get("projects")
1223
- if not isinstance(projects, list):
1224
- raise ConfigError("projects", "must be an array")
1225
- ids = {}
1226
- converted = []
1227
- conflicts = []
1228
- for index, project in enumerate(projects):
1229
- if not isinstance(project, dict):
1230
- raise ConfigError(f"projects[{index}]", "must be a JSON object")
1231
- directory = normalize_project_dir(project.get("dir"), f"projects[{index}].dir")
1232
- project_id = Path(directory).name.lower()
1233
- if not re.fullmatch(PROJECT_ID_PATTERN, project_id):
1234
- conflicts.append(f"projects[{index}].dir -> invalid projectId {project_id!r}")
1235
- elif project_id in ids:
1236
- conflicts.append(f"projects[{index}].dir -> projectId {project_id!r} also from projects[{ids[project_id]}]")
1237
- ids[project_id] = index
1238
- entry = {"projectId": project_id}
1239
- for key, value in project.items():
1240
- if key != "deploy":
1241
- entry[key] = value
1242
- if project.get("type") == "site" and "deploy" in project:
1243
- deploy = project["deploy"]
1244
- if not isinstance(deploy, list):
1245
- raise ConfigError(f"projects[{index}].deploy", "must be an array")
1246
- targets = []
1247
- output_dirs = set()
1248
- env_targets = set()
1249
- for target_index, target in enumerate(deploy):
1250
- if not isinstance(target, dict):
1251
- raise ConfigError(f"projects[{index}].deploy[{target_index}]", "must be a JSON object")
1252
- env_target = target.get("env")
1253
- if env_target in env_targets:
1254
- conflicts.append(f"projects[{index}].deploy[{target_index}].env -> duplicate envTarget {env_target!r}")
1255
- env_targets.add(env_target)
1256
- converted_target = {"envTarget": env_target}
1257
- for key in ("slug", "name", "env"):
1258
- if key in target:
1259
- converted_target[key] = target[key]
1260
- if "dir" in target:
1261
- output_dirs.add(normalize_project_relative_path(target["dir"], f"projects[{index}].deploy[{target_index}].dir"))
1262
- targets.append(converted_target)
1263
- if len(output_dirs) > 1:
1264
- conflicts.append(f"projects[{index}].deploy[].dir -> multiple site output directories")
1265
- entry["deploy"] = targets
1266
- if output_dirs:
1267
- entry["build"] = {"outputDir": next(iter(output_dirs))}
1268
- converted.append(entry)
1269
- if conflicts:
1270
- raise ConfigError("migration", "ambiguous mapping(s): " + "; ".join(conflicts))
1271
- migrated["projects"] = converted
1272
- validate_config(migrated)
1273
- return migrated, []
1274
-
1275
-
1276
- def canonical_config_text(document):
1277
- """The byte-stable semantic representation shared by build and deploy."""
1278
- validate_config(document)
1279
- return serialize_config(document)
1280
-
1281
-
1282
- def canonical_config_sha256(document):
1283
- return hashlib.sha256(canonical_config_text(document).encode("utf-8")).hexdigest()
1284
-
1285
-
1286
- def migrate(source, target, dry_run=False):
1287
- source_path = Path(source).resolve()
1288
- target_path = Path(target).resolve()
1289
- if source_path.parent != target_path.parent:
1290
- raise ConfigError("migration", "--from and --to must be in the same normalized workspace root")
1291
- if target_path.exists():
1292
- raise ConfigError("migration", f"target already exists: {target_path}")
1293
- migrated, _ = migrate_document(read_config_document(source_path), source_path.parent)
1009
+
1010
+ if "environment" in raw:
1011
+ notes.append(
1012
+ f"dropped root environment ({raw['environment']!r}): it is a runtime init parameter now. "
1013
+ "Pass it to SuperSDK.init at runtime, or use the demo environment switcher."
1014
+ )
1015
+
1016
+ projects = []
1017
+ android = raw.get("android")
1018
+ if isinstance(android, dict) or (config_dir / "android").is_dir():
1019
+ entry = {"type": "android", "dir": "android", "name": app_label}
1020
+ if isinstance(android, dict) and "package" in android:
1021
+ entry["package"] = android["package"]
1022
+ projects.append(entry)
1023
+
1024
+ ios = raw.get("ios")
1025
+ if isinstance(ios, dict) or (config_dir / "ios").is_dir():
1026
+ entry = {"type": "ios", "dir": "ios", "name": app_label}
1027
+ if isinstance(ios, dict):
1028
+ for key in ("bundleId", "spmMode"):
1029
+ if key in ios:
1030
+ entry[key] = ios[key]
1031
+ projects.append(entry)
1032
+
1033
+ web = raw.get("web")
1034
+ sites = raw.get("sites")
1035
+ if isinstance(web, dict) or isinstance(sites, list) or (config_dir / "web").is_dir():
1036
+ entry = {"type": "site", "dir": "web", "name": app_label}
1037
+ if isinstance(sites, list):
1038
+ # 逐字搬运:一个字段都不能丢,包括 CLI 以后才认识的键。
1039
+ entry["deploy"] = sites
1040
+ if isinstance(web, dict) and "host" in web:
1041
+ entry["offline"] = {"host": web["host"]}
1042
+ else:
1043
+ notes.append(
1044
+ "site project has no offline.host; offline packaging stays disabled until the site is published "
1045
+ "once (the CLI records the server-issued host) or you set projects[].offline.host by hand."
1046
+ )
1047
+ projects.append(entry)
1048
+
1049
+ migrated["projects"] = projects
1050
+ # 未知根键原样保留。"projects" 在跳过集里是**纵深防御**:上面的 fail-closed 守卫已经
1051
+ # 让带根级 projects 的文档到不了这里,但这行保证「即使守卫被改坏,迁移结果也不会被
1052
+ # 输入里的同名键覆盖」—— 这是数据丢失,不是配置问题。
1053
+ consumed = {
1054
+ "schemaVersion", "spid", "orgId", "name", "version", "sdk",
1055
+ "environment", "android", "ios", "web", "sites", "projects",
1056
+ }
1057
+ for key, value in raw.items():
1058
+ if key in consumed:
1059
+ continue
1060
+ migrated[key] = value
1061
+
1062
+ if not projects:
1063
+ notes.append("no android/ios/web project was found; projects[] is empty until you run `supercli add`.")
1064
+ return migrated, notes
1065
+
1066
+
1067
+ def migrate(config, dry_run):
1068
+ config_path = Path(config)
1069
+ raw = read_config_document(config_path)
1070
+ migrated, notes = migrate_document(raw, config_path.parent)
1071
+ if migrated is None:
1072
+ for note in notes:
1073
+ print(note)
1074
+ return 0
1294
1075
  text = serialize_config(migrated)
1295
1076
  if dry_run:
1296
1077
  sys.stdout.write(text)
1297
- return 0
1298
- temp = target_path.with_name(f".{target_path.name}.tmp.{os.getpid()}.{uuid.uuid4().hex}")
1078
+ else:
1079
+ temp = config_path.with_name(f".{config_path.name}.tmp.{os.getpid()}.{uuid.uuid4().hex}")
1080
+ temp.write_text(text, encoding="utf-8")
1081
+ os.replace(temp, config_path)
1082
+ print(f"migrated {config_path} to schemaVersion {CONFIG_SCHEMA_VERSION}")
1083
+ for note in notes:
1084
+ print(note)
1299
1085
  try:
1300
- with temp.open("x", encoding="utf-8") as handle:
1301
- handle.write(text)
1302
- handle.flush()
1303
- os.fsync(handle.fileno())
1304
- # Hard-link install is atomic and no-clobber: unlike os.replace(), it
1305
- # cannot overwrite a user file created after the exists() preflight.
1306
- try:
1307
- os.link(temp, target_path)
1308
- except FileExistsError as exc:
1309
- raise ConfigError("migration", f"target already exists: {target_path}") from exc
1310
- except OSError as exc:
1311
- raise ConfigError("migration", f"could not install target atomically: {exc}") from exc
1312
- temp.unlink()
1313
- try:
1314
- directory_fd = os.open(str(target_path.parent), os.O_RDONLY)
1315
- try:
1316
- os.fsync(directory_fd)
1317
- finally:
1318
- os.close(directory_fd)
1319
- except OSError:
1320
- pass
1321
- finally:
1322
- if temp.exists():
1323
- temp.unlink()
1324
- print(f"migrated {source_path} to {target_path} (schemaVersion 4); source was not modified")
1086
+ # 迁移是**逐字搬运**,不修数据:v2 时就缺的字段(比如从没设过 android.package)
1087
+ # 迁移后依然缺。所以校验失败不代表迁移失败 —— 文件已经写好了,这里只是把
1088
+ # 「接下来还要你补什么」说清楚,退出码非零是为了不让人以为万事大吉。
1089
+ validate_config(migrated, config_path=config_path)
1090
+ except ConfigError as exc:
1091
+ print(f"post-migration check: the file is now schemaVersion 3 but still needs attention -> {exc}", file=sys.stderr)
1092
+ return 1
1325
1093
  return 0
1326
1094
 
1327
1095
 
@@ -1358,8 +1126,7 @@ def main(argv):
1358
1126
  check.add_argument("--config", required=True)
1359
1127
 
1360
1128
  migrate_cmd = sub.add_parser("migrate")
1361
- migrate_cmd.add_argument("--from", dest="source", required=True)
1362
- migrate_cmd.add_argument("--to", dest="target", required=True)
1129
+ migrate_cmd.add_argument("--config", required=True)
1363
1130
  migrate_cmd.add_argument("--dry-run", action="store_true")
1364
1131
 
1365
1132
  args = parser.parse_args(argv)
@@ -1383,7 +1150,7 @@ def main(argv):
1383
1150
  elif args.command == "engine-check":
1384
1151
  engine_check(args.root, args.config)
1385
1152
  elif args.command == "migrate":
1386
- return migrate(args.source, args.target, args.dry_run)
1153
+ return migrate(args.config, args.dry_run)
1387
1154
  except ConfigError as exc:
1388
1155
  print(str(exc), file=sys.stderr)
1389
1156
  return 1