primitive-admin 1.0.61 → 1.0.62

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 (300) hide show
  1. package/README.md +125 -69
  2. package/assets/skill/skills/primitive-platform/SKILL.md +336 -37
  3. package/dist/bin/primitive.js +25 -14
  4. package/dist/bin/primitive.js.map +1 -1
  5. package/dist/src/commands/analytics.js +36 -16
  6. package/dist/src/commands/analytics.js.map +1 -1
  7. package/dist/src/commands/apps.js +49 -188
  8. package/dist/src/commands/apps.js.map +1 -1
  9. package/dist/src/commands/blob-buckets.js +13 -153
  10. package/dist/src/commands/blob-buckets.js.map +1 -1
  11. package/dist/src/commands/collection-type-configs.js +14 -100
  12. package/dist/src/commands/collection-type-configs.js.map +1 -1
  13. package/dist/src/commands/collections.js +47 -8
  14. package/dist/src/commands/collections.js.map +1 -1
  15. package/dist/src/commands/config.d.ts +46 -0
  16. package/dist/src/commands/config.js +479 -0
  17. package/dist/src/commands/config.js.map +1 -0
  18. package/dist/src/commands/connections.js +12 -7
  19. package/dist/src/commands/connections.js.map +1 -1
  20. package/dist/src/commands/cron-triggers.js +84 -176
  21. package/dist/src/commands/cron-triggers.js.map +1 -1
  22. package/dist/src/commands/database-type-configs.d.ts +2 -0
  23. package/dist/src/commands/database-type-configs.js +171 -0
  24. package/dist/src/commands/database-type-configs.js.map +1 -0
  25. package/dist/src/commands/database-types.js +4 -4
  26. package/dist/src/commands/database-types.js.map +1 -1
  27. package/dist/src/commands/databases.d.ts +63 -0
  28. package/dist/src/commands/databases.js +649 -87
  29. package/dist/src/commands/databases.js.map +1 -1
  30. package/dist/src/commands/documents.js +869 -12
  31. package/dist/src/commands/documents.js.map +1 -1
  32. package/dist/src/commands/email-templates.js +18 -125
  33. package/dist/src/commands/email-templates.js.map +1 -1
  34. package/dist/src/commands/env.d.ts +12 -1
  35. package/dist/src/commands/env.js +98 -25
  36. package/dist/src/commands/env.js.map +1 -1
  37. package/dist/src/commands/feature-flags.d.ts +14 -0
  38. package/dist/src/commands/feature-flags.js +116 -0
  39. package/dist/src/commands/feature-flags.js.map +1 -0
  40. package/dist/src/commands/group-type-configs.js +14 -109
  41. package/dist/src/commands/group-type-configs.js.map +1 -1
  42. package/dist/src/commands/init.d.ts +9 -1
  43. package/dist/src/commands/init.js +1056 -277
  44. package/dist/src/commands/init.js.map +1 -1
  45. package/dist/src/commands/integrations.js +136 -421
  46. package/dist/src/commands/integrations.js.map +1 -1
  47. package/dist/src/commands/metadata-category-configs.d.ts +12 -0
  48. package/dist/src/commands/metadata-category-configs.js +112 -0
  49. package/dist/src/commands/metadata-category-configs.js.map +1 -0
  50. package/dist/src/commands/metadata.js +33 -141
  51. package/dist/src/commands/metadata.js.map +1 -1
  52. package/dist/src/commands/prompts.js +206 -563
  53. package/dist/src/commands/prompts.js.map +1 -1
  54. package/dist/src/commands/rule-sets.d.ts +1 -1
  55. package/dist/src/commands/rule-sets.js +16 -132
  56. package/dist/src/commands/rule-sets.js.map +1 -1
  57. package/dist/src/commands/scripts.js +67 -234
  58. package/dist/src/commands/scripts.js.map +1 -1
  59. package/dist/src/commands/sessions.js +17 -5
  60. package/dist/src/commands/sessions.js.map +1 -1
  61. package/dist/src/commands/sync-app-settings.d.ts +113 -70
  62. package/dist/src/commands/sync-app-settings.js +193 -242
  63. package/dist/src/commands/sync-app-settings.js.map +1 -1
  64. package/dist/src/commands/sync.d.ts +1932 -49
  65. package/dist/src/commands/sync.js +9521 -1769
  66. package/dist/src/commands/sync.js.map +1 -1
  67. package/dist/src/commands/tokens.js +8 -2
  68. package/dist/src/commands/tokens.js.map +1 -1
  69. package/dist/src/commands/users.js +92 -1
  70. package/dist/src/commands/users.js.map +1 -1
  71. package/dist/src/commands/vars.js +44 -58
  72. package/dist/src/commands/vars.js.map +1 -1
  73. package/dist/src/commands/webhooks.js +318 -156
  74. package/dist/src/commands/webhooks.js.map +1 -1
  75. package/dist/src/commands/workflows.d.ts +49 -12
  76. package/dist/src/commands/workflows.js +652 -1086
  77. package/dist/src/commands/workflows.js.map +1 -1
  78. package/dist/src/lib/access-rule-display.d.ts +21 -0
  79. package/dist/src/lib/access-rule-display.js +34 -0
  80. package/dist/src/lib/access-rule-display.js.map +1 -0
  81. package/dist/src/lib/api-client.d.ts +541 -61
  82. package/dist/src/lib/api-client.js +559 -102
  83. package/dist/src/lib/api-client.js.map +1 -1
  84. package/dist/src/lib/app-settings-descriptor.d.ts +180 -25
  85. package/dist/src/lib/app-settings-descriptor.js +403 -82
  86. package/dist/src/lib/app-settings-descriptor.js.map +1 -1
  87. package/dist/src/lib/canonical-json.d.ts +12 -0
  88. package/dist/src/lib/canonical-json.js +35 -0
  89. package/dist/src/lib/canonical-json.js.map +1 -0
  90. package/dist/src/lib/cli-manifest.d.ts +8 -0
  91. package/dist/src/lib/cli-manifest.js +1 -0
  92. package/dist/src/lib/cli-manifest.js.map +1 -1
  93. package/dist/src/lib/codegen-shared/generatedFiles.d.ts +6 -2
  94. package/dist/src/lib/codegen-shared/generatedFiles.js +9 -2
  95. package/dist/src/lib/codegen-shared/generatedFiles.js.map +1 -1
  96. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.d.ts +6 -6
  97. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js +8 -8
  98. package/dist/src/lib/codegen-shared/resolveCodegenSourceDir.js.map +1 -1
  99. package/dist/src/lib/config-object-descriptor.d.ts +127 -0
  100. package/dist/src/lib/config-object-descriptor.js +658 -0
  101. package/dist/src/lib/config-object-descriptor.js.map +1 -0
  102. package/dist/src/lib/config-payload.d.ts +85 -0
  103. package/dist/src/lib/config-payload.js +116 -0
  104. package/dist/src/lib/config-payload.js.map +1 -0
  105. package/dist/src/lib/config-surface.d.ts +130 -0
  106. package/dist/src/lib/config-surface.js +300 -0
  107. package/dist/src/lib/config-surface.js.map +1 -0
  108. package/dist/src/lib/credentials-store.d.ts +10 -0
  109. package/dist/src/lib/credentials-store.js +23 -0
  110. package/dist/src/lib/credentials-store.js.map +1 -1
  111. package/dist/src/lib/data-input.d.ts +23 -0
  112. package/dist/src/lib/data-input.js +50 -0
  113. package/dist/src/lib/data-input.js.map +1 -0
  114. package/dist/src/lib/db-codegen/dbTemplates.js +1 -1
  115. package/dist/src/lib/db-codegen/dbTemplates.js.map +1 -1
  116. package/dist/src/lib/db-codegen/dbTypeIR.d.ts +1 -1
  117. package/dist/src/lib/env-resolver-core.d.ts +147 -0
  118. package/dist/src/lib/env-resolver-core.js +265 -0
  119. package/dist/src/lib/env-resolver-core.js.map +1 -0
  120. package/dist/src/lib/env-resolver.d.ts +28 -6
  121. package/dist/src/lib/env-resolver.js +44 -32
  122. package/dist/src/lib/env-resolver.js.map +1 -1
  123. package/dist/src/lib/generated-allowlist.js +12 -0
  124. package/dist/src/lib/generated-allowlist.js.map +1 -1
  125. package/dist/src/lib/generated-config-surfaces.d.ts +682 -0
  126. package/dist/src/lib/generated-config-surfaces.js +4058 -0
  127. package/dist/src/lib/generated-config-surfaces.js.map +1 -0
  128. package/dist/src/lib/generated-template-lint.d.ts +212 -0
  129. package/dist/src/lib/generated-template-lint.js +624 -0
  130. package/dist/src/lib/generated-template-lint.js.map +1 -0
  131. package/dist/src/lib/init-adopt.d.ts +16 -0
  132. package/dist/src/lib/init-adopt.js +34 -0
  133. package/dist/src/lib/init-adopt.js.map +1 -0
  134. package/dist/src/lib/init-assets.d.ts +39 -0
  135. package/dist/src/lib/init-assets.js +97 -0
  136. package/dist/src/lib/init-assets.js.map +1 -0
  137. package/dist/src/lib/init-config.d.ts +44 -5
  138. package/dist/src/lib/init-config.js +80 -7
  139. package/dist/src/lib/init-config.js.map +1 -1
  140. package/dist/src/lib/init-ios-links.d.ts +50 -0
  141. package/dist/src/lib/init-ios-links.js +153 -0
  142. package/dist/src/lib/init-ios-links.js.map +1 -0
  143. package/dist/src/lib/init-plan.d.ts +80 -0
  144. package/dist/src/lib/init-plan.js +95 -0
  145. package/dist/src/lib/init-plan.js.map +1 -0
  146. package/dist/src/lib/init-production-env.d.ts +48 -0
  147. package/dist/src/lib/init-production-env.js +59 -0
  148. package/dist/src/lib/init-production-env.js.map +1 -0
  149. package/dist/src/lib/init-schema.d.ts +74 -0
  150. package/dist/src/lib/init-schema.js +358 -0
  151. package/dist/src/lib/init-schema.js.map +1 -0
  152. package/dist/src/lib/init-xcode.d.ts +33 -0
  153. package/dist/src/lib/init-xcode.js +114 -0
  154. package/dist/src/lib/init-xcode.js.map +1 -0
  155. package/dist/src/lib/integration-request-config.d.ts +30 -0
  156. package/dist/src/lib/integration-request-config.js +145 -0
  157. package/dist/src/lib/integration-request-config.js.map +1 -0
  158. package/dist/src/lib/local-state.d.ts +55 -0
  159. package/dist/src/lib/local-state.js +167 -0
  160. package/dist/src/lib/local-state.js.map +1 -0
  161. package/dist/src/lib/log-inspection.d.ts +568 -0
  162. package/dist/src/lib/log-inspection.js +639 -0
  163. package/dist/src/lib/log-inspection.js.map +1 -0
  164. package/dist/src/lib/migration-nag.d.ts +2 -2
  165. package/dist/src/lib/migration-nag.js +3 -3
  166. package/dist/src/lib/object-status-filter.d.ts +22 -0
  167. package/dist/src/lib/object-status-filter.js +45 -0
  168. package/dist/src/lib/object-status-filter.js.map +1 -0
  169. package/dist/src/lib/output.d.ts +24 -1
  170. package/dist/src/lib/output.js +42 -1
  171. package/dist/src/lib/output.js.map +1 -1
  172. package/dist/src/lib/package-manager.d.ts +140 -0
  173. package/dist/src/lib/package-manager.js +305 -0
  174. package/dist/src/lib/package-manager.js.map +1 -0
  175. package/dist/src/lib/paginate.d.ts +50 -0
  176. package/dist/src/lib/paginate.js +53 -0
  177. package/dist/src/lib/paginate.js.map +1 -1
  178. package/dist/src/lib/platform-owned.d.ts +29 -3
  179. package/dist/src/lib/platform-owned.js +42 -3
  180. package/dist/src/lib/platform-owned.js.map +1 -1
  181. package/dist/src/lib/project-config.js +13 -5
  182. package/dist/src/lib/project-config.js.map +1 -1
  183. package/dist/src/lib/query-operators.d.ts +1 -1
  184. package/dist/src/lib/query-operators.js +1 -1
  185. package/dist/src/lib/record-filter.d.ts +18 -0
  186. package/dist/src/lib/record-filter.js +55 -0
  187. package/dist/src/lib/record-filter.js.map +1 -0
  188. package/dist/src/lib/resolve-init-dev-port.d.ts +56 -0
  189. package/dist/src/lib/resolve-init-dev-port.js +55 -0
  190. package/dist/src/lib/resolve-init-dev-port.js.map +1 -0
  191. package/dist/src/lib/resolve-init-server.d.ts +64 -0
  192. package/dist/src/lib/resolve-init-server.js +77 -0
  193. package/dist/src/lib/resolve-init-server.js.map +1 -0
  194. package/dist/src/lib/resolve-platform.d.ts +43 -14
  195. package/dist/src/lib/resolve-platform.js +74 -12
  196. package/dist/src/lib/resolve-platform.js.map +1 -1
  197. package/dist/src/lib/run-status.d.ts +19 -0
  198. package/dist/src/lib/run-status.generated.d.ts +39 -0
  199. package/dist/src/lib/run-status.generated.js +66 -0
  200. package/dist/src/lib/run-status.generated.js.map +1 -0
  201. package/dist/src/lib/run-status.js +19 -0
  202. package/dist/src/lib/run-status.js.map +1 -0
  203. package/dist/src/lib/server-text-normalization.d.ts +51 -0
  204. package/dist/src/lib/server-text-normalization.js +90 -0
  205. package/dist/src/lib/server-text-normalization.js.map +1 -0
  206. package/dist/src/lib/server-url.d.ts +22 -0
  207. package/dist/src/lib/server-url.js +33 -0
  208. package/dist/src/lib/server-url.js.map +1 -0
  209. package/dist/src/lib/signing-secret-status.d.ts +81 -0
  210. package/dist/src/lib/signing-secret-status.js +116 -0
  211. package/dist/src/lib/signing-secret-status.js.map +1 -0
  212. package/dist/src/lib/skill-installer.js +6 -3
  213. package/dist/src/lib/skill-installer.js.map +1 -1
  214. package/dist/src/lib/snapshots.d.ts +2 -2
  215. package/dist/src/lib/snapshots.js +2 -2
  216. package/dist/src/lib/swift-codegen/dbGenerator.d.ts +15 -2
  217. package/dist/src/lib/swift-codegen/dbGenerator.js +250 -18
  218. package/dist/src/lib/swift-codegen/dbGenerator.js.map +1 -1
  219. package/dist/src/lib/swift-codegen/generator.d.ts +11 -2
  220. package/dist/src/lib/swift-codegen/generator.js +181 -7
  221. package/dist/src/lib/swift-codegen/generator.js.map +1 -1
  222. package/dist/src/lib/swift-codegen/siblingSymbols.d.ts +7 -3
  223. package/dist/src/lib/swift-codegen/siblingSymbols.js +4 -1
  224. package/dist/src/lib/swift-codegen/siblingSymbols.js.map +1 -1
  225. package/dist/src/lib/sync-dir-selector.d.ts +21 -0
  226. package/dist/src/lib/sync-dir-selector.js +30 -0
  227. package/dist/src/lib/sync-dir-selector.js.map +1 -0
  228. package/dist/src/lib/sync-paths.d.ts +39 -0
  229. package/dist/src/lib/sync-paths.js +70 -2
  230. package/dist/src/lib/sync-paths.js.map +1 -1
  231. package/dist/src/lib/sync-resource-types.d.ts +138 -31
  232. package/dist/src/lib/sync-resource-types.js +241 -47
  233. package/dist/src/lib/sync-resource-types.js.map +1 -1
  234. package/dist/src/lib/sync-selectors.d.ts +95 -0
  235. package/dist/src/lib/sync-selectors.js +228 -0
  236. package/dist/src/lib/sync-selectors.js.map +1 -0
  237. package/dist/src/lib/template.d.ts +62 -4
  238. package/dist/src/lib/template.js +147 -39
  239. package/dist/src/lib/template.js.map +1 -1
  240. package/dist/src/lib/test-case-keys.d.ts +29 -0
  241. package/dist/src/lib/test-case-keys.js +55 -0
  242. package/dist/src/lib/test-case-keys.js.map +1 -0
  243. package/dist/src/lib/test-case-variables.d.ts +15 -0
  244. package/dist/src/lib/test-case-variables.js +29 -0
  245. package/dist/src/lib/test-case-variables.js.map +1 -0
  246. package/dist/src/lib/toml-database-config.d.ts +4 -4
  247. package/dist/src/lib/toml-database-config.js +27 -34
  248. package/dist/src/lib/toml-database-config.js.map +1 -1
  249. package/dist/src/lib/toml-metadata-config.d.ts +9 -5
  250. package/dist/src/lib/toml-metadata-config.js +40 -45
  251. package/dist/src/lib/toml-metadata-config.js.map +1 -1
  252. package/dist/src/lib/toml-native-form.d.ts +1 -1
  253. package/dist/src/lib/toml-native-form.js +1 -1
  254. package/dist/src/lib/toml-params-validator.d.ts +1 -1
  255. package/dist/src/lib/toml-params-validator.js +1 -1
  256. package/dist/src/lib/toml-scalar-edit.d.ts +43 -0
  257. package/dist/src/lib/toml-scalar-edit.js +283 -0
  258. package/dist/src/lib/toml-scalar-edit.js.map +1 -0
  259. package/dist/src/lib/user-selector.d.ts +24 -0
  260. package/dist/src/lib/user-selector.js +33 -0
  261. package/dist/src/lib/user-selector.js.map +1 -0
  262. package/dist/src/lib/version-check.d.ts +25 -0
  263. package/dist/src/lib/version-check.js +77 -8
  264. package/dist/src/lib/version-check.js.map +1 -1
  265. package/dist/src/lib/watch.d.ts +121 -0
  266. package/dist/src/lib/watch.js +169 -0
  267. package/dist/src/lib/watch.js.map +1 -0
  268. package/dist/src/lib/workflow-apply.d.ts +69 -45
  269. package/dist/src/lib/workflow-apply.js +99 -72
  270. package/dist/src/lib/workflow-apply.js.map +1 -1
  271. package/dist/src/lib/workflow-codegen/generator.js +4 -4
  272. package/dist/src/lib/workflow-codegen/generator.js.map +1 -1
  273. package/dist/src/lib/workflow-codegen/invokerIR.d.ts +11 -0
  274. package/dist/src/lib/workflow-codegen/invokerIR.js +5 -0
  275. package/dist/src/lib/workflow-codegen/invokerIR.js.map +1 -1
  276. package/dist/src/lib/workflow-config-apply.d.ts +70 -0
  277. package/dist/src/lib/workflow-config-apply.js +137 -0
  278. package/dist/src/lib/workflow-config-apply.js.map +1 -0
  279. package/dist/src/lib/workflow-config-sidecar.d.ts +63 -0
  280. package/dist/src/lib/workflow-config-sidecar.js +96 -0
  281. package/dist/src/lib/workflow-config-sidecar.js.map +1 -0
  282. package/dist/src/lib/workflow-defaults.d.ts +29 -0
  283. package/dist/src/lib/workflow-defaults.js +41 -0
  284. package/dist/src/lib/workflow-defaults.js.map +1 -0
  285. package/dist/src/lib/workflow-include-preserve.d.ts +76 -0
  286. package/dist/src/lib/workflow-include-preserve.js +286 -0
  287. package/dist/src/lib/workflow-include-preserve.js.map +1 -0
  288. package/dist/src/lib/workflow-payload.d.ts +31 -20
  289. package/dist/src/lib/workflow-payload.js +100 -110
  290. package/dist/src/lib/workflow-payload.js.map +1 -1
  291. package/dist/src/lib/workflow-toml-validator.d.ts +37 -16
  292. package/dist/src/lib/workflow-toml-validator.js +141 -16
  293. package/dist/src/lib/workflow-toml-validator.js.map +1 -1
  294. package/dist/src/types/index.d.ts +78 -22
  295. package/dist/src/validators.d.ts +7 -7
  296. package/dist/src/validators.js +6 -6
  297. package/package.json +11 -6
  298. package/dist/src/commands/settings.d.ts +0 -15
  299. package/dist/src/commands/settings.js +0 -102
  300. package/dist/src/commands/settings.js.map +0 -1
