@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,1161 +0,0 @@
1
- #!/usr/bin/env python3
2
- import argparse
3
- import ipaddress
4
- import json
5
- import os
6
- import re
7
- import shlex
8
- import sys
9
- import uuid
10
- from pathlib import Path
11
- from urllib.parse import urlparse
12
-
13
- sys.path.insert(0, str(Path(__file__).resolve().parent))
14
- from web_host_validator import HostValidationError, normalize_host
15
-
16
-
17
- # 🔴 引擎版本。这份脚本被 vendored 进**每一个**生成出来的工作空间,生成物里没有版本标记
18
- # 就无法回答「这份 managed config 是哪一版引擎写的」。用户升级 CLI 后在老仓库里跑
19
- # `supercli add`,CLI 写出新 schema、仓库自带的老引擎报「schemaVersion 必须是 N」——
20
- # 那条错指向用户自己的配置文件,完全指不到真正的原因(工程模板过期了)。
21
- # 版本号写进 managed config 纯为溯源;`engine-check` 子命令据此给出可执行的升级提示。
22
- ENGINE_VERSION = "3.0.0"
23
-
24
- MANAGED_BY = "supersdk-template"
25
- # 每个项目目录下的 `.supersdk/managed/config.json` 有自己的 snake_case `schema_version`,
26
- # 与根配置文件的 `schemaVersion` 是**两份**契约,各自独立演进。
27
- MANAGED_CONFIG_SCHEMA_VERSION = 3
28
- MANAGED_CONFIG_KEYS = (
29
- "managed_by",
30
- "schema_version",
31
- "engine_version",
32
- "spid",
33
- "name",
34
- "platform",
35
- "dir",
36
- "version",
37
- "sdk",
38
- "platform_config",
39
- )
40
-
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")
45
-
46
- # 首批项目类型。`type` 是普通字符串字段,加新类型只要加一个 build_<type>.sh 与一段投影,
47
- # 不需要动 schema 版本;但**未知类型一律 fail-closed**,否则 plan 会给出一个根本不存在的
48
- # helper 路径,直到 build 阶段才炸。
49
- PROJECT_TYPES = ("android", "ios", "site")
50
- TYPE_ORDER = {name: index for index, name in enumerate(PROJECT_TYPES)}
51
-
52
- # 每个项目条目允许的键。身份键(package / bundleId)只出现在项目里:
53
- # 永不继承、永不推导,推导出来的身份等于把第三方 App 发到别人的反向域名下。
54
- COMMON_PROJECT_KEYS = {"type", "dir", "name", "version", "sdk"}
55
- TYPE_PROJECT_KEYS = {
56
- "android": {"package"},
57
- "ios": {"bundleId", "spmMode"},
58
- "site": {"deploy", "offline"},
59
- }
60
- # 打错的身份键必须给定向诊断,而不是泛泛的 "unknown key"。
61
- PROJECT_KEY_ALIASES = {
62
- "ios": {"bundle_id": "bundleId", "bundleID": "bundleId", "bundle-id": "bundleId"},
63
- "android": {"applicationId": "package", "package_name": "package", "packageName": "package"},
64
- "site": {"host": "offline.host", "sites": "deploy"},
65
- }
66
- SITE_OFFLINE_KEYS = {"host"}
67
- VERSION_KEYS = {"name", "code"}
68
- SDK_KEYS = {"androidVersion", "iosPackageUrl", "iosVersion"}
69
- SDK_PROJECTION = {
70
- "android": {"mock": ("androidVersion",), "real": ("androidVersion",)},
71
- "ios": {"mock": (), "real": ("iosPackageUrl", "iosVersion")},
72
- "site": {"mock": (), "real": ()},
73
- }
74
-
75
- ANDROID_NAMESPACE = "com.supersdk.simple"
76
- ANDROID_VERSION_RE = r"^[0-9]+\.[0-9]+\.[0-9]+(?:[-.][A-Za-z0-9]+)*$"
77
- IOS_VERSION_PATTERN = r"^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$"
78
- SPID_PATTERN = r"[a-z0-9]{8}"
79
- BUNDLE_ID_PATTERN = r"[A-Za-z0-9][A-Za-z0-9-]*(\.[A-Za-z0-9][A-Za-z0-9-]*)+"
80
- JAVA_PACKAGE_PATTERN = r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+"
81
-
82
- DEFAULT_VERSION_NAME = "1.0.0"
83
- DEFAULT_VERSION_CODE = 1
84
-
85
- # 退役根键。每一条都给**定向**诊断,而不是被「未知键原样保留」的规则带过去。
86
- # v1 关键字先于 schemaVersion 检查(它们的诊断与 schemaVersion 无关);
87
- # v2 关键字在 schemaVersion 之后检查,因为对 v2 文档来说 migrate 提示才是更有用的那条。
88
- RETIRED_ROOT_KEYS = {
89
- "schema_version": f"retired schema v1 key; use camelCase schemaVersion: {CONFIG_SCHEMA_VERSION}",
90
- "app_id": "retired key; rename it to spid",
91
- }
92
-
93
- # environment 是本轮最重要的一条:它是**运行时 init 参数**,编译期根本不需要。
94
- RETIRED_V2_ROOT_KEYS = {
95
- "environment": (
96
- "retired key; environment is a runtime init parameter, not build configuration. "
97
- "Delete it from supersdk.json: SuperSDK.init(context, spid, provider) defaults to prod, "
98
- "and the bundled demo apps switch environment at runtime"
99
- ),
100
- "android": 'retired schema v2 key; it is now an entry in projects[]: {"type": "android", "dir": "android", ...}',
101
- "ios": 'retired schema v2 key; it is now an entry in projects[]: {"type": "ios", "dir": "ios", ...}',
102
- "web": 'retired schema v2 key; it is now an entry in projects[]: {"type": "site", "dir": "web", ...}',
103
- "sites": 'retired schema v2 key; each entry moved verbatim into the site project deploy[] array',
104
- }
105
-
106
- # 每个必填字段都在:少一个字段的迁移提示,对照抄的人就是死路。
107
- MIGRATION_TEMPLATE = """{
108
- "schemaVersion": 3,
109
- "spid": "demo0001",
110
- "name": "SuperSDK Simple",
111
- "version": {
112
- "name": "1.0.0",
113
- "code": 1
114
- },
115
- "sdk": {
116
- "androidVersion": "1.0.0.57-SNAPSHOT"
117
- },
118
- "projects": [
119
- {
120
- "type": "android",
121
- "dir": "android",
122
- "name": "SuperSDK Simple",
123
- "package": "com.example.app"
124
- },
125
- {
126
- "type": "ios",
127
- "dir": "ios",
128
- "name": "SuperSDK Simple",
129
- "bundleId": "com.example.app",
130
- "spmMode": "mock"
131
- },
132
- {
133
- "type": "site",
134
- "dir": "web",
135
- "name": "SuperSDK Simple Web",
136
- "offline": {
137
- "host": "app.example.com"
138
- }
139
- }
140
- ]
141
- }
142
- """
143
-
144
- # 写盘键序:根键 + 项目条目内部键。CLI 侧 serializeAppConfig 用同一套顺序,
145
- # 两边写出的字节形态必须一致,否则 git diff 里会出现整文件重排。
146
- #
147
- # 🔴 这个不变式是**被测出来的**,不是靠这段注释维持的:常量在 Python 与 TypeScript 里各写
148
- # 一份,曾经真的漂过(这里排 deploy/offline 在前,CLI 侧排 version/sdk 在前),而当时的注释
149
- # 照样宣称「两边一致」—— 一句拦不住漂移的注释,只会让下一个人去改错的那一边。
150
- # **这份元组是源**,supercli/src/config/appConfig.ts 逐字抄它;改这里必须同步改那边,
151
- # 由 tests/test_template_foundation.py::test_key_order_matches_the_cli_serializer 兜底。
152
- # 项目条目键序的语义:先身份(type/dir/name),再平台身份字段,再站点侧的 deploy/offline,
153
- # 最后是可覆盖的默认值(version/sdk)。
154
- ROOT_KEY_ORDER = ("schemaVersion", "spid", "orgId", "name", "version", "sdk", "projects")
155
- PROJECT_KEY_ORDER = ("type", "dir", "name", "package", "bundleId", "spmMode", "deploy", "offline", "version", "sdk")
156
- NESTED_KEY_ORDER = {
157
- "version": ("name", "code"),
158
- "sdk": ("androidVersion", "iosPackageUrl", "iosVersion"),
159
- "offline": ("host",),
160
- }
161
- DEPLOY_KEY_ORDER = ("slug", "name", "env", "dir")
162
-
163
-
164
- class ConfigError(Exception):
165
- def __init__(self, field, message):
166
- super().__init__(f"{field}: {message}")
167
- self.field = field
168
- self.message = message
169
-
170
-
171
- def helper_path():
172
- return Path(__file__).resolve()
173
-
174
-
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}"
179
-
180
-
181
- def config_file_state(target_path):
182
- """判定已存在的 supersdk.json,让提示永远不会覆盖真值。
183
-
184
- 返回 ("missing" | "valid" | "invalid", reason)。直接解析目标文件,不走 load_config(),
185
- 否则会再次触发 legacy 扫描。
186
- """
187
- if not target_path.is_file():
188
- return "missing", ""
189
- try:
190
- validate_config(read_config_document(target_path), config_path=target_path)
191
- except ConfigError as exc:
192
- return "invalid", exc.message
193
- return "valid", ""
194
-
195
-
196
- def migration_hint(legacy_path, target_path):
197
- legacy = shlex.quote(str(legacy_path))
198
- target = shlex.quote(str(target_path))
199
- skeleton = f"cat > {target} <<'SUPERSDK_JSON'\n{MIGRATION_TEMPLATE}SUPERSDK_JSON\n"
200
- header = (
201
- f"legacy config {legacy_path} is not supported; the template reads standard JSON "
202
- f"{CONFIG_FILENAME} (schemaVersion {CONFIG_SCHEMA_VERSION}) only.\n"
203
- )
204
- state, reason = config_file_state(target_path)
205
- if state == "valid":
206
- # 这里唯一安全的动作:真实配置已经在位,发 `cat >` 骨架会把 spid/package/bundleId/host
207
- # 全部替换成默认值。
208
- return (
209
- header
210
- + f"your {target_path} is already in place and valid, so nothing needs to be written; "
211
- "the legacy file is the only leftover. Copy-paste to remove it:\n"
212
- + f"rm {legacy}\n"
213
- )
214
- if state == "invalid":
215
- return (
216
- header
217
- + f"{target_path} exists but is not usable ({reason}), so back it up before replacing it. "
218
- "Copy-paste to migrate, then replace every value with the one from the legacy file "
219
- "(the legacy file is deleted last because it is the source of those values):\n"
220
- + f"cp {target} {shlex.quote(str(target_path) + '.bak')}\n"
221
- + skeleton
222
- + f"rm {legacy}\n"
223
- )
224
- return (
225
- header
226
- + "Copy-paste to migrate, then replace every value with the one from the legacy file "
227
- "(the new file is written first and the legacy file is deleted last, because the legacy "
228
- "file is the source of those values):\n"
229
- + skeleton
230
- + f"rm {legacy}\n"
231
- )
232
-
233
-
234
- def reject_duplicate_keys(pairs):
235
- mapping = {}
236
- for key, value in pairs:
237
- if key in mapping:
238
- raise ConfigError(key, "duplicate key")
239
- mapping[key] = value
240
- return mapping
241
-
242
-
243
- def reject_json_constant(name):
244
- # stdlib json 接受 NaN/Infinity/-Infinity,supercli 的 JSON.parse 不接受。
245
- # 两边必须以同一种方式读同一个文件,所以这里也拒。
246
- raise ConfigError(CONFIG_FILENAME, f"{name} is not standard JSON; use a number, string, or null")
247
-
248
-
249
- def read_config_document(config_path):
250
- """读并解析一个配置文件。不做 legacy 扫描,因此可重入。"""
251
- config_path = Path(config_path)
252
- if not config_path.is_file():
253
- raise ConfigError(CONFIG_FILENAME, f"not found: {config_path}")
254
- try:
255
- text = config_path.read_text(encoding="utf-8")
256
- except (OSError, UnicodeDecodeError) as exc:
257
- raise ConfigError(CONFIG_FILENAME, f"unreadable: {exc}") from exc
258
- try:
259
- return json.loads(text, object_pairs_hook=reject_duplicate_keys, parse_constant=reject_json_constant)
260
- except ConfigError:
261
- raise
262
- except json.JSONDecodeError as exc:
263
- raise ConfigError(CONFIG_FILENAME, f"invalid JSON at line {exc.lineno} column {exc.colno}: {exc.msg}") from exc
264
-
265
-
266
- def load_config(path):
267
- config_path = Path(path)
268
- target_path = config_path.parent / CONFIG_FILENAME
269
- # 对退役方言硬失败,而不是猜一份等价的 JSON。
270
- if config_path.name in LEGACY_CONFIG_FILENAMES or config_path.suffix.lower() in (".yaml", ".yml"):
271
- raise ConfigError(config_path.name, migration_hint(config_path, target_path))
272
- for legacy_name in LEGACY_CONFIG_FILENAMES:
273
- legacy_path = config_path.parent / legacy_name
274
- if legacy_path.is_file():
275
- raise ConfigError(legacy_name, migration_hint(legacy_path, target_path))
276
- return read_config_document(config_path)
277
-
278
-
279
- def require_mapping(value, field):
280
- if value is None:
281
- return {}
282
- if not isinstance(value, dict):
283
- raise ConfigError(field, "must be a JSON object")
284
- return value
285
-
286
-
287
- def require_string(value, field, allow_empty=False):
288
- if value is None:
289
- raise ConfigError(field, "must not be empty")
290
- if not isinstance(value, str):
291
- raise ConfigError(field, "must be a string")
292
- if not allow_empty and value.strip() == "":
293
- raise ConfigError(field, "must not be empty")
294
- return value
295
-
296
-
297
- def validate_android_version(value, field="sdk.androidVersion"):
298
- if not isinstance(value, str) or not re.fullmatch(ANDROID_VERSION_RE, value.strip()):
299
- raise ConfigError(field, f"must match {ANDROID_VERSION_RE}")
300
- return value.strip()
301
-
302
-
303
- def validate_version_code(value, field="version.code"):
304
- if isinstance(value, bool) or not isinstance(value, int) or value <= 0 or value > 2147483647:
305
- raise ConfigError(field, "must be a positive 32-bit integer")
306
- return value
307
-
308
-
309
- def is_positive_int(value):
310
- return not isinstance(value, bool) and isinstance(value, int) and value > 0
311
-
312
-
313
- def validate_ios_package_url(value, field="sdk.iosPackageUrl"):
314
- if value is None or not isinstance(value, str) or value.strip() == "":
315
- raise ConfigError(field, "must be an HTTPS URL or spmMode must be mock")
316
- parsed = urlparse(value)
317
- if parsed.scheme != "https" or not parsed.netloc:
318
- raise ConfigError(field, "must be an HTTPS URL")
319
- host = (parsed.hostname or "").lower()
320
- if (
321
- host in {"localhost", "127.0.0.1", "0.0.0.0", "::1", "example.com", "example.org"}
322
- or host.endswith(".localhost")
323
- or host.endswith(".local")
324
- or host.endswith(".example.com")
325
- or host.endswith(".example.org")
326
- or "example.invalid" in host
327
- ):
328
- raise ConfigError(field, "must not be a placeholder or local URL")
329
- try:
330
- address = ipaddress.ip_address(host)
331
- except ValueError:
332
- address = None
333
- if address and (address.is_private or address.is_loopback or address.is_link_local or address.is_unspecified):
334
- raise ConfigError(field, "must not be a placeholder or local URL")
335
- return value
336
-
337
-
338
- def validate_ios_version(value, field="sdk.iosVersion"):
339
- if not isinstance(value, str) or not re.fullmatch(IOS_VERSION_PATTERN, value):
340
- raise ConfigError(field, f"must match {IOS_VERSION_PATTERN}")
341
- return value
342
-
343
-
344
- def validate_sdk_namespace(raw_sdk, field):
345
- """只做**形状**校验(键名/标量),值的合法性留给按项目的 scope。"""
346
- sdk = require_mapping(raw_sdk, field)
347
- for key, value in sdk.items():
348
- if not isinstance(key, str):
349
- raise ConfigError(field, "keys must be strings")
350
- if key not in SDK_KEYS:
351
- raise ConfigError(f"{field}.{key}", "unknown key")
352
- if isinstance(value, (dict, list)):
353
- raise ConfigError(f"{field}.{key}", "must be a scalar")
354
- return sdk
355
-
356
-
357
- def validate_version_namespace(raw_version, field):
358
- version = require_mapping(raw_version, field)
359
- for key in version:
360
- if key not in VERSION_KEYS:
361
- raise ConfigError(f"{field}.{key}", "unknown key")
362
- return version
363
-
364
-
365
- def resolve_version(version, field):
366
- """把一份 version 对象归一成 {name, code}。整值替换后的兜底默认值在这里生效。"""
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)
370
- version_name = require_string(version_name, f"{field}.name")
371
- version_code = validate_version_code(version.get("code", DEFAULT_VERSION_CODE), f"{field}.code")
372
- return {"name": version_name, "code": version_code}
373
-
374
-
375
- def validate_cli_owned_keys(raw):
376
- # `orgId` 归 supercli。模板只做类型校验,保证站点侧的 schema 变更永远不会打断 App 构建。
377
- if "orgId" in raw and not isinstance(raw["orgId"], str):
378
- raise ConfigError("orgId", "must be a string")
379
-
380
-
381
- def normalize_project_dir(value, field):
382
- """项目目录:相对、无 `..`、至少一段、不吞工作空间根。"""
383
- raw = require_string(value, field)
384
- if "\\" in raw:
385
- raise ConfigError(field, "must use forward slashes")
386
- if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
387
- raise ConfigError(field, "must be relative to the workspace root")
388
- parts = [part for part in raw.split("/") if part != ""]
389
- if not parts:
390
- raise ConfigError(field, "must name a subdirectory of the workspace root")
391
- for part in parts:
392
- if part in (".", ".."):
393
- raise ConfigError(field, "must not contain . or .. segments")
394
- return "/".join(parts)
395
-
396
-
397
- def assert_dirs_are_disjoint(entries):
398
- """dir 全局唯一,且不得互为祖先。
399
-
400
- 这是**工作空间级**不变式,与选了哪个项目无关:两个项目共用一个目录,
401
- 第二次注入会静默覆盖第一次的 managed config。
402
- """
403
- seen = {}
404
- for index, entry in entries:
405
- directory = entry["dir"]
406
- if directory in seen:
407
- raise ConfigError(
408
- f"projects[{index}].dir",
409
- f"duplicates projects[{seen[directory]}].dir ({directory}); every project needs its own directory",
410
- )
411
- seen[directory] = index
412
- ordered = sorted(seen.items(), key=lambda item: item[0].split("/"))
413
- for (first, first_index), (second, second_index) in zip(ordered, ordered[1:]):
414
- first_parts = first.split("/")
415
- second_parts = second.split("/")
416
- if second_parts[: len(first_parts)] == first_parts:
417
- raise ConfigError(
418
- f"projects[{second_index}].dir",
419
- f"{second} is nested inside projects[{first_index}].dir ({first}); project directories must be disjoint",
420
- )
421
-
422
-
423
- def read_project_shape(entry, index):
424
- """只读出选择所需的最小信息(type / dir),其余校验按 selected 分流。"""
425
- if not isinstance(entry, dict):
426
- raise ConfigError(f"projects[{index}]", "must be a JSON object")
427
- project_type = entry.get("type")
428
- if project_type is None:
429
- raise ConfigError(f"projects[{index}].type", f"is required; one of {', '.join(PROJECT_TYPES)}")
430
- project_type = require_string(project_type, f"projects[{index}].type")
431
- directory = normalize_project_dir(entry.get("dir"), f"projects[{index}].dir")
432
- return {"index": index, "type": project_type, "dir": directory, "raw": entry}
433
-
434
-
435
- def select_project_shapes(shapes, platform="all", project=None):
436
- selected = shapes
437
- if project is not None:
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]
442
- if not selected:
443
- known = ", ".join(shape["dir"] for shape in shapes) or "<none>"
444
- raise ConfigError("--project", f"no project with dir {wanted}; configured directories: {known}")
445
- if platform != "all" and selected[0]["type"] != platform:
446
- raise ConfigError("--project", f"{wanted} is a {selected[0]['type']} project, not {platform}")
447
- if platform != "all":
448
- selected = [shape for shape in selected if shape["type"] == platform]
449
- return sorted(selected, key=lambda shape: (TYPE_ORDER.get(shape["type"], len(TYPE_ORDER)), shape["index"]))
450
-
451
-
452
- def validate_project(shape, root_name, workspace_version, workspace_sdk):
453
- entry = shape["raw"]
454
- index = shape["index"]
455
- directory = shape["dir"]
456
- project_type = shape["type"]
457
- label = f"projects[{directory}]"
458
-
459
- if project_type not in PROJECT_TYPES:
460
- raise ConfigError(f"projects[{index}].type", f"unknown project type {project_type!r}; expected one of {', '.join(PROJECT_TYPES)}")
461
-
462
- allowed = COMMON_PROJECT_KEYS | TYPE_PROJECT_KEYS[project_type]
463
- aliases = PROJECT_KEY_ALIASES[project_type]
464
- for key in entry:
465
- if key in aliases:
466
- raise ConfigError(f"{label}.{aliases[key]}", f"use canonical {aliases[key]}")
467
- if key not in allowed:
468
- raise ConfigError(f"{label}.{key}", f"unknown key for {project_type} projects")
469
-
470
- # version / sdk:workspace 级默认 + 项目级覆盖,**整值替换,不做深合并**。
471
- if "version" in entry:
472
- override = validate_version_namespace(entry.get("version"), f"{label}.version")
473
- missing = sorted(VERSION_KEYS - set(override))
474
- if missing:
475
- raise ConfigError(
476
- f"{label}.version",
477
- "replaces the workspace version wholesale (values are not merged), so it must set both "
478
- f"name and code; missing: {', '.join(missing)}",
479
- )
480
- version = resolve_version(override, f"{label}.version")
481
- else:
482
- version = dict(workspace_version)
483
-
484
- sdk = dict(validate_sdk_namespace(entry.get("sdk"), f"{label}.sdk")) if "sdk" in entry else dict(workspace_sdk)
485
-
486
- name = entry.get("name")
487
- if name is not None:
488
- name = require_string(name, f"{label}.name")
489
-
490
- if project_type == "android":
491
- platform_config = validate_android_project(label, entry, name, root_name, sdk)
492
- elif project_type == "ios":
493
- platform_config = validate_ios_project(label, entry, name, root_name, sdk)
494
- else:
495
- platform_config = validate_site_project(label, entry)
496
-
497
- mode = platform_config.get("spmMode", "mock")
498
- projected_sdk = {key: sdk[key] for key in project_sdk(project_type, mode) if key in sdk}
499
-
500
- return {
501
- "type": project_type,
502
- "dir": directory,
503
- "name": name,
504
- "version": version,
505
- "sdk": projected_sdk,
506
- "platformConfig": platform_config,
507
- }
508
-
509
-
510
- def require_project_name(label, name, root_name, project_type, target):
511
- if name is not None and name.strip() != "":
512
- if name != name.strip():
513
- raise ConfigError(f"{label}.name", "must not have leading or trailing whitespace")
514
- if any(ord(char) < 32 for char in name):
515
- raise ConfigError(f"{label}.name", f"must be a {target} without control characters")
516
- return name
517
- hint = (
518
- "the workspace-level name is a description and is never projected as an App label, "
519
- "so it will not be used here"
520
- if root_name is not None
521
- else "it is never derived from spid or from the project directory"
522
- )
523
- raise ConfigError(f"{label}.name", f"is required for {project_type} projects and is the {target}; {hint}")
524
-
525
-
526
- def validate_android_project(label, entry, name, root_name, sdk):
527
- require_project_name(label, name, root_name, "android", "Android app label")
528
- package_name = entry.get("package")
529
- if package_name is None:
530
- raise ConfigError(f"{label}.package", "is required for android projects and is never derived")
531
- package_name = require_string(package_name, f"{label}.package")
532
- if not re.fullmatch(JAVA_PACKAGE_PATTERN, package_name):
533
- raise ConfigError(f"{label}.package", "must be a Java package")
534
- if package_name == ANDROID_NAMESPACE:
535
- raise ConfigError(f"{label}.package", f"must differ from fixed namespace {ANDROID_NAMESPACE}")
536
- validate_android_version(sdk.get("androidVersion"), f"{label}.sdk.androidVersion")
537
- return {"package": package_name}
538
-
539
-
540
- def validate_ios_project(label, entry, name, root_name, sdk):
541
- require_project_name(label, name, root_name, "ios", "iOS display name")
542
- bundle_id = entry.get("bundleId")
543
- if bundle_id is None:
544
- raise ConfigError(f"{label}.bundleId", "is required for ios projects and is never derived")
545
- bundle_id = require_string(bundle_id, f"{label}.bundleId")
546
- if not re.fullmatch(BUNDLE_ID_PATTERN, bundle_id):
547
- raise ConfigError(f"{label}.bundleId", "must be a bundle identifier")
548
-
549
- spm_mode = entry.get("spmMode", "mock")
550
- if not isinstance(spm_mode, str) or spm_mode not in {"mock", "real"}:
551
- raise ConfigError(f"{label}.spmMode", "must be mock or real")
552
- if spm_mode == "mock":
553
- for key in ("iosPackageUrl", "iosVersion"):
554
- if key in sdk:
555
- raise ConfigError(f"{label}.sdk.{key}", "not allowed when spmMode is mock")
556
- else:
557
- validate_ios_package_url(sdk.get("iosPackageUrl"), f"{label}.sdk.iosPackageUrl")
558
- validate_ios_version(sdk.get("iosVersion"), f"{label}.sdk.iosVersion")
559
- return {"bundleId": bundle_id, "spmMode": spm_mode}
560
-
561
-
562
- def validate_site_project(label, entry):
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")
574
- for key in offline:
575
- if key not in SITE_OFFLINE_KEYS:
576
- raise ConfigError(f"{label}.offline.{key}", "unknown key")
577
- host = offline.get("host")
578
- if host is not None:
579
- host = require_string(host, f"{label}.offline.host")
580
- try:
581
- host = normalize_host(host)
582
- except HostValidationError as exc:
583
- raise ConfigError(f"{label}.offline.host", str(exc)) from exc
584
- return {"host": host}
585
-
586
-
587
- def check_root_envelope(raw, config_path=None):
588
- """根信封:退役键 + schemaVersion。定位项目和全量校验都要先过这一关。"""
589
- if not isinstance(raw, dict):
590
- raise ConfigError(CONFIG_FILENAME, "top-level document must be a JSON object")
591
-
592
- for key, reason in RETIRED_ROOT_KEYS.items():
593
- if key in raw:
594
- raise ConfigError(key, reason)
595
-
596
- schema_version = raw.get("schemaVersion")
597
- if isinstance(schema_version, bool) or not isinstance(schema_version, int) or schema_version != CONFIG_SCHEMA_VERSION:
598
- message = f"must be {CONFIG_SCHEMA_VERSION}"
599
- if schema_version == 2 and not isinstance(schema_version, bool):
600
- message += (
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)
605
- )
606
- raise ConfigError("schemaVersion", message)
607
-
608
- for key, reason in RETIRED_V2_ROOT_KEYS.items():
609
- if key in raw:
610
- raise ConfigError(key, reason)
611
-
612
-
613
- def read_project_shapes(raw):
614
- """读出所有项目的 type/dir,并校验工作空间级不变式(目录唯一且互不嵌套)。"""
615
- if "projects" not in raw:
616
- raise ConfigError("projects", "is required; add one with `supercli add <android|ios|site> <dir>`")
617
- entries = raw.get("projects")
618
- if not isinstance(entries, list):
619
- raise ConfigError("projects", "must be an array")
620
- shapes = [read_project_shape(entry, index) for index, entry in enumerate(entries)]
621
- assert_dirs_are_disjoint([(shape["index"], shape) for shape in shapes])
622
- return shapes
623
-
624
-
625
- def no_selection_error(dirs, platform):
626
- if not dirs:
627
- return ConfigError("projects", "is empty; add one with `supercli add <android|ios|site> <dir>`")
628
- scope = f"type {platform}" if platform != "all" else "this workspace"
629
- return ConfigError("--platform", f"no project matches {scope}; configured directories: {', '.join(dirs)}")
630
-
631
-
632
- def resolve_shapes(config_path, platform="all", project=None):
633
- """只回答「该进哪个目录」。
634
-
635
- 🔴 故意**不**做 per-project 全量校验:build_<type>.sh 只是想定位自己的项目目录,
636
- 拿这个问题去触发 bundleId/package 校验,会把 helper 自己更精确的诊断
637
- (比如「managed config 里的 bundleId 缺失」)永远挡在后面。
638
- """
639
- raw = load_config(config_path)
640
- check_root_envelope(raw, config_path)
641
- shapes = read_project_shapes(raw)
642
- selected = select_project_shapes(shapes, platform, project)
643
- if not selected:
644
- raise no_selection_error([shape["dir"] for shape in shapes], platform)
645
- return selected
646
-
647
-
648
- def validate_config(raw, selected=None, project=None, config_path=None):
649
- """校验根配置。
650
-
651
- 🔴 `selected`(平台/类型)与 `project`(目录)现在**真的**限定 per-project 校验的范围:
652
- v2 里 selected 只影响 web.host 归一化,iOS spmMode、android.package 格式、sdk.* 一律
653
- 无条件执行 —— 一个坏的 iosPackageUrl 会让 `--platform android` 也失败。v3 起所有
654
- per-project 校验一律 scope 到 selected,这是**有意的放宽**。
655
- 工作空间级不变式(schemaVersion / spid / dir 唯一性)仍然无条件执行。
656
- """
657
- platform = selected or "all"
658
- check_root_envelope(raw, config_path)
659
- validate_cli_owned_keys(raw)
660
-
661
- spid = require_string(raw.get("spid"), "spid")
662
- if not re.fullmatch(SPID_PATTERN, spid):
663
- raise ConfigError("spid", f"must match ^{SPID_PATTERN}$")
664
-
665
- root_name = raw.get("name")
666
- if root_name is not None:
667
- root_name = require_string(root_name, "name")
668
-
669
- # workspace 级 version/sdk 的**形状**无条件校验(它是工作空间级字段,与选谁无关);
670
- # sdk 里各个值的合法性(androidVersion 格式、real 模式的 url/version)因类型而异,
671
- # 留给按项目的 scope。
672
- workspace_version = resolve_version(validate_version_namespace(raw.get("version"), "version"), "version")
673
- workspace_sdk = validate_sdk_namespace(raw.get("sdk"), "sdk")
674
-
675
- shapes = read_project_shapes(raw)
676
- selected_shapes = select_project_shapes(shapes, platform, project)
677
- projects = [validate_project(shape, root_name, workspace_version, workspace_sdk) for shape in selected_shapes]
678
-
679
- return {
680
- "schemaVersion": CONFIG_SCHEMA_VERSION,
681
- "engineVersion": ENGINE_VERSION,
682
- "spid": spid,
683
- "name": root_name,
684
- "projects": projects,
685
- "projectDirs": [shape["dir"] for shape in shapes],
686
- }
687
-
688
-
689
- def load_and_validate(config_path, selected=None, project=None):
690
- return validate_config(load_config(config_path), selected, project, config_path=config_path)
691
-
692
-
693
- def require_selection(normalized, platform, project):
694
- if normalized["projects"]:
695
- return normalized["projects"]
696
- raise no_selection_error(normalized["projectDirs"], platform)
697
-
698
-
699
- def target_path(root, project):
700
- return Path(root) / project["dir"] / ".supersdk" / "managed" / "config.json"
701
-
702
-
703
- def project_sdk(platform, mode="mock"):
704
- if platform not in SDK_PROJECTION:
705
- raise ConfigError("platform", f"unknown platform: {platform}")
706
- if mode not in SDK_PROJECTION[platform]:
707
- raise ConfigError("sdk", f"unknown projection mode: {mode}")
708
- return list(SDK_PROJECTION[platform][mode])
709
-
710
-
711
- def target_content(normalized, project):
712
- return {
713
- "managed_by": MANAGED_BY,
714
- "schema_version": MANAGED_CONFIG_SCHEMA_VERSION,
715
- "engine_version": ENGINE_VERSION,
716
- "spid": normalized["spid"],
717
- "name": project["name"],
718
- "platform": project["type"],
719
- "dir": project["dir"],
720
- "version": project["version"],
721
- "sdk": project["sdk"],
722
- "platform_config": project["platformConfig"],
723
- }
724
-
725
-
726
- def test_fail_point(name):
727
- # 原子写回滚的内部回归钩子,不是对外功能。
728
- if os.environ.get("SUPERSDK_TEMPLATE_TEST_MODE") != "1":
729
- return 0
730
- raw = os.environ.get(name, "0") or "0"
731
- try:
732
- value = int(raw)
733
- except ValueError as exc:
734
- raise ConfigError(name, "must be an integer") from exc
735
- if value < 0:
736
- raise ConfigError(name, "must be non-negative")
737
- return value
738
-
739
-
740
- def is_managed_or_empty(path):
741
- if not path.exists():
742
- return True
743
- if path.stat().st_size == 0:
744
- return True
745
- try:
746
- return json.loads(path.read_text(encoding="utf-8")).get("managed_by") == MANAGED_BY
747
- except OSError as exc:
748
- raise ConfigError(str(path), f"cannot inspect target: {exc}") from exc
749
- except (json.JSONDecodeError, UnicodeDecodeError, AttributeError):
750
- return False
751
-
752
-
753
- def build_write_plan(root, normalized):
754
- return [
755
- (target_path(root, project), json.dumps(target_content(normalized, project), indent=2, sort_keys=True) + "\n")
756
- for project in normalized["projects"]
757
- ]
758
-
759
-
760
- def inject(root, config, platform, project, force, dry_run):
761
- root_path = Path(root)
762
- normalized = load_and_validate(config, platform, project)
763
- require_selection(normalized, platform, project)
764
- plan = build_write_plan(root, normalized)
765
- if dry_run:
766
- refused = [str(path) for path, _ in plan if not force and not is_managed_or_empty(path)]
767
- print(
768
- json.dumps(
769
- {
770
- "would_abort": bool(refused),
771
- "would_write": [] if refused else [str(path) for path, _ in plan],
772
- "would_refuse": refused,
773
- },
774
- indent=2,
775
- sort_keys=True,
776
- )
777
- )
778
- return
779
- refused = [str(path) for path, _ in plan if not force and not is_managed_or_empty(path)]
780
- if refused:
781
- raise ConfigError("refuse", "refuse overwrite unmanaged file(s): " + ", ".join(refused))
782
-
783
- temp_files = []
784
- backups = {}
785
- replaced = []
786
- created_dirs = set()
787
- run_id = f"{os.getpid()}.{uuid.uuid4().hex}"
788
- fail_after = test_fail_point("SUPERSDK_TEMPLATE_TEST_FAIL_REPLACE_AFTER")
789
- fail_at = test_fail_point("SUPERSDK_TEMPLATE_TEST_FAIL_REPLACE_AT")
790
- try:
791
- for path, content in plan:
792
- directory = path.parent
793
- while directory != root_path and directory != directory.parent:
794
- if not directory.exists():
795
- created_dirs.add(directory)
796
- directory = directory.parent
797
- path.parent.mkdir(parents=True, exist_ok=True)
798
- temp = path.with_name(f".{path.name}.tmp.{run_id}")
799
- if temp.exists():
800
- raise OSError(f"sidecar already exists: {temp}")
801
- temp.write_text(content, encoding="utf-8")
802
- temp_files.append(temp)
803
-
804
- for index, (path, _) in enumerate(plan, start=1):
805
- backup = path.with_name(f".{path.name}.bak.{run_id}")
806
- if backup.exists():
807
- raise OSError(f"sidecar already exists: {backup}")
808
- if path.exists():
809
- os.replace(path, backup)
810
- backups[path] = backup
811
- else:
812
- backups[path] = None
813
- if fail_at and index >= fail_at:
814
- raise OSError("simulated replace syscall failure")
815
- os.replace(temp_files[index - 1], path)
816
- replaced.append(path)
817
- if fail_after and index >= fail_after:
818
- raise OSError("simulated replace failure")
819
- except Exception as exc:
820
- rollback_errors = []
821
-
822
- def remember(action, target, error):
823
- rollback_errors.append(f"{action} {target}: {error}")
824
-
825
- for path in replaced:
826
- try:
827
- if path.exists():
828
- path.unlink()
829
- except Exception as rollback_exc:
830
- remember("remove", path, rollback_exc)
831
- for path, backup in backups.items():
832
- try:
833
- if backup is not None and backup.exists():
834
- os.replace(backup, path)
835
- except Exception as rollback_exc:
836
- remember("restore", path, rollback_exc)
837
- for temp in temp_files:
838
- try:
839
- if temp.exists():
840
- temp.unlink()
841
- except Exception as rollback_exc:
842
- remember("remove", temp, rollback_exc)
843
- for directory in sorted(created_dirs, key=lambda item: len(str(item)), reverse=True):
844
- try:
845
- directory.rmdir()
846
- except OSError:
847
- pass
848
- if rollback_errors:
849
- print(f"write failed; rollback incomplete: {exc}; {'; '.join(rollback_errors)}", file=sys.stderr)
850
- else:
851
- print(f"write failed; rolled back: {exc}", file=sys.stderr)
852
- raise SystemExit(1)
853
-
854
- cleanup_errors = []
855
- for backup in backups.values():
856
- if backup is not None and backup.exists():
857
- try:
858
- backup.unlink()
859
- except Exception as cleanup_exc:
860
- cleanup_errors.append(f"remove {backup}: {cleanup_exc}")
861
- if cleanup_errors:
862
- print(f"warning: backup cleanup incomplete: {'; '.join(cleanup_errors)}", file=sys.stderr)
863
- print(json.dumps({"written": [str(path) for path, _ in plan], "skipped": [], "refused": []}, indent=2, sort_keys=True))
864
-
865
-
866
- def print_plan(root, config, platform, project):
867
- normalized = load_and_validate(config, platform, project)
868
- require_selection(normalized, platform, project)
869
- for item in normalized["projects"]:
870
- helper = Path(root) / "scripts" / ("build_" + item["type"] + ".sh")
871
- print(f"platform={item['type']} dir={item['dir']} helper={helper} mode=plan")
872
-
873
-
874
- def print_resolve(config, platform, project):
875
- """给 build_<type>.sh 用:把「哪个项目」定下来,零歧义或者 fail-closed。"""
876
- print(resolve_single(config, platform, project))
877
-
878
-
879
- def resolve_single(config, platform, project):
880
- projects = resolve_shapes(config, platform, project)
881
- if len(projects) > 1:
882
- dirs = ", ".join(item["dir"] for item in projects)
883
- raise ConfigError(
884
- "--project",
885
- f"{len(projects)} {platform} projects are configured ({dirs}); pass --project <dir> to pick one",
886
- )
887
- return projects[0]["dir"]
888
-
889
-
890
- def engine_check(root, config):
891
- """比对已落盘 managed config 里的引擎版本与本脚本常量,不一致只 warn,不阻断。"""
892
- try:
893
- normalized = load_and_validate(config)
894
- except ConfigError:
895
- # 真正的命令会给出更好的诊断;这里保持安静,不抢话。
896
- return
897
- stale = []
898
- for directory in normalized["projectDirs"]:
899
- managed = Path(root) / directory / ".supersdk" / "managed" / "config.json"
900
- if not managed.is_file():
901
- continue
902
- try:
903
- payload = json.loads(managed.read_text(encoding="utf-8"))
904
- except (OSError, json.JSONDecodeError, UnicodeDecodeError):
905
- continue
906
- if payload.get("managed_by") != MANAGED_BY:
907
- continue
908
- recorded = payload.get("engine_version")
909
- if recorded != ENGINE_VERSION:
910
- stale.append((directory, recorded))
911
- if stale:
912
- details = ", ".join(f"{directory} (engine {recorded or 'unrecorded'})" for directory, recorded in stale)
913
- print(
914
- f"warning: managed config was produced by a different template engine than {ENGINE_VERSION}: {details}. "
915
- "Re-run ./super_build.sh --build to reproject it.",
916
- file=sys.stderr,
917
- )
918
-
919
-
920
- def order_keys(document, order):
921
- """按固定键序重排;未知键按原有相对顺序追加在末尾(未知键必须原样保留)。
922
-
923
- 累加器用 `dict` 之外的 `Object.create(null)` 等价物:Python 里普通 dict 没有原型
924
- 污染问题,但「未知键原样保留」这条纪律与 CLI 侧完全一致。
925
- """
926
- ordered = {}
927
- for key in order:
928
- if key in document:
929
- ordered[key] = document[key]
930
- for key in document:
931
- if key not in order:
932
- ordered[key] = document[key]
933
- return ordered
934
-
935
-
936
- def serialize_config(document):
937
- out = {}
938
- for key, value in order_keys(document, ROOT_KEY_ORDER).items():
939
- if key in NESTED_KEY_ORDER and isinstance(value, dict):
940
- out[key] = order_keys(value, NESTED_KEY_ORDER[key])
941
- elif key == "projects" and isinstance(value, list):
942
- out[key] = [serialize_project(item) for item in value]
943
- else:
944
- out[key] = value
945
- return json.dumps(out, indent=2, ensure_ascii=False) + "\n"
946
-
947
-
948
- def serialize_project(entry):
949
- if not isinstance(entry, dict):
950
- return entry
951
- out = {}
952
- for key, value in order_keys(entry, PROJECT_KEY_ORDER).items():
953
- if key in NESTED_KEY_ORDER and isinstance(value, dict):
954
- out[key] = order_keys(value, NESTED_KEY_ORDER[key])
955
- elif key == "deploy" and isinstance(value, list):
956
- out[key] = [order_keys(item, DEPLOY_KEY_ORDER) if isinstance(item, dict) else item for item in value]
957
- else:
958
- out[key] = value
959
- return out
960
-
961
-
962
- def migrate_document(raw, config_dir):
963
- """v2 -> v3,零信息损失。
964
-
965
- 🔴 结构性事实:v2 的模板目录就是 `android/ ios/ web/`,v3 可以原样保留
966
- (`{"type": "site", "dir": "web"}`)—— **迁移不移动任何文件**,只改配置。
967
- v2 的 `sites[]` 每条 `{slug,name,env,dir}` 逐字搬进 site 项目的 `deploy[]`。
968
- """
969
- if not isinstance(raw, dict):
970
- raise ConfigError(CONFIG_FILENAME, "top-level document must be a JSON object")
971
- version = raw.get("schemaVersion")
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
- )
999
-
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}
1006
- for key in ("spid", "orgId", "name", "version", "sdk"):
1007
- if key in raw:
1008
- migrated[key] = raw[key]
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
1075
- text = serialize_config(migrated)
1076
- if dry_run:
1077
- sys.stdout.write(text)
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)
1085
- try:
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
1093
- return 0
1094
-
1095
-
1096
- def main(argv):
1097
- parser = argparse.ArgumentParser(description="SuperSDK workspace schema and injection helper")
1098
- sub = parser.add_subparsers(dest="command", required=True)
1099
-
1100
- def add_selection(command):
1101
- command.add_argument("--platform", choices=["all", *PROJECT_TYPES], default="all")
1102
- command.add_argument("--project", default=None, help="Project directory relative to the workspace root")
1103
-
1104
- validate = sub.add_parser("validate")
1105
- validate.add_argument("--config", required=True)
1106
- add_selection(validate)
1107
-
1108
- plan = sub.add_parser("plan")
1109
- plan.add_argument("--root", required=True)
1110
- plan.add_argument("--config", required=True)
1111
- add_selection(plan)
1112
-
1113
- inject_cmd = sub.add_parser("inject")
1114
- inject_cmd.add_argument("--root", required=True)
1115
- inject_cmd.add_argument("--config", required=True)
1116
- add_selection(inject_cmd)
1117
- inject_cmd.add_argument("--force", action="store_true")
1118
- inject_cmd.add_argument("--dry-run", action="store_true")
1119
-
1120
- resolve = sub.add_parser("resolve")
1121
- resolve.add_argument("--config", required=True)
1122
- add_selection(resolve)
1123
-
1124
- check = sub.add_parser("engine-check")
1125
- check.add_argument("--root", required=True)
1126
- check.add_argument("--config", required=True)
1127
-
1128
- migrate_cmd = sub.add_parser("migrate")
1129
- migrate_cmd.add_argument("--config", required=True)
1130
- migrate_cmd.add_argument("--dry-run", action="store_true")
1131
-
1132
- args = parser.parse_args(argv)
1133
- try:
1134
- if args.command == "validate":
1135
- normalized = load_and_validate(args.config, args.platform, args.project)
1136
- # 🔴 显式选择必须 fail closed,与 plan/inject/resolve 同一语义:被问到
1137
- # 「android 这边配置对不对」时,回一句 `"projects": []` + exit 0 是错的信号。
1138
- # `--project` 已经在 select_project_shapes 里挡住了,这里补的是 `--platform`。
1139
- # `--platform all` 不在此列:空 projects[] 是 `supercli init` 之后、`add` 之前
1140
- # 的合法形态,「还没有项目」不是「配置有问题」。
1141
- if args.platform != "all":
1142
- require_selection(normalized, args.platform, args.project)
1143
- print(json.dumps(normalized, indent=2, sort_keys=True))
1144
- elif args.command == "plan":
1145
- print_plan(args.root, args.config, args.platform, args.project)
1146
- elif args.command == "inject":
1147
- inject(args.root, args.config, args.platform, args.project, args.force, args.dry_run)
1148
- elif args.command == "resolve":
1149
- print_resolve(args.config, args.platform, args.project)
1150
- elif args.command == "engine-check":
1151
- engine_check(args.root, args.config)
1152
- elif args.command == "migrate":
1153
- return migrate(args.config, args.dry_run)
1154
- except ConfigError as exc:
1155
- print(str(exc), file=sys.stderr)
1156
- return 1
1157
- return 0
1158
-
1159
-
1160
- if __name__ == "__main__":
1161
- raise SystemExit(main(sys.argv[1:]))