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

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
@@ -1,107 +1,169 @@
1
- # SuperSDK Simple App Template
1
+ # SuperSDK Workspace Template
2
2
 
3
- This directory is the copy-ready `app_repo_example` template scaffold for
4
- Android, iOS, and Web hosts. Edit one root `supersdk.json`, run plan or build
5
- from this directory, and use the root ordered summary to inspect platform
6
- results.
3
+ This directory is the copy-ready `app_repo_example` template scaffold for a SuperSDK
4
+ workspace. One workspace = one `spid`. The directory holding `supersdk.json` is the
5
+ workspace root; every project listed in `projects[]` lives in a subdirectory of it.
6
+
7
+ Edit one root `supersdk.json`, run plan or build from the workspace root, and use the
8
+ root ordered summary to inspect project results.
7
9
 
8
10
  Platform status: BL-002 provides the Android Maven host, BL-003 provides the iOS
9
11
  SPM/mock host, BL-004 provides the Web/JSSDK host, and BL-005 connects them
10
12
  through the root build orchestration described below.
11
13
 
14
+ ## Layout
15
+
16
+ Workspace-level (shared by every project, laid down once by `supercli init`):
17
+
18
+ - `supersdk.json` — the single source of truth for this workspace
19
+ - `super_build.sh` — root orchestration entry point
20
+ - `scripts/` — the config engine and the per-type build helpers
21
+ - `output/` — offline packages, one subdirectory per site project
22
+
23
+ Per-project (copied by `supercli add <type> <dir>`):
24
+
25
+ - `android/` — Android host, type `android`
26
+ - `ios/` — iOS host, type `ios`
27
+ - `web/` — Web/site host, type `site`
28
+
29
+ The directory names above are only defaults. `projects[].dir` may be any relative
30
+ path, at any depth (`apps/android`, `clients/mobile/ios`, …). Nothing in the build
31
+ scripts assumes a fixed nesting level: they locate the workspace root by searching
32
+ upwards for `supersdk.json`, exactly like the CLI does.
33
+
12
34
  ## Maintainer Flow
13
35
 
14
36
  ```bash
15
37
  ./super_build.sh --plan
16
38
  ./super_build.sh --build
17
- ./super_build.sh --platform web --build
39
+ ./super_build.sh --platform site --build
40
+ ./super_build.sh --project web --build
18
41
  ```
19
42
 
20
43
  No arguments are equivalent to `./super_build.sh --plan`. Plan mode validates
21
- `supersdk.json` and prints Android -> iOS -> Web helper order without invoking
22
- platform build helpers or emitting `SUPERSDK_BUILD_SUMMARY_JSON=`.
44
+ `supersdk.json` and prints Android -> iOS -> Site helper order without invoking
45
+ project build helpers or emitting `SUPERSDK_BUILD_SUMMARY_JSON=`.
23
46
 
24
- Build mode validates and injects managed config first, then runs selected
25
- platform helpers in order. The default `./super_build.sh --build` selects
26
- Android, iOS, and Web. `--platform android|ios|web --build` injects and runs
27
- only that platform; non-selected platform managed config is not created or
28
- rewritten.
47
+ Build mode validates and injects managed config first, then runs the selected
48
+ project helpers in order. The default `./super_build.sh --build` selects every
49
+ project. `--platform android|ios|site` selects every project of that type;
50
+ `--project <dir>` selects exactly one. Managed config for non-selected projects is
51
+ not created or rewritten.
29
52
 
30
53
  ## Configuration Checklist
31
54
 
32
55
  - Edit `supersdk.json`. It is standard JSON: no comments, no trailing commas.
