@composable-os/cli 0.0.0-stage → 0.1.0-beta.10

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 (176) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +24 -2
  3. package/dist/accounts-X4CKM3HL.js +46 -0
  4. package/dist/blocks-YWDHEBOK.js +233 -0
  5. package/dist/chunk-2ABSVMGB.js +13 -0
  6. package/dist/chunk-5KSXSK7Y.js +47 -0
  7. package/dist/chunk-6GDEDOV7.js +157 -0
  8. package/dist/chunk-6UPUF4ML.js +29998 -0
  9. package/dist/chunk-6UWRT4VM.js +220 -0
  10. package/dist/chunk-6VXHPKGG.js +1302 -0
  11. package/dist/chunk-7CQGMVDO.js +63 -0
  12. package/dist/chunk-A4NTSYWV.js +11092 -0
  13. package/dist/chunk-CP6BXI6F.js +25825 -0
  14. package/dist/chunk-DU6OIFOU.js +2358 -0
  15. package/dist/chunk-E4WCYTCT.js +347 -0
  16. package/dist/chunk-GYSGVT6R.js +284 -0
  17. package/dist/chunk-GYTEW66E.js +50 -0
  18. package/dist/chunk-HDIOVFAZ.js +544 -0
  19. package/dist/chunk-IFG4FRW5.js +504 -0
  20. package/dist/chunk-JJHHNV46.js +227 -0
  21. package/dist/chunk-K6T42YCH.js +704 -0
  22. package/dist/chunk-KGHA67HG.js +765 -0
  23. package/dist/chunk-LJFLENFC.js +88 -0
  24. package/dist/chunk-LLULPZAJ.js +365 -0
  25. package/dist/chunk-M7A6FR2Z.js +2586 -0
  26. package/dist/chunk-O2UIZHND.js +249 -0
  27. package/dist/chunk-Q4N55M2Z.js +552 -0
  28. package/dist/chunk-QGGJ2G6Z.js +349 -0
  29. package/dist/chunk-R4W5XAUD.js +837 -0
  30. package/dist/chunk-TQFGGSA4.js +748 -0
  31. package/dist/chunk-VY64DMQO.js +15302 -0
  32. package/dist/chunk-WC5LHBBA.js +426 -0
  33. package/dist/chunk-WO6D3XP3.js +9351 -0
  34. package/dist/chunk-Y7JZFSTQ.js +1425 -0
  35. package/dist/chunk-YJJHF65I.js +759 -0
  36. package/dist/chunk-Z3RMMB6S.js +668 -0
  37. package/dist/cli-2DFENR62.js +134 -0
  38. package/dist/cli-YIOVSKOD.js +24531 -0
  39. package/dist/cli.js +25 -0
  40. package/dist/client-repo-PRU3VCQQ.js +55 -0
  41. package/dist/create.js +25 -0
  42. package/dist/fields-2NC7LSYE.js +50 -0
  43. package/dist/grants-QXMKYMGB.js +32 -0
  44. package/dist/invoke-I3NNNXVL.js +39 -0
  45. package/dist/order-PUWD65BC.js +19 -0
  46. package/dist/person-WIQQ7ITU.js +68 -0
  47. package/dist/plan-on-sale-NB774CQL.js +26 -0
  48. package/dist/platform/migrations/0001_init.sql +59 -0
  49. package/dist/platform/migrations/0002_users_settings.sql +34 -0
  50. package/dist/platform/migrations/0003_people_organisations.sql +225 -0
  51. package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
  52. package/dist/platform/migrations/0005_views_audit.sql +79 -0
  53. package/dist/platform/migrations/0006_search.sql +223 -0
  54. package/dist/platform/migrations/0007_crm_views.sql +141 -0
  55. package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
  56. package/dist/platform/migrations/0010_approval_queue.sql +90 -0
  57. package/dist/platform/migrations/0011_connected_apps.sql +36 -0
  58. package/dist/platform/migrations/0020_extensions.sql +373 -0
  59. package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
  60. package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
  61. package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
  62. package/dist/platform/migrations/0061_audit_retention.sql +95 -0
  63. package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
  64. package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
  65. package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
  66. package/dist/platform/migrations/0065_storage_stats.sql +13 -0
  67. package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
  68. package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
  69. package/dist/platform/migrations/0100_stage_history.sql +54 -0
  70. package/dist/platform/migrations/0110_integrations.sql +103 -0
  71. package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
  72. package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
  73. package/dist/platform/migrations/0130_automations.sql +113 -0
  74. package/dist/platform/migrations/0131_notifications.sql +29 -0
  75. package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
  76. package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
  77. package/dist/platform/migrations/0160_releases.sql +41 -0
  78. package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
  79. package/dist/platform/migrations/0170_automation_connections.sql +32 -0
  80. package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
  81. package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
  82. package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
  83. package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
  84. package/dist/platform/migrations/0210_daily_digest.sql +33 -0
  85. package/dist/platform/migrations/0220_entitlements.sql +13 -0
  86. package/dist/platform/migrations/0221_support_grants.sql +33 -0
  87. package/dist/platform/migrations/0250_judge.sql +11 -0
  88. package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
  89. package/dist/platform/migrations/0252_judge_usage.sql +14 -0
  90. package/dist/platform/migrations/0255_summary_checks.sql +9 -0
  91. package/dist/platform/migrations/0256_outbound_check.sql +9 -0
  92. package/dist/platform/migrations/0260_ai_usage.sql +20 -0
  93. package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
  94. package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
  95. package/dist/platform/migrations/0320_duplicates.sql +41 -0
  96. package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
  97. package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
  98. package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
  99. package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
  100. package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
  101. package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
  102. package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
  103. package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
  104. package/dist/platform/migrations/0362_voice_usage.sql +17 -0
  105. package/dist/platform/migrations/0365_routines.sql +38 -0
  106. package/dist/platform/migrations/0370_approval_execution.sql +20 -0
  107. package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
  108. package/dist/platform/migrations/0380_rec_views.sql +94 -0
  109. package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
  110. package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
  111. package/dist/platform/migrations/0402_erase_requests.sql +34 -0
  112. package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
  113. package/dist/platform/migrations/0411_device_sessions.sql +33 -0
  114. package/dist/platform/migrations/0420_transition_history.sql +100 -0
  115. package/dist/platform/migrations/0421_orders.sql +134 -0
  116. package/dist/platform/migrations/0422_order_payments.sql +109 -0
  117. package/dist/platform/migrations/0440_capacity.sql +100 -0
  118. package/dist/platform/migrations/0441_capacity_views.sql +40 -0
  119. package/dist/platform/migrations/0450_order_grants.sql +21 -0
  120. package/dist/platform/migrations/0451_pack_roles.sql +18 -0
  121. package/dist/platform/migrations/0460_content.sql +59 -0
  122. package/dist/platform/migrations/0461_media.sql +52 -0
  123. package/dist/platform/migrations/0470_publish_versions.sql +36 -0
  124. package/dist/platform/migrations/0471_permission_grants.sql +18 -0
  125. package/dist/platform/migrations/0490_staff_invites.sql +40 -0
  126. package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
  127. package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
  128. package/dist/platform/migrations/0500_published_media_field.sql +25 -0
  129. package/dist/platform/migrations/0501_import_keys.sql +23 -0
  130. package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
  131. package/dist/platform/migrations/0516_order_tax.sql +63 -0
  132. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  133. package/dist/platform/migrations/0530_subscriptions.sql +173 -0
  134. package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
  135. package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
  136. package/dist/platform/migrations/0533_allowances.sql +262 -0
  137. package/dist/platform/migrations/0560_recurring.sql +75 -0
  138. package/dist/platform/migrations/0580_subscription_grants.sql +21 -0
  139. package/dist/platform/migrations/0581_once_per_person.sql +34 -0
  140. package/dist/platform/migrations/0600_tool_actions_ran_at_queue.sql +22 -0
  141. package/dist/platform/sdk/allowance.ts +522 -0
  142. package/dist/platform/sdk/automation-check.ts +534 -0
  143. package/dist/platform/sdk/automation.ts +743 -0
  144. package/dist/platform/sdk/behaviour.ts +215 -0
  145. package/dist/platform/sdk/capacity.ts +201 -0
  146. package/dist/platform/sdk/contract.ts +884 -0
  147. package/dist/platform/sdk/document.ts +935 -0
  148. package/dist/platform/sdk/field-types.ts +111 -0
  149. package/dist/platform/sdk/formula/ast.ts +72 -0
  150. package/dist/platform/sdk/formula/compile.ts +454 -0
  151. package/dist/platform/sdk/formula/index.ts +4 -0
  152. package/dist/platform/sdk/formula/parser.ts +417 -0
  153. package/dist/platform/sdk/index.ts +36 -0
  154. package/dist/platform/sdk/manifest.ts +1709 -0
  155. package/dist/platform/sdk/media.ts +108 -0
  156. package/dist/platform/sdk/permissions.ts +60 -0
  157. package/dist/platform/sdk/recurring.ts +321 -0
  158. package/dist/platform/sdk/renamed.ts +63 -0
  159. package/dist/platform/sdk/rich-text-fixture.ts +68 -0
  160. package/dist/platform/sdk/rich-text.ts +221 -0
  161. package/dist/platform/sdk/runtime.ts +410 -0
  162. package/dist/platform/sdk/sellable.ts +888 -0
  163. package/dist/platform/sdk/slug.ts +25 -0
  164. package/dist/platform/sdk/states.ts +484 -0
  165. package/dist/platform/sdk/testing.ts +847 -0
  166. package/dist/platform/sdk/unique.ts +81 -0
  167. package/dist/products-2H5DR232.js +11 -0
  168. package/dist/run-PZUCSDDL.js +508 -0
  169. package/dist/run-RT2HVWMK.js +648 -0
  170. package/dist/run-Y7T4TVOL.js +309 -0
  171. package/dist/src-GYS6NBQB.js +44 -0
  172. package/dist/src-XTOD7EXW.js +348 -0
  173. package/dist/token-MOJUA2U6.js +70 -0
  174. package/dist/token-util-TENRN4V7.js +6 -0
  175. package/dist/visibility-DLGHU4YN.js +33 -0
  176. package/package.json +33 -4
