@kerf-js/cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (176) hide show
  1. package/LICENSE +16 -0
  2. package/README.md +554 -2
  3. package/bin/kerf.mjs +15 -0
  4. package/docs/async.md +50 -0
  5. package/docs/browser.md +53 -0
  6. package/docs/config.md +127 -0
  7. package/docs/core.md +30 -0
  8. package/docs/deploy.md +108 -0
  9. package/docs/design.md +106 -0
  10. package/docs/entrypoints.md +83 -0
  11. package/docs/fonts.md +118 -0
  12. package/docs/icons.md +108 -0
  13. package/docs/lists.md +25 -0
  14. package/docs/meta.md +92 -0
  15. package/docs/plugins.md +166 -0
  16. package/docs/props.md +88 -0
  17. package/docs/reactivity.md +26 -0
  18. package/docs/rules.md +39 -0
  19. package/docs/rust.md +253 -0
  20. package/docs/start-short.md +10 -0
  21. package/docs/start.md +642 -0
  22. package/docs/state.md +122 -0
  23. package/docs/style.md +82 -0
  24. package/docs/surface.md +158 -0
  25. package/docs/testing.md +81 -0
  26. package/docs/theme.md +263 -0
  27. package/docs/ui-state.md +105 -0
  28. package/docs/verify.md +61 -0
  29. package/package.json +47 -3
  30. package/src/add/config.mjs +93 -0
  31. package/src/add/errors.mjs +2 -0
  32. package/src/add/setup.mjs +88 -0
  33. package/src/add-rust.mjs +178 -0
  34. package/src/add.mjs +392 -0
  35. package/src/agents-md.mjs +240 -0
  36. package/src/alias.mjs +70 -0
  37. package/src/audit/page.mjs +313 -0
  38. package/src/audit/report.mjs +69 -0
  39. package/src/audit/utils.mjs +5 -0
  40. package/src/audit.mjs +319 -0
  41. package/src/browser/cli.mjs +53 -0
  42. package/src/browser/client.mjs +299 -0
  43. package/src/browser/commands.mjs +258 -0
  44. package/src/capture.mjs +21 -0
  45. package/src/catalog/audit.mjs +129 -0
  46. package/src/catalog/auth.mjs +40 -0
  47. package/src/catalog/compiler.mjs +337 -0
  48. package/src/catalog/contracts.mjs +18 -0
  49. package/src/catalog/database.mjs +52 -0
  50. package/src/catalog/deploy.mjs +117 -0
  51. package/src/catalog/design.mjs +159 -0
  52. package/src/catalog/forms.mjs +25 -0
  53. package/src/catalog/hydration.mjs +29 -0
  54. package/src/catalog/icons.mjs +24 -0
  55. package/src/catalog/media.mjs +163 -0
  56. package/src/catalog/metadata.mjs +116 -0
  57. package/src/catalog/plugins.mjs +228 -0
  58. package/src/catalog/realtime.mjs +195 -0
  59. package/src/catalog/rust.mjs +75 -0
  60. package/src/catalog/server-functions.mjs +100 -0
  61. package/src/catalog/state.mjs +39 -0
  62. package/src/catalog/style-groups.mjs +54 -0
  63. package/src/catalog/tests.mjs +127 -0
  64. package/src/catalog/text.mjs +200 -0
  65. package/src/catalog/ui-state.mjs +42 -0
  66. package/src/catalog.mjs +103 -0
  67. package/src/check/runtime.mjs +280 -0
  68. package/src/check.mjs +321 -0
  69. package/src/cli/authoring.mjs +213 -0
  70. package/src/cli/project.mjs +302 -0
  71. package/src/cli.mjs +340 -0
  72. package/src/config.d.ts +1 -0
  73. package/src/config.mjs +5 -0
  74. package/src/contributions.mjs +119 -0
  75. package/src/db-layer.mjs +41 -0
  76. package/src/deploy/cdn.mjs +142 -0
  77. package/src/deploy/files.mjs +266 -0
  78. package/src/deploy/fit.mjs +166 -0
  79. package/src/deploy/hosts.mjs +126 -0
  80. package/src/deploy/index/cli.mjs +20 -0
  81. package/src/deploy/index/environment.mjs +69 -0
  82. package/src/deploy/index/steps.mjs +87 -0
  83. package/src/deploy/index.mjs +387 -0
  84. package/src/deploy/needs.mjs +149 -0
  85. package/src/design-checks/accessible-names.mjs +62 -0
  86. package/src/design-checks/contrast.mjs +43 -0
  87. package/src/design-checks/csp.mjs +60 -0
  88. package/src/design-checks/files.mjs +59 -0
  89. package/src/design-checks/heading-links.mjs +61 -0
  90. package/src/design-checks/interaction.mjs +65 -0
  91. package/src/design-checks/jsx.mjs +67 -0
  92. package/src/design-checks/layout-values.mjs +68 -0
  93. package/src/design-checks/native-controls.mjs +48 -0
  94. package/src/design-checks/outline.mjs +39 -0
  95. package/src/design-checks/reporter.mjs +37 -0
  96. package/src/design-checks/rules.mjs +274 -0
  97. package/src/design-checks/values.mjs +262 -0
  98. package/src/design-checks.mjs +49 -0
  99. package/src/diag.mjs +98 -0
  100. package/src/docs.mjs +228 -0
  101. package/src/doctor.mjs +42 -0
  102. package/src/files.mjs +60 -0
  103. package/src/fix.mjs +48 -0
  104. package/src/gate/after.mjs +40 -0
  105. package/src/gate/before.mjs +54 -0
  106. package/src/gate/classify.mjs +72 -0
  107. package/src/gate/mutation.mjs +209 -0
  108. package/src/gate/resolve-cases.mjs +22 -0
  109. package/src/gate/result.mjs +63 -0
  110. package/src/gate/run.mjs +75 -0
  111. package/src/gate.mjs +178 -0
  112. package/src/index.mjs +9 -0
  113. package/src/infer/box-props.cjs +140 -0
  114. package/src/infer/core-boxes.cjs +46 -0
  115. package/src/infer/derived-writes.cjs +95 -0
  116. package/src/infer/engine/checks.cjs +193 -0
  117. package/src/infer/engine/flow.cjs +293 -0
  118. package/src/infer/engine/report.cjs +158 -0
  119. package/src/infer/engine/utils.cjs +15 -0
  120. package/src/infer/engine.cjs +265 -0
  121. package/src/infer/facts/sites.cjs +114 -0
  122. package/src/infer/facts.cjs +345 -0
  123. package/src/infer/hosts.cjs +161 -0
  124. package/src/infer/lsp.mjs +240 -0
  125. package/src/infer/session.cjs +161 -0
  126. package/src/infer/shadow.cjs +54 -0
  127. package/src/infer/worker.cjs +145 -0
  128. package/src/jsx-scan.mjs +128 -0
  129. package/src/kerf.mjs +98 -0
  130. package/src/load-config/schema.mjs +300 -0
  131. package/src/load-config.mjs +302 -0
  132. package/src/map.mjs +177 -0
  133. package/src/mcp/browser-tools.mjs +155 -0
  134. package/src/mcp.mjs +273 -0
  135. package/src/meta-table.mjs +63 -0
  136. package/src/mutate.mjs +224 -0
  137. package/src/plugin-checks.mjs +118 -0
  138. package/src/plugins.mjs +258 -0
  139. package/src/project.mjs +310 -0
  140. package/src/props-checks.mjs +64 -0
  141. package/src/props-listener.mjs +56 -0
  142. package/src/react-checks.mjs +67 -0
  143. package/src/server-state-checks.mjs +34 -0
  144. package/src/share-checks.mjs +158 -0
  145. package/src/site.mjs +46 -0
  146. package/src/slots.mjs +181 -0
  147. package/src/start/build.mjs +116 -0
  148. package/src/start/routes.mjs +38 -0
  149. package/src/start.mjs +394 -0
  150. package/src/state-checks/core-state.mjs +223 -0
  151. package/src/state-checks/modules.mjs +17 -0
  152. package/src/state-checks/scan.mjs +232 -0
  153. package/src/state-checks/server-graph.mjs +65 -0
  154. package/src/state-checks.mjs +189 -0
  155. package/src/style/find.mjs +121 -0
  156. package/src/style.mjs +327 -0
  157. package/src/surface-checks.mjs +384 -0
  158. package/src/tailwind.mjs +23 -0
  159. package/src/tasks.mjs +261 -0
  160. package/src/test-rules/context.mjs +109 -0
  161. package/src/test-rules/file-rules.mjs +279 -0
  162. package/src/test-rules/rule-helpers.mjs +244 -0
  163. package/src/test-rules/syntax.mjs +223 -0
  164. package/src/test-rules/test-rules.mjs +127 -0
  165. package/src/testdiff.mjs +219 -0
  166. package/src/tests.mjs +120 -0
  167. package/src/text-checks.mjs +332 -0
  168. package/src/tokens.mjs +33 -0
  169. package/src/trust/scan.mjs +95 -0
  170. package/src/trust.mjs +394 -0
  171. package/src/workspace.mjs +182 -0
  172. package/ts-plugin/context.js +57 -0
  173. package/ts-plugin/index.js +17 -0
  174. package/ts-plugin/mapping.js +65 -0
  175. package/ts-plugin/package.json +1 -0
  176. package/ts-plugin/proxy.js +144 -0