33
- - Keep `"schemaVersion": 2`.
34
- - Set `spid`, `environment`, and `name`. Replace the example `demo0001` with
35
- the real 8-character lowercase alphanumeric spid issued by the console.
36
- - Keep `"environment": "prod"` for production, or use an explicit 1–10 character
37
- lowercase alphanumeric environment such as `staging`.
38
- - Set `android.package` for Android builds. It is required whenever Android is
39
- built and must differ from the fixed `com.supersdk.simple` namespace.
40
- - Set `ios.bundleId` for iOS builds. It is required whenever iOS is built: the
41
- app identity is never derived from `spid`, so a missing value fails the build
42
- instead of shipping under the SDK's own reverse-domain namespace. The default
43
- `"spmMode": "mock"` uses the bundled `ios/MockSuperSDKPackage`.
44
- - Set `web.host` for Web packaging.
45
- - Run `./super_build.sh --plan`.
46
- - Run `./super_build.sh --build` or a single-platform build.
47
-
48
- `orgId` and `sites` are owned by `supercli`. The template type-checks them
49
- (`orgId` a string, `sites` an array) and otherwise ignores them, so site-side
50
- changes can never break an App build. Any other unrecognized root key is kept
51
- as-is. The retired `supersdk.yaml` / `supersdk.yml` / `super-site.yml` files are
52
- rejected with a copy-pasteable migration command; there is no silent fallback.
53
- The command matches the situation: with no usable `supersdk.json` it writes the
54
- full skeleton first and deletes the legacy file last, and when `supersdk.json` is
55
- already valid it only offers `rm <legacy>` so pasting it cannot overwrite real
56
- values.
56
+ - Keep `"schemaVersion": 3`.
57
+ - Set `spid`: the real 8-character lowercase alphanumeric spid issued by the console.
58
+ Replace the example `demo0001`.
59
+ - The root `name` is a **description of the workspace**. It is never projected as an
60
+ App label. Every android/ios project carries its own `name`, and that is the real
61
+ identity (Android app label / iOS display name).
62
+ - Set `package` on each android project and `bundleId` on each ios project. Identity
63
+ is never derived and never inherited: a missing value fails the build instead of
64
+ shipping under the SDK's own reverse-domain namespace.
65
+ - `spmMode` defaults to `mock` and uses the bundled `MockSuperSDKPackage`.
66
+ - For site projects, `offline.host` is optional and is filled in by the CLI after the
67
+ first successful publish. Without it the site still builds `dist/`; only the offline
68
+ zip is skipped, and the reason is printed.
69
+ - `version` and `sdk` may be set at workspace level and overridden per project. An
70
+ override **replaces the whole value** — it is not merged — so a project-level
71
+ `version` must set both `name` and `code`.
72
+ - Run `./super_build.sh --plan`, then `./super_build.sh --build`.
73
+
74
+ ### There is no `environment` in this file
75
+
76
+ `environment` is a **runtime** parameter of `SuperSDK.init`, not build configuration.
77
+ It is not in `supersdk.json`, not in the managed config, and not in `BuildConfig`.
78
+ Omitting it at init time means `prod`. All three demo apps switch environment at
79
+ runtime instead:
80
+
81
+ - Android: buttons in `MainActivity`, persisted by `EnvironmentStore` (SharedPreferences)
82
+ - iOS: a segmented control in `SimpleViewController`, persisted by `EnvironmentStore` (UserDefaults)
83
+ - Web: the `Switch environment` selector, persisted in `localStorage`
84
+
85
+ The rule across the whole toolchain: **configuration says what this is, publishing says
86
+ where it goes, runtime says which environment to talk to.**
87
+
88
+ ### CLI-owned keys
89
+
90
+ `orgId` and each site project's `deploy[]` are owned by `supercli`. The template
91
+ type-checks them (`orgId` a string, `deploy` an array of objects) and otherwise ignores
92
+ them, so a site-side schema change can never break an App build. Any other unrecognized
93
+ root key is kept as-is.
57
94
 
58
95
  `supersdk.json` must be standard JSON in the strict sense. `NaN`, `Infinity`, and
59
96
  `-Infinity` are rejected even though Python's parser accepts them, because
60
97
  `supercli` reads the same file with `JSON.parse`, which does not.
61
98
 
62
- Note that the top-level `environment` is the App's own SDK runtime environment
63
- (injected into all three native configs), while `sites[].env` is the project
64
- environment a site publishes into. They are not asserted to be equal: building
65
- with a `staging` SDK config and publishing to a `prod` site is a legal
66
- combination.
67
-
68
- Generated files live under each platform `.supersdk/managed/` directory and
99
+ Generated files live under each project's `.supersdk/managed/` directory and
69
100
  are safe to overwrite only when they contain `managed_by: supersdk-template`.