@@ -1,15 +1,30 @@
1
- import { confirm, input, select } from "@inquirer/prompts";
2
- import { appendFileSync, existsSync, readFileSync, writeFileSync } from "fs";
3
- import { basename, join, resolve } from "path";
4
- import { CURRENT_CONFIG_VERSION, PROJECT_CONFIG_DIR, PROJECT_CONFIG_FILENAME, PROJECT_CONFIG_DISPLAY_NAME, saveProjectConfig, loadProjectConfigFromPath, } from "../lib/project-config.js";
1
+ import { checkbox, confirm, input, select } from "@inquirer/prompts";
2
+ import { appendFileSync, existsSync, readFileSync, readdirSync, writeFileSync, } from "fs";
3
+ import { basename, join, relative, resolve } from "path";
4
+ import { CURRENT_CONFIG_VERSION, PROJECT_CONFIG_DIR, PROJECT_CONFIG_FILENAME, PROJECT_CONFIG_DISPLAY_NAME, findProjectRoot, saveProjectConfig, loadProjectConfigFromPath, } from "../lib/project-config.js";
5
+ import { resolveAdoptedEnvironment } from "../lib/init-adopt.js";
6
+ import { CANONICAL_SCHEMA_HEADER, FALLBACK_STARTER_SCHEMA, platformLabel, rootAgentsMarkdown, } from "../lib/init-assets.js";
7
+ import { checkInitGuards, planInit } from "../lib/init-plan.js";
8
+ import { resolveProductionRuntime } from "../lib/init-production-env.js";
9
+ import { checkClientWiring, composeSchemaContent, declaredModelNames, findClientSchema, wireClientToSchema, writeCanonicalSchema, } from "../lib/init-schema.js";
10
+ import { declareSharedProjectConfig } from "../lib/init-xcode.js";
11
+ import { deriveCallbackScheme, linkOptInGuidance, missingUrlTypeGuidance, stampCallbackScheme, } from "../lib/init-ios-links.js";
12
+ import { getExplicitEnvName } from "../lib/env-resolver.js";
5
13
  import { ApiClient } from "../lib/api-client.js";
6
14
  import { browserLogin } from "../lib/auth-flow.js";
7
15
  import { loadCredentials, setCurrentApp } from "../lib/config.js";
8
- import { INIT_CONFIG_FILENAME, loadInitConfig, parseInitConfigToml, resolveUseExistingAppId, validateInitConfig, } from "../lib/init-config.js";
9
- import { resolvePlatform, } from "../lib/resolve-platform.js";
16
+ import { isProjectMode, seedCredentialsForEnvInProject, } from "../lib/credentials-store.js";
17
+ import { getCurrentEnvironment, getProjectConfig } from "../lib/env-resolver.js";
18
+ import { normalizeServerUrl } from "../lib/channel.js";
19
+ import { INIT_CONFIG_FILENAME, loadInitConfig, parseInitConfigToml, resolveSkipInstall, resolveUseExistingAppId, validateInitConfig, } from "../lib/init-config.js";
20
+ import { parsePlatformList, resolvePlatforms, } from "../lib/resolve-platform.js";
21
+ import { resolveInitServer } from "../lib/resolve-init-server.js";
22
+ import { validateServerUrl } from "../lib/server-url.js";
23
+ import { DEFAULT_DEV_PORT, resolveDevPort, validateDevPort, } from "../lib/resolve-init-dev-port.js";
24
+ import { DEFAULT_SERVER_URL, PRODUCTION_SERVER_URL } from "../lib/constants.js";
10
25
  import { divider, error, info, keyValue, success, warn, } from "../lib/output.js";
11
- import { gitInitialCommit, gitInitRepo, installPnpmGlobally, installPrimitiveCli, isDirectoryEmpty, isPnpmInstalled, isPortFree, isPrimitiveCliInstalled, isXcodeInstalled, iosTemplateUrl, vueTemplateUrl, resolveTemplateBranch, prepareTemplate, runPnpmInstall, runSwiftPackageResolve, updateEnvFile, updateEnvPort, updatePrimitiveJson, updateViteConfig, } from "../lib/template.js";
12
- const DEFAULT_SERVER_URL = process.env.PRIMITIVE_SERVER_URL || "https://primitiveapi.com";
26
+ import { installCommand, PRIMITIVE_CLI_PACKAGE } from "../lib/package-manager.js";
27
+ import { gitInitialCommit, gitInitRepo, installPnpmGlobally, installPrimitiveCli, isDirectoryEmpty, isPnpmInstalled, isPortFree, isPrimitiveCliInstalled, isXcodeInstalled, iosTemplateUrl, vueTemplateUrl, resolveTemplateBranch, prepareTemplate, runPnpmInstall, runSwiftPackageResolve, updateEnvFile, updateEnvPort, configurePrimitiveJson, updateViteConfig, } from "../lib/template.js";
13
28
  /**
14
29
  * The .gitignore lines `init` writes for Primitive CLI local state.
15
30
  *
@@ -26,54 +41,23 @@ const DEFAULT_SERVER_URL = process.env.PRIMITIVE_SERVER_URL || "https://primitiv
26
41
  */
27
42
  export const GITIGNORE_LOCAL_STATE_ENTRIES = [
28
43
  ".primitive/credentials.json",
44
+ // This machine's Primitive environment selection (`primitive env use`).
45
+ // The committed `defaultEnvironment` is the team default; the selection is
46
+ // per-machine and must never be committable (#2873).
47
+ ".primitive/local.json",
29
48
  ".primitive/sync/**/.primitive-sync.json",
30
49
  ".primitive/sync-backups/",
31
50
  ".snapshots/",
32
51
  "config-snapshots/",
33
52
  ];
34
53
  /**
35
- * Writes .primitive/config.json into the project directory and ensures the
36
- * .gitignore entry for local state exists. Safe to call in a directory that
37
- * already has a config in that case we add/update the "dev" environment
38
- * instead of overwriting the file.
54
+ * Ensures the project root's .gitignore lists the Primitive CLI's local state.
55
+ *
56
+ * Split out of `scaffoldProjectConfig` because a run that ADOPTS an existing
57
+ * project (#2890) must not rewrite its config, but still has to make sure the
58
+ * per-machine state a new client's environment produces cannot be committed.
39
59
  */