@@ -0,0 +1,266 @@
1
+ // The files a host needs, written by `kerf deploy init` and compared by `kerf check` (research 46 §7). Each text file
2
+ // starts with `# kerf deploy init <target>, sha <hash>`, the hash of what follows: a matching hash that differs from what
3
+ // init writes now is stale (E006), and a hash that doesn't match was edited by hand, so kerf leaves it alone.
4
+
5
+ import { createHash } from 'node:crypto'
6
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
7
+ import { dirname, join } from 'node:path'
8
+ import { host, presetFor } from './hosts.mjs'
9
+
10
+ /** The lockfile's manager: how the image and the workflow install. */
11
+ const MANAGERS = [
12
+ [
13
+ 'pnpm-lock.yaml',
14
+ {
15
+ name: 'pnpm',
16
+ install: 'corepack enable && pnpm install --frozen-lockfile',
17
+ x: 'pnpm exec',
18
+ cache: 'pnpm',
19
+ },
20
+ ],
21
+ [
22
+ 'yarn.lock',
23
+ {
24
+ name: 'yarn',
25
+ install: 'corepack enable && yarn install --immutable',
26
+ x: 'yarn',
27
+ cache: 'yarn',
28
+ },
29
+ ],
30
+ ['bun.lock', { name: 'bun', install: 'bun install --frozen-lockfile', x: 'bunx', cache: '' }],
31
+ ['package-lock.json', { name: 'npm', install: 'npm ci', x: 'npx', cache: 'npm' }],
32
+ ]
33
+ export const managerOf = (root) =>
34
+ (MANAGERS.find(([lock]) => existsSync(join(root, lock))) ?? [
35
+ null,
36
+ { name: 'npm', install: 'npm install', x: 'npx', cache: '' },
37
+ ])[1]
38
+
39
+ /** Where a server host keeps what must last: SQLite's default `file:.data/app.db` lands on it unchanged. */
40
+ export const DATA = '/app/.data'
41
+
42
+ const sha = (body) => createHash('sha256').update(body).digest('hex').slice(0, 12)
43
+ const stamp = (target, body) => `# kerf deploy init ${target}, sha ${sha(body)}\n${body}`
44
+ const STAMP = /^# kerf deploy init (\w+), sha ([0-9a-f]{12})\n/
45
+
46
+ const IMAGES = { node: 'node:26-slim', bun: 'oven/bun:1-slim', deno: 'denoland/deno:latest' }
47
+ const RUN = {
48
+ node: '["node", ".output/server/index.mjs"]',
49
+ bun: '["bun", "run", ".output/server/index.mjs"]',
50
+ deno: '["deno", "run", "-A", ".output/server/index.mjs"]',
51
+ }
52
+
53
+ /** A two-stage image: build with the lockfile's manager, run the server. A sidecar needs cargo to build and `kerf start` to run. */
54
+ function dockerfile({ runtime, manager, needs }) {
55
+ const rust = needs.sidecar || needs.native
56
+ const lines = [
57
+ `FROM ${IMAGES.node} AS build`,
58
+ 'WORKDIR /app',
59
+ ...(rust
60
+ ? [
61
+ 'RUN apt-get update && apt-get install -y --no-install-recommends curl ca-certificates build-essential && curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal',
62
+ 'ENV PATH=/root/.cargo/bin:$PATH',
63
+ ]
64
+ : []),
65
+ 'COPY . .',
66
+ `RUN ${manager.install}`,
67
+ `RUN ${manager.x} kerf build --preset ${presetFor({}, runtime)}`,
68
+ '',
69
+ `FROM ${needs.sidecar ? IMAGES.node : (IMAGES[runtime] ?? IMAGES.node)}`,
70
+ 'WORKDIR /app',
71
+ 'ENV NODE_ENV=production HOST=0.0.0.0 PORT=8080',
72
+ // `kerf start` runs each sidecar next to the server; without one the server is all there is
73
+ ...(needs.sidecar
74
+ ? [
75
+ 'COPY --from=build /app ./',
76
+ 'EXPOSE 8080',
77
+ `CMD ["${manager.x.split(' ')[0]}", ${manager.x.includes(' ') ? `"${manager.x.split(' ')[1]}", ` : ''}"kerf", "start"]`,
78
+ ]
79
+ : [
80
+ 'COPY --from=build /app/.output ./.output',
81
+ 'EXPOSE 8080',
82
+ `CMD ${RUN[runtime] ?? RUN.node}`,
83
+ ]),
84
+ ]
85
+ return `${lines.join('\n')}\n`
86
+ }
87
+
88
+ const DOCKERIGNORE =
89
+ 'node_modules\n.output\n.kerf/*\n!.kerf/plugins.lock.json\n.env\n.env.*\n.git\n.netlify\n.vercel\ntarget\n'
90
+
91
+ function flyToml({ deploy, needs }) {
92
+ const fly = deploy.fly ?? {}
93
+ const held = needs.required || needs.feed || needs.sidecar
94
+ const lines = [
95
+ `app = ${JSON.stringify(fly.app ?? 'my-app')}`,
96
+ `primary_region = ${JSON.stringify(fly.region ?? 'iad')}`,
97
+ '',
98
+ '[env]',
99
+ ' PORT = "8080"',
100
+ ...(needs.uploads && fly.volume
101
+ ? [` KERF_MEDIA_DIR = "${fly.volume.path ?? DATA}/media"`]
102
+ : []),
103
+ '',
104
+ '[http_service]',
105
+ ' internal_port = 8080',
106
+ ' force_https = true',
107
+ ' auto_stop_machines = "stop"',
108
+ ' auto_start_machines = true',
109
+ // a change feed is a listener: a stopped machine hears nothing
110
+ ` min_machines_running = ${held ? 1 : 0}`,
111
+ ...(fly.volume
112
+ ? [
113
+ '',
114
+ '[[mounts]]',
115
+ ` source = ${JSON.stringify(fly.volume.name ?? 'data')}`,
116
+ ` destination = ${JSON.stringify(fly.volume.path ?? DATA)}`,
117
+ ` initial_size = "${fly.volume.sizeGb ?? 1}gb"`,
118
+ ]
119
+ : []),
120
+ '',
121
+ '[[vm]]',
122
+ ` memory = ${JSON.stringify(fly.memory ?? '512mb')}`,
123
+ ]
124
+ return `${lines.join('\n')}\n`
125
+ }
126
+
127
+ function renderYaml({ deploy, needs }) {
128
+ const r = deploy.render ?? {}
129
+ const lines = [
130
+ 'services:',
131
+ ' - type: web',
132
+ ` name: ${r.service ?? 'my-app'}`,
133
+ ' runtime: docker',
134
+ ` plan: ${r.plan ?? (r.disk ? 'starter' : 'free')}`,
135
+ ` region: ${r.region ?? 'oregon'}`,
136
+ // the workflow deploys once `kerf check` passes, through the deploy hook
137
+ ' autoDeploy: false',
138
+ ' healthCheckPath: /',
139
+ ' envVars:',
140
+ ' - key: NODE_ENV',
141
+ ' value: production',
142
+ ...(needs.uploads && r.disk
143
+ ? [' - key: KERF_MEDIA_DIR', ` value: ${r.disk.path ?? DATA}/media`]
144
+ : []),
145
+ ...(r.disk
146
+ ? [
147
+ ' disk:',
148
+ ' name: data',
149
+ ` mountPath: ${r.disk.path ?? DATA}`,
150
+ ` sizeGB: ${r.disk.sizeGb ?? 1}`,
151
+ ]
152
+ : []),
153
+ ]
154
+ return `${lines.join('\n')}\n`
155
+ }
156
+
157
+ const netlifyToml = ({ manager }) =>
158
+ `[build]\n command = "${manager.x} kerf build --preset netlify"\n publish = "dist"\n\n[build.environment]\n NODE_VERSION = "26"\n`
159
+
160
+ const vercelJson = ({ manager }) =>
161
+ `${JSON.stringify({ $schema: 'https://openapi.vercel.sh/vercel.json', framework: null, installCommand: manager.install.replace(/^corepack enable && /, ''), buildCommand: `${manager.x} kerf build --preset vercel` }, null, 2)}\n`
162
+
163
+ const wranglerToml = ({ deploy }) =>
164
+ `name = ${JSON.stringify(deploy.cloudflare?.name ?? 'my-app')}\ncompatibility_flags = ["nodejs_compat"]\n`
165
+
166
+ /** The workflow: on push to the branch, check and deploy to production; on a pull request, a preview where the host has one. */
167
+ function workflow({ target, deploy, manager }) {
168
+ const h = host(target)
169
+ const previews = h.kind !== 'server'
170
+ const node =
171
+ manager.name === 'bun'
172
+ ? [' - uses: oven-sh/setup-bun@v2']
173
+ : [
174
+ ' - uses: actions/setup-node@v4',
175
+ ' with:',
176
+ ' node-version: 26',
177
+ ...(manager.cache ? [` cache: ${manager.cache}`] : []),
178
+ ]
179
+ const lines = [
180
+ 'name: kerf deploy',
181
+ 'on:',
182
+ ' push:',
183
+ ` branches: [${deploy.branch ?? 'main'}]`,
184
+ ...(previews ? [' pull_request:'] : []),
185
+ 'permissions:',
186
+ ' contents: read',
187
+ 'concurrency:',
188
+ // oxlint-disable-next-line no-template-curly-in-string -- a GitHub Actions expression, not a JS template
189
+ ' group: kerf-deploy-${{ github.ref }}',
190
+ ' cancel-in-progress: true',
191
+ 'jobs:',
192
+ ' deploy:',
193
+ ' runs-on: ubuntu-latest',
194
+ ' steps:',
195
+ ' - uses: actions/checkout@v4',
196
+ ...node,
197
+ ...(target === 'fly' ? [' - uses: superfly/flyctl-actions/setup-flyctl@master'] : []),
198
+ ` - run: ${manager.install}`,
199
+ ` - run: ${manager.x} kerf check`,
200
+ // oxlint-disable-next-line no-template-curly-in-string -- a GitHub Actions expression, not a JS template
201
+ ` - run: ${manager.x} kerf deploy --yes${previews ? " ${{ github.event_name == 'push' && '--prod' || '' }}" : ' --prod'}`,
202
+ ' env:',
203
+ ...h.env.map((k) => ` ${k}: \${{ secrets.${k} }}`),
204
+ ]
205
+ return `${lines.join('\n')}\n`
206
+ }
207
+
208
+ const WORKFLOW = '.github/workflows/kerf-deploy.yml'
209
+
210
+ /**
211
+ * What `kerf deploy init <target>` writes, as `{ path, text }`, every text one stamped.
212
+ * @param {{ target: string, deploy: any, needs: any, runtime: string, manager: any }} ctx
213
+ */
214
+ export function filesFor(ctx) {
215
+ const { target } = ctx
216
+ const out = []
217
+ const text = (path, body) => out.push({ path, text: stamp(target, body) })
218
+ if (target === 'netlify') text('netlify.toml', netlifyToml(ctx))
219
+ if (target === 'vercel') out.push({ path: 'vercel.json', text: vercelJson(ctx), json: true })
220
+ if (target === 'cloudflare') text('wrangler.toml', wranglerToml(ctx))
221
+ if (target === 'fly') text('fly.toml', flyToml(ctx))
222
+ if (target === 'render') text('render.yaml', renderYaml(ctx))
223
+ if (target === 'fly' || target === 'render') {
224
+ text('Dockerfile', dockerfile(ctx))
225
+ out.push({ path: '.dockerignore', text: DOCKERIGNORE, plain: true })
226
+ }
227
+ if ((ctx.deploy.ci ?? 'github') === 'github') text(WORKFLOW, workflow(ctx))
228
+ return out
229
+ }
230
+
231
+ /**
232
+ * Each generated file's state: `missing`, `current`, `stale` (kerf's, from an older config), `edited` (by hand: left
233
+ * alone), or `foreign` (no stamp: not kerf's).
234
+ */
235
+ export function fileStates(root, files) {
236
+ return files.map((f) => {
237
+ const abs = join(root, f.path)
238
+ if (!existsSync(abs)) return { ...f, state: 'missing' }
239
+ const now = readFileSync(abs, 'utf8')
240
+ if (now === f.text) return { ...f, state: 'current' }
241
+ if (f.json)
242
+ return {
243
+ ...f,
244
+ state: JSON.parse(now || '{}').buildCommand?.includes('kerf build --preset vercel')
245
+ ? 'edited'
246
+ : 'stale',
247
+ }
248
+ if (f.plain) return { ...f, state: 'edited' }
249
+ const m = STAMP.exec(now)
250
+ if (!m) return { ...f, state: 'foreign' }
251
+ return { ...f, state: sha(now.slice(m[0].length)) === m[2] ? 'stale' : 'edited' }
252
+ })
253
+ }
254
+
255
+ /** Write what's missing or stale. Never a file kerf didn't write, or one edited since. */
256
+ export function writeFiles(root, states, { force = false } = {}) {
257
+ const written = []
258
+ for (const f of states) {
259
+ if (f.state === 'current' || (!force && (f.state === 'edited' || f.state === 'foreign')))
260
+ continue
261
+ mkdirSync(dirname(join(root, f.path)), { recursive: true })
262
+ writeFileSync(join(root, f.path), f.text)
263
+ written.push(f.path)
264
+ }
265
+ return written
266
+ }
@@ -0,0 +1,166 @@
1
+ // Which hosts can run an app, and which one to suggest (research 46 §4). A finding is a need the host can't meet: an
2
+ // error when nothing on that host fixes it, a warning when it runs degraded or needs a paid add-on.
3
+
4
+ import { HOSTS } from './hosts.mjs'
5
+
6
+ const SERVERS = "`deploy: { target: 'fly' }` or `'render'`: a server that stays up"
7
+ const SPLIT =
8
+ 'or keep the pages here and run realtime on a small server (the split, `kerf docs deploy`)'
9
+
10
+ /** What a disk need asks of a host, with the config that gives it one. */
11
+ function disk(h, need, cfg = {}, assume) {
12
+ if (h.disk === 'none')
13
+ return {
14
+ severity: 'error',
15
+ fix:
16
+ need.what === 'a SQLite file'
17
+ ? `${SERVERS}, with a volume or disk, or a hosted database here (Postgres on Neon or Supabase, Turso for SQLite)`
18
+ : `${SERVERS}, with a volume or disk: this kerf has no object store for uploads yet (research 46 §9)`,
19
+ }
20
+ const has = h.id === 'fly' ? cfg.fly?.volume : cfg.render?.disk
21
+ if (has) return
22
+ const add =
23
+ h.id === 'fly'
24
+ ? "`deploy.fly.volume: { name: 'data', sizeGb: 1 }` (billed)"
25
+ : '`deploy.render.disk: { sizeGb: 1 }` (a paid plan)'
26
+ return {
27
+ severity: assume ? 'warning' : 'error',
28
+ fix: `add ${add}: it mounts at \`/app/.data\`, where SQLite's default \`file:.data/app.db\` already is, and uploads go to \`.data/media\``,
29
+ }
30
+ }
31
+
32
+ /**
33
+ * @param {ReturnType<import('./needs.mjs').needsOf>} needs
34
+ * @param {import('./hosts.mjs').Host} h
35
+ * @param {{ deploy?: any, assume?: boolean, local?: boolean }} [options] `assume`: a paid add-on is a warning (the hosts list,
36
+ * before a target is chosen). `local`: the build is deployed from this machine.
37
+ * @returns {{ host: string, fits: boolean, findings: { code: string, severity: string, file: string, why: string, fix: string }[] }}
38
+ */
39
+ export function fit(needs, h, { deploy = {}, assume = false, local = false } = {}) {
40
+ const findings = []
41
+ const add = (code, severity, need, why, fix) =>
42
+ findings.push({ code, severity, file: need.file, why, fix })
43
+ if (needs.sockets && !h.sockets)
44
+ add(
45
+ 'E001',
46
+ 'error',
47
+ needs.sockets,
48
+ `${needs.sockets.what} holds a WebSocket, and ${h.name} ends each process with its request: the page would load and never connect (R024)`,
49
+ `${SERVERS}, or \`'cloudflare'\` (Durable Objects), ${SPLIT}`,
50
+ )
51
+ if (needs.required && !h.held)
52
+ add(
53
+ 'E002',
54
+ 'error',
55
+ needs.required,
56
+ `${needs.required.what} needs a change feed that stays connected, and ${h.name} keeps no process between requests (R013)`,
57
+ `${SERVERS}, run \`kerf db listen\` on one with \`listener: 'external'\`, or drop \`required\``,
58
+ )
59
+ if (needs.sidecar && !h.sidecars)
60
+ add(
61
+ 'E002',
62
+ 'error',
63
+ needs.sidecar,
64
+ `${needs.sidecar.what} is a second process next to the server, and ${h.name} runs only the server`,
65
+ `${SERVERS} (the image runs both), or deploy the sidecar on its own and set \`rust.services.<name>.external: true\` with its \`KERF_RUST_<NAME>_URL\``,
66
+ )
67
+ if (needs.native && h.kind === 'workers')
68
+ add(
69
+ 'R104',
70
+ 'error',
71
+ needs.native,
72
+ `${needs.native.what} loads an addon or a \`.wasm\` file, and ${h.name} has no file system`,
73
+ 'use `remote()`, or a server host',
74
+ )
75
+ for (const key of ['sqlite', 'uploads']) {
76
+ const need = needs[key]
77
+ const d = need && disk(h, need, deploy, assume)
78
+ if (d)
79
+ add(
80
+ 'E003',
81
+ d.severity,
82
+ need,
83
+ `${need.what} is kept on local disk, and ${h.disk === 'none' ? `${h.name}'s disk is gone after each request` : `${h.name} wipes it on each deploy without one`}`,
84
+ d.fix,
85
+ )
86
+ }
87
+ if (needs.feed && !h.held)
88
+ add(
89
+ 'R014',
90
+ 'warning',
91
+ needs.feed,
92
+ `${needs.feed.what} needs a process that stays up: on ${h.name}, writes from outside the app won't reach \`.live()\``,
93
+ `${SERVERS}, or \`kerf db listen\` on one with \`listener: 'external'\``,
94
+ )
95
+ if (needs.memoryBus && h.many)
96
+ add(
97
+ 'E009',
98
+ 'warning',
99
+ needs.memoryBus,
100
+ `${needs.memoryBus.what} reaches the clients of one instance, and ${h.name} runs many`,
101
+ h.id === 'cloudflare'
102
+ ? '`durableObjectBus` in `src/realtime.server.ts`'
103
+ : '`kerf add redis` or `kerf add nats`, or `postgresBus({ url })` in `src/realtime.server.ts`',
104
+ )
105
+ if (needs.addons && local && h.prebuilt && process.platform !== 'linux')
106
+ add(
107
+ 'E004',
108
+ 'warning',
109
+ needs.addons,
110
+ `${needs.addons.what} has a compiled addon, built here for ${process.platform}, and ${h.name} runs Linux`,
111
+ "deploy from CI (`deploy.ci: 'github'` builds on Linux), or drop the addon",
112
+ )
113
+ return { host: h.id, fits: !findings.some((f) => f.severity === 'error'), findings }
114
+ }
115
+
116
+ /** Every host, fitted, and the one to suggest (research 46 §4), with why. */
117
+ export function hostsReport(needs, { deploy = {} } = {}) {
118
+ const fits = HOSTS.map((h) => ({
119
+ ...fit(needs, h, { deploy, assume: true }),
120
+ name: h.name,
121
+ kind: h.kind,
122
+ cost: h.cost,
123
+ pricing: h.pricing,
124
+ deploys: h.deploys,
125
+ }))
126
+ return { fits, suggestion: suggest(needs, fits) }
127
+ }
128
+
129
+ /** @returns {{ host: string, why: string, alternative?: string }} */
130
+ export function suggest(needs, fits = HOSTS.map((h) => fit(needs, h, { assume: true }))) {
131
+ const ok = (id) => fits.find((f) => f.host === id)?.fits
132
+ const clean = (id) => ok(id) && !fits.find((f) => f.host === id).findings.length
133
+ const held = needs.required || needs.sidecar || needs.feed
134
+ const kept = needs.sqlite || needs.uploads
135
+ if (!needs.sockets && !held && !kept) {
136
+ if (clean('netlify'))
137
+ return {
138
+ host: 'netlify',
139
+ why: 'nothing here needs a server that stays up: a CDN with functions behind it is the cheapest and fastest host',
140
+ alternative: 'vercel',
141
+ }
142
+ if (ok('netlify'))
143
+ return {
144
+ host: 'netlify',
145
+ why: 'nothing here needs a server that stays up, once the warnings are fixed',
146
+ alternative: 'vercel',
147
+ }
148
+ }
149
+ if (needs.sockets && !held && !kept && !needs.native && clean('cloudflare'))
150
+ return {
151
+ host: 'cloudflare',
152
+ why: 'channels need a socket, and a Durable Object holds one for each room without a server to run',
153
+ alternative: 'fly',
154
+ }
155
+ if (kept)
156
+ return {
157
+ host: 'fly',
158
+ why: `${kept.what} needs a disk that lasts: a Fly volume is per machine and cheap`,
159
+ alternative: 'render',
160
+ }
161
+ return {
162
+ host: 'fly',
163
+ why: `${(needs.sockets ?? held).what} needs a server that stays up, and Fly runs the app as it is. Render's free instance does too, but sleeps after 15 idle minutes`,
164
+ alternative: 'render',
165
+ }
166
+ }
@@ -0,0 +1,126 @@
1
+ // The hosts `kerf deploy` knows (research 46 §3): what each can run, its preset, what its CLI reads, and a cost hint.
2
+ // The fit (fit.mjs) and the generated files (files.mjs) both read this table, so they can't disagree about a host.
3
+
4
+ /**
5
+ * @typedef {{
6
+ * id: string, name: string, kind: 'functions' | 'workers' | 'server',
7
+ * preset?: string, sockets: boolean, held: boolean, disk: 'none' | 'volume' | 'paid-disk', sidecars: boolean,
8
+ * many: boolean, prebuilt: boolean, env: string[], cost: string, pricing: string, docs: string, deploys: boolean,
9
+ * }} Host
10
+ * `preset`: the Nitro preset, or none for the runtime's server preset. `prebuilt`: what is built here is what ships, so a
11
+ * native addon from this machine goes too. `deploys`: `kerf deploy` drives it (AWS is a fit only, research 46 §11).
12
+ */
13
+
14
+ /** @type {Host[]} */
15
+ export const HOSTS = [
16
+ {
17
+ id: 'netlify',
18
+ name: 'Netlify',
19
+ kind: 'functions',
20
+ preset: 'netlify',
21
+ sockets: false,
22
+ held: false,
23
+ disk: 'none',
24
+ sidecars: false,
25
+ many: true,
26
+ prebuilt: true,
27
+ env: ['NETLIFY_AUTH_TOKEN', 'NETLIFY_SITE_ID'],
28
+ deploys: true,
29
+ cost: 'free tier; usage past it is billed in credits',
30
+ pricing: 'https://www.netlify.com/pricing/',
31
+ docs: 'https://docs.netlify.com/cli/get-started/',
32
+ },
33
+ {
34
+ id: 'vercel',
35
+ name: 'Vercel',
36
+ kind: 'functions',
37
+ preset: 'vercel',
38
+ sockets: false,
39
+ held: false,
40
+ disk: 'none',
41
+ sidecars: false,
42
+ many: true,
43
+ prebuilt: true,
44
+ env: ['VERCEL_TOKEN', 'VERCEL_ORG_ID', 'VERCEL_PROJECT_ID'],
45
+ deploys: true,
46
+ cost: 'Hobby is free for non-commercial use; Pro is per seat',
47
+ pricing: 'https://vercel.com/pricing',
48
+ docs: 'https://vercel.com/docs/cli',
49
+ },
50
+ {
51
+ id: 'cloudflare',
52
+ name: 'Cloudflare Workers',
53
+ kind: 'workers',
54
+ preset: 'cloudflare_durable',
55
+ sockets: true,
56
+ held: false,
57
+ disk: 'none',
58
+ sidecars: false,
59
+ many: true,
60
+ prebuilt: true,
61
+ env: ['CLOUDFLARE_API_TOKEN', 'CLOUDFLARE_ACCOUNT_ID'],
62
+ deploys: true,
63
+ cost: 'free tier includes Workers and SQLite-backed Durable Objects',
64
+ pricing: 'https://developers.cloudflare.com/workers/platform/pricing/',
65
+ docs: 'https://developers.cloudflare.com/workers/wrangler/',
66
+ },
67
+ {
68
+ id: 'fly',
69
+ name: 'Fly.io',
70
+ kind: 'server',
71
+ sockets: true,
72
+ held: true,
73
+ disk: 'volume',
74
+ sidecars: true,
75
+ many: false,
76
+ prebuilt: false,
77
+ env: ['FLY_API_TOKEN'],
78
+ deploys: true,
79
+ cost: 'pay as you go, no free tier for new organizations',
80
+ pricing: 'https://fly.io/docs/about/pricing/',
81
+ docs: 'https://fly.io/docs/flyctl/',
82
+ },
83
+ {
84
+ id: 'render',
85
+ name: 'Render',
86
+ kind: 'server',
87
+ sockets: true,
88
+ held: true,
89
+ disk: 'paid-disk',
90
+ sidecars: true,
91
+ many: false,
92
+ prebuilt: false,
93
+ env: ['RENDER_DEPLOY_HOOK_URL'],
94
+ deploys: true,
95
+ cost: 'free instance sleeps after 15 idle minutes and has no disk; paid plans add a disk',
96
+ pricing: 'https://render.com/pricing',
97
+ docs: 'https://render.com/docs/blueprint-spec',
98
+ },
99
+ {
100
+ id: 'aws',
101
+ name: 'AWS Lambda',
102
+ kind: 'functions',
103
+ preset: 'aws_lambda',
104
+ sockets: false,
105
+ held: false,
106
+ disk: 'none',
107
+ sidecars: false,
108
+ many: true,
109
+ prebuilt: true,
110
+ env: [],
111
+ deploys: false,
112
+ cost: 'Lambda has a free tier; a server would go on App Runner, billed per running instance',
113
+ pricing: 'https://aws.amazon.com/pricing/',
114
+ docs: 'https://nitro.build/deploy/providers/aws',
115
+ },
116
+ ]
117
+
118
+ export const TARGETS = HOSTS.filter((h) => h.deploys).map((h) => h.id)
119
+
120
+ export const host = (id) => HOSTS.find((h) => h.id === id)
121
+
122
+ /** `runtime` in the config as the server preset a container runs. */
123
+ const SERVER_PRESETS = { node: 'node', bun: 'bun', deno: 'deno_server' }
124
+
125
+ /** The preset a build for this host uses. */
126
+ export const presetFor = (h, runtime = 'node') => h.preset ?? SERVER_PRESETS[runtime] ?? 'node'
@@ -0,0 +1,20 @@
1
+ import { spawnSync } from 'node:child_process'
2
+
3
+ const refused = (message) => Object.assign(new Error(message), { code: 'E_REFUSED' })
4
+
5
+ /** The host's CLI: on PATH, else through npx for the ones on npm. */
6
+ export function cliFor(
7
+ name,
8
+ {
9
+ which = (cmd) =>
10
+ spawnSync(process.platform === 'win32' ? 'where' : 'which', [cmd], { encoding: 'utf8' })
11
+ .status === 0,
12
+ } = {},
13
+ ) {
14
+ const npm = { netlify: 'netlify-cli', vercel: 'vercel', wrangler: 'wrangler' }
15
+ for (const cmd of name === 'flyctl' ? ['flyctl', 'fly'] : [name]) if (which(cmd)) return [cmd]
16
+ if (npm[name]) return ['npx', '--yes', npm[name]]
17
+ throw refused(
18
+ `\`${name}\` isn't installed: ${name === 'flyctl' ? 'https://fly.io/docs/flyctl/install/' : `npm install -g ${npm[name] ?? name}`}`,
19
+ )
20
+ }
@@ -0,0 +1,69 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ /** A variable a step reads, and whether its absence stops the deploy (E007). */
5
+ export function missingEnv(root, target, config, env) {
6
+ const ci = !!env.CI
7
+ const linked = {
8
+ netlify: existsSync(join(root, '.netlify/state.json')) || !!config.deploy?.netlify?.site,
9
+ vercel: existsSync(join(root, '.vercel/project.json')),
10
+ }
11
+ // a token: the CLI's own login stands in, except in CI. An id: needed unless the project is linked.
12
+ const token = (k, how) => [k, ci ? 'error' : 'warning', how, ": the CLI's own login is used"]
13
+ const id = (k, known, how) => [k, known ? null : 'error', how, '']
14
+ const need = {
15
+ netlify: [
16
+ token(
17
+ 'NETLIFY_AUTH_TOKEN',
18
+ '`netlify login` here, or a personal access token from User settings → Applications',
19
+ ),
20
+ id(
21
+ 'NETLIFY_SITE_ID',
22
+ linked.netlify,
23
+ '`netlify link`, `deploy.netlify.site`, or the site id from Site configuration',
24
+ ),
25
+ ],
26
+ vercel: [
27
+ token('VERCEL_TOKEN', '`vercel login` here, or a token from Account Settings → Tokens'),
28
+ id('VERCEL_ORG_ID', linked.vercel, '`vercel link` writes it to .vercel/project.json'),
29
+ id('VERCEL_PROJECT_ID', linked.vercel, '`vercel link` writes it to .vercel/project.json'),
30
+ ],
31
+ cloudflare: [
32
+ token('CLOUDFLARE_API_TOKEN', '`wrangler login` here, or a token with Workers Scripts: Edit'),
33
+ id('CLOUDFLARE_ACCOUNT_ID', !ci, 'the account id on the Workers overview page'),
34
+ ],
35
+ fly: [token('FLY_API_TOKEN', '`flyctl auth login` here, or `flyctl tokens create deploy`')],
36
+ render: [id('RENDER_DEPLOY_HOOK_URL', false, "the service's Settings → Deploy Hook")],
37
+ }[target]
38
+ return need
39
+ .filter(([k, severity]) => severity && !env[k])
40
+ .map(([k, severity, how, local]) => ({
41
+ code: 'E007',
42
+ severity,
43
+ file: 'kerf.config.ts',
44
+ why: `\`${k}\` is unset${severity === 'warning' ? local : ''}`,
45
+ fix: `${how}. Set it in the environment (never a file)`,
46
+ }))
47
+ }
48
+
49
+ /** The URL a host's CLI printed. */
50
+ export function urlFrom(step, stdout) {
51
+ if (step.url === 'json') {
52
+ try {
53
+ const j = JSON.parse(stdout.slice(stdout.indexOf('{')))
54
+ return j.url ?? j.deploy_url
55
+ } catch {
56
+ return
57
+ }
58
+ }
59
+ if (step.url === 'last-line')
60
+ return stdout
61
+ .trim()
62
+ .split('\n')
63
+ .reverse()
64
+ .find((l) => l.trim().startsWith('https://'))
65
+ ?.trim()
66
+ if (step.url === 'workers') return /https:\/\/[\w.-]+\.workers\.dev/.exec(stdout)?.[0]
67
+ if (step.url === 'fly') return /https:\/\/[\w.-]+\.fly\.dev/.exec(stdout)?.[0]
68
+ return step.url
69
+ }