70
101
  Use `--force` only when intentionally replacing unmanaged target files.
71
102
 
72
- ## Web Output And Publishing
103
+ ## Migrating From schemaVersion 2
73
104
 
74
- `web/src` is authored input. The Web build renders the single publishable
75
- package root at `web/dist`:
105
+ `schemaVersion: 3` is breaking and there is no backward compatibility. A v2 config
106
+ fails closed with the exact command to run:
76
107
 
77
108
  ```bash
78
- ./super_build.sh --platform web --build
109
+ python3 scripts/supersdk_template.py migrate --config supersdk.json
79
110
  ```
80
111
 
81
- That writes `web/dist/` (static assets plus the generated
82
- `web/dist/supersdk-config.json` the browser fallback reads) and the offline
83
- package `output/<host>@<version>@<md5>.zip`, both from the same tree. The zip is
84
- not a byte-identical copy of `web/dist`: it also carries the offline manifest
85
- `__super_meta.json`, which belongs to the offline package only. `web/dist`
86
- is the directory to hand to the site publisher:
112
+ The migration is in-place and moves **no files**: the v2 template directories were
113
+ already `android/`, `ios/`, and `web/`, so they become `projects[]` entries pointing at
114
+ the same paths. `sites[]` moves verbatim into the site project's `deploy[]`, the v2
115
+ `name` becomes each android/ios project's `name`, and the retired root `environment` is
116
+ dropped with a printed note.
117
+
118
+ The retired `supersdk.yaml` / `supersdk.yml` / `super-site.yml` files are rejected with
119
+ a copy-pasteable migration command; there is no silent fallback. The command matches the
120
+ situation: with no usable `supersdk.json` it writes the full skeleton first and deletes
121
+ the legacy file last, and when `supersdk.json` is already valid it only offers
122
+ `rm <legacy>` so pasting it cannot overwrite real values.
123
+
124
+ ## Engine Version
125
+
126
+ `scripts/supersdk_template.py` is vendored into every workspace and records its
127
+ `engine_version` in each managed config. `./super_build.sh` compares that recorded
128
+ value with the engine it is about to run and prints a warning when they differ; it
129
+ never blocks. If you see that warning, re-run `./super_build.sh --build` to reproject.
130
+
131
+ ## Site Output And Publishing
132
+
133
+ `<site>/src` is authored input. The site build renders the single publishable
134
+ package root at `<site>/dist`:
135
+
136
+ ```bash
137
+ ./super_build.sh --platform site --build
138
+ ```
139
+
140
+ That writes `<site>/dist/` (static assets plus the generated
141
+ `supersdk-config.json` the browser fallback reads) and, when `offline.host` is set, the
142
+ offline package `output/<site dir>/<host>@<version>@<md5>.zip`, both from the same tree.
143
+ The zip is not a byte-identical copy of `dist`: it also carries the offline manifest
144
+ `__super_meta.json`, which belongs to the offline package only. Offline packages are
145
+ namespaced by project directory, so two site projects that share a host and version
146
+ cannot overwrite each other's zip.
147
+
148
+ `<site>/dist` is the directory to hand to the site publisher:
87
149
 
88
150
  ```bash
89
151
  supercli publish-site web/dist --spid <spid> --slug <slug> --env <env> --version <x.y.z>
90
152
  ```
91
153
 
92
- `web/dist` is a build output: it is gitignored and replaced wholesale on every
93
- build. Never edit it by hand, and never point the publisher at `web/src` — that
154
+ `dist` is a build output: it is gitignored and replaced wholesale on every
155
+ build. Never edit it by hand, and never point the publisher at `<site>/src` — that
94
156
  tree has no runtime config and still carries `js/supersdk.provenance.json`.
95
157
 
96
- For local debugging, `python3 scripts/serve_web.py` serves `web/dist` when it
97
- exists and falls back to the unbuilt `web/src` with a warning.
158
+ For local debugging, `python3 scripts/serve_web.py` serves the built `dist` when it
159
+ exists and falls back to the unbuilt `src` with a warning.
98
160
 
99
161
  ## Ordered Summary
100
162
 
101
163
  Build mode writes exactly one root-owned machine-readable stdout line:
