@mobilebytelabs/rconfig-cli 0.0.0-stage → 0.1.1

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 (3) hide show
  1. package/dist/cli.js +1141 -0
  2. package/package.json +34 -4
  3. package/README.md +0 -3
package/dist/cli.js ADDED
@@ -0,0 +1,1141 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/main.ts
4
+ import { chmodSync, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "node:fs";
5
+ import { homedir as homedir2 } from "node:os";
6
+ import { join as join3 } from "node:path";
7
+
8
+ // ../mcp/src/firebase-import.ts
9
+ var UNSUPPORTED = [
10
+ [/app\.userProperty/, "app.userProperty (Google Analytics user properties) has no rconfig equivalent"],
11
+ [/app\.audiences/, "app.audiences (Google Analytics audiences) has no rconfig equivalent"],
12
+ [/app\.firebaseInstallationId/, "app.firebaseInstallationId targets single installs; rconfig has no per-install allow-list"],
13
+ [/device\.prefers/, "device.prefers has no rconfig equivalent"],
14
+ [/app\.id\b/, "app.id selects a Firebase app; an rconfig app is one product, so the term has no meaning here"]
15
+ ];
16
+ var OPS = { "==": "eq", "!=": "ne", ">": "gt", ">=": "gte", "<": "lt", "<=": "lte" };
17
+ var str = String.raw`'([^']*)'`;
18
+ var list = String.raw`\[([^\]]*)\]`;
19
+ var items = (s) => [...s.matchAll(/'([^']*)'/g)].map((m) => m[1]);
20
+ var iso = (s) => /[zZ]|[+-]\d\d:?\d\d$/.test(s) ? s : s + "Z";
21
+ var literal = (raw) => {
22
+ const t = raw.trim();
23
+ const q = t.match(/^'([^']*)'$/);
24
+ if (q) return q[1];
25
+ if (/^-?\d+(\.\d+)?$/.test(t)) return Number(t);
26
+ if (t === "true" || t === "false") return t === "true";
27
+ return t;
28
+ };
29
+ function parseFirebaseCondition(expression) {
30
+ let e = expression.trim();
31
+ while (e.startsWith("(") && e.endsWith(")")) e = e.slice(1, -1).trim();
32
+ for (const [re, why] of UNSUPPORTED) if (re.test(e)) return { unsupported: why };
33
+ if (e.includes("||")) return { unsupported: "|| (OR) \u2014 an rconfig condition is a conjunction; split it into one condition per branch" };
34
+ if (e === "true" || e === "") return { predicate: {} };
35
+ const p = {};
36
+ const set = (k, v) => {
37
+ if (k in p) return `two terms both set ${k}; the conjunction cannot be expressed as one value`;
38
+ p[k] = v;
39
+ return null;
40
+ };
41
+ for (const rawTerm of e.split("&&")) {
42
+ let t = rawTerm.trim();
43
+ while (t.startsWith("(") && t.endsWith(")")) t = t.slice(1, -1).trim();
44
+ let m;
45
+ let clash = null;
46
+ if (m = t.match(new RegExp(String.raw`^device\.os\s*==\s*${str}$`))) clash = set("platforms", [m[1]]);
47
+ else if (m = t.match(new RegExp(String.raw`^device\.os\s+in\s+${list}$`))) clash = set("platforms", items(m[1]));
48
+ else if (m = t.match(/^app\.(version|build)\.(>=|<=)\(\s*\[?\s*'([^']*)'\s*\]?\s*\)$/)) {
49
+ const [, what, op, v] = m;
50
+ if (what === "version") clash = set(op === ">=" ? "min_app_version" : "max_app_version", v);
51
+ else if (/^\d+$/.test(v)) clash = set(op === ">=" ? "min_build" : "max_build", Number(v));
52
+ else return { unsupported: `app.build compares a number; got '${v}'` };
53
+ } else if (m = t.match(new RegExp(String.raw`^device\.country\s+in\s+${list}$`))) clash = set("countries", items(m[1]).map((c) => c.toUpperCase()));
54
+ else if (m = t.match(new RegExp(String.raw`^device\.language\s+in\s+${list}$`))) clash = set("languages", items(m[1]));
55
+ else if (m = t.match(/^percent(?:\('[^']*'\))?\s*(<=|<)\s*(\d+(?:\.\d+)?)$/)) clash = set("percentile", Number(m[2]));
56
+ else if (m = t.match(/^percent(?:\('[^']*'\))?\s+between\s+(\d+(?:\.\d+)?)\s+and\s+(\d+(?:\.\d+)?)$/)) {
57
+ if (Number(m[1]) !== 0) {
58
+ return { unsupported: `percent between ${m[1]} and ${m[2]} \u2014 rconfig percentiles start at 0; only "between 0 and n" maps` };
59
+ }
60
+ clash = set("percentile", Number(m[2]));
61
+ } else if (m = t.match(/^app\.customSignal\['([^']+)'\]\s*(==|!=|>=|<=|>|<)\s*(.+)$/)) {
62
+ const signals = p.signals ?? [];
63
+ signals.push({ key: m[1], op: OPS[m[2]], value: literal(m[3]) });
64
+ p.signals = signals;
65
+ } else if (m = t.match(new RegExp(String.raw`^app\.customSignal\['([^']+)'\]\s+in\s+${list}$`))) {
66
+ const signals = p.signals ?? [];
67
+ signals.push({ key: m[1], op: "in", value: items(m[2]) });
68
+ p.signals = signals;
69
+ } else if (m = t.match(/^app\.firstOpenTimestamp\s*(>=|>|<=|<)\s*\(\s*'([^']*)'\s*\)$/)) {
70
+ clash = set(m[1].startsWith(">") ? "first_open_after" : "first_open_before", iso(m[2]));
71
+ } else if (m = t.match(/^dateTime\s*(>=|>|<=|<)\s*dateTime\(\s*'([^']*)'(?:\s*,\s*'([^']*)')?\s*\)$/)) {
72
+ if (m[3] && m[3] !== "UTC") return { unsupported: `dateTime with time zone '${m[3]}' \u2014 write it in UTC` };
73
+ clash = set(m[1].startsWith(">") ? "starts_at" : "ends_at", iso(m[2]));
74
+ } else {
75
+ return { unsupported: `no rconfig equivalent for: ${t}` };
76
+ }
77
+ if (clash) return { unsupported: clash };
78
+ }
79
+ return { predicate: p };
80
+ }
81
+ var TYPES = { STRING: "string", BOOLEAN: "boolean", NUMBER: "number", JSON: "json" };
82
+ function typed(v, type) {
83
+ if (type === "boolean") return v === "true";
84
+ if (type === "number") return Number(v);
85
+ if (type === "json") return JSON.parse(v);
86
+ return v;
87
+ }
88
+ function fromFirebase(fb) {
89
+ const report = {
90
+ skipped_conditions: [],
91
+ skipped_parameters: [],
92
+ dropped_values: [],
93
+ notes: [
94
+ "Percentage conditions use rconfig's own bucketing (seeded per app and key), so devices are re-bucketed: the same 10% of users is not the same 10% Firebase chose."
95
+ ]
96
+ };
97
+ const conditions = [];
98
+ const skipped = /* @__PURE__ */ new Map();
99
+ (fb.conditions ?? []).forEach((c, i) => {
100
+ const r = parseFirebaseCondition(c.expression);
101
+ if ("unsupported" in r) {
102
+ skipped.set(c.name, r.unsupported);
103
+ report.skipped_conditions.push({ name: c.name, expression: c.expression, reason: r.unsupported });
104
+ } else {
105
+ conditions.push({ name: c.name, predicate: r.predicate, priority: i + 1 });
106
+ }
107
+ });
108
+ const priorityOf = new Map(conditions.map((c) => [c.name, c.priority]));
109
+ const all = [
110
+ ...Object.entries(fb.parameters ?? {}).map(([k, v]) => [k, v, null]),
111
+ ...Object.entries(fb.parameterGroups ?? {}).flatMap(([g, grp]) => Object.entries(grp.parameters ?? {}).map(([k, v]) => [k, v, g]))
112
+ ];
113
+ const parameters = [];
114
+ for (const [key, fp, group] of all) {
115
+ const type = TYPES[fp.valueType ?? "STRING"] ?? "string";
116
+ if (fp.defaultValue?.useInAppDefault || fp.defaultValue?.value === void 0) {
117
+ const n = Object.keys(fp.conditionalValues ?? {}).length;
118
+ report.skipped_parameters.push({
119
+ key,
120
+ reason: `its default is the in-app default; rconfig serves a key only with a server default, and inventing one would override the app's bundled value${n ? ` (its ${n} conditional value(s) were not imported)` : ""}`
121
+ });
122
+ continue;
123
+ }
124
+ const values = [];
125
+ for (const [cname, cv] of Object.entries(fp.conditionalValues ?? {})) {
126
+ if (skipped.has(cname)) {
127
+ report.dropped_values.push({ parameter: key, condition: cname, reason: `condition skipped: ${skipped.get(cname)}` });
128
+ } else if (cv.useInAppDefault || cv.value === void 0) {
129
+ report.dropped_values.push({ parameter: key, condition: cname, reason: "useInAppDefault \u2014 these users keep the server default instead" });
130
+ } else if (priorityOf.has(cname)) {
131
+ values.push({ condition: cname, value: typed(cv.value, type), priority: priorityOf.get(cname) });
132
+ }
133
+ }
134
+ values.sort((a, b) => a.priority - b.priority);
135
+ parameters.push({ key, type, description: fp.description ?? null, group, default: typed(fp.defaultValue.value, type), values });
136
+ }
137
+ parameters.sort((a, b) => a.key.localeCompare(b.key));
138
+ return { template: { schema: "rconfig-template/1", parameters, conditions, configs: [] }, report };
139
+ }
140
+
141
+ // ../mcp/src/operations.ts
142
+ function createApiClient(functionsUrl, token) {
143
+ return {
144
+ async call(op, args) {
145
+ let res;
146
+ try {
147
+ res = await fetch(`${functionsUrl.replace(/\/$/, "")}/v1-admin`, {
148
+ method: "POST",
149
+ headers: { "Authorization": `Bearer ${token}`, "Content-Type": "application/json" },
150
+ body: JSON.stringify({ op, args })
151
+ });
152
+ } catch (e) {
153
+ return { error: `could not reach the control plane: ${e.message}` };
154
+ }
155
+ let body;
156
+ try {
157
+ body = await res.json();
158
+ } catch {
159
+ return { error: `the control plane returned ${res.status} with no JSON body` };
160
+ }
161
+ return body;
162
+ }
163
+ };
164
+ }
165
+ async function call(db, _token, op, args = {}) {
166
+ const envelope = await db.call(op, args);
167
+ if (envelope.error) return { error: envelope.error };
168
+ return envelope.data;
169
+ }
170
+ var listApps = (db, token) => call(db, token, "list_apps");
171
+ var env = (e) => e ? { target_environment: e } : {};
172
+ var listParameters = (db, token, appId, e) => call(db, token, "list_parameters", { app_id: appId, ...env(e) });
173
+ var listConditions = (db, token, appId, e) => call(db, token, "list_conditions", { app_id: appId, ...env(e) });
174
+ var listVersions = (db, token, appId, e) => call(db, token, "list_versions", { app_id: appId, ...env(e) });
175
+ var onboardApp = (db, token, input) => call(db, token, "onboard_app", { ...input });
176
+ var listKeys = (db, token, appId) => call(db, token, "list_keys", { app_id: appId });
177
+ var createParameter = (db, token, appId, p, e) => call(db, token, "create_parameter", { app_id: appId, ...p, ...env(e) });
178
+ var createCondition = (db, token, appId, c, e) => call(db, token, "create_condition", { app_id: appId, ...c, ...env(e) });
179
+ var addOverride = (db, token, o) => call(db, token, "add_override", { ...o });
180
+ var publish = (db, token, appId, e, description) => call(db, token, "publish", { app_id: appId, ...env(e), ...description ? { description } : {} });
181
+ var rollback = (db, token, appId, version, e) => call(db, token, "rollback", { app_id: appId, version, ...env(e) });
182
+ var updateParameter = (db, token, parameterId, p) => call(db, token, "update_parameter", { parameter_id: parameterId, ...p });
183
+ var deleteParameter = (db, token, parameterId) => call(db, token, "delete_parameter", { parameter_id: parameterId });
184
+ var updateCondition = (db, token, conditionId, c) => call(db, token, "update_condition", { condition_id: conditionId, ...c });
185
+ var deleteCondition = (db, token, conditionId, cascade = false) => call(db, token, "delete_condition", { condition_id: conditionId, cascade });
186
+ var updateOverride = (db, token, o) => call(db, token, "update_override", { ...o });
187
+ var deleteOverride = (db, token, o) => call(db, token, "delete_override", { ...o });
188
+ var exportTemplate = (db, token, appId, e) => call(db, token, "export_template", { app_id: appId, ...env(e) });
189
+ var importTemplate = (db, token, appId, template, o = {}) => call(db, token, "import_template", {
190
+ app_id: appId,
191
+ template,
192
+ mode: o.mode ?? "merge",
193
+ dry_run: o.dry_run ?? false,
194
+ ...env(o.env)
195
+ });
196
+ var getPublishedSnapshot = (db, token, appId, e) => call(db, token, "get_published_snapshot", { app_id: appId, ...env(e) });
197
+
198
+ // src/cli.ts
199
+ import { parseArgs } from "node:util";
200
+
201
+ // ../mcp/src/integrate-io.ts
202
+ import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
203
+ import { dirname, join as join2, relative } from "node:path";
204
+ import { execFileSync } from "node:child_process";
205
+ import { homedir } from "node:os";
206
+
207
+ // ../mcp/src/integrate.ts
208
+ var SDK_VERSION = "5.0.4";
209
+ var MAVEN = "io.github.mobilebytelabs";
210
+ var KTOR = "3.2.1";
211
+ var SAMPLE_KEY = "welcome_message";
212
+ var SAMPLE_DEFAULT = "Hello from rconfig";
213
+ var dirOf = (p) => p.includes("/") ? p.slice(0, p.lastIndexOf("/")) : "";
214
+ var join = (...p) => p.filter(Boolean).join("/");
215
+ var isGradle = (p) => /(^|\/)build\.gradle(\.kts)?$/.test(p);
216
+ var KMP = /kotlin\("multiplatform"\)|kotlinMultiplatform|org\.jetbrains\.kotlin\.multiplatform/;
217
+ var ANDROID_APP = /com\.android\.application|android\.application|androidApplication/;
218
+ function packageFrom(text) {
219
+ return text.match(/applicationId\s*=?\s*"([^"]+)"/)?.[1] ?? text.match(/namespace\s*=?\s*"([^"]+)"/)?.[1] ?? null;
220
+ }
221
+ function diFrom(text) {
222
+ if (/hilt/i.test(text)) return "hilt";
223
+ if (/koin/i.test(text)) return "koin";
224
+ if (/dagger/i.test(text)) return "dagger";
225
+ return "none";
226
+ }
227
+ var usesCompose = (text) => /compose/i.test(text);
228
+ function detectProject(files) {
229
+ const paths = Object.keys(files).sort((a, b) => a.split("/").length - b.split("/").length);
230
+ const gradle = paths.filter(isGradle);
231
+ const androidPkg = gradle.map((p) => packageFrom(files[p])).find(Boolean) ?? null;
232
+ const root = gradle.filter((p) => !p.includes("/")).map((p) => files[p]).join("\n");
233
+ const kmp = gradle.find((p) => KMP.test(files[p]) && /commonMain/.test(files[p]));
234
+ if (kmp) {
235
+ const text = files[kmp];
236
+ return {
237
+ type: "kmp",
238
+ module: dirOf(kmp),
239
+ packageName: androidPkg,
240
+ language: "kotlin",
241
+ di: diFrom(text) === "koin" ? "koin" : "none",
242
+ ui: usesCompose(text) ? "compose" : "none",
243
+ evidence: `${kmp} applies the Kotlin Multiplatform plugin`
244
+ };
245
+ }
246
+ const android = gradle.find((p) => ANDROID_APP.test(files[p]));
247
+ if (android) {
248
+ const text = files[android];
249
+ return {
250
+ type: "android",
251
+ module: dirOf(android),
252
+ packageName: packageFrom(text) ?? androidPkg,
253
+ language: /kotlin/.test(text) ? "kotlin" : "java",
254
+ di: diFrom(text + "\n" + root),
255
+ ui: usesCompose(text) ? "compose" : "views",
256
+ evidence: `${android} applies com.android.application`
257
+ };
258
+ }
259
+ const desktop = gradle.find((p) => /mainClass|application\b|org\.jetbrains\.compose/.test(files[p]));
260
+ if (desktop) {
261
+ const text = files[desktop];
262
+ return {
263
+ type: "desktop",
264
+ module: dirOf(desktop),
265
+ packageName: text.match(/group\s*=\s*"([^"]+)"/)?.[1] ?? null,
266
+ language: /kotlin/.test(text) ? "kotlin" : "java",
267
+ di: diFrom(text) === "koin" ? "koin" : "none",
268
+ ui: usesCompose(text) ? "compose" : "swing",
269
+ evidence: `${desktop} builds a JVM application`
270
+ };
271
+ }
272
+ const pbx = paths.find((p) => p.endsWith(".pbxproj"));
273
+ const spm = paths.find((p) => /(^|\/)Package\.swift$/.test(p));
274
+ if (pbx || spm) {
275
+ const bundle = pbx ? files[pbx].match(/PRODUCT_BUNDLE_IDENTIFIER = "?([A-Za-z0-9.\-]+)"?;/)?.[1] ?? null : null;
276
+ const swiftDir = dirOf(paths.find((p) => /App\.swift$/.test(p)) ?? paths.find((p) => p.endsWith(".swift")) ?? "");
277
+ return { type: "ios", module: swiftDir, packageName: bundle, language: "swift", di: "none", ui: "swiftui", evidence: `${pbx ?? spm} is an Apple project` };
278
+ }
279
+ const pkg = paths.find((p) => /(^|\/)package\.json$/.test(p));
280
+ if (pkg) {
281
+ let name = null;
282
+ try {
283
+ name = JSON.parse(files[pkg]).name ?? null;
284
+ } catch {
285
+ }
286
+ return { type: "web", module: dirOf(pkg), packageName: name, language: "typescript", di: "none", ui: "dom", evidence: `${pkg} is a JavaScript project` };
287
+ }
288
+ return null;
289
+ }
290
+ function addToBlock(text, opener, line) {
291
+ const m = opener.exec(text);
292
+ if (!m) return null;
293
+ const at = m.index + m[0].length;
294
+ const indent = (text.slice(text.lastIndexOf("\n", m.index) + 1, m.index).match(/^\s*/)?.[0] ?? "") + " ";
295
+ return `${text.slice(0, at)}
296
+ ${indent}${line}${text.slice(at)}`;
297
+ }
298
+ var READ_STEPS = (ui, inject) => [
299
+ `Get it: ${inject} \u2014 every path returns the same instance.`,
300
+ 'In a ViewModel: `val welcome = remoteConfig.stringFlow(RConfigKeys.WELCOME_MESSAGE).stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), "")`; one-off reads are `remoteConfig.getString(\u2026)`, and `suspend fun fetchAndActivate()` refreshes on demand.',
301
+ ui === "compose" ? "In Compose: `val welcome by viewModel.welcome.collectAsStateWithLifecycle()`, or straight from the instance `val welcome by remoteConfig.collectStringAsState(RConfigKeys.WELCOME_MESSAGE)`; put `RConfigTemplateHost()` once at the root for server-driven dialogs and banners." : ui === "swing" ? "In Swing: `scope.launch { remoteConfig.stringFlow(RConfigKeys.WELCOME_MESSAGE).collect { label.text = it } }` (MainScope runs on the Swing thread); add `RConfigSwing.templatePanel()` to your frame." : ui === "views" ? "In an Activity/Fragment: `lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.welcome.collect { binding.title.text = it } } }`; add `RConfigViews.templateHost(this)` over your root layout for server-driven dialogs and banners." : "Without UI: `remoteConfig.stringFlow(RConfigKeys.WELCOME_MESSAGE).collect { \u2026 }` in any coroutine."
302
+ ];
303
+ var INJECT = {
304
+ hilt: "`@Inject constructor(private val remoteConfig: RemoteConfig)` in a @HiltViewModel or any injected class",
305
+ dagger: "`@Inject constructor(private val remoteConfig: RemoteConfig)` in any class your component builds",
306
+ koin: "`koinInject<RemoteConfig>()` in Compose, `class HomeViewModel(private val remoteConfig: RemoteConfig)` + `viewModelOf(::HomeViewModel)`, or `get()` in a definition",
307
+ none: "`RemoteConfig.instance` anywhere, or pass it into your ViewModel's constructor"
308
+ };
309
+ function planIntegration(files, d, input) {
310
+ const patches = [];
311
+ const steps = [];
312
+ const version = input.appVersion ?? "1.0.0";
313
+ const addDeps = (deps, opener, where) => {
314
+ const build = [join(d.module, "build.gradle.kts"), join(d.module, "build.gradle")].find((p) => p in files);
315
+ if (!build) {
316
+ steps.push(`Add to ${where}: ${deps.join(", ")}`);
317
+ return;
318
+ }
319
+ let text = files[build];
320
+ for (const dep of [...deps].reverse()) {
321
+ const coordinate = dep.match(/"([^"]+)"/)[1];
322
+ if (text.includes(coordinate.split(":").slice(0, 2).join(":"))) continue;
323
+ const next = addToBlock(text, opener, dep);
324
+ if (next === null) {
325
+ steps.push(`Add ${dep} to ${where} in ${build}`);
326
+ continue;
327
+ }
328
+ text = next;
329
+ }
330
+ if (text !== files[build]) patches.push({ path: build, action: "modify", before: files[build], after: text });
331
+ };
332
+ const create = (path, body) => {
333
+ if (!(path in files)) patches.push({ path, action: "create", after: body });
334
+ };
335
+ switch (d.type) {
336
+ case "kmp": {
337
+ const artifact = d.ui === "compose" || d.di === "koin" ? "cmp-remote-config-compose" : "cmp-remote-config";
338
+ addDeps([`implementation("${MAVEN}:${artifact}:${SDK_VERSION}")`], /commonMain\.dependencies\s*\{/, "commonMain.dependencies");
339
+ create(join(d.module, "src/commonMain/kotlin/rconfig/RConfigSetup.kt"), kmpSetup(input, version, d));
340
+ steps.push(
341
+ d.di === "koin" ? "Add rconfigModule to startKoin { modules(\u2026) } \u2014 the one initialisation; it uses the HttpClient in your graph if there is one." : "Call `initRemoteConfig(httpClient)` once at startup (an HttpClient on each target's engine) \u2014 the one initialisation.",
342
+ d.ui === "compose" ? "Call `RConfigRoot()` once at the root of your UI: fetch, live updates while composed, server-driven templates." : "Call `remoteConfig.start(appScope)` once: fetch, then live updates.",
343
+ ...READ_STEPS(d.ui, INJECT[d.di])
344
+ );
345
+ break;
346
+ }
347
+ case "android":
348
+ case "desktop": {
349
+ const android = d.type === "android";
350
+ const deps = [
351
+ `implementation("${MAVEN}:cmp-remote-config:${SDK_VERSION}")`,
352
+ `implementation("${MAVEN}:cmp-remote-config-compose:${SDK_VERSION}")`,
353
+ `implementation("io.ktor:${android ? "ktor-client-okhttp" : "ktor-client-cio"}:${KTOR}")`
354
+ ];
355
+ if (android && d.language === "kotlin") deps.push(`implementation("androidx.lifecycle:lifecycle-process:2.8.7")`);
356
+ if (!android && d.ui === "swing") deps.push(`implementation("org.jetbrains.kotlinx:kotlinx-coroutines-swing:1.11.0")`);
357
+ addDeps(deps, /^dependencies\s*\{/m, "dependencies");
358
+ if (d.language === "kotlin") {
359
+ create(join(d.module, "src/main/kotlin/rconfig/RConfigSetup.kt"), android ? androidSetup(input, d) : desktopSetup(input, version, d));
360
+ steps.push(...android ? androidSteps(d) : desktopSteps(d));
361
+ } else {
362
+ create(join(d.module, "src/main/java/rconfig/RConfigSetup.java"), javaSetup(input, version, d));
363
+ if (d.di === "hilt" || d.di === "dagger") create(join(d.module, "src/main/java/rconfig/RConfigModule.java"), javaModule(d));
364
+ steps.push(
365
+ d.di === "hilt" ? "Inject RConfig where needed (@Inject RConfig rc); RConfigModule installs it in SingletonComponent." : d.di === "dagger" ? "Add RConfigModule to your @Component(modules = \u2026) and inject RConfig where needed." : android ? "Call RConfigSetup.start() in Application.onCreate." : "Call RConfigSetup.start() in main().",
366
+ `Read with rc.getString(\u2026) after fetchAndActivate's callback (on the ${android ? "main" : "AWT event"} thread); listen with rc.addOnConfigUpdateListener(\u2026) and call rc.activate() in it.`,
367
+ android ? "Add RConfigViews.templateHost(context, rc) over your root layout for server-driven dialogs and banners." : "Add RConfigSwing.templatePanel(rc) to your frame for server-driven dialogs and banners."
368
+ );
369
+ }
370
+ steps.push("The SDK is Java 21 bytecode \u2014 compile with a Java 21 toolchain.");
371
+ break;
372
+ }
373
+ case "ios": {
374
+ create(join(d.module, "RConfigSetup.swift"), iosSetup(input));
375
+ steps.push(
376
+ "Add the Swift package (File \u2192 Add Package Dependencies \u2192 this repository, product RConfig) or `pod 'RConfig'`.",
377
+ "Call RConfigSetup.start() in your App's init, `.task { for await _ in RConfig.shared.updates { \u2026 } }` for live updates, and add RConfigTemplateView() over your root view."
378
+ );
379
+ break;
380
+ }
381
+ case "web": {
382
+ const pkgPath = join(d.module, "package.json");
383
+ const pkg = JSON.parse(files[pkgPath]);
384
+ if (!pkg.dependencies?.["@mobilebytelabs/rconfig"]) {
385
+ pkg.dependencies = { ...pkg.dependencies ?? {}, "@mobilebytelabs/rconfig": `^${SDK_VERSION}` };
386
+ patches.push({ path: pkgPath, action: "modify", before: files[pkgPath], after: JSON.stringify(pkg, null, 2) + "\n" });
387
+ }
388
+ const src = Object.keys(files).some((p) => p.startsWith(join(d.module, "src/"))) ? join(d.module, "src") : d.module;
389
+ create(join(src, "rconfig.ts"), webSetup(input, version));
390
+ steps.push("Run your package manager's install, then import { rc, startRConfig } from './rconfig' and await startRConfig() at boot.");
391
+ break;
392
+ }
393
+ }
394
+ steps.push(`Register ${input.packageName} under Platforms in the dashboard (Android: add your signing fingerprints).`);
395
+ return { detection: d, patches, nextSteps: steps };
396
+ }
397
+ function androidSteps(d) {
398
+ const init = {
399
+ hilt: "Initialisation is RConfigModule (installed in SingletonComponent). In your @HiltAndroidApp Application: `@Inject lateinit var remoteConfig: RemoteConfig`, then `remoteConfig.syncWhileForeground()` in onCreate().",
400
+ dagger: "Add RConfigModule to your @Component(modules = [\u2026]); inject RemoteConfig into your Application and call `remoteConfig.syncWhileForeground()` in onCreate().",
401
+ koin: "Add rconfigModule to startKoin { modules(\u2026) } \u2014 startKoin is the one initialisation; then `get<RemoteConfig>().syncWhileForeground()` in Application.onCreate().",
402
+ none: "In Application.onCreate(): `initRemoteConfig().syncWhileForeground()` \u2014 the one initialisation."
403
+ }[d.di];
404
+ return [init, ...READ_STEPS(d.ui, INJECT[d.di])];
405
+ }
406
+ function desktopSteps(d) {
407
+ const init = d.di === "koin" ? "Add rconfigModule to startKoin { modules(\u2026) } \u2014 the one initialisation." : "Call `initRemoteConfig()` once in main() \u2014 the one initialisation.";
408
+ const start = d.ui === "compose" ? "In your root composable: `RConfigRoot()` (fetch, live updates while composed, server-driven templates)." : "In main(): `val scope = MainScope(); remoteConfig.start(scope)` \u2014 fetch, then live updates.";
409
+ return [init, start, ...READ_STEPS(d.ui, INJECT[d.di])];
410
+ }
411
+ function describePlan(plan) {
412
+ const d = plan.detection;
413
+ const lines = [`Project: ${d.type} \xB7 ${d.language} \xB7 DI ${d.di} \xB7 UI ${d.ui} (${d.evidence})`];
414
+ if (plan.patches.length === 0) lines.push("Already integrated \u2014 nothing to change.");
415
+ for (const p of plan.patches) {
416
+ lines.push("", `${p.action === "create" ? "+++ create" : "*** modify"} ${p.path}`);
417
+ if (p.action === "create") lines.push(...p.after.split("\n").map((l) => `+ ${l}`));
418
+ else {
419
+ const before = new Set(p.before.split("\n"));
420
+ lines.push(...p.after.split("\n").filter((l) => !before.has(l)).map((l) => `+ ${l}`));
421
+ }
422
+ }
423
+ lines.push("", "Next:", ...plan.nextSteps.map((s) => `- ${s}`));
424
+ return lines.join("\n");
425
+ }
426
+ var header = (c) => `${c} Added by \`rconfig init\`. \`${SAMPLE_KEY}\` exists in your product; edit it in the dashboard and publish.`;
427
+ var imports = (list2) => [...new Set(list2)].sort().map((i) => `import ${i}`).join("\n");
428
+ var KEYS = `/** Parameter keys, in one place. */
429
+ object RConfigKeys {
430
+ const val WELCOME_MESSAGE = "${SAMPLE_KEY}"
431
+ }`;
432
+ var DEFAULTS = `defaults = mapOf(RConfigKeys.WELCOME_MESSAGE to "${SAMPLE_DEFAULT}")`;
433
+ var KOIN = `
434
+ /** Add to startKoin { modules(\u2026) }. Binds RemoteConfig (and RConfigCore) as singletons. */
435
+ val rconfigModule = module {
436
+ remoteConfig(rconfigOptions)
437
+ }
438
+ `;
439
+ function kotlinSetup(o) {
440
+ const { i, d } = o;
441
+ const list2 = [
442
+ "com.mobilebytelabs.remoteconfig.RConfigOptions",
443
+ "com.mobilebytelabs.remoteconfig.RemoteConfig",
444
+ ...o.extra ?? []
445
+ ];
446
+ if (d.di !== "koin") list2.push("io.ktor.client.HttpClient", ...o.engine ? [o.engine.import] : []);
447
+ const client = o.engine ? o.engine.expr : "httpClient";
448
+ const initParams = o.engine ? "" : "httpClient: HttpClient";
449
+ let wiring;
450
+ switch (d.di) {
451
+ case "koin":
452
+ list2.push("com.mobilebytelabs.remoteconfig.remoteConfig", "org.koin.dsl.module");
453
+ wiring = KOIN;
454
+ break;
455
+ case "hilt":
456
+ case "dagger":
457
+ list2.push("dagger.Module", "dagger.Provides", "javax.inject.Singleton");
458
+ if (d.di === "hilt") list2.push("dagger.hilt.InstallIn", "dagger.hilt.components.SingletonComponent");
459
+ wiring = `
460
+ /** The one initialisation: inject RemoteConfig anywhere your graph reaches. */
461
+ @Module${d.di === "hilt" ? "\n@InstallIn(SingletonComponent::class)" : ""}
462
+ object RConfigModule {
463
+ @Provides
464
+ @Singleton
465
+ fun remoteConfig(): RemoteConfig = initRemoteConfig()
466
+ }
467
+ `;
468
+ break;
469
+ default:
470
+ wiring = "";
471
+ }
472
+ const init = d.di === "koin" ? "" : `
473
+ /** Creates the app's one instance (later calls return it). Afterwards \`RemoteConfig.instance\` works anywhere too. */
474
+ fun initRemoteConfig(${initParams}): RemoteConfig = RemoteConfig.initialize(rconfigOptions, ${client})
475
+ `;
476
+ const version = o.version ? `
477
+
478
+ /** Keep in step with your release version \u2014 the server targets by it. */
479
+ const val APP_VERSION = "${o.version}"` : "";
480
+ const args = o.version ? `PUBLISHABLE_KEY, "${i.packageName}", APP_VERSION` : `PUBLISHABLE_KEY, "${i.packageName}"`;
481
+ return `${header("//")}
482
+ package rconfig
483
+
484
+ ${imports(list2)}
485
+
486
+ ${KEYS}
487
+
488
+ // A publishable key is not a secret: the server binds it to your registered package${d.type === "android" ? " and signing certificate" : ""}.
489
+ private const val PUBLISHABLE_KEY = "${i.key}"${version}
490
+
491
+ /** Everything the SDK needs to start.${o.version ? "" : " The version is read from the app (versionName)."} */
492
+ val rconfigOptions = RConfigOptions(${args}).apply {
493
+ ${o.platform ? ` platform = "${o.platform}"
494
+ ` : ""} ${DEFAULTS}
495
+ }
496
+ ${init}${wiring}${o.extraBody ?? ""}`;
497
+ }
498
+ function kmpSetup(i, version, d) {
499
+ const compose = d.ui === "compose";
500
+ return kotlinSetup({
501
+ i,
502
+ d,
503
+ version,
504
+ extra: compose ? [
505
+ "androidx.compose.runtime.Composable",
506
+ "androidx.compose.runtime.LaunchedEffect",
507
+ "com.mobilebytelabs.remoteconfig.start",
508
+ "com.mobilebytelabs.remoteconfig.ui.RConfigTemplateHost"
509
+ ] : [],
510
+ extraBody: compose ? ROOT : ""
511
+ });
512
+ }
513
+ var ROOT = `
514
+ /** Once at the root of your UI: fetches, applies live updates while composed, shows server-driven templates. */
515
+ @Composable
516
+ fun RConfigRoot(remoteConfig: RemoteConfig = RemoteConfig.instance) {
517
+ LaunchedEffect(remoteConfig) { remoteConfig.start(this) }
518
+ RConfigTemplateHost()
519
+ }
520
+ `;
521
+ function androidSetup(i, d) {
522
+ return kotlinSetup({
523
+ i,
524
+ d,
525
+ engine: { import: "io.ktor.client.engine.okhttp.OkHttp", expr: "HttpClient(OkHttp)" },
526
+ extra: [
527
+ "androidx.lifecycle.Lifecycle",
528
+ "androidx.lifecycle.ProcessLifecycleOwner",
529
+ "androidx.lifecycle.lifecycleScope",
530
+ "androidx.lifecycle.repeatOnLifecycle",
531
+ "com.mobilebytelabs.remoteconfig.applyUpdates",
532
+ "kotlinx.coroutines.launch"
533
+ ],
534
+ extraBody: `
535
+ /**
536
+ * Fetch when the app comes to the foreground and apply live updates while it stays there; the socket
537
+ * closes in the background. Call once from Application.onCreate().
538
+ */
539
+ fun RemoteConfig.syncWhileForeground() {
540
+ val app = ProcessLifecycleOwner.get()
541
+ app.lifecycleScope.launch {
542
+ app.repeatOnLifecycle(Lifecycle.State.STARTED) {
543
+ fetchAndActivate()
544
+ applyUpdates()
545
+ }
546
+ }
547
+ }
548
+ `
549
+ });
550
+ }
551
+ function desktopSetup(i, version, d) {
552
+ const compose = d.ui === "compose";
553
+ return kotlinSetup({
554
+ i,
555
+ d,
556
+ version,
557
+ platform: "desktop",
558
+ engine: { import: "io.ktor.client.engine.cio.CIO", expr: "HttpClient(CIO)" },
559
+ extra: compose ? [
560
+ "androidx.compose.runtime.Composable",
561
+ "androidx.compose.runtime.LaunchedEffect",
562
+ "com.mobilebytelabs.remoteconfig.start",
563
+ "com.mobilebytelabs.remoteconfig.ui.RConfigTemplateHost"
564
+ ] : [],
565
+ extraBody: compose ? ROOT : ""
566
+ });
567
+ }
568
+ function javaSetup(i, version, d) {
569
+ return `${header("//")}
570
+ package rconfig;
571
+
572
+ import com.mobilebytelabs.remoteconfig.RConfigOptions;
573
+ import com.mobilebytelabs.remoteconfig.java.RConfig;
574
+ import java.util.Map;
575
+
576
+ public final class RConfigSetup {
577
+ private RConfigSetup() {}
578
+
579
+ public static final String WELCOME_MESSAGE = "${SAMPLE_KEY}";
580
+
581
+ /** Creates the app's single instance; later calls return it. Callbacks arrive on the ${d.type === "android" ? "main" : "AWT event"} thread. */
582
+ public static RConfig start() {
583
+ // A publishable key is not a secret: the server binds it to your registered package.
584
+ RConfigOptions options = new RConfigOptions("${i.key}", "${i.packageName}", "${version}");
585
+ options.setPlatform("${d.type === "android" ? "android" : "desktop"}");
586
+ options.setDefaults(Map.of(WELCOME_MESSAGE, "${SAMPLE_DEFAULT}"));
587
+ RConfig rc = RConfig.initialize(options);
588
+ rc.fetchAndActivate((changed, error) -> { });
589
+ rc.addOnConfigUpdateListener(update -> rc.activate());
590
+ return rc;
591
+ }
592
+ }
593
+ `;
594
+ }
595
+ function javaModule(d) {
596
+ return `${header("//")}
597
+ package rconfig;
598
+
599
+ import com.mobilebytelabs.remoteconfig.java.RConfig;
600
+ import dagger.Module;
601
+ import dagger.Provides;
602
+ ${d.di === "hilt" ? "import dagger.hilt.InstallIn;\nimport dagger.hilt.components.SingletonComponent;\n" : ""}import javax.inject.Singleton;
603
+
604
+ @Module${d.di === "hilt" ? "\n@InstallIn(SingletonComponent.class)" : ""}
605
+ public final class RConfigModule {
606
+ @Provides
607
+ @Singleton
608
+ static RConfig rconfig() {
609
+ return RConfigSetup.start();
610
+ }
611
+ }
612
+ `;
613
+ }
614
+ function iosSetup(i) {
615
+ return `${header("//")}
616
+ import RConfig
617
+
618
+ enum RConfigKeys {
619
+ static let welcomeMessage = "${SAMPLE_KEY}"
620
+ }
621
+
622
+ enum RConfigSetup {
623
+ // A publishable key is not a secret: the server binds it to your registered bundle id.
624
+ static func start() {
625
+ RConfig.configure(publishableKey: "${i.key}", packageName: "${i.packageName}",
626
+ defaults: [RConfigKeys.welcomeMessage: "${SAMPLE_DEFAULT}"])
627
+ }
628
+ }
629
+ `;
630
+ }
631
+ function webSetup(i, version) {
632
+ return `${header("//")}
633
+ import { RConfig, renderTemplates } from "@mobilebytelabs/rconfig"
634
+
635
+ export const KEYS = { welcomeMessage: "${SAMPLE_KEY}" } as const
636
+
637
+ // A publishable key is not a secret: restrict it to your site's origin under Platforms \u2192 Web.
638
+ export const rc = new RConfig("${i.key}", "${i.packageName}", "${version}", {
639
+ defaults: { [KEYS.welcomeMessage]: "${SAMPLE_DEFAULT}" },
640
+ })
641
+
642
+ /** Fetch + apply, apply live updates, show any delivered template in \`container\`, flush analytics when the tab hides. */
643
+ export async function startRConfig(container: HTMLElement = document.body): Promise<string> {
644
+ await rc.fetchAndActivate()
645
+ rc.onConfigUpdate(() => rc.activate())
646
+ document.addEventListener("visibilitychange", () => { if (document.hidden) void rc.flushEvents() })
647
+ await renderTemplates(container, rc)
648
+ return rc.getString(KEYS.welcomeMessage)
649
+ }
650
+ `;
651
+ }
652
+
653
+ // ../mcp/src/integrate-io.ts
654
+ var SKIP = /* @__PURE__ */ new Set(["node_modules", ".git", "build", ".gradle", "dist", "DerivedData", "Pods", ".next", ".idea", ".build"]);
655
+ var WANTED = /(^|\/)(build\.gradle(\.kts)?|settings\.gradle(\.kts)?|package\.json|Package\.swift|project\.pbxproj)$|\.swift$|(^|\/)src\/[^/]+$/;
656
+ function readProject(dir) {
657
+ const out = {};
658
+ const walk = (d, depth) => {
659
+ if (depth > 6) return;
660
+ for (const name of readdirSync(d)) {
661
+ if (SKIP.has(name) || name.startsWith(".")) continue;
662
+ const p = join2(d, name);
663
+ const rel = relative(dir, p);
664
+ let st;
665
+ try {
666
+ st = statSync(p);
667
+ } catch {
668
+ continue;
669
+ }
670
+ if (st.isDirectory()) walk(p, depth + 1);
671
+ else if (WANTED.test(rel) && st.size < 512e3) out[rel] = readFileSync(p, "utf8");
672
+ }
673
+ };
674
+ walk(dir, 0);
675
+ return out;
676
+ }
677
+ var PLATFORMS = {
678
+ kmp: ["android", "ios", "desktop", "web"],
679
+ android: ["android"],
680
+ ios: ["ios"],
681
+ desktop: ["desktop"],
682
+ web: ["web"]
683
+ };
684
+ var fail = (r) => r && typeof r === "object" && "error" in r ? String(r.error) : null;
685
+ function debugFingerprint(keystore = join2(homedir(), ".android", "debug.keystore")) {
686
+ try {
687
+ const out = execFileSync(
688
+ "keytool",
689
+ ["-list", "-v", "-keystore", keystore, "-storepass", "android", "-alias", "androiddebugkey"],
690
+ { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }
691
+ );
692
+ return out.match(/SHA-?256:\s*([0-9A-F:]{95})/i)?.[1].toUpperCase() ?? null;
693
+ } catch {
694
+ return null;
695
+ }
696
+ }
697
+ async function provisionWithToken(db, token, d, packageName, name, certDigests) {
698
+ const display = name ?? packageName.split(".").pop() ?? packageName;
699
+ const slug = display.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
700
+ let appId;
701
+ let key;
702
+ const platforms = PLATFORMS[d.type];
703
+ const debug = platforms.includes("android") && !certDigests?.length ? debugFingerprint() : null;
704
+ const cert_digests = certDigests?.length ? certDigests : debug ? [debug] : void 0;
705
+ const made = await onboardApp(db, token, { display_name: display, bundle_id: packageName, platforms, cert_digests });
706
+ const err = fail(made);
707
+ if (!err) {
708
+ const m = made;
709
+ appId = m.app_id;
710
+ key = m.keys.find((k) => k.environment === "live")?.key ?? m.keys[0]?.key;
711
+ } else if (/already exists/.test(err)) {
712
+ const apps = await listApps(db, token);
713
+ if (fail(apps)) throw new Error(fail(apps));
714
+ const hit = apps.find((a) => a.slug === slug);
715
+ if (!hit) throw new Error(err);
716
+ appId = hit.id;
717
+ const keys = await listKeys(db, token, appId);
718
+ if (fail(keys)) throw new Error(fail(keys));
719
+ key = keys.filter((k) => !k.revoked_at).sort((a, b) => (a.environment === "live" ? -1 : 1) - (b.environment === "live" ? -1 : 1))[0]?.key;
720
+ } else {
721
+ throw new Error(err);
722
+ }
723
+ if (!key) throw new Error("the product has no active key \u2014 create one under Keys");
724
+ const created = await createParameter(db, token, appId, { key: "welcome_message", type: "string", default_value: "Hello from rconfig" });
725
+ const createdErr = fail(created);
726
+ if (!createdErr) {
727
+ const pub = await publish(db, token, appId, void 0, "rconfig init: welcome_message");
728
+ if (fail(pub)) throw new Error(fail(pub));
729
+ } else if (!/already has a parameter/.test(createdErr)) {
730
+ throw new Error(createdErr);
731
+ }
732
+ return { appId, key };
733
+ }
734
+ async function integrateProject(o) {
735
+ const files = readProject(o.dir);
736
+ const d = detectProject(files);
737
+ if (!d) throw new Error("no Gradle, Xcode/SPM or package.json project found here");
738
+ const packageName = o.packageName ?? d.packageName;
739
+ if (!packageName) throw new Error("could not read the package / bundle id \u2014 pass it explicitly");
740
+ let key = o.key;
741
+ let appId;
742
+ if (!key) {
743
+ if (!o.token || !o.db) throw new Error("give a publishable key (rck_\u2026) or an access token (rcp_\u2026)");
744
+ if (o.dryRun) key = "rck_live_(issued on the real run)";
745
+ else ({ appId, key } = await provisionWithToken(o.db, o.token, d, packageName, o.name, o.certDigests));
746
+ }
747
+ if (!/^rck_/.test(key)) throw new Error("the key must be a publishable key (rck_\u2026)");
748
+ const plan = planIntegration(files, d, { key, packageName, appVersion: o.appVersion });
749
+ const written = [];
750
+ if (!o.dryRun) {
751
+ for (const p of plan.patches) {
752
+ const target = join2(o.dir, p.path);
753
+ mkdirSync(dirname(target), { recursive: true });
754
+ writeFileSync(target, p.after);
755
+ written.push(p.path);
756
+ }
757
+ }
758
+ return { plan, written, appId, key, summary: describePlan(plan) };
759
+ }
760
+
761
+ // src/cli.ts
762
+ var USAGE = `Usage: rconfig <command> [options]
763
+
764
+ init [--key rck_\u2026] [--package id] [--name n] [--dry-run]
765
+ wire the SDK into the project in this directory (with an rcp_
766
+ token instead of --key it creates the product, key and a sample)
767
+ apps list
768
+ params list|set|delete params set <key> <value> --type string|boolean|number|json [--group g]
769
+ [--server-only | --no-server-only] backend-only: never sent to apps
770
+ conditions list|set|delete conditions set <name> --predicate '<json>' [--priority n]
771
+ overrides set|delete overrides set <param-key> <condition-name> <value> [--priority n]
772
+ publish [--message text] ship the drafts as a new version
773
+ rollback <version> publish an earlier version again
774
+ versions published versions, newest first
775
+ snapshot the published version: what devices receive, plus server-only values
776
+ export [-o file] drafts as an rconfig-template/1 document
777
+ import <file> [--firebase] [--mode merge|replace] [--dry-run]
778
+
779
+ Options: --app <id|slug> --env dev|staging|prod (default prod) --json
780
+ Auth: RCONFIG_TOKEN, else ~/.config/rconfig/credentials (rconfig login). An rcp_ access token \u2014
781
+ from the dashboard: Account \u2192 Access Tokens.
782
+
783
+ Every change is a DRAFT until 'rconfig publish'. Exit codes: 0 ok \xB7 1 refused by the server \xB7 2 usage.`;
784
+ var Usage = class extends Error {
785
+ };
786
+ var Refused = class extends Error {
787
+ };
788
+ function ok(r) {
789
+ if (r && typeof r === "object" && "error" in r) throw new Refused(r.error);
790
+ return r;
791
+ }
792
+ function typed2(raw, type) {
793
+ if (type === "string") return raw;
794
+ if (type === "boolean") {
795
+ if (raw !== "true" && raw !== "false") throw new Usage(`"${raw}" is not a boolean (true | false)`);
796
+ return raw === "true";
797
+ }
798
+ if (type === "number") {
799
+ const n = Number(raw);
800
+ if (raw.trim() === "" || !Number.isFinite(n)) throw new Usage(`"${raw}" is not a number`);
801
+ return n;
802
+ }
803
+ if (type === "json") {
804
+ try {
805
+ return JSON.parse(raw);
806
+ } catch {
807
+ throw new Usage(`"${raw}" is not valid JSON`);
808
+ }
809
+ }
810
+ throw new Usage(`--type must be string, boolean, number or json`);
811
+ }
812
+ async function run(argv2, d) {
813
+ let parsed;
814
+ try {
815
+ parsed = parseArgs({
816
+ args: argv2,
817
+ allowPositionals: true,
818
+ strict: true,
819
+ options: {
820
+ app: { type: "string" },
821
+ env: { type: "string" },
822
+ json: { type: "boolean" },
823
+ type: { type: "string" },
824
+ group: { type: "string" },
825
+ description: { type: "string" },
826
+ // Two flags rather than allowNegative, which needs Node 22.4 (engines says 20).
827
+ "server-only": { type: "boolean" },
828
+ "no-server-only": { type: "boolean" },
829
+ predicate: { type: "string" },
830
+ priority: { type: "string" },
831
+ cascade: { type: "boolean" },
832
+ message: { type: "string" },
833
+ output: { type: "string", short: "o" },
834
+ firebase: { type: "boolean" },
835
+ mode: { type: "string" },
836
+ "dry-run": { type: "boolean" },
837
+ key: { type: "string" },
838
+ package: { type: "string" },
839
+ name: { type: "string" },
840
+ help: { type: "boolean", short: "h" }
841
+ }
842
+ });
843
+ } catch (e) {
844
+ d.err(`${e.message}
845
+
846
+ ${USAGE}`);
847
+ return 2;
848
+ }
849
+ const { values: o, positionals: [cmd, ...rest] } = parsed;
850
+ if (!cmd || o.help) {
851
+ d.err(USAGE);
852
+ return o.help ? 0 : 2;
853
+ }
854
+ const show = (v, human) => d.out(o.json || !human ? JSON.stringify(v, null, 2) : human());
855
+ if (cmd === "init") {
856
+ try {
857
+ const token = d.token();
858
+ const r = await integrateProject({
859
+ dir: d.cwd?.() ?? ".",
860
+ key: o.key,
861
+ packageName: o.package,
862
+ name: o.name,
863
+ dryRun: o["dry-run"],
864
+ token: token && /^rcp_/.test(token) ? token : void 0,
865
+ db: token && /^rcp_/.test(token) ? d.client(token) : void 0
866
+ });
867
+ if (o.json) show({ type: r.plan.detection.type, app_id: r.appId, key: r.key, written: r.written, next: r.plan.nextSteps });
868
+ else d.out(`${o["dry-run"] ? "Dry run \u2014 nothing written.\n\n" : ""}${r.summary}${r.written.length ? `
869
+
870
+ Wrote ${r.written.length} file(s).` : ""}`);
871
+ return 0;
872
+ } catch (e) {
873
+ d.err(`rconfig init: ${e.message}`);
874
+ return /key|token|project|package/.test(e.message) ? 2 : 1;
875
+ }
876
+ }
877
+ try {
878
+ const env2 = o.env;
879
+ if (env2 && !["dev", "staging", "prod"].includes(env2)) throw new Usage("--env must be dev, staging or prod");
880
+ const token = d.token();
881
+ if (!token) throw new Usage("no access token: set RCONFIG_TOKEN or run 'rconfig login'");
882
+ if (/^rck_/.test(token)) {
883
+ throw new Usage("that is a publishable key (rck_\u2026), which is PUBLIC and belongs in your app's source. Authenticate with an access token (rcp_\u2026) from Account \u2192 Access Tokens.");
884
+ }
885
+ const db = d.client(token);
886
+ const appId = async () => {
887
+ if (!o.app) throw new Usage("--app <id|slug> is required");
888
+ if (/^[0-9a-f-]{36}$/i.test(o.app)) return o.app;
889
+ const apps = ok(await listApps(db, token));
890
+ const hit = apps.find((a) => a.slug === o.app);
891
+ if (!hit) throw new Usage(`no app with slug "${o.app}" in this token's scope`);
892
+ return hit.id;
893
+ };
894
+ const paramByKey = async (app, key) => ok(await listParameters(db, token, app, env2)).find((p) => p.key === key);
895
+ const conditionByName = async (app, name) => ok(await listConditions(db, token, app, env2)).find((c) => c.name === name);
896
+ const need = (v, what) => {
897
+ if (v === void 0) throw new Usage(`missing ${what}`);
898
+ return v;
899
+ };
900
+ const sub = rest[0];
901
+ const serverOnly = o["server-only"] ? { server_only: true } : o["no-server-only"] ? { server_only: false } : {};
902
+ switch (cmd) {
903
+ case "apps": {
904
+ if (sub !== "list") throw new Usage("apps list");
905
+ const apps = ok(await listApps(db, token));
906
+ show(apps, () => apps.map((a) => `${a.slug.padEnd(28)} ${a.id} ${a.display_name}`).join("\n"));
907
+ return 0;
908
+ }
909
+ case "params": {
910
+ const app = await appId();
911
+ if (sub === "list") {
912
+ const ps = ok(await listParameters(db, token, app, env2));
913
+ show(ps, () => ps.map((p) => `${p.key.padEnd(28)} ${p.type.padEnd(8)} ${JSON.stringify(p.default_value)}${p.override_count ? ` (+${p.override_count} overrides)` : ""}${p.server_only ? " [server only]" : ""}`).join("\n") || "(no parameters)");
914
+ return 0;
915
+ }
916
+ const key = need(rest[1], "<key>");
917
+ if (sub === "delete") {
918
+ const p = await paramByKey(app, key);
919
+ if (!p) throw new Refused(`no parameter "${key}"`);
920
+ show(ok(await deleteParameter(db, token, p.id)), () => `deleted ${key} (draft \u2014 publish to ship)`);
921
+ return 0;
922
+ }
923
+ if (sub !== "set") throw new Usage("params list|set|delete");
924
+ const raw = need(rest[2], "<value>");
925
+ const existing = await paramByKey(app, key);
926
+ const type = o.type ?? (existing ? void 0 : "string");
927
+ const value = typed2(raw, type ?? existing?.type ?? "string");
928
+ if (existing) {
929
+ ok(await updateParameter(db, token, existing.id, {
930
+ default_value: value,
931
+ ...o.type ? { type: o.type } : {},
932
+ ...o.group !== void 0 ? { group: o.group } : {},
933
+ ...o.description !== void 0 ? { description: o.description } : {},
934
+ ...serverOnly
935
+ }));
936
+ d.out(`updated ${key} (draft \u2014 publish to ship)`);
937
+ } else {
938
+ ok(await createParameter(db, token, app, {
939
+ key,
940
+ type,
941
+ default_value: value,
942
+ ...o.group ? { group: o.group } : {},
943
+ ...o.description ? { description: o.description } : {},
944
+ ...serverOnly
945
+ }, env2));
946
+ d.out(`created ${key} (draft \u2014 publish to ship)`);
947
+ }
948
+ return 0;
949
+ }
950
+ case "conditions": {
951
+ const app = await appId();
952
+ if (sub === "list") {
953
+ const cs = ok(await listConditions(db, token, app, env2));
954
+ show(cs, () => cs.map((c) => `${String(c.priority ?? "-").padStart(4)} ${c.name.padEnd(24)} ${JSON.stringify(c.predicate)} used by ${c.used_by}`).join("\n") || "(no conditions)");
955
+ return 0;
956
+ }
957
+ const name = need(rest[1], "<name>");
958
+ const existing = await conditionByName(app, name);
959
+ if (sub === "delete") {
960
+ if (!existing) throw new Refused(`no condition "${name}"`);
961
+ show(ok(await deleteCondition(db, token, existing.id, o.cascade ?? false)), () => `deleted ${name}`);
962
+ return 0;
963
+ }
964
+ if (sub !== "set") throw new Usage("conditions list|set|delete");
965
+ let predicate;
966
+ if (o.predicate !== void 0) {
967
+ try {
968
+ predicate = JSON.parse(o.predicate);
969
+ } catch {
970
+ throw new Usage(`--predicate must be JSON, e.g. '{"platforms":["ios"]}'`);
971
+ }
972
+ }
973
+ const priority = o.priority !== void 0 ? Number(o.priority) : void 0;
974
+ if (priority !== void 0 && !Number.isInteger(priority)) throw new Usage("--priority must be an integer");
975
+ if (existing) {
976
+ ok(await updateCondition(db, token, existing.id, { ...predicate ? { predicate } : {}, ...priority !== void 0 ? { priority } : {} }));
977
+ d.out(`updated condition ${name}`);
978
+ } else {
979
+ ok(await createCondition(db, token, app, { name, predicate: predicate ?? {}, ...priority !== void 0 ? { priority } : {} }, env2));
980
+ d.out(`created condition ${name}`);
981
+ }
982
+ return 0;
983
+ }
984
+ case "overrides": {
985
+ const app = await appId();
986
+ const key = need(rest[1], "<param-key>"), cname = need(rest[2], "<condition-name>");
987
+ const p = await paramByKey(app, key);
988
+ const c = await conditionByName(app, cname);
989
+ if (!p) throw new Refused(`no parameter "${key}"`);
990
+ if (!c) throw new Refused(`no condition "${cname}"`);
991
+ if (sub === "delete") {
992
+ ok(await deleteOverride(db, token, { parameter_id: p.id, condition_id: c.id }));
993
+ d.out(`removed ${cname} from ${key}`);
994
+ return 0;
995
+ }
996
+ if (sub !== "set") throw new Usage("overrides set|delete");
997
+ const value = typed2(need(rest[3], "<value>"), p.type);
998
+ const priority = o.priority !== void 0 ? Number(o.priority) : void 0;
999
+ const updated = await updateOverride(db, token, { parameter_id: p.id, condition_id: c.id, value, ...priority !== void 0 ? { priority } : {} });
1000
+ if (updated && typeof updated === "object" && "error" in updated) {
1001
+ ok(await addOverride(db, token, { parameter_id: p.id, condition_id: c.id, value, ...priority !== void 0 ? { priority } : {} }));
1002
+ }
1003
+ d.out(`${key} \u2192 ${JSON.stringify(value)} when ${cname} (draft \u2014 publish to ship)`);
1004
+ return 0;
1005
+ }
1006
+ case "publish": {
1007
+ const r = ok(await publish(db, token, await appId(), env2, o.message));
1008
+ show(r, () => `published v${r.version}${env2 ? ` (${env2})` : ""}`);
1009
+ return 0;
1010
+ }
1011
+ case "rollback": {
1012
+ const v = Number(need(sub, "<version>"));
1013
+ if (!Number.isInteger(v) || v < 1) throw new Usage("rollback <version> \u2014 a positive integer");
1014
+ const r = ok(await rollback(db, token, await appId(), v, env2));
1015
+ show(r, () => `rolled back: v${r.version} now carries v${v}'s content`);
1016
+ return 0;
1017
+ }
1018
+ case "versions": {
1019
+ const vs = ok(await listVersions(db, token, await appId(), env2));
1020
+ show(vs, () => vs.map((v) => `v${v.version} ${v.published_at}${v.rolled_back_from ? ` (rollback of v${v.rolled_back_from})` : ""}`).join("\n") || "(never published)");
1021
+ return 0;
1022
+ }
1023
+ case "snapshot": {
1024
+ show(ok(await getPublishedSnapshot(db, token, await appId(), env2)));
1025
+ return 0;
1026
+ }
1027
+ case "export": {
1028
+ const tpl = ok(await exportTemplate(db, token, await appId(), env2));
1029
+ const text = JSON.stringify(tpl, null, 2) + "\n";
1030
+ if (o.output) {
1031
+ d.writeFile(o.output, text);
1032
+ d.err(`wrote ${o.output}`);
1033
+ } else d.out(text.trimEnd());
1034
+ return 0;
1035
+ }
1036
+ case "import": {
1037
+ const file = need(sub, "<file>");
1038
+ const mode = o.mode ?? "merge";
1039
+ if (!["merge", "replace"].includes(mode)) throw new Usage("--mode must be merge or replace");
1040
+ let doc;
1041
+ try {
1042
+ doc = JSON.parse(d.readFile(file));
1043
+ } catch (e) {
1044
+ throw new Usage(`cannot read ${file}: ${e.message}`);
1045
+ }
1046
+ const app = await appId();
1047
+ const dry = o["dry-run"] ?? false;
1048
+ const conv = o.firebase ? fromFirebase(doc) : { template: doc, report: null };
1049
+ const counts = ok(await importTemplate(db, token, app, conv.template, { mode, dry_run: dry, env: env2 }));
1050
+ show({ counts, report: conv.report }, () => {
1051
+ const lines = [`${dry ? "dry run \u2014 nothing written: would" : "imported as drafts:"} create ${counts.create}, update ${counts.update}, delete ${counts.delete}`];
1052
+ if (counts.configs_not_imported) lines.push(`(${counts.configs_not_imported} config(s) in the file were not imported)`);
1053
+ const r = conv.report;
1054
+ if (r) {
1055
+ for (const s of r.skipped_conditions) lines.push(`skipped condition ${s.name}: ${s.reason}`);
1056
+ for (const s of r.skipped_parameters) lines.push(`skipped parameter ${s.key}: ${s.reason}`);
1057
+ for (const v of r.dropped_values) lines.push(`dropped ${v.parameter} @ ${v.condition}: ${v.reason}`);
1058
+ lines.push(...r.notes.map((n) => `note: ${n}`));
1059
+ }
1060
+ if (!dry) lines.push("Nothing reaches a device until 'rconfig publish'.");
1061
+ return lines.join("\n");
1062
+ });
1063
+ return 0;
1064
+ }
1065
+ default:
1066
+ throw new Usage(`unknown command "${cmd}"`);
1067
+ }
1068
+ } catch (e) {
1069
+ if (e instanceof Usage) {
1070
+ d.err(`${e.message}
1071
+
1072
+ ${USAGE}`);
1073
+ return 2;
1074
+ }
1075
+ d.err(`rconfig: ${e.message}`);
1076
+ return 1;
1077
+ }
1078
+ }
1079
+
1080
+ // src/main.ts
1081
+ var URL_ = process.env.RCONFIG_URL ?? "https://gohifhjcvsawcdhcpbkw.supabase.co/functions/v1";
1082
+ var CREDENTIALS = join3(homedir2(), ".config", "rconfig", "credentials");
1083
+ function storedToken() {
1084
+ try {
1085
+ return readFileSync2(CREDENTIALS, "utf8").trim() || void 0;
1086
+ } catch {
1087
+ return void 0;
1088
+ }
1089
+ }
1090
+ async function hidden(prompt) {
1091
+ process.stderr.write(prompt);
1092
+ const stdin = process.stdin;
1093
+ if (!stdin.isTTY) {
1094
+ let s2 = "";
1095
+ for await (const chunk of stdin) s2 += chunk;
1096
+ return s2.trim();
1097
+ }
1098
+ stdin.setRawMode(true);
1099
+ stdin.resume();
1100
+ let s = "";
1101
+ return new Promise((resolve) => {
1102
+ stdin.on("data", (b) => {
1103
+ for (const ch of b.toString("utf8")) {
1104
+ if (ch === "\r" || ch === "\n") {
1105
+ stdin.setRawMode(false);
1106
+ stdin.pause();
1107
+ process.stderr.write("\n");
1108
+ resolve(s.trim());
1109
+ return;
1110
+ }
1111
+ if (ch === "") process.exit(130);
1112
+ if (ch === "\x7F") s = s.slice(0, -1);
1113
+ else s += ch;
1114
+ }
1115
+ });
1116
+ });
1117
+ }
1118
+ async function login() {
1119
+ const token = await hidden("rcp_ access token (Account \u2192 Access Tokens): ");
1120
+ if (!/^rcp_[A-Za-z0-9]{40}$/.test(token)) {
1121
+ process.stderr.write(/^rck_/.test(token) ? "that is a publishable key (rck_\u2026), which is PUBLIC and belongs in your app's source. Use an rcp_ access token.\n" : "that is not an rcp_ access token.\n");
1122
+ return 2;
1123
+ }
1124
+ mkdirSync2(join3(homedir2(), ".config", "rconfig"), { recursive: true, mode: 448 });
1125
+ writeFileSync2(CREDENTIALS, token + "\n", { mode: 384 });
1126
+ chmodSync(CREDENTIALS, 384);
1127
+ process.stderr.write(`saved to ${CREDENTIALS} (0600)
1128
+ `);
1129
+ return 0;
1130
+ }
1131
+ var argv = process.argv.slice(2);
1132
+ var code = argv[0] === "login" ? await login() : await run(argv, {
1133
+ client: (token) => createApiClient(URL_, token),
1134
+ token: () => process.env.RCONFIG_TOKEN || storedToken(),
1135
+ out: (s) => process.stdout.write(s + "\n"),
1136
+ err: (s) => process.stderr.write(s + "\n"),
1137
+ readFile: (p) => readFileSync2(p, "utf8"),
1138
+ writeFile: (p, s) => writeFileSync2(p, s),
1139
+ cwd: () => process.cwd()
1140
+ });
1141
+ process.exit(code);
package/package.json CHANGED
@@ -1,6 +1,36 @@
1
1
  {
2
2
  "name": "@mobilebytelabs/rconfig-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.1",
4
+ "description": "Command line for the rconfig control plane: parameters, conditions, publish, export/import, Firebase migration.",
5
+ "type": "module",
6
+ "bin": {
7
+ "rconfig": "dist/cli.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "scripts": {
16
+ "build": "esbuild src/main.ts --bundle --platform=node --format=esm --target=node20 --outfile=dist/cli.js --banner:js='#!/usr/bin/env node'",
17
+ "test": "node --test --experimental-strip-types __tests__/*.test.ts",
18
+ "typecheck": "tsc --noEmit -p .",
19
+ "prepack": "npm run build"
20
+ },
21
+ "devDependencies": {
22
+ "@types/node": "^22.9.0",
23
+ "esbuild": "^0.25.0",
24
+ "typescript": "^5.9.3"
25
+ },
26
+ "license": "Apache-2.0",
27
+ "repository": {
28
+ "type": "git",
29
+ "url": "git+https://github.com/therajanmaurya/kmp-remote-config.git",
30
+ "directory": "cli"
31
+ },
32
+ "homepage": "https://rconfig.mobilebytesensei.com/docs",
33
+ "publishConfig": {
34
+ "access": "public"
35
+ }
36
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.