40
- async function scaffoldProjectConfig(opts) {
41
- const configPath = join(opts.targetDir, PROJECT_CONFIG_DIR, PROJECT_CONFIG_FILENAME);
42
- let config;
43
- if (existsSync(configPath)) {
44
- // Respect an existing config: merge in the new dev env if missing.
45
- try {
46
- config = loadProjectConfigFromPath(configPath);
47
- }
48
- catch {
49
- // Existing file is broken — don't clobber it; just warn and skip.
50
- warn(`${PROJECT_CONFIG_DISPLAY_NAME} exists but is invalid. Skipping project config scaffold.`);
51
- return;
52
- }
53
- if (!config.environments.dev) {
54
- config.environments.dev = {
55
- apiUrl: opts.serverUrl,
56
- appId: opts.appId,
57
- appName: opts.appName,
58
- };
59
- if (!config.defaultEnvironment)
60
- config.defaultEnvironment = "dev";
61
- }
62
- }
63
- else {
64
- config = {
65
- version: CURRENT_CONFIG_VERSION,
66
- defaultEnvironment: "dev",
67
- environments: {
68
- dev: {
69
- apiUrl: opts.serverUrl,
70
- appId: opts.appId,
71
- appName: opts.appName,
72
- },
73
- },
74
- };
75
- }
76
- saveProjectConfig(configPath, config);
60
+ export function ensureGitignoreLocalState(targetDir) {
77
61
  // Ensure .primitive/ local state (credentials, per-machine sync state) is
78
62
  // gitignored. The config.json itself lives in .primitive/ too, but we
79
63
  // gitignore only the sensitive / per-machine artifacts — config.json and
@@ -86,7 +70,7 @@ async function scaffoldProjectConfig(opts) {
86
70
  // which incorrectly hid the TOML export tree from `git status`. If we see
87
71
  // that legacy entry, replace it with the targeted pattern in-place so
88
72
  // users who re-run init pick up the fix.
89
- const gitignorePath = join(opts.targetDir, ".gitignore");
73
+ const gitignorePath = join(targetDir, ".gitignore");
90
74
  const LEGACY_SYNC_IGNORE = ".primitive/sync/";
91
75
  const gitignoreEntries = [...GITIGNORE_LOCAL_STATE_ENTRIES];
92
76
  let linesToAdd = [];
@@ -131,18 +115,52 @@ async function scaffoldProjectConfig(opts) {
131
115
  // Non-fatal
132
116
  }
133
117
  }
134
- success(`Wrote ${PROJECT_CONFIG_DISPLAY_NAME} with dev environment`);
135
118
  }
136
- function validateServerUrl(url) {
137
- if (!url.trim())
138
- return "Server URL cannot be empty";
139
- try {
140
- new URL(url);
141
- return true;
119
+ /**
120
+ * Writes .primitive/config.json into the project directory and ensures the
121
+ * .gitignore entry for local state exists. Safe to call in a directory that
122
+ * already has a config — in that case we add/update the "dev" environment
123
+ * instead of overwriting the file.
124
+ */
125
+ async function scaffoldProjectConfig(opts) {
126
+ const configPath = join(opts.targetDir, PROJECT_CONFIG_DIR, PROJECT_CONFIG_FILENAME);
127
+ let config;
128
+ if (existsSync(configPath)) {
129
+ // Respect an existing config: merge in the new dev env if missing.
130
+ try {
131
+ config = loadProjectConfigFromPath(configPath);
132
+ }
133
+ catch {
134
+ // Existing file is broken — don't clobber it; just warn and skip.
135
+ warn(`${PROJECT_CONFIG_DISPLAY_NAME} exists but is invalid. Skipping project config scaffold.`);
136
+ return;
137
+ }
138
+ if (!config.environments.dev) {
139
+ config.environments.dev = {
140
+ apiUrl: opts.serverUrl,
141
+ appId: opts.appId,
142
+ appName: opts.appName,
143
+ };
144
+ if (!config.defaultEnvironment)
145
+ config.defaultEnvironment = "dev";
146
+ }
142
147
  }
143
- catch {
144
- return "Please enter a valid URL (e.g., https://example.com)";
148
+ else {
149
+ config = {
150
+ version: CURRENT_CONFIG_VERSION,
151
+ defaultEnvironment: "dev",
152
+ environments: {
153
+ dev: {
154
+ apiUrl: opts.serverUrl,
155
+ appId: opts.appId,
156
+ appName: opts.appName,
157
+ },
158
+ },
159
+ };
145
160
  }
161
+ saveProjectConfig(configPath, config);
162
+ ensureGitignoreLocalState(opts.targetDir);
163
+ success(`Wrote ${PROJECT_CONFIG_DISPLAY_NAME} with dev environment`);
146
164
  }
147
165
  /**
148
166
  * Prompts for login when credentials are missing or the server has changed.
@@ -195,6 +213,23 @@ async function ensureAuthenticated(credentials, serverUrl, serverChanged, contex
195
213
  success(`Logged in as ${result.credentials.email}`);
196
214
  return result.credentials;
197
215
  }
216
+ /**
217
+ * Finds the name of the project-config environment (if any) whose `apiUrl`
218
+ * matches `serverUrl`, so the project-mode "not logged in" remedy can name a
219
+ * real, working environment instead of a placeholder. Comparison uses the
220
+ * same canonicalization as `resolveInitServer` (trailing-slash-insensitive)
221
+ * so `https://host/` in `.primitive/config.json` still matches.
222
+ */
223
+ function findEnvironmentForServer(serverUrl) {
224
+ const project = getProjectConfig();
225
+ if (!project)
226
+ return undefined;
227
+ const canonicalTarget = normalizeServerUrl(serverUrl) ?? serverUrl;
228
+ return Object.keys(project.environments).find((name) => {
229
+ const apiUrl = project.environments[name].apiUrl;
230
+ return (normalizeServerUrl(apiUrl) ?? apiUrl) === canonicalTarget;
231
+ });
232
+ }
198
233
  /**
199
234
  * Loads the init config from --config flag or auto-discovers it in CWD.
200
235
  * Returns null if no config file is found/specified.
@@ -245,55 +280,97 @@ export function registerInitCommand(program) {
245
280
  .option("-s, --server <url>", "Server URL (default: current CLI server or https://primitiveapi.com)")
246
281
  .option("--skip-install", "Skip dependency installation")
247
282
  .option("--config <path>", `Path to an init config file for non-interactive setup (default: auto-discover ${INIT_CONFIG_FILENAME} in the current directory)`)
248
- .option("-p, --platform <platform>", "Target platform: web or ios (SwiftUI). Omit to be prompted interactively.")
283
+ .option("-p, --platform <platforms>", "Client platform(s) to scaffold: web, ios (SwiftUI), or both as a comma-separated list (web,ios). Omit to be prompted interactively.")
249
284
  .addHelpText("after", `
250
285
  Examples:
251
286
  $ primitive init my-app # Create web app in ./my-app
252
287
  $ primitive init # Interactive: prompt for directory and app name
253
288
  $ primitive init my-app --platform ios # Create an iOS (SwiftUI) app
289
+ $ primitive init my-app --platform web,ios # One app, a web client and an iOS client
290
+ $ primitive init ios --platform ios # Add an iOS client to the app of the surrounding project
254
291
  $ primitive init . --use-existing-app-id 01HXY... # Use existing app in current dir
255
292
  $ primitive init my-app --skip-install # Skip dependency install
256
293
  $ primitive init --config .primitive-init.toml # Non-interactive from config file
257
294
 
295
+ One app, several clients:
296
+ Selecting more than one platform scaffolds them side by side under one project:
297
+ each client in its own directory (web/, ios/), with .primitive/config.json, the
298
+ git repository and the shared models/models.toml at the root. Run inside a
299
+ directory that already has an ancestor .primitive/config.json and init ADDS the
300
+ client to that app instead: it reuses the selected environment's app, writes no
301
+ nested .primitive/ or .git/, makes no commit, and leaves the files for you to
302
+ review and commit in the outer repository.
303
+
258
304
  Non-interactive mode:
259
305
  Create a ${INIT_CONFIG_FILENAME} file (or pass --config <path>) to skip all prompts.
260
306
  The config file uses TOML format:
261
307
 
262
- action = "create" # "create" or "use-existing"
308
+ action = "create" # "create", "use-existing", or "add-client"
263
309
  app_name = "My App" # Required for action = "create"
264
310
  app_id = "01HXY..." # Required for action = "use-existing"
265
311
  dir = "my-app" # Project directory (optional)
266
- platform = "web" # "web" or "ios" (optional, defaults to web)
312
+ platform = "web" # "web", "ios", "web,ios", or ["web", "ios"]
313
+ # (optional, defaults to web)
314
+ promote_schema = false # Only with action = "add-client". Consent to move
315
+ # an existing single-client repo's models.toml to
316
+ # <project root>/models/models.toml so every client
317
+ # reads one copy.
267
318
  access_mode = "invite-only" # "public", "domain", or "invite-only" (optional)
268
- dev_port = 5173 # Dev server port (optional)
269
- skip_install = false # Skip pnpm install (optional)
270
- server = "https://..." # Custom server URL (optional)
319
+ dev_port = 5173 # Dev server port (optional). Set it to skip the
320
+ # port prompt: init pins the port in
321
+ # vite.config.ts and .env and adds
322
+ # http://localhost:<port> to the app's CORS
323
+ # allowed origins and redirect URIs.
324
+ skip_install = false # Skip pnpm install (optional). Same effect as
325
+ # --skip-install; the flag wins if both are set.
326
+ server = "https://..." # Server to create the app on (optional).
327
+ # Same effect as -s/--server; the flag wins if
328
+ # both are set. If the CLI already points at a
329
+ # different server, init stops and tells you how
330
+ # to point it here first. Outside a Primitive
331
+ # project, if you are not logged in at all, init
332
+ # logs in to this one; inside a project the
333
+ # selected environment's apiUrl is the target
334
+ # even when logged out, so a different value
335
+ # here stops the run.
271
336
  invite_emails = ["a@b.com"] # Emails to invite (optional, for invite-only)
272
337
  allowed_domains = ["b.com"] # Allowed domains (optional, for domain mode)
273
338
  overwrite = false # Overwrite non-empty target directory (optional)
274
339
 
275
340
  This command will:
276
- 1. Download the Primitive app template (web or Apple SwiftUI)
277
- 2. Prompt for an app name and create it on the Primitive server (or use existing)
278
- 3. Configure the project with your app ID
341
+ 1. Download a Primitive app template for each selected platform (web, Apple SwiftUI)
342
+ 2. Prompt for an app name and create it on the Primitive server (or use existing,
343
+ or adopt the app of the project it is run inside)
344
+ 3. Configure the project with your app ID and point every client at one model schema
279
345
  4. Install dependencies (pnpm for web, swift package resolve for Apple)
280
346
  `)
281
347
  .action(handleInit);
282
348
  }
283
349
  async function handleInit(projectDirArg, options) {
284
350
  // Validate an explicitly-passed `--platform` flag up front. Only `web` and
285
- // `ios` are supported (#1009 removed `macos`). An omitted flag is
286
- // `undefined` (the commander default was dropped) and is resolved below.
287
- if (options.platform !== undefined &&
288
- options.platform !== "web" &&
289
- options.platform !== "ios") {
290
- error(`Unknown platform "${options.platform}". Supported platforms: web, ios`);
291
- process.exit(1);
351
+ // `ios` are supported (#1009 removed `macos`), and the flag names a LIST —
352
+ // `--platform web,ios` scaffolds both clients of one app (#2890). An omitted
353
+ // flag is `undefined` (the commander default was dropped) and is resolved
354
+ // below.
355
+ let flagPlatforms;
356
+ if (options.platform !== undefined) {
357
+ const parsed = parsePlatformList(options.platform);
358
+ if (!parsed.ok) {
359
+ error(parsed.error);
360
+ process.exit(1);
361
+ }
362
+ flagPlatforms = parsed.platforms;
292
363
  }
293
364
  // `initConfig` is the parsed-and-validated `primitive-init.toml` for
294
365
  // non-interactive runs (CI, scripted scaffolding). When non-null, the
295
366
  // rest of this function uses it to skip prompts.
296
367
  const initConfig = loadInitConfigFromOptions(options);
368
+ // Whether to skip the dependency install (steps 7-8). Both the
369
+ // `--skip-install` flag and the config's `skip_install` key request it; the
370
+ // flag wins. Reading only the flag is what made the documented config key a
371
+ // no-op (#2720).
372
+ const { skipInstall, source: skipInstallSource } = resolveSkipInstall(options.skipInstall, initConfig);
373
+ const skipInstallReason = skipInstallSource === "config" ? "skip_install = true in config" : "--skip-install";
297
374
  // Resolve the target platform per the 4-case interactivity contract:
298
375
  // (a) explicit --platform flag -> use it (never prompt)
299
376
  // (b) init-config TOML present -> use its platform or fall back to web
@@ -301,23 +378,30 @@ async function handleInit(projectDirArg, options) {
301
378
  // (d) non-TTY, no flag/cfg -> fall back to web (no hang/crash)
302
379
  // The prompt is TTY-guarded inside `resolvePlatform` so a piped/CI stdin
303
380
  // never triggers the `@inquirer/prompts` `ERR_USE_AFTER_CLOSE` crash.
304
- const platform = await resolvePlatform({
305
- flag: options.platform,
306
- configPlatform: initConfig?.platform,
381
+ // The init config's `platform` was validated above, so it parses.
382
+ const configPlatforms = initConfig?.platform !== undefined
383
+ ? parsePlatformList(initConfig.platform).platforms
384
+ : undefined;
385
+ const platforms = await resolvePlatforms({
386
+ flag: flagPlatforms,
387
+ configPlatform: configPlatforms,
307
388
  hasConfig: initConfig != null,
308
389
  isTTY: Boolean(process.stdin.isTTY),
309
- promptFn: () => select({
310
- message: "What platform are you building for?",
390
+ promptFn: () => checkbox({
391
+ message: "Which clients are you building? (space to select)",
311
392
  choices: [
312
- { value: "web", name: "web (Vue 3 + TypeScript + Tailwind)" },
393
+ { value: "web", name: "web (Vue 3 + TypeScript + Tailwind)", checked: true },
313
394
  { value: "ios", name: "ios (Swift + SwiftUI)" },
314
395
  ],
315
- default: "web",
396
+ // A run with nothing selected has nothing to scaffold; re-ask rather
397
+ // than proceeding with an empty list.
398
+ validate: (choices) => choices.length > 0 ? true : "Select at least one client.",
316
399
  }),
317
400
  });
318
- // iOS shares the SwiftUI template, Xcode toolchain, and primitive.json
319
- // config path. (macOS was removed in #1009.)
320
- const isApple = platform === "ios";
401
+ // iOS brings the SwiftUI template, the Xcode toolchain and the
402
+ // primitive.json config path whether it is the only client or one of
403
+ // several. (macOS was removed in #1009.)
404
+ const isApple = platforms.includes("ios");
321
405
  // Apple-family platforms require macOS with Xcode.
322
406
  if (isApple && process.platform !== "darwin") {
323
407
  error("iOS apps require macOS with Xcode installed.");
@@ -331,14 +415,27 @@ async function handleInit(projectDirArg, options) {
331
415
  }
332
416
  }
333
417
  // Step 1: Determine project directory
418
+ //
419
+ // Run from inside an existing Primitive app, one platform goes in a
420
+ // directory named after itself (`ios/`, `web/`) rather than in a new
421
+ // project's. That default is also what makes an `add-client` init config
422
+ // non-interactive without a `dir` key (#2890). A run selecting several
423
+ // platforms names the directory their subdirectories go under, which has no
424
+ // obvious default, so it is asked for as before.
334
425
  let projectDir = projectDirArg;
335
426
  if (!projectDir && initConfig?.dir) {
336
427
  projectDir = initConfig.dir;
337
428
  }
429
+ const clientDirDefault = platforms.length === 1 && findProjectRoot(process.cwd()) ? platforms[0] : null;
430
+ if (!projectDir && clientDirDefault && initConfig) {
431
+ projectDir = clientDirDefault;
432
+ }
338
433
  if (!projectDir) {
339
434
  projectDir = await input({
340
- message: "Project name (a new directory will be created):",
341
- default: "my-primitive-app",
435
+ message: clientDirDefault
436
+ ? "Directory for the new client:"
437
+ : "Project name (a new directory will be created):",
438
+ default: clientDirDefault ?? "my-primitive-app",
342
439
  validate: (value) => {
343
440
  if (!value.trim())
344
441
  return "Project name cannot be empty";
@@ -349,19 +446,53 @@ async function handleInit(projectDirArg, options) {
349
446
  const targetDir = resolve(process.cwd(), projectDir);
350
447
  // Used as the default app name suggestion when prompting
351
448
  const defaultAppName = projectDir === "." ? basename(targetDir) : basename(projectDir);
352
- // Step 2: Check if directory exists and is non-empty
353
- if (existsSync(targetDir) && !isDirectoryEmpty(targetDir)) {
449
+ // ── Which layout is this run producing? (#2890) ────────────────────────
450
+ //
451
+ // A `.primitive/config.json` in an ANCESTOR of the target means this app
452
+ // already exists and this run adds a client to it. Passing the ancestor only
453
+ // when it differs from the target keeps `primitive init .` at a project root
454
+ // on its existing merge behavior.
455
+ const ancestorRoot = findProjectRoot(targetDir);
456
+ const adoptedRoot = ancestorRoot && resolve(ancestorRoot) !== resolve(targetDir) ? ancestorRoot : null;
457
+ const plan = planInit({
458
+ platforms,
459
+ targetDir,
460
+ ancestorProjectRoot: adoptedRoot,
461
+ });
462
+ // The adopted app's identity comes from the project config's selected
463
+ // environment — never from a flag or a prompt.
464
+ let adopted = null;
465
+ if (adoptedRoot) {
466
+ try {
467
+ adopted = resolveAdoptedEnvironment(adoptedRoot, {
468
+ explicitEnvName: getExplicitEnvName(),
469
+ envVarName: process.env.PRIMITIVE_ENV || null,
470
+ });
471
+ }
472
+ catch (err) {
473
+ error(`Could not read the Primitive project at ${adoptedRoot}: ${err.message}`);
474
+ warn("No project files were written.");
475
+ process.exit(1);
476
+ }
477
+ }
478
+ // Step 2: Check if the target — and each client directory under it — exists
479
+ // and is non-empty. Each directory follows the same overwrite contract.
480
+ const directoriesToGuard = [targetDir, ...plan.clients.map((c) => c.dir)].filter((dir, index, all) => all.indexOf(dir) === index);
481
+ for (const dir of directoriesToGuard) {
482
+ if (!existsSync(dir) || isDirectoryEmpty(dir))
483
+ continue;
484
+ const label = dir === targetDir ? projectDir : relative(process.cwd(), dir);
354
485
  if (initConfig) {
355
486
  // Non-interactive: require explicit overwrite opt-in
356
487
  if (!initConfig.overwrite) {
357
- error(`Directory "${projectDir}" already exists and is not empty.`);
488
+ error(`Directory "${label}" already exists and is not empty.`);
358
489
  error('Set overwrite = true in your config file to allow overwriting.');
359
490
  process.exit(1);
360
491
  }
361
- warn(`Directory "${projectDir}" already exists and is not empty. Overwriting (overwrite = true in config).`);
492
+ warn(`Directory "${label}" already exists and is not empty. Overwriting (overwrite = true in config).`);
362
493
  }
363
494
  else {
364
- warn(`Directory "${projectDir}" already exists and is not empty.`);
495
+ warn(`Directory "${label}" already exists and is not empty.`);
365
496
  const overwrite = await confirm({
366
497
  message: "Do you want to overwrite the existing contents?",
367
498
  default: false,
@@ -372,34 +503,53 @@ async function handleInit(projectDirArg, options) {
372
503
  }
373
504
  }
374
505
  }
375
- // Step 2.5: Determine target server
376
- let serverUrl;
377
- let serverChanged = false;
378
- if (options.server) {
506
+ // Step 2.5: Determine target server. Precedence: `--server` flag, then the
507
+ // init-config `server` key, then the current login, then the default. The
508
+ // config key used to be dropped on the floor here (#2376).
509
+ if (options.server !== undefined) {
379
510
  const validation = validateServerUrl(options.server);
380
511
  if (validation !== true) {
381
512
  error(validation);
382
513
  process.exit(1);
383
514
  }
384
- serverUrl = options.server;
385
- // Check if explicit --server differs from current credentials
386
- const existingCredentials = loadCredentials();
387
- if (existingCredentials?.serverUrl &&
388
- existingCredentials.serverUrl !== options.server) {
389
- serverChanged = true;
390
- }
391
515
  }
392
- else {
393
- const existingCredentials = loadCredentials();
394
- const currentServer = existingCredentials?.serverUrl;
395
- if (currentServer && currentServer !== DEFAULT_SERVER_URL && !initConfig) {
516
+ const existingCredentials = loadCredentials();
517
+ // In project mode the CLI is pinned to the selected environment's `apiUrl`
518
+ // even before that environment has any credentials: `saveCredentialsStore()`
519
+ // writes tokens into the environment's slot and discards the server they were
520
+ // minted for, and `loadCredentialsStore()` blends them back with
521
+ // `env.config.apiUrl`. So "logged out" does not mean "no current server"
522
+ // there — the environment still fixes the target, and the mismatch check
523
+ // below has to compare against it. Reading only the credentials' `serverUrl`
524
+ // let a logged-out environment slip past the guard: init would log in to the
525
+ // config's server and then send every later call to the environment's own
526
+ // `apiUrl`.
527
+ const currentEnvironment = getCurrentEnvironment();
528
+ // When adopting, the app already lives somewhere: the environment being
529
+ // adopted fixes the server, and a `--server` that disagrees is a mistake
530
+ // rather than a choice.
531
+ const currentServer = adopted
532
+ ? adopted.config.apiUrl
533
+ : existingCredentials?.serverUrl ?? currentEnvironment?.config.apiUrl;
534
+ const resolvedServer = await resolveInitServer({
535
+ flagServer: options.server,
536
+ configServer: initConfig?.server,
537
+ hasConfig: initConfig != null,
538
+ currentServer,
539
+ defaultServer: DEFAULT_SERVER_URL,
540
+ // An adopt run has nowhere else to put the client: the environment it is
541
+ // adopting names the server, so there is nothing to ask about.
542
+ isTTY: Boolean(process.stdin.isTTY) && plan.mode !== "add-client",
543
+ promptFn: async () => {
544
+ // Only reached when a current server exists (see resolveInitServer).
545
+ const current = currentServer ?? DEFAULT_SERVER_URL;
396
546
  console.log();
397
547
  const serverChoice = await select({
398
- message: `The Primitive CLI is currently using ${currentServer}.\nWhere do you want to create this app?`,
548
+ message: `The Primitive CLI is currently using ${current}.\nWhere do you want to create this app?`,
399
549
  choices: [
400
550
  {
401
- value: currentServer,
402
- name: `Current server (${currentServer})`,
551
+ value: current,
552
+ name: `Current server (${current})`,
403
553
  },
404
554
  {
405
555
  value: DEFAULT_SERVER_URL,
@@ -412,60 +562,187 @@ async function handleInit(projectDirArg, options) {
412
562
  ],
413
563
  default: currentServer,
414
564
  });
415
- if (serverChoice === "__custom__") {
416
- serverUrl = await input({
417
- message: "Enter the server URL:",
418
- validate: validateServerUrl,
419
- });
565
+ if (serverChoice !== "__custom__")
566
+ return serverChoice;
567
+ return input({
568
+ message: "Enter the server URL:",
569
+ validate: validateServerUrl,
570
+ });
571
+ },
572
+ });
573
+ const serverUrl = resolvedServer.serverUrl;
574
+ const serverChanged = resolvedServer.serverChanged;
575
+ if (resolvedServer.source === "config") {
576
+ info(`Server: ${serverUrl} (from config)`);
577
+ }
578
+ // A run that can't get usable credentials for the resolved server must fail
579
+ // loudly here rather than hang on the OAuth callback — or, as in #2376,
580
+ // quietly build the app on the current server. Two cases qualify:
581
+ //
582
+ // * a non-interactive init-config run, which has no way to drive a browser;
583
+ // * any project-mode run, because a login always lands in the selected
584
+ // environment's slot and is read back with that environment's `apiUrl`.
585
+ // Logging in to a different server there would leave the project holding
586
+ // credentials the rest of the CLI sends somewhere else.
587
+ //
588
+ // In legacy mode an interactive run can still log in to the requested server
589
+ // and have it stored correctly, so it goes through the login flow below.
590
+ const inProjectMode = isProjectMode() || plan.mode === "add-client";
591
+ if (serverChanged && (initConfig || inProjectMode)) {
592
+ const requestedBy = resolvedServer.source === "flag"
593
+ ? "--server"
594
+ : resolvedServer.source === "config"
595
+ ? "the init config's `server`"
596
+ : "the server you selected";
597
+ // `currentServer` is the stored login's server when there is one, and
598
+ // otherwise the selected environment's `apiUrl` — say which, so the user
599
+ // isn't told they're "logged in to" a server they never logged in to.
600
+ const currentDescription = existingCredentials
601
+ ? `the CLI is logged in to ${currentServer}`
602
+ : `this project's "${adopted?.name ?? currentEnvironment?.name}" environment targets ${currentServer}`;
603
+ error(`Not logged in to ${serverUrl}.`);
604
+ error(`${requestedBy} requests ${serverUrl}, but ${currentDescription}.`);
605
+ // The remedy differs by mode: `primitive login` resolves its target
606
+ // through `getConfiguredServerUrl()`, which returns the active
607
+ // environment's `apiUrl` whenever a project config is in scope and ignores
608
+ // `PRIMITIVE_SERVER_URL` there. Printing the legacy-mode hint inside a
609
+ // project would send the user in circles.
610
+ if (inProjectMode) {
611
+ error(`Inside a Primitive project, \`primitive login\` targets the selected environment's server, so PRIMITIVE_SERVER_URL has no effect here.`);
612
+ // `primitive -e <env> login` only resolves the mismatch if `<env>` is
613
+ // both logged into AND passed to the init re-run — `currentServer` is
614
+ // always the *selected* environment's apiUrl (that's what made this
615
+ // serverChanged in the first place), so re-running `primitive login`
616
+ // or `primitive init` without `-e` reproduces the identical error.
617
+ // Look up which configured environment (if any) actually targets
618
+ // `serverUrl` so the hint names a real, working command instead of a
619
+ // placeholder.
620
+ const targetEnvName = findEnvironmentForServer(serverUrl);
621
+ // The re-run has to resolve to the same server, and it re-reads every
622
+ // input from scratch. Only a config-selected server survives on its own:
623
+ // when the flag (or the interactive prompt) is what won here, an
624
+ // otherwise-identical re-run would fall back to the config's `server` —
625
+ // or prompt again — and reproduce this exact error. Pin it with
626
+ // `--server`, which outranks both.
627
+ const serverFlag = resolvedServer.source === "config" ? "" : ` --server ${serverUrl}`;
628
+ if (targetEnvName) {
629
+ const configFlag = options.config ? ` --config ${options.config}` : "";
630
+ error(`Log in to the "${targetEnvName}" environment and run init against it: ` +
631
+ `\`primitive -e ${targetEnvName} login\` then ` +
632
+ `\`primitive -e ${targetEnvName} init${configFlag}${serverFlag}\`.`);
420
633
  }
421
634
  else {
422
- serverUrl = serverChoice;
635
+ error(`This project has no environment configured for ${serverUrl}. ` +
636
+ `Add one (\`primitive env add <name> --api-url ${serverUrl}\`) and ` +
637
+ `re-run with \`-e <name>${serverFlag}\`, or re-run init outside the project directory.`);
423
638
  }
424
- serverChanged = currentServer !== serverUrl;
425
639
  }
426
640
  else {
427
- serverUrl = currentServer || DEFAULT_SERVER_URL;
641
+ error(`Log in to the target server first: PRIMITIVE_SERVER_URL=${serverUrl} primitive login`);
428
642
  }
643
+ warn("No project files were written.");
644
+ process.exit(1);
645
+ }
646
+ // Everything this run must be refused for, before a download or a write.
647
+ const guardError = checkInitGuards({
648
+ action: initConfig?.action,
649
+ hasConfig: initConfig != null,
650
+ ancestorProjectRoot: adoptedRoot,
651
+ configAppId: initConfig?.app_id,
652
+ flagAppId: options.useExistingAppId,
653
+ environmentAppId: adopted?.config.appId,
654
+ environmentName: adopted?.name,
655
+ });
656
+ if (guardError) {
657
+ error(guardError);
658
+ warn("No project files were written.");
659
+ process.exit(1);
429
660
  }
430
- // Step 4: Check authentication
431
- let credentials = loadCredentials();
661
+ if (plan.mode === "add-client") {
662
+ info(`Found an existing Primitive project at ${adoptedRoot} (environment "${adopted.name}").`);
663
+ // A run driven by a config already said what it wants; anything else asks,
664
+ // and a piped stdin gets the key that says it non-interactively rather than
665
+ // `confirmPrompt`'s `--yes` remedy, which init has no flag for.
666
+ if (!initConfig) {
667
+ if (!process.stdin.isTTY) {
668
+ error(`Adding a client to the project at ${adoptedRoot} needs a confirmation, and stdin is not interactive.`);
669
+ error(`Re-run with an init config containing \`action = "add-client"\` to confirm non-interactively.`);
670
+ warn("No project files were written.");
671
+ process.exit(1);
672
+ }
673
+ const proceed = await confirm({
674
+ message: `Add this client to app ${adopted.config.appName ?? adopted.config.appId} in ${adoptedRoot}?`,
675
+ default: true,
676
+ });
677
+ if (!proceed) {
678
+ error("Aborted. No project files were written.");
679
+ process.exit(1);
680
+ }
681
+ }
682
+ }
683
+ // ── The one schema (#2890) ─────────────────────────────────────────────
684
+ //
685
+ // Decided here, before anything is downloaded or written, because the answer
686
+ // can be "stop": an adopted repository whose client keeps its schema
687
+ // somewhere this run does not recognize, or one whose owner declines the
688
+ // move, must end with nothing changed.
689
+ const schemaPlan = plan.canonicalSchemaPath
690
+ ? await resolveSchemaComposition({
691
+ plan,
692
+ promoteConsent: initConfig?.promote_schema === true,
693
+ interactive: initConfig == null && Boolean(process.stdin.isTTY),
694
+ nonInteractive: initConfig != null,
695
+ })
696
+ : null;
697
+ // Step 4: Check authentication (credentials were loaded for the server
698
+ // resolution above — reuse them rather than re-reading the file).
699
+ let credentials = existingCredentials;
432
700
  let appId;
433
701
  let appName;
434
- let preparedTemplate = null;
702
+ const preparedTemplates = new Map();
435
703
  const cleanupPreparedTemplate = () => {
436
- try {
437
- preparedTemplate?.cleanup();
438
- }
439
- catch {
440
- // Non-fatal cleanup best effort
704
+ for (const prepared of preparedTemplates.values()) {
705
+ try {
706
+ prepared.cleanup();
707
+ }
708
+ catch {
709
+ // Non-fatal cleanup best effort
710
+ }
441
711
  }
442
- preparedTemplate = null;
712
+ preparedTemplates.clear();
443
713
  };
444
714
  const prepareTemplateOrExit = async () => {
445
- if (preparedTemplate)
446
- return;
447
- // Download and validate the archive before app creation, but keep it staged
448
- // in a temp directory. That avoids both failure modes: app-creation failure
449
- // leaves no scaffold, and template-download failure leaves no orphaned app.
450
- info(`Preparing your ${platform === "ios" ? "iOS" : "web"} project template...`);
451
- // The branch is the channel (issue #1934): scaffolding against the alpha
452
- // server pulls the alpha template branch, whose Primitive deps pin the
453
- // alpha prerelease libraries. Falls back to main (with a warning) if the
454
- // channel branch isn't available.
455
- const templateBranch = resolveTemplateBranch(serverUrl);
456
- const templateUrlFor = isApple ? iosTemplateUrl : vueTemplateUrl;
457
- try {
458
- preparedTemplate = await prepareTemplate({
459
- templateUrl: templateUrlFor(templateBranch),
460
- fallbackTemplateUrl: templateBranch !== "main" ? templateUrlFor("main") : undefined,
461
- onFallback: (reason) => warn(`Template branch "${templateBranch}" unavailable (${reason}) — falling back to main.`),
462
- onProgress: info,
463
- });
464
- }
465
- catch (err) {
466
- error(`Failed to download template: ${err.message}`);
467
- error("Check your internet connection and try again.");
468
- process.exit(1);
715
+ // EVERY selected template downloads and validates before the app is
716
+ // created, and none of them touches the target directory yet. That keeps
717
+ // both failure modes covered with several clients in play: app-creation
718
+ // failure leaves no scaffold, and a download failure of either template —
719
+ // leaves no orphaned app and nothing half-written (#1218, #2890).
720
+ for (const client of plan.clients) {
721
+ if (preparedTemplates.has(client.platform))
722
+ continue;
723
+ info(`Preparing your ${platformLabel(client.platform)} project template...`);
724
+ // The branch is the channel (issue #1934): scaffolding against the alpha
725
+ // server pulls the alpha template branch, whose Primitive deps pin the
726
+ // alpha prerelease libraries. Falls back to main (with a warning) if the
727
+ // channel branch isn't available.
728
+ const templateBranch = resolveTemplateBranch(serverUrl);
729
+ const templateUrlFor = client.platform === "ios" ? iosTemplateUrl : vueTemplateUrl;
730
+ try {
731
+ preparedTemplates.set(client.platform, await prepareTemplate({
732
+ templateUrl: templateUrlFor(templateBranch),
733
+ fallbackTemplateUrl: templateBranch !== "main" ? templateUrlFor("main") : undefined,
734
+ onFallback: (reason) => warn(`Template branch "${templateBranch}" unavailable (${reason}) — falling back to main.`),
735
+ onProgress: info,
736
+ }));
737
+ }
738
+ catch (err) {
739
+ error(`Failed to download template: ${err.message}`);
740
+ error("Check your internet connection and try again.");
741
+ // A template that already downloaded must not survive as a temp
742
+ // directory when the run stops here.
743
+ cleanupPreparedTemplate();
744
+ process.exit(1);
745
+ }
469
746
  }
470
747
  };
471
748
  // An existing app can be selected two ways: the `--use-existing-app-id` flag,
@@ -474,7 +751,49 @@ async function handleInit(projectDirArg, options) {
474
751
  // the create branch and prompt for an app name — hanging non-interactive
475
752
  // runs. (#1217)
476
753
  const useExistingAppId = resolveUseExistingAppId(options.useExistingAppId, initConfig);
477
- if (useExistingAppId) {
754
+ if (plan.mode === "add-client") {
755
+ // ── Adopt: the app is the one this project already targets ──────────
756
+ //
757
+ // `appName` is OPTIONAL in a valid environment, so it is resolved rather
758
+ // than assumed: the environment's name, else the app's name from the API
759
+ // when we are authenticated, else the client directory's own name. No
760
+ // downstream writer ever receives an undefined display name, and no
761
+ // scaffold ships an unresolved placeholder.
762
+ appId = adopted.config.appId;
763
+ appName = adopted.config.appName ?? "";
764
+ // Credentials are resolved from the working directory, while the app comes
765
+ // from the project the TARGET sits in — a target inside a different project
766
+ // (or a run from outside any) can leave the CLI holding another server's
767
+ // token, and every API call here would go there with this app's id. The
768
+ // run continues unauthenticated instead: nothing it writes needs the API.
769
+ const credentialServer = credentials ? normalizeServerUrl(credentials.serverUrl) : null;
770
+ if (credentialServer && credentialServer !== normalizeServerUrl(adopted.config.apiUrl)) {
771
+ warn(`The CLI is logged in to ${credentials.serverUrl}, but the "${adopted.name}" environment in ${adoptedRoot} targets ${adopted.config.apiUrl}.`);
772
+ warn(`Continuing without contacting either server. Run init from inside that project, or log in to ${adopted.config.apiUrl}, to have the app verified.`);
773
+ credentials = null;
774
+ }
775
+ else {
776
+ credentials = await ensureAuthenticated(credentials, serverUrl, serverChanged, {
777
+ reason: "verify the app",
778
+ allowSkip: true,
779
+ nonInteractive: !!initConfig,
780
+ });
781
+ }
782
+ if (!appName && credentials) {
783
+ try {
784
+ const client = new ApiClient();
785
+ appName = (await client.getApp(appId)).name;
786
+ }
787
+ catch (err) {
788
+ warn(`Could not look up the app's name: ${err.message}`);
789
+ }
790
+ }
791
+ if (!appName)
792
+ appName = basename(plan.clients[0].dir);
793
+ info(`Adding a ${plan.clients.map((c) => platformLabel(c.platform)).join(" and ")} client to ${appName} (${appId}).`);
794
+ await prepareTemplateOrExit();
795
+ }
796
+ else if (useExistingAppId) {
478
797
  // Using existing app ID - verify it exists
479
798
  appId = useExistingAppId;
480
799
  appName = "(existing app)"; // Default if we can't verify
@@ -549,7 +868,7 @@ async function handleInit(projectDirArg, options) {
549
868
  else {
550
869
  console.log();
551
870
  info("Let's configure who can access your app.");
552
- info("(You can change this later with 'primitive apps update')");
871
+ info("(You can change this later in app.toml, then 'primitive config push --only app')");
553
872
  accessMode = await select({
554
873
  message: "Who should be able to sign up for your app?",
555
874
  choices: [
@@ -675,13 +994,16 @@ async function handleInit(projectDirArg, options) {
675
994
  }
676
995
  }
677
996
  }
678
- // Step 3 (deferred): install the already-prepared template + init git, now
679
- // that the app exists. The network download and archive validation already
680
- // happened before createApp, without touching targetDir.
681
- info(`Setting up your ${platform === "ios" ? "iOS" : "web"} project...`);
997
+ // ── Install every selected template ─────────────────────────────────
998
+ //
999
+ // The network download and archive validation already happened above,
1000
+ // without touching any target directory.
682
1001
  try {
683
- preparedTemplate.install(targetDir);
684
- success("Template extracted successfully.");
1002
+ for (const client of plan.clients) {
1003
+ info(`Setting up your ${platformLabel(client.platform)} project...`);
1004
+ preparedTemplates.get(client.platform).install(client.dir);
1005
+ success(`${platformLabel(client.platform)} template extracted into ${client.dir}.`);
1006
+ }
685
1007
  }
686
1008
  catch (err) {
687
1009
  error(`Failed to write template files: ${err.message}`);
@@ -691,128 +1013,298 @@ async function handleInit(projectDirArg, options) {
691
1013
  finally {
692
1014
  cleanupPreparedTemplate();
693
1015
  }
694
- // Initialize git repository (commit happens later, after env + install)
695
- try {
696
- await gitInitRepo(targetDir);
697
- }
698
- catch {
699
- // Non-fatal: git may not be installed, or already a git repo
700
- }
701
- // Step 4.5: Update CLI to point at this app
702
- try {
703
- setCurrentApp(appId, appName);
704
- info(`CLI now using app: ${appName} (${appId})`);
1016
+ // Initialize git repository (commit happens later, after env + install).
1017
+ // An adopted repository already has one, and a nested repository inside it is
1018
+ // exactly what this change stops producing.
1019
+ if (plan.initsGit) {
1020
+ try {
1021
+ await gitInitRepo(plan.projectRoot);
1022
+ }
1023
+ catch {
1024
+ // Non-fatal: git may not be installed, or already a git repo
1025
+ }
705
1026
  }
706
- catch (err) {
707
- // Not critical - user may not be logged in (e.g. used --use-existing-app-id without login)
708
- warn(`Could not set current app in CLI config: ${err.message}`);
1027
+ // Step 4.5: Update CLI to point at this app. Adopting does not: the app is
1028
+ // already the project's, and the CLI's global selection is not this run's to
1029
+ // move.
1030
+ if (plan.ownsApp) {
1031
+ try {
1032
+ setCurrentApp(appId, appName);
1033
+ info(`CLI now using app: ${appName} (${appId})`);
1034
+ }
1035
+ catch (err) {
1036
+ // Not critical - user may not be logged in (e.g. used --use-existing-app-id without login)
1037
+ warn(`Could not set current app in CLI config: ${err.message}`);
1038
+ }
709
1039
  }
710
- // Steps 5-8: Platform-specific configuration and dependency installation
711
- if (isApple) {
712
- // ── Apple (SwiftUI) path ──────────────────────────────────────────
713
- // Step 5: Update primitive.json
714
- info("Configuring primitive.json...");
1040
+ // Step 4.6: Scaffold .primitive/config.json with a "dev" environment bound
1041
+ // to this app, and seed its credential slot with the session we just
1042
+ // authenticated so `primitive` commands run from inside the project pick
1043
+ // up project mode without a second login.
1044
+ if (plan.writesProjectConfig) {
715
1045
  try {
716
- const updated = updatePrimitiveJson(targetDir, appId, serverUrl, appName);
717
- if (!updated) {
718
- warn("No primitive.json file found in template.");
719
- warn(`Please manually set appId to "${appId}" in your primitive.json.`);
720
- }
721
- else {
722
- success("primitive.json configured.");
1046
+ await scaffoldProjectConfig({
1047
+ targetDir: plan.projectRoot,
1048
+ appId,
1049
+ appName,
1050
+ serverUrl,
1051
+ });
1052
+ if (credentials) {
1053
+ seedCredentialsForEnvInProject(plan.projectRoot, "dev", credentials);
723
1054
  }
1055
+ success(`Project environment "dev" configured (.primitive/config.json).`);
724
1056
  }
725
1057
  catch (err) {
726
- warn(`Could not update primitive.json: ${err.message}`);
727
- warn(`Please manually set appId to "${appId}" in your primitive.json.`);
1058
+ warn(`Could not scaffold .primitive/config.json: ${err.message}`);
728
1059
  }
729
- // Step 6-7: Skip port selection and pnpm (not applicable to Apple)
730
- // Step 8: Resolve Swift packages
731
- if (!options.skipInstall) {
732
- info("Resolving Swift packages (this may take a few minutes)...");
1060
+ }
1061
+ else {
1062
+ // Adopting: the config is the project's own. Only make sure the local state
1063
+ // a new client's environment produces stays out of the repository.
1064
+ try {
1065
+ ensureGitignoreLocalState(plan.projectRoot);
1066
+ }
1067
+ catch (err) {
1068
+ warn(`Could not update .gitignore: ${err.message}`);
1069
+ }
1070
+ }
1071
+ // ── The one model schema (#2890) ────────────────────────────────────
1072
+ if (plan.canonicalSchemaPath && schemaPlan) {
1073
+ composeSchema({ plan, schemaPlan });
1074
+ }
1075
+ // ── The app-wide AGENTS.md ──────────────────────────────────────────
1076
+ if (plan.writesRootAgents) {
1077
+ const agentsPath = join(plan.projectRoot, "AGENTS.md");
1078
+ if (!existsSync(agentsPath)) {
733
1079
  try {
734
- await runSwiftPackageResolve(targetDir);
735
- success("Swift packages resolved.");
1080
+ // The clients this run wrote, plus any the repository already had —
1081
+ // adding iOS to a web app describes a repository with two clients.
1082
+ const written = plan.clients.map((client) => ({
1083
+ platform: client.platform,
1084
+ dir: relative(plan.projectRoot, client.dir) || ".",
1085
+ }));
1086
+ const clients = [
1087
+ ...written,
1088
+ ...discoverExistingClients(plan.projectRoot).filter((existing) => !written.some((client) => client.dir === existing.dir)),
1089
+ ];
1090
+ writeFileSync(agentsPath, rootAgentsMarkdown({ appName, clients }));
1091
+ success("Wrote AGENTS.md describing the app layout.");
736
1092
  }
737
1093
  catch (err) {
738
- warn(`Swift package resolution failed: ${err.message}`);
739
- warn("You can try running 'swift package resolve' manually.");
1094
+ warn(`Could not write AGENTS.md: ${err.message}`);
740
1095
  }
741
1096
  }
742
- else {
743
- info("Skipping dependency installation (--skip-install).");
744
- }
745
1097
  }
746
- else {
1098
+ // ── Per-client configuration and dependency installation ────────────
1099
+ //
1100
+ // The production runtime target is derived once from the project's own
1101
+ // environments, so a client built for production talks to a backend the app
1102
+ // id actually exists on (#2890).
1103
+ const production = plan.mode === "standalone"
1104
+ ? undefined
1105
+ : resolveProductionRuntime({
1106
+ environments: (adopted?.projectConfig.environments ??
1107
+ readProjectEnvironments(plan.projectRoot)),
1108
+ selectedServerUrl: serverUrl,
1109
+ selectedAppId: appId,
1110
+ selectedAppName: appName,
1111
+ productionServerUrl: PRODUCTION_SERVER_URL,
1112
+ });
1113
+ /**
1114
+ * The URL scheme derived for each Apple client, for the final summary.
1115
+ * `registered` is false when the client's plist had no `PrimitiveAuth` URL
1116
+ * type to stamp it into, so the summary and the opt-in guidance describe a
1117
+ * candidate scheme rather than a registered one.
1118
+ */
1119
+ const iosCallbackSchemes = [];
1120
+ for (const client of plan.clients) {
1121
+ if (client.platform === "ios") {
1122
+ // ── Apple (SwiftUI) path ────────────────────────────────────────
1123
+ // The Xcode build phases name the project config as a declared input,
1124
+ // and inside Xcode's script sandbox a phase may read only what it
1125
+ // declared. When the config lives above this client, both the generated
1126
+ // spec and the checked-in .xcodeproj have to say so — otherwise a fresh
1127
+ // clone (primitive.json is gitignored) cannot build in Xcode at all, and
1128
+ // a working copy that has one keeps whichever environment wrote it.
1129
+ if (resolve(client.dir) !== resolve(plan.projectRoot)) {
1130
+ const declared = declareSharedProjectConfig(client.dir, plan.projectRoot);
1131
+ if (declared.length > 0) {
1132
+ success(`Xcode build phases read ${relative(client.dir, join(plan.projectRoot, ".primitive", "config.json"))}.`);
1133
+ }
1134
+ }
1135
+ // Step 5: Generate primitive.json from the environment.
1136
+ //
1137
+ // In a current template the file is a build product, written by
1138
+ // `scripts/resolve-primitive-config.sh` from `.primitive/config.json`
1139
+ // (#2873) — it walks up to the project root, so a client inside a
1140
+ // composed repository resolves the same one every other command does. A
1141
+ // template that predates the change has no such script and a tracked
1142
+ // primitive.json instead; fill that in the old way.
1143
+ info("Configuring primitive.json...");
1144
+ try {
1145
+ const result = configurePrimitiveJson(client.dir, appId, serverUrl, appName, {
1146
+ // Adopting resolved an environment of the project's own — the one
1147
+ // whose app this client is being added to. The script has to be told
1148
+ // which, or it re-resolves from this machine and can configure the
1149
+ // client for a different app on a different backend.
1150
+ environmentName: adopted?.name,
1151
+ });
1152
+ if (result.outcome === "generated") {
1153
+ success("primitive.json generated from .primitive/config.json.");
1154
+ }
1155
+ else if (result.outcome === "filled") {
1156
+ success("primitive.json configured.");
1157
+ }
1158
+ else if (result.outcome === "failed") {
1159
+ warn(`Could not generate primitive.json: ${result.detail}`);
1160
+ warn("Run 'bash scripts/resolve-primitive-config.sh' in the project to retry.");
1161
+ }
1162
+ else {
1163
+ // Neither the resolve script nor a template primitive.json — an
1164
+ // unexpectedly old or trimmed template. The remedy is still never
1165
+ // "type the app ID somewhere else": it is already in
1166
+ // .primitive/config.json, which is where every reader looks.
1167
+ warn("This template has neither scripts/resolve-primitive-config.sh nor a primitive.json.");
1168
+ warn(`The project config holds the app ID; update the template to generate primitive.json from it.`);
1169
+ }
1170
+ }
1171
+ catch (err) {
1172
+ warn(`Could not configure primitive.json: ${err.message}`);
1173
+ warn("Run 'bash scripts/resolve-primitive-config.sh' in the project to retry.");
1174
+ }
1175
+ // Step 5b: Give this client its own URL scheme (#2969).
1176
+ //
1177
+ // The template ships `primitiveapp` registered, which every app
1178
+ // scaffolded from it would otherwise share — iOS then picks arbitrarily
1179
+ // between two of them for an incoming link. The stamped scheme carries
1180
+ // the app id, so no two apps collide.
1181
+ //
1182
+ // Nothing is written to the app's `emailRedirectUris`, here or on the
1183
+ // server: the manager sends no redirect target by default, so this app's
1184
+ // email sign-in works immediately and code-only. The link is the
1185
+ // developer's opt-in, and this run only prints what it takes.
1186
+ const callbackScheme = deriveCallbackScheme(appName, appId, basename(client.dir));
1187
+ const stamped = stampCallbackScheme(client.dir, callbackScheme);
1188
+ iosCallbackSchemes.push({
1189
+ dir: client.dir,
1190
+ scheme: callbackScheme,
1191
+ registered: stamped.outcome !== "not-found",
1192
+ });
1193
+ if (stamped.outcome === "not-found") {
1194
+ for (const line of missingUrlTypeGuidance(callbackScheme))
1195
+ warn(line);
1196
+ }
1197
+ else {
1198
+ success(`Callback URL scheme registered: ${callbackScheme}`);
1199
+ }
1200
+ // Step 6-7: Skip port selection and pnpm (not applicable to Apple)
1201
+ // Step 8: Resolve Swift packages
1202
+ if (!skipInstall) {
1203
+ info("Resolving Swift packages (this may take a few minutes)...");
1204
+ try {
1205
+ await runSwiftPackageResolve(client.dir);
1206
+ success("Swift packages resolved.");
1207
+ }
1208
+ catch (err) {
1209
+ warn(`Swift package resolution failed: ${err.message}`);
1210
+ warn("You can try running 'swift package resolve' manually.");
1211
+ }
1212
+ }
1213
+ else {
1214
+ info(`Skipping dependency installation (${skipInstallReason}).`);
1215
+ }
1216
+ continue;
1217
+ }
747
1218
  // ── Web path ──────────────────────────────────────────────────────
748
- // Step 5: Update .env file
1219
+ // Step 5: Fill in an OLD template's .env identity keys.
1220
+ //
1221
+ // A current template does not author them at all — `primitiveEnv()` reads
1222
+ // `.primitive/config.json`, which it finds by walking up — so "no keys to
1223
+ // replace" is the expected outcome, not a problem (#2873). The fill-in
1224
+ // survives only so a new CLI still produces a working scaffold from a
1225
+ // template that predates the change.
749
1226
  info("Configuring environment...");
750
1227
  try {
751
- const envResult = updateEnvFile(targetDir, appId, serverUrl, appName);
1228
+ const envResult = updateEnvFile(client.dir, appId, serverUrl, appName, production);
752
1229
  if (!envResult.envUpdated) {
753
- warn("No .env or .env.example file found in template.");
754
- warn(`Please manually set VITE_APP_ID=${appId} in your .env file.`);
755
- }
756
- else if (!envResult.envProductionUpdated) {
757
- info(".env configured. No .env.production file found (this is optional).");
1230
+ info("No .env file in this template identity comes from .primitive/config.json.");
758
1231
  }
759
1232
  else {
760
- success("Environment configured (.env and .env.production).");
1233
+ success("Environment configured.");
761
1234
  }
762
1235
  }
763
1236
  catch (err) {
764
1237
  warn(`Could not update .env file: ${err.message}`);
765
- warn(`Please manually set VITE_APP_ID=${appId} in your .env file.`);
766
1238
  }
767
- // Step 6: Confirm the dev port to use. Default to 5173; warn about taken ports.
1239
+ // Step 6: Determine the dev port. Default to 5173; warn about taken ports
1240
+ // when prompting. The init config's `dev_port` decides it non-interactively
1241
+ // — this was the one branch in the command that prompted unconditionally,
1242
+ // so the documented key was ignored and a closed stdin threw
1243
+ // ERR_USE_AFTER_CLOSE into the catch below (#2720).
768
1244
  try {
769
- console.log();
770
- const defaultPort = 5173;
1245
+ const defaultPort = DEFAULT_DEV_PORT;
771
1246
  const defaultOrigin = `http://localhost:${defaultPort}`;
772
- // Scan up to 10 ports starting from 5173 to surface what's already in use
773
- const takenPorts = [];
774
- for (let p = defaultPort; p < defaultPort + 10; p++) {
775
- if (!(await isPortFree(p)))
776
- takenPorts.push(p);
777
- else
778
- break;
779
- }
780
- if (takenPorts.length > 0) {
781
- warn(`Port${takenPorts.length > 1 ? "s" : ""} ${takenPorts.join(", ")} ${takenPorts.length > 1 ? "are" : "is"} already in use.`);
782
- }
783
- const portInput = await input({
784
- message: "Dev server port for this project:",
785
- default: String(defaultPort),
786
- validate: (val) => {
787
- const n = parseInt(val, 10);
788
- if (isNaN(n) || n < 1 || n > 65535)
789
- return "Enter a valid port number.";
790
- return true;
1247
+ const resolvedPort = await resolveDevPort({
1248
+ configPort: initConfig?.dev_port,
1249
+ hasConfig: initConfig != null,
1250
+ isTTY: Boolean(process.stdin.isTTY),
1251
+ defaultPort,
1252
+ promptFn: async () => {
1253
+ console.log();
1254
+ // Scan up to 10 ports starting from 5173 to surface what's already in use
1255
+ const takenPorts = [];
1256
+ for (let p = defaultPort; p < defaultPort + 10; p++) {
1257
+ if (!(await isPortFree(p)))
1258
+ takenPorts.push(p);
1259
+ else
1260
+ break;
1261
+ }
1262
+ if (takenPorts.length > 0) {
1263
+ warn(`Port${takenPorts.length > 1 ? "s" : ""} ${takenPorts.join(", ")} ${takenPorts.length > 1 ? "are" : "is"} already in use.`);
1264
+ }
1265
+ const portInput = await input({
1266
+ message: "Dev server port for this project:",
1267
+ default: String(defaultPort),
1268
+ validate: validateDevPort,
1269
+ });
1270
+ return parseInt(portInput, 10);
791
1271
  },
792
1272
  });
793
- const chosenPort = parseInt(portInput, 10);
1273
+ const chosenPort = resolvedPort.port;
1274
+ if (resolvedPort.source === "config") {
1275
+ info(`Dev server port: ${chosenPort} (from config)`);
1276
+ }
794
1277
  if (chosenPort !== defaultPort) {
795
1278
  const devOrigin = `http://localhost:${chosenPort}`;
796
- // Pin the port in vite.config.ts and update .env
797
- updateViteConfig(targetDir, chosenPort);
798
- updateEnvPort(targetDir, chosenPort);
1279
+ // Pin the port in vite.config.ts and update .env. A vite config whose
1280
+ // shape we can't patch must be said out loud — otherwise the dev
1281
+ // server keeps 5173 while .env and the redirect URIs point elsewhere.
1282
+ const viteUpdated = updateViteConfig(client.dir, chosenPort);
1283
+ if (!viteUpdated) {
1284
+ warn(`Could not pin port ${chosenPort} in vite.config.ts — set \`server.port\` there manually.`);
1285
+ }
1286
+ updateEnvPort(client.dir, chosenPort);
799
1287
  // Update app settings: CORS, redirect URIs, baseUrl
800
1288
  if (!credentials) {
801
1289
  info(`Local files updated. Skipping server CORS/redirect config — not authenticated.`);
802
1290
  }
803
1291
  else {
804
1292
  try {
805
- const client = new ApiClient();
1293
+ const apiClient = new ApiClient();
806
1294
  let existingOrigins = [];
807
- let existingRedirectUris = [];
1295
+ let existingEmailRedirectUris = [];
1296
+ let existingGoogleClients = null;
808
1297
  try {
809
- const currentSettings = await client.getAppSettings(appId);
1298
+ const currentSettings = await apiClient.getAppSettings(appId);
810
1299
  if (currentSettings.corsMode === "custom" &&
811
1300
  Array.isArray(currentSettings.corsAllowedOrigins)) {
812
1301
  existingOrigins = currentSettings.corsAllowedOrigins;
813
1302
  }
814
- if (Array.isArray(currentSettings.redirectUris)) {
815
- existingRedirectUris = currentSettings.redirectUris;
1303
+ if (Array.isArray(currentSettings.emailRedirectUris)) {
1304
+ existingEmailRedirectUris = currentSettings.emailRedirectUris;
1305
+ }
1306
+ if (currentSettings.googleClients) {
1307
+ existingGoogleClients = currentSettings.googleClients;
816
1308
  }
817
1309
  }
818
1310
  catch {
@@ -820,19 +1312,46 @@ async function handleInit(projectDirArg, options) {
820
1312
  }
821
1313
  // Always include 5173 since it's the universal localhost default
822
1314
  const corsOrigins = Array.from(new Set([...existingOrigins, defaultOrigin, devOrigin]));
823
- const redirectUris = Array.from(new Set([
824
- ...existingRedirectUris,
1315
+ // MERGED into the creation-time seed, never replacing it (#2891):
1316
+ // `emailRedirectUris` matching is fail-closed, so blindly writing
1317
+ // only this port's callback would break every other environment the
1318
+ // app already serves.
1319
+ const emailRedirectUris = Array.from(new Set([
1320
+ ...existingEmailRedirectUris,
825
1321
  `${defaultOrigin}/oauth/callback`,
826
1322
  `${devOrigin}/oauth/callback`,
827
1323
  ]));
828
- await client.updateAppSettings(appId, {
1324
+ const settingsUpdate = {
829
1325
  corsMode: "custom",
830
1326
  corsAllowedOrigins: corsOrigins,
831
1327
  corsAllowCredentials: true,
832
- redirectUris,
1328
+ emailRedirectUris,
833
1329
  baseUrl: devOrigin,
834
- });
835
- success(`Dev port set to ${chosenPort}: vite.config.ts, .env, CORS, redirect URIs, and base URL updated.`);
1330
+ };
1331
+ // A Google web client redirects to this dev origin too, so its own
1332
+ // `redirectUris` needs the callback. A PUT replaces the WHOLE map,
1333
+ // so the complete map is sent back — an entry for a platform this
1334
+ // scaffold does not touch (ios, desktop, …) would otherwise be
1335
+ // deleted as a side effect of choosing a dev port.
1336
+ const webEntry = existingGoogleClients?.clients?.web;
1337
+ if (webEntry) {
1338
+ settingsUpdate.googleClients = {
1339
+ ...existingGoogleClients,
1340
+ clients: {
1341
+ ...existingGoogleClients.clients,
1342
+ web: {
1343
+ ...webEntry,
1344
+ redirectUris: Array.from(new Set([
1345
+ ...(webEntry.redirectUris ?? []),
1346
+ `${defaultOrigin}/oauth/callback`,
1347
+ `${devOrigin}/oauth/callback`,
1348
+ ])),
1349
+ },
1350
+ },
1351
+ };
1352
+ }
1353
+ await apiClient.updateAppSettings(appId, settingsUpdate);
1354
+ success(`Dev port set to ${chosenPort}: ${viteUpdated ? "vite.config.ts, " : ""}.env, CORS, redirect URIs, and base URL updated.`);
836
1355
  }
837
1356
  catch (err) {
838
1357
  warn(`Could not update app settings: ${err.message}`);
@@ -840,18 +1359,32 @@ async function handleInit(projectDirArg, options) {
840
1359
  }
841
1360
  }
842
1361
  }
843
- catch {
844
- // Non-fatal: port detection or settings update failed silently
1362
+ catch (err) {
1363
+ // Non-fatal but say so. A silent swallow here is what hid the closed
1364
+ // stdin crash in #2720: the run kept 5173 and still exited 0.
1365
+ warn(`Could not configure the dev server port: ${err.message}`);
1366
+ warn("The project keeps the default port 5173.");
845
1367
  }
846
- // Step 7: Check if pnpm is installed globally, offer to install if not
1368
+ // Step 7: Check if pnpm is installed globally, offer to install if not.
1369
+ //
1370
+ // An offer, so only where there is someone to ask: a config-driven run
1371
+ // answers no questions, and a piped stdin has no answer to give. Either way
1372
+ // the install below still runs pnpm through npx, so the client gets its
1373
+ // dependencies — this is about the machine, not about this project.
847
1374
  const pnpmInstalled = await isPnpmInstalled();
848
1375
  if (!pnpmInstalled) {
849
1376
  console.log();
850
1377
  info("pnpm is not installed globally on your system.");
851
- const installPnpm = await confirm({
852
- message: "Install pnpm globally? (recommended for future use)",
853
- default: true,
854
- });
1378
+ const canAsk = initConfig == null && Boolean(process.stdin.isTTY);
1379
+ const installPnpm = canAsk
1380
+ ? await confirm({
1381
+ message: "Install pnpm globally? (recommended for future use)",
1382
+ default: true,
1383
+ })
1384
+ : false;
1385
+ if (!canAsk) {
1386
+ info("Using npx to run pnpm. Install it globally later with: npm install -g pnpm");
1387
+ }
855
1388
  if (installPnpm) {
856
1389
  info("Installing pnpm...");
857
1390
  try {
@@ -865,10 +1398,10 @@ async function handleInit(projectDirArg, options) {
865
1398
  }
866
1399
  }
867
1400
  // Step 8: Install dependencies with pnpm (via npx to handle version management)
868
- if (!options.skipInstall) {
1401
+ if (!skipInstall) {
869
1402
  info("Installing dependencies...");
870
1403
  try {
871
- await runPnpmInstall(targetDir);
1404
+ await runPnpmInstall(client.dir);
872
1405
  success("Dependencies installed.");
873
1406
  }
874
1407
  catch (err) {
@@ -877,7 +1410,7 @@ async function handleInit(projectDirArg, options) {
877
1410
  }
878
1411
  }
879
1412
  else {
880
- info("Skipping dependency installation (--skip-install).");
1413
+ info(`Skipping dependency installation (${skipInstallReason}).`);
881
1414
  }
882
1415
  }
883
1416
  // Step 9: Install primitive CLI globally if not already installed
@@ -892,7 +1425,7 @@ async function handleInit(projectDirArg, options) {
892
1425
  }
893
1426
  catch (err) {
894
1427
  warn(`Could not install CLI: ${err.message}`);
895
- warn("You can install it manually with: npm install -g primitive-admin");
1428
+ warn(`You can install it manually with: ${installCommand(PRIMITIVE_CLI_PACKAGE)}`);
896
1429
  }
897
1430
  }
898
1431
  else {
@@ -910,7 +1443,7 @@ async function handleInit(projectDirArg, options) {
910
1443
  }
911
1444
  catch (err) {
912
1445
  warn(`Could not install CLI: ${err.message}`);
913
- warn("You can install it manually with: npm install -g primitive-admin");
1446
+ warn(`You can install it manually with: ${installCommand(PRIMITIVE_CLI_PACKAGE)}`);
914
1447
  }
915
1448
  }
916
1449
  }
@@ -941,39 +1474,285 @@ async function handleInit(projectDirArg, options) {
941
1474
  catch {
942
1475
  // Non-fatal: skill installation should never block init
943
1476
  }
944
- // Step 11: Create initial git commit (captures env config + installed dependencies)
945
- try {
946
- await gitInitialCommit(targetDir);
947
- }
948
- catch {
949
- // Non-fatal: git may not be installed, or already committed
1477
+ // Step 11: Create initial git commit (captures env config + installed
1478
+ // dependencies). Not when adopting: the surrounding repository owns its
1479
+ // history, and the new files are the user's to review and commit.
1480
+ if (plan.initsGit) {
1481
+ try {
1482
+ await gitInitialCommit(plan.projectRoot);
1483
+ }
1484
+ catch {
1485
+ // Non-fatal: git may not be installed, or already committed
1486
+ }
950
1487
  }
951
1488
  // Step 12: Show success message
952
1489
  divider();
953
- success("Project initialized successfully!");
1490
+ success(plan.mode === "add-client"
1491
+ ? "Client added successfully!"
1492
+ : "Project initialized successfully!");
954
1493
  divider();
955
- keyValue("Directory", targetDir);
1494
+ keyValue("Project", plan.projectRoot);
956
1495
  keyValue("App Name", appName);
957
1496
  keyValue("App ID", appId);
958
- keyValue("Platform", platform === "ios" ? "iOS (SwiftUI)" : "Web");
1497
+ for (const client of plan.clients) {
1498
+ keyValue(platformLabel(client.platform), client.dir);
1499
+ }
1500
+ if (plan.canonicalSchemaPath) {
1501
+ keyValue("Model schema", plan.canonicalSchemaPath);
1502
+ }
1503
+ for (const { scheme, registered } of iosCallbackSchemes) {
1504
+ keyValue("Callback URL scheme", registered ? scheme : `${scheme} (not registered — see the warning above)`);
1505
+ }
959
1506
  divider();
1507
+ // Email sign-in already works for the scaffolded app — code-only, no app
1508
+ // settings — so this is an opt-in, not a step (#2969).
1509
+ for (const { scheme, registered } of iosCallbackSchemes) {
1510
+ for (const line of linkOptInGuidance(scheme, { registered }))
1511
+ info(line);
1512
+ divider();
1513
+ }
1514
+ if (plan.mode === "add-client") {
1515
+ info(`No .primitive/ and no .git/ were created inside the new client — this app has one of each, at ${plan.projectRoot}.`);
1516
+ info(`The new files are uncommitted: review them with \`git status\` in ${plan.projectRoot} and commit when you are happy.`);
1517
+ divider();
1518
+ }
960
1519
  info("Next steps:");
961
- if (projectDir !== ".") {
962
- console.log(` cd ${projectDir}`);
1520
+ for (const client of plan.clients) {
1521
+ const relativeDir = relative(process.cwd(), client.dir);
1522
+ // A target outside the working directory reads better as its own path than
1523
+ // as a chain of `../`.
1524
+ const where = relativeDir.startsWith("..") ? client.dir : relativeDir || ".";
1525
+ if (where !== ".")
1526
+ console.log(` cd ${where}`);
1527
+ if (client.platform === "ios") {
1528
+ if (skipInstall)
1529
+ console.log(" swift package resolve");
1530
+ // The Xcode project lists its sources explicitly, and the shared schema
1531
+ // brings models the checked-in project does not compile yet — so the
1532
+ // first build regenerates. `run-ios.sh` runs codegen and xcodegen in that
1533
+ // order; a build straight from Xcode before that stops and says so.
1534
+ if (resolve(client.dir) !== resolve(plan.projectRoot)) {
1535
+ console.log(" ./run-ios.sh # codegen + xcodegen, then the Simulator");
1536
+ console.log(" # then: open *.xcodeproj");
1537
+ }
1538
+ else {
1539
+ console.log(" open *.xcodeproj");
1540
+ console.log(" # or: ./run-ios.sh (iOS Simulator)");
1541
+ }
1542
+ }
1543
+ else {
1544
+ if (skipInstall)
1545
+ console.log(" pnpm install");
1546
+ console.log(" pnpm dev");
1547
+ }
963
1548
  }
964
- if (isApple) {
965
- if (options.skipInstall) {
966
- console.log(" swift package resolve");
1549
+ console.log();
1550
+ }
1551
+ /** Where a project root's environments live, for the production derivation. */
1552
+ function readProjectEnvironments(projectRoot) {
1553
+ const configPath = join(projectRoot, PROJECT_CONFIG_DIR, PROJECT_CONFIG_FILENAME);
1554
+ if (!existsSync(configPath))
1555
+ return undefined;
1556
+ try {
1557
+ return loadProjectConfigFromPath(configPath).environments;
1558
+ }
1559
+ catch {
1560
+ return undefined;
1561
+ }
1562
+ }
1563
+ /**
1564
+ * The clients a repository already has, for the app-wide `AGENTS.md`.
1565
+ *
1566
+ * A run that adds a client to an existing app knows only about the one it is
1567
+ * writing, and a layout description that names one client of two describes the
1568
+ * repository wrongly to the next agent that reads it. The signals are the ones
1569
+ * the templates ship — a Swift package or Xcode project, a Vite project — so a
1570
+ * `functions/` directory with a `package.json` is not mistaken for a client.
1571
+ */
1572
+ function discoverExistingClients(projectRoot) {
1573
+ let entries;
1574
+ try {
1575
+ entries = readdirSync(projectRoot, { withFileTypes: true });
1576
+ }
1577
+ catch {
1578
+ return [];
1579
+ }
1580
+ const found = [];
1581
+ for (const entry of entries) {
1582
+ if (!entry.isDirectory() || entry.name.startsWith("."))
1583
+ continue;
1584
+ const dir = join(projectRoot, entry.name);
1585
+ const hasXcodeProject = (() => {
1586
+ try {
1587
+ return readdirSync(dir).some((name) => name.endsWith(".xcodeproj"));
1588
+ }
1589
+ catch {
1590
+ return false;
1591
+ }
1592
+ })();
1593
+ if (existsSync(join(dir, "Package.swift")) || hasXcodeProject) {
1594
+ found.push({ platform: "ios", dir: entry.name });
1595
+ }
1596
+ else if (existsSync(join(dir, "package.json")) &&
1597
+ existsSync(join(dir, "vite.config.ts"))) {
1598
+ found.push({ platform: "web", dir: entry.name });
1599
+ }
1600
+ }
1601
+ return found;
1602
+ }
1603
+ /**
1604
+ * Decides how this run gets to ONE schema — before anything is downloaded or
1605
+ * written, because the answer can be "stop".
1606
+ */
1607
+ async function resolveSchemaComposition(input) {
1608
+ const schemaPath = input.plan.canonicalSchemaPath;
1609
+ if (existsSync(schemaPath))
1610
+ return { alreadyPresent: true };
1611
+ // A fresh composition seeds the shared schema from the clients it is about
1612
+ // to scaffold; there is nothing to move and nobody to ask.
1613
+ if (input.plan.mode !== "add-client")
1614
+ return { alreadyPresent: false };
1615
+ const root = input.plan.projectRoot;
1616
+ const existing = ["web", "ios"]
1617
+ .map((platform) => ({ platform, schemaPath: findClientSchema(root, platform) }))
1618
+ .find((candidate) => candidate.schemaPath !== null);
1619
+ if (existing) {
1620
+ // The flat single-client layout `primitive init` still produces: the client
1621
+ // IS the repository root, and its schema has to become the app's.
1622
+ const from = relative(root, existing.schemaPath);
1623
+ // Moving the schema is only half of it — what reads the schema has to be
1624
+ // able to name the new location. A client that cannot be rewired would keep
1625
+ // its own copy beside the app's, which is the drift the one schema exists
1626
+ // to prevent, so the run stops here: before the download, before the move,
1627
+ // with the repository exactly as it was.
1628
+ const blocked = checkClientWiring(root, existing.platform, schemaPath);
1629
+ if (blocked) {
1630
+ error(`The ${platformLabel(existing.platform)} client at ${root} cannot be pointed at ${relative(root, schemaPath)}: ${blocked}.`);
1631
+ error(`Every client of an app reads one schema, so ${from} stays where it is. Restore that file to its template shape, or move the schema and rewire the client by hand, then re-run this command.`);
1632
+ warn("No project files were written.");
1633
+ process.exit(1);
1634
+ }
1635
+ info(`This repository's model schema is at ${from}. Adding a second client means moving it to models/models.toml so both clients read one copy.`);
1636
+ if (!input.promoteConsent) {
1637
+ if (!input.interactive) {
1638
+ error(`Adding a client needs the schema at models/models.toml, and moving ${from} there needs your consent.`);
1639
+ error(input.nonInteractive
1640
+ ? 'Set `promote_schema = true` alongside `action = "add-client"` in the init config to allow the move.'
1641
+ : "Re-run from an interactive terminal, or with an init config setting `promote_schema = true`, to allow the move.");
1642
+ warn("No project files were written.");
1643
+ process.exit(1);
1644
+ }
1645
+ const proceed = await confirm({
1646
+ message: `Move ${from} to models/models.toml and point both clients at it?`,
1647
+ default: true,
1648
+ });
1649
+ if (!proceed) {
1650
+ error("Aborted. No project files were written.");
1651
+ process.exit(1);
1652
+ }
1653
+ }
1654
+ return {
1655
+ alreadyPresent: false,
1656
+ promoteFrom: { dir: root, platform: existing.platform, schemaPath: existing.schemaPath },
1657
+ };
1658
+ }
1659
+ // A root that looks like a client but keeps its schema somewhere neither
1660
+ // template does: say exactly what to do, and write nothing.
1661
+ const looksLikeClient = existsSync(join(root, "package.json")) || existsSync(join(root, "Package.swift"));
1662
+ if (looksLikeClient) {
1663
+ error(`The project at ${root} has a client, but no model schema where either template keeps one (src/models/models.toml, or Sources/<App>/Models/models.toml).`);
1664
+ error(`Move that client's schema to ${root}/models/models.toml and point its codegen at it, then re-run this command.`);
1665
+ warn("No project files were written.");
1666
+ process.exit(1);
1667
+ }
1668
+ return { alreadyPresent: false };
1669
+ }
1670
+ /**
1671
+ * Writes the app's one schema and points every client at it.
1672
+ *
1673
+ * The promoted file and the new wiring are written BEFORE the old client-local
1674
+ * copy goes away, so an interrupted promotion leaves a client with a schema
1675
+ * rather than one with neither.
1676
+ */
1677
+ function composeSchema(input) {
1678
+ const { plan, schemaPlan } = input;
1679
+ const schemaPath = plan.canonicalSchemaPath;
1680
+ const reportAddedModels = (added) => {
1681
+ if (added.length === 0)
1682
+ return;
1683
+ info(`Added ${added.map((model) => `\`${model}\``).join(", ")} to ${relative(plan.projectRoot, schemaPath)} — the models the added client's own code reads. Models the app already declares are untouched.`);
1684
+ };
1685
+ const clientsToWire = [
1686
+ ...(schemaPlan.promoteFrom
1687
+ ? [{ platform: schemaPlan.promoteFrom.platform, dir: schemaPlan.promoteFrom.dir }]
1688
+ : []),
1689
+ ...plan.clients,
1690
+ ];
1691
+ // Asked of every client before the shared schema exists. A client that cannot
1692
+ // be pointed at it keeps its own copy — so writing the shared one anyway, and
1693
+ // wiring whichever clients did work, would leave the app with two schemas and
1694
+ // the run reporting success. One schema, or none: the existing client's
1695
+ // shape was already checked before the download, so this catches an installed
1696
+ // template whose wiring this CLI no longer recognizes.
1697
+ const unreachable = clientsToWire
1698
+ .map((client) => ({
1699
+ client,
1700
+ reason: checkClientWiring(client.dir, client.platform, schemaPath),
1701
+ }))
1702
+ .filter((checked) => checked.reason !== null);
1703
+ if (unreachable.length > 0) {
1704
+ for (const { client, reason } of unreachable) {
1705
+ error(`The ${platformLabel(client.platform)} client at ${client.dir} cannot be pointed at ${schemaPath}: ${reason}.`);
1706
+ }
1707
+ error("Every client of an app reads one model schema, so nothing was moved and no client was rewired.");
1708
+ warn(`The templates this run installed are still in place; remove them and re-run, or point each client at ${schemaPath} by hand.`);
1709
+ process.exit(1);
1710
+ }
1711
+ // Every client this run installs ships a starter schema AND code generated
1712
+ // from it — the web template's store reads `UserPref`, and its generator
1713
+ // refuses a schema with no models at all. So the app's schema has to declare
1714
+ // what each client reads, whether it is being written now or was already
1715
+ // there: a promoted comment-only Swift starter would otherwise hand a new web
1716
+ // client a schema it cannot generate from, and the run would report success.
1717
+ const starters = plan.clients
1718
+ .map((client) => findClientSchema(client.dir, client.platform))
1719
+ .filter((found) => found !== null)
1720
+ .map((found) => readFileSync(found, "utf-8"));
1721
+ if (!schemaPlan.alreadyPresent) {
1722
+ // The base is the promoted client's schema when one is being promoted —
1723
+ // its models are the app's — else the richest starter this run installs.
1724
+ const base = (schemaPlan.promoteFrom
1725
+ ? readFileSync(schemaPlan.promoteFrom.schemaPath, "utf-8")
1726
+ : starters.find((starter) => declaredModelNames(starter).length > 0)) ??
1727
+ starters[0] ??
1728
+ FALLBACK_STARTER_SCHEMA;
1729
+ const composed = composeSchemaContent({ base, starters });
1730
+ if (writeCanonicalSchema(schemaPath, `${CANONICAL_SCHEMA_HEADER}\n${composed.content}`)) {
1731
+ success(`Wrote ${relative(plan.projectRoot, schemaPath)} — the app's one model schema.`);
1732
+ reportAddedModels(schemaPlan.promoteFrom ? composed.added : []);
967
1733
  }
968
- console.log(" open *.xcodeproj");
969
- console.log(" # or: ./run-ios.sh (iOS Simulator)");
970
1734
  }
971
1735
  else {
972
- if (options.skipInstall) {
973
- console.log(" pnpm install");
1736
+ const composed = composeSchemaContent({
1737
+ base: readFileSync(schemaPath, "utf-8"),
1738
+ starters,
1739
+ });
1740
+ if (composed.added.length > 0) {
1741
+ writeFileSync(schemaPath, composed.content);
1742
+ reportAddedModels(composed.added);
974
1743
  }
975
- console.log(" pnpm dev");
976
1744
  }
977
- console.log();
1745
+ for (const client of clientsToWire) {
1746
+ const result = wireClientToSchema(client.dir, client.platform, schemaPath);
1747
+ if (result.error) {
1748
+ // The check above said this client could be wired, so an error here is
1749
+ // the filesystem changing under the run — still not something to finish
1750
+ // on top of, because it is a client reading a schema of its own.
1751
+ error(`Could not point the ${platformLabel(client.platform)} client at the shared schema: ${result.error}.`);
1752
+ error(`Point it at ${schemaPath} before using this repository.`);
1753
+ process.exit(1);
1754
+ }
1755
+ success(`${platformLabel(client.platform)} client reads ${relative(client.dir, schemaPath)}.`);
1756
+ }
978
1757
  }
979
1758
  //# sourceMappingURL=init.js.map