toiljs 0.0.116 → 0.0.117

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 (325) hide show
  1. package/CHANGELOG.md +5 -0
  2. package/README.md +16 -7
  3. package/build/backend/.tsbuildinfo +1 -1
  4. package/build/cli/.tsbuildinfo +1 -1
  5. package/build/cli/index.js +2375 -258
  6. package/build/client/.tsbuildinfo +1 -1
  7. package/build/client/dev/devtools.js +1 -1
  8. package/build/client/dev/error-overlay.js +1 -1
  9. package/build/client/routing/mount.js +1 -1
  10. package/build/compiler/.tsbuildinfo +1 -1
  11. package/build/compiler/auth-emails.js +7 -3
  12. package/build/compiler/emails.js +1 -1
  13. package/build/compiler/index.d.ts +1 -0
  14. package/build/compiler/index.js +25 -4
  15. package/build/compiler/pages.js +2 -3
  16. package/build/compiler/prerender.d.ts +3 -8
  17. package/build/compiler/prerender.js +88 -127
  18. package/build/compiler/ssg.js +3 -4
  19. package/build/compiler/template-build.js +3 -4
  20. package/build/compiler/toil-docs.generated.js +6 -5
  21. package/build/compiler/vite.js +3 -6
  22. package/build/devserver/.tsbuildinfo +1 -1
  23. package/build/devserver/db/database.js +7 -3
  24. package/build/devserver/db/types.js +1 -1
  25. package/build/devserver/production.js +4 -3
  26. package/build/devserver/runtime/crypto.d.ts +1 -1
  27. package/build/io/.tsbuildinfo +1 -1
  28. package/build/logger/.tsbuildinfo +1 -1
  29. package/build/shared/.tsbuildinfo +1 -1
  30. package/examples/basic/client/routes/analytics.tsx +7 -5
  31. package/examples/basic/server/tsconfig.json +1 -3
  32. package/package.json +45 -44
  33. package/presets/no-uint8array-tostring.js +120 -153
  34. package/presets/oxlint.d.ts +5 -0
  35. package/presets/oxlint.js +224 -0
  36. package/server/runtime/tsconfig.json +1 -3
  37. package/tsconfig.json +2 -11
  38. package/.github/ISSUE_TEMPLATE/bug_report.md +0 -38
  39. package/.github/ISSUE_TEMPLATE/bug_report.yml +0 -90
  40. package/.github/ISSUE_TEMPLATE/config.yml +0 -8
  41. package/.github/ISSUE_TEMPLATE/feature_request.md +0 -20
  42. package/.github/PULL_REQUEST_TEMPLATE.md +0 -43
  43. package/.github/changelog-config.json +0 -45
  44. package/.github/dependabot.yml +0 -27
  45. package/.github/workflows/ci.yml +0 -222
  46. package/.vscode/settings.json +0 -10
  47. package/docs/README.md +0 -107
  48. package/docs/auth/README.md +0 -104
  49. package/docs/auth/configuration.md +0 -105
  50. package/docs/auth/emails.md +0 -92
  51. package/docs/auth/extending.md +0 -202
  52. package/docs/auth/how-it-works.md +0 -138
  53. package/docs/auth/usage.md +0 -188
  54. package/docs/backend/README.md +0 -143
  55. package/docs/backend/data.md +0 -351
  56. package/docs/backend/rest.md +0 -402
  57. package/docs/backend/rpc.md +0 -226
  58. package/docs/background/README.md +0 -114
  59. package/docs/background/daemons.md +0 -276
  60. package/docs/background/derive.md +0 -179
  61. package/docs/cli/README.md +0 -379
  62. package/docs/concepts/ai-guide.md +0 -132
  63. package/docs/concepts/config.md +0 -416
  64. package/docs/concepts/decorators.md +0 -127
  65. package/docs/concepts/security.md +0 -108
  66. package/docs/concepts/tiers.md +0 -166
  67. package/docs/concepts/types.md +0 -216
  68. package/docs/database/README.md +0 -143
  69. package/docs/database/capacity.md +0 -350
  70. package/docs/database/counters.md +0 -174
  71. package/docs/database/documents.md +0 -277
  72. package/docs/database/events.md +0 -307
  73. package/docs/database/membership.md +0 -246
  74. package/docs/database/setup.md +0 -155
  75. package/docs/database/unique.md +0 -216
  76. package/docs/database/views.md +0 -246
  77. package/docs/frontend/README.md +0 -104
  78. package/docs/frontend/components.md +0 -286
  79. package/docs/frontend/data-fetching.md +0 -260
  80. package/docs/frontend/images.md +0 -148
  81. package/docs/frontend/metadata.md +0 -344
  82. package/docs/frontend/navigation.md +0 -296
  83. package/docs/frontend/rendering.md +0 -236
  84. package/docs/frontend/routing.md +0 -346
  85. package/docs/frontend/scripts.md +0 -118
  86. package/docs/frontend/search.md +0 -191
  87. package/docs/frontend/styling.md +0 -147
  88. package/docs/frontend/toil-global.md +0 -216
  89. package/docs/getting-started/README.md +0 -81
  90. package/docs/getting-started/create-project.md +0 -131
  91. package/docs/getting-started/deploy.md +0 -101
  92. package/docs/getting-started/first-app.md +0 -215
  93. package/docs/getting-started/installation.md +0 -124
  94. package/docs/getting-started/migrating.md +0 -125
  95. package/docs/getting-started/project-structure.md +0 -163
  96. package/docs/introduction/README.md +0 -66
  97. package/docs/introduction/design-principles.md +0 -81
  98. package/docs/introduction/distributed.md +0 -91
  99. package/docs/introduction/how-it-works.md +0 -121
  100. package/docs/introduction/hyperscale.md +0 -70
  101. package/docs/introduction/modern-stack.md +0 -85
  102. package/docs/introduction/vs-other-frameworks.md +0 -64
  103. package/docs/introduction/why-toil.md +0 -99
  104. package/docs/llms.txt +0 -95
  105. package/docs/realtime/README.md +0 -102
  106. package/docs/realtime/channels.md +0 -211
  107. package/docs/realtime/streams.md +0 -369
  108. package/docs/services/README.md +0 -60
  109. package/docs/services/analytics.md +0 -279
  110. package/docs/services/caching.md +0 -175
  111. package/docs/services/cookies.md +0 -235
  112. package/docs/services/crypto.md +0 -209
  113. package/docs/services/email.md +0 -289
  114. package/docs/services/environment.md +0 -141
  115. package/docs/services/ratelimit.md +0 -174
  116. package/docs/services/time.md +0 -85
  117. package/eslint.config.js +0 -57
  118. package/examples/basic/client/routes/docs/[...slug].tsx +0 -12
  119. package/presets/eslint.js +0 -88
  120. package/src/backend/index.ts +0 -204
  121. package/src/cli/configure.ts +0 -363
  122. package/src/cli/create.ts +0 -924
  123. package/src/cli/db.ts +0 -158
  124. package/src/cli/diagnostics.ts +0 -665
  125. package/src/cli/doctor.ts +0 -982
  126. package/src/cli/features.ts +0 -170
  127. package/src/cli/index.ts +0 -326
  128. package/src/cli/notify.ts +0 -120
  129. package/src/cli/proc.ts +0 -56
  130. package/src/cli/ui.ts +0 -169
  131. package/src/cli/update.ts +0 -248
  132. package/src/cli/updates.ts +0 -92
  133. package/src/cli/validate.ts +0 -31
  134. package/src/cli/version-check.ts +0 -125
  135. package/src/client/auth.ts +0 -869
  136. package/src/client/channel/channel.ts +0 -146
  137. package/src/client/components/Form.tsx +0 -65
  138. package/src/client/components/Image.tsx +0 -160
  139. package/src/client/components/Script.tsx +0 -113
  140. package/src/client/components/Slot.tsx +0 -21
  141. package/src/client/dev/devtools.tsx +0 -1089
  142. package/src/client/dev/error-overlay.tsx +0 -225
  143. package/src/client/errors.ts +0 -11
  144. package/src/client/head/head.ts +0 -182
  145. package/src/client/head/metadata.ts +0 -110
  146. package/src/client/index.ts +0 -130
  147. package/src/client/navigation/Link.tsx +0 -108
  148. package/src/client/navigation/NavLink.tsx +0 -86
  149. package/src/client/navigation/navigation.ts +0 -235
  150. package/src/client/navigation/prefetch.ts +0 -169
  151. package/src/client/navigation/scroll.ts +0 -53
  152. package/src/client/routing/Router.tsx +0 -216
  153. package/src/client/routing/action.ts +0 -122
  154. package/src/client/routing/error-boundary.tsx +0 -43
  155. package/src/client/routing/hooks.ts +0 -140
  156. package/src/client/routing/lazy.ts +0 -77
  157. package/src/client/routing/loader.ts +0 -381
  158. package/src/client/routing/match.ts +0 -47
  159. package/src/client/routing/mount.tsx +0 -90
  160. package/src/client/routing/params-context.ts +0 -10
  161. package/src/client/routing/slot-context.ts +0 -7
  162. package/src/client/rpc.ts +0 -97
  163. package/src/client/search/search.ts +0 -189
  164. package/src/client/search/use-page-search.ts +0 -73
  165. package/src/client/ssr/markers.tsx +0 -172
  166. package/src/client/stream/client.ts +0 -237
  167. package/src/client/types.ts +0 -73
  168. package/src/compiler/auth-emails.ts +0 -312
  169. package/src/compiler/config.ts +0 -369
  170. package/src/compiler/docs.ts +0 -127
  171. package/src/compiler/email-preview.ts +0 -314
  172. package/src/compiler/emails.ts +0 -404
  173. package/src/compiler/fonts.ts +0 -89
  174. package/src/compiler/generate.ts +0 -471
  175. package/src/compiler/image-blur.ts +0 -42
  176. package/src/compiler/image-report.ts +0 -88
  177. package/src/compiler/index.ts +0 -1362
  178. package/src/compiler/pages.ts +0 -49
  179. package/src/compiler/plugin.ts +0 -391
  180. package/src/compiler/prerender.ts +0 -263
  181. package/src/compiler/routes.ts +0 -170
  182. package/src/compiler/seo.ts +0 -415
  183. package/src/compiler/sri.ts +0 -144
  184. package/src/compiler/ssg.ts +0 -177
  185. package/src/compiler/ssr-codegen.ts +0 -85
  186. package/src/compiler/template-build.ts +0 -676
  187. package/src/compiler/template.ts +0 -262
  188. package/src/compiler/toil-docs.generated.ts +0 -77
  189. package/src/compiler/vite.ts +0 -245
  190. package/src/devserver/analytics/index.ts +0 -317
  191. package/src/devserver/config/dotenv.ts +0 -102
  192. package/src/devserver/config/env.ts +0 -30
  193. package/src/devserver/config/ratelimit.ts +0 -123
  194. package/src/devserver/daemon/catalog.ts +0 -120
  195. package/src/devserver/daemon/cron.ts +0 -87
  196. package/src/devserver/daemon/host.ts +0 -134
  197. package/src/devserver/daemon/index.ts +0 -369
  198. package/src/devserver/daemon/runtime.ts +0 -48
  199. package/src/devserver/db/catalog.ts +0 -109
  200. package/src/devserver/db/database.ts +0 -1834
  201. package/src/devserver/db/derives.ts +0 -121
  202. package/src/devserver/db/index.ts +0 -20
  203. package/src/devserver/db/routeKinds.ts +0 -191
  204. package/src/devserver/db/types.ts +0 -168
  205. package/src/devserver/email/caps.ts +0 -0
  206. package/src/devserver/email/config.ts +0 -141
  207. package/src/devserver/email/console.ts +0 -348
  208. package/src/devserver/email/index.ts +0 -155
  209. package/src/devserver/email/providers.ts +0 -131
  210. package/src/devserver/email/status.ts +0 -23
  211. package/src/devserver/email/validate.ts +0 -37
  212. package/src/devserver/email/wire.ts +0 -55
  213. package/src/devserver/http/cache.ts +0 -0
  214. package/src/devserver/http/envelope.ts +0 -157
  215. package/src/devserver/http/proxy.ts +0 -172
  216. package/src/devserver/http/runtime.ts +0 -387
  217. package/src/devserver/index.ts +0 -43
  218. package/src/devserver/production-ipc.ts +0 -63
  219. package/src/devserver/production-worker.ts +0 -83
  220. package/src/devserver/production.ts +0 -718
  221. package/src/devserver/runtime/crypto.ts +0 -587
  222. package/src/devserver/runtime/host.ts +0 -427
  223. package/src/devserver/runtime/module.ts +0 -442
  224. package/src/devserver/server.ts +0 -251
  225. package/src/devserver/ssr.ts +0 -208
  226. package/src/devserver/stream/catalog.ts +0 -106
  227. package/src/devserver/stream/host.ts +0 -42
  228. package/src/devserver/stream/index.ts +0 -301
  229. package/src/devserver/stream/manager.ts +0 -167
  230. package/src/devserver/stream/router.ts +0 -101
  231. package/src/devserver/stream/wire.ts +0 -58
  232. package/src/devserver/stream/ws.ts +0 -78
  233. package/src/devserver/wasm/sections.ts +0 -59
  234. package/src/devserver/wasm/surface.ts +0 -115
  235. package/src/io/FastMap.ts +0 -151
  236. package/src/io/FastSet.ts +0 -113
  237. package/src/io/codec.ts +0 -362
  238. package/src/io/index.ts +0 -10
  239. package/src/io/lengths.ts +0 -14
  240. package/src/io/types.ts +0 -19
  241. package/src/logger/index.ts +0 -22
  242. package/src/shared/index.ts +0 -46
  243. package/test/analytics-dev.test.ts +0 -113
  244. package/test/assembly/aspect-shim.ts +0 -33
  245. package/test/assembly/cookie.spec.ts +0 -303
  246. package/test/assembly/example.spec.ts +0 -22
  247. package/test/assembly/ssr.spec.ts +0 -95
  248. package/test/assembly.test.ts +0 -59
  249. package/test/auth-emails.test.ts +0 -118
  250. package/test/built-ssr.test.ts +0 -148
  251. package/test/channel.test.ts +0 -21
  252. package/test/config-host-port.test.ts +0 -59
  253. package/test/configure.test.ts +0 -94
  254. package/test/daemon-build.test.ts +0 -278
  255. package/test/daemon-catalog.test.ts +0 -349
  256. package/test/daemon-emulation.test.ts +0 -256
  257. package/test/db.test.ts +0 -0
  258. package/test/devserver-database.test.ts +0 -1102
  259. package/test/devserver-email.test.ts +0 -306
  260. package/test/devserver-pqauth.test.ts +0 -93
  261. package/test/devserver-secrets.test.ts +0 -63
  262. package/test/devserver.test.ts +0 -259
  263. package/test/doctor.test.ts +0 -298
  264. package/test/dom/Image.test.tsx +0 -144
  265. package/test/dom/Link.test.tsx +0 -67
  266. package/test/dom/NavLink.test.tsx +0 -37
  267. package/test/dom/Script.test.tsx +0 -48
  268. package/test/dom/action.test.tsx +0 -146
  269. package/test/dom/error-overlay.test.tsx +0 -44
  270. package/test/dom/loader.test.tsx +0 -121
  271. package/test/dom/navigation.test.ts +0 -59
  272. package/test/dom/revalidate.test.tsx +0 -38
  273. package/test/dom/route-head.test.tsx +0 -56
  274. package/test/dom/router-loading.test.tsx +0 -44
  275. package/test/dom/scroll.test.ts +0 -56
  276. package/test/dom/slot.test.tsx +0 -131
  277. package/test/dom/use-metadata.test.tsx +0 -58
  278. package/test/dom/view-transitions.test.tsx +0 -53
  279. package/test/dynamic-routing.test.ts +0 -132
  280. package/test/email-console.test.ts +0 -86
  281. package/test/email-preview.test.ts +0 -73
  282. package/test/emails.test.ts +0 -58
  283. package/test/errors.test.ts +0 -21
  284. package/test/example-guestbook.test.ts +0 -123
  285. package/test/features.test.ts +0 -149
  286. package/test/fixtures/bignum-wire/spec.ts +0 -25
  287. package/test/fixtures/daemon-app.ts +0 -65
  288. package/test/fixtures/stream-echo.ts +0 -26
  289. package/test/fixtures/stream-gate.ts +0 -28
  290. package/test/fixtures/stream-trap.ts +0 -18
  291. package/test/fixtures/stream-typed.ts +0 -41
  292. package/test/fonts.test.ts +0 -28
  293. package/test/global-setup.ts +0 -17
  294. package/test/head.test.ts +0 -42
  295. package/test/image-blur.test.ts +0 -50
  296. package/test/io.test.ts +0 -117
  297. package/test/metadata.test.ts +0 -40
  298. package/test/navlink.test.ts +0 -28
  299. package/test/pages.test.ts +0 -105
  300. package/test/placeholder.test.ts +0 -9
  301. package/test/pqauth-e2e.test.ts +0 -216
  302. package/test/pqauth-email.test.ts +0 -801
  303. package/test/prerender.test.ts +0 -116
  304. package/test/prettier-plugin.test.ts +0 -46
  305. package/test/routes.test.ts +0 -76
  306. package/test/rpc-bignum-wire.test.ts +0 -164
  307. package/test/rpc-dispatch.test.ts +0 -132
  308. package/test/rpc-kinds.test.ts +0 -18
  309. package/test/rpc.test.ts +0 -66
  310. package/test/search.test.ts +0 -114
  311. package/test/seo.test.ts +0 -175
  312. package/test/slot-layouts.test.ts +0 -69
  313. package/test/sri.test.ts +0 -129
  314. package/test/ssg.test.ts +0 -36
  315. package/test/ssr-hydration.test.tsx +0 -122
  316. package/test/ssr-render.test.ts +0 -197
  317. package/test/ssr-template.test.tsx +0 -482
  318. package/test/stream-emulation.test.ts +0 -479
  319. package/test/ui.test.ts +0 -40
  320. package/test/update.test.ts +0 -58
  321. package/test/validate.test.ts +0 -42
  322. package/test/version-check.test.ts +0 -130
  323. package/tests/data-parity/generated-parity.ts +0 -99
  324. package/tests/data-parity/parity.ts +0 -80
  325. package/tests/data-parity/spec.ts +0 -46