@@ -0,0 +1,1302 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ CHANNELS,
4
+ CloudflareClient,
5
+ GATEWAY_TOKEN_SECRET,
6
+ JUDGE_BYOK_VAR,
7
+ JUDGE_GATEWAY_PROVIDER,
8
+ MODEL_ROLES_VAR,
9
+ apiKillSwitchStore,
10
+ appliedMigrationsViaApi,
11
+ applyBundleMigrations,
12
+ compareVersions,
13
+ d1ApiMigrations,
14
+ databaseIdOf,
15
+ deployWorkers,
16
+ fetchReleaseManifest,
17
+ fetchVerifiedRelease,
18
+ gatewayProviderSlug,
19
+ getRelease,
20
+ healthSmoke,
21
+ installedExtensionsViaApi,
22
+ killSwitchControl,
23
+ listReleases,
24
+ locateDeployment,
25
+ mergeSecrets,
26
+ neededResources,
27
+ newRunId,
28
+ openBundle,
29
+ preflight,
30
+ provisionAiGateway,
31
+ provisionResources,
32
+ releaseAssetNames,
33
+ retireGatewayToken,
34
+ rollbackTarget,
35
+ runRollback,
36
+ runUpdate,
37
+ runsViaApi,
38
+ saveRunViaApi,
39
+ toHex,
40
+ varWorkers,
41
+ verifyBundleBytes,
42
+ withByokProvider,
43
+ withDeploymentVar,
44
+ workersDevHostname,
45
+ writeDeploymentState
46
+ } from "./chunk-DU6OIFOU.js";
47
+ import {
48
+ PROVIDER_INFO,
49
+ ROLE_PRESETS,
50
+ RoleLayerError,
51
+ modelRolesVar
52
+ } from "./chunk-KGHA67HG.js";
53
+ import {
54
+ DEFAULT_PRODUCT,
55
+ products
56
+ } from "./chunk-2ABSVMGB.js";
57
+ import {
58
+ PRODUCT_LABEL_VAR
59
+ } from "./chunk-6UWRT4VM.js";
60
+
61
+ // src/io.ts
62
+ import { createInterface } from "node:readline/promises";
63
+ var Redactor = class {
64
+ values = /* @__PURE__ */ new Set();
65
+ add(value) {
66
+ if (value && value.length >= 6) this.values.add(value);
67
+ }
68
+ clean(text) {
69
+ let out = text;
70
+ for (const value of this.values) out = out.split(value).join("***");
71
+ return out;
72
+ }
73
+ };
74
+ function terminalIo(redactor) {
75
+ const interactive = Boolean(process.stdin.isTTY && process.stdout.isTTY);
76
+ return {
77
+ interactive,
78
+ out: (line) => process.stdout.write(`${redactor.clean(line)}
79
+ `),
80
+ err: (line) => process.stderr.write(`${redactor.clean(line)}
81
+ `),
82
+ async ask(question, options = {}) {
83
+ const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
84
+ const suffix = options.default ? ` [${options.default}]` : "";
85
+ if (options.secret) {
86
+ const output = rl;
87
+ const prompt = `${question}${suffix}: `;
88
+ process.stdout.write(prompt);
89
+ output._writeToOutput = () => {
90
+ };
91
+ const answer2 = await rl.question("");
92
+ process.stdout.write("\n");
93
+ rl.close();
94
+ return answer2.trim() || options.default || "";
95
+ }
96
+ const answer = await rl.question(`${question}${suffix}: `);
97
+ rl.close();
98
+ return answer.trim() || options.default || "";
99
+ }
100
+ };
101
+ }
102
+ async function choose(io, question, choices, fallback) {
103
+ if (choices.length === 1) return choices[0];
104
+ io.out(question);
105
+ for (const [i, c] of choices.entries()) io.out(` ${i + 1}) ${c}`);
106
+ for (; ; ) {
107
+ const answer = await io.ask("Choose", fallback ? { default: fallback } : {});
108
+ const index = Number(answer) - 1;
109
+ if (choices[index]) return choices[index];
110
+ if (choices.includes(answer)) return answer;
111
+ io.err(`Pick 1-${choices.length}.`);
112
+ }
113
+ }
114
+
115
+ // src/main.ts
116
+ import { existsSync, readFileSync } from "node:fs";
117
+ import { join } from "node:path";
118
+ var HELP = `cos: the Composable OS command. One command for a company's own repository and for
119
+ installing a product with no repository.
120
+
121
+ A client repo (stage 24)
122
+ cos create <dir> [--label <name>] [--with-mobile] [--version x.y.z]
123
+ a new client repo from the release's template (also
124
+ \`npm create composable-os <dir>\`)
125
+ cos init [--web <dir>] [--mobile <dir>] [--id <id>] [--label <name>] [--packs <list>]
126
+ [--envs staging,live] [--yes]
127
+ adopt the repo you are in: adds product.ts, skills/, each
128
+ app's typed client and host module and the rules in
129
+ AGENTS.md; shows a diff of every change to a file that
130
+ exists and applies it with --yes. The id and label default
131
+ to the folder's name; an adopted web app keeps its Worker
132
+ and deploys itself (web.deploy "own"); --envs declares
133
+ environments and binds HOST under the site's own ones
134
+ cos deploy [--env <name>] the host from the release in product.ts, with its packs and
135
+ the org's own extensions (checked first), then the web app;
136
+ with environments in product.ts, the one --env names
137
+ (--rotate-customer-auth-secret: a new customer secret,
138
+ which signs every customer out)
139
+ cos upgrade [--version X.Y.Z] in a client repo: move product.ts to a newer platform
140
+ version, regenerate the client, replace skills/, report type
141
+ errors; deploys nothing
142
+ cos add <block>, cos diff <block> [--accept]
143
+ copy a block from the release; show its upstream changes
144
+ (--accept: record them as merged by hand)
145
+ (cos add with no block lists them, with their skins)
146
+ cos client generate in a client repo: each app's typed client, again
147
+ cos content import <folder> --host <url> [--email <you>] [--dry-run] [--publish] [--yes]
148
+ load posts and their pictures into the host as you,
149
+ signed in for the run (by code with --email, else in the
150
+ browser); checks everything first and writes nothing on a
151
+ problem; a re-run creates nothing twice; --publish
152
+ publishes (or schedules) them with their own dates
153
+ (docs/importing.md)
154
+ cos courses import <folder> --host <url> [--email <you>] [--dry-run] [--publish] [--yes]
155
+ [--wait <minutes>]
156
+ load courses, bundles, their videos (to Stream) and the
157
+ students' access, completions and lesson progress from an
158
+ old course platform, as you; checks first, uploads nothing
159
+ twice on a re-run, keeps a student's own progress
160
+ (docs/importing.md)
161
+ cos subscriptions offers import <offers.csv> --host <url> --plan <object>[:<id>]
162
+ [--email <you>] [--dry-run] [--invite] [--reissue]
163
+ continuation offers for people subscribed on another
164
+ platform (email, paid-up date): each signs in and
165
+ subscribes again, free until that date; people come
166
+ first, none is created; --invite lets them sign in under
167
+ any sign-up setting; --reissue gives an address staff
168
+ withdrew a fresh offer (docs/importing.md)
169
+ cos subscriptions offers report --host <url> [--status taken] [--out <file.csv>]
170
+ who has taken their offer and when they are charged from,
171
+ so you end exactly those old subscriptions
172
+
173
+ Installing a product with no client repo
174
+ cos install [options] install, or repair an existing install (idempotent)
175
+ cos upgrade [--version X.Y.Z] update to a newer release (preflight, bookmark, migrate,
176
+ switch all Workers, smoke check; rolls back on failure)
177
+ cos rollback redeploy the previous release and restore its bookmark
178
+ cos status installed version, channel, URL and available releases
179
+ cos uninstall delete the Workers, database, bucket and namespace (asks)
180
+ cos ext check <dir> | test <dir> in a checkout of the repository: check an extension with
181
+ the checks the host runs, and run its tests
182
+ cos client generate --out <dir> in a checkout: write a product's typed client (customer.ts
183
+ and staff.ts) from its registry; see cos client --help
184
+
185
+ Options
186
+ --token <t> Cloudflare API token (or CLOUDFLARE_API_TOKEN). Needs, on the account:
187
+ Workers Scripts Edit, D1 Edit, Workers R2 Storage Edit, Workers KV
188
+ Storage Edit, Queues Edit, Vectorize Edit, Account Settings Read; with AI
189
+ on, AI Gateway Edit, Account API Tokens Edit (to generate the gateway's
190
+ token) and Secrets Store Edit (for --provider-key); and for a custom
191
+ hostname, Zone Read + Workers Routes Edit on that zone.
192
+ --account <id> account id (or CLOUDFLARE_ACCOUNT_ID); asked when the token sees several
193
+ --version <x.y.z> release to install or upgrade to (default: newest on the channel)
194
+ --channel <c> stable (default) or beta
195
+ --hostname <h> "workers.dev" (default) or a hostname on one of your zones
196
+ --zone <name> the zone of a custom hostname (default: inferred from it)
197
+ --identity <i> better-auth (default) or cloudflare-access
198
+ --gatekeepers <list> optional gatekeeper Workers to install, e.g. google,email-send
199
+ --ai <on|off> in-app AI: Workers AI and the demo-records Vectorize index (default on,
200
+ or COS_AI). Off: AI features say "AI is not configured". Upgrades keep
201
+ the choice; re-run install with --ai to change it
202
+ --ai-gateway <id|off> AI Gateway every model call goes through (default: one named after the
203
+ install, e.g. crm, created with logging and authentication on and its
204
+ token, with AI Gateway Run and Workers AI Read, stored as
205
+ AI_GATEWAY_TOKEN). Workers AI then goes through it over REST with
206
+ prompt and response logging off. off: call Workers AI directly over
207
+ the binding
208
+ --provider-key P=KEY store a provider key in the gateway as BYOK (repeatable), e.g.
209
+ deepseek=\u2026 or openai=\u2026 (a custom provider by its slug; typesafe=\u2026 is
210
+ the judge's key, Jev, and sets JUDGE_BYOK). Never logged.
211
+ Keys can also be added later in Settings \u2192 AI
212
+ --model-roles <m> this deployment's model roles (the AI_MODEL_ROLES layer): a preset
213
+ (${Object.keys(ROLE_PRESETS).join(", ")}), a JSON file, inline JSON, or
214
+ default (the shipped Workers AI roles). Kept by upgrades; Settings \u2192 AI
215
+ overrides still win
216
+ --ai-admin-token <t> Settings \u2192 AI's token (or COS_AI_ADMIN_TOKEN), stored on demo-app as
217
+ CLOUDFLARE_API_TOKEN; permissions in docs/deploying.md "In-app AI"
218
+ --secret NAME=VALUE a secret to set (repeatable); WORKER:NAME=VALUE for a gatekeeper's
219
+ --update-token <t> store a scoped token so Settings \u2192 Updates can update in place
220
+ --store-update-token store --token itself for one-click updates
221
+ --product <id> the product to install (default ${DEFAULT_PRODUCT}; one of ${Object.keys(products).join(", ")})
222
+ --repo <owner/repo> where releases come from (default: the product's own repository)
223
+ --no-gh skip \`gh attestation verify\` even if gh is installed
224
+ --require-gh fail unless \`gh attestation verify\` passes (full Sigstore check)
225
+ --wait after install, wait until /api/health answers
226
+ --bundle-dir <dir> use composable-os-<product>-<version>.tar.gz and SHA256SUMS from <dir> instead of downloading
227
+ (still verified against its build attestation)
228
+ --yes don't ask; fail on anything that would need an answer
229
+ -h, --help
230
+
231
+ Nothing is sent anywhere except the Cloudflare API and GitHub Releases. No telemetry.
232
+ `;
233
+ function parseArgs(argv) {
234
+ const flags = {};
235
+ let command = "";
236
+ for (let i = 0; i < argv.length; i++) {
237
+ const arg = argv[i];
238
+ if (arg === "-h") {
239
+ flags.help = true;
240
+ continue;
241
+ }
242
+ if (!arg.startsWith("--")) {
243
+ if (!command) command = arg;
244
+ else throw new Error(`unexpected argument ${arg}`);
245
+ continue;
246
+ }
247
+ const [key, inline] = arg.slice(2).split(/=(.*)/s, 2);
248
+ const takesValue = ![
249
+ "yes",
250
+ "help",
251
+ "no-gh",
252
+ "require-gh",
253
+ "wait",
254
+ "store-update-token",
255
+ "json",
256
+ "unverified",
257
+ "skip-build",
258
+ "no-typecheck",
259
+ "rotate-customer-auth-secret",
260
+ "accept",
261
+ "with-mobile",
262
+ "dry-run",
263
+ "publish",
264
+ "invite",
265
+ "reissue"
266
+ ].includes(key);
267
+ let value = true;
268
+ if (takesValue) {
269
+ value = inline ?? argv[++i];
270
+ if (value === void 0) throw new Error(`--${key} needs a value`);
271
+ }
272
+ if (key === "secret") flags.secret = [...flags.secret ?? [], String(value)];
273
+ else if (key === "provider-key")
274
+ flags["provider-key"] = [...flags["provider-key"] ?? [], String(value)];
275
+ else flags[key] = value;
276
+ }
277
+ return { command, flags };
278
+ }
279
+ var CliError = class extends Error {
280
+ };
281
+ var PACKS_VAR = "COS_PACKS";
282
+ var CUSTOMER_SECRET = "CUSTOMER_AUTH_SECRET";
283
+ var ORG_EXTENSIONS_VAR = "COS_ORG_EXTENSIONS";
284
+ function str(flags, key) {
285
+ const value = flags[key];
286
+ return typeof value === "string" ? value : void 0;
287
+ }
288
+ function productOf(flags, deps) {
289
+ const known = deps.products ?? { all: products, default: DEFAULT_PRODUCT };
290
+ const id = str(flags, "product") ?? known.default;
291
+ const product = known.all[id];
292
+ if (!product) {
293
+ throw new CliError(`Unknown product ${id}. Known: ${Object.keys(known.all).join(", ")}.`);
294
+ }
295
+ return product;
296
+ }
297
+ async function session(flags, deps) {
298
+ const { io, env } = deps;
299
+ const product = productOf(flags, deps);
300
+ let token = str(flags, "token") ?? env.CLOUDFLARE_API_TOKEN;
301
+ if (!token) {
302
+ if (!io.interactive || flags.yes)
303
+ throw new CliError("A Cloudflare API token is needed: --token or CLOUDFLARE_API_TOKEN.");
304
+ io.out(
305
+ "Create a token at https://dash.cloudflare.com/profile/api-tokens with the permissions in `--help`."
306
+ );
307
+ token = await io.ask("Cloudflare API token", { secret: true });
308
+ }
309
+ deps.redactor.add(token);
310
+ const api = new CloudflareClient({
311
+ token,
312
+ ...env.COS_CLOUDFLARE_API ? { apiBase: env.COS_CLOUDFLARE_API } : {},
313
+ ...deps.fetch ? { fetch: deps.fetch } : {}
314
+ });
315
+ let accountId = str(flags, "account") ?? env.CLOUDFLARE_ACCOUNT_ID;
316
+ await api.verifyToken(accountId);
317
+ if (!accountId) {
318
+ const accounts = await api.listAccounts();
319
+ if (accounts.length === 0) throw new CliError("The token cannot see any account.");
320
+ if (accounts.length > 1 && (flags.yes || !io.interactive)) {
321
+ throw new CliError("The token sees several accounts; pass --account <id>.");
322
+ }
323
+ const label = await choose(
324
+ io,
325
+ "Which account?",
326
+ accounts.map((a) => `${a.name} (${a.id})`)
327
+ );
328
+ accountId = accounts.find((a) => label.endsWith(`(${a.id})`))?.id;
329
+ }
330
+ const source = releaseSource(flags, deps, product);
331
+ return { ...source, api, accountId };
332
+ }
333
+ function githubToken(deps) {
334
+ const token = deps.env.GITHUB_TOKEN || deps.env.GH_TOKEN || void 0;
335
+ if (token) deps.redactor.add(token);
336
+ return token;
337
+ }
338
+ function releaseSource(flags, deps, product) {
339
+ const { env } = deps;
340
+ const repository = str(flags, "repo") ?? product.updateRepository;
341
+ const github = {
342
+ repository,
343
+ product: product.id,
344
+ ...env.COS_GITHUB_API ? { apiBase: env.COS_GITHUB_API } : {},
345
+ ...deps.fetch ? { fetch: deps.fetch } : {},
346
+ ...githubToken(deps) ? { token: githubToken(deps) } : {}
347
+ };
348
+ const bundleDir = str(flags, "bundle-dir");
349
+ if (flags.unverified && !bundleDir)
350
+ throw new CliError("--unverified only applies to --bundle-dir");
351
+ let extra;
352
+ if (!flags["no-gh"] && deps.ghVerifier) extra = deps.ghVerifier;
353
+ if (flags["require-gh"] && !deps.ghVerifier) {
354
+ throw new CliError("--require-gh: the GitHub CLI (gh) is not installed.");
355
+ }
356
+ return {
357
+ product,
358
+ github,
359
+ repository,
360
+ extra,
361
+ ...bundleDir ? { bundleDir } : {},
362
+ unverified: Boolean(flags.unverified)
363
+ };
364
+ }
365
+ async function verified(s, version, deps) {
366
+ const local = s.bundleDir ? join(s.bundleDir, releaseAssetNames(s.product.id, version).bundle) : null;
367
+ if (local && existsSync(local)) {
368
+ deps.io.out(`Verifying the local bundle ${local}\u2026`);
369
+ const bytes = new Uint8Array(readFileSync(local));
370
+ const sums = readFileSync(join(s.bundleDir, "SHA256SUMS"), "utf8");
371
+ if (s.unverified) deps.io.err(" WARNING: --unverified: skipping the build attestation check.");
372
+ const { digest } = await verifyBundleBytes({
373
+ bytes,
374
+ product: s.product.id,
375
+ version,
376
+ sums,
377
+ repository: s.repository,
378
+ github: s.github,
379
+ skipProvenance: s.unverified,
380
+ ...s.extra && !s.unverified ? { extra: s.extra } : {}
381
+ });
382
+ const bundle = await openBundle(bytes);
383
+ if (bundle.manifest.version !== version) {
384
+ throw new CliError(`${local} holds ${bundle.manifest.version}, not ${version}`);
385
+ }
386
+ if (bundle.manifest.product !== s.product.id) {
387
+ throw new CliError(
388
+ `${local} is a release of ${bundle.manifest.product}, not ${s.product.id}`
389
+ );
390
+ }
391
+ return { bundle, digest };
392
+ }
393
+ deps.io.out(`Downloading ${s.product.label} ${version} and verifying it\u2026`);
394
+ const release = await fetchVerifiedRelease(version, {
395
+ ...s.github,
396
+ ...s.extra ? { extra: s.extra } : {}
397
+ });
398
+ deps.io.out(
399
+ ` sha256 ${release.digest} matches SHA256SUMS and its build attestation (${s.repository}, release workflow, v${version})${s.extra ? "; gh attestation verify passed" : ""}`
400
+ );
401
+ return release;
402
+ }
403
+ function parseSecrets(flags, redactor, appWorker) {
404
+ const out = {};
405
+ for (const entry of flags.secret ?? []) {
406
+ const match = /^(?:([\w-]+):)?([A-Z][A-Z0-9_]*)=(.*)$/s.exec(entry);
407
+ if (!match) throw new CliError(`--secret expects NAME=VALUE or WORKER:NAME=VALUE`);
408
+ const worker = match[1] ?? appWorker;
409
+ out[worker] ??= {};
410
+ out[worker][match[2]] = match[3];
411
+ redactor.add(match[3]);
412
+ }
413
+ return out;
414
+ }
415
+ function parseProviderKeys(flags, redactor) {
416
+ const out = [];
417
+ for (const entry of flags["provider-key"] ?? []) {
418
+ const match = /^([a-z0-9][a-z0-9-]*)=(.+)$/is.exec(entry);
419
+ if (match?.[2]) redactor.add(match[2]);
420
+ if (!match) throw new CliError("--provider-key expects PROVIDER=KEY, e.g. deepseek=\u2026");
421
+ out.push({ provider: match[1].toLowerCase(), key: match[2] });
422
+ }
423
+ return out;
424
+ }
425
+ function modelRolesChoice(flags) {
426
+ const raw = str(flags, "model-roles")?.trim();
427
+ if (raw === void 0) return void 0;
428
+ const isFile = raw !== "default" && !ROLE_PRESETS[raw] && !/^[[{]/.test(raw);
429
+ if (isFile && !existsSync(raw)) {
430
+ throw new CliError(
431
+ `--model-roles: no preset or file "${raw}" (presets: ${Object.keys(ROLE_PRESETS).join(", ")}, or default)`
432
+ );
433
+ }
434
+ try {
435
+ return modelRolesVar(isFile ? readFileSync(raw, "utf8") : raw);
436
+ } catch (error) {
437
+ if (error instanceof RoleLayerError) throw new CliError(`--model-roles: ${error.message}`);
438
+ throw error;
439
+ }
440
+ }
441
+ function registryProvider(slug) {
442
+ return Object.values(PROVIDER_INFO).find((p) => p.gatewaySlug === slug && p.needsKey)?.id;
443
+ }
444
+ function aiChoice(flags, env) {
445
+ const value = (str(flags, "ai") ?? env.COS_AI)?.trim().toLowerCase();
446
+ if (value === void 0 || value === "") return void 0;
447
+ if (value === "on" || value === "true") return true;
448
+ if (value === "off" || value === "false") return false;
449
+ throw new CliError("--ai is on or off");
450
+ }
451
+ function randomSecret() {
452
+ return toHex(crypto.getRandomValues(new Uint8Array(32)));
453
+ }
454
+ var FAKE_PROVIDER_VAR = "PAYMENTS_FAKE_PROVIDER";
455
+ var FAKE_SECRET = "FAKE_WEBHOOK_SECRET";
456
+ function generateFakePaymentsSecrets(manifest, gatekeepers, vars, secrets, stored, redactor) {
457
+ for (const name of gatekeepers) {
458
+ const worker = manifest.workers.find((w) => w.name === name);
459
+ if (!worker?.secrets?.some((s) => s.name === FAKE_SECRET)) continue;
460
+ if (vars[name] && FAKE_SECRET in vars[name]) {
461
+ const { [FAKE_SECRET]: _plain, ...rest } = vars[name];
462
+ vars[name] = rest;
463
+ }
464
+ if (vars[name]?.[FAKE_PROVIDER_VAR] !== "true") continue;
465
+ if (stored.get(name)?.includes(FAKE_SECRET) || secrets[name]?.[FAKE_SECRET]) continue;
466
+ const secret = randomSecret();
467
+ redactor.add(secret);
468
+ secrets[name] = { ...secrets[name], [FAKE_SECRET]: secret };
469
+ }
470
+ }
471
+ async function latestVersion(s, channel) {
472
+ const releases = await listReleases(channel, s.github);
473
+ const latest = releases[0];
474
+ if (!latest) throw new CliError(`No ${channel} release is published in ${s.repository} yet.`);
475
+ return latest.version;
476
+ }
477
+ function deploymentDatabase(flags, s) {
478
+ return str(flags, "database") ?? s.product.names.database;
479
+ }
480
+ function firstInstallNames(flags) {
481
+ const text = str(flags, "names");
482
+ if (!text) return { workers: {}, resources: {} };
483
+ const parsed = JSON.parse(text);
484
+ const ok = (map) => map === void 0 || typeof map === "object" && map !== null && Object.values(map).every((v) => typeof v === "string" && /^[a-z0-9-]+$/.test(v));
485
+ if (!ok(parsed.workers) || !ok(parsed.resources))
486
+ throw new CliError("--names is { workers, resources } of names");
487
+ return { workers: parsed.workers ?? {}, resources: parsed.resources ?? {} };
488
+ }
489
+ async function install(flags, deps) {
490
+ const { io } = deps;
491
+ const s = await session(flags, deps);
492
+ const existing = await locateDeployment(s.api, s.accountId, deploymentDatabase(flags, s));
493
+ const found = existing?.state ?? null;
494
+ const names = found ? null : firstInstallNames(flags);
495
+ const channelFlag = str(flags, "channel");
496
+ if (channelFlag && !CHANNELS.includes(channelFlag))
497
+ throw new CliError("--channel is stable or beta");
498
+ const channel = channelFlag ?? found?.channel ?? "stable";
499
+ const version = str(flags, "version") ?? found?.version ?? await latestVersion(s, channel);
500
+ if (found && compareVersions(version, found.version) > 0) {
501
+ throw new CliError(
502
+ `${s.product.label} ${found.version} is already installed here. Run \`cos upgrade --version ${version}\` to update it.`
503
+ );
504
+ }
505
+ if (found)
506
+ io.out(
507
+ `Found an existing install (${found.version}); re-running it to repair anything missing.`
508
+ );
509
+ const { bundle, digest } = await verified(s, version, deps);
510
+ const manifest = bundle.manifest;
511
+ const previous = found;
512
+ const app = manifest.workers.find((w) => w.role === "app");
513
+ if (!app) throw new CliError("The release has no app Worker.");
514
+ let hostnameMode = previous?.hostnameMode ?? "workers.dev";
515
+ let hostname = previous?.hostname;
516
+ let zoneId = previous?.zoneId;
517
+ if (!previous) {
518
+ let choice = str(flags, "hostname");
519
+ if (!choice && io.interactive && !flags.yes) {
520
+ choice = await io.ask(
521
+ "Hostname (workers.dev, or e.g. crm.example.com on one of your zones)",
522
+ {
523
+ default: "workers.dev"
524
+ }
525
+ );
526
+ }
527
+ if (!choice || choice === "workers.dev") {
528
+ hostname = await workersDevHostname(
529
+ s.api,
530
+ s.accountId,
531
+ names?.workers[app.name] ?? app.name,
532
+ deploymentDatabase(flags, s)
533
+ );
534
+ } else {
535
+ hostnameMode = "custom";
536
+ hostname = choice.toLowerCase();
537
+ const zones = await s.api.listZones(s.accountId);
538
+ const zoneName = str(flags, "zone");
539
+ const zone = zoneName ? zones.find((z) => z.name === zoneName) : zones.filter((z) => hostname === z.name || hostname?.endsWith(`.${z.name}`)).sort((a, b) => b.name.length - a.name.length)[0];
540
+ if (!zone) throw new CliError(`No active zone in this account covers ${hostname}.`);
541
+ zoneId = zone.id;
542
+ }
543
+ }
544
+ if (!hostname) throw new CliError("No hostname.");
545
+ let identity = previous?.identityProvider ?? str(flags, "identity");
546
+ if (!identity) {
547
+ identity = io.interactive && !flags.yes ? await choose(
548
+ io,
549
+ "Sign-in:",
550
+ ["better-auth", "cloudflare-access"],
551
+ "better-auth"
552
+ ) : "better-auth";
553
+ }
554
+ if (identity !== "better-auth" && identity !== "cloudflare-access") {
555
+ throw new CliError("--identity is better-auth or cloudflare-access");
556
+ }
557
+ const optional = manifest.workers.filter((w) => w.optional);
558
+ const requested = (str(flags, "gatekeepers") ?? "").split(",").map((g) => g.trim()).filter(Boolean).map(
559
+ (g) => g.startsWith(s.product.names.gatekeeperPrefix) ? g : `${s.product.names.gatekeeperPrefix}${g}`
560
+ );
561
+ for (const name of requested) {
562
+ if (!optional.some((w) => w.name === name)) throw new CliError(`Unknown gatekeeper ${name}.`);
563
+ }
564
+ const gatekeepers = [.../* @__PURE__ */ new Set([...previous?.gatekeepers ?? [], ...requested])].sort();
565
+ const ai = aiChoice(flags, deps.env) ?? previous?.ai ?? true;
566
+ const gatewayFlag = str(flags, "ai-gateway")?.trim();
567
+ if (gatewayFlag !== void 0 && gatewayFlag !== "off" && !/^[a-z0-9][a-z0-9-_]{0,63}$/i.test(gatewayFlag)) {
568
+ throw new CliError("--ai-gateway is a gateway id (letters, digits, - and _) or off");
569
+ }
570
+ const aiGateway = gatewayFlag === "off" ? false : gatewayFlag ?? previous?.aiGateway;
571
+ const providerKeys = parseProviderKeys(flags, deps.redactor);
572
+ if (providerKeys.length && (!ai || aiGateway === false)) {
573
+ throw new CliError("--provider-key stores keys in AI Gateway: it needs AI and a gateway on");
574
+ }
575
+ const modelRoles = modelRolesChoice(flags);
576
+ if (modelRoles && !ai) throw new CliError("--model-roles needs in-app AI on (--ai on)");
577
+ const secrets = parseSecrets(flags, deps.redactor, app.name);
578
+ secrets[app.name] ??= {};
579
+ const appSecrets = secrets[app.name];
580
+ const scripts = new Set((await s.api.listScripts(s.accountId)).map((sc) => sc.id));
581
+ const deployedAs = (name) => (previous?.workerNames ?? names?.workers)?.[name] ?? name;
582
+ const appSet = scripts.has(deployedAs(app.name)) ? await s.api.listSecrets(s.accountId, deployedAs(app.name)) : [];
583
+ if (!appSet.includes("BETTER_AUTH_SECRET") && !appSecrets.BETTER_AUTH_SECRET) {
584
+ appSecrets.BETTER_AUTH_SECRET = randomSecret();
585
+ deps.redactor.add(appSecrets.BETTER_AUTH_SECRET);
586
+ }
587
+ appSecrets.BETTER_AUTH_URL ??= `https://${hostname}`;
588
+ const customerAuthUrl = str(flags, "customer-auth-url");
589
+ if (customerAuthUrl !== void 0) {
590
+ if (!/^https?:\/\/[^/]+$/.test(customerAuthUrl)) {
591
+ throw new CliError("--customer-auth-url is the web app's origin, https://host");
592
+ }
593
+ if (flags["rotate-customer-auth-secret"] || !appSet.includes(CUSTOMER_SECRET) && !appSecrets[CUSTOMER_SECRET]) {
594
+ let secret = randomSecret();
595
+ while (secret === appSecrets.BETTER_AUTH_SECRET) secret = randomSecret();
596
+ appSecrets[CUSTOMER_SECRET] = secret;
597
+ deps.redactor.add(secret);
598
+ }
599
+ }
600
+ const updateToken = str(flags, "update-token") ?? (flags["store-update-token"] ? str(flags, "token") ?? deps.env.CLOUDFLARE_API_TOKEN : void 0);
601
+ if (updateToken) {
602
+ deps.redactor.add(updateToken);
603
+ appSecrets.COS_UPDATE_TOKEN = updateToken;
604
+ }
605
+ const aiAdminToken = str(flags, "ai-admin-token") ?? deps.env.COS_AI_ADMIN_TOKEN;
606
+ if (aiAdminToken) {
607
+ deps.redactor.add(aiAdminToken);
608
+ appSecrets.CLOUDFLARE_API_TOKEN = aiAdminToken;
609
+ }
610
+ if (identity === "cloudflare-access") {
611
+ for (const name of ["CF_ACCESS_TEAM_DOMAIN", "CF_ACCESS_AUD"]) {
612
+ if (appSecrets[name] || appSet.includes(name)) continue;
613
+ if (flags.yes || !io.interactive)
614
+ throw new CliError(`Cloudflare Access needs --secret ${name}=\u2026`);
615
+ appSecrets[name] = await io.ask(
616
+ name === "CF_ACCESS_AUD" ? "Access application AUD tag" : "Access team domain"
617
+ );
618
+ }
619
+ }
620
+ const gatekeeperSet = /* @__PURE__ */ new Map();
621
+ for (const name of gatekeepers) {
622
+ const worker = manifest.workers.find((w) => w.name === name);
623
+ const set = scripts.has(deployedAs(name)) ? await s.api.listSecrets(s.accountId, deployedAs(name)) : [];
624
+ gatekeeperSet.set(name, set);
625
+ for (const secret of worker?.secrets ?? []) {
626
+ if (!secret.required || set.includes(secret.name) || secrets[name]?.[secret.name]) continue;
627
+ if (flags.yes || !io.interactive) {
628
+ throw new CliError(`${name} needs --secret ${name}:${secret.name}=\u2026`);
629
+ }
630
+ const value = await io.ask(
631
+ `${name} ${secret.name}${secret.description ? ` (${secret.description})` : ""}`,
632
+ {
633
+ secret: true
634
+ }
635
+ );
636
+ deps.redactor.add(value);
637
+ secrets[name] = { ...secrets[name], [secret.name]: value };
638
+ }
639
+ }
640
+ let vars = { ...previous?.vars ?? {} };
641
+ if (identity !== "better-auth")
642
+ vars[app.name] = { ...vars[app.name], IDENTITY_PROVIDER: identity };
643
+ if (modelRoles !== void 0) {
644
+ vars = withDeploymentVar(vars, manifest, MODEL_ROLES_VAR, modelRoles);
645
+ }
646
+ for (const [flag, name] of [
647
+ ["packs", PACKS_VAR],
648
+ ["org-extensions", ORG_EXTENSIONS_VAR]
649
+ ]) {
650
+ const value = str(flags, flag);
651
+ if (value === void 0) continue;
652
+ for (const worker of varWorkers(manifest, name))
653
+ vars[worker] = { ...vars[worker], [name]: value };
654
+ }
655
+ if (customerAuthUrl !== void 0) {
656
+ vars[app.name] = { ...vars[app.name], CUSTOMER_AUTH_URL: customerAuthUrl };
657
+ }
658
+ const nativeRedirects = str(flags, "native-redirect-uris");
659
+ if (nativeRedirects !== void 0) {
660
+ vars[app.name] = { ...vars[app.name], NATIVE_REDIRECT_URIS: nativeRedirects };
661
+ } else if (vars[app.name]?.NATIVE_REDIRECT_URIS === void 0) {
662
+ vars[app.name] = { ...vars[app.name], NATIVE_REDIRECT_URIS: "http://127.0.0.1/cos-sign-in" };
663
+ }
664
+ const gatekeeperVars = str(flags, "gatekeeper-vars");
665
+ if (gatekeeperVars !== void 0) {
666
+ const parsed = JSON.parse(gatekeeperVars);
667
+ for (const [worker, values] of Object.entries(parsed)) {
668
+ if (!manifest.workers.some((w) => w.name === worker && w.role === "gatekeeper")) {
669
+ throw new CliError(`--gatekeeper-vars names ${worker}, not a gatekeeper of this release`);
670
+ }
671
+ vars[worker] = { ...vars[worker], ...values };
672
+ }
673
+ }
674
+ generateFakePaymentsSecrets(manifest, gatekeepers, vars, secrets, gatekeeperSet, deps.redactor);
675
+ const sendEmailFlag = str(flags, "send-email");
676
+ const sendEmail = {
677
+ ...previous?.sendEmail ?? {},
678
+ ...sendEmailFlag ? JSON.parse(sendEmailFlag) : {}
679
+ };
680
+ const label = str(flags, "label");
681
+ if (label !== void 0) {
682
+ for (const worker of varWorkers(manifest, PRODUCT_LABEL_VAR)) {
683
+ vars[worker] = { ...vars[worker], [PRODUCT_LABEL_VAR]: label };
684
+ }
685
+ }
686
+ if (aiGateway === false) {
687
+ for (const [worker, values] of Object.entries(vars)) {
688
+ if (values.AI_GATEWAY_ID === void 0 && values.AI_GATEWAY_REST === void 0) continue;
689
+ const { AI_GATEWAY_ID: _gone, AI_GATEWAY_REST: _rest, ...rest } = values;
690
+ vars[worker] = rest;
691
+ }
692
+ }
693
+ io.out(
694
+ `
695
+ Installing ${s.product.label} ${version} into account ${s.accountId} at https://${hostname}`
696
+ );
697
+ if (!ai) io.out("In-app AI is off (--ai off): no Workers AI or Vectorize bindings.");
698
+ io.out("Resources:");
699
+ const resources = {
700
+ ...previous?.resources ?? {},
701
+ ...await provisionResources(
702
+ s.api,
703
+ s.accountId,
704
+ neededResources(manifest, gatekeepers, { ai }),
705
+ (l) => io.out(l),
706
+ previous?.resourceNames ?? names?.resources
707
+ )
708
+ };
709
+ const base = {
710
+ version,
711
+ accountId: s.accountId,
712
+ hostname,
713
+ hostnameMode,
714
+ ...zoneId ? { zoneId } : {},
715
+ identityProvider: identity,
716
+ channel,
717
+ gatekeepers,
718
+ ai,
719
+ ...aiGateway !== void 0 ? { aiGateway } : {},
720
+ ...previous?.aiGatewayCreated ? { aiGatewayCreated: true } : {},
721
+ ...previous?.aiGatewayTokenId ? { aiGatewayTokenId: previous.aiGatewayTokenId } : {},
722
+ ...previous?.aiGatewayTokenWorkersAi ? { aiGatewayTokenWorkersAi: true } : {},
723
+ workerNames: previous?.workerNames ?? names?.workers ?? {},
724
+ ...previous?.resourceNames ? { resourceNames: previous.resourceNames } : names && Object.keys(names.resources).length ? { resourceNames: names.resources } : {},
725
+ vars,
726
+ ...sendEmail && Object.keys(sendEmail).length ? { sendEmail } : {},
727
+ resources,
728
+ bundleDigest: digest,
729
+ installedAt: previous?.installedAt ?? (/* @__PURE__ */ new Date()).toISOString(),
730
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
731
+ };
732
+ if (ai && aiGateway !== false) io.out("AI Gateway:");
733
+ const suppliedToken = Object.values(secrets).find((v) => v[GATEWAY_TOKEN_SECRET])?.[GATEWAY_TOKEN_SECRET];
734
+ const gateway = await provisionAiGateway({
735
+ api: s.api,
736
+ manifest,
737
+ state: base,
738
+ ...suppliedToken ? { token: suppliedToken } : {},
739
+ log: (l) => io.out(l)
740
+ });
741
+ for (const values of Object.values(gateway.secrets)) {
742
+ for (const value of Object.values(values)) deps.redactor.add(value);
743
+ }
744
+ Object.assign(secrets, mergeSecrets(secrets, gateway.secrets));
745
+ const state = { ...base, vars: gateway.vars, ...gateway.state };
746
+ if (providerKeys.length) {
747
+ if (!gateway.gatewayId) {
748
+ throw new CliError("--provider-key: no AI Gateway could be set up (see the warning above).");
749
+ }
750
+ for (const { provider, key } of providerKeys) {
751
+ const slug = gatewayProviderSlug(manifest, provider);
752
+ await s.api.setGatewayProviderKey(s.accountId, gateway.gatewayId, slug, key);
753
+ io.out(` provider key ${slug}: stored in AI Gateway ${gateway.gatewayId} (BYOK)`);
754
+ const registry = registryProvider(slug);
755
+ if (registry) state.vars = withByokProvider(state.vars, manifest, registry);
756
+ if (slug === JUDGE_GATEWAY_PROVIDER) {
757
+ state.vars = withDeploymentVar(state.vars, manifest, JUDGE_BYOK_VAR, "true");
758
+ }
759
+ }
760
+ }
761
+ if (modelRoles !== void 0) {
762
+ const name = str(flags, "model-roles")?.trim() ?? "";
763
+ const what = !modelRoles ? "the shipped defaults" : ROLE_PRESETS[name] ? name : "custom JSON";
764
+ const on = varWorkers(manifest, MODEL_ROLES_VAR).join(" and ");
765
+ io.out(`Model roles (${MODEL_ROLES_VAR} on ${on}): ${what}`);
766
+ }
767
+ const databaseId = databaseIdOf(manifest, resources);
768
+ io.out("Core migrations:");
769
+ const applied = await applyBundleMigrations(
770
+ bundle,
771
+ d1ApiMigrations(s.api, s.accountId, databaseId),
772
+ (l) => io.out(l)
773
+ );
774
+ if (!applied.length) io.out(" up to date");
775
+ await writeDeploymentState(s.api, databaseId, state);
776
+ io.out("Workers:");
777
+ for (const [worker, values] of Object.entries(secrets)) {
778
+ if (Object.keys(values).length)
779
+ io.out(` setting secrets on ${worker}: ${Object.keys(values).sort().join(", ")}`);
780
+ }
781
+ const result = await deployWorkers({ api: s.api, bundle, state, secrets, log: (l) => io.out(l) });
782
+ await retireGatewayToken(s.api, s.accountId, gateway.retiredTokenId, (l) => io.out(l));
783
+ if (flags.wait) {
784
+ io.out("Waiting for /api/health\u2026");
785
+ await healthSmoke(hostname, version, {
786
+ ...deps.fetch ? { fetch: deps.fetch } : {},
787
+ ...deps.env.COS_HEALTH_ORIGIN ? { origin: deps.env.COS_HEALTH_ORIGIN } : {},
788
+ ...deps.smokeDelayMs !== void 0 ? { delayMs: deps.smokeDelayMs } : {}
789
+ });
790
+ }
791
+ io.out(`
792
+ Done. ${s.product.label} ${version} is at ${result.url}`);
793
+ io.out(`Open ${result.url}/setup to create the first admin and finish setting up.`);
794
+ if (!updateToken) {
795
+ io.out(
796
+ "Updates: run `npx @composable-os/cli upgrade` (or store a token with --update-token for Settings \u2192 Updates)."
797
+ );
798
+ }
799
+ return 0;
800
+ }
801
+ async function locate(s, flags = {}) {
802
+ const located = await locateDeployment(s.api, s.accountId, deploymentDatabase(flags, s));
803
+ if (!located?.state) {
804
+ throw new CliError(
805
+ `No ${s.product.label} installed from a release was found in this account. Run \`npx @composable-os/cli install\` first.`
806
+ );
807
+ }
808
+ return { databaseId: located.databaseId, state: located.state };
809
+ }
810
+ function printPreflight(io, result) {
811
+ io.out(`Preflight ${result.from ?? "?"} \u2192 ${result.to}: ${result.ok ? "OK" : "BLOCKED"}`);
812
+ io.out(` migrations: ${result.migrations.length ? result.migrations.join(", ") : "none"}`);
813
+ const gk = result.gatekeepers;
814
+ if (gk.added.length || gk.changed.length || gk.removed.length) {
815
+ io.out(
816
+ ` gatekeepers: +${gk.added.join(",") || "-"} ~${gk.changed.join(",") || "-"} -${gk.removed.join(",") || "-"}`
817
+ );
818
+ }
819
+ for (const secret of result.secrets) {
820
+ io.out(
821
+ ` secret ${secret.worker} ${secret.name}${secret.required ? " (required)" : ""}: ${secret.set === null ? "?" : secret.set ? "set" : "not set"}`
822
+ );
823
+ }
824
+ for (const extension of result.extensions) {
825
+ io.out(
826
+ ` extension ${extension.id}: contract ${extension.contractVersion} ${extension.compatible ? "ok" : "INCOMPATIBLE"}`
827
+ );
828
+ }
829
+ for (const w of result.warnings) io.out(` note: ${w.message}`);
830
+ for (const b of result.blockers) io.err(` blocked: ${b.message}`);
831
+ }
832
+ async function currentManifest(s, version) {
833
+ try {
834
+ return await fetchReleaseManifest(await getRelease(version, s.github), s.github);
835
+ } catch {
836
+ return null;
837
+ }
838
+ }
839
+ async function upgrade(flags, deps) {
840
+ const { io } = deps;
841
+ const s = await session(flags, deps);
842
+ const { databaseId, state: found } = await locate(s, flags);
843
+ const channel = found.channel;
844
+ const target = str(flags, "version") ?? await latestVersion(s, channel);
845
+ if (compareVersions(target, found.version) <= 0) {
846
+ io.out(
847
+ `${s.product.label} ${found.version} is installed; nothing newer on the ${channel} channel.`
848
+ );
849
+ return 0;
850
+ }
851
+ const release = await verified(s, target, deps);
852
+ const state = found;
853
+ const secretsSet = {};
854
+ const scripts = new Set((await s.api.listScripts(s.accountId)).map((x) => x.id));
855
+ for (const worker of release.bundle.manifest.workers) {
856
+ const deployed = state.workerNames[worker.name] ?? worker.name;
857
+ if (scripts.has(deployed))
858
+ secretsSet[worker.name] = await s.api.listSecrets(s.accountId, deployed);
859
+ }
860
+ const result = preflight({
861
+ currentVersion: state.version,
862
+ current: await currentManifest(s, state.version),
863
+ target: release.bundle.manifest,
864
+ appliedMigrations: await appliedMigrationsViaApi(s.api, s.accountId, databaseId),
865
+ extensions: await installedExtensionsViaApi(s.api, s.accountId, databaseId),
866
+ installedGatekeepers: state.gatekeepers,
867
+ secretsSet
868
+ });
869
+ printPreflight(io, result);
870
+ if (!result.ok) return 1;
871
+ if (!flags.yes && io.interactive) {
872
+ const answer = await io.ask(`Update ${state.version} \u2192 ${target}? (yes/no)`, { default: "no" });
873
+ if (answer.toLowerCase() !== "yes") return 1;
874
+ }
875
+ const run = {
876
+ id: newRunId(),
877
+ kind: "update",
878
+ from_version: state.version,
879
+ to_version: target,
880
+ status: "running",
881
+ step: null,
882
+ bookmark: null,
883
+ bundle_digest: release.digest,
884
+ preflight: JSON.stringify(result),
885
+ error: null,
886
+ started_by: null,
887
+ surface: "cli",
888
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
889
+ finished_at: null
890
+ };
891
+ await saveRunViaApi(s.api, s.accountId, databaseId, run);
892
+ let previousBundle = null;
893
+ const outcome = await runUpdate({
894
+ api: s.api,
895
+ state,
896
+ databaseId,
897
+ target: release.bundle,
898
+ targetDigest: release.digest,
899
+ previous: async () => {
900
+ previousBundle ??= (await verified(s, state.version, deps)).bundle;
901
+ return previousBundle;
902
+ },
903
+ migrations: d1ApiMigrations(s.api, s.accountId, databaseId),
904
+ // Stage 5's kill switch, reversibly: on before migrating, off after the smoke check or rollback.
905
+ automations: killSwitchControl(apiKillSwitchStore(s.api, s.accountId, databaseId)),
906
+ smoke: (hostname, version) => healthSmoke(hostname, version, {
907
+ ...deps.fetch ? { fetch: deps.fetch } : {},
908
+ ...deps.env.COS_HEALTH_ORIGIN ? { origin: deps.env.COS_HEALTH_ORIGIN } : {},
909
+ ...deps.smokeDelayMs !== void 0 ? { delayMs: deps.smokeDelayMs } : {}
910
+ }),
911
+ onStep: async (step, o) => {
912
+ run.step = step;
913
+ run.bookmark = o?.bookmark ?? run.bookmark;
914
+ if (step === "done") {
915
+ run.status = o?.status ?? "failed";
916
+ run.error = o?.rollbackError ? `${o.error}; rollback failed: ${o.rollbackError}` : o?.error ?? null;
917
+ run.finished_at = (/* @__PURE__ */ new Date()).toISOString();
918
+ }
919
+ if (step === "pause" || step === "bookmark" || step === "restored" || step === "done") {
920
+ await saveRunViaApi(s.api, s.accountId, databaseId, run);
921
+ }
922
+ },
923
+ log: (l) => io.out(l)
924
+ });
925
+ if (outcome.status === "succeeded") {
926
+ io.out(
927
+ `
928
+ Updated to ${s.product.label} ${target}. Migrations applied: ${outcome.migrations.join(", ") || "none"}.`
929
+ );
930
+ return 0;
931
+ }
932
+ io.err(`
933
+ Update failed: ${outcome.error}`);
934
+ io.err(
935
+ outcome.status === "rolled_back" ? `Rolled back to ${state.version} and restored the database to bookmark ${outcome.bookmark}.` : `Rollback did not complete (${outcome.rollbackError ?? "no bookmark"}). Run \`cos rollback\`, or see docs/deploying.md.`
936
+ );
937
+ return 1;
938
+ }
939
+ async function rollback(flags, deps) {
940
+ const { io } = deps;
941
+ const s = await session(flags, deps);
942
+ const { databaseId, state } = await locate(s, flags);
943
+ const runs = await runsViaApi(s.api, s.accountId, databaseId, 20);
944
+ const last = rollbackTarget(runs);
945
+ if (!last?.from_version) {
946
+ io.err("There is no completed update to roll back.");
947
+ return 1;
948
+ }
949
+ if (!flags.yes && io.interactive) {
950
+ const answer = await io.ask(
951
+ `Roll back ${state.version} \u2192 ${last.from_version} and restore the database to before the update (changes since then are lost)? (yes/no)`,
952
+ { default: "no" }
953
+ );
954
+ if (answer.toLowerCase() !== "yes") return 1;
955
+ }
956
+ const previous = await verified(s, last.from_version, deps);
957
+ const record = {
958
+ id: newRunId(),
959
+ kind: "rollback",
960
+ from_version: state.version,
961
+ to_version: last.from_version,
962
+ status: "running",
963
+ step: null,
964
+ bookmark: last.bookmark,
965
+ bundle_digest: previous.digest,
966
+ preflight: null,
967
+ error: null,
968
+ started_by: null,
969
+ surface: "cli",
970
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
971
+ finished_at: null
972
+ };
973
+ await runRollback({
974
+ api: s.api,
975
+ state,
976
+ databaseId,
977
+ previous: previous.bundle,
978
+ previousDigest: previous.digest,
979
+ bookmark: last.bookmark,
980
+ automations: killSwitchControl(apiKillSwitchStore(s.api, s.accountId, databaseId)),
981
+ log: (l) => io.out(l)
982
+ });
983
+ await saveRunViaApi(s.api, s.accountId, databaseId, { ...last, status: "rolled_back" });
984
+ await saveRunViaApi(s.api, s.accountId, databaseId, {
985
+ ...record,
986
+ status: "succeeded",
987
+ finished_at: (/* @__PURE__ */ new Date()).toISOString()
988
+ });
989
+ io.out(`Rolled back to ${s.product.label} ${last.from_version}.`);
990
+ return 0;
991
+ }
992
+ async function status(flags, deps) {
993
+ const { io } = deps;
994
+ const s = await session(flags, deps);
995
+ const { state, databaseId } = await locate(s, flags);
996
+ const releases = await listReleases(state.channel, s.github).catch(() => []);
997
+ const newer = releases.filter((r) => compareVersions(r.version, state.version) > 0);
998
+ const runs = await runsViaApi(s.api, s.accountId, databaseId, 5);
999
+ if (flags.json) {
1000
+ io.out(
1001
+ JSON.stringify(
1002
+ { state: { ...state, resources: void 0 }, available: newer.map((r) => r.version), runs },
1003
+ null,
1004
+ 2
1005
+ )
1006
+ );
1007
+ return 0;
1008
+ }
1009
+ io.out(
1010
+ `${s.product.label} ${state.version} (${state.channel} channel) at https://${state.hostname}`
1011
+ );
1012
+ io.out(
1013
+ ` sign-in: ${state.identityProvider}; gatekeepers: ${state.gatekeepers.join(", ") || "none"}; AI: ${state.ai === false ? "off" : "on"}`
1014
+ );
1015
+ io.out(
1016
+ newer.length ? ` available: ${newer.map((r) => r.version).join(", ")} (run \`cos upgrade\`)` : " up to date"
1017
+ );
1018
+ for (const run of runs) {
1019
+ io.out(
1020
+ ` ${run.started_at} ${run.kind} ${run.from_version ?? "?"} \u2192 ${run.to_version}: ${run.status} (${run.surface})`
1021
+ );
1022
+ }
1023
+ return 0;
1024
+ }
1025
+ async function uninstall(flags, deps) {
1026
+ const { io } = deps;
1027
+ const s = await session(flags, deps);
1028
+ const { state } = await locate(s, flags);
1029
+ if (!flags.yes) {
1030
+ if (!io.interactive) throw new CliError("uninstall deletes everything; pass --yes");
1031
+ const answer = await io.ask(
1032
+ `This deletes the Workers, the database and every record of https://${state.hostname}. Type the hostname to confirm`
1033
+ );
1034
+ if (answer !== state.hostname) return 1;
1035
+ }
1036
+ const names = [
1037
+ ...new Set(
1038
+ [s.product.names.app, ...state.gatekeepers, s.product.names.runner].map(
1039
+ (n) => state.workerNames[n] ?? n
1040
+ )
1041
+ )
1042
+ ];
1043
+ const failures = [];
1044
+ const attempt = async (label, action) => {
1045
+ try {
1046
+ await action();
1047
+ io.out(` deleted ${label}`);
1048
+ } catch (error) {
1049
+ failures.push(`${label}: ${error.message}`);
1050
+ }
1051
+ };
1052
+ for (const name of names)
1053
+ await attempt(`Worker ${name}`, () => s.api.deleteScript(s.accountId, name));
1054
+ const seen = /* @__PURE__ */ new Set();
1055
+ for (const [key, value] of Object.entries(state.resources)) {
1056
+ const kind = key.slice(0, key.indexOf("("));
1057
+ if (seen.has(`${kind}:${value}`)) continue;
1058
+ seen.add(`${kind}:${value}`);
1059
+ if (kind === "D1_ID") await attempt(`D1 ${key}`, () => s.api.deleteD1(s.accountId, value));
1060
+ if (kind === "KV_ID") await attempt(`KV ${key}`, () => s.api.deleteKv(s.accountId, value));
1061
+ if (kind === "R2_NAME") await attempt(`R2 ${value}`, () => s.api.deleteR2(s.accountId, value));
1062
+ if (kind === "VECTORIZE_NAME") {
1063
+ await attempt(`Vectorize ${value}`, () => s.api.deleteVectorize(s.accountId, value));
1064
+ }
1065
+ if (kind === "QUEUE_NAME") {
1066
+ const queue = (await s.api.listQueues(s.accountId)).find((q) => q.queue_name === value);
1067
+ if (queue)
1068
+ await attempt(`Queue ${value}`, () => s.api.deleteQueue(s.accountId, queue.queue_id));
1069
+ }
1070
+ }
1071
+ if (typeof state.aiGateway === "string" && state.aiGatewayCreated) {
1072
+ const gatewayId = state.aiGateway;
1073
+ await attempt(`AI Gateway ${gatewayId}`, () => s.api.deleteAiGateway(s.accountId, gatewayId));
1074
+ }
1075
+ if (state.aiGatewayTokenId) {
1076
+ const tokenId = state.aiGatewayTokenId;
1077
+ await attempt("the AI Gateway token", () => s.api.deleteAccountToken(s.accountId, tokenId));
1078
+ }
1079
+ for (const failure of failures) io.err(` could not delete ${failure}`);
1080
+ return failures.length ? 1 : 0;
1081
+ }
1082
+ async function ext(argv, deps) {
1083
+ let runExt;
1084
+ try {
1085
+ ({ runExt } = await import("./cli-YIOVSKOD.js"));
1086
+ return await runExt(argv, deps.io);
1087
+ } catch (error) {
1088
+ if (error.code === "ERR_MODULE_NOT_FOUND") {
1089
+ deps.io.err(
1090
+ "cos ext runs in a checkout of the Composable OS repository, after pnpm install: pnpm cos ext check <dir>"
1091
+ );
1092
+ return 2;
1093
+ }
1094
+ throw error;
1095
+ }
1096
+ }
1097
+ async function client(argv, deps) {
1098
+ if (argv[0] === "generate" && !argv.includes("--out")) {
1099
+ const repo = await import("./client-repo-PRU3VCQQ.js");
1100
+ const parsed = parseArgs(["client", ...argv.slice(1)]);
1101
+ const dir = str(parsed.flags, "dir") ?? process.cwd();
1102
+ if (repo.isClientRepo(dir)) {
1103
+ try {
1104
+ return await repo.regenerate(parsed.flags, deps);
1105
+ } catch (error) {
1106
+ if (!(error instanceof CliError)) throw error;
1107
+ deps.io.err(error.message);
1108
+ return 1;
1109
+ }
1110
+ }
1111
+ }
1112
+ try {
1113
+ const { runClient } = await import("./cli-2DFENR62.js");
1114
+ return await runClient(argv, deps.io);
1115
+ } catch (error) {
1116
+ if (error.code === "ERR_MODULE_NOT_FOUND") {
1117
+ deps.io.err(
1118
+ "cos client runs in a checkout of the Composable OS repository, after pnpm install: pnpm cos client generate --out <dir>"
1119
+ );
1120
+ return 2;
1121
+ }
1122
+ throw error;
1123
+ }
1124
+ }
1125
+ async function content(argv, deps) {
1126
+ if (argv[0] !== "import") {
1127
+ deps.io.err(
1128
+ "Usage: cos content import <folder> --host <url> [--email <you>] [--dry-run] [--publish] [--yes]"
1129
+ );
1130
+ return 2;
1131
+ }
1132
+ const rest = argv.slice(1);
1133
+ const positional = rest[0] && !rest[0].startsWith("-") ? [rest[0]] : [];
1134
+ let parsed;
1135
+ try {
1136
+ parsed = parseArgs(["import", ...rest.slice(positional.length)]);
1137
+ } catch (error) {
1138
+ deps.io.err(error.message);
1139
+ return 2;
1140
+ }
1141
+ const { contentImport } = await import("./run-PZUCSDDL.js");
1142
+ try {
1143
+ return await contentImport(
1144
+ positional,
1145
+ {
1146
+ ...str(parsed.flags, "host") ? { host: str(parsed.flags, "host") } : {},
1147
+ ...str(parsed.flags, "email") ? { email: str(parsed.flags, "email") } : {},
1148
+ dryRun: Boolean(parsed.flags["dry-run"]),
1149
+ publish: Boolean(parsed.flags.publish),
1150
+ yes: Boolean(parsed.flags.yes)
1151
+ },
1152
+ deps.io
1153
+ );
1154
+ } catch (error) {
1155
+ deps.io.err(`Error: ${error.message}`);
1156
+ return 1;
1157
+ }
1158
+ }
1159
+ async function courses(argv, deps) {
1160
+ const usage = "Usage: cos courses import <folder> --host <url> [--email <you>] [--dry-run] [--publish] [--yes] [--wait <minutes>]";
1161
+ if (argv[0] !== "import") {
1162
+ deps.io.err(usage);
1163
+ return 2;
1164
+ }
1165
+ const rest = argv.slice(1);
1166
+ const positional = rest[0] && !rest[0].startsWith("-") ? [rest[0]] : [];
1167
+ let parsed;
1168
+ try {
1169
+ parsed = parseArgs(["import", ...rest.slice(positional.length)]);
1170
+ } catch (error) {
1171
+ deps.io.err(error.message);
1172
+ return 2;
1173
+ }
1174
+ const wait = str(parsed.flags, "wait");
1175
+ if (wait !== void 0 && !/^\d{1,4}$/.test(wait)) {
1176
+ deps.io.err("--wait is minutes, a whole number");
1177
+ return 2;
1178
+ }
1179
+ const { coursesImport } = await import("./run-RT2HVWMK.js");
1180
+ try {
1181
+ return await coursesImport(
1182
+ positional,
1183
+ {
1184
+ ...str(parsed.flags, "host") ? { host: str(parsed.flags, "host") } : {},
1185
+ ...str(parsed.flags, "email") ? { email: str(parsed.flags, "email") } : {},
1186
+ dryRun: Boolean(parsed.flags["dry-run"]),
1187
+ publish: Boolean(parsed.flags.publish),
1188
+ yes: Boolean(parsed.flags.yes),
1189
+ ...wait !== void 0 ? { wait: Number(wait) } : {}
1190
+ },
1191
+ deps.io
1192
+ );
1193
+ } catch (error) {
1194
+ deps.io.err(`Error: ${error.message}`);
1195
+ return 1;
1196
+ }
1197
+ }
1198
+ async function subscriptions(argv, deps) {
1199
+ const { OFFERS_USAGE, offersImport, offersReport } = await import("./run-Y7T4TVOL.js");
1200
+ if (argv[0] !== "offers" || argv[1] !== "import" && argv[1] !== "report") {
1201
+ deps.io.err(OFFERS_USAGE);
1202
+ return 2;
1203
+ }
1204
+ const rest = argv.slice(2);
1205
+ const positional = argv[1] === "import" && rest[0] && !rest[0].startsWith("-") ? [rest[0]] : [];
1206
+ let parsed;
1207
+ try {
1208
+ parsed = parseArgs([argv[1], ...rest.slice(positional.length)]);
1209
+ } catch (error) {
1210
+ deps.io.err(error.message);
1211
+ return 2;
1212
+ }
1213
+ const flag = (name) => {
1214
+ const value = str(parsed.flags, name);
1215
+ return value !== void 0 ? { [name]: value } : {};
1216
+ };
1217
+ try {
1218
+ if (argv[1] === "report") {
1219
+ return await offersReport(
1220
+ { ...flag("host"), ...flag("email"), ...flag("status"), ...flag("out") },
1221
+ deps.io
1222
+ );
1223
+ }
1224
+ return await offersImport(
1225
+ positional,
1226
+ {
1227
+ ...flag("host"),
1228
+ ...flag("email"),
1229
+ ...flag("plan"),
1230
+ dryRun: Boolean(parsed.flags["dry-run"]),
1231
+ invite: Boolean(parsed.flags.invite),
1232
+ reissue: Boolean(parsed.flags.reissue)
1233
+ },
1234
+ deps.io
1235
+ );
1236
+ } catch (error) {
1237
+ deps.io.err(`Error: ${error.message}`);
1238
+ return 1;
1239
+ }
1240
+ }
1241
+ async function runCli(argv, input) {
1242
+ const deps = input;
1243
+ if (argv[0] === "content") return content(argv.slice(1), deps);
1244
+ if (argv[0] === "courses") return courses(argv.slice(1), deps);
1245
+ if (argv[0] === "subscriptions") return subscriptions(argv.slice(1), deps);
1246
+ if (argv[0] === "ext") return ext(argv.slice(1), deps);
1247
+ if (argv[0] === "client") return client(argv.slice(1), deps);
1248
+ const positional = ["create", "add", "diff"].includes(argv[0] ?? "") && argv[1] && !argv[1].startsWith("-") ? [argv[1]] : [];
1249
+ let parsed;
1250
+ try {
1251
+ parsed = parseArgs(positional.length ? [argv[0], ...argv.slice(2)] : argv);
1252
+ } catch (error) {
1253
+ deps.io.err(error.message);
1254
+ return 2;
1255
+ }
1256
+ if (parsed.flags.help || !argv.length) {
1257
+ deps.io.out(HELP);
1258
+ return argv.length ? 0 : 2;
1259
+ }
1260
+ const repo = await import("./client-repo-PRU3VCQQ.js");
1261
+ const blocks = await import("./blocks-YWDHEBOK.js");
1262
+ const commands = {
1263
+ install,
1264
+ // In a client repo (its product.ts is a client product), `cos upgrade` moves the repo to a
1265
+ // newer platform version; anywhere else it updates an installed deployment, as before.
1266
+ upgrade: (flags, d) => repo.isClientRepo(str(flags, "dir") ?? process.cwd()) ? repo.upgradeRepo(flags, d) : upgrade(flags, d),
1267
+ rollback,
1268
+ status,
1269
+ uninstall,
1270
+ create: (flags, d) => repo.create(positional, flags, d),
1271
+ init: repo.init,
1272
+ deploy: repo.deploy,
1273
+ add: (flags, d) => blocks.add(positional, flags, d),
1274
+ diff: (flags, d) => blocks.diff(positional, flags, d)
1275
+ };
1276
+ const command = commands[parsed.command];
1277
+ if (!command) {
1278
+ deps.io.err(`Unknown command ${parsed.command}.
1279
+
1280
+ ${HELP}`);
1281
+ return 2;
1282
+ }
1283
+ try {
1284
+ return await command(parsed.flags, deps);
1285
+ } catch (error) {
1286
+ deps.io.err(`Error: ${error.message}`);
1287
+ return 1;
1288
+ }
1289
+ }
1290
+
1291
+ export {
1292
+ Redactor,
1293
+ terminalIo,
1294
+ CliError,
1295
+ str,
1296
+ releaseSource,
1297
+ verified,
1298
+ latestVersion,
1299
+ install,
1300
+ upgrade,
1301
+ runCli
1302
+ };