@supersdk/supercli 0.2.1-staging.21 → 0.3.0-staging.23

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 (53) hide show
  1. package/dist/cli.js +4 -2
  2. package/dist/cli.js.map +1 -1
  3. package/dist/commands/add.js +519 -0
  4. package/dist/commands/add.js.map +1 -0
  5. package/dist/commands/init.js +234 -0
  6. package/dist/commands/init.js.map +1 -0
  7. package/dist/commands/publishSite.js +354 -71
  8. package/dist/commands/publishSite.js.map +1 -1
  9. package/dist/config/appConfig.js +160 -45
  10. package/dist/config/appConfig.js.map +1 -1
  11. package/dist/publish/siteConfig.js +278 -63
  12. package/dist/publish/siteConfig.js.map +1 -1
  13. package/dist/template/README.md +144 -85
  14. package/dist/template/android/app/build.gradle.kts +0 -3
  15. package/dist/template/android/app/src/main/java/com/supersdk/simple/EnvironmentStore.java +41 -0
  16. package/dist/template/android/app/src/main/java/com/supersdk/simple/MainActivity.java +57 -4
  17. package/dist/template/android/app/src/main/java/com/supersdk/simple/SimpleApplication.java +3 -1
  18. package/dist/template/android/gradle/supersdk-config-reader.gradle +5 -3
  19. package/dist/template/android/supersdk-default.config.json +4 -3
  20. package/dist/template/ios/Sources/App/EnvironmentStore.swift +35 -0
  21. package/dist/template/ios/Sources/App/SimpleSDKBootstrap.swift +2 -1
  22. package/dist/template/ios/Sources/App/SimpleSDKProbe.swift +15 -0
  23. package/dist/template/ios/Sources/App/SimpleViewController.swift +52 -8
  24. package/dist/template/ios/Tests/SimpleAppTests/SimpleSDKInitializationTests.swift +12 -1
  25. package/dist/template/scripts/android_snapshot_canary.py +17 -8
  26. package/dist/template/scripts/build_android.sh +36 -9
  27. package/dist/template/scripts/build_ios.sh +63 -24
  28. package/dist/template/scripts/build_site.sh +43 -0
  29. package/dist/template/scripts/lib/workspace.sh +43 -0
  30. package/dist/template/scripts/serve_web.py +26 -9
  31. package/dist/template/scripts/super_build_orchestrator.py +49 -28
  32. package/dist/template/scripts/supersdk_template.py +759 -240
  33. package/dist/template/scripts/web_package.py +44 -20
  34. package/dist/template/super_build.sh +40 -12
  35. package/dist/template/supersdk.json +25 -13
  36. package/dist/template/template_manifest.json +25 -0
  37. package/dist/template/web/src/css/style.css +28 -0
  38. package/dist/template/web/src/index.html +8 -0
  39. package/dist/template/web/src/js/app.js +92 -19
  40. package/dist/workspace/config.js +440 -0
  41. package/dist/workspace/config.js.map +1 -0
  42. package/dist/workspace/identity.js +106 -0
  43. package/dist/workspace/identity.js.map +1 -0
  44. package/dist/workspace/interactive.js +96 -0
  45. package/dist/workspace/interactive.js.map +1 -0
  46. package/dist/workspace/template.js +357 -0
  47. package/dist/workspace/template.js.map +1 -0
  48. package/package.json +1 -1
  49. package/dist/commands/createApp.js +0 -448
  50. package/dist/commands/createApp.js.map +0 -1
  51. package/dist/createApp/copyTemplate.js +0 -561
  52. package/dist/createApp/copyTemplate.js.map +0 -1
  53. package/dist/template/scripts/build_web.sh +0 -12
@@ -14,71 +14,152 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
14
14
  from web_host_validator import HostValidationError, normalize_host
15
15
 
16
16
 
17
- MANAGED_BY = "supersdk-template"
18
- # Managed projections under <platform>/.supersdk/managed/config.json keep their own
19
- # snake_case `schema_version`; it is a different contract from the root config file.
20
- MANAGED_CONFIG_SCHEMA_VERSION = 2
21
- MANAGED_SCHEMA_VERSION = MANAGED_CONFIG_SCHEMA_VERSION
22
- MANAGED_CONFIG_KEYS = ("managed_by", "schema_version", "spid", "environment", "name", "platform", "version", "sdk", "platform_config")
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
23
 
24
- # Root project config: one human+machine writable standard JSON file at the repo root.
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` 所在目录即工作空间根。
25
42
  CONFIG_FILENAME = "supersdk.json"
26
- CONFIG_SCHEMA_VERSION = 2
43
+ CONFIG_SCHEMA_VERSION = 3
27
44
  LEGACY_CONFIG_FILENAMES = ("supersdk.yaml", "supersdk.yml", "super-site.yml")
28
- # Retired root keys keep a targeted diagnostic; every other unknown root key is
29
- # preserved and ignored so CLI-owned and hand-written fields never break a build.
30
- RETIRED_ROOT_KEYS = {
31
- "schema_version": f"retired schema v1 key; use camelCase schemaVersion: {CONFIG_SCHEMA_VERSION}",
32
- "app_id": "retired key; rename it to spid",
33
- }
34
45
 
35
- ANDROID_NAMESPACE = "com.supersdk.simple"
36
- ANDROID_VERSION_RE = r"^[0-9]+\.[0-9]+\.[0-9]+(?:[-.][A-Za-z0-9]+)*$"
37
- PLATFORMS = ("android", "ios", "web")
38
- NAMESPACE_KEYS = {
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 = {
39
56
  "android": {"package"},
40
57
  "ios": {"bundleId", "spmMode"},
41
- "web": {"host"},
42
- "version": {"name", "code"},
58
+ "site": {"deploy", "offline"},
43
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"}
44
68
  SDK_KEYS = {"androidVersion", "iosPackageUrl", "iosVersion"}
45
- IOS_VERSION_PATTERN = r"^[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?$"
46
- SPID_PATTERN = r"[a-z0-9]{8}"
47
- ENVIRONMENT_PATTERN = r"[a-z0-9]{1,10}"
48
- BUNDLE_ID_PATTERN = r"[A-Za-z0-9][A-Za-z0-9-]*(\.[A-Za-z0-9][A-Za-z0-9-]*)+"
49
69
  SDK_PROJECTION = {
50
70
  "android": {"mock": ("androidVersion",), "real": ("androidVersion",)},
51
71
  "ios": {"mock": (), "real": ("iosPackageUrl", "iosVersion")},
52
- "web": {"mock": (), "real": ()},
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',
53
104
  }
54
105
 
55
- # Every required field is present on purpose: a migration hint that omits one is
56
- # a dead end for whoever copies it.
106
+ # 每个必填字段都在:少一个字段的迁移提示,对照抄的人就是死路。
57
107
  MIGRATION_TEMPLATE = """{
58
- "schemaVersion": 2,
108
+ "schemaVersion": 3,
59
109
  "spid": "demo0001",
60
110
  "name": "SuperSDK Simple",
61
- "environment": "prod",
62
- "android": {
63
- "package": "com.example.app"
64
- },
65
- "ios": {
66
- "bundleId": "com.example.app",
67
- "spmMode": "mock"
68
- },
69
- "web": {
70
- "host": "app.example.com"
71
- },
72
111
  "version": {
73
112
  "name": "1.0.0",
74
113
  "code": 1
75
114
  },
76
115
  "sdk": {
77
116
  "androidVersion": "1.0.0.54-SNAPSHOT"
78
- }
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
+ ]
79
141
  }
80
142
  """
81
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
+
82
163
 
83
164
  class ConfigError(Exception):
84
165
  def __init__(self, field, message):
@@ -87,16 +168,26 @@ class ConfigError(Exception):
87
168
  self.message = message
88
169
 
89
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
+
90
181
  def config_file_state(target_path):
91
- """Classify an existing supersdk.json so the hint never overwrites real values.
182
+ """判定已存在的 supersdk.json,让提示永远不会覆盖真值。
92
183
 
93
- Returns ("missing" | "valid" | "invalid", reason). It parses the target directly
94
- instead of going through load_config(), which would re-trigger the legacy scan.
184
+ 返回 ("missing" | "valid" | "invalid", reason)。直接解析目标文件,不走 load_config(),
185
+ 否则会再次触发 legacy 扫描。
95
186
  """
96
187
  if not target_path.is_file():
97
188
  return "missing", ""
98
189
  try:
99
- validate_config(read_config_document(target_path))
190
+ validate_config(read_config_document(target_path), config_path=target_path)
100
191
  except ConfigError as exc:
101
192
  return "invalid", exc.message
102
193
  return "valid", ""
@@ -112,8 +203,8 @@ def migration_hint(legacy_path, target_path):
112
203
  )
113
204
  state, reason = config_file_state(target_path)
114
205
  if state == "valid":
115
- # The only safe action here: the real config already exists, so emitting a
116
- # `cat >` skeleton would replace live spid/package/bundleId/host with defaults.
206
+ # 这里唯一安全的动作:真实配置已经在位,发 `cat >` 骨架会把 spid/package/bundleId/host
207
+ # 全部替换成默认值。
117
208
  return (
118
209
  header
119
210
  + f"your {target_path} is already in place and valid, so nothing needs to be written; "
@@ -150,13 +241,13 @@ def reject_duplicate_keys(pairs):
150
241
 
151
242
 
152
243
  def reject_json_constant(name):
153
- # stdlib json accepts NaN/Infinity/-Infinity; JSON.parse in supercli does not.
154
- # Both sides must read the same file the same way, so reject them here too.
244
+ # stdlib json 接受 NaN/Infinity/-Infinity,supercli 的 JSON.parse 不接受。
245
+ # 两边必须以同一种方式读同一个文件,所以这里也拒。
155
246
  raise ConfigError(CONFIG_FILENAME, f"{name} is not standard JSON; use a number, string, or null")
156
247
 
157
248
 
158
249
  def read_config_document(config_path):
159
- """Read and parse one config file. No legacy scanning, so it is reentrant."""
250
+ """读并解析一个配置文件。不做 legacy 扫描,因此可重入。"""
160
251
  config_path = Path(config_path)
161
252
  if not config_path.is_file():
162
253
  raise ConfigError(CONFIG_FILENAME, f"not found: {config_path}")
@@ -175,7 +266,7 @@ def read_config_document(config_path):
175
266
  def load_config(path):
176
267
  config_path = Path(path)
177
268
  target_path = config_path.parent / CONFIG_FILENAME
178
- # Fail closed on the retired dialects instead of guessing an equivalent JSON doc.
269
+ # 对退役方言硬失败,而不是猜一份等价的 JSON。
179
270
  if config_path.name in LEGACY_CONFIG_FILENAMES or config_path.suffix.lower() in (".yaml", ".yml"):
180
271
  raise ConfigError(config_path.name, migration_hint(config_path, target_path))
181
272
  for legacy_name in LEGACY_CONFIG_FILENAMES:
@@ -203,15 +294,15 @@ def require_string(value, field, allow_empty=False):
203
294
  return value
204
295
 
205
296
 
206
- def validate_android_version(value):
297
+ def validate_android_version(value, field="sdk.androidVersion"):
207
298
  if not isinstance(value, str) or not re.fullmatch(ANDROID_VERSION_RE, value.strip()):
208
- raise ConfigError("sdk.androidVersion", f"must match {ANDROID_VERSION_RE}")
299
+ raise ConfigError(field, f"must match {ANDROID_VERSION_RE}")
209
300
  return value.strip()
210
301
 
211
302
 
212
- def validate_version_code(value):
303
+ def validate_version_code(value, field="version.code"):
213
304
  if isinstance(value, bool) or not isinstance(value, int) or value <= 0 or value > 2147483647:
214
- raise ConfigError("version.code", "must be a positive 32-bit integer")
305
+ raise ConfigError(field, "must be a positive 32-bit integer")
215
306
  return value
216
307
 
217
308
 
@@ -219,32 +310,12 @@ def is_positive_int(value):
219
310
  return not isinstance(value, bool) and isinstance(value, int) and value > 0
220
311
 
221
312
 
222
- def validate_known_namespace(data, namespace):
223
- value = require_mapping(data.get(namespace), namespace)
224
- allowed = NAMESPACE_KEYS[namespace]
225
- for key in value:
226
- if namespace == "ios" and key in {"bundle_id", "bundleID", "bundle-id"}:
227
- raise ConfigError("ios.bundleId", "use canonical ios.bundleId")
228
- if key not in allowed:
229
- raise ConfigError(f"{namespace}.{key}", "unknown key")
230
- return value
231
-
232
-
233
- def validate_ios_spm_mode(ios):
234
- if "spmMode" not in ios:
235
- return "mock"
236
- value = ios.get("spmMode")
237
- if not isinstance(value, str) or value.strip() == "" or value not in {"mock", "real"}:
238
- raise ConfigError("ios.spmMode", "must be mock or real")
239
- return value
240
-
241
-
242
- def validate_ios_package_url(value):
313
+ def validate_ios_package_url(value, field="sdk.iosPackageUrl"):
243
314
  if value is None or not isinstance(value, str) or value.strip() == "":
244
- raise ConfigError("sdk.iosPackageUrl", "must be an HTTPS URL or ios.spmMode must be mock")
315
+ raise ConfigError(field, "must be an HTTPS URL or spmMode must be mock")
245
316
  parsed = urlparse(value)
246
317
  if parsed.scheme != "https" or not parsed.netloc:
247
- raise ConfigError("sdk.iosPackageUrl", "must be an HTTPS URL")
318
+ raise ConfigError(field, "must be an HTTPS URL")
248
319
  host = (parsed.hostname or "").lower()
249
320
  if (
250
321
  host in {"localhost", "127.0.0.1", "0.0.0.0", "::1", "example.com", "example.org"}
@@ -254,180 +325,379 @@ def validate_ios_package_url(value):
254
325
  or host.endswith(".example.org")
255
326
  or "example.invalid" in host
256
327
  ):
257
- raise ConfigError("sdk.iosPackageUrl", "must not be a placeholder or local URL")
328
+ raise ConfigError(field, "must not be a placeholder or local URL")
258
329
  try:
259
330
  address = ipaddress.ip_address(host)
260
331
  except ValueError:
261
332
  address = None
262
333
  if address and (address.is_private or address.is_loopback or address.is_link_local or address.is_unspecified):
263
- raise ConfigError("sdk.iosPackageUrl", "must not be a placeholder or local URL")
334
+ raise ConfigError(field, "must not be a placeholder or local URL")
264
335
  return value
265
336
 
266
337
 
267
- def validate_ios_version(value):
338
+ def validate_ios_version(value, field="sdk.iosVersion"):
268
339
  if not isinstance(value, str) or not re.fullmatch(IOS_VERSION_PATTERN, value):
269
- raise ConfigError("sdk.iosVersion", f"must match {IOS_VERSION_PATTERN}")
340
+ raise ConfigError(field, f"must match {IOS_VERSION_PATTERN}")
270
341
  return value
271
342
 
272
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
+
273
375
  def validate_cli_owned_keys(raw):
274
- # `orgId` and `sites` belong to supercli. The template only type-checks them so a
275
- # site-side schema change can never break an app build, then ignores them wholesale.
376
+ # `orgId` 归 supercli。模板只做类型校验,保证站点侧的 schema 变更永远不会打断 App 构建。
276
377
  if "orgId" in raw and not isinstance(raw["orgId"], str):
277
378
  raise ConfigError("orgId", "must be a string")
278
- if "sites" in raw and not isinstance(raw["sites"], list):
279
- raise ConfigError("sites", "must be an array")
280
379
 
281
380
 
282
- def validate_config(raw, selected=None):
283
- selected = set(selected or PLATFORMS)
284
- if not isinstance(raw, dict):
285
- raise ConfigError(CONFIG_FILENAME, "top-level document must be a JSON object")
286
- for key, reason in RETIRED_ROOT_KEYS.items():
287
- if key in raw:
288
- raise ConfigError(key, reason)
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)
289
395
 
290
- schema_version = raw.get("schemaVersion")
291
- if isinstance(schema_version, bool) or not isinstance(schema_version, int) or schema_version != CONFIG_SCHEMA_VERSION:
292
- raise ConfigError("schemaVersion", f"must be {CONFIG_SCHEMA_VERSION}")
293
396
 
294
- validate_cli_owned_keys(raw)
397
+ def assert_dirs_are_disjoint(entries):
398
+ """dir 全局唯一,且不得互为祖先。
295
399
 
296
- spid = require_string(raw.get("spid"), "spid")
297
- if not re.fullmatch(SPID_PATTERN, spid):
298
- raise ConfigError("spid", f"must match ^{SPID_PATTERN}$")
299
- environment = raw.get("environment", "prod")
300
- environment = require_string(environment, "environment")
301
- if not re.fullmatch(ENVIRONMENT_PATTERN, environment):
302
- raise ConfigError("environment", f"must match ^{ENVIRONMENT_PATTERN}$")
303
-
304
- name = raw.get("name", "SuperSDK Simple")
305
- name = require_string(name, "name")
306
-
307
- android = validate_known_namespace(raw, "android")
308
- ios = validate_known_namespace(raw, "ios")
309
- web = validate_known_namespace(raw, "web")
310
- version = validate_known_namespace(raw, "version")
311
- sdk = require_mapping(raw.get("sdk", {}), "sdk")
312
- for key, value in sdk.items():
313
- if not isinstance(key, str):
314
- raise ConfigError("sdk", "keys must be strings")
315
- if key not in SDK_KEYS:
316
- raise ConfigError(f"sdk.{key}", "unknown key")
317
- if isinstance(value, (dict, list)):
318
- raise ConfigError(f"sdk.{key}", "must be a scalar")
319
- if key == "androidVersion" and value is not None:
320
- validate_android_version(value)
321
-
322
- android_package = android.get("package")
323
- if android_package is not None:
324
- android_package = require_string(android_package, "android.package")
325
- if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+", android_package):
326
- raise ConfigError("android.package", "must be a Java package")
327
-
328
- bundle_id = ios.get("bundleId")
329
- if bundle_id is not None:
330
- bundle_id = require_string(bundle_id, "ios.bundleId")
331
- if not re.fullmatch(BUNDLE_ID_PATTERN, bundle_id):
332
- raise ConfigError("ios.bundleId", "must be a bundle identifier")
333
- spm_mode = validate_ios_spm_mode(ios)
334
- if spm_mode == "mock":
335
- for key in ("iosPackageUrl", "iosVersion"):
336
- if key in sdk:
337
- raise ConfigError(f"sdk.{key}", "not allowed when ios.spmMode is mock")
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")
338
481
  else:
339
- validate_ios_package_url(sdk.get("iosPackageUrl"))
340
- validate_ios_version(sdk.get("iosVersion"))
482
+ version = dict(workspace_version)
341
483
 
342
- web_host = web.get("host")
343
- if web_host is not None and "web" in selected:
344
- web_host = require_string(web_host, "web.host")
345
- try:
346
- web_host = normalize_host(web_host)
347
- except HostValidationError as exc:
348
- raise ConfigError("web.host", str(exc)) from exc
484
+ sdk = dict(validate_sdk_namespace(entry.get("sdk"), f"{label}.sdk")) if "sdk" in entry else dict(workspace_sdk)
349
485
 
350
- version_name = version.get("name", "1.0.0")
351
- if isinstance(version_name, (int, float)) and not isinstance(version_name, bool):
352
- version_name = str(version_name)
353
- version_name = require_string(version_name, "version.name")
354
- version_code = validate_version_code(version.get("code", 1))
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}
355
499
 
356
500
  return {
357
- "schemaVersion": CONFIG_SCHEMA_VERSION,
358
- "spid": spid,
359
- "environment": environment,
501
+ "type": project_type,
502
+ "dir": directory,
360
503
  "name": name,
361
- "platforms": {
362
- "android": {"package": android_package},
363
- "ios": {"bundleId": bundle_id, "spmMode": spm_mode},
364
- "web": {"host": web_host},
365
- },
366
- "version": {"name": version_name, "code": version_code},
367
- "sdk": sdk,
504
+ "version": version,
505
+ "sdk": projected_sdk,
506
+ "platformConfig": platform_config,
368
507
  }
369
508
 
370
509
 
371
- def require_android_config(normalized):
372
- android = normalized["platforms"]["android"]
373
- package_name = android.get("package")
374
- if package_name is None or not isinstance(package_name, str) or package_name.strip() == "":
375
- raise ConfigError("android.package", "required for android platform")
376
- if not re.fullmatch(r"[A-Za-z][A-Za-z0-9_]*(\.[A-Za-z][A-Za-z0-9_]*)+", package_name):
377
- raise ConfigError("android.package", "must be a valid Java package")
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")
378
534
  if package_name == ANDROID_NAMESPACE:
379
- raise ConfigError("android.package", f"must differ from fixed namespace {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}
380
538
 
381
- name = normalized["name"]
382
- if name.strip() == "" or any(ord(char) < 32 for char in name):
383
- raise ConfigError("name", "must be a non-empty Android app label without control characters")
384
- if name != name.strip():
385
- raise ConfigError("name", "must not have leading or trailing whitespace")
386
539
 
387
- version_name = normalized["version"]["name"]
388
- if not isinstance(version_name, str) or version_name.strip() == "":
389
- raise ConfigError("version.name", "must be a non-empty Android versionName")
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")
390
548
 
391
- version_code = normalized["version"]["code"]
392
- validate_version_code(version_code)
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}
393
585
 
394
- android_version = normalized["sdk"].get("androidVersion")
395
- validate_android_version(android_version)
396
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")
397
591
 
398
- def require_ios_config(normalized):
399
- ios = normalized["platforms"]["ios"]
400
- # Symmetric with require_android_config: an iOS app identity is never derived.
401
- # Guessing one would ship a third-party app under the SDK's own reverse domain.
402
- bundle_id = ios.get("bundleId")
403
- if bundle_id is None or not isinstance(bundle_id, str) or bundle_id.strip() == "":
404
- raise ConfigError("ios.bundleId", "required for ios platform")
405
- if not re.fullmatch(BUNDLE_ID_PATTERN, bundle_id):
406
- raise ConfigError("ios.bundleId", "must be a valid bundle identifier")
407
- if ios.get("spmMode", "mock") != "real":
408
- return
409
- for key in SDK_PROJECTION["ios"]["real"]:
410
- require_string(normalized["sdk"].get(key), f"sdk.{key}")
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)
411
611
 
412
612
 
413
- def enforce_platform_contracts(normalized, platform):
414
- for item in selected_platforms(platform):
415
- if item == "android":
416
- require_android_config(normalized)
417
- if item == "ios":
418
- require_ios_config(normalized)
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
419
623
 
420
624
 
421
- def load_and_validate(config_path, selected=None):
422
- return validate_config(load_config(config_path), selected)
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)}")
423
630
 
424
631
 
425
- def selected_platforms(platform):
426
- return list(PLATFORMS) if platform == "all" else [platform]
632
+ def resolve_shapes(config_path, platform="all", project=None):
633
+ """只回答「该进哪个目录」。
427
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")
428
668
 
429
- def target_path(root, platform):
430
- return Path(root) / platform / ".supersdk" / "managed" / "config.json"
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"
431
701
 
432
702
 
433
703
  def project_sdk(platform, mode="mock"):
@@ -438,28 +708,23 @@ def project_sdk(platform, mode="mock"):
438
708
  return list(SDK_PROJECTION[platform][mode])
439
709
 
440
710
 
441
- def project_sdk_values(normalized, platform):
442
- sdk = normalized["sdk"]
443
- mode = normalized["platforms"][platform].get("spmMode", "mock")
444
- return {key: sdk[key] for key in project_sdk(platform, mode) if key in sdk}
445
-
446
-
447
- def target_content(normalized, platform):
711
+ def target_content(normalized, project):
448
712
  return {
449
713
  "managed_by": MANAGED_BY,
450
714
  "schema_version": MANAGED_CONFIG_SCHEMA_VERSION,
715
+ "engine_version": ENGINE_VERSION,
451
716
  "spid": normalized["spid"],
452
- "environment": normalized["environment"],
453
- "name": normalized["name"],
454
- "platform": platform,
455
- "version": normalized["version"],
456
- "sdk": project_sdk_values(normalized, platform),
457
- "platform_config": normalized["platforms"][platform],
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"],
458
723
  }
459
724
 
460
725
 
461
726
  def test_fail_point(name):
462
- # Internal regression-test hook for atomic-write rollback; not a public template feature.
727
+ # 原子写回滚的内部回归钩子,不是对外功能。
463
728
  if os.environ.get("SUPERSDK_TEMPLATE_TEST_MODE") != "1":
464
729
  return 0
465
730
  raw = os.environ.get(name, "0") or "0"
@@ -485,18 +750,18 @@ def is_managed_or_empty(path):
485
750
  return False
486
751
 
487
752
 
488
- def build_write_plan(root, normalized, platform):
489
- enforce_platform_contracts(normalized, platform)
753
+ def build_write_plan(root, normalized):
490
754
  return [
491
- (target_path(root, item), json.dumps(target_content(normalized, item), indent=2, sort_keys=True) + "\n")
492
- for item in selected_platforms(platform)
755
+ (target_path(root, project), json.dumps(target_content(normalized, project), indent=2, sort_keys=True) + "\n")
756
+ for project in normalized["projects"]
493
757
  ]
494
758
 
495
759
 
496
- def inject(root, config, platform, force, dry_run):
760
+ def inject(root, config, platform, project, force, dry_run):
497
761
  root_path = Path(root)
498
- normalized = load_and_validate(config, selected_platforms(platform))
499
- plan = build_write_plan(root, normalized, platform)
762
+ normalized = load_and_validate(config, platform, project)
763
+ require_selection(normalized, platform, project)
764
+ plan = build_write_plan(root, normalized)
500
765
  if dry_run:
501
766
  refused = [str(path) for path, _ in plan if not force and not is_managed_or_empty(path)]
502
767
  print(
@@ -525,7 +790,7 @@ def inject(root, config, platform, force, dry_run):
525
790
  try:
526
791
  for path, content in plan:
527
792
  directory = path.parent
528
- while directory != root_path:
793
+ while directory != root_path and directory != directory.parent:
529
794
  if not directory.exists():
530
795
  created_dirs.add(directory)
531
796
  directory = directory.parent
@@ -598,40 +863,294 @@ def inject(root, config, platform, force, dry_run):
598
863
  print(json.dumps({"written": [str(path) for path, _ in plan], "skipped": [], "refused": []}, indent=2, sort_keys=True))
599
864
 
600
865
 
601
- def print_plan(root, config, platform):
602
- normalized = load_and_validate(config, selected_platforms(platform))
603
- enforce_platform_contracts(normalized, platform)
604
- for item in selected_platforms(platform):
605
- print(f"platform={item} helper={Path(root) / 'scripts' / ('build_' + item + '.sh')} mode=plan")
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
606
1094
 
607
1095
 
608
1096
  def main(argv):
609
- parser = argparse.ArgumentParser(description="SuperSDK template schema and injection helper")
1097
+ parser = argparse.ArgumentParser(description="SuperSDK workspace schema and injection helper")
610
1098
  sub = parser.add_subparsers(dest="command", required=True)
611
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
+
612
1104
  validate = sub.add_parser("validate")
613
1105
  validate.add_argument("--config", required=True)
1106
+ add_selection(validate)
614
1107
 
615
1108
  plan = sub.add_parser("plan")
616
1109
  plan.add_argument("--root", required=True)
617
1110
  plan.add_argument("--config", required=True)
618
- plan.add_argument("--platform", choices=["all", *PLATFORMS], default="all")
1111
+ add_selection(plan)
619
1112
 
620
1113
  inject_cmd = sub.add_parser("inject")
621
1114
  inject_cmd.add_argument("--root", required=True)
622
1115
  inject_cmd.add_argument("--config", required=True)
623
- inject_cmd.add_argument("--platform", choices=["all", *PLATFORMS], default="all")
1116
+ add_selection(inject_cmd)
624
1117
  inject_cmd.add_argument("--force", action="store_true")
625
1118
  inject_cmd.add_argument("--dry-run", action="store_true")
626
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
+
627
1132
  args = parser.parse_args(argv)
628
1133
  try:
629
1134
  if args.command == "validate":
630
- print(json.dumps(load_and_validate(args.config), indent=2, sort_keys=True))
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))
631
1144
  elif args.command == "plan":
632
- print_plan(args.root, args.config, args.platform)
1145
+ print_plan(args.root, args.config, args.platform, args.project)
633
1146
  elif args.command == "inject":
634
- inject(args.root, args.config, args.platform, args.force, args.dry_run)
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)
635
1154
  except ConfigError as exc:
636
1155
  print(str(exc), file=sys.stderr)
637
1156
  return 1