package/src/cli/doctor.ts DELETED
@@ -1,982 +0,0 @@
1
- /**
2
- * `toiljs doctor`, read-only project diagnostics. Gathers facts from disk (package.json, lockfiles,
3
- * the resolved `toil.config`, the app entry, `index.html`, the scanned routes, client source files,
4
- * and the server target), runs the pure checks in `diagnostics.ts`, and prints a grouped human
5
- * report (or `--json` for CI). Never throws on a partial/non-toiljs project: missing inputs become
6
- * fail/warn checks. Sets a non-zero exit code when any check fails.
7
- */
8
- import fs from 'node:fs';
9
- import { createRequire } from 'node:module';
10
- import path from 'node:path';
11
- import { fileURLToPath } from 'node:url';
12
-
13
- import {
14
- loadConfig,
15
- type ResolvedToilConfig,
16
- scanRoutes,
17
- TOIL_SERVER_ENV_DTS,
18
- } from 'toiljs/compiler';
19
-
20
- import {
21
- type AuthFacts,
22
- type Check,
23
- checkAuthSecrets,
24
- checkBasePath,
25
- checkConfigLoads,
26
- checkDevScripts,
27
- checkDir,
28
- checkDuplicatePatterns,
29
- type CheckGroup,
30
- checkMigrationsDir,
31
- checkMountSlots,
32
- checkNode,
33
- checkPackageManager,
34
- checkPeer,
35
- checkPrettierPlugin,
36
- checkRelativeAssets,
37
- checkRestDispatch,
38
- checkRootElement,
39
- checkRoutesPresent,
40
- checkRpcWiring,
41
- checkSeoUrl,
42
- checkServerEntry,
43
- checkServerTsPlugin,
44
- type CheckStatus,
45
- checkStyling,
46
- checkToilconfig,
47
- checkToiljsInstalled,
48
- checkToilscriptInstalled,
49
- checkTypeScript,
50
- checkWasmBuilt,
51
- findRelativeAssets,
52
- hasFailures,
53
- rangeMajor,
54
- type RestFacts,
55
- RPC_TOILSCRIPT_MIN,
56
- type RpcFacts,
57
- satisfiesMin,
58
- type SourceFile,
59
- summarize,
60
- TYPESCRIPT_FIX_RANGE,
61
- } from './diagnostics.js';
62
- import {
63
- detectTailwind,
64
- type Preprocessor,
65
- PREPROCESSOR_PKG,
66
- preprocessorForExt,
67
- TAILWIND_ENTRY,
68
- } from './features.js';
69
- import { accent, bold, danger, dim, success, version, warn } from './ui.js';
70
-
71
- export interface DoctorOptions {
72
- readonly root?: string;
73
- readonly cwd: string;
74
- /** Emit machine-readable JSON instead of the human report. */
75
- readonly json?: boolean;
76
- /** Auto-fix what can be fixed in place (the typed-RPC wiring, and an unsupported typescript). */
77
- readonly fix?: boolean;
78
- }
79
-
80
- /** Parses a JSON file into a plain object, or null on any error / non-object. */
81
- function readJsonObject(file: string): Record<string, unknown> | null {
82
- try {
83
- const parsed: unknown = JSON.parse(fs.readFileSync(file, 'utf8'));
84
- return typeof parsed === 'object' && parsed !== null
85
- ? (parsed as Record<string, unknown>)
86
- : null;
87
- } catch {
88
- return null;
89
- }
90
- }
91
-
92
- /** Coerces a value to a `Record<string, string>` (drops non-string entries). */
93
- function stringRecord(value: unknown): Record<string, string> {
94
- if (typeof value !== 'object' || value === null) return {};
95
- const out: Record<string, string> = {};
96
- for (const [k, v] of Object.entries(value)) if (typeof v === 'string') out[k] = v;
97
- return out;
98
- }
99
-
100
- function readFile(file: string): string | null {
101
- try {
102
- return fs.readFileSync(file, 'utf8');
103
- } catch {
104
- return null;
105
- }
106
- }
107
-
108
- function writeFile(file: string, content: string): void {
109
- fs.writeFileSync(file, content);
110
- }
111
-
112
- /**
113
- * Whether `name` is installed for the project at `root`. Tries Node resolution first (handles
114
- * hoisting), then falls back to walking `node_modules`, since a strict `exports` map can make
115
- * `require.resolve('<pkg>')` throw even when the package is present (the toilscript false positive).
116
- */
117
- function isPackageInstalled(root: string, name: string): boolean {
118
- const require = createRequire(path.join(root, 'package.json'));
119
- for (const id of [`${name}/package.json`, name]) {
120
- try {
121
- require.resolve(id);
122
- return true;
123
- } catch {
124
- // try the next resolution strategy
125
- }
126
- }
127
- for (let dir = root; ; ) {
128
- if (fs.existsSync(path.join(dir, 'node_modules', name, 'package.json'))) return true;
129
- const parent = path.dirname(dir);
130
- if (parent === dir) return false;
131
- dir = parent;
132
- }
133
- }
134
-
135
- /**
136
- * The version of `name` actually installed for the project at `root`, or null when absent. Reads the
137
- * resolved package.json rather than trusting the declared range, since the installed copy is what
138
- * the compiler API consumers load. Falls back to walking `node_modules` (see `isPackageInstalled`).
139
- */
140
- function installedVersion(root: string, name: string): string | null {
141
- const require = createRequire(path.join(root, 'package.json'));
142
- let pkgPath: string | null = null;
143
- try {
144
- pkgPath = require.resolve(`${name}/package.json`);
145
- } catch {
146
- for (let dir = root; pkgPath === null; ) {
147
- const candidate = path.join(dir, 'node_modules', name, 'package.json');
148
- if (fs.existsSync(candidate)) pkgPath = candidate;
149
- const parent = path.dirname(dir);
150
- if (parent === dir) break;
151
- dir = parent;
152
- }
153
- }
154
- if (pkgPath === null) return null;
155
- const pkg = readJsonObject(pkgPath);
156
- return pkg && typeof pkg.version === 'string' ? pkg.version : null;
157
- }
158
-
159
- /**
160
- * Pins an unsupported TypeScript (the native 7.x, which ships no JavaScript compiler API) back to a
161
- * range toiljs can drive. Rewrites whichever of `devDependencies`/`dependencies` declares it; a
162
- * project with no declaration at all is left alone (nothing to pin), and the reinstall is left to
163
- * the user since only they know their package manager.
164
- */
165
- function applyTypeScriptFix(root: string): RpcFixResult {
166
- const changed: string[] = [];
167
- const skipped: string[] = [];
168
-
169
- const pkgPath = path.join(root, 'package.json');
170
- const pkg = readJsonObject(pkgPath);
171
- if (pkg === null) return { changed, skipped };
172
-
173
- const field = (['devDependencies', 'dependencies'] as const).find((f) => {
174
- const deps = asRecord(pkg[f]);
175
- return deps !== null && typeof deps.typescript === 'string';
176
- });
177
- if (field === undefined) {
178
- // Nothing declares typescript: it is either absent or hoisted from a workspace root.
179
- if (installedVersion(root, 'typescript') !== null) {
180
- skipped.push('typescript (installed but not declared in package.json; pin it by hand)');
181
- }
182
- return { changed, skipped };
183
- }
184
-
185
- const deps = asRecord(pkg[field]);
186
- if (deps === null) return { changed, skipped };
187
- const declared = deps.typescript as string;
188
- const declaredMajor = rangeMajor(declared);
189
- const installedMajor = rangeMajor(installedVersion(root, 'typescript') ?? '');
190
- const unsupported =
191
- (declaredMajor !== null && declaredMajor >= 7) ||
192
- (installedMajor !== null && installedMajor >= 7);
193
- if (!unsupported) return { changed, skipped };
194
-
195
- deps.typescript = TYPESCRIPT_FIX_RANGE;
196
- writeFile(pkgPath, JSON.stringify(pkg, null, 4) + '\n');
197
- changed.push(`package.json (typescript ${declared} -> ${TYPESCRIPT_FIX_RANGE})`);
198
- return { changed, skipped };
199
- }
200
-
201
- /** Narrows a value to a plain (non-array) object, or null. */
202
- function asRecord(value: unknown): Record<string, unknown> | null {
203
- return typeof value === 'object' && value !== null && !Array.isArray(value)
204
- ? (value as Record<string, unknown>)
205
- : null;
206
- }
207
-
208
- const RPC_MODULE_FLAG = '--rpcModule shared/server.ts';
209
- const RPC_GITIGNORE_LINE = 'shared/server.ts';
210
- const RPC_GITIGNORE_RE = /(^|\n)\s*shared\/server\.ts\s*(\r?\n|$)/;
211
-
212
- /**
213
- * Whether a dependency range is an ordinary registry semver range (so a deliberate
214
- * `latest`/`*`/`file:`/`github:`/`workspace:`/`npm:` pin is left untouched and treated
215
- * as already-OK rather than clobbered to a version).
216
- */
217
- function looksLikeSemverRange(range: string): boolean {
218
- return /^\s*[v^~>=<]*\s*\d+\.\d+/.test(range);
219
- }
220
-
221
- /** Reads the project and reports which parts of the typed-RPC wiring are present. */
222
- function gatherRpcFacts(root: string): RpcFacts {
223
- const pkg = readJsonObject(path.join(root, 'package.json'));
224
- const scripts = pkg ? stringRecord(pkg.scripts) : {};
225
- const deps = {
226
- ...(pkg ? stringRecord(pkg.dependencies) : {}),
227
- ...(pkg ? stringRecord(pkg.devDependencies) : {}),
228
- };
229
- const tsconfig = readJsonObject(path.join(root, 'tsconfig.json'));
230
- const gitignore = readFile(path.join(root, '.gitignore'));
231
-
232
- // Either the combined `build` or `build:server` carrying --rpcModule counts (the fixer writes both).
233
- const buildServerWired = [scripts['build:server'], scripts['build']].some(
234
- (s) => typeof s === 'string' && s.includes('--rpcModule'),
235
- );
236
-
237
- let tsconfigWired = false;
238
- if (tsconfig) {
239
- // An absent `include` compiles all files, so `shared` is covered implicitly.
240
- const include = tsconfig.include;
241
- const hasShared = !Array.isArray(include) || include.includes('shared');
242
- const paths = asRecord(asRecord(tsconfig.compilerOptions)?.paths);
243
- tsconfigWired = hasShared && paths !== null && 'shared/*' in paths;
244
- }
245
-
246
- const gitignoreWired = gitignore !== null && RPC_GITIGNORE_RE.test(gitignore);
247
- const range = deps.toilscript;
248
- // A non-semver range (file:/github:/latest/*) can't be assessed; don't flag it.
249
- const toilscriptOk =
250
- range == null
251
- ? false
252
- : looksLikeSemverRange(range)
253
- ? satisfiesMin(range, RPC_TOILSCRIPT_MIN)
254
- : true;
255
-
256
- return { buildServerWired, tsconfigWired, gitignoreWired, toilscriptOk };
257
- }
258
-
259
- /** The server `.ts` sources, read from the directories of the toilconfig entries (capped). */
260
- function serverSources(root: string, toilconfig: Record<string, unknown> | null): string[] {
261
- const dirs = new Set<string>();
262
- const entries = Array.isArray(toilconfig?.entries)
263
- ? (toilconfig.entries as unknown[]).filter((e): e is string => typeof e === 'string')
264
- : [];
265
- for (const e of entries) dirs.add(path.dirname(path.resolve(root, e)));
266
-
267
- const out: string[] = [];
268
- const cap = 200;
269
- const maxDepth = 16; // bounds the walk so a symlink cycle in a hostile project can't hang doctor
270
- const visit = (current: string, depth: number): void => {
271
- if (out.length >= cap || depth > maxDepth) return;
272
- let listing: fs.Dirent[];
273
- try {
274
- listing = fs.readdirSync(current, { withFileTypes: true });
275
- } catch {
276
- return;
277
- }
278
- for (const entry of listing) {
279
- if (out.length >= cap) break;
280
- const full = path.join(current, entry.name);
281
- // isDirectory() follows symlinks; the depth cap keeps a symlink cycle bounded.
282
- if (entry.isDirectory()) {
283
- if (entry.name !== 'node_modules') visit(full, depth + 1);
284
- } else if (entry.name.endsWith('.ts') && !entry.name.endsWith('.d.ts')) {
285
- const src = readFile(full);
286
- if (src !== null) out.push(src);
287
- }
288
- }
289
- };
290
- for (const dir of dirs) visit(dir, 0);
291
- return out;
292
- }
293
-
294
- /** Scans the server sources for `@rest` controllers and whether anything dispatches them. */
295
- function gatherRestFacts(root: string, toilconfig: Record<string, unknown> | null): RestFacts {
296
- let hasControllers = false;
297
- let dispatched = false;
298
- for (const src of serverSources(root, toilconfig)) {
299
- if (/@rest\b/.test(src)) hasControllers = true;
300
- if (/\bRest\s*\.\s*dispatch\s*\(/.test(src) || /\bRestHandler\b/.test(src))
301
- dispatched = true;
302
- if (hasControllers && dispatched) break;
303
- }
304
- return { hasControllers, dispatched };
305
- }
306
-
307
- /** Whether `.env.secrets` assigns `key` a non-empty value (a bare `KEY=` counts as unset). */
308
- function secretDefined(root: string, key: string): boolean {
309
- const raw = readFile(path.join(root, '.env.secrets'));
310
- if (raw === null) return false;
311
- return new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=\\s*\\S`, 'm').test(raw);
312
- }
313
-
314
- /**
315
- * Whether the server uses the auth primitive (so a missing session secret matters) and whether
316
- * `AUTH_SESSION_SECRET` is set locally. `getSecure` reads ONLY the `.env.secrets` bucket, so that
317
- * is the source we check; on a deploy target the secret lives on the dashboard instead.
318
- */
319
- function gatherAuthFacts(root: string, toilconfig: Record<string, unknown> | null): AuthFacts {
320
- let usesAuth = false;
321
- for (const src of serverSources(root, toilconfig)) {
322
- if (/\bAuthService\b/.test(src) || /@user\b/.test(src) || /@auth\b/.test(src)) {
323
- usesAuth = true;
324
- break;
325
- }
326
- }
327
- return { usesAuth, sessionSecretSet: secretDefined(root, 'AUTH_SESSION_SECRET') };
328
- }
329
-
330
- /** The toilscript language-service plugin id wired into a server tsconfig. */
331
- const TS_PLUGIN_NAME = 'toilscript/std/ts-plugin.cjs';
332
-
333
- /**
334
- * The server's tsconfig.json (the one beside a toilconfig entry, conventionally
335
- * `server/tsconfig.json`), or null if none exists. That is the project the editor uses for server
336
- * files, so it is where the toilscript LS plugin must live.
337
- */
338
- function serverTsconfigPath(root: string, toilconfig: Record<string, unknown> | null): string | null {
339
- const dirs = new Set<string>();
340
- const entries = Array.isArray(toilconfig?.entries)
341
- ? (toilconfig.entries as unknown[]).filter((e): e is string => typeof e === 'string')
342
- : [];
343
- for (const e of entries) dirs.add(path.dirname(path.resolve(root, e)));
344
- if (dirs.size === 0) dirs.add(path.join(root, 'server'));
345
- for (const dir of dirs) {
346
- const p = path.join(dir, 'tsconfig.json');
347
- if (fs.existsSync(p)) return p;
348
- }
349
- return null;
350
- }
351
-
352
- /**
353
- * Whether a `migrations/` folder exists under any server dir (the dir of a toilconfig entry,
354
- * conventionally `server/`). ToilDB `@migrate` functions live in `*.migration.ts` files there, and
355
- * the build auto-discovers them; a missing folder is a warn, not a fail (older projects predate it).
356
- */
357
- function serverMigrationsExist(root: string, toilconfig: Record<string, unknown> | null): boolean {
358
- const dirs = new Set<string>();
359
- const entries = Array.isArray(toilconfig?.entries)
360
- ? (toilconfig.entries as unknown[]).filter((e): e is string => typeof e === 'string')
361
- : [];
362
- for (const e of entries) dirs.add(path.dirname(path.resolve(root, e)));
363
- if (dirs.size === 0) dirs.add(path.join(root, 'server'));
364
- for (const dir of dirs) {
365
- if (fs.existsSync(path.join(dir, 'migrations'))) return true;
366
- }
367
- return false;
368
- }
369
-
370
- /** Whether a parsed tsconfig's `compilerOptions.plugins` references the toilscript LS plugin. */
371
- function tsconfigHasToilPlugin(tsconfig: Record<string, unknown> | null): boolean {
372
- const plugins = asRecord(tsconfig?.compilerOptions)?.plugins;
373
- if (!Array.isArray(plugins)) return false;
374
- return plugins.some((p) => {
375
- const name = asRecord(p)?.name;
376
- return typeof name === 'string' && name.includes('ts-plugin');
377
- });
378
- }
379
-
380
- interface RpcFixResult {
381
- /** Files written. */
382
- readonly changed: string[];
383
- /** Files that need a manual edit (e.g. tsconfig with comments). */
384
- readonly skipped: string[];
385
- }
386
-
387
- /**
388
- * Applies the typed-RPC wiring in place: appends `--rpcModule` to the toilscript build scripts,
389
- * adds `shared` (+ the `shared/*` alias) to tsconfig, ignores the generated module, and lifts the
390
- * toilscript floor. Idempotent; only writes files it actually changes.
391
- */
392
- function applyRpcFix(root: string): RpcFixResult {
393
- const changed: string[] = [];
394
- const skipped: string[] = [];
395
-
396
- const pkgPath = path.join(root, 'package.json');
397
- const pkgRaw = readFile(pkgPath);
398
- const pkg = pkgRaw !== null ? readJsonObject(pkgPath) : null;
399
- if (pkg !== null) {
400
- let touched = false;
401
- const scripts = asRecord(pkg.scripts) ?? {};
402
- for (const key of ['build', 'build:server']) {
403
- const value = scripts[key];
404
- if (
405
- typeof value === 'string' &&
406
- value.includes('toilscript') &&
407
- !value.includes('--rpcModule')
408
- ) {
409
- scripts[key] = `${value} ${RPC_MODULE_FLAG}`;
410
- pkg.scripts = scripts;
411
- touched = true;
412
- }
413
- }
414
- let toilscriptDeclared = false;
415
- for (const field of ['devDependencies', 'dependencies']) {
416
- const bag = asRecord(pkg[field]);
417
- const current = bag?.toilscript;
418
- if (bag && typeof current === 'string') {
419
- toilscriptDeclared = true;
420
- // Only lift a real semver range that floors below the minimum; leave file:/latest/* pins alone.
421
- if (looksLikeSemverRange(current) && !satisfiesMin(current, RPC_TOILSCRIPT_MIN)) {
422
- bag.toilscript = `^${RPC_TOILSCRIPT_MIN}`;
423
- touched = true;
424
- }
425
- }
426
- }
427
- if (!toilscriptDeclared) {
428
- // A server project needs toilscript; add it so the wiring actually resolves.
429
- const dd = asRecord(pkg.devDependencies) ?? {};
430
- dd.toilscript = `^${RPC_TOILSCRIPT_MIN}`;
431
- pkg.devDependencies = dd;
432
- touched = true;
433
- }
434
- if (touched) {
435
- writeFile(pkgPath, JSON.stringify(pkg, null, 4) + '\n');
436
- changed.push('package.json');
437
- }
438
- } else if (pkgRaw !== null) {
439
- skipped.push('package.json (unparseable)');
440
- }
441
-
442
- const tsPath = path.join(root, 'tsconfig.json');
443
- const tsRaw = readFile(tsPath);
444
- const tsconfig = tsRaw !== null ? readJsonObject(tsPath) : null;
445
- if (tsconfig !== null) {
446
- let touched = false;
447
- // Only touch `include` if it already exists; an absent `include` compiles all files,
448
- // and synthesizing one would narrow what TypeScript sees.
449
- if (Array.isArray(tsconfig.include)) {
450
- const include = [...(tsconfig.include as unknown[])];
451
- let changedInclude = false;
452
- // `shared` (the @data/@remote RPC alias target) right after `client`.
453
- if (!include.includes('shared')) {
454
- const at = include.indexOf('client');
455
- include.splice(at >= 0 ? at + 1 : include.length, 0, 'shared');
456
- changedInclude = true;
457
- }
458
- // `emails` (the React email-template pipeline) + `toil.config.ts`, so the
459
- // typescript-eslint project service / editor cover them — otherwise
460
- // `emails/*.tsx` (and a typed `toil.config.ts`) raise "not found by the
461
- // project service". Harmless when absent (a non-matching glob).
462
- for (const entry of ['emails', 'toil.config.ts']) {
463
- if (!include.includes(entry)) {
464
- include.push(entry);
465
- changedInclude = true;
466
- }
467
- }
468
- if (changedInclude) {
469
- tsconfig.include = include;
470
- touched = true;
471
- }
472
- }
473
- const co = asRecord(tsconfig.compilerOptions) ?? {};
474
- const paths = asRecord(co.paths) ?? {};
475
- if (!('shared/*' in paths)) {
476
- paths['shared/*'] = ['./shared/*'];
477
- co.paths = paths;
478
- tsconfig.compilerOptions = co;
479
- touched = true;
480
- }
481
- if (touched) {
482
- writeFile(tsPath, JSON.stringify(tsconfig, null, 4) + '\n');
483
- changed.push('tsconfig.json');
484
- }
485
- } else if (tsRaw !== null) {
486
- skipped.push('tsconfig.json (JSON with comments, add "shared" + paths by hand)');
487
- }
488
-
489
- const giPath = path.join(root, '.gitignore');
490
- const giRaw = readFile(giPath);
491
- if (giRaw === null) {
492
- writeFile(giPath, `${RPC_GITIGNORE_LINE}\n`);
493
- changed.push('.gitignore');
494
- } else if (!RPC_GITIGNORE_RE.test(giRaw)) {
495
- const sep = giRaw.length === 0 || giRaw.endsWith('\n') ? '' : '\n';
496
- writeFile(giPath, `${giRaw}${sep}${RPC_GITIGNORE_LINE}\n`);
497
- changed.push('.gitignore');
498
- }
499
-
500
- // Migrate the editor-only server-globals d.ts to the current shapes (the
501
- // exact content `toiljs build`/`dev` regenerate), in each server source dir.
502
- // This is what fixes a stale, scaffolded `toil-server-env.d.ts` whose
503
- // standalone class decls made a second, incompatible `Cookie`.
504
- const serverToilconfig = readJsonObject(path.join(root, 'toilconfig.json'));
505
- if (serverToilconfig !== null) {
506
- const entries = Array.isArray(serverToilconfig.entries)
507
- ? (serverToilconfig.entries as unknown[]).filter(
508
- (e): e is string => typeof e === 'string',
509
- )
510
- : [];
511
- const dirs = new Set<string>();
512
- for (const e of entries) dirs.add(path.dirname(path.resolve(root, e)));
513
- if (dirs.size === 0) dirs.add(path.join(root, 'server'));
514
- for (const dir of dirs) {
515
- const envPath = path.join(dir, 'toil-server-env.d.ts');
516
- if (readFile(envPath) !== TOIL_SERVER_ENV_DTS) {
517
- try {
518
- fs.mkdirSync(dir, { recursive: true });
519
- writeFile(envPath, TOIL_SERVER_ENV_DTS);
520
- changed.push(path.relative(root, envPath));
521
- } catch {
522
- // editor-only; ignore write failures
523
- }
524
- }
525
- }
526
- }
527
-
528
- return { changed, skipped };
529
- }
530
-
531
- const PRETTIER_PLUGIN = 'toiljs/prettier-plugin';
532
- const PRETTIER_MENTION = /toiljs\/prettier(-plugin)?/;
533
- const PRETTIER_CONFIG_FILES = [
534
- '.prettierrc',
535
- '.prettierrc.json',
536
- '.prettierrc.json5',
537
- '.prettierrc.yaml',
538
- '.prettierrc.yml',
539
- '.prettierrc.js',
540
- '.prettierrc.cjs',
541
- '.prettierrc.mjs',
542
- '.prettierrc.ts',
543
- 'prettier.config.js',
544
- 'prettier.config.cjs',
545
- 'prettier.config.mjs',
546
- 'prettier.config.ts',
547
- ];
548
-
549
- /** Whether any prettier config (file or package.json field) pulls in the toilscript plugin. */
550
- function prettierPluginPresent(root: string, pkg: Record<string, unknown> | null): boolean {
551
- if (pkg && pkg.prettier !== undefined && PRETTIER_MENTION.test(JSON.stringify(pkg.prettier))) {
552
- return true;
553
- }
554
- for (const name of PRETTIER_CONFIG_FILES) {
555
- const raw = readFile(path.join(root, name));
556
- if (raw !== null && PRETTIER_MENTION.test(raw)) return true;
557
- }
558
- return false;
559
- }
560
-
561
- /**
562
- * Adds `toiljs/prettier-plugin` to the project's prettier config so prettier can format the
563
- * toilscript server. Handles the common cases (package.json `prettier`, a JSON `.prettierrc`,
564
- * or no config at all); warns for shapes it can't safely edit (a JS config, or a string preset).
565
- */
566
- function applyPrettierFix(root: string, pkg: Record<string, unknown> | null): RpcFixResult {
567
- const changed: string[] = [];
568
- const skipped: string[] = [];
569
- if (prettierPluginPresent(root, pkg)) return { changed, skipped };
570
-
571
- // package.json "prettier" object.
572
- const pkgPath = path.join(root, 'package.json');
573
- const pkgConfig = pkg ? asRecord(pkg.prettier) : null;
574
- if (pkgConfig !== null) {
575
- const full = readJsonObject(pkgPath);
576
- const target = full ? asRecord(full.prettier) : null;
577
- if (full && target) {
578
- target.plugins = [
579
- ...(Array.isArray(target.plugins) ? target.plugins : []),
580
- PRETTIER_PLUGIN,
581
- ];
582
- writeFile(pkgPath, JSON.stringify(full, null, 4) + '\n');
583
- changed.push('package.json');
584
- return { changed, skipped };
585
- }
586
- }
587
-
588
- // A JSON .prettierrc / .prettierrc.json object.
589
- for (const name of ['.prettierrc', '.prettierrc.json']) {
590
- const filePath = path.join(root, name);
591
- const raw = readFile(filePath);
592
- if (raw === null) continue;
593
- const obj = readJsonObject(filePath);
594
- if (obj === null) {
595
- skipped.push(`${name} (add "${PRETTIER_PLUGIN}" to plugins by hand)`);
596
- return { changed, skipped };
597
- }
598
- obj.plugins = [...(Array.isArray(obj.plugins) ? obj.plugins : []), PRETTIER_PLUGIN];
599
- writeFile(filePath, JSON.stringify(obj, null, 4) + '\n');
600
- changed.push(name);
601
- return { changed, skipped };
602
- }
603
-
604
- // A JS/TS config we can't safely edit.
605
- const jsConfig = PRETTIER_CONFIG_FILES.find((name) => readFile(path.join(root, name)) !== null);
606
- if (jsConfig) {
607
- skipped.push(`${jsConfig} (add "${PRETTIER_PLUGIN}" to its plugins by hand)`);
608
- return { changed, skipped };
609
- }
610
-
611
- // No config at all: create one.
612
- writeFile(
613
- path.join(root, '.prettierrc.json'),
614
- JSON.stringify({ plugins: [PRETTIER_PLUGIN] }, null, 4) + '\n',
615
- );
616
- changed.push('.prettierrc.json');
617
- return { changed, skipped };
618
- }
619
-
620
- /**
621
- * Wires the editor side of the toilscript server: adds the LS plugin to the server tsconfig (so the
622
- * editor stops false-flagging `@database` static collections / `@data` members), and points VS Code
623
- * at the workspace TypeScript (so it actually loads that plugin). Idempotent; only writes real
624
- * changes, and skips (with a note) configs it can't safely edit (a tsconfig with comments).
625
- */
626
- function applyServerEditorFix(root: string, toilconfig: Record<string, unknown> | null): RpcFixResult {
627
- const changed: string[] = [];
628
- const skipped: string[] = [];
629
-
630
- // 1. The LS plugin in the server tsconfig.
631
- const tsPath = serverTsconfigPath(root, toilconfig);
632
- if (tsPath === null) {
633
- skipped.push('server/tsconfig.json (not found; add the toilscript ts-plugin by hand)');
634
- } else {
635
- const rel = path.relative(root, tsPath);
636
- const raw = readFile(tsPath);
637
- const parsed = raw !== null ? readJsonObject(tsPath) : null;
638
- if (parsed === null) {
639
- skipped.push(`${rel} (JSON with comments; add the "${TS_PLUGIN_NAME}" plugin by hand)`);
640
- } else if (!tsconfigHasToilPlugin(parsed)) {
641
- const co = asRecord(parsed.compilerOptions) ?? {};
642
- const existingPlugins: unknown[] = Array.isArray(co.plugins)
643
- ? (co.plugins as unknown[])
644
- : [];
645
- co.plugins = [...existingPlugins, { name: TS_PLUGIN_NAME }];
646
- parsed.compilerOptions = co;
647
- writeFile(tsPath, JSON.stringify(parsed, null, 4) + '\n');
648
- changed.push(rel);
649
- }
650
- }
651
-
652
- // 2. Make VS Code use the workspace TypeScript, so it loads the plugin above.
653
- const vsPath = path.join(root, '.vscode', 'settings.json');
654
- const vsRaw = readFile(vsPath);
655
- const vs = vsRaw !== null ? readJsonObject(vsPath) : {};
656
- if (vs === null) {
657
- skipped.push('.vscode/settings.json (unparseable; set typescript.tsdk by hand)');
658
- } else {
659
- let touched = false;
660
- if (vs['typescript.tsdk'] !== 'node_modules/typescript/lib') {
661
- vs['typescript.tsdk'] = 'node_modules/typescript/lib';
662
- touched = true;
663
- }
664
- if (vs['typescript.enablePromptUseWorkspaceTsdk'] !== true) {
665
- vs['typescript.enablePromptUseWorkspaceTsdk'] = true;
666
- touched = true;
667
- }
668
- if (touched) {
669
- fs.mkdirSync(path.dirname(vsPath), { recursive: true });
670
- writeFile(vsPath, JSON.stringify(vs, null, 4) + '\n');
671
- changed.push('.vscode/settings.json');
672
- }
673
- }
674
-
675
- return { changed, skipped };
676
- }
677
-
678
- /** Reads the framework's own package.json (engines + peerDependencies) for the requirements. */
679
- function frameworkMeta(): { node: string; peers: Record<string, string> } {
680
- const pkgPath = path.resolve(
681
- path.dirname(fileURLToPath(import.meta.url)),
682
- '..',
683
- '..',
684
- 'package.json',
685
- );
686
- const pkg = readJsonObject(pkgPath);
687
- const engines = pkg ? stringRecord(pkg.engines) : {};
688
- const peers = pkg ? stringRecord(pkg.peerDependencies) : {};
689
- return { node: engines.node ?? '>=24.0.0', peers };
690
- }
691
-
692
- const LOCKFILES = ['package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb'];
693
-
694
- /** Reads the app entry source (the file that mounts the app), or null if none is found. */
695
- function readEntry(clientAbsDir: string): string | null {
696
- for (const name of ['toil.tsx', 'toil.jsx', 'main.tsx', 'main.jsx']) {
697
- const source = readFile(path.join(clientAbsDir, name));
698
- if (source !== null && /toiljs\/routes|\bmount\s*\(/.test(source)) return source;
699
- }
700
- return null;
701
- }
702
-
703
- /** Collects client `.tsx`/`.jsx` sources (capped) for the relative-asset scan. */
704
- function collectSources(root: string, dir: string, cap: number): SourceFile[] {
705
- const out: SourceFile[] = [];
706
- const visit = (current: string): void => {
707
- if (out.length >= cap) return;
708
- let entries: fs.Dirent[];
709
- try {
710
- entries = fs.readdirSync(current, { withFileTypes: true });
711
- } catch {
712
- return;
713
- }
714
- for (const entry of entries) {
715
- if (out.length >= cap) break;
716
- const full = path.join(current, entry.name);
717
- if (entry.isDirectory()) {
718
- if (entry.name !== 'node_modules') visit(full);
719
- } else if (/\.(tsx|jsx)$/.test(entry.name)) {
720
- const source = readFile(full);
721
- if (source !== null) out.push({ path: path.relative(root, full), source });
722
- }
723
- }
724
- };
725
- visit(dir);
726
- return out;
727
- }
728
-
729
- /** Picks a check glyph in the brand palette. */
730
- function glyph(status: CheckStatus): string {
731
- if (status === 'pass') return success('✓');
732
- if (status === 'warn') return warn('⚠');
733
- return danger('✗');
734
- }
735
-
736
- function renderHuman(groups: readonly CheckGroup[]): void {
737
- const summary = summarize(groups);
738
- const out: string[] = [];
739
- for (const group of groups) {
740
- out.push(' ' + bold(group.title));
741
- for (const check of group.checks) {
742
- let line = ` ${glyph(check.status)} ${check.label}`;
743
- if (check.detail) line += dim(` ${check.detail}`);
744
- out.push(line);
745
- if (check.fix && check.status !== 'pass')
746
- out.push(' ' + dim(`fix: ${check.fix}`));
747
- }
748
- out.push('');
749
- }
750
- const parts = [success(`${String(summary.pass)} passed`)];
751
- if (summary.warn > 0) {
752
- parts.push(warn(`${String(summary.warn)} warning${summary.warn === 1 ? '' : 's'}`));
753
- }
754
- if (summary.fail > 0) parts.push(danger(`${String(summary.fail)} failed`));
755
- out.push(' ' + parts.join(dim(', ')));
756
- out.push('');
757
- process.stdout.write(out.join('\n') + '\n');
758
- }
759
-
760
- export async function runDoctor(opts: DoctorOptions): Promise<void> {
761
- const root = path.resolve(opts.root ?? opts.cwd);
762
- const meta = frameworkMeta();
763
-
764
- const projectPkg = readJsonObject(path.join(root, 'package.json'));
765
- const deps: Record<string, string> = {
766
- ...(projectPkg ? stringRecord(projectPkg.dependencies) : {}),
767
- ...(projectPkg ? stringRecord(projectPkg.devDependencies) : {}),
768
- };
769
-
770
- // Config (the only async fact). On failure, downstream paths fall back to conventional defaults.
771
- let cfg: ResolvedToilConfig | null = null;
772
- let configError: string | undefined;
773
- try {
774
- cfg = await loadConfig({ root });
775
- } catch (err) {
776
- configError = err instanceof Error ? err.message : String(err);
777
- }
778
-
779
- const clientAbsDir = cfg ? cfg.clientAbsDir : path.join(root, 'client');
780
- const routesAbsDir = cfg ? cfg.routesAbsDir : path.join(clientAbsDir, 'routes');
781
- const publicDir = cfg ? cfg.publicDir : path.join(clientAbsDir, 'public');
782
-
783
- const entrySource = readEntry(clientAbsDir);
784
- const indexHtml = readFile(path.join(publicDir, 'index.html'));
785
- const routes = scanRoutes(routesAbsDir);
786
- const mainPatterns = routes.filter((r) => r.slot === undefined).map((r) => r.pattern);
787
- const assetIssues = findRelativeAssets(collectSources(root, clientAbsDir, 200));
788
-
789
- // Styling facts from the entry's style imports.
790
- let preprocessorImported: Preprocessor | null = null;
791
- let tailwindImported = false;
792
- if (entrySource) {
793
- const styleImport = /import\s+['"]\.\/styles\/main\.([a-z]+)['"]/.exec(entrySource);
794
- if (styleImport) preprocessorImported = preprocessorForExt(styleImport[1]);
795
- tailwindImported = entrySource.includes(TAILWIND_ENTRY);
796
- }
797
- const ppPkg = preprocessorImported ? PREPROCESSOR_PKG[preprocessorImported] : null;
798
- const preprocessorInstalled = ppPkg === null || ppPkg in deps;
799
-
800
- // Server / WASM facts.
801
- const toilconfig = readJsonObject(path.join(root, 'toilconfig.json'));
802
- const serverPresent = toilconfig !== null;
803
- let missingEntries: string[] = [];
804
- let toilscriptInstalled = false;
805
- let wasmExists = false;
806
- if (toilconfig) {
807
- const entries = Array.isArray(toilconfig.entries)
808
- ? toilconfig.entries.filter((e): e is string => typeof e === 'string')
809
- : [];
810
- missingEntries = entries.filter((e) => !fs.existsSync(path.join(root, e)));
811
- toilscriptInstalled = isPackageInstalled(root, 'toilscript');
812
- const targets =
813
- typeof toilconfig.targets === 'object' && toilconfig.targets !== null
814
- ? (toilconfig.targets as Record<string, unknown>)
815
- : {};
816
- const outFiles: string[] = [];
817
- for (const target of Object.values(targets)) {
818
- if (typeof target === 'object' && target !== null) {
819
- const outFile = (target as Record<string, unknown>).outFile;
820
- if (typeof outFile === 'string') outFiles.push(outFile);
821
- }
822
- }
823
- wasmExists = outFiles.some((f) => fs.existsSync(path.join(root, f)));
824
- if (!wasmExists && outFiles.length === 0) {
825
- try {
826
- wasmExists = fs
827
- .readdirSync(path.join(root, 'build', 'server'))
828
- .some((f) => f.endsWith('.wasm'));
829
- } catch {
830
- wasmExists = false;
831
- }
832
- }
833
- }
834
-
835
- const peerName = (n: string): Check => checkPeer(n, deps[n] ?? null, meta.peers[n] ?? '*');
836
- // typescript gets its own check: its peer range is the only one whose upper bound matters (7.x
837
- // clears the `>=6.0.0` floor but ships no compiler API), and it is fixable in place.
838
- const peerChecks = Object.keys(meta.peers)
839
- .filter((n) => n !== 'typescript')
840
- .map(peerName);
841
- const typeScriptFix = opts.fix ? applyTypeScriptFix(root) : null;
842
- // Re-read the declared range: `--fix` may have just rewritten it.
843
- const declaredTypeScript = (() => {
844
- const pkg = readJsonObject(path.join(root, 'package.json'));
845
- if (pkg === null) return deps.typescript ?? null;
846
- for (const field of ['devDependencies', 'dependencies'] as const) {
847
- const range = asRecord(pkg[field])?.typescript;
848
- if (typeof range === 'string') return range;
849
- }
850
- return null;
851
- })();
852
- const typeScriptCheck = checkTypeScript(
853
- installedVersion(root, 'typescript'),
854
- declaredTypeScript,
855
- );
856
-
857
- // Server tooling (RPC wiring + the prettier plugin + the editor LS plugin): optionally fix in
858
- // place, then re-read.
859
- const rpcFix = serverPresent && opts.fix ? applyRpcFix(root) : null;
860
- const prettierFix = serverPresent && opts.fix ? applyPrettierFix(root, projectPkg) : null;
861
- const editorFix = serverPresent && opts.fix ? applyServerEditorFix(root, toilconfig) : null;
862
- const rpcFacts = gatherRpcFacts(root);
863
- const restFacts = gatherRestFacts(root, toilconfig);
864
- const authFacts = gatherAuthFacts(root, toilconfig);
865
- const prettierPresent = prettierPluginPresent(
866
- root,
867
- readJsonObject(path.join(root, 'package.json')),
868
- );
869
- // Only assess the LS plugin when a server tsconfig exists and parses; an absent or
870
- // commented one is left to the user rather than warned on.
871
- const serverTsPath = serverPresent ? serverTsconfigPath(root, toilconfig) : null;
872
- const serverTsParsed = serverTsPath ? readJsonObject(serverTsPath) : null;
873
- const serverTsPluginPresent =
874
- serverTsPath === null || serverTsParsed === null ? true : tsconfigHasToilPlugin(serverTsParsed);
875
- // The typescript pin is fixable without a server; the rest only apply to one.
876
- const applied = [typeScriptFix, rpcFix, prettierFix, editorFix].filter(
877
- (fix): fix is RpcFixResult => fix !== null,
878
- );
879
- const serverFix =
880
- applied.length > 0
881
- ? {
882
- changed: applied.flatMap((fix) => fix.changed),
883
- skipped: applied.flatMap((fix) => fix.skipped),
884
- }
885
- : null;
886
-
887
- const groups: CheckGroup[] = [
888
- {
889
- title: 'Environment',
890
- checks: [
891
- checkNode(process.versions.node, meta.node),
892
- checkToiljsInstalled('toiljs' in deps ? version() : null),
893
- ...peerChecks,
894
- typeScriptCheck,
895
- checkPackageManager(LOCKFILES.filter((f) => fs.existsSync(path.join(root, f)))),
896
- ],
897
- },
898
- {
899
- title: 'Project + routing',
900
- checks: [
901
- checkDir(
902
- 'client-dir',
903
- 'client/ directory',
904
- fs.existsSync(clientAbsDir),
905
- 'Create a client/ directory for your app.',
906
- ),
907
- checkDir(
908
- 'routes-dir',
909
- 'routes/ directory',
910
- fs.existsSync(routesAbsDir),
911
- 'Create client/routes/ and add an index.tsx.',
912
- ),
913
- checkRootElement(indexHtml),
914
- checkMountSlots(entrySource),
915
- checkRoutesPresent(routes.length),
916
- checkDuplicatePatterns(mainPatterns),
917
- checkRelativeAssets(assetIssues),
918
- checkDevScripts(projectPkg ? stringRecord(projectPkg.scripts) : {}),
919
- ],
920
- },
921
- {
922
- title: 'Config + assets',
923
- checks: [
924
- checkConfigLoads(cfg !== null, configError),
925
- checkBasePath(cfg ? cfg.base : '/'),
926
- checkSeoUrl(cfg?.seo != null, cfg?.seo?.url != null),
927
- checkStyling({
928
- preprocessorImported,
929
- preprocessorInstalled,
930
- tailwindImported,
931
- tailwindInstalled: detectTailwind(deps),
932
- }),
933
- ],
934
- },
935
- {
936
- title: 'Server / WASM',
937
- checks: serverPresent
938
- ? [
939
- checkToilconfig(true),
940
- checkServerEntry(missingEntries),
941
- checkToilscriptInstalled(toilscriptInstalled),
942
- checkWasmBuilt(wasmExists),
943
- checkRpcWiring(rpcFacts),
944
- checkRestDispatch(restFacts),
945
- checkPrettierPlugin(prettierPresent),
946
- checkServerTsPlugin(serverTsPluginPresent),
947
- checkMigrationsDir(serverMigrationsExist(root, toilconfig)),
948
- ]
949
- : [checkToilconfig(false)],
950
- },
951
- ];
952
-
953
- // Security checks only apply to a server (no server, no sessions to forge).
954
- if (serverPresent) {
955
- groups.push({ title: 'Security', checks: [checkAuthSecrets(authFacts)] });
956
- }
957
-
958
- const summary = summarize(groups);
959
- if (opts.json) {
960
- process.stdout.write(JSON.stringify({ groups, summary, fixed: serverFix }, null, 2) + '\n');
961
- } else {
962
- process.stdout.write('\n' + accent(' Doctor') + dim(` ${root}`) + '\n\n');
963
- renderHuman(groups);
964
- if (serverFix) renderFix(serverFix);
965
- }
966
- if (hasFailures(summary)) process.exitCode = 1;
967
- }
968
-
969
- /** Prints the result of `--fix`, and whether a reinstall is needed (a changed dependency range). */
970
- function renderFix(result: RpcFixResult): void {
971
- const out: string[] = [];
972
- if (result.changed.length > 0) {
973
- out.push(' ' + success('fixed') + dim(` ${result.changed.join(', ')}`));
974
- if (result.changed.some((entry) => entry.startsWith('package.json'))) {
975
- out.push(' ' + dim('run your installer (npm/pnpm/yarn) to apply the version changes.'));
976
- }
977
- } else {
978
- out.push(' ' + dim('nothing to fix.'));
979
- }
980
- for (const item of result.skipped) out.push(' ' + warn('skipped') + dim(` ${item}`));
981
- process.stdout.write(out.join('\n') + '\n\n');
982
- }