102
164
 
103
165
  ```text
104
- SUPERSDK_BUILD_SUMMARY_JSON={"schema_version":1,...}
166
+ SUPERSDK_BUILD_SUMMARY_JSON={"schema_version":2,...}
105
167
  ```
106
168
 
107
169
  Consumers must parse only lines that start with `SUPERSDK_BUILD_SUMMARY_JSON=`.
@@ -117,26 +179,30 @@ Summary fields are:
117
179
  - `overall_exit_code`
118
180
  - `platforms`
119
181
  - `platform`
182
+ - `dir`
120
183
  - `status`
121
184
  - `exit_code`
122
185
  - `reason`
123
186
  - `command`
124
187
 
125
- Platform `status` is `success`, `skipped`, or `failed`. `status=success` means
188
+ `platform` is the project type and `dir` is the project directory. A workspace may
189
+ hold several projects of the same type, so `dir` is what identifies a row.
190
+
191
+ Project `status` is `success`, `skipped`, or `failed`. `status=success` means
126
192
  the helper exited successfully under the helper contract; artifact-level validation
127
193
  is performed by canonical smoke. Long failure reasons are capped and end with
128
- `...(truncated)` when shortened. Per-platform `exit_code` mirrors the helper
194
+ `...(truncated)` when shortened. Per-project `exit_code` mirrors the helper
129
195
  process return code; a negative value means the helper was killed by that signal
130
196
  number. Launch errors use synthesized `exit_code=127`; helper timeouts use
131
197
  synthesized `exit_code=124`. In both cases, `reason` identifies the sentinel.
132
198
 
133
199
  ## Exit Codes
134
200
 
135
- - `0`: usage/config/injection succeeded and no selected platform failed.
201
+ - `0`: usage/config/injection succeeded and no selected project failed.
136
202
  - `1` with no summary: config validation or managed-config injection failed
137
- before platform orchestration started.
138
- - `1` with a summary: at least one selected platform had a hard failure after
139
- platform orchestration started.
203
+ before project orchestration started.
204
+ - `1` with a summary: at least one selected project had a hard failure after
205
+ project orchestration started.
140
206
  - `2` with no summary: usage or argument error, such as an invalid platform.
141
207
 
142
208
  This distinction lets downstream scripts tell a config error from a build
@@ -150,26 +216,26 @@ Android and iOS helpers may report toolchain, simulator, or temporary network
150
216
  conditions as `skipped` when they exit 0 and a raw stdout/stderr line starts
151
217
  with `SKIP_` or `BUILD SKIPPED`. Matching is case-sensitive and does not trim
152
218
  leading whitespace. A nonzero helper exit code always wins and is a hard
153
- failure. Web has no skip mode: it is `success` or `failed`.
219
+ failure. Site projects have no skip mode: they are `success` or `failed`.
154
220
 
155
- The root build continues through all selected platforms after a hard helper
156
- failure, then returns nonzero with every selected platform represented in the
221
+ The root build continues through all selected projects after a hard helper
222
+ failure, then returns nonzero with every selected project represented in the
157
223
  ordered summary. An internal orchestrator error still emits a failed summary, but
158
- may stop at the affected platform because the runner itself is no longer in a
224
+ may stop at the affected project because the runner itself is no longer in a
159
225
  trustworthy state.
160
226
 
161
- ## Platform Prerequisites
227
+ ## Project Prerequisites
162
228
 
163
- - Android: executable `android/gradlew`, `android/gradle/wrapper/gradle-wrapper.jar`,
229
+ - Android: executable `<android>/gradlew`, `<android>/gradle/wrapper/gradle-wrapper.jar`,
164
230
  JDK 17+, Android SDK, and reachable Maven metadata unless deterministic test
165
231
  mode or local metadata fixtures are used.
166
- - iOS: `ios/project.yml`, bundled `ios/MockSuperSDKPackage`, `xcodegen`,
232
+ - iOS: `<ios>/project.yml`, bundled `<ios>/MockSuperSDKPackage`, `xcodegen`,
167
233
  `xcodebuild`, and an available simulator for a full local build. Missing
168
234
  local toolchain is reported as an explicit skip unless a non-skippable CI gate
169
235
  is requested.
170
- - Web: bundled static assets `index.html`, `js/app.js`, `js/supersdk.js`,
171
- `css/style.css`, and `js/supersdk.provenance.json`. Web packaging uses the
172
- Python stdlib zip path and does not require Node/Vite.
236
+ - Site: bundled static assets `index.html`, `js/app.js`, `js/supersdk.js`,
237
+ `css/style.css`, and `js/supersdk.provenance.json` under `<site>/src`. Site packaging
238
+ uses the Python stdlib zip path and does not require Node/Vite.
173
239
 
174
240
  Maintainers can set `SUPERSDK_BUILD_HELPER_TIMEOUT_SECONDS` to adjust the
175
241
  per-helper timeout for CI or smoke troubleshooting. The default is 1800 seconds.
@@ -183,22 +249,15 @@ python3 supersimples/tests/e2e/build_orchestration_smoke.py
183
249
  ```
184
250
 
185
251
  The canonical smoke copies this template to a temporary directory outside the
186
- monorepo, edits `supersdk.json`, verifies platform entry assets, pins Android
252
+ monorepo, edits `supersdk.json`, verifies project entry assets, pins Android
187
253
  SNAPSHOT metadata to a local fixture, forces Android deterministic test mode,
188
254
  forces deterministic iOS `SKIP_XCODEGEN_MISSING`, runs the root build, checks
189
- the ordered summary, checks all three managed configs, verifies a real Web zip
255
+ the ordered summary, checks all three managed configs, verifies a real site zip
190
256
  containing `index.html`, `js/app.js`, and `__super_meta.json`, and rejects
191
257
  monorepo-only path/module leaks in generated outputs and copied Android/iOS
192
258
  build config files. Android and iOS are deterministic non-real-build paths in
193
- this smoke; Web packaging is the real platform build. Use a separate toolchain
259
+ this smoke; site packaging is the real project build. Use a separate toolchain
194
260
  CI lane when you need real Android Gradle or iOS simulator compilation.
195
261
 
196
262
  Publishing this template to the public `supersdks/simple` repository is BL-006,
197
263
  not part of this feature.
198
-
199
- ## BREAKING identity migration
200
-
201
- The root `app_id` key is retired. Rename it to `spid`, add `environment`
202
- (`prod` when omitted by SDK callers), then rerun `./super_build.sh --plan`.
203
- The managed Android, iOS, and Web configs are all projected from these same
204
- root values; do not maintain platform-specific identity aliases.
@@ -12,7 +12,6 @@ plugins {
12
12
  apply(from = "../gradle/supersdk-config-reader.gradle")
13
13
 
14
14
  val supersdkSpid = extra["supersdkSpid"] as String
15
- val supersdkEnvironment = extra["supersdkEnvironment"] as String
16
15
  val supersdkAppName = extra["supersdkAppName"] as String
17
16
  val supersdkApplicationId = extra["supersdkApplicationId"] as String
18
17
  val supersdkVersionName = extra["supersdkVersionName"] as String
@@ -80,12 +79,10 @@ android {
80
79
  buildTypes {
81
80
  debug {
82
81
  buildConfigField("String", "SUPERSDK_SPID", quotedJavaString(supersdkSpid))
83
- buildConfigField("String", "SUPERSDK_ENVIRONMENT", quotedJavaString(supersdkEnvironment))
84
82
  buildConfigField("String", "SUPERSDK_APP_NAME", quotedJavaString(supersdkAppName))
85
83
  }
86
84
  release {
87
85
  buildConfigField("String", "SUPERSDK_SPID", quotedJavaString(supersdkSpid))
88
- buildConfigField("String", "SUPERSDK_ENVIRONMENT", quotedJavaString(supersdkEnvironment))
89
86
  buildConfigField("String", "SUPERSDK_APP_NAME", quotedJavaString(supersdkAppName))
90
87
  isMinifyEnabled = false
91
88
  }
@@ -0,0 +1,41 @@
1
+ package com.supersdk.simple;
2
+
3
+ import android.content.Context;
4
+ import android.content.SharedPreferences;
5
+
6
+ /**
7
+ * 运行时环境的唯一读写口。
8
+ *
9
+ * 🔴 为什么不进 BuildConfig:environment 是 {@code SuperSDK.init} 的**运行时**参数,
10
+ * 编译期根本不需要它。一旦编进产物,「换个环境看看」就变成「重新配置 + 重新打包」。
11
+ * 所以它不在 supersdk.json 里,也不在 managed config 里,只存在于设备上的这份偏好里。
12
+ * 省略环境时 SDK 默认 prod,这里的默认值与之一致。
13
+ */
14
+ public final class EnvironmentStore {
15
+ public static final String DEFAULT_ENVIRONMENT = "prod";
16
+ /** 演示用的候选值。SDK 侧的约束是 ^[a-z0-9]{1,10}$,不限于这几个。 */
17
+ public static final String[] CHOICES = {"prod", "staging", "dev"};
18
+
19
+ private static final String PREFS = "supersdk_simple";
20
+ private static final String KEY = "environment";
21
+
22
+ private EnvironmentStore() {
23
+ }
24
+
25
+ public static String get(Context context) {
26
+ SharedPreferences prefs = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE);
27
+ String value = prefs.getString(KEY, DEFAULT_ENVIRONMENT);
28
+ return isValid(value) ? value : DEFAULT_ENVIRONMENT;
29
+ }
30
+
31
+ public static void set(Context context, String environment) {
32
+ if (!isValid(environment)) {
33
+ throw new IllegalArgumentException("environment must match ^[a-z0-9]{1,10}$: " + environment);
34
+ }
35
+ context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(KEY, environment).apply();
36
+ }
37
+
38
+ public static boolean isValid(String environment) {
39
+ return environment != null && environment.matches("[a-z0-9]{1,10}");
40
+ }
41
+ }
@@ -3,15 +3,68 @@ package com.supersdk.simple;
3
3
  import android.app.Activity;
4
4
  import android.os.Bundle;
5
5
  import android.view.Gravity;
6
+ import android.view.View;
7
+ import android.widget.Button;
8
+ import android.widget.LinearLayout;
6
9
  import android.widget.TextView;
10
+ import android.widget.Toast;
7
11
 
12
+ /**
13
+ * 最小 demo:显示 App 名 + 当前运行时环境,并允许在运行时切换环境。
14
+ *
15
+ * 切换只写偏好,不重复调用 {@code SuperSDK.init} —— SDK 的初始化是进程级的,
16
+ * 就地重入的语义没有保证。真正生效点在下次进程启动的 {@link SimpleApplication#onCreate()},
17
+ * 这一点必须**说给用户看**,而不是让人以为点一下就换好了。
18
+ */
8
19
  public class MainActivity extends Activity {
20
+ private TextView environmentLabel;
21
+
9
22
  @Override
10
23
  protected void onCreate(Bundle savedInstanceState) {
11
24
  super.onCreate(savedInstanceState);
12
- TextView view = new TextView(this);
13
- view.setGravity(Gravity.CENTER);
14
- view.setText(R.string.app_name);
15
- setContentView(view);
25
+
26
+ LinearLayout root = new LinearLayout(this);
27
+ root.setOrientation(LinearLayout.VERTICAL);
28
+ root.setGravity(Gravity.CENTER);
29
+ int padding = (int) (24 * getResources().getDisplayMetrics().density);
30
+ root.setPadding(padding, padding, padding, padding);
31
+
32
+ TextView title = new TextView(this);
33
+ title.setGravity(Gravity.CENTER);
34
+ title.setText(R.string.app_name);
35
+ root.addView(title);
36
+
37
+ TextView spid = new TextView(this);
38
+ spid.setGravity(Gravity.CENTER);
39
+ spid.setText("spid: " + BuildConfig.SUPERSDK_SPID);
40
+ root.addView(spid);
41
+
42
+ environmentLabel = new TextView(this);
43
+ environmentLabel.setGravity(Gravity.CENTER);
44
+ root.addView(environmentLabel);
45
+
46
+ for (final String choice : EnvironmentStore.CHOICES) {
47
+ Button button = new Button(this);
48
+ button.setText(choice);
49
+ button.setOnClickListener(new View.OnClickListener() {
50
+ @Override
51
+ public void onClick(View view) {
52
+ EnvironmentStore.set(MainActivity.this, choice);
53
+ renderEnvironment();
54
+ Toast.makeText(
55
+ MainActivity.this,
56
+ "environment set to " + choice + "; restart the app to re-init the SDK",
57
+ Toast.LENGTH_LONG).show();
58
+ }
59
+ });
60
+ root.addView(button);
61
+ }
62
+
63
+ setContentView(root);
64
+ renderEnvironment();
65
+ }
66
+
67
+ private void renderEnvironment() {
68
+ environmentLabel.setText("environment: " + EnvironmentStore.get(this) + " (applies on next launch)");
16
69
  }
17
70
  }
@@ -12,8 +12,10 @@ public class SimpleApplication extends Application {
12
12
  @Override
13
13
  public void onCreate() {
14
14
  super.onCreate();
15
+ // spid 是编译期身份(来自 supersdk.json),environment 是运行时选择(来自设备偏好)。
16
+ // 三参 init 省略环境时 SDK 默认 prod;这里显式传,是为了让 demo 能在运行时切换。
15
17
  try {
16
- SuperSDK.init(this, BuildConfig.SUPERSDK_SPID, BuildConfig.SUPERSDK_ENVIRONMENT, new SuperSDKProvider() {});
18
+ SuperSDK.init(this, BuildConfig.SUPERSDK_SPID, EnvironmentStore.get(this), new SuperSDKProvider() {});
17
19
  } catch (RuntimeException exception) {
18
20
  Log.e(TAG, "SuperSDK init failed; check supersdk.json and the resolved SDK dependency.", exception);
19
21
  throw exception;
@@ -46,8 +46,8 @@ def sdk = config.sdk instanceof Map ? config.sdk : [:]
46
46
  if (config.managed_by != "supersdk-template") {
47
47
  throw new GradleException("SuperSDK Android config invalid at ${configFile}: managed_by must be supersdk-template")
48
48
  }
49
- if (config.schema_version != 2) {
50
- throw new GradleException("SuperSDK Android config invalid at ${configFile}: schema_version must be 2")
49
+ if (config.schema_version != 3) {
50
+ throw new GradleException("SuperSDK Android config invalid at ${configFile}: schema_version must be 3")
51
51
  }
52
52
  def versionCodeValue = version.code
53
53
  if (!(versionCodeValue instanceof Number)) {
@@ -60,7 +60,9 @@ if (versionCodeDecimal.scale() > 0 || versionCodeDecimal < BigDecimal.ONE || ver
60
60
 
61
61
  ext.supersdkAndroidConfigPath = configFile.absolutePath
62
62
  ext.supersdkSpid = requireMatchingString(config.spid, "spid", /[a-z0-9]{8}/, 'must match ^[a-z0-9]{8}$')
63
- ext.supersdkEnvironment = requireMatchingString(config.environment, "environment", /[a-z0-9]{1,10}/, 'must match ^[a-z0-9]{1,10}$')
63
+ // 🔴 这里**没有** environment。它是 SuperSDK.init 的运行时参数,编译期不需要,
64
+ // 也就不该进 BuildConfig —— 一旦编进产物,换环境就等于重新打包。
65
+ // demo 在运行时切(见 EnvironmentStore.java)。
64
66
  ext.supersdkAppName = requireString(config.name, "name")
65
67
  if ((ext.supersdkAppName =~ /[\x00-\x1F]/).find() || ext.supersdkAppName != ext.supersdkAppName.trim()) {
66
68
  throw new GradleException("SuperSDK Android config invalid at ${configFile}: name must be a non-empty Android app label without control characters or edge whitespace")
@@ -1,16 +1,17 @@
1
1
  {
2
- "spid": "demo0001",
3
- "environment": "prod",
2
+ "dir": "android",
3
+ "engine_version": "3.0.0",
4
4
  "managed_by": "supersdk-template",
5
5
  "name": "SuperSDK Simple",
6
6
  "platform": "android",
7
7
  "platform_config": {
8
8
  "package": "com.supersdk.simple.host"
9
9
  },
10
- "schema_version": 2,
10
+ "schema_version": 3,
11
11
  "sdk": {
12
12
  "androidVersion": "1.0.0.54-SNAPSHOT"
13
13
  },
14
+ "spid": "demo0001",
14
15
  "version": {
15
16
  "code": 1,
16
17
  "name": "1.0.0"
@@ -0,0 +1,35 @@
1
+ import Foundation
2
+
3
+ /// 运行时环境的唯一读写口。
4
+ ///
5
+ /// 🔴 为什么不进 `SimpleConfig`(那是构建期投影出来的):environment 是
6
+ /// `SuperSDKManager.initialize` 的**运行时**参数,编译期不需要。把它编进产物,
7
+ /// 「换个环境看看」就变成「改配置 + 重新出包」。省略环境时 SDK 默认 prod,
8
+ /// 这里的默认值与之一致。
9
+ enum EnvironmentStore {
10
+ static let defaultEnvironment = "prod"
11
+ /// 演示用的候选值。SDK 侧的约束是 ^[a-z0-9]{1,10}$,不限于这几个。
12
+ static let choices = ["prod", "staging", "dev"]
13
+
14
+ private static let key = "supersdk.simple.environment"
15
+
16
+ static var current: String {
17
+ guard let stored = UserDefaults.standard.string(forKey: key), isValid(stored) else {
18
+ return defaultEnvironment
19
+ }
20
+ return stored
21
+ }
22
+
23
+ @discardableResult
24
+ static func set(_ environment: String) -> Bool {
25
+ guard isValid(environment) else {
26
+ return false
27
+ }
28
+ UserDefaults.standard.set(environment, forKey: key)
29
+ return true
30
+ }
31
+
32
+ static func isValid(_ environment: String) -> Bool {
33
+ environment.range(of: "^[a-z0-9]{1,10}$", options: .regularExpression) != nil
34
+ }
35
+ }
@@ -2,9 +2,10 @@ import SuperSDK
2
2
 
3
3
  enum SimpleSDKBootstrap {
4
4
  static func initialize() throws {
5
+ // spid 是编译期身份(投影自 supersdk.json),environment 是运行时选择。
5
6
  try SuperSDKManager.shared.initialize(
6
7
  spid: SimpleConfig.spid,
7
- environment: SimpleConfig.environment,
8
+ environment: EnvironmentStore.current,
8
9
  provider: SimpleSDKProvider()
9
10
  )
10
11
  }
@@ -5,6 +5,7 @@ struct SimpleSDKProbeResult {
5
5
  let resetClearedState: Bool
6
6
  let initializedSpid: String?
7
7
  let initializedEnvironment: String?
8
+ let expectedEnvironment: String
8
9
  let providerWasSet: Bool
9
10
  let providerTypeName: String?
10
11
  }
@@ -16,14 +17,28 @@ enum SimpleSDKProbe {
16
17
  && SuperSDKManager.shared.lastInitializedEnvironment == nil
17
18
  && !SuperSDKManager.shared.lastProviderWasSet
18
19
  && SuperSDKManager.shared.lastProviderTypeName == nil
20
+ // 环境是运行时读出来的,所以断言的期望值也必须运行时取,不能钉死成字面量。
21
+ let expectedEnvironment = EnvironmentStore.current
19
22
  try! SimpleSDKBootstrap.initialize()
20
23
  return SimpleSDKProbeResult(
21
24
  resetClearedState: resetClearedState,
22
25
  initializedSpid: SuperSDKManager.shared.lastInitializedSpid,
23
26
  initializedEnvironment: SuperSDKManager.shared.lastInitializedEnvironment,
27
+ expectedEnvironment: expectedEnvironment,
24
28
  providerWasSet: SuperSDKManager.shared.lastProviderWasSet,
25
29
  providerTypeName: SuperSDKManager.shared.lastProviderTypeName
26
30
  )
27
31
  }
32
+
33
+ static func environmentRoundTripForTesting() -> [String] {
34
+ var seen: [String] = []
35
+ let original = EnvironmentStore.current
36
+ for choice in EnvironmentStore.choices {
37
+ EnvironmentStore.set(choice)
38
+ seen.append(EnvironmentStore.current)
39
+ }
40
+ EnvironmentStore.set(original)
41
+ return seen
42
+ }
28
43
  }
29
44
  #endif