@supatype/cli 0.3.6 → 0.7.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 (903) hide show
  1. package/CHANGELOG.md +174 -1
  2. package/deno.d.ts +11 -0
  3. package/dist/adopt-columns.d.ts +157 -0
  4. package/dist/adopt-columns.d.ts.map +1 -0
  5. package/dist/adopt-columns.js +789 -0
  6. package/dist/adopt-columns.js.map +1 -0
  7. package/dist/adopt-walkthrough.d.ts +50 -15
  8. package/dist/adopt-walkthrough.d.ts.map +1 -1
  9. package/dist/adopt-walkthrough.js +93 -61
  10. package/dist/adopt-walkthrough.js.map +1 -1
  11. package/dist/api-config-cache.d.ts +3 -3
  12. package/dist/api-config-cache.d.ts.map +1 -1
  13. package/dist/api-config-cache.js +14 -20
  14. package/dist/api-config-cache.js.map +1 -1
  15. package/dist/app/framework.d.ts.map +1 -1
  16. package/dist/app/framework.js +5 -5
  17. package/dist/app/framework.js.map +1 -1
  18. package/dist/app/proxy-dev-app.d.ts.map +1 -1
  19. package/dist/app/proxy-dev-app.js +3 -2
  20. package/dist/app/proxy-dev-app.js.map +1 -1
  21. package/dist/ast-read.d.ts +17 -0
  22. package/dist/ast-read.d.ts.map +1 -0
  23. package/dist/ast-read.js +32 -0
  24. package/dist/ast-read.js.map +1 -0
  25. package/dist/augmentation-generator.d.ts +14 -2
  26. package/dist/augmentation-generator.d.ts.map +1 -1
  27. package/dist/augmentation-generator.js +194 -61
  28. package/dist/augmentation-generator.js.map +1 -1
  29. package/dist/augmentation-relationships.d.ts +32 -0
  30. package/dist/augmentation-relationships.d.ts.map +1 -0
  31. package/dist/augmentation-relationships.js +122 -0
  32. package/dist/augmentation-relationships.js.map +1 -0
  33. package/dist/auth-answer.d.ts +16 -0
  34. package/dist/auth-answer.d.ts.map +1 -0
  35. package/dist/auth-answer.js +21 -0
  36. package/dist/auth-answer.js.map +1 -0
  37. package/dist/auth-providers.d.ts +89 -0
  38. package/dist/auth-providers.d.ts.map +1 -0
  39. package/dist/auth-providers.js +243 -0
  40. package/dist/auth-providers.js.map +1 -0
  41. package/dist/binary-cache.d.ts +9 -6
  42. package/dist/binary-cache.d.ts.map +1 -1
  43. package/dist/binary-cache.js +150 -46
  44. package/dist/binary-cache.js.map +1 -1
  45. package/dist/binary-download-lock.d.ts.map +1 -1
  46. package/dist/binary-download-lock.js +13 -10
  47. package/dist/binary-download-lock.js.map +1 -1
  48. package/dist/byo-preflight.d.ts +26 -0
  49. package/dist/byo-preflight.d.ts.map +1 -0
  50. package/dist/byo-preflight.js +69 -0
  51. package/dist/byo-preflight.js.map +1 -0
  52. package/dist/cache-identity-scope.d.ts +7 -3
  53. package/dist/cache-identity-scope.d.ts.map +1 -1
  54. package/dist/cache-identity-scope.js +20 -10
  55. package/dist/cache-identity-scope.js.map +1 -1
  56. package/dist/cache-provider.d.ts +17 -18
  57. package/dist/cache-provider.d.ts.map +1 -1
  58. package/dist/cache-provider.js +27 -25
  59. package/dist/cache-provider.js.map +1 -1
  60. package/dist/cli-package-version.d.ts.map +1 -1
  61. package/dist/cli-package-version.js +2 -2
  62. package/dist/cli-package-version.js.map +1 -1
  63. package/dist/cli-standalone.d.ts.map +1 -1
  64. package/dist/cli-standalone.js +2 -6
  65. package/dist/cli-standalone.js.map +1 -1
  66. package/dist/cli-version-embedded.js +1 -1
  67. package/dist/cli.d.ts.map +1 -1
  68. package/dist/cli.js +4 -0
  69. package/dist/cli.js.map +1 -1
  70. package/dist/client-generator.d.ts +5 -2
  71. package/dist/client-generator.d.ts.map +1 -1
  72. package/dist/client-generator.js +32 -22
  73. package/dist/client-generator.js.map +1 -1
  74. package/dist/cloud-credentials.d.ts.map +1 -1
  75. package/dist/cloud-credentials.js +32 -26
  76. package/dist/cloud-credentials.js.map +1 -1
  77. package/dist/commands/add.d.ts.map +1 -1
  78. package/dist/commands/add.js +3 -2
  79. package/dist/commands/add.js.map +1 -1
  80. package/dist/commands/admin.d.ts +51 -16
  81. package/dist/commands/admin.d.ts.map +1 -1
  82. package/dist/commands/admin.js +162 -136
  83. package/dist/commands/admin.js.map +1 -1
  84. package/dist/commands/adopt.d.ts +23 -0
  85. package/dist/commands/adopt.d.ts.map +1 -1
  86. package/dist/commands/adopt.js +205 -42
  87. package/dist/commands/adopt.js.map +1 -1
  88. package/dist/commands/app.d.ts.map +1 -1
  89. package/dist/commands/app.js +4 -3
  90. package/dist/commands/app.js.map +1 -1
  91. package/dist/commands/cache.d.ts.map +1 -1
  92. package/dist/commands/cache.js +2 -1
  93. package/dist/commands/cache.js.map +1 -1
  94. package/dist/commands/cloud.d.ts +4 -1
  95. package/dist/commands/cloud.d.ts.map +1 -1
  96. package/dist/commands/cloud.js +47 -23
  97. package/dist/commands/cloud.js.map +1 -1
  98. package/dist/commands/db.d.ts.map +1 -1
  99. package/dist/commands/db.js +9 -7
  100. package/dist/commands/db.js.map +1 -1
  101. package/dist/commands/deploy.d.ts +6 -0
  102. package/dist/commands/deploy.d.ts.map +1 -1
  103. package/dist/commands/deploy.js +65 -17
  104. package/dist/commands/deploy.js.map +1 -1
  105. package/dist/commands/dev.d.ts +8 -2
  106. package/dist/commands/dev.d.ts.map +1 -1
  107. package/dist/commands/dev.js +385 -268
  108. package/dist/commands/dev.js.map +1 -1
  109. package/dist/commands/doctor.d.ts +56 -8
  110. package/dist/commands/doctor.d.ts.map +1 -1
  111. package/dist/commands/doctor.js +180 -61
  112. package/dist/commands/doctor.js.map +1 -1
  113. package/dist/commands/engine.d.ts +1 -1
  114. package/dist/commands/engine.d.ts.map +1 -1
  115. package/dist/commands/engine.js +14 -13
  116. package/dist/commands/engine.js.map +1 -1
  117. package/dist/commands/functions.d.ts.map +1 -1
  118. package/dist/commands/functions.js +85 -96
  119. package/dist/commands/functions.js.map +1 -1
  120. package/dist/commands/generate.d.ts +6 -0
  121. package/dist/commands/generate.d.ts.map +1 -1
  122. package/dist/commands/generate.js +20 -20
  123. package/dist/commands/generate.js.map +1 -1
  124. package/dist/commands/init.d.ts +19 -0
  125. package/dist/commands/init.d.ts.map +1 -1
  126. package/dist/commands/init.js +105 -82
  127. package/dist/commands/init.js.map +1 -1
  128. package/dist/commands/internal.d.ts.map +1 -1
  129. package/dist/commands/internal.js +3 -2
  130. package/dist/commands/internal.js.map +1 -1
  131. package/dist/commands/keys.js.map +1 -1
  132. package/dist/commands/link-helpers.d.ts.map +1 -1
  133. package/dist/commands/link-helpers.js +16 -8
  134. package/dist/commands/link-helpers.js.map +1 -1
  135. package/dist/commands/login.d.ts.map +1 -1
  136. package/dist/commands/login.js +2 -1
  137. package/dist/commands/login.js.map +1 -1
  138. package/dist/commands/migrate.d.ts +43 -0
  139. package/dist/commands/migrate.d.ts.map +1 -1
  140. package/dist/commands/migrate.js +98 -47
  141. package/dist/commands/migrate.js.map +1 -1
  142. package/dist/commands/pg.d.ts.map +1 -1
  143. package/dist/commands/pg.js +24 -23
  144. package/dist/commands/pg.js.map +1 -1
  145. package/dist/commands/plugins.d.ts.map +1 -1
  146. package/dist/commands/plugins.js +36 -27
  147. package/dist/commands/plugins.js.map +1 -1
  148. package/dist/commands/pull.d.ts.map +1 -1
  149. package/dist/commands/pull.js +6 -5
  150. package/dist/commands/pull.js.map +1 -1
  151. package/dist/commands/push.d.ts +23 -0
  152. package/dist/commands/push.d.ts.map +1 -1
  153. package/dist/commands/push.js +249 -84
  154. package/dist/commands/push.js.map +1 -1
  155. package/dist/commands/rename.d.ts +20 -0
  156. package/dist/commands/rename.d.ts.map +1 -0
  157. package/dist/commands/rename.js +74 -0
  158. package/dist/commands/rename.js.map +1 -0
  159. package/dist/commands/seed.d.ts +12 -0
  160. package/dist/commands/seed.d.ts.map +1 -1
  161. package/dist/commands/seed.js +65 -12
  162. package/dist/commands/seed.js.map +1 -1
  163. package/dist/commands/self-host.d.ts.map +1 -1
  164. package/dist/commands/self-host.js +93 -27
  165. package/dist/commands/self-host.js.map +1 -1
  166. package/dist/commands/self-update.d.ts.map +1 -1
  167. package/dist/commands/self-update.js +2 -1
  168. package/dist/commands/self-update.js.map +1 -1
  169. package/dist/commands/status.d.ts.map +1 -1
  170. package/dist/commands/status.js +16 -12
  171. package/dist/commands/status.js.map +1 -1
  172. package/dist/commands/types.d.ts.map +1 -1
  173. package/dist/commands/types.js +9 -7
  174. package/dist/commands/types.js.map +1 -1
  175. package/dist/commands/update.d.ts.map +1 -1
  176. package/dist/commands/update.js +8 -4
  177. package/dist/commands/update.js.map +1 -1
  178. package/dist/compose-db-psql.d.ts +20 -0
  179. package/dist/compose-db-psql.d.ts.map +1 -0
  180. package/dist/compose-db-psql.js +30 -0
  181. package/dist/compose-db-psql.js.map +1 -0
  182. package/dist/compose-db-roles.d.ts +41 -0
  183. package/dist/compose-db-roles.d.ts.map +1 -0
  184. package/dist/compose-db-roles.js +118 -0
  185. package/dist/compose-db-roles.js.map +1 -0
  186. package/dist/compose-engine-run.d.ts +27 -0
  187. package/dist/compose-engine-run.d.ts.map +1 -0
  188. package/dist/compose-engine-run.js +61 -0
  189. package/dist/compose-engine-run.js.map +1 -0
  190. package/dist/compose-kong.d.ts +31 -0
  191. package/dist/compose-kong.d.ts.map +1 -0
  192. package/dist/compose-kong.js +145 -0
  193. package/dist/compose-kong.js.map +1 -0
  194. package/dist/compose-rename.d.ts.map +1 -1
  195. package/dist/compose-rename.js +2 -2
  196. package/dist/compose-rename.js.map +1 -1
  197. package/dist/compose-render-mode.d.ts +41 -0
  198. package/dist/compose-render-mode.d.ts.map +1 -0
  199. package/dist/compose-render-mode.js +70 -0
  200. package/dist/compose-render-mode.js.map +1 -0
  201. package/dist/compose-services.d.ts.map +1 -1
  202. package/dist/compose-services.js +3 -2
  203. package/dist/compose-services.js.map +1 -1
  204. package/dist/config.d.ts +18 -2
  205. package/dist/config.d.ts.map +1 -1
  206. package/dist/config.js +50 -13
  207. package/dist/config.js.map +1 -1
  208. package/dist/db-port.d.ts +57 -13
  209. package/dist/db-port.d.ts.map +1 -1
  210. package/dist/db-port.js +78 -38
  211. package/dist/db-port.js.map +1 -1
  212. package/dist/db-preflight.d.ts +22 -8
  213. package/dist/db-preflight.d.ts.map +1 -1
  214. package/dist/db-preflight.js +86 -46
  215. package/dist/db-preflight.js.map +1 -1
  216. package/dist/db-rows.d.ts +20 -0
  217. package/dist/db-rows.d.ts.map +1 -0
  218. package/dist/db-rows.js +20 -0
  219. package/dist/db-rows.js.map +1 -0
  220. package/dist/destructive-consent.d.ts +88 -0
  221. package/dist/destructive-consent.d.ts.map +1 -0
  222. package/dist/destructive-consent.js +184 -0
  223. package/dist/destructive-consent.js.map +1 -0
  224. package/dist/dev-api-keys.d.ts +26 -0
  225. package/dist/dev-api-keys.d.ts.map +1 -0
  226. package/dist/dev-api-keys.js +52 -0
  227. package/dist/dev-api-keys.js.map +1 -0
  228. package/dist/dev-compose.d.ts +92 -15
  229. package/dist/dev-compose.d.ts.map +1 -1
  230. package/dist/dev-compose.js +676 -465
  231. package/dist/dev-compose.js.map +1 -1
  232. package/dist/dev-db-ready.d.ts +20 -0
  233. package/dist/dev-db-ready.d.ts.map +1 -0
  234. package/dist/dev-db-ready.js +21 -0
  235. package/dist/dev-db-ready.js.map +1 -0
  236. package/dist/dev-functions-watch.d.ts +24 -0
  237. package/dist/dev-functions-watch.d.ts.map +1 -0
  238. package/dist/dev-functions-watch.js +82 -0
  239. package/dist/dev-functions-watch.js.map +1 -0
  240. package/dist/dev-initial-push.d.ts +41 -6
  241. package/dist/dev-initial-push.d.ts.map +1 -1
  242. package/dist/dev-initial-push.js +84 -31
  243. package/dist/dev-initial-push.js.map +1 -1
  244. package/dist/dev-ports.d.ts +58 -6
  245. package/dist/dev-ports.d.ts.map +1 -1
  246. package/dist/dev-ports.js +157 -49
  247. package/dist/dev-ports.js.map +1 -1
  248. package/dist/dev-ready-panel.d.ts +5 -0
  249. package/dist/dev-ready-panel.d.ts.map +1 -1
  250. package/dist/dev-ready-panel.js +13 -0
  251. package/dist/dev-ready-panel.js.map +1 -1
  252. package/dist/dev-schema-watch.d.ts +19 -0
  253. package/dist/dev-schema-watch.d.ts.map +1 -0
  254. package/dist/dev-schema-watch.js +49 -0
  255. package/dist/dev-schema-watch.js.map +1 -0
  256. package/dist/dev-session-lock.d.ts +30 -1
  257. package/dist/dev-session-lock.d.ts.map +1 -1
  258. package/dist/dev-session-lock.js +83 -10
  259. package/dist/dev-session-lock.js.map +1 -1
  260. package/dist/dev-shutdown.d.ts +17 -3
  261. package/dist/dev-shutdown.d.ts.map +1 -1
  262. package/dist/dev-shutdown.js +48 -4
  263. package/dist/dev-shutdown.js.map +1 -1
  264. package/dist/diff-output.d.ts +71 -3
  265. package/dist/diff-output.d.ts.map +1 -1
  266. package/dist/diff-output.js +173 -18
  267. package/dist/diff-output.js.map +1 -1
  268. package/dist/docker-env.d.ts +16 -0
  269. package/dist/docker-env.d.ts.map +1 -0
  270. package/dist/docker-env.js +16 -0
  271. package/dist/docker-env.js.map +1 -0
  272. package/dist/docker-postgres.d.ts.map +1 -1
  273. package/dist/docker-postgres.js +14 -9
  274. package/dist/docker-postgres.js.map +1 -1
  275. package/dist/drift-consent.d.ts +36 -0
  276. package/dist/drift-consent.d.ts.map +1 -0
  277. package/dist/drift-consent.js +78 -0
  278. package/dist/drift-consent.js.map +1 -0
  279. package/dist/engine-answers.d.ts +51 -0
  280. package/dist/engine-answers.d.ts.map +1 -0
  281. package/dist/engine-answers.js +183 -0
  282. package/dist/engine-answers.js.map +1 -0
  283. package/dist/engine-client.d.ts +156 -9
  284. package/dist/engine-client.d.ts.map +1 -1
  285. package/dist/engine-client.js +315 -129
  286. package/dist/engine-client.js.map +1 -1
  287. package/dist/engine-floor.d.ts +10 -0
  288. package/dist/engine-floor.d.ts.map +1 -1
  289. package/dist/engine-floor.js +28 -0
  290. package/dist/engine-floor.js.map +1 -1
  291. package/dist/engine-json-line.d.ts +9 -0
  292. package/dist/engine-json-line.d.ts.map +1 -0
  293. package/dist/engine-json-line.js +23 -0
  294. package/dist/engine-json-line.js.map +1 -0
  295. package/dist/engine-ownership-gate.d.ts +79 -0
  296. package/dist/engine-ownership-gate.d.ts.map +1 -0
  297. package/dist/engine-ownership-gate.js +213 -0
  298. package/dist/engine-ownership-gate.js.map +1 -0
  299. package/dist/engine-push-output.d.ts +23 -2
  300. package/dist/engine-push-output.d.ts.map +1 -1
  301. package/dist/engine-push-output.js +22 -15
  302. package/dist/engine-push-output.js.map +1 -1
  303. package/dist/env-file.d.ts +15 -2
  304. package/dist/env-file.d.ts.map +1 -1
  305. package/dist/env-file.js +61 -22
  306. package/dist/env-file.js.map +1 -1
  307. package/dist/error-message.d.ts +5 -0
  308. package/dist/error-message.d.ts.map +1 -0
  309. package/dist/error-message.js +11 -0
  310. package/dist/error-message.js.map +1 -0
  311. package/dist/field-bounds.d.ts +8 -2
  312. package/dist/field-bounds.d.ts.map +1 -1
  313. package/dist/field-bounds.js +9 -15
  314. package/dist/field-bounds.js.map +1 -1
  315. package/dist/field-masking-tier.d.ts +4 -3
  316. package/dist/field-masking-tier.d.ts.map +1 -1
  317. package/dist/field-masking-tier.js +36 -13
  318. package/dist/field-masking-tier.js.map +1 -1
  319. package/dist/functions-deno-types.d.ts +8 -8
  320. package/dist/functions-deno-types.d.ts.map +1 -1
  321. package/dist/functions-deno-types.js +53 -25
  322. package/dist/functions-deno-types.js.map +1 -1
  323. package/dist/functions-router-gen.d.ts +21 -2
  324. package/dist/functions-router-gen.d.ts.map +1 -1
  325. package/dist/functions-router-gen.js +89 -18
  326. package/dist/functions-router-gen.js.map +1 -1
  327. package/dist/functions-template.d.ts +10 -0
  328. package/dist/functions-template.d.ts.map +1 -0
  329. package/dist/functions-template.js +39 -0
  330. package/dist/functions-template.js.map +1 -0
  331. package/dist/hooks-generator.d.ts.map +1 -1
  332. package/dist/hooks-generator.js +110 -83
  333. package/dist/hooks-generator.js.map +1 -1
  334. package/dist/host-database.d.ts +46 -5
  335. package/dist/host-database.d.ts.map +1 -1
  336. package/dist/host-database.js +72 -15
  337. package/dist/host-database.js.map +1 -1
  338. package/dist/index.d.ts +2 -1
  339. package/dist/index.d.ts.map +1 -1
  340. package/dist/index.js +1 -1
  341. package/dist/index.js.map +1 -1
  342. package/dist/init-dependency-versions.d.ts.map +1 -1
  343. package/dist/init-dependency-versions.js +8 -1
  344. package/dist/init-dependency-versions.js.map +1 -1
  345. package/dist/init-project-detect.d.ts.map +1 -1
  346. package/dist/init-project-detect.js +3 -2
  347. package/dist/init-project-detect.js.map +1 -1
  348. package/dist/json-file.d.ts +15 -0
  349. package/dist/json-file.d.ts.map +1 -0
  350. package/dist/json-file.js +38 -0
  351. package/dist/json-file.js.map +1 -0
  352. package/dist/json-type-text.d.ts +18 -0
  353. package/dist/json-type-text.d.ts.map +1 -0
  354. package/dist/json-type-text.js +112 -0
  355. package/dist/json-type-text.js.map +1 -0
  356. package/dist/jwt-secret-length.d.ts +22 -0
  357. package/dist/jwt-secret-length.d.ts.map +1 -0
  358. package/dist/jwt-secret-length.js +36 -0
  359. package/dist/jwt-secret-length.js.map +1 -0
  360. package/dist/jwt.d.ts +5 -0
  361. package/dist/jwt.d.ts.map +1 -1
  362. package/dist/jwt.js +25 -1
  363. package/dist/jwt.js.map +1 -1
  364. package/dist/link.d.ts +5 -1
  365. package/dist/link.d.ts.map +1 -1
  366. package/dist/link.js +47 -5
  367. package/dist/link.js.map +1 -1
  368. package/dist/local-gateway.d.ts +9 -0
  369. package/dist/local-gateway.d.ts.map +1 -1
  370. package/dist/local-gateway.js +16 -0
  371. package/dist/local-gateway.js.map +1 -1
  372. package/dist/local-secrets.d.ts +84 -2
  373. package/dist/local-secrets.d.ts.map +1 -1
  374. package/dist/local-secrets.js +115 -5
  375. package/dist/local-secrets.js.map +1 -1
  376. package/dist/local-stack.d.ts +30 -0
  377. package/dist/local-stack.d.ts.map +1 -0
  378. package/dist/local-stack.js +81 -0
  379. package/dist/local-stack.js.map +1 -0
  380. package/dist/mailer-autoconfirm.d.ts +37 -0
  381. package/dist/mailer-autoconfirm.d.ts.map +1 -0
  382. package/dist/mailer-autoconfirm.js +69 -0
  383. package/dist/mailer-autoconfirm.js.map +1 -0
  384. package/dist/model-cache.d.ts +6 -2
  385. package/dist/model-cache.d.ts.map +1 -1
  386. package/dist/model-cache.js +33 -27
  387. package/dist/model-cache.js.map +1 -1
  388. package/dist/model-hooks.d.ts +7 -6
  389. package/dist/model-hooks.d.ts.map +1 -1
  390. package/dist/model-hooks.js +83 -138
  391. package/dist/model-hooks.js.map +1 -1
  392. package/dist/model-versioning.d.ts +7 -1
  393. package/dist/model-versioning.d.ts.map +1 -1
  394. package/dist/model-versioning.js +24 -27
  395. package/dist/model-versioning.js.map +1 -1
  396. package/dist/native-dev-env.d.ts +39 -0
  397. package/dist/native-dev-env.d.ts.map +1 -0
  398. package/dist/native-dev-env.js +50 -0
  399. package/dist/native-dev-env.js.map +1 -0
  400. package/dist/native-functions-watch.d.ts +11 -0
  401. package/dist/native-functions-watch.d.ts.map +1 -0
  402. package/dist/native-functions-watch.js +59 -0
  403. package/dist/native-functions-watch.js.map +1 -0
  404. package/dist/native-keyspace.d.ts +23 -0
  405. package/dist/native-keyspace.d.ts.map +1 -0
  406. package/dist/native-keyspace.js +53 -0
  407. package/dist/native-keyspace.js.map +1 -0
  408. package/dist/native-pg-auth.d.ts +46 -0
  409. package/dist/native-pg-auth.d.ts.map +1 -0
  410. package/dist/native-pg-auth.js +107 -0
  411. package/dist/native-pg-auth.js.map +1 -0
  412. package/dist/native-realtime.d.ts +26 -0
  413. package/dist/native-realtime.d.ts.map +1 -0
  414. package/dist/native-realtime.js +43 -0
  415. package/dist/native-realtime.js.map +1 -0
  416. package/dist/native-roles-sql.d.ts +27 -0
  417. package/dist/native-roles-sql.d.ts.map +1 -0
  418. package/dist/native-roles-sql.js +73 -0
  419. package/dist/native-roles-sql.js.map +1 -0
  420. package/dist/owner-default.d.ts +19 -0
  421. package/dist/owner-default.d.ts.map +1 -0
  422. package/dist/owner-default.js +42 -0
  423. package/dist/owner-default.js.map +1 -0
  424. package/dist/package-json.d.ts +20 -0
  425. package/dist/package-json.d.ts.map +1 -0
  426. package/dist/package-json.js +29 -0
  427. package/dist/package-json.js.map +1 -0
  428. package/dist/parent-watch.d.ts +40 -0
  429. package/dist/parent-watch.d.ts.map +1 -0
  430. package/dist/parent-watch.js +75 -0
  431. package/dist/parent-watch.js.map +1 -0
  432. package/dist/postgres-ctl.d.ts +29 -6
  433. package/dist/postgres-ctl.d.ts.map +1 -1
  434. package/dist/postgres-ctl.js +67 -17
  435. package/dist/postgres-ctl.js.map +1 -1
  436. package/dist/postgres-image.d.ts +35 -0
  437. package/dist/postgres-image.d.ts.map +1 -0
  438. package/dist/postgres-image.js +127 -0
  439. package/dist/postgres-image.js.map +1 -0
  440. package/dist/postgrest-release.d.ts +25 -0
  441. package/dist/postgrest-release.d.ts.map +1 -0
  442. package/dist/postgrest-release.js +35 -0
  443. package/dist/postgrest-release.js.map +1 -0
  444. package/dist/project-config.d.ts +145 -17
  445. package/dist/project-config.d.ts.map +1 -1
  446. package/dist/project-config.js +271 -115
  447. package/dist/project-config.js.map +1 -1
  448. package/dist/project-name-override.d.ts +25 -0
  449. package/dist/project-name-override.d.ts.map +1 -0
  450. package/dist/project-name-override.js +52 -0
  451. package/dist/project-name-override.js.map +1 -0
  452. package/dist/pull-utils.d.ts +26 -3
  453. package/dist/pull-utils.d.ts.map +1 -1
  454. package/dist/pull-utils.js +44 -5
  455. package/dist/pull-utils.js.map +1 -1
  456. package/dist/push-audit.d.ts +39 -0
  457. package/dist/push-audit.d.ts.map +1 -0
  458. package/dist/push-audit.js +116 -0
  459. package/dist/push-audit.js.map +1 -0
  460. package/dist/push-refusal.d.ts +94 -0
  461. package/dist/push-refusal.d.ts.map +1 -0
  462. package/dist/push-refusal.js +275 -0
  463. package/dist/push-refusal.js.map +1 -0
  464. package/dist/recorded-field-masking-tier.d.ts +43 -0
  465. package/dist/recorded-field-masking-tier.d.ts.map +1 -0
  466. package/dist/recorded-field-masking-tier.js +88 -0
  467. package/dist/recorded-field-masking-tier.js.map +1 -0
  468. package/dist/rename-journal.d.ts +54 -0
  469. package/dist/rename-journal.d.ts.map +1 -0
  470. package/dist/rename-journal.js +150 -0
  471. package/dist/rename-journal.js.map +1 -0
  472. package/dist/resolve-api-url.d.ts.map +1 -1
  473. package/dist/resolve-api-url.js +4 -3
  474. package/dist/resolve-api-url.js.map +1 -1
  475. package/dist/resolve-target.d.ts +85 -26
  476. package/dist/resolve-target.d.ts.map +1 -1
  477. package/dist/resolve-target.js +214 -62
  478. package/dist/resolve-target.js.map +1 -1
  479. package/dist/rest-cache-admin.d.ts +9 -8
  480. package/dist/rest-cache-admin.d.ts.map +1 -1
  481. package/dist/rest-cache-admin.js +32 -9
  482. package/dist/rest-cache-admin.js.map +1 -1
  483. package/dist/rest-ready.d.ts +28 -0
  484. package/dist/rest-ready.d.ts.map +1 -0
  485. package/dist/rest-ready.js +53 -0
  486. package/dist/rest-ready.js.map +1 -0
  487. package/dist/restore-system-relation-targets.d.ts.map +1 -1
  488. package/dist/restore-system-relation-targets.js +49 -31
  489. package/dist/restore-system-relation-targets.js.map +1 -1
  490. package/dist/route-manifest.d.ts.map +1 -1
  491. package/dist/route-manifest.js +4 -10
  492. package/dist/route-manifest.js.map +1 -1
  493. package/dist/runtime-routes.d.ts.map +1 -1
  494. package/dist/runtime-routes.js +23 -28
  495. package/dist/runtime-routes.js.map +1 -1
  496. package/dist/schema-ast-v2.d.ts +35 -1
  497. package/dist/schema-ast-v2.d.ts.map +1 -1
  498. package/dist/schema-ast-v2.js +22 -7
  499. package/dist/schema-ast-v2.js.map +1 -1
  500. package/dist/schema-push-lock.d.ts.map +1 -1
  501. package/dist/schema-push-lock.js +14 -37
  502. package/dist/schema-push-lock.js.map +1 -1
  503. package/dist/schema-sources.d.ts +7 -1
  504. package/dist/schema-sources.d.ts.map +1 -1
  505. package/dist/schema-sources.js +19 -8
  506. package/dist/schema-sources.js.map +1 -1
  507. package/dist/seed-ir.d.ts.map +1 -1
  508. package/dist/seed-ir.js +30 -9
  509. package/dist/seed-ir.js.map +1 -1
  510. package/dist/seed-runner.d.ts.map +1 -1
  511. package/dist/seed-runner.js +26 -3
  512. package/dist/seed-runner.js.map +1 -1
  513. package/dist/seed.d.ts +31 -4
  514. package/dist/seed.d.ts.map +1 -1
  515. package/dist/seed.js +3 -1
  516. package/dist/seed.js.map +1 -1
  517. package/dist/self-host-compose.d.ts +66 -4
  518. package/dist/self-host-compose.d.ts.map +1 -1
  519. package/dist/self-host-compose.js +326 -102
  520. package/dist/self-host-compose.js.map +1 -1
  521. package/dist/shell-ports.d.ts +26 -0
  522. package/dist/shell-ports.d.ts.map +1 -0
  523. package/dist/shell-ports.js +56 -0
  524. package/dist/shell-ports.js.map +1 -0
  525. package/dist/storage-provision.d.ts +21 -4
  526. package/dist/storage-provision.d.ts.map +1 -1
  527. package/dist/storage-provision.js +12 -0
  528. package/dist/storage-provision.js.map +1 -1
  529. package/dist/studio-admin-roles.d.ts.map +1 -1
  530. package/dist/studio-admin-roles.js +2 -1
  531. package/dist/studio-admin-roles.js.map +1 -1
  532. package/dist/studio-auth-config.d.ts +22 -0
  533. package/dist/studio-auth-config.d.ts.map +1 -0
  534. package/dist/studio-auth-config.js +45 -0
  535. package/dist/studio-auth-config.js.map +1 -0
  536. package/dist/studio-roles.d.ts +13 -0
  537. package/dist/studio-roles.d.ts.map +1 -0
  538. package/dist/studio-roles.js +12 -0
  539. package/dist/studio-roles.js.map +1 -0
  540. package/dist/target-client.d.ts +13 -2
  541. package/dist/target-client.d.ts.map +1 -1
  542. package/dist/target-client.js +56 -40
  543. package/dist/target-client.js.map +1 -1
  544. package/dist/tsx-runner.d.ts +13 -0
  545. package/dist/tsx-runner.d.ts.map +1 -1
  546. package/dist/tsx-runner.js +36 -19
  547. package/dist/tsx-runner.js.map +1 -1
  548. package/dist/type-extractor.d.ts +2 -0
  549. package/dist/type-extractor.d.ts.map +1 -1
  550. package/dist/type-extractor.js +400 -96
  551. package/dist/type-extractor.js.map +1 -1
  552. package/dist/type-generation.d.ts +35 -5
  553. package/dist/type-generation.d.ts.map +1 -1
  554. package/dist/type-generation.js +57 -27
  555. package/dist/type-generation.js.map +1 -1
  556. package/dist/type-resolver.d.ts.map +1 -1
  557. package/dist/type-resolver.js +8 -1
  558. package/dist/type-resolver.js.map +1 -1
  559. package/dist/ui/clack-api.d.ts +3 -0
  560. package/dist/ui/clack-api.d.ts.map +1 -1
  561. package/dist/ui/clack-api.js +14 -7
  562. package/dist/ui/clack-api.js.map +1 -1
  563. package/dist/ui/clack.d.ts.map +1 -1
  564. package/dist/ui/clack.js +9 -7
  565. package/dist/ui/clack.js.map +1 -1
  566. package/dist/ui/components/PromptPanel.d.ts +1 -0
  567. package/dist/ui/components/PromptPanel.d.ts.map +1 -1
  568. package/dist/ui/components/PromptPanel.js +2 -1
  569. package/dist/ui/components/PromptPanel.js.map +1 -1
  570. package/dist/ui/confirm.d.ts +8 -0
  571. package/dist/ui/confirm.d.ts.map +1 -1
  572. package/dist/ui/confirm.js +12 -0
  573. package/dist/ui/confirm.js.map +1 -1
  574. package/dist/ui/dev/DevDashboard.d.ts.map +1 -1
  575. package/dist/ui/dev/DevDashboard.js +19 -4
  576. package/dist/ui/dev/DevDashboard.js.map +1 -1
  577. package/dist/ui/flows/FlowApp.d.ts.map +1 -1
  578. package/dist/ui/flows/FlowApp.js +17 -1
  579. package/dist/ui/flows/FlowApp.js.map +1 -1
  580. package/dist/ui/flows/prompt-fields.d.ts +13 -0
  581. package/dist/ui/flows/prompt-fields.d.ts.map +1 -1
  582. package/dist/ui/flows/prompt-fields.js +17 -4
  583. package/dist/ui/flows/prompt-fields.js.map +1 -1
  584. package/dist/ui/flows/types.d.ts +2 -1
  585. package/dist/ui/flows/types.d.ts.map +1 -1
  586. package/dist/ui/runtime/cancel.d.ts +5 -0
  587. package/dist/ui/runtime/cancel.d.ts.map +1 -1
  588. package/dist/ui/runtime/cancel.js +7 -0
  589. package/dist/ui/runtime/cancel.js.map +1 -1
  590. package/dist/ui/runtime/dev-prompt-queue.d.ts +5 -4
  591. package/dist/ui/runtime/dev-prompt-queue.d.ts.map +1 -1
  592. package/dist/ui/runtime/dev-prompt-queue.js +2 -5
  593. package/dist/ui/runtime/dev-prompt-queue.js.map +1 -1
  594. package/dist/ui/runtime/run-clack-flow.js.map +1 -1
  595. package/dist/unique-file-token.d.ts +10 -0
  596. package/dist/unique-file-token.d.ts.map +1 -0
  597. package/dist/unique-file-token.js +13 -0
  598. package/dist/unique-file-token.js.map +1 -0
  599. package/package.json +14 -4
  600. package/.turbo/turbo-build.log +0 -4
  601. package/.turbo/turbo-test.log +0 -583
  602. package/.turbo/turbo-typecheck.log +0 -4
  603. package/assets/supatype-logo-wordmark.ascii.txt +0 -6
  604. package/bin/dev-entry.ts +0 -3
  605. package/dist/supatype-eval-1781522769253.d.mts +0 -2
  606. package/dist/supatype-eval-1781522769253.d.mts.map +0 -1
  607. package/dist/supatype-eval-1781522769253.mjs +0 -3
  608. package/dist/supatype-eval-1781522769253.mjs.map +0 -1
  609. package/scripts/build-release-artifacts.sh +0 -112
  610. package/scripts/generate-homebrew-formula.mjs +0 -123
  611. package/scripts/mirror-deno-release.sh +0 -76
  612. package/src/TYPE-RESOLUTION.md +0 -294
  613. package/src/adopt-walkthrough.ts +0 -142
  614. package/src/api-config-cache.ts +0 -172
  615. package/src/app/framework.ts +0 -247
  616. package/src/app/proxy-dev-app.ts +0 -175
  617. package/src/app-config.ts +0 -208
  618. package/src/app-vite-env.ts +0 -27
  619. package/src/augmentation-generator.ts +0 -279
  620. package/src/binary-cache.ts +0 -998
  621. package/src/binary-download-lock.ts +0 -124
  622. package/src/cache-clean.ts +0 -81
  623. package/src/cache-identity-scope.ts +0 -92
  624. package/src/cache-pins.ts +0 -243
  625. package/src/cache-provider.ts +0 -61
  626. package/src/cli-artifacts.ts +0 -65
  627. package/src/cli-install-method.ts +0 -98
  628. package/src/cli-package-version.ts +0 -19
  629. package/src/cli-standalone.ts +0 -144
  630. package/src/cli-version-embedded.ts +0 -12
  631. package/src/cli.ts +0 -87
  632. package/src/client-generator.ts +0 -122
  633. package/src/cloud-credentials.ts +0 -183
  634. package/src/commands/add.ts +0 -105
  635. package/src/commands/admin.ts +0 -819
  636. package/src/commands/adopt.ts +0 -81
  637. package/src/commands/app.ts +0 -100
  638. package/src/commands/cache.ts +0 -233
  639. package/src/commands/cloud.ts +0 -299
  640. package/src/commands/db.ts +0 -301
  641. package/src/commands/deploy-types.ts +0 -49
  642. package/src/commands/deploy.ts +0 -464
  643. package/src/commands/dev.ts +0 -1217
  644. package/src/commands/diff.ts +0 -73
  645. package/src/commands/doctor.ts +0 -197
  646. package/src/commands/engine.ts +0 -31
  647. package/src/commands/functions.ts +0 -1010
  648. package/src/commands/generate.ts +0 -45
  649. package/src/commands/hooks.ts +0 -138
  650. package/src/commands/init.ts +0 -1537
  651. package/src/commands/internal.ts +0 -60
  652. package/src/commands/introspect.ts +0 -48
  653. package/src/commands/keys.ts +0 -269
  654. package/src/commands/link-helpers.ts +0 -281
  655. package/src/commands/login.ts +0 -127
  656. package/src/commands/logs.ts +0 -56
  657. package/src/commands/migrate-from-v1.ts +0 -132
  658. package/src/commands/migrate.ts +0 -231
  659. package/src/commands/pg.ts +0 -128
  660. package/src/commands/plugins.ts +0 -517
  661. package/src/commands/pull.ts +0 -46
  662. package/src/commands/push.ts +0 -427
  663. package/src/commands/seed.ts +0 -319
  664. package/src/commands/self-host.ts +0 -404
  665. package/src/commands/self-update.ts +0 -89
  666. package/src/commands/status.ts +0 -117
  667. package/src/commands/types.ts +0 -77
  668. package/src/commands/update.ts +0 -172
  669. package/src/components.ts +0 -6
  670. package/src/compose-local-server-image.ts +0 -85
  671. package/src/compose-rename.ts +0 -73
  672. package/src/compose-services.ts +0 -175
  673. package/src/config.ts +0 -276
  674. package/src/db-port.ts +0 -99
  675. package/src/db-preflight.ts +0 -663
  676. package/src/dev-compose.ts +0 -1650
  677. package/src/dev-db-reset.ts +0 -95
  678. package/src/dev-initial-push.ts +0 -134
  679. package/src/dev-log-bus.ts +0 -121
  680. package/src/dev-log-filter.ts +0 -74
  681. package/src/dev-logo.ts +0 -61
  682. package/src/dev-ports.ts +0 -271
  683. package/src/dev-ready-panel.ts +0 -80
  684. package/src/dev-session-lock.ts +0 -98
  685. package/src/dev-session.ts +0 -210
  686. package/src/dev-shutdown.ts +0 -159
  687. package/src/dev-task-colors.ts +0 -66
  688. package/src/diff-output.ts +0 -90
  689. package/src/docker-postgres.ts +0 -295
  690. package/src/docker-runtime.ts +0 -151
  691. package/src/engine-client.ts +0 -350
  692. package/src/engine-floor.ts +0 -261
  693. package/src/engine-push-output.ts +0 -98
  694. package/src/ensure-binary.ts +0 -68
  695. package/src/ensure-component-binaries.ts +0 -71
  696. package/src/ensure-dev-api-config.ts +0 -18
  697. package/src/env-file.ts +0 -183
  698. package/src/field-bounds.ts +0 -359
  699. package/src/field-masking-tier.ts +0 -107
  700. package/src/functions-context-refresh.ts +0 -25
  701. package/src/functions-deno-types.ts +0 -258
  702. package/src/functions-router-gen.ts +0 -256
  703. package/src/gitignore.ts +0 -76
  704. package/src/hook-upload.ts +0 -107
  705. package/src/hooks-generator.ts +0 -444
  706. package/src/host-database.ts +0 -176
  707. package/src/index.ts +0 -11
  708. package/src/init-dependency-versions.ts +0 -69
  709. package/src/init-package-json.ts +0 -63
  710. package/src/init-project-detect.ts +0 -99
  711. package/src/jwt.ts +0 -14
  712. package/src/kong-config.ts +0 -116
  713. package/src/link.ts +0 -250
  714. package/src/local-gateway.ts +0 -9
  715. package/src/local-secrets.ts +0 -104
  716. package/src/local-storage.ts +0 -14
  717. package/src/main.ts +0 -20
  718. package/src/model-cache.ts +0 -122
  719. package/src/model-hooks.ts +0 -430
  720. package/src/model-versioning.ts +0 -167
  721. package/src/pgbouncer-userlist.ts +0 -15
  722. package/src/postgres-ctl.ts +0 -333
  723. package/src/preview-config-check.ts +0 -52
  724. package/src/process-manager.ts +0 -224
  725. package/src/project-config.ts +0 -939
  726. package/src/prompts.ts +0 -2
  727. package/src/pull-utils.ts +0 -275
  728. package/src/realtime-launch.ts +0 -52
  729. package/src/release-pins.ts +0 -31
  730. package/src/release-public-key.ts +0 -12
  731. package/src/required-host-components.ts +0 -37
  732. package/src/resolve-api-url.ts +0 -44
  733. package/src/resolve-target.ts +0 -480
  734. package/src/rest-cache-admin.ts +0 -141
  735. package/src/restore-system-relation-targets.ts +0 -45
  736. package/src/retired-no-cache.ts +0 -27
  737. package/src/route-manifest.ts +0 -17
  738. package/src/runtime-routes.ts +0 -298
  739. package/src/schema-ast-v2.ts +0 -488
  740. package/src/schema-push-lock.ts +0 -170
  741. package/src/schema-sources.ts +0 -248
  742. package/src/scripts/postinstall.ts +0 -20
  743. package/src/seed-ir.ts +0 -311
  744. package/src/seed-runner.ts +0 -109
  745. package/src/seed.ts +0 -451
  746. package/src/self-host-compose.ts +0 -1246
  747. package/src/service-role-check.ts +0 -111
  748. package/src/storage-provision.ts +0 -90
  749. package/src/strict.ts +0 -40
  750. package/src/studio-admin-roles.ts +0 -30
  751. package/src/studio-dev-server.ts +0 -70
  752. package/src/supatype-eval-1781522769253.mts +0 -1
  753. package/src/systemd.ts +0 -137
  754. package/src/target-client.ts +0 -127
  755. package/src/tsx-runner.ts +0 -128
  756. package/src/type-extractor.ts +0 -3365
  757. package/src/type-generation.ts +0 -169
  758. package/src/type-resolver.ts +0 -457
  759. package/src/ui/README.md +0 -21
  760. package/src/ui/brand.ts +0 -6
  761. package/src/ui/clack-api.ts +0 -123
  762. package/src/ui/clack.ts +0 -153
  763. package/src/ui/components/FlowSpinner.tsx +0 -15
  764. package/src/ui/components/LogoWordmark.tsx +0 -36
  765. package/src/ui/components/PromptPanel.tsx +0 -17
  766. package/src/ui/components/SelectField.tsx +0 -58
  767. package/src/ui/confirm.ts +0 -39
  768. package/src/ui/dev/DevDashboard.tsx +0 -223
  769. package/src/ui/dev/DevReadyPanelView.tsx +0 -134
  770. package/src/ui/fatal.ts +0 -38
  771. package/src/ui/flows/FlowApp.tsx +0 -69
  772. package/src/ui/flows/prompt-fields.tsx +0 -198
  773. package/src/ui/flows/types.ts +0 -50
  774. package/src/ui/index.ts +0 -8
  775. package/src/ui/interactive.ts +0 -4
  776. package/src/ui/messages.ts +0 -85
  777. package/src/ui/next-steps.ts +0 -10
  778. package/src/ui/progress.ts +0 -39
  779. package/src/ui/prompts.ts +0 -48
  780. package/src/ui/runtime/cancel.ts +0 -6
  781. package/src/ui/runtime/command-chrome.ts +0 -147
  782. package/src/ui/runtime/dev-prompt-queue.ts +0 -84
  783. package/src/ui/runtime/flow-session.ts +0 -11
  784. package/src/ui/runtime/run-clack-flow.tsx +0 -65
  785. package/src/ui/runtime/stdin-after-ink.ts +0 -20
  786. package/src/ui/theme.ts +0 -41
  787. package/src/valkey-sidecar.ts +0 -126
  788. package/tests/access-composition.test.ts +0 -790
  789. package/tests/admin-ensure.test.ts +0 -139
  790. package/tests/admin-studio-membership.test.ts +0 -121
  791. package/tests/adopt-result.test.ts +0 -27
  792. package/tests/adopt-walkthrough.test.ts +0 -129
  793. package/tests/api-config-cache-seed.test.ts +0 -180
  794. package/tests/api-schemas.test.ts +0 -83
  795. package/tests/app-command.test.ts +0 -64
  796. package/tests/archive-name-alias.test.ts +0 -42
  797. package/tests/ast-derived-outputs.test.ts +0 -92
  798. package/tests/augmentation-generator.test.ts +0 -393
  799. package/tests/binary-cache-cloud-overrides.test.ts +0 -123
  800. package/tests/binary-download-lock.test.ts +0 -41
  801. package/tests/cache-clean.test.ts +0 -206
  802. package/tests/cache-identity-scope.test.ts +0 -61
  803. package/tests/cache-provider-config.test.ts +0 -132
  804. package/tests/cached-artifact-format.test.ts +0 -84
  805. package/tests/cli-help.test.ts +0 -170
  806. package/tests/cli-install-method.test.ts +0 -66
  807. package/tests/cli-package-version.test.ts +0 -15
  808. package/tests/client-generator.test.ts +0 -103
  809. package/tests/command-chrome-coverage.test.ts +0 -154
  810. package/tests/command-chrome-wrap.test.ts +0 -52
  811. package/tests/compose-parsable-defaults.test.ts +0 -60
  812. package/tests/compose-services.test.ts +0 -144
  813. package/tests/config-load-failure.test.ts +0 -44
  814. package/tests/config.test.ts +0 -301
  815. package/tests/db-port.test.ts +0 -128
  816. package/tests/db-preflight.test.ts +0 -152
  817. package/tests/db-published-and-addressable.test.ts +0 -69
  818. package/tests/dev-db-reset.test.ts +0 -162
  819. package/tests/dev-initial-push.test.ts +0 -142
  820. package/tests/dev-ports-owner.test.ts +0 -40
  821. package/tests/dev-ports.test.ts +0 -41
  822. package/tests/dev-ready-panel.test.ts +0 -37
  823. package/tests/dev-session-lock.test.ts +0 -54
  824. package/tests/dev-ui.test.ts +0 -202
  825. package/tests/docker-postgres.test.ts +0 -39
  826. package/tests/docker-runtime.test.ts +0 -225
  827. package/tests/doctor-render.test.ts +0 -62
  828. package/tests/doctor-service-role.test.ts +0 -55
  829. package/tests/engine-floor.test.ts +0 -238
  830. package/tests/engine-push-output.test.ts +0 -96
  831. package/tests/ensure-binary.test.ts +0 -59
  832. package/tests/ensure-dev-api-config.test.ts +0 -22
  833. package/tests/env-file.test.ts +0 -121
  834. package/tests/external-database-compose.test.ts +0 -262
  835. package/tests/external-database-config.test.ts +0 -154
  836. package/tests/field-bounds-matrix.test.ts +0 -163
  837. package/tests/field-bounds.test.ts +0 -139
  838. package/tests/field-masking-tier.test.ts +0 -184
  839. package/tests/field-validators.test.ts +0 -139
  840. package/tests/fixtures/identity-scope-corpus.json +0 -42
  841. package/tests/fixtures/seed_golden_ir.json +0 -186
  842. package/tests/functions-concurrency.test.ts +0 -71
  843. package/tests/functions-context-refresh.test.ts +0 -86
  844. package/tests/functions-deno-types.test.ts +0 -197
  845. package/tests/gitignore-secrets.test.ts +0 -90
  846. package/tests/homebrew-formula.test.ts +0 -100
  847. package/tests/hook-upload.test.ts +0 -125
  848. package/tests/hooks-generator.test.ts +0 -298
  849. package/tests/host-connection-targets.test.ts +0 -84
  850. package/tests/host-database.test.ts +0 -176
  851. package/tests/init-dependency-versions.test.ts +0 -62
  852. package/tests/init-package-json.test.ts +0 -18
  853. package/tests/init-project-detect.test.ts +0 -53
  854. package/tests/init.test.ts +0 -369
  855. package/tests/keys-write.test.ts +0 -148
  856. package/tests/keys.test.ts +0 -166
  857. package/tests/link.test.ts +0 -148
  858. package/tests/local-secrets.test.ts +0 -92
  859. package/tests/local-server-image-env.test.ts +0 -93
  860. package/tests/migrate-from-v1.test.ts +0 -29
  861. package/tests/minisign.test.ts +0 -102
  862. package/tests/model-cache-declaration.test.ts +0 -229
  863. package/tests/model-cache-manifest.test.ts +0 -99
  864. package/tests/model-constraints.test.ts +0 -293
  865. package/tests/model-hooks.test.ts +0 -433
  866. package/tests/model-versions.test.ts +0 -229
  867. package/tests/native-keyspace.test.ts +0 -130
  868. package/tests/normalize-admin-config.test.ts +0 -48
  869. package/tests/pg-spawn-env.test.ts +0 -18
  870. package/tests/port-in-use.test.ts +0 -58
  871. package/tests/postgres-archive-tag.test.ts +0 -9
  872. package/tests/preview-config-check.test.ts +0 -104
  873. package/tests/proxy-dev-app.test.ts +0 -77
  874. package/tests/pull-utils.test.ts +0 -151
  875. package/tests/readiness-poll.test.ts +0 -84
  876. package/tests/realtime-launch.test.ts +0 -25
  877. package/tests/release-pins.test.ts +0 -28
  878. package/tests/required-host-components.test.ts +0 -53
  879. package/tests/resolve-api-url.test.ts +0 -23
  880. package/tests/rest-cache-admin.test.ts +0 -64
  881. package/tests/retired-no-cache.test.ts +0 -46
  882. package/tests/route-manifest.test.ts +0 -29
  883. package/tests/runtime-contract.test.ts +0 -948
  884. package/tests/schema-sources.test.ts +0 -119
  885. package/tests/seed-discover.test.ts +0 -31
  886. package/tests/seed-ir.test.ts +0 -436
  887. package/tests/self-host-keys.test.ts +0 -92
  888. package/tests/service-role-check.test.ts +0 -109
  889. package/tests/service-role-routes.test.ts +0 -51
  890. package/tests/stdin-after-ink.test.ts +0 -8
  891. package/tests/storage-provision.test.ts +0 -100
  892. package/tests/strict.test.ts +0 -78
  893. package/tests/studio-admin-roles.test.ts +0 -59
  894. package/tests/target-client-refresh.test.ts +0 -94
  895. package/tests/tsconfig.json +0 -15
  896. package/tests/tsx-runner.test.ts +0 -66
  897. package/tests/type-extractor.test.ts +0 -1601
  898. package/tests/type-resolver.test.ts +0 -59
  899. package/tests/ui-confirm.test.ts +0 -45
  900. package/tests/ui-messages.test.ts +0 -52
  901. package/tsconfig.json +0 -11
  902. package/tsconfig.tsbuildinfo +0 -1
  903. package/vitest.config.ts +0 -21
@@ -1,3365 +0,0 @@
1
- import { existsSync, readFileSync, realpathSync } from "node:fs"
2
- import { createHash } from "node:crypto"
3
- import { dirname, isAbsolute, relative, resolve } from "node:path"
4
- import ts from "typescript"
5
- import { isIdentityDependent, type AccessRuleNode } from "./cache-identity-scope.js"
6
- import {
7
- applyImportRename,
8
- createResolveContext,
9
- needsChecker,
10
- resolveTypeNode,
11
- tryResolveTypeReference,
12
- unknownTypeError,
13
- type ResolveContext,
14
- } from "./type-resolver.js"
15
-
16
- import {
17
- emitField,
18
- emitModel,
19
- emitSchema,
20
- defaultPgTypeForKind,
21
- scalar,
22
- type BlockDefinitionAst,
23
- type ExtractedSchemaAstV2,
24
- type ExtractedStorageBucketAst,
25
- type FieldAstV2,
26
- type KernelFieldFacts,
27
- type FieldKind,
28
- type ParsedField,
29
- } from "./schema-ast-v2.js"
30
- import { compileBounds, measureFormFor, type DeclaredBounds } from "./field-bounds.js"
31
-
32
- export type { ExtractedSchemaAstV2 as ExtractedSchemaAst, ExtractedStorageBucketAst } from "./schema-ast-v2.js"
33
-
34
- interface FieldParseContext {
35
- autoLocalize?: boolean
36
- }
37
-
38
- export function extractSchemaAstFromTypes(
39
- schemaPath: string,
40
- cwd: string = process.cwd(),
41
- ): ExtractedSchemaAstV2 | null {
42
- const absPath = resolve(cwd, schemaPath)
43
- if (!existsSync(absPath)) {
44
- throw new Error(`Schema file not found: ${absPath}`)
45
- }
46
-
47
- const sourceFiles = loadSchemaSourceFiles(absPath)
48
- const resolveCtx = createResolveContext(sourceFiles)
49
- const bucketAliases = new Map<string, string>()
50
- const bucketsById = new Map<string, ExtractedStorageBucketAst>()
51
- for (const sourceFile of sourceFiles) {
52
- const bucketContext = collectBucketContext(sourceFile, resolveCtx)
53
- for (const [alias, bucketId] of bucketContext.aliases) {
54
- bucketAliases.set(alias, bucketId)
55
- }
56
- for (const [bucketId, bucket] of bucketContext.bucketsById) {
57
- const existing = bucketsById.get(bucketId)
58
- if (existing !== undefined && !bucketsEqual(existing, bucket)) {
59
- throw new Error(
60
- `Conflicting Bucket<> declarations for id "${bucketId}". Use a single export per bucket id.`,
61
- )
62
- }
63
- bucketsById.set(bucketId, bucket)
64
- }
65
- }
66
-
67
- const blockAliases = new Map<string, BlockDefinitionAst>()
68
- for (const sourceFile of sourceFiles) {
69
- const next = collectBlockAliases(sourceFile, bucketAliases, bucketsById, resolveCtx)
70
- for (const [name, block] of next) {
71
- blockAliases.set(name, block)
72
- }
73
- }
74
-
75
- const models: ExtractedSchemaAstV2["models"] = []
76
-
77
- for (const sourceFile of sourceFiles) {
78
- for (const stmt of sourceFile.statements) {
79
- if (!ts.isTypeAliasDeclaration(stmt)) continue
80
- if (!hasExportModifier(stmt)) continue
81
- if (!ts.isTypeReferenceNode(stmt.type)) continue
82
- const modelTypeName = stmt.type.typeName.getText(sourceFile)
83
- if (modelTypeName !== "Model" && modelTypeName !== "LocalizedModel") continue
84
- const [fieldsArg, metaArg] = stmt.type.typeArguments ?? []
85
- if (!fieldsArg) continue
86
- const fieldsLiteral = unwrapModelFields(fieldsArg, sourceFile, resolveCtx)
87
- if (!fieldsLiteral) continue
88
-
89
- const metaHints = parseMetaLiteral(metaArg, sourceFile)
90
- const fieldContext: FieldParseContext = {
91
- autoLocalize: modelTypeName === "LocalizedModel" || metaHints.autoLocalize === true,
92
- }
93
-
94
- const fields: Record<string, FieldAstV2> = {}
95
- for (const member of fieldsLiteral.members) {
96
- if (!ts.isPropertySignature(member) || !member.type) continue
97
- const name = getPropertyName(member.name)
98
- if (!name) continue
99
- fields[name] = parseFieldType(
100
- name,
101
- member.type,
102
- sourceFile,
103
- blockAliases,
104
- bucketAliases,
105
- bucketsById,
106
- fieldContext,
107
- resolveCtx,
108
- )
109
- }
110
-
111
- const {
112
- tableName,
113
- access,
114
- options,
115
- indexes,
116
- constraints,
117
- hooks,
118
- validators,
119
- searchFields,
120
- cache,
121
- } =
122
- parseModelMeta(
123
- metaArg,
124
- sourceFile,
125
- stmt.name.text,
126
- fieldsArg,
127
- fields,
128
- resolveCtx,
129
- )
130
-
131
- models.push(
132
- emitModel(
133
- stmt.name.text,
134
- fields,
135
- options,
136
- tableName,
137
- access,
138
- indexes,
139
- hooks,
140
- constraints,
141
- validators,
142
- searchFields,
143
- cache,
144
- ),
145
- )
146
- }
147
- }
148
-
149
- if (models.length === 0) return null
150
-
151
- const storageBuckets =
152
- bucketsById.size > 0 ? [...bucketsById.values()].sort((a, b) => a.id.localeCompare(b.id)) : undefined
153
-
154
- let localeConfig: { locales: string[]; defaultLocale: string } | undefined
155
- for (const sourceFile of sourceFiles) {
156
- const found = collectLocaleConfig(sourceFile)
157
- if (!found) continue
158
- if (localeConfig !== undefined) {
159
- throw new Error(
160
- "Conflicting LocaleConfig declarations. Export at most one `localeConfig` type alias.",
161
- )
162
- }
163
- localeConfig = found
164
- }
165
-
166
- return emitSchema(models, {
167
- ...(storageBuckets !== undefined && storageBuckets.length > 0 && { storageBuckets }),
168
- ...(localeConfig !== undefined && {
169
- locales: localeConfig.locales,
170
- defaultLocale: localeConfig.defaultLocale,
171
- }),
172
- })
173
- }
174
-
175
- export interface SchemaSourceFile {
176
- relativePath: string
177
- absolutePath: string
178
- sha256: string
179
- bytes: number
180
- }
181
-
182
- export interface SchemaSourceGraph {
183
- entryPoint: string
184
- files: SchemaSourceFile[]
185
- }
186
-
187
- export function collectSchemaSourcePaths(entryAbsPath: string, projectRoot: string): SchemaSourceGraph {
188
- const root = resolve(projectRoot)
189
- const entryReal = realpathSync(entryAbsPath)
190
- const entryPoint = relative(root, entryReal).replace(/\\/g, "/")
191
- if (entryPoint.startsWith("..")) {
192
- throw new Error(`Schema entry must be under project root: ${entryAbsPath}`)
193
- }
194
-
195
- const absolutePaths = walkSchemaSourceAbsPaths(entryReal)
196
- const files: SchemaSourceFile[] = []
197
-
198
- for (const abs of absolutePaths) {
199
- const real = realpathSync(abs)
200
- const rel = relative(root, real).replace(/\\/g, "/")
201
- if (rel.startsWith("..")) {
202
- throw new Error(`Schema source escapes project root: ${abs}`)
203
- }
204
- const content = readFileSync(real)
205
- files.push({
206
- relativePath: rel,
207
- absolutePath: real,
208
- sha256: createHash("sha256").update(content).digest("hex"),
209
- bytes: content.length,
210
- })
211
- }
212
-
213
- files.sort((a, b) => a.relativePath.localeCompare(b.relativePath))
214
- return { entryPoint, files }
215
- }
216
-
217
- function walkSchemaSourceAbsPaths(entryPath: string): string[] {
218
- const visited = new Set<string>()
219
- const paths: string[] = []
220
- const queue: string[] = [entryPath]
221
-
222
- while (queue.length > 0) {
223
- const currentPath = queue.shift()
224
- if (!currentPath) continue
225
- if (visited.has(currentPath)) continue
226
- visited.add(currentPath)
227
- if (!existsSync(currentPath)) continue
228
- paths.push(currentPath)
229
-
230
- const sourceText = readFileSync(currentPath, "utf8")
231
- const sourceFile = ts.createSourceFile(currentPath, sourceText, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
232
- const baseDir = dirname(currentPath)
233
- for (const stmt of sourceFile.statements) {
234
- let specifier: string | undefined
235
- if (ts.isExportDeclaration(stmt)) {
236
- if (!stmt.moduleSpecifier || !ts.isStringLiteral(stmt.moduleSpecifier)) continue
237
- specifier = stmt.moduleSpecifier.text
238
- } else if (ts.isImportDeclaration(stmt)) {
239
- if (!stmt.moduleSpecifier || !ts.isStringLiteral(stmt.moduleSpecifier)) continue
240
- specifier = stmt.moduleSpecifier.text
241
- } else {
242
- continue
243
- }
244
- if (!specifier.startsWith(".")) continue
245
- const nextPath = resolveTypeModulePath(baseDir, specifier)
246
- if (!nextPath) continue
247
- if (!visited.has(nextPath)) queue.push(nextPath)
248
- }
249
- }
250
-
251
- return paths
252
- }
253
-
254
- function loadSchemaSourceFiles(entryPath: string): ts.SourceFile[] {
255
- return walkSchemaSourceAbsPaths(entryPath).map((abs) => {
256
- const sourceText = readFileSync(abs, "utf8")
257
- return ts.createSourceFile(abs, sourceText, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS)
258
- })
259
- }
260
-
261
- function resolveTypeModulePath(fromDir: string, specifier: string): string | null {
262
- const basePath = isAbsolute(specifier) ? specifier : resolve(fromDir, specifier)
263
- const candidates = specifier.endsWith(".js")
264
- ? [
265
- basePath,
266
- basePath.replace(/\.js$/i, ".ts"),
267
- basePath.replace(/\.js$/i, ".tsx"),
268
- basePath.replace(/\.js$/i, ".d.ts"),
269
- ]
270
- : [
271
- basePath,
272
- `${basePath}.ts`,
273
- `${basePath}.tsx`,
274
- `${basePath}.d.ts`,
275
- resolve(basePath, "index.ts"),
276
- resolve(basePath, "index.tsx"),
277
- resolve(basePath, "index.d.ts"),
278
- ]
279
-
280
- for (const candidate of candidates) {
281
- if (existsSync(candidate)) return candidate
282
- }
283
- return null
284
- }
285
-
286
- function hasExportModifier(node: ts.Node): boolean {
287
- if (!ts.canHaveModifiers(node)) return false
288
- return (ts.getModifiers(node)?.some((mod) => mod.kind === ts.SyntaxKind.ExportKeyword) ?? false)
289
- }
290
-
291
- function getPropertyName(name: ts.PropertyName): string | null {
292
- if (ts.isIdentifier(name) || ts.isStringLiteral(name) || ts.isNumericLiteral(name)) return name.text
293
- return null
294
- }
295
-
296
- /**
297
- * Known @supatype/types intersection mixins and the field source text they contribute.
298
- * Used when a mixin type can't be resolved from the local alias registry
299
- * (it comes from the external @supatype/types package, not a local file).
300
- */
301
- const KNOWN_MIXIN_SOURCES: Record<string, string> = {
302
- Timestamps: "{ created_at: ServerDefault<Date>; updated_at: ServerDefault<Date> }",
303
- SoftDelete: "{ deleted_at: Optional<Date> }",
304
- Publishable: "{ published_at: Optional<Date> }",
305
- }
306
-
307
- function synthesizeTypeLiteralMembers(source: string): ts.TypeElement[] {
308
- const synth = ts.createSourceFile(
309
- "__synth__.ts",
310
- `type __T__ = ${source}`,
311
- ts.ScriptTarget.Latest,
312
- true,
313
- ts.ScriptKind.TS,
314
- )
315
- const decl = synth.statements[0]
316
- if (!decl || !ts.isTypeAliasDeclaration(decl) || !ts.isTypeLiteralNode(decl.type)) return []
317
- return [...decl.type.members]
318
- }
319
-
320
- function mergeIntersectionParts(
321
- parts: readonly ts.TypeNode[],
322
- sourceFile: ts.SourceFile,
323
- resolveCtx: ResolveContext,
324
- depth: number,
325
- ): ts.TypeLiteralNode | null {
326
- const allMembers: ts.TypeElement[] = []
327
- for (const part of parts) {
328
- const resolved = unwrapModelFields(part, sourceFile, resolveCtx, depth + 1)
329
- if (resolved) {
330
- allMembers.push(...resolved.members)
331
- continue
332
- }
333
- // Fall back to known @supatype/types intersection mixins (Timestamps, SoftDelete, Publishable)
334
- if (ts.isTypeReferenceNode(part) && ts.isIdentifier(part.typeName)) {
335
- const typeName = applyImportRename(part.typeName.text, sourceFile, resolveCtx.renameMap)
336
- const mixinSource = KNOWN_MIXIN_SOURCES[typeName]
337
- if (mixinSource) {
338
- allMembers.push(...synthesizeTypeLiteralMembers(mixinSource))
339
- continue
340
- }
341
- }
342
- // Unresolvable parts are skipped, the model still extracts with whatever fields were found
343
- }
344
- if (allMembers.length === 0) return null
345
- return ts.factory.createTypeLiteralNode(allMembers)
346
- }
347
-
348
- function unwrapModelFields(
349
- typeNode: ts.TypeNode,
350
- sourceFile: ts.SourceFile,
351
- resolveCtx: ResolveContext,
352
- depth = 0,
353
- ): ts.TypeLiteralNode | null {
354
- if (depth > 16) return null
355
- if (ts.isTypeLiteralNode(typeNode)) return typeNode
356
-
357
- // Handle intersection types: `{ …fields } & Timestamps`, `{ …fields } & SoftDelete`, etc.
358
- if (ts.isIntersectionTypeNode(typeNode)) {
359
- return mergeIntersectionParts(typeNode.types, sourceFile, resolveCtx, depth)
360
- }
361
-
362
- if (needsChecker(typeNode)) {
363
- const resolved = resolveTypeNode(typeNode, sourceFile, resolveCtx)
364
- if (ts.isTypeLiteralNode(resolved)) return resolved
365
- return unwrapModelFields(resolved, sourceFile, resolveCtx, depth + 1)
366
- }
367
-
368
- if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return null
369
-
370
- const typeName = applyImportRename(typeNode.typeName.text, sourceFile, resolveCtx.renameMap)
371
-
372
- // Composite helpers in @supatype/types wrap the concrete field object.
373
- if (
374
- typeName === "WithTimestamps" ||
375
- typeName === "WithSoftDelete" ||
376
- typeName === "WithPublishable"
377
- ) {
378
- const inner = typeNode.typeArguments?.[0]
379
- if (!inner) return null
380
- return unwrapModelFields(inner, sourceFile, resolveCtx, depth + 1)
381
- }
382
-
383
- const expanded = tryResolveTypeReference(typeNode, sourceFile, resolveCtx)
384
- if (expanded) {
385
- if (ts.isTypeLiteralNode(expanded)) return expanded
386
- return unwrapModelFields(expanded, sourceFile, resolveCtx, depth + 1)
387
- }
388
-
389
- return null
390
- }
391
-
392
- /** Parse `Default<T, V>` second type argument into a JSON-serializable literal. */
393
- function parseDefaultLiteral(
394
- node: ts.TypeNode,
395
- sourceFile: ts.SourceFile,
396
- ): string | number | boolean | null | undefined {
397
- if (ts.isLiteralTypeNode(node)) {
398
- const lit = node.literal
399
- if (ts.isStringLiteral(lit) || ts.isNoSubstitutionTemplateLiteral(lit)) return lit.text
400
- if (ts.isNumericLiteral(lit)) return Number(lit.text)
401
- if (lit.kind === ts.SyntaxKind.TrueKeyword) return true
402
- if (lit.kind === ts.SyntaxKind.FalseKeyword) return false
403
- if (lit.kind === ts.SyntaxKind.NullKeyword) return null
404
- }
405
- if (node.kind === ts.SyntaxKind.TrueKeyword) return true
406
- if (node.kind === ts.SyntaxKind.FalseKeyword) return false
407
- if (node.kind === ts.SyntaxKind.NullKeyword) return null
408
- // Negative numeric literals appear as PrefixUnaryExpression in some TS versions.
409
- if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken) {
410
- const inner = parseDefaultLiteral(node.operand as unknown as ts.TypeNode, sourceFile)
411
- if (typeof inner === "number") return -inner
412
- }
413
- return undefined
414
- }
415
-
416
- /** Which {@link DeclaredBounds} key each length/item modifier fills. */
417
- const BOUND_KEY_BY_MODIFIER = {
418
- MaxLength: "maxLength",
419
- MinLength: "minLength",
420
- MaxItems: "maxItems",
421
- MinItems: "minItems",
422
- } as const satisfies Record<string, keyof DeclaredBounds>
423
-
424
- /**
425
- * A `Between` bound: a number for a numeric column, an ISO-8601 string for a temporal one.
426
- *
427
- * Which of the two is legal is decided from the field's kind in `compileBounds`, not here, because
428
- * the kind is not known until the wrappers are off.
429
- */
430
- function parseRangeBound(
431
- node: ts.TypeNode | undefined,
432
- sourceFile: ts.SourceFile,
433
- ): number | string | undefined {
434
- const asNumber = parseNumericTypeArg(node, sourceFile)
435
- if (asNumber !== undefined) return asNumber
436
- return literalStringType(node) ?? undefined
437
- }
438
-
439
- /**
440
- * Whether a `JSON<T>` field holds an array, which is what decides between item bounds and none.
441
- *
442
- * Answered from the declared type argument rather than guessed downstream: the engine sees only
443
- * `JSONB` and cannot tell `JSON<Item[]>` from `JSON<{ a: string }>`, so `jsonb_array_length` would
444
- * be a coin flip that raises at insert time when it loses.
445
- */
446
- function jsonTypeArgIsArray(node: ts.TypeNode, sourceFile: ts.SourceFile): boolean {
447
- if (!ts.isTypeReferenceNode(node)) return false
448
- const arg = node.typeArguments?.[0]
449
- if (!arg) return false
450
- return isArrayLikeTypeNode(arg, sourceFile)
451
- }
452
-
453
- function isArrayLikeTypeNode(node: ts.TypeNode, sourceFile: ts.SourceFile): boolean {
454
- if (ts.isArrayTypeNode(node)) return true
455
- // `readonly Item[]`
456
- if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.ReadonlyKeyword) {
457
- return isArrayLikeTypeNode(node.type, sourceFile)
458
- }
459
- if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName)) {
460
- return node.typeName.text === "Array" || node.typeName.text === "ReadonlyArray"
461
- }
462
- return false
463
- }
464
-
465
- function parseFieldType(
466
- fieldName: string,
467
- typeNode: ts.TypeNode,
468
- sourceFile: ts.SourceFile,
469
- blockAliases: Map<string, BlockDefinitionAst>,
470
- bucketAliases: Map<string, string>,
471
- bucketsById: Map<string, ExtractedStorageBucketAst>,
472
- context: FieldParseContext = {},
473
- resolveCtx: ResolveContext,
474
- ): FieldAstV2 {
475
- const flags = {
476
- required: true,
477
- unique: false,
478
- index: false,
479
- primaryKey: false,
480
- serverGenerated: false,
481
- autoIncrement: false,
482
- relationCardinality: undefined as "one" | "many" | undefined,
483
- relationTarget: undefined as string | undefined,
484
- editorReadOnly: false,
485
- computedFromSources: undefined as string[] | undefined,
486
- computedFromTemplate: undefined as string | undefined,
487
- fieldDefault: undefined as string | number | boolean | null | undefined,
488
- localized: false,
489
- notLocalized: false,
490
- searchable: false,
491
- bounds: {} as DeclaredBounds,
492
- }
493
-
494
- const resolving = new Set<string>()
495
- let current = typeNode
496
- while (ts.isTypeReferenceNode(current) && ts.isIdentifier(current.typeName)) {
497
- const typeName = applyImportRename(current.typeName.text, sourceFile, resolveCtx.renameMap)
498
- switch (typeName) {
499
- case "Optional":
500
- flags.required = false
501
- current = current.typeArguments?.[0] ?? current
502
- continue
503
- case "Unique":
504
- flags.unique = true
505
- current = current.typeArguments?.[0] ?? current
506
- continue
507
- case "Indexed":
508
- flags.index = true
509
- current = current.typeArguments?.[0] ?? current
510
- continue
511
- case "ServerDefault":
512
- flags.serverGenerated = true
513
- current = current.typeArguments?.[0] ?? current
514
- continue
515
- case "AutoIncrement":
516
- flags.serverGenerated = true
517
- flags.autoIncrement = true
518
- current = current.typeArguments?.[0] ?? current
519
- continue
520
- case "PrimaryKey":
521
- flags.primaryKey = true
522
- flags.required = true
523
- flags.unique = true
524
- current = current.typeArguments?.[0] ?? current
525
- continue
526
- case "Default": {
527
- const valueArg = current.typeArguments?.[1]
528
- if (valueArg !== undefined) {
529
- const literal = parseDefaultLiteral(valueArg, sourceFile)
530
- if (literal !== undefined) {
531
- flags.fieldDefault = literal
532
- }
533
- }
534
- // Unwrap to T so `Default<boolean, true>` resolves as boolean, not text.
535
- current = current.typeArguments?.[0] ?? current
536
- continue
537
- }
538
- case "Searchable":
539
- // Used to unwrap and drop the declaration on the floor, so a schema saying a column was
540
- // searchable compiled, pushed, and produced a Studio list view with no search box: the
541
- // engine was never told, so the admin config carried no `searchFields` for Studio to read.
542
- flags.searchable = true
543
- current = current.typeArguments?.[0] ?? current
544
- continue
545
- case "EditorReadOnly":
546
- flags.editorReadOnly = true
547
- current = current.typeArguments?.[0] ?? current
548
- continue
549
- case "Computed":
550
- flags.editorReadOnly = true
551
- flags.serverGenerated = true
552
- current = current.typeArguments?.[0] ?? current
553
- continue
554
- case "ComputedFrom": {
555
- const valueArg = current.typeArguments?.[0]
556
- const sourcesArg = current.typeArguments?.[1]
557
- const parsed = parseComputedFromSecondArg(sourcesArg, sourceFile)
558
- if (parsed) {
559
- flags.computedFromSources = parsed.sources
560
- flags.computedFromTemplate = parsed.template
561
- } else {
562
- flags.computedFromSources = ["title"]
563
- }
564
- current = valueArg ?? current
565
- continue
566
- }
567
- case "MaxLength":
568
- case "MinLength":
569
- case "MaxItems":
570
- case "MinItems": {
571
- const amount = parseNumericTypeArg(current.typeArguments?.[1], sourceFile)
572
- if (amount !== undefined) {
573
- flags.bounds[BOUND_KEY_BY_MODIFIER[typeName]] = amount
574
- }
575
- current = current.typeArguments?.[0] ?? current
576
- continue
577
- }
578
- case "Between": {
579
- const min = parseRangeBound(current.typeArguments?.[1], sourceFile)
580
- const max = parseRangeBound(current.typeArguments?.[2], sourceFile)
581
- if (min !== undefined) flags.bounds.min = min
582
- if (max !== undefined) flags.bounds.max = max
583
- current = current.typeArguments?.[0] ?? current
584
- continue
585
- }
586
- case "Localized":
587
- flags.localized = true
588
- current = current.typeArguments?.[0] ?? current
589
- continue
590
- case "NotLocalized":
591
- flags.notLocalized = true
592
- current = current.typeArguments?.[0] ?? current
593
- continue
594
- case "RelatedTo": {
595
- flags.relationCardinality = "one"
596
- flags.relationTarget = relationTargetFromTypeArg(current.typeArguments?.[0], sourceFile)
597
- const relOpts = parseRelationOptions(current.typeArguments?.[1], sourceFile)
598
- // `target` must match `ModelAst.name` to satisfy validator resolution.
599
- // FK column follows the field name (two relations to the same model need distinct columns).
600
- return emitField({
601
- kind: "relation",
602
- kernel: {
603
- cardinality: "belongsTo",
604
- target: flags.relationTarget!,
605
- ...relationOptionsKernel(relOpts),
606
- },
607
- db: { foreignKey: relationForeignKeyFromField(fieldName) },
608
- platform: flags.editorReadOnly ? { readOnly: true } : {},
609
- })
610
- }
611
- case "HasOne": {
612
- flags.relationCardinality = "one"
613
- flags.relationTarget = relationTargetFromTypeArg(current.typeArguments?.[0], sourceFile)
614
- const relOpts = parseRelationOptions(current.typeArguments?.[1], sourceFile)
615
- return emitField({
616
- kind: "relation",
617
- kernel: {
618
- cardinality: "hasOne",
619
- target: flags.relationTarget,
620
- ...relationOptionsKernel(relOpts),
621
- },
622
- db: {},
623
- platform: flags.editorReadOnly ? { readOnly: true } : {},
624
- })
625
- }
626
- case "HasMany": {
627
- flags.relationCardinality = "many"
628
- flags.relationTarget = relationTargetFromTypeArg(current.typeArguments?.[0], sourceFile)
629
- const relOpts = parseRelationOptions(current.typeArguments?.[1], sourceFile)
630
- return emitField({
631
- kind: "relation",
632
- kernel: {
633
- cardinality: "hasMany",
634
- target: flags.relationTarget,
635
- ...relationOptionsKernel(relOpts),
636
- },
637
- db: {},
638
- platform: flags.editorReadOnly ? { readOnly: true } : {},
639
- })
640
- }
641
- case "ManyToMany": {
642
- flags.relationCardinality = "many"
643
- flags.relationTarget = relationTargetFromTypeArg(current.typeArguments?.[0], sourceFile)
644
- const relOpts = parseRelationOptions(current.typeArguments?.[1], sourceFile)
645
- return emitField({
646
- kind: "relation",
647
- kernel: {
648
- cardinality: "manyToMany",
649
- target: flags.relationTarget,
650
- ...relationOptionsKernel(relOpts),
651
- },
652
- db: {},
653
- platform: flags.editorReadOnly ? { readOnly: true } : {},
654
- })
655
- }
656
- default: {
657
- const resolved = tryResolveTypeReference(current, sourceFile, resolveCtx, { fieldName, resolving })
658
- if (resolved) {
659
- current = resolved
660
- continue
661
- }
662
- break
663
- }
664
- }
665
- break
666
- }
667
-
668
- const scalarBase = parseScalarType(
669
- current,
670
- sourceFile,
671
- blockAliases,
672
- bucketAliases,
673
- bucketsById,
674
- context,
675
- resolveCtx,
676
- fieldName,
677
- resolving,
678
- )
679
-
680
- let parsed: ParsedField = {
681
- kind: scalarBase.kind,
682
- kernel: {
683
- ...scalarBase.kernel,
684
- required: flags.required,
685
- ...(flags.primaryKey && { primaryKey: true }),
686
- },
687
- db: {
688
- ...scalarBase.db,
689
- unique: flags.unique,
690
- index: flags.index,
691
- },
692
- platform: {
693
- ...scalarBase.platform,
694
- ...(flags.editorReadOnly && { readOnly: true }),
695
- ...(flags.searchable && { searchable: true }),
696
- },
697
- }
698
-
699
- if (flags.autoIncrement && parsed.kind === "integer") {
700
- parsed = { ...parsed, kind: "serial", db: { ...parsed.db, pgType: "SERIAL" } }
701
- }
702
-
703
- if (fieldName === "id" && parsed.kind === "uuid" && flags.primaryKey === false) {
704
- parsed = {
705
- ...parsed,
706
- kernel: { ...parsed.kernel, primaryKey: true, required: true },
707
- db: { ...parsed.db, unique: true },
708
- }
709
- }
710
-
711
- if (flags.fieldDefault !== undefined) {
712
- if (parsed.kernel.default !== undefined) {
713
- throw new Error(
714
- `Field "${fieldName}": use either Default<…> or an inline type default (e.g. RichText<"…">), not both.`,
715
- )
716
- }
717
- parsed = {
718
- ...parsed,
719
- kernel: { ...parsed.kernel, default: { kind: "value", value: flags.fieldDefault } },
720
- }
721
- }
722
-
723
- if (parsed.kernel.primaryKey === true && parsed.kind === "uuid" && parsed.kernel.default === undefined) {
724
- parsed = {
725
- ...parsed,
726
- kernel: { ...parsed.kernel, default: { kind: "genRandomUuid" } },
727
- }
728
- } else if (
729
- parsed.kernel.primaryKey === true &&
730
- (parsed.kind === "serial" || parsed.kind === "bigSerial")
731
- ) {
732
- flags.serverGenerated = true
733
- }
734
-
735
- if (flags.serverGenerated === true) {
736
- parsed = { ...parsed, db: { ...parsed.db, serverGenerated: true } }
737
- }
738
-
739
- const auditTs =
740
- fieldName === "created_at" ||
741
- fieldName === "updated_at" ||
742
- fieldName === "createdAt" ||
743
- fieldName === "updatedAt"
744
- if (auditTs) {
745
- parsed = { ...parsed, db: { ...parsed.db, serverGenerated: true } }
746
- if (
747
- (parsed.kind === "datetime" || parsed.kind === "date") &&
748
- parsed.kernel.default === undefined
749
- ) {
750
- parsed = { ...parsed, kernel: { ...parsed.kernel, default: { kind: "now" } } }
751
- }
752
- }
753
-
754
- if (
755
- flags.serverGenerated &&
756
- (parsed.kind === "datetime" || parsed.kind === "date") &&
757
- parsed.kernel.default === undefined
758
- ) {
759
- parsed = { ...parsed, kernel: { ...parsed.kernel, default: { kind: "now" } } }
760
- }
761
-
762
- const hasCfTemplate = flags.computedFromTemplate !== undefined
763
- const hasCfSources = Boolean(flags.computedFromSources && flags.computedFromSources.length > 0)
764
- if (parsed.kind === "text" && (hasCfTemplate || hasCfSources)) {
765
- const kernel: ParsedField["kernel"] = { ...parsed.kernel }
766
- if (hasCfSources && flags.computedFromSources) {
767
- kernel.sources = flags.computedFromSources
768
- }
769
- if (hasCfTemplate && flags.computedFromTemplate !== undefined) {
770
- kernel.template = flags.computedFromTemplate
771
- }
772
- parsed = { ...parsed, kernel }
773
- }
774
-
775
- // Bounds compile here, not in the modifier cases above: `MaxLength<string[], 10>` is only knowably
776
- // an item count once the wrappers are off and the kind is `array`. Compiling early is what made
777
- // every bound `char_length`, which does not exist for an array and fails `CREATE TABLE`.
778
- const jsonIsArray = parsed.kind === "json" && jsonTypeArgIsArray(current, sourceFile)
779
- if (jsonIsArray) {
780
- parsed = { ...parsed, kernel: { ...parsed.kernel, jsonArray: true } }
781
- }
782
-
783
- if (Object.keys(flags.bounds).length > 0) {
784
- const compiled = compileBounds(fieldName, parsed.kind, flags.bounds, { jsonIsArray })
785
- parsed = {
786
- ...parsed,
787
- kernel: {
788
- ...parsed.kernel,
789
- ...(compiled.check !== undefined && {
790
- check: mergeCheckConstraint(parsed.kernel.check, compiled.check),
791
- }),
792
- ...(compiled.validation !== undefined && { validation: compiled.validation }),
793
- },
794
- }
795
- }
796
-
797
- return emitField(finalizeParsedField(parsed, flags, context))
798
- }
799
-
800
- function finalizeParsedField(
801
- parsed: ParsedField,
802
- flags: { localized: boolean; notLocalized: boolean },
803
- context: FieldParseContext,
804
- ): ParsedField {
805
- let localized = flags.localized
806
-
807
- if (
808
- !localized &&
809
- !flags.notLocalized &&
810
- context.autoLocalize &&
811
- shouldAutoLocalizeFieldKind(parsed.kind)
812
- ) {
813
- localized = true
814
- }
815
-
816
- if (parsed.kind === "blocks" && parsed.kernel.blocks && context.autoLocalize && !localized) {
817
- return {
818
- ...parsed,
819
- kernel: {
820
- ...parsed.kernel,
821
- blocks: parsed.kernel.blocks.map((blockDef) => ({
822
- ...blockDef,
823
- fields: Object.fromEntries(
824
- Object.entries(blockDef.fields).map(([name, fieldWire]) => [
825
- name,
826
- localizeFieldWire(fieldWire),
827
- ]),
828
- ),
829
- })),
830
- },
831
- }
832
- }
833
-
834
- if (localized) {
835
- return {
836
- ...parsed,
837
- kernel: { ...parsed.kernel, localized: true },
838
- db: { ...parsed.db, pgType: "JSONB" },
839
- }
840
- }
841
- return parsed
842
- }
843
-
844
- function shouldAutoLocalizeFieldKind(kind: unknown): boolean {
845
- return kind === "text" || kind === "richText"
846
- }
847
-
848
- function localizeFieldWire(field: FieldAstV2): FieldAstV2 {
849
- if (field.localized === true) return field
850
- if (!shouldAutoLocalizeFieldKind(field.kind)) return field
851
- const annotations = (field.annotations ?? {}) as { db?: Record<string, unknown>; platform?: Record<string, unknown> }
852
- return {
853
- ...field,
854
- localized: true,
855
- annotations: {
856
- ...annotations,
857
- db: { ...annotations.db, pgType: "JSONB" },
858
- },
859
- }
860
- }
861
-
862
- function parseScalarType(
863
- typeNode: ts.TypeNode,
864
- sourceFile: ts.SourceFile,
865
- blockAliases: Map<string, BlockDefinitionAst>,
866
- bucketAliases: Map<string, string>,
867
- bucketsById: Map<string, ExtractedStorageBucketAst>,
868
- context: FieldParseContext = {},
869
- resolveCtx: ResolveContext,
870
- fieldName = "?",
871
- resolving: Set<string> = new Set(),
872
- ): ParsedField {
873
- if (ts.isArrayTypeNode(typeNode)) {
874
- const element = parseScalarType(
875
- typeNode.elementType,
876
- sourceFile,
877
- blockAliases,
878
- bucketAliases,
879
- bucketsById,
880
- context,
881
- resolveCtx,
882
- fieldName,
883
- resolving,
884
- )
885
- return scalar("array", {
886
- db: { elementType: defaultPgTypeForKind(element.kind) },
887
- })
888
- }
889
-
890
- if (ts.isUnionTypeNode(typeNode)) {
891
- const literals = typeNode.types.filter(ts.isLiteralTypeNode)
892
- if (literals.length === typeNode.types.length && literals.every((lit) => ts.isStringLiteral(lit.literal))) {
893
- return scalar("enum", {
894
- kernel: {
895
- values: literals.map((lit) => (lit.literal as ts.StringLiteral).text),
896
- },
897
- })
898
- }
899
- const nonNull = typeNode.types.find((t) => t.kind !== ts.SyntaxKind.NullKeyword)
900
- if (nonNull) {
901
- return parseScalarType(
902
- nonNull,
903
- sourceFile,
904
- blockAliases,
905
- bucketAliases,
906
- bucketsById,
907
- context,
908
- resolveCtx,
909
- fieldName,
910
- resolving,
911
- )
912
- }
913
- }
914
-
915
- if (ts.isTypeReferenceNode(typeNode) && ts.isIdentifier(typeNode.typeName)) {
916
- const resolved = tryResolveTypeReference(typeNode, sourceFile, resolveCtx, { fieldName, resolving })
917
- if (resolved) {
918
- return parseScalarType(
919
- resolved,
920
- sourceFile,
921
- blockAliases,
922
- bucketAliases,
923
- bucketsById,
924
- context,
925
- resolveCtx,
926
- fieldName,
927
- resolving,
928
- )
929
- }
930
- }
931
-
932
- if (ts.isTypeReferenceNode(typeNode)) {
933
- const ref = ts.isIdentifier(typeNode.typeName)
934
- ? applyImportRename(typeNode.typeName.text, sourceFile, resolveCtx.renameMap)
935
- : typeNode.typeName.getText(sourceFile)
936
- switch (ref) {
937
- case "UUID":
938
- case "SupatypeAuthUserId":
939
- return scalar("uuid")
940
- case "RichText": {
941
- const defaultArg = typeNode.typeArguments?.[0]
942
- if (!defaultArg) return scalar("richText")
943
- const literal = parseDefaultLiteral(defaultArg, sourceFile)
944
- if (literal === undefined) {
945
- throw new Error(
946
- `RichText default must be a string literal (plain text or Lexical JSON string), not HTML.`,
947
- )
948
- }
949
- if (typeof literal !== "string") {
950
- throw new Error(
951
- `RichText<…> default must be a string literal (plain text or Lexical JSON string).`,
952
- )
953
- }
954
- return scalar("richText", {
955
- kernel: { default: { kind: "value", value: literal } },
956
- })
957
- }
958
- case "Slug": {
959
- const fromArg = typeNode.typeArguments?.[0]
960
- const fromLiteral = fromArg ? literalStringType(fromArg) : null
961
- return scalar("slug", { kernel: { from: fromLiteral ?? "title" } })
962
- }
963
- case "Email":
964
- return scalar("email")
965
- case "URL":
966
- return scalar("url")
967
- case "Markdown":
968
- case "PhoneNumber":
969
- return scalar("text")
970
- case "Color":
971
- return scalar("color")
972
- case "IPAddress":
973
- return scalar("ip")
974
- case "CIDR":
975
- return scalar("cidr")
976
- case "MacAddress":
977
- return scalar("macaddr")
978
- case "XML":
979
- return scalar("xml")
980
- case "TSQuery":
981
- return scalar("tsQuery")
982
- case "TSVector":
983
- return scalar("tsVector")
984
- case "Money":
985
- return scalar("money")
986
- case "Decimal": {
987
- // `Decimal<10, 2>` names a precision and a scale, and the engine renders `NUMERIC(p, s)`
988
- // from them: but nothing used to read the type arguments, so every Decimal became an
989
- // unbounded NUMERIC. Silently, which is the worst way to lose a constraint on a money column.
990
- const precision = parseNumericTypeArg(typeNode.typeArguments?.[0], sourceFile)
991
- const scale = parseNumericTypeArg(typeNode.typeArguments?.[1], sourceFile)
992
- return scalar("decimal", {
993
- kernel: {
994
- ...(precision !== undefined && { precision }),
995
- ...(scale !== undefined && { scale }),
996
- },
997
- })
998
- }
999
- case "DateOnly":
1000
- return scalar("date")
1001
- case "Date":
1002
- case "DateTime":
1003
- case "Timestamp":
1004
- return scalar("datetime", { db: { pgType: "TIMESTAMP WITH TIME ZONE" } })
1005
- case "Int":
1006
- return scalar("integer")
1007
- case "SmallInt":
1008
- return scalar("smallInt")
1009
- case "BigInt":
1010
- return scalar("bigInt")
1011
- case "Float":
1012
- return scalar("float")
1013
- case "Bytea":
1014
- return scalar("bytes")
1015
- case "JSON":
1016
- return scalar("json")
1017
- case "Button":
1018
- return scalar("button", { db: { pgType: "JSONB" } })
1019
- case "Duration":
1020
- return scalar("json", {
1021
- db: { pgType: "JSONB" },
1022
- platform: { editor: "duration" },
1023
- kernel: { tsType: "{ ms: number }" },
1024
- })
1025
- // `Code` and `Currency` each carry two values, so a scalar column would have to drop one:
1026
- // JSONB keeps `lang` with its `source`, and an amount with the currency it is denominated in.
1027
- // `tsType` is what stops the generated client row from flattening them to an opaque object.
1028
- case "Code": {
1029
- const lang = literalStringType(typeNode.typeArguments?.[0])
1030
- return scalar("json", {
1031
- db: { pgType: "JSONB" },
1032
- // `editor` picks the Studio widget. Without it a code snippet and a money amount both get
1033
- // the raw JSON editor, because the widget is otherwise chosen from the column kind alone
1034
- // and both of these are JSONB.
1035
- platform: { editor: "code" },
1036
- kernel: { tsType: `{ lang: ${lang !== null ? JSON.stringify(lang) : "string"}; source: string }` },
1037
- })
1038
- }
1039
- case "Currency": {
1040
- const currencyCode = literalStringType(typeNode.typeArguments?.[0])
1041
- return scalar("json", {
1042
- db: { pgType: "JSONB" },
1043
- platform: { editor: "currency" },
1044
- kernel: {
1045
- tsType: `{ amount: string; code: ${currencyCode !== null ? JSON.stringify(currencyCode) : "string"} }`,
1046
- },
1047
- })
1048
- }
1049
- case "GeoPoint":
1050
- case "Geo":
1051
- return scalar("geo", { kernel: { geoType: "point", srid: 4326 } })
1052
- case "Asset":
1053
- case "FileAsset": {
1054
- const bucket = resolveBucketName(typeNode.typeArguments?.[0], sourceFile, bucketAliases, "assets")
1055
- const assetOpts = parseAssetFieldOptions(typeNode.typeArguments?.[1], sourceFile)
1056
- return attachStorageFieldMeta(
1057
- scalar("file", {
1058
- // JSONB, not TEXT. The column holds { bucket, path }, this package's own
1059
- // DEFAULT_DB_BY_KIND says JSONB, and the engine honours an explicit annotation, so
1060
- // TEXT here was one code path from a text column with a JSON object written into it.
1061
- db: { pgType: "JSONB" },
1062
- kernel: { bucket, ...(assetOpts.localized && { localized: true }) },
1063
- }),
1064
- bucket,
1065
- bucketsById,
1066
- )
1067
- }
1068
- case "ImageAsset": {
1069
- const bucket = resolveBucketName(typeNode.typeArguments?.[0], sourceFile, bucketAliases, "images")
1070
- const assetOpts = parseAssetFieldOptions(typeNode.typeArguments?.[1], sourceFile)
1071
- return attachStorageFieldMeta(
1072
- scalar("image", {
1073
- // JSONB, not TEXT. The column holds { bucket, path }, this package's own
1074
- // DEFAULT_DB_BY_KIND says JSONB, and the engine honours an explicit annotation, so
1075
- // TEXT here was one code path from a text column with a JSON object written into it.
1076
- db: { pgType: "JSONB" },
1077
- kernel: { bucket, ...(assetOpts.localized && { localized: true }) },
1078
- }),
1079
- bucket,
1080
- bucketsById,
1081
- )
1082
- }
1083
- case "Blocks":
1084
- return scalar("blocks", {
1085
- kernel: {
1086
- index: true,
1087
- blocks: parseBlocksTypeDefinitions(
1088
- typeNode.typeArguments?.[0],
1089
- sourceFile,
1090
- blockAliases,
1091
- bucketAliases,
1092
- bucketsById,
1093
- context,
1094
- resolveCtx,
1095
- ),
1096
- },
1097
- })
1098
- case "Vector": {
1099
- const dimensions = typeNode.typeArguments?.[0]?.getText(sourceFile)
1100
- return scalar("vector", {
1101
- kernel: { dimensions: Number(dimensions ?? "1536") },
1102
- })
1103
- }
1104
- default:
1105
- throw unknownTypeError(ref, fieldName)
1106
- }
1107
- }
1108
-
1109
- switch (typeNode.kind) {
1110
- case ts.SyntaxKind.StringKeyword:
1111
- return scalar("text")
1112
- case ts.SyntaxKind.NumberKeyword:
1113
- return scalar("float")
1114
- case ts.SyntaxKind.BooleanKeyword:
1115
- return scalar("boolean")
1116
- default:
1117
- return scalar("json")
1118
- }
1119
- }
1120
-
1121
- function collectBlockAliases(
1122
- sourceFile: ts.SourceFile,
1123
- bucketAliases: Map<string, string>,
1124
- bucketsById: Map<string, ExtractedStorageBucketAst>,
1125
- resolveCtx: ResolveContext,
1126
- ): Map<string, BlockDefinitionAst> {
1127
- const blocks = new Map<string, BlockDefinitionAst>()
1128
- for (const stmt of sourceFile.statements) {
1129
- if (!ts.isTypeAliasDeclaration(stmt)) continue
1130
- if (!ts.isTypeReferenceNode(stmt.type)) continue
1131
- if (!ts.isIdentifier(stmt.type.typeName) || stmt.type.typeName.text !== "Block") continue
1132
- const block = parseInlineBlockDefinition(
1133
- stmt.type,
1134
- sourceFile,
1135
- new Map(),
1136
- bucketAliases,
1137
- bucketsById,
1138
- {},
1139
- resolveCtx,
1140
- )
1141
- if (!block) continue
1142
- blocks.set(stmt.name.text, block)
1143
- }
1144
- return blocks
1145
- }
1146
-
1147
- function collectLocaleConfig(
1148
- sourceFile: ts.SourceFile,
1149
- ): { locales: string[]; defaultLocale: string } | undefined {
1150
- for (const stmt of sourceFile.statements) {
1151
- if (!ts.isTypeAliasDeclaration(stmt)) continue
1152
- if (!hasExportModifier(stmt)) continue
1153
- if (!ts.isTypeReferenceNode(stmt.type)) continue
1154
- if (stmt.type.typeName.getText(sourceFile) !== "LocaleConfig") continue
1155
- const parsed = parseLocaleConfigTypeRef(stmt.type, sourceFile)
1156
- if (parsed) return parsed
1157
- }
1158
- return undefined
1159
- }
1160
-
1161
- function parseLocaleConfigTypeRef(
1162
- typeRef: ts.TypeReferenceNode,
1163
- sourceFile: ts.SourceFile,
1164
- ): { locales: string[]; defaultLocale: string } | null {
1165
- const [localesArg, defaultArg] = typeRef.typeArguments ?? []
1166
- if (!localesArg || !defaultArg) return null
1167
-
1168
- const locales = parseStringLiteralTuple(localesArg, sourceFile)
1169
- const defaultLocale = literalStringType(defaultArg)
1170
- if (!locales || locales.length === 0 || !defaultLocale) return null
1171
- if (!locales.includes(defaultLocale)) {
1172
- throw new Error(
1173
- `LocaleConfig defaultLocale "${defaultLocale}" must be one of: ${locales.join(", ")}`,
1174
- )
1175
- }
1176
- return { locales, defaultLocale }
1177
- }
1178
-
1179
- function parseStringLiteralTuple(node: ts.TypeNode, sourceFile: ts.SourceFile): string[] | null {
1180
- if (!ts.isTupleTypeNode(node)) return null
1181
- const out: string[] = []
1182
- for (const el of node.elements) {
1183
- const lit = literalStringType(el)
1184
- if (!lit) return null
1185
- out.push(lit)
1186
- }
1187
- return out
1188
- }
1189
-
1190
- function collectBucketContext(
1191
- sourceFile: ts.SourceFile,
1192
- resolveCtx: ResolveContext,
1193
- ): {
1194
- aliases: Map<string, string>
1195
- bucketsById: Map<string, ExtractedStorageBucketAst>
1196
- } {
1197
- const aliases = new Map<string, string>()
1198
- const bucketsById = new Map<string, ExtractedStorageBucketAst>()
1199
-
1200
- for (const stmt of sourceFile.statements) {
1201
- if (!ts.isTypeAliasDeclaration(stmt)) continue
1202
- if (!ts.isTypeReferenceNode(stmt.type)) continue
1203
- if (!ts.isIdentifier(stmt.type.typeName) || stmt.type.typeName.text !== "Bucket") continue
1204
- const [nameArg, configArg] = stmt.type.typeArguments ?? []
1205
- if (!nameArg || !ts.isLiteralTypeNode(nameArg) || !ts.isStringLiteral(nameArg.literal)) continue
1206
- const id = nameArg.literal.text
1207
- aliases.set(stmt.name.text, id)
1208
-
1209
- const parsed =
1210
- configArg && ts.isTypeLiteralNode(configArg)
1211
- ? parseBucketTypeLiteral(configArg, sourceFile, id, resolveCtx)
1212
- : {}
1213
-
1214
- const next = buildExtractedBucketAst(id, parsed)
1215
- const existing = bucketsById.get(id)
1216
- if (existing !== undefined && !bucketsEqual(existing, next)) {
1217
- throw new Error(
1218
- `Conflicting Bucket<> declarations for id "${id}". Use a single export per bucket id.`,
1219
- )
1220
- }
1221
- bucketsById.set(id, next)
1222
- }
1223
-
1224
- return { aliases, bucketsById }
1225
- }
1226
-
1227
- function buildExtractedBucketAst(
1228
- id: string,
1229
- parsed: Partial<ParsedBucketLiteral>,
1230
- ): ExtractedStorageBucketAst {
1231
- const mode = parsed.accessMode ?? "private"
1232
- const pub = mode === "public"
1233
-
1234
- const row: ExtractedStorageBucketAst = {
1235
- id,
1236
- public: pub,
1237
- accessMode: mode,
1238
- ...(parsed.allowedMimeTypes !== undefined && parsed.allowedMimeTypes.length > 0
1239
- ? { allowedMimeTypes: parsed.allowedMimeTypes }
1240
- : {}),
1241
- ...(parsed.fileSizeLimit !== undefined ? { fileSizeLimit: parsed.fileSizeLimit } : {}),
1242
- ...(parsed.access !== undefined &&
1243
- Object.keys(parsed.access).length > 0 && { access: parsed.access }),
1244
- ...(parsed.s3BucketPolicy !== undefined ? { s3BucketPolicy: parsed.s3BucketPolicy } : {}),
1245
- }
1246
- return row
1247
- }
1248
-
1249
- interface ParsedBucketLiteral {
1250
- accessMode?: "public" | "private" | "custom"
1251
- allowedMimeTypes?: string[]
1252
- fileSizeLimit?: number
1253
- access?: Record<string, unknown>
1254
- s3BucketPolicy?: string
1255
- }
1256
-
1257
- function parseBucketTypeLiteral(
1258
- lit: ts.TypeLiteralNode,
1259
- sourceFile: ts.SourceFile,
1260
- bucketId: string,
1261
- resolveCtx: ResolveContext,
1262
- ): Partial<ParsedBucketLiteral> {
1263
- const out: Partial<ParsedBucketLiteral> = {}
1264
- for (const member of lit.members) {
1265
- if (!ts.isPropertySignature(member) || !member.type) continue
1266
- const key = getPropertyName(member.name)
1267
- if (!key) continue
1268
-
1269
- if (key === "accessMode") {
1270
- const mode = parseAccessModeLiteral(member.type, sourceFile)
1271
- if (mode !== undefined) out.accessMode = mode
1272
- continue
1273
- }
1274
- if (key === "maxSize") {
1275
- const s = parseSizeStringLiteral(member.type, sourceFile)
1276
- if (s !== undefined) {
1277
- const bytes = parseDataSizeBytes(s)
1278
- out.fileSizeLimit = bytes
1279
- }
1280
- continue
1281
- }
1282
- if (key === "accept") {
1283
- const types = parseMimeAcceptList(member.type, sourceFile)
1284
- if (types !== undefined) out.allowedMimeTypes = types
1285
- continue
1286
- }
1287
- if (key === "access") {
1288
- const acc = parsePartialBucketAccess(member.type, sourceFile, bucketId, resolveCtx)
1289
- if (acc !== undefined && Object.keys(acc).length > 0) out.access = acc
1290
- continue
1291
- }
1292
- if (key === "s3BucketPolicy") {
1293
- const pol = parseJsonStringLiteral(member.type, sourceFile)
1294
- if (pol !== undefined) out.s3BucketPolicy = pol
1295
- continue
1296
- }
1297
- }
1298
- return out
1299
- }
1300
-
1301
- function parseAccessModeLiteral(
1302
- typeNode: ts.TypeNode,
1303
- sourceFile: ts.SourceFile,
1304
- ): "public" | "private" | "custom" | undefined {
1305
- const text = stripQuotes(typeNode.getText(sourceFile))
1306
- if (text === "public" || text === "private" || text === "custom") return text
1307
- return undefined
1308
- }
1309
-
1310
- function parseSizeStringLiteral(typeNode: ts.TypeNode, sourceFile: ts.SourceFile): string | undefined {
1311
- return literalStringType(typeNode) ?? (stripQuotes(typeNode.getText(sourceFile)) || undefined)
1312
- }
1313
-
1314
- function parseJsonStringLiteral(typeNode: ts.TypeNode, sourceFile: ts.SourceFile): string | undefined {
1315
- return parseSizeStringLiteral(typeNode, sourceFile)
1316
- }
1317
-
1318
- function parseMimeAcceptList(typeNode: ts.TypeNode, sourceFile: ts.SourceFile): string[] | undefined {
1319
- if (ts.isTypeOperatorNode(typeNode) && typeNode.operator === ts.SyntaxKind.ReadonlyKeyword) {
1320
- return parseMimeAcceptList(typeNode.type, sourceFile)
1321
- }
1322
- if (ts.isTupleTypeNode(typeNode)) {
1323
- const values: string[] = []
1324
- for (const el of typeNode.elements) {
1325
- const node: ts.TypeNode = ts.isNamedTupleMember(el) ? el.type : el
1326
- const s = literalStringType(node)
1327
- if (!s) return undefined
1328
- values.push(s)
1329
- }
1330
- return values.length > 0 ? values : undefined
1331
- }
1332
- if (ts.isUnionTypeNode(typeNode)) {
1333
- const values: string[] = []
1334
- for (const u of typeNode.types) {
1335
- const s = literalStringType(u)
1336
- if (!s) return undefined
1337
- values.push(s)
1338
- }
1339
- return values.length > 0 ? values : undefined
1340
- }
1341
- return undefined
1342
- }
1343
-
1344
- /** The operations a bucket's `access` may name, the same four a model's may. */
1345
- const BUCKET_RULE_KEYS: ReadonlySet<string> = new Set(["read", "create", "update", "delete"])
1346
-
1347
- function parsePartialBucketAccess(
1348
- typeNode: ts.TypeNode,
1349
- sourceFile: ts.SourceFile,
1350
- bucketId: string,
1351
- resolveCtx: ResolveContext,
1352
- ): Record<string, unknown> | undefined {
1353
- // Same hazard as model access: silently dropping these rules publishes a
1354
- // bucket with no read/write restrictions, so an alias must resolve and an
1355
- // unresolvable annotation must fail rather than degrade to "no rules".
1356
- const literal = resolveAccessLiteral(typeNode, sourceFile, resolveCtx)
1357
- if (!literal) {
1358
- throw new Error(
1359
- `Bucket "${bucketId}": could not resolve its \`access\` rules from ` +
1360
- `\`${typeNode.getText(sourceFile)}\`.\n` +
1361
- ` access must be an object type, or a type alias for one, e.g.\n` +
1362
- ` export type MediaAccess = { read: Public; create: Authenticated }\n` +
1363
- ` Refusing to continue: an unresolved access block would leave this bucket unrestricted.`,
1364
- )
1365
- }
1366
- const access: Record<string, unknown> = {}
1367
- for (const member of literal.members) {
1368
- if (!ts.isPropertySignature(member) || !member.type) continue
1369
- const key = getPropertyName(member.name)
1370
- // Refused rather than skipped. Skipping is how `update` went unenforced: the author wrote an
1371
- // overwrite rule, the bucket got none, and nothing said so.
1372
- if (key === null || !BUCKET_RULE_KEYS.has(key)) {
1373
- const written = key ?? member.name.getText(sourceFile)
1374
- throw new Error(
1375
- `Bucket "${bucketId}": \`${written}\` is not a bucket rule. Use read, create, update or delete.`,
1376
- )
1377
- }
1378
- const bucketRule = parseAccessRule(member.type, sourceFile, resolveCtx)
1379
- assertAccessRuleIsRenderable(bucketRule, bucketId, key)
1380
- access[key] = bucketRule
1381
- }
1382
- return access
1383
- }
1384
-
1385
- /** Parse human-readable size from schema types, e.g. `50MB`. */
1386
- function parseDataSizeBytes(lit: string): number {
1387
- const m = lit.trim().match(/^(\d+(?:\.\d+)?)\s*(B|KB|MB|GB)$/i)
1388
- if (!m?.[1] || !m[2]) throw new Error(`Invalid maxSize literal: "${lit}". Use forms like "50MB", "100KB".`)
1389
- const n = Number(m[1])
1390
- if (!Number.isFinite(n) || n < 0) throw new Error(`Invalid maxSize number in: "${lit}"`)
1391
- const pow: Record<string, number> = {
1392
- B: 0,
1393
- KB: 10,
1394
- MB: 20,
1395
- GB: 30,
1396
- }
1397
- const unit = m[2].toUpperCase() as keyof typeof pow
1398
- const exp = pow[unit]
1399
- if (exp === undefined) throw new Error(`Unsupported maxSize unit in: "${lit}"`)
1400
- return Math.round(n * Math.pow(2, exp))
1401
- }
1402
-
1403
- function stripQuotes(s: string): string {
1404
- return s.replace(/^['"]|['"]$/g, "")
1405
- }
1406
-
1407
- function bucketsEqual(a: ExtractedStorageBucketAst, b: ExtractedStorageBucketAst): boolean {
1408
- return (
1409
- a.public === b.public &&
1410
- (a.accessMode ?? "private") === (b.accessMode ?? "private") &&
1411
- JSON.stringify(a.access ?? null) === JSON.stringify(b.access ?? null) &&
1412
- JSON.stringify(a.allowedMimeTypes ?? null) === JSON.stringify(b.allowedMimeTypes ?? null) &&
1413
- (a.fileSizeLimit ?? null) === (b.fileSizeLimit ?? null) &&
1414
- (a.s3BucketPolicy ?? null) === (b.s3BucketPolicy ?? null)
1415
- )
1416
- }
1417
-
1418
- function attachStorageFieldMeta(
1419
- field: ParsedField,
1420
- bucketId: string,
1421
- bucketsById: Map<string, ExtractedStorageBucketAst>,
1422
- ): ParsedField {
1423
- const cfg = bucketsById.get(bucketId)
1424
- if (cfg?.accessMode !== undefined) {
1425
- return {
1426
- ...field,
1427
- kernel: { ...field.kernel, accessMode: cfg.accessMode },
1428
- }
1429
- }
1430
- return field
1431
- }
1432
-
1433
- function parseBlocksTypeDefinitions(
1434
- blocksArg: ts.TypeNode | undefined,
1435
- sourceFile: ts.SourceFile,
1436
- blockAliases: Map<string, BlockDefinitionAst>,
1437
- bucketAliases: Map<string, string>,
1438
- bucketsById: Map<string, ExtractedStorageBucketAst>,
1439
- context: FieldParseContext = {},
1440
- resolveCtx: ResolveContext,
1441
- ): BlockDefinitionAst[] {
1442
- if (!blocksArg) return []
1443
- const parts = ts.isUnionTypeNode(blocksArg) ? blocksArg.types : [blocksArg]
1444
- const out: BlockDefinitionAst[] = []
1445
- for (const part of parts) {
1446
- if (ts.isTypeReferenceNode(part) && ts.isIdentifier(part.typeName)) {
1447
- if (part.typeName.text === "Block") {
1448
- const inline = parseInlineBlockDefinition(
1449
- part,
1450
- sourceFile,
1451
- blockAliases,
1452
- bucketAliases,
1453
- bucketsById,
1454
- context,
1455
- resolveCtx,
1456
- )
1457
- if (inline) out.push(inline)
1458
- continue
1459
- }
1460
- const aliased = blockAliases.get(part.typeName.text)
1461
- if (aliased) out.push(aliased)
1462
- }
1463
- }
1464
- return out
1465
- }
1466
-
1467
- function parseInlineBlockDefinition(
1468
- ref: ts.TypeReferenceNode,
1469
- sourceFile: ts.SourceFile,
1470
- blockAliases: Map<string, BlockDefinitionAst>,
1471
- bucketAliases: Map<string, string>,
1472
- bucketsById: Map<string, ExtractedStorageBucketAst>,
1473
- context: FieldParseContext = {},
1474
- resolveCtx: ResolveContext,
1475
- ): BlockDefinitionAst | null {
1476
- const [nameArg, fieldsArg, metaArg] = ref.typeArguments ?? []
1477
- const name = literalStringType(nameArg)
1478
- if (!name || !fieldsArg || !ts.isTypeLiteralNode(fieldsArg)) return null
1479
-
1480
- const fields: Record<string, FieldAstV2> = {}
1481
- for (const member of fieldsArg.members) {
1482
- if (!ts.isPropertySignature(member) || !member.type) continue
1483
- const fieldName = getPropertyName(member.name)
1484
- if (!fieldName) continue
1485
- fields[fieldName] = parseFieldType(
1486
- fieldName,
1487
- member.type,
1488
- sourceFile,
1489
- blockAliases,
1490
- bucketAliases,
1491
- bucketsById,
1492
- context,
1493
- resolveCtx,
1494
- )
1495
- }
1496
-
1497
- let label: string | undefined
1498
- let icon: string | undefined
1499
- if (metaArg && ts.isTypeLiteralNode(metaArg)) {
1500
- for (const m of metaArg.members) {
1501
- if (!ts.isPropertySignature(m) || !m.type) continue
1502
- const key = getPropertyName(m.name)
1503
- if (!key) continue
1504
- const value = literalStringType(m.type)
1505
- if (!value) continue
1506
- if (key === "label") label = value
1507
- if (key === "icon") icon = value
1508
- }
1509
- }
1510
-
1511
- return {
1512
- name,
1513
- ...(label !== undefined && { label }),
1514
- ...(icon !== undefined && { icon }),
1515
- fields,
1516
- }
1517
- }
1518
-
1519
- function literalStringType(typeNode: ts.TypeNode | undefined): string | null {
1520
- if (!typeNode) return null
1521
- if (ts.isLiteralTypeNode(typeNode) && ts.isStringLiteral(typeNode.literal)) return typeNode.literal.text
1522
- return null
1523
- }
1524
-
1525
- /** Field names referenced in `{name}` and `{truncate(name, n)}` (case-sensitive, same as model fields). */
1526
- function fieldNamesInComputedTemplate(template: string): string[] {
1527
- const fields = new Set<string>()
1528
- const reTrunc = /\{truncate\s*\(\s*([a-zA-Z_]\w*)\s*,\s*(\d+)\s*\)\}/gi
1529
- let m: RegExpExecArray | null
1530
- while ((m = reTrunc.exec(template)) !== null) {
1531
- const ref = m[1]
1532
- if (ref) fields.add(ref)
1533
- }
1534
- const reSimple = /\{([a-zA-Z_]\w*)\}/g
1535
- while ((m = reSimple.exec(template)) !== null) {
1536
- const ref = m[1]
1537
- if (ref) fields.add(ref)
1538
- }
1539
- return [...fields]
1540
- }
1541
-
1542
- function looksLikeComputedTemplateLiteral(lit: string): boolean {
1543
- return /\{truncate\s*\(/i.test(lit) || /\{[a-zA-Z_]\w*\}/g.test(lit)
1544
- }
1545
-
1546
- /** Resolves second type arg of `ComputedFrom<Value, Sources>`, tuple concat, single field, or template literal. */
1547
- function parseComputedFromSecondArg(
1548
- sourcesArg: ts.TypeNode | undefined,
1549
- sourceFile: ts.SourceFile,
1550
- ): { sources: string[]; template?: string } | null {
1551
- if (!sourcesArg) return null
1552
- const single = literalStringType(sourcesArg)
1553
- if (single) {
1554
- if (looksLikeComputedTemplateLiteral(single)) {
1555
- return { sources: fieldNamesInComputedTemplate(single), template: single }
1556
- }
1557
- return { sources: [single] }
1558
- }
1559
-
1560
- const elemsFromTupleType = (tuple: ts.TupleTypeNode): ts.TypeNode[] | null => {
1561
- const nodes: ts.TypeNode[] = []
1562
- for (const el of tuple.elements) {
1563
- if (ts.isNamedTupleMember(el)) {
1564
- if (!el.type) return null
1565
- nodes.push(el.type)
1566
- continue
1567
- }
1568
- nodes.push(el as ts.TypeNode)
1569
- }
1570
- return nodes
1571
- }
1572
-
1573
- const tupleElems = (): ts.TypeNode[] | null => {
1574
- if (ts.isTupleTypeNode(sourcesArg)) return elemsFromTupleType(sourcesArg)
1575
- if (ts.isTypeOperatorNode(sourcesArg) && sourcesArg.operator === ts.SyntaxKind.ReadonlyKeyword) {
1576
- const inner = sourcesArg.type
1577
- if (inner && ts.isTupleTypeNode(inner)) return elemsFromTupleType(inner)
1578
- }
1579
- return null
1580
- }
1581
-
1582
- const elems = tupleElems()
1583
- if (!elems || elems.length === 0) return null
1584
- const keys: string[] = []
1585
- for (const node of elems) {
1586
- const k = literalStringType(node)
1587
- if (!k) return null
1588
- keys.push(k)
1589
- }
1590
- return { sources: keys }
1591
- }
1592
-
1593
- function resolveBucketName(
1594
- typeArg: ts.TypeNode | undefined,
1595
- sourceFile: ts.SourceFile,
1596
- bucketAliases: Map<string, string>,
1597
- fallback: string,
1598
- ): string {
1599
- if (!typeArg) return fallback
1600
- if (ts.isTypeReferenceNode(typeArg) && ts.isIdentifier(typeArg.typeName)) {
1601
- return bucketAliases.get(typeArg.typeName.text) ?? typeArg.typeName.text
1602
- }
1603
- return literalStringType(typeArg) ?? (typeArg.getText(sourceFile).replace(/^['"]|['"]$/g, "") || fallback)
1604
- }
1605
-
1606
- function isBooleanLiteralType(typeNode: ts.TypeNode, value: boolean): boolean {
1607
- if (value) {
1608
- if (typeNode.kind === ts.SyntaxKind.TrueKeyword) return true
1609
- if (ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === ts.SyntaxKind.TrueKeyword) {
1610
- return true
1611
- }
1612
- return false
1613
- }
1614
- if (typeNode.kind === ts.SyntaxKind.FalseKeyword) return true
1615
- if (ts.isLiteralTypeNode(typeNode) && typeNode.literal.kind === ts.SyntaxKind.FalseKeyword) {
1616
- return true
1617
- }
1618
- return false
1619
- }
1620
-
1621
- function parseAssetFieldOptions(
1622
- optionsArg: ts.TypeNode | undefined,
1623
- sourceFile: ts.SourceFile,
1624
- ): { localized: boolean } {
1625
- if (!optionsArg || !ts.isTypeLiteralNode(optionsArg)) return { localized: false }
1626
- for (const member of optionsArg.members) {
1627
- if (!ts.isPropertySignature(member) || !member.type) continue
1628
- const key = getPropertyName(member.name)
1629
- if (key === "localized" && isBooleanLiteralType(member.type, true)) {
1630
- return { localized: true }
1631
- }
1632
- }
1633
- return { localized: false }
1634
- }
1635
-
1636
- /** What `versions` resolved to on a model, or absent when the model declares none. */
1637
- type ParsedVersions = { drafts: boolean; keep: number }
1638
-
1639
- /** Versions kept per record when a model states no retention. Mirrors `model-versioning.ts`. */
1640
- const DEFAULT_VERSIONS_KEPT = 20
1641
-
1642
- /**
1643
- * `versions: true` or `versions: { drafts, keep }`.
1644
- *
1645
- * A malformed member is ignored rather than fatal, matching every other key here: the declaration is
1646
- * a *type*, so TypeScript has already refused anything `ModelVersionsOptions` does not allow, and
1647
- * this parser's job is reading what compiled rather than validating it a second time.
1648
- */
1649
- function parseVersions(typeNode: ts.TypeNode): ParsedVersions | undefined {
1650
- if (isBooleanLiteralType(typeNode, true)) {
1651
- return { drafts: true, keep: DEFAULT_VERSIONS_KEPT }
1652
- }
1653
- if (isBooleanLiteralType(typeNode, false)) return undefined
1654
- if (!ts.isTypeLiteralNode(typeNode)) return undefined
1655
-
1656
- const parsed: ParsedVersions = { drafts: true, keep: DEFAULT_VERSIONS_KEPT }
1657
- for (const member of typeNode.members) {
1658
- if (!ts.isPropertySignature(member) || !member.type) continue
1659
- const key = getPropertyName(member.name)
1660
- if (key === "drafts") {
1661
- if (isBooleanLiteralType(member.type, false)) parsed.drafts = false
1662
- if (isBooleanLiteralType(member.type, true)) parsed.drafts = true
1663
- } else if (
1664
- key === "keep" &&
1665
- ts.isLiteralTypeNode(member.type) &&
1666
- ts.isNumericLiteral(member.type.literal)
1667
- ) {
1668
- const keep = Number(member.type.literal.text)
1669
- // A retention of zero would prune the draft being edited, so it reads as "unstated" rather
1670
- // than as an instruction to keep nothing.
1671
- if (Number.isFinite(keep) && keep >= 1) parsed.keep = Math.floor(keep)
1672
- }
1673
- }
1674
- return parsed
1675
- }
1676
-
1677
- interface MetaLiteral {
1678
- tableName?: string
1679
- label?: string
1680
- labelPlural?: string
1681
- singleton?: boolean
1682
- timestamps?: boolean
1683
- softDelete?: boolean
1684
- autoLocalize?: boolean
1685
- versions?: ParsedVersions
1686
- searchable?: string[]
1687
- }
1688
-
1689
- function parseMetaLiteral(
1690
- metaArg: ts.TypeNode | undefined,
1691
- sourceFile: ts.SourceFile,
1692
- ): MetaLiteral {
1693
- const result: MetaLiteral = {}
1694
-
1695
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return result
1696
-
1697
- for (const member of metaArg.members) {
1698
- if (!ts.isPropertySignature(member) || !member.type) continue
1699
- const key = getPropertyName(member.name)
1700
- if (!key) continue
1701
-
1702
- if (key === "singleton" && isBooleanLiteralType(member.type, true)) {
1703
- result.singleton = true
1704
- } else if (key === "timestamps") {
1705
- if (isBooleanLiteralType(member.type, true)) result.timestamps = true
1706
- if (isBooleanLiteralType(member.type, false)) result.timestamps = false
1707
- } else if (key === "softDelete") {
1708
- if (isBooleanLiteralType(member.type, true)) result.softDelete = true
1709
- if (isBooleanLiteralType(member.type, false)) result.softDelete = false
1710
- } else if (key === "autoLocalize" && isBooleanLiteralType(member.type, true)) {
1711
- result.autoLocalize = true
1712
- } else if (key === "searchable" && ts.isTupleTypeNode(member.type)) {
1713
- result.searchable = member.type.elements
1714
- .map(literalStringType)
1715
- .filter((name): name is string => name !== null)
1716
- } else if (key === "versions") {
1717
- const versions = parseVersions(member.type)
1718
- if (versions !== undefined) result.versions = versions
1719
- } else if (key === "tableName" || key === "label" || key === "labelPlural") {
1720
- const text = literalStringType(member.type)
1721
- if (text !== null) result[key] = text
1722
- }
1723
- }
1724
-
1725
- return result
1726
- }
1727
-
1728
- function hasCompositeWrapper(typeNode: ts.TypeNode, wrapperName: string): boolean {
1729
- if (!ts.isTypeReferenceNode(typeNode) || !ts.isIdentifier(typeNode.typeName)) return false
1730
- if (typeNode.typeName.text === wrapperName) return true
1731
- if (
1732
- typeNode.typeName.text === "WithTimestamps" ||
1733
- typeNode.typeName.text === "WithSoftDelete" ||
1734
- typeNode.typeName.text === "WithPublishable"
1735
- ) {
1736
- const inner = typeNode.typeArguments?.[0]
1737
- if (inner) return hasCompositeWrapper(inner, wrapperName)
1738
- }
1739
- return false
1740
- }
1741
-
1742
- function parseModelMeta(
1743
- metaArg: ts.TypeNode | undefined,
1744
- sourceFile: ts.SourceFile,
1745
- modelName: string,
1746
- fieldsArg: ts.TypeNode,
1747
- fields: Record<string, FieldAstV2>,
1748
- resolveCtx: ResolveContext,
1749
- ): {
1750
- tableName: string
1751
- access: Record<string, unknown>
1752
- options: Record<string, unknown>
1753
- indexes: unknown[]
1754
- constraints: unknown[]
1755
- hooks: Record<string, ParsedModelHook>
1756
- validators: Record<string, ParsedModelHook>
1757
- searchFields: string[]
1758
- cache: ParsedModelCache | undefined
1759
- } {
1760
- const literal = parseMetaLiteral(metaArg, sourceFile)
1761
- const singleton = literal.singleton === true
1762
- const tableName =
1763
- literal.tableName ?? (singleton ? `_global_${toSnakeCase(modelName)}` : toSnakeCase(modelName))
1764
-
1765
- const timestamps =
1766
- literal.timestamps ??
1767
- (hasCompositeWrapper(fieldsArg, "WithTimestamps") ||
1768
- (fields["created_at"] !== undefined && fields["updated_at"] !== undefined))
1769
-
1770
- const softDelete =
1771
- literal.softDelete ??
1772
- (hasCompositeWrapper(fieldsArg, "WithSoftDelete") || fields["deleted_at"] !== undefined)
1773
-
1774
- const options: Record<string, unknown> = {}
1775
- if (singleton) options.singleton = true
1776
- if (timestamps) options.timestamps = true
1777
- if (softDelete) options.softDelete = true
1778
- if (literal.autoLocalize === true) options.autoLocalize = true
1779
- if (literal.versions !== undefined) options.versions = literal.versions
1780
- if (literal.label !== undefined) options.label = literal.label
1781
- if (literal.labelPlural !== undefined) options.labelPlural = literal.labelPlural
1782
-
1783
- const access = parseModelAccess(metaArg, sourceFile, modelName, fields, resolveCtx)
1784
- if (literal.versions !== undefined) assertVersionsWithoutFieldRules(access, modelName)
1785
-
1786
- const cache = parseModelCache(metaArg, sourceFile)
1787
- if (cache !== undefined) assertCacheIsServable(cache, access, fields, modelName)
1788
-
1789
- return {
1790
- tableName,
1791
- access,
1792
- options,
1793
- searchFields: resolveSearchFields(literal.searchable, fields, modelName),
1794
- indexes: parseModelIndexes(metaArg, sourceFile, fields),
1795
- constraints: parseModelConstraints(metaArg, sourceFile, modelName, fields, resolveCtx),
1796
- hooks: parseModelHooks(metaArg, sourceFile),
1797
- validators: parseModelValidators(metaArg, sourceFile, modelName, fields),
1798
- // Always present, possibly undefined: a conditional spread here infers the key away entirely
1799
- // and the caller cannot destructure it. emitModel is what decides whether it reaches the AST.
1800
- cache,
1801
- }
1802
- }
1803
-
1804
- /**
1805
- * Refuse a cache declaration the runtime cannot honour, naming the model and the reason.
1806
- *
1807
- * Both checks exist because the failure they prevent is silent. A public entry on a caller-varying
1808
- * table serves one user's rows to another and looks like a cache hit. `rows: true` on a table with
1809
- * no primary key is simply never registered, and reads stay exactly as fast as they were with a
1810
- * setting in the schema saying otherwise.
1811
- *
1812
- * Checked here rather than left to the server for the same reason the constraint operands are: the
1813
- * message can name what the author wrote.
1814
- */
1815
- function assertCacheIsServable(
1816
- cache: ParsedModelCache,
1817
- access: Record<string, unknown>,
1818
- fields: Record<string, FieldAstV2>,
1819
- model: string,
1820
- ): void {
1821
- if (cache.public === true) {
1822
- const read = access["read"] as AccessRuleNode | undefined
1823
- if (isIdentityDependent(read)) {
1824
- throw new Error(
1825
- `Model "${model}": \`cache.public\` cannot be used with an \`access.read\` rule that ` +
1826
- `varies by caller. A public cache entry is shared by everyone, so one caller's rows ` +
1827
- `would be served to another. Use \`cache: { enabled: true }\` for per-user entries, or ` +
1828
- `make the read rule row-independent: a rule like \`Lte<"published_at", Now>\` varies by ` +
1829
- `row without varying by caller and is safe to share.`,
1830
- )
1831
- }
1832
- }
1833
-
1834
- if (cache.rows === true) {
1835
- const keyed = Object.keys(fields).filter((f) => fields[f]?.["primaryKey"] === true)
1836
- if (keyed.length === 0) {
1837
- throw new Error(
1838
- `Model "${model}": \`cache.rows\` needs a primary key, because the row cache's key IS the ` +
1839
- `primary key, so there is nothing to cache by. Declare one, or drop \`rows\` and keep the ` +
1840
- `response cache, which has no such requirement.`,
1841
- )
1842
- }
1843
- }
1844
-
1845
- assertTtlIsInRange(cache.maxTtl, model)
1846
- }
1847
-
1848
- /**
1849
- * The columns Studio's list view searches, from either way of saying so.
1850
- *
1851
- * Two spellings, because they answer different questions: `Searchable<string>` on the field says
1852
- * *this column is worth searching*, and `searchable: ["title", "name"]` on the model says *search
1853
- * these, in this order*, which matters because the list view filters on the first one. A model
1854
- * using both gets the explicit order first and any remaining flagged columns after it.
1855
- *
1856
- * A name that matches no field throws rather than being dropped. Silently ignoring it is how this
1857
- * whole feature came to be inert: the declaration compiled and nothing downstream ever saw it.
1858
- */
1859
- function resolveSearchFields(
1860
- declared: string[] | undefined,
1861
- fields: Record<string, FieldAstV2>,
1862
- modelName: string,
1863
- ): string[] {
1864
- const ordered: string[] = []
1865
-
1866
- for (const name of declared ?? []) {
1867
- if (fields[name] === undefined) {
1868
- throw new Error(
1869
- `Model "${modelName}": \`searchable\` names "${name}", which is not a field on this model. ` +
1870
- `Searchable columns are: ${Object.keys(fields).join(", ")}.`,
1871
- )
1872
- }
1873
- if (!ordered.includes(name)) ordered.push(name)
1874
- }
1875
-
1876
- for (const [name, field] of Object.entries(fields)) {
1877
- if (field.annotations?.platform?.searchable !== true) continue
1878
- if (!ordered.includes(name)) ordered.push(name)
1879
- }
1880
-
1881
- return ordered
1882
- }
1883
-
1884
- /**
1885
- * The bounds the admin API already enforces, enforced where the number was written.
1886
- *
1887
- * `cache_max_ttl` is refused outside 0–86400 by `PATCH /admin/v1/config/rest`, and a declared cap
1888
- * is the same quantity. Left to the server, an out-of-range `maxTtl` reaches it as part of a
1889
- * manifest rather than a request (nothing refuses a manifest), and the ceiling it produces is
1890
- * whatever the arithmetic makes of it: a negative cap reads as "no cap declared" and permits more
1891
- * than the author asked for, which is the one direction a ceiling must never move in.
1892
- */
1893
- function assertTtlIsInRange(ttl: number | undefined, model: string): void {
1894
- if (ttl === undefined) return
1895
- if (!Number.isInteger(ttl)) {
1896
- throw new Error(
1897
- `Model "${model}": \`cache.maxTtl\` must be a whole number of seconds, not ${ttl}.`,
1898
- )
1899
- }
1900
- if (ttl < 0 || ttl > MAX_CACHE_TTL_SECONDS) {
1901
- throw new Error(
1902
- `Model "${model}": \`cache.maxTtl\` must be between 0 and ${MAX_CACHE_TTL_SECONDS} seconds ` +
1903
- `(24 hours), not ${ttl}. That is the same bound the admin API enforces on the project-wide ` +
1904
- `cache TTL, and a declaration outside it is not a cap the runtime can apply.`,
1905
- )
1906
- }
1907
- }
1908
-
1909
- /** The admin API's bound on a cache TTL, in seconds. */
1910
- const MAX_CACHE_TTL_SECONDS = 86_400
1911
-
1912
- /**
1913
- * Refuse a model that declares both `versions` and per-column rules.
1914
- *
1915
- * A version snapshot is opaque `jsonb`. `supatype_mask` is driven by security labels on a specific
1916
- * table's column and rewrites references to *that* column; the view tier puts the same expression in
1917
- * a view over the real columns. Neither can see inside a snapshot, so a masked value would sit in
1918
- * plain sight in `<table>_versions` for anyone able to read it, and there is no narrower grant to
1919
- * hide it behind now that drafts are visible to the record's creator.
1920
- *
1921
- * Refused here rather than left to the engine for the same reason the constraint operands are: the
1922
- * message can name the model and the columns the author wrote.
1923
- */
1924
- function assertVersionsWithoutFieldRules(access: Record<string, unknown>, model: string): void {
1925
- const fields = access["fields"]
1926
- if (typeof fields !== "object" || fields === null) return
1927
- const masked = Object.keys(fields)
1928
- if (masked.length === 0) return
1929
-
1930
- throw new Error(
1931
- `Model "${model}": \`versions\` and \`access.fields\` cannot both be declared. ` +
1932
- `A version snapshot is opaque JSONB, so the per-column rules on ` +
1933
- `${masked.map((c) => `\`${c}\``).join(", ")} cannot be enforced inside it and the value would ` +
1934
- `be readable in the versions table. Drop one: keep the field rules, or version a model that ` +
1935
- `does not mask a column.`,
1936
- )
1937
- }
1938
-
1939
- /**
1940
- * Operands a `CHECK` cannot evaluate, and why.
1941
- *
1942
- * All of these are legal in an access rule, which is exactly why they need refusing here rather
1943
- * than left to fail at `CREATE TABLE`: the vocabulary is shared, so the mistake is easy and the
1944
- * error Postgres gives for it names nothing useful.
1945
- */
1946
- const CONSTRAINT_FORBIDDEN_OPERANDS: Record<string, string> = {
1947
- authUid: "a CHECK constraint cannot see who is writing",
1948
- authRole: "a CHECK constraint cannot see who is writing",
1949
- claim: "a CHECK constraint cannot read the caller's JWT",
1950
- role: "a CHECK constraint cannot see the caller's role",
1951
- now: "a row valid on insert would become invalid on update, so a constraint cannot read the clock",
1952
- startOf: "a constraint cannot read the clock",
1953
- ago: "a constraint cannot read the clock",
1954
- fromNow: "a constraint cannot read the clock",
1955
- rows: "a CHECK constraint cannot query another table",
1956
- exists: "a CHECK constraint cannot query another table",
1957
- }
1958
-
1959
- /**
1960
- * Walk a parsed constraint node and refuse anything the database cannot enforce as a `CHECK`.
1961
- *
1962
- * Walks the parsed form rather than the syntax, so a node reached through `Any`, `All` or `Not`
1963
- * is checked the same as a top-level one.
1964
- */
1965
- function assertConstraintIsEnforceable(node: unknown, model: string, index: number): void {
1966
- if (Array.isArray(node)) {
1967
- for (const item of node) assertConstraintIsEnforceable(item, model, index)
1968
- return
1969
- }
1970
- if (typeof node !== "object" || node === null) return
1971
-
1972
- const record = node as Record<string, unknown>
1973
- for (const key of ["type", "kind"]) {
1974
- const value = record[key]
1975
- if (typeof value !== "string") continue
1976
- const why = CONSTRAINT_FORBIDDEN_OPERANDS[value]
1977
- if (why !== undefined) {
1978
- throw new Error(
1979
- `Model "${model}": constraint ${index + 1} uses \`${value}\`, which is not allowed in a ` +
1980
- `constraint because ${why}. Move the rule to \`access\` if it depends on the caller.`,
1981
- )
1982
- }
1983
- }
1984
- for (const value of Object.values(record)) assertConstraintIsEnforceable(value, model, index)
1985
- }
1986
-
1987
- /**
1988
- * Resolve `Length<>` and `ItemCount<>` inside a constraint to the measure their column actually
1989
- * takes, so the engine renders mechanically and never has to know about field kinds.
1990
- *
1991
- * Done here because this is the only layer that has both halves: the field's kind, and the table
1992
- * the bounds modifiers already resolve against. The engine seeing `JSONB` cannot tell an array from
1993
- * an object, and a second kind table in Rust is how `char_length(text[])` would come back in a new
1994
- * file after being fixed once.
1995
- */
1996
- function resolveConstraintMeasures(
1997
- node: unknown,
1998
- fields: Record<string, FieldAstV2>,
1999
- model: string,
2000
- index: number,
2001
- ): void {
2002
- if (Array.isArray(node)) {
2003
- for (const item of node) resolveConstraintMeasures(item, fields, model, index)
2004
- return
2005
- }
2006
- if (typeof node !== "object" || node === null) return
2007
-
2008
- const record = node as Record<string, unknown>
2009
- const kind = record["kind"]
2010
- if (kind === "length" || kind === "itemCount") {
2011
- const column = String(record["column"])
2012
- const field = fields[column]
2013
- if (!field) {
2014
- throw new Error(
2015
- `Model "${model}": constraint ${index + 1} measures \`${column}\`, which is not a field on ` +
2016
- "this model. Measures need a declared field, because the measure depends on its type.",
2017
- )
2018
- }
2019
- const measure = kind === "length" ? "length" : "items"
2020
- const resolved = measureFormFor(field.kind as FieldKind, measure, {
2021
- jsonIsArray: field["jsonArray"] === true,
2022
- })
2023
- if (resolved.form === undefined) {
2024
- throw new Error(
2025
- `Model "${model}": constraint ${index + 1} uses ` +
2026
- `\`${kind === "length" ? "Length" : "ItemCount"}<"${column}">\`, but ` +
2027
- `${resolved.instead}.`,
2028
- )
2029
- }
2030
- record["form"] = resolved.form
2031
- return
2032
- }
2033
-
2034
- for (const value of Object.values(record)) {
2035
- resolveConstraintMeasures(value, fields, model, index)
2036
- }
2037
- }
2038
-
2039
- /**
2040
- * Read `constraints` from a model's meta.
2041
- *
2042
- * Reuses `parseAccessRule`, because a constraint *is* an access rule with a narrower operand set:
2043
- * a second parser for the same node vocabulary would be two grammars to keep aligned, and they
2044
- * would drift the first time either gained a node.
2045
- */
2046
- function parseModelConstraints(
2047
- metaArg: ts.TypeNode | undefined,
2048
- sourceFile: ts.SourceFile,
2049
- modelName: string,
2050
- fields: Record<string, FieldAstV2>,
2051
- resolveCtx: ResolveContext,
2052
- ): unknown[] {
2053
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return []
2054
-
2055
- const prop = metaArg.members.find(
2056
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "constraints",
2057
- )
2058
- if (!prop || !ts.isPropertySignature(prop) || !prop.type) return []
2059
-
2060
- if (!ts.isTupleTypeNode(prop.type)) {
2061
- throw new Error(
2062
- `Model "${modelName}": \`constraints\` must be a tuple, as in ` +
2063
- `\`constraints: [Lte<"starts_at", "ends_at">]\`.`,
2064
- )
2065
- }
2066
-
2067
- return prop.type.elements.map((element, index) => {
2068
- const parsed = parseAccessRule(element, sourceFile, resolveCtx)
2069
- if (parsed["type"] === "private") {
2070
- throw new Error(
2071
- `Model "${modelName}": constraint ${index + 1}, ` +
2072
- `\`${ownerText(element, sourceFile)}\`, is not a rule this vocabulary knows.`,
2073
- )
2074
- }
2075
- assertConstraintIsEnforceable(parsed, modelName, index)
2076
- resolveConstraintMeasures(parsed, fields, modelName, index)
2077
- return parsed
2078
- })
2079
- }
2080
-
2081
- /** One lifecycle hook: `"fn-name"` or `{ function: "fn-name", timeout: 5000 }`. */
2082
- interface ParsedModelHook {
2083
- function: string
2084
- timeout?: number
2085
- onUnavailable?: "reject" | "log"
2086
- }
2087
-
2088
- const HOOK_EVENTS = ["beforeChange", "afterChange", "beforeDelete", "afterDelete"] as const
2089
-
2090
- /**
2091
- * Read `hooks` from a model's meta.
2092
- *
2093
- * Deliberately strict: an entry that is neither a string nor an object with a `function` name is
2094
- * **dropped**, and `validateModelHooks` then reports the model whose hook did not survive. A hook
2095
- * silently not firing is the failure this feature cannot have, so an unreadable declaration must
2096
- * fail the push rather than extract to nothing.
2097
- */
2098
- /**
2099
- * Read `validate` from a model's meta: field name to the function that checks it.
2100
- *
2101
- * Strict for the same reason `parseModelHooks` is: a validator that silently never fires is the
2102
- * failure this feature cannot have. An entry that is neither a string nor an object with a
2103
- * `function` name is dropped here and reported by `validateModelHooks`, which fails the push.
2104
- *
2105
- * Keyed by the **field** as written, not the column: the extractor resolves the two, and a validator
2106
- * naming a field the model does not declare is an error worth catching here where the message can
2107
- * list what the model does have.
2108
- */
2109
- function parseModelValidators(
2110
- metaArg: ts.TypeNode | undefined,
2111
- sourceFile: ts.SourceFile,
2112
- modelName: string,
2113
- fields: Record<string, FieldAstV2>,
2114
- ): Record<string, ParsedModelHook> {
2115
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return {}
2116
-
2117
- const prop = metaArg.members.find(
2118
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "validate",
2119
- )
2120
- if (!prop || !ts.isPropertySignature(prop) || !prop.type) return {}
2121
- if (!ts.isTypeLiteralNode(prop.type)) {
2122
- throw new Error(
2123
- `Model "${modelName}": \`validate\` must be an object mapping a field to a function name, ` +
2124
- 'as in `validate: { setupItems: "validate-setup-items" }`.',
2125
- )
2126
- }
2127
-
2128
- const out: Record<string, ParsedModelHook> = {}
2129
- for (const member of prop.type.members) {
2130
- if (!ts.isPropertySignature(member) || !member.type) continue
2131
- const field = getPropertyName(member.name)
2132
- if (!field) continue
2133
-
2134
- if (!Object.prototype.hasOwnProperty.call(fields, field)) {
2135
- const known = Object.keys(fields).join(", ")
2136
- throw new Error(
2137
- `Model "${modelName}": \`validate\` names "${field}", which is not a field on this model. ` +
2138
- `Fields are: ${known}.`,
2139
- )
2140
- }
2141
-
2142
- const parsed = parseModelHookValue(member.type, sourceFile)
2143
- if (parsed === null) {
2144
- throw new Error(
2145
- `Model "${modelName}": the validator for "${field}" must be a function name, or an object ` +
2146
- 'with a `function` name, as in `{ function: "check-it", timeout: 5000 }`.',
2147
- )
2148
- }
2149
- out[field] = parsed
2150
- }
2151
- return out
2152
- }
2153
-
2154
- function parseModelHooks(
2155
- metaArg: ts.TypeNode | undefined,
2156
- sourceFile: ts.SourceFile,
2157
- ): Record<string, ParsedModelHook> {
2158
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return {}
2159
-
2160
- const hooksProp = metaArg.members.find(
2161
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "hooks",
2162
- )
2163
- if (!hooksProp || !ts.isPropertySignature(hooksProp) || !hooksProp.type) return {}
2164
- if (!ts.isTypeLiteralNode(hooksProp.type)) return {}
2165
-
2166
- const hooks: Record<string, ParsedModelHook> = {}
2167
- for (const member of hooksProp.type.members) {
2168
- if (!ts.isPropertySignature(member) || !member.type) continue
2169
- const event = getPropertyName(member.name)
2170
- if (!event || !(HOOK_EVENTS as readonly string[]).includes(event)) continue
2171
-
2172
- const parsed = parseModelHookValue(member.type, sourceFile)
2173
- if (parsed !== null) hooks[event] = parsed
2174
- }
2175
- return hooks
2176
- }
2177
-
2178
- function parseModelHookValue(
2179
- node: ts.TypeNode,
2180
- sourceFile: ts.SourceFile,
2181
- ): ParsedModelHook | null {
2182
- const literal = literalStringType(node)
2183
- if (literal !== null) {
2184
- return literal.trim().length > 0 ? { function: literal } : null
2185
- }
2186
- if (!ts.isTypeLiteralNode(node)) return null
2187
-
2188
- let fn: string | undefined
2189
- let timeout: number | undefined
2190
- let onUnavailable: "reject" | "log" | undefined
2191
-
2192
- for (const member of node.members) {
2193
- if (!ts.isPropertySignature(member) || !member.type) continue
2194
- const key = getPropertyName(member.name)
2195
- if (key === "function") {
2196
- const value = literalStringType(member.type)
2197
- if (value !== null && value.trim().length > 0) fn = value
2198
- } else if (key === "timeout") {
2199
- timeout = parseNumericTypeArg(member.type, sourceFile)
2200
- } else if (key === "onUnavailable") {
2201
- const value = literalStringType(member.type)
2202
- if (value === "reject" || value === "log") onUnavailable = value
2203
- }
2204
- }
2205
-
2206
- if (fn === undefined) return null
2207
- return {
2208
- function: fn,
2209
- ...(timeout !== undefined && { timeout }),
2210
- ...(onUnavailable !== undefined && { onUnavailable }),
2211
- }
2212
- }
2213
-
2214
- function parseModelIndexes(
2215
- metaArg: ts.TypeNode | undefined,
2216
- sourceFile: ts.SourceFile,
2217
- fields: Record<string, FieldAstV2>,
2218
- ): unknown[] {
2219
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return []
2220
-
2221
- const indexesProp = metaArg.members.find(
2222
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "indexes",
2223
- )
2224
- if (
2225
- !indexesProp ||
2226
- !ts.isPropertySignature(indexesProp) ||
2227
- !indexesProp.type ||
2228
- !ts.isTupleTypeNode(indexesProp.type)
2229
- ) {
2230
- return []
2231
- }
2232
-
2233
- const indexes: unknown[] = []
2234
- for (const element of indexesProp.type.elements) {
2235
- if (!ts.isTypeLiteralNode(element)) continue
2236
- const indexDef: Record<string, unknown> = { using: "btree", unique: false }
2237
- for (const member of element.members) {
2238
- if (!ts.isPropertySignature(member) || !member.type) continue
2239
- const key = getPropertyName(member.name)
2240
- if (!key) continue
2241
- if (key === "name") {
2242
- const name = literalStringType(member.type)
2243
- if (name !== null) indexDef.name = name
2244
- } else if (key === "unique" && isBooleanLiteralType(member.type, true)) {
2245
- indexDef.unique = true
2246
- } else if (key === "fields" && ts.isTupleTypeNode(member.type)) {
2247
- indexDef.fields = member.type.elements
2248
- .map((fieldNode) => {
2249
- if (!ts.isLiteralTypeNode(fieldNode) || !ts.isStringLiteral(fieldNode.literal)) return null
2250
- return resolveIndexFieldName(fieldNode.literal.text, fields)
2251
- })
2252
- .filter((field): field is string => field !== null)
2253
- }
2254
- }
2255
- if (Array.isArray(indexDef.fields) && indexDef.fields.length > 0) {
2256
- indexes.push(indexDef)
2257
- }
2258
- }
2259
- return indexes
2260
- }
2261
-
2262
- function resolveIndexFieldName(fieldName: string, fields: Record<string, FieldAstV2>): string | null {
2263
- if (fields[fieldName] !== undefined) {
2264
- const field = fields[fieldName]
2265
- if (field.kind === "relation" && field.annotations?.db?.foreignKey) {
2266
- return field.annotations.db.foreignKey as string
2267
- }
2268
- return fieldName
2269
- }
2270
- return fieldName
2271
- }
2272
-
2273
- /**
2274
- * Resolve an `access:` annotation to its rule object.
2275
- *
2276
- * `access` may be written inline (`access: { read: Public }`) or factored into a
2277
- * shared type alias (`access: CmsPublicReadAdminWrite`), the latter is the
2278
- * natural way to reuse one policy set across many models, so it has to resolve
2279
- * through aliases and intersections, not just literals.
2280
- *
2281
- * Anything unresolvable throws. Returning `{}` here means "no access rules",
2282
- * which the differ treats as "emit no RLS policies", so a typo or an
2283
- * unsupported shape silently published a table with no row-level protection at
2284
- * all. Failing the extract is the only safe outcome.
2285
- */
2286
- /**
2287
- * Nodes that parse but that the engine's RLS renderer does not know.
2288
- *
2289
- * `Length`, `ItemCount` and `Matches` exist for `constraints`, and they share a parser with access
2290
- * rules because a constraint *is* an access rule with a narrower operand set. That reuse runs both
2291
- * ways: nothing stops someone writing `Gte<Length<"title">, Literal<5>>` in an `access` block, where
2292
- * it would parse cleanly, reach an engine that has no case for it, and produce a policy that does
2293
- * not say what the author wrote. Refusing here keeps the sharing honest until the RLS renderer
2294
- * learns them.
2295
- */
2296
- const CONSTRAINT_ONLY_NODES = new Set(["length", "itemCount", "matches"])
2297
-
2298
- function assertAccessRuleIsRenderable(node: unknown, model: string, operation: string): void {
2299
- if (Array.isArray(node)) {
2300
- for (const item of node) assertAccessRuleIsRenderable(item, model, operation)
2301
- return
2302
- }
2303
- if (typeof node !== "object" || node === null) return
2304
-
2305
- const record = node as Record<string, unknown>
2306
- // Operands are tagged `kind`, rules `type`, so both are checked: `Matches` is a rule.
2307
- const tag = [record["kind"], record["type"]].find(
2308
- (value) => typeof value === "string" && CONSTRAINT_ONLY_NODES.has(value),
2309
- )
2310
- if (typeof tag === "string") {
2311
- const spelled = { length: "Length", itemCount: "ItemCount", matches: "Matches" }[tag] ?? tag
2312
- throw new Error(
2313
- `Model "${model}": \`${spelled}<>\` is not supported in an \`access\` rule (\`${operation}\`). ` +
2314
- "It belongs in `constraints`, which the database enforces for every writer.",
2315
- )
2316
- }
2317
- for (const value of Object.values(record)) {
2318
- assertAccessRuleIsRenderable(value, model, operation)
2319
- }
2320
- }
2321
-
2322
- function parseModelAccess(
2323
- metaArg: ts.TypeNode | undefined,
2324
- sourceFile: ts.SourceFile,
2325
- modelName: string,
2326
- fields: Record<string, FieldAstV2>,
2327
- resolveCtx: ResolveContext,
2328
- ): Record<string, unknown> {
2329
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return {}
2330
- const accessProp = metaArg.members.find(
2331
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "access",
2332
- )
2333
- if (!accessProp || !ts.isPropertySignature(accessProp) || !accessProp.type) {
2334
- return {}
2335
- }
2336
-
2337
- const literal = resolveAccessLiteral(accessProp.type, sourceFile, resolveCtx)
2338
- if (!literal) {
2339
- throw new Error(
2340
- `Model "${modelName}": could not resolve its \`access\` rules from ` +
2341
- `\`${accessProp.type.getText(sourceFile)}\`.\n` +
2342
- ` access must be an object type, or a type alias for one:\n` +
2343
- ` export type PublicReadAdminWrite = { read: Public; create: Role<"admin"> }\n` +
2344
- ` A \`const … as const\` value cannot be used here, access is read from types, and\n` +
2345
- ` rule names like Public / Role are types, not values.\n` +
2346
- ` Refusing to continue: an unresolved access block would publish this table with no RLS.`,
2347
- )
2348
- }
2349
-
2350
- const access: Record<string, unknown> = {}
2351
- for (const member of literal.members) {
2352
- if (!ts.isPropertySignature(member) || !member.type) continue
2353
- const key = getPropertyName(member.name)
2354
- if (!key) continue
2355
-
2356
- // `update: { using, check }` splits which rows may be changed from what they
2357
- // may be changed into. Flattened here into the two AST fields the engine
2358
- // renders, so the engine never has to know about the sugar.
2359
- if (key === "update") {
2360
- const split = parseUpdateSplit(member.type, sourceFile, resolveCtx)
2361
- if (split) {
2362
- access["update"] = split.using
2363
- if (split.check !== undefined) access["updateCheck"] = split.check
2364
- continue
2365
- }
2366
- }
2367
-
2368
- if (key === "fields") {
2369
- const fieldRules = parseFieldAccess(member.type, sourceFile, modelName, fields, resolveCtx)
2370
- if (Object.keys(fieldRules).length > 0) access["fields"] = fieldRules
2371
- continue
2372
- }
2373
-
2374
- const rule = parseAccessRule(member.type, sourceFile, resolveCtx)
2375
- assertAccessRuleIsRenderable(rule, modelName, key)
2376
- access[key] = rule
2377
- }
2378
-
2379
- if (Object.keys(access).length === 0) {
2380
- throw new Error(
2381
- `Model "${modelName}": \`access\` resolved to an empty rule set ` +
2382
- `(from \`${accessProp.type.getText(sourceFile)}\`). Remove \`access\` if the table is ` +
2383
- `intentionally unrestricted, or declare at least one of read/create/update/delete.`,
2384
- )
2385
- }
2386
- return access
2387
- }
2388
-
2389
- /**
2390
- * `fields: { [column]: { read?, write? } }`, per-column narrowing of the table rules.
2391
- *
2392
- * Any rule the DSL can express is allowed. Enforcement is a query rewrite that
2393
- * evaluates the rule per row with the caller's claims, so ownership, membership and
2394
- * application roles all work here, none of which a column privilege could express.
2395
- */
2396
- function parseFieldAccess(
2397
- typeNode: ts.TypeNode,
2398
- sourceFile: ts.SourceFile,
2399
- modelName: string,
2400
- fields: Record<string, FieldAstV2>,
2401
- resolveCtx?: ResolveContext,
2402
- ): Record<string, Record<string, unknown>> {
2403
- const literal = resolveCtx
2404
- ? resolveAccessLiteral(typeNode, sourceFile, resolveCtx)
2405
- : ts.isTypeLiteralNode(typeNode)
2406
- ? typeNode
2407
- : null
2408
- if (!literal) {
2409
- throw new Error(
2410
- `Model "${modelName}": could not resolve \`access.fields\` from ` +
2411
- `\`${typeNode.getText(sourceFile)}\`. It must be an object type, or a type ` +
2412
- `alias for one: \`fields: { salary: { read: Private } }\`.`,
2413
- )
2414
- }
2415
-
2416
- const out: Record<string, Record<string, unknown>> = {}
2417
- for (const member of literal.members) {
2418
- if (!ts.isPropertySignature(member) || !member.type) continue
2419
- const declared = getPropertyName(member.name)
2420
- if (!declared) continue
2421
- // A privilege is granted on a column, and a relation field is not one --
2422
- // `author` is stored as `author_id`. Same mapping the index builder uses.
2423
- // Names that match nothing are passed through rather than rejected: composite
2424
- // wrappers expand into columns this map never sees, so a hard error here would
2425
- // refuse valid schemas. Postgres rejects the unknown column at push instead.
2426
- const column = resolveIndexFieldName(declared, fields) ?? declared
2427
-
2428
- const columnLiteral = resolveCtx
2429
- ? resolveAccessLiteral(member.type, sourceFile, resolveCtx)
2430
- : ts.isTypeLiteralNode(member.type)
2431
- ? member.type
2432
- : null
2433
- if (!columnLiteral) {
2434
- throw new Error(
2435
- `Model "${modelName}": \`access.fields.${column}\` must be an object with ` +
2436
- `\`read\` and/or \`write\`, found \`${member.type.getText(sourceFile)}\`.`,
2437
- )
2438
- }
2439
-
2440
- const rules: Record<string, unknown> = {}
2441
- for (const opMember of columnLiteral.members) {
2442
- if (!ts.isPropertySignature(opMember) || !opMember.type) continue
2443
- const operation = getPropertyName(opMember.name)
2444
- if (operation !== "read" && operation !== "write") {
2445
- throw new Error(
2446
- `Model "${modelName}": \`access.fields.${column}\` may only contain ` +
2447
- `\`read\` and \`write\`, found "${operation}".`,
2448
- )
2449
- }
2450
- rules[operation] = parseAccessRule(opMember.type, sourceFile, resolveCtx)
2451
- }
2452
-
2453
- // An empty `{}` reads as "this column is restricted" but restricts nothing.
2454
- if (Object.keys(rules).length === 0) {
2455
- throw new Error(
2456
- `Model "${modelName}": \`access.fields.${column}\` declares no rules. ` +
2457
- `Give it a \`read\` or a \`write\`, or remove the entry.`,
2458
- )
2459
- }
2460
- out[column] = rules
2461
- }
2462
- return out
2463
- }
2464
-
2465
- /**
2466
- * `update: { using: …, check: … }`, or null when `update` is a plain rule.
2467
- *
2468
- * An update policy has two halves: `USING` picks which existing rows may be
2469
- * modified, `WITH CHECK` constrains what they may become. One rule for both is the
2470
- * right default and what every existing schema means, but it makes "an editor may
2471
- * move a post between their own sites" inexpressible, because the row they are
2472
- * changing and the row they are changing it into are judged by the same predicate.
2473
- */
2474
- function parseUpdateSplit(
2475
- typeNode: ts.TypeNode,
2476
- sourceFile: ts.SourceFile,
2477
- resolveCtx?: ResolveContext,
2478
- ): { using: Record<string, unknown>; check?: Record<string, unknown> } | null {
2479
- const literal = resolveCtx
2480
- ? resolveAccessLiteral(typeNode, sourceFile, resolveCtx)
2481
- : ts.isTypeLiteralNode(typeNode)
2482
- ? typeNode
2483
- : null
2484
- if (!literal) return null
2485
-
2486
- let using: ts.TypeNode | undefined
2487
- let check: ts.TypeNode | undefined
2488
- for (const member of literal.members) {
2489
- if (!ts.isPropertySignature(member) || !member.type) continue
2490
- const name = getPropertyName(member.name)
2491
- if (name === "using") using = member.type
2492
- else if (name === "check") check = member.type
2493
- else if (name !== undefined) {
2494
- throw new Error(
2495
- `\`update\` may only contain \`using\` and \`check\`, found "${name}".`,
2496
- )
2497
- }
2498
- }
2499
-
2500
- // Not the split form at all, an object with neither key is some other shape.
2501
- if (!using && !check) return null
2502
- if (!using) {
2503
- throw new Error(
2504
- "`update: { check }` needs a `using` rule too, without it no row is " +
2505
- "selectable for update, so the check can never apply.",
2506
- )
2507
- }
2508
-
2509
- const parsed: { using: Record<string, unknown>; check?: Record<string, unknown> } = {
2510
- using: parseAccessRule(using, sourceFile, resolveCtx),
2511
- }
2512
- if (check) parsed.check = parseAccessRule(check, sourceFile, resolveCtx)
2513
- return parsed
2514
- }
2515
-
2516
- /** Walk aliases/intersections down to the object type holding the access rules. */
2517
- function resolveAccessLiteral(
2518
- typeNode: ts.TypeNode,
2519
- sourceFile: ts.SourceFile,
2520
- resolveCtx: ResolveContext,
2521
- depth = 0,
2522
- ): ts.TypeLiteralNode | null {
2523
- if (depth > 16) return null
2524
- if (ts.isTypeLiteralNode(typeNode)) return typeNode
2525
-
2526
- if (ts.isIntersectionTypeNode(typeNode)) {
2527
- const members: ts.TypeElement[] = []
2528
- for (const part of typeNode.types) {
2529
- const resolved = resolveAccessLiteral(part, sourceFile, resolveCtx, depth + 1)
2530
- if (!resolved) return null
2531
- members.push(...resolved.members)
2532
- }
2533
- return ts.factory.createTypeLiteralNode(members)
2534
- }
2535
-
2536
- if (ts.isTypeReferenceNode(typeNode)) {
2537
- const expanded = tryResolveTypeReference(typeNode, sourceFile, resolveCtx)
2538
- if (expanded) return resolveAccessLiteral(expanded, sourceFile, resolveCtx, depth + 1)
2539
- }
2540
-
2541
- if (needsChecker(typeNode)) {
2542
- const resolved = resolveTypeNode(typeNode, sourceFile, resolveCtx)
2543
- if (resolved !== typeNode) {
2544
- return resolveAccessLiteral(resolved, sourceFile, resolveCtx, depth + 1)
2545
- }
2546
- }
2547
-
2548
- return null
2549
- }
2550
-
2551
- /**
2552
- * `access` rules may be declared in a different file from the model (a shared
2553
- * alias), and `getText(file)` reads the given file's text at the node's offsets
2554
- *- so passing the model's file for a node owned by another one yielded garbage
2555
- * and every rule silently fell through to `private`. Always read a node's text
2556
- * from the file that actually owns it.
2557
- */
2558
- function ownerText(node: ts.Node, fallback: ts.SourceFile): string {
2559
- const own = node.pos >= 0 ? node.getSourceFile() : undefined
2560
- return node.getText(own ?? fallback)
2561
- }
2562
-
2563
- function parseAccessRule(
2564
- typeNode: ts.TypeNode,
2565
- sourceFile: ts.SourceFile,
2566
- resolveCtx?: ResolveContext,
2567
- depth = 0,
2568
- ): Record<string, unknown> {
2569
- // Reuse a single rule from a shared set: `access: { read: Rules["read"] }`.
2570
- if (ts.isIndexedAccessTypeNode(typeNode) && resolveCtx) {
2571
- const member = resolveIndexedAccessRule(typeNode, sourceFile, resolveCtx)
2572
- if (member) return parseAccessRule(member, sourceFile, resolveCtx)
2573
- throw new Error(
2574
- `Could not resolve access rule from \`${ownerText(typeNode, sourceFile)}\`. ` +
2575
- `Reference a rule set member as \`Rules["read"]\`, where Rules is a type alias.`,
2576
- )
2577
- }
2578
-
2579
- if (!ts.isTypeReferenceNode(typeNode)) return { type: "private" }
2580
-
2581
- // `Rules.read` is a qualified name (namespace lookup), not a member of a type
2582
- // alias: TypeScript rejects it, and it used to fall through to `private`,
2583
- // silently denying an operation the author meant to grant.
2584
- if (ts.isQualifiedName(typeNode.typeName)) {
2585
- const text = ownerText(typeNode.typeName, sourceFile)
2586
- const [head, ...rest] = text.split(".")
2587
- throw new Error(
2588
- `Access rule \`${text}\` is not valid: a member of a rule-set type must be written ` +
2589
- `\`${head}["${rest.join(".")}"]\`, not \`${text}\`.`,
2590
- )
2591
- }
2592
-
2593
- const ref = ownerText(typeNode.typeName, sourceFile)
2594
- switch (ref) {
2595
- case "Public":
2596
- case "BucketPublic":
2597
- return { type: "public" }
2598
- case "LoggedIn":
2599
- case "BucketLoggedIn":
2600
- return { type: "authenticated" }
2601
- case "Private":
2602
- case "BucketPrivate":
2603
- return { type: "private" }
2604
- case "BucketOwner":
2605
- return { type: "owner", field: "owner_id" }
2606
- case "Owner": {
2607
- const args = typeNode.typeArguments ?? []
2608
- const keyArg = args.length >= 2 ? args[1] : args[0]
2609
- // Must match engine `AccessRule::Owner { field }` (see supatype-schema-engine parser/ast.rs).
2610
- return {
2611
- type: "owner",
2612
- field: keyArg ? ownerText(keyArg, sourceFile).replace(/['"]/g, "") : "user_id",
2613
- }
2614
- }
2615
- case "OwnerFrom": {
2616
- const relationArg = typeNode.typeArguments?.[0]
2617
- const relationField = relationArg
2618
- ? ownerText(relationArg, sourceFile).replace(/['"]/g, "")
2619
- : "owner"
2620
- return { type: "owner", field: relationField }
2621
- }
2622
- case "Role":
2623
- case "BucketRole": {
2624
- const roleArg = typeNode.typeArguments?.[0]
2625
- return {
2626
- type: "role",
2627
- roles: [roleArg ? ownerText(roleArg, sourceFile).replace(/['"]/g, "") : "admin"],
2628
- }
2629
- }
2630
- case "Any": {
2631
- const listArg = typeNode.typeArguments?.[0]
2632
- if (!listArg || !ts.isTupleTypeNode(listArg)) {
2633
- throw new Error(
2634
- `\`Any<>\` takes a tuple of rules, as in ` +
2635
- `\`Any<[Role<"admin">, Owner<"author_id">]>\`.`,
2636
- )
2637
- }
2638
- // An empty list would compile to a policy that grants nothing while
2639
- // reading like a grant, the exact silent-denial failure the unknown-rule
2640
- // branch below exists to prevent.
2641
- if (listArg.elements.length === 0) {
2642
- throw new Error(
2643
- "`Any<[]>` grants nothing. List the rules that should allow access, or " +
2644
- "use `Private` if denying is the intent.",
2645
- )
2646
- }
2647
- return {
2648
- type: "any",
2649
- rules: listArg.elements.map((element) =>
2650
- parseAccessRule(element, sourceFile, resolveCtx),
2651
- ),
2652
- }
2653
- }
2654
- case "All": {
2655
- const listArg = typeNode.typeArguments?.[0]
2656
- if (!listArg || !ts.isTupleTypeNode(listArg)) {
2657
- throw new Error(
2658
- '`All<>` takes a tuple of rules, as in `All<[Role<"editor">, NotNull<"published_at">]>`.',
2659
- )
2660
- }
2661
- // Unlike `Any<[]>`, an empty `All` grants *everything*, an empty AND is
2662
- // true. Reading as a restriction while imposing none is worse than an error.
2663
- if (listArg.elements.length === 0) {
2664
- throw new Error(
2665
- "`All<[]>` restricts nothing and grants everything. List the rules that " +
2666
- "must hold, or use `Public` if that is the intent.",
2667
- )
2668
- }
2669
- return {
2670
- type: "all",
2671
- rules: listArg.elements.map((element) =>
2672
- parseAccessRule(element, sourceFile, resolveCtx),
2673
- ),
2674
- }
2675
- }
2676
- case "Not": {
2677
- const inner = typeNode.typeArguments?.[0]
2678
- if (!inner) {
2679
- throw new Error('`Not<>` takes one rule, as in `Not<Role<"banned">>`.')
2680
- }
2681
- return { type: "not", rule: parseAccessRule(inner, sourceFile, resolveCtx) }
2682
- }
2683
- case "Eq":
2684
- case "Neq":
2685
- case "Gt":
2686
- case "Gte":
2687
- case "Lt":
2688
- case "Lte":
2689
- case "Like": {
2690
- const args = typeNode.typeArguments ?? []
2691
- if (args.length !== 2) {
2692
- throw new Error(
2693
- `\`${ref}<>\` takes two operands, as in \`${ref}<"author_id", AuthUid>\`.`,
2694
- )
2695
- }
2696
- return {
2697
- type: "compare",
2698
- op: ref.toLowerCase(),
2699
- left: parseAccessOperand(args[0]!, sourceFile),
2700
- right: parseAccessOperand(args[1]!, sourceFile),
2701
- }
2702
- }
2703
- case "Matches": {
2704
- const args = typeNode.typeArguments ?? []
2705
- if (args.length !== 2) {
2706
- throw new Error(
2707
- '`Matches<>` takes a column and a pattern, as in `Matches<"sku", "^[A-Z]{3}$">`.',
2708
- )
2709
- }
2710
- const column = stringLiteralArg(args[0], "Matches", "column")
2711
- const pattern = literalStringType(args[1] as ts.TypeNode)
2712
- if (pattern === null) {
2713
- throw new Error(
2714
- '`Matches<>` needs a string literal pattern, as in `Matches<"sku", "^[A-Z]{3}$">`.',
2715
- )
2716
- }
2717
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(column)) {
2718
- throw new Error(`\`Matches<"${column}", ...>\` does not name a valid column.`)
2719
- }
2720
- // Validated here so an unparseable pattern is a CLI error naming the field, rather than a
2721
- // Postgres error part way through a migration. Postgres regex is POSIX and JavaScript's is
2722
- // not, so this catches malformed patterns, not every dialect difference.
2723
- try {
2724
- new RegExp(pattern)
2725
- } catch {
2726
- throw new Error(
2727
- `\`Matches<"${column}", "${pattern}">\`: the pattern is not a valid regular expression.`,
2728
- )
2729
- }
2730
- return { type: "matches", column, pattern }
2731
- }
2732
- case "IsNull":
2733
- case "NotNull": {
2734
- const operand = typeNode.typeArguments?.[0]
2735
- if (!operand) {
2736
- throw new Error(`\`${ref}<>\` takes one operand, as in \`${ref}<"deleted_at">\`.`)
2737
- }
2738
- return {
2739
- type: "nullCheck",
2740
- operand: parseAccessOperand(operand, sourceFile),
2741
- isNull: ref === "IsNull",
2742
- }
2743
- }
2744
- case "Exists": {
2745
- const source = typeNode.typeArguments?.[0]
2746
- if (!source) {
2747
- throw new Error('`Exists<>` takes a source, as in `Exists<MySites>`.')
2748
- }
2749
- return {
2750
- type: "exists",
2751
- source: parseMembershipSource(source, sourceFile, resolveCtx),
2752
- }
2753
- }
2754
- case "In": {
2755
- const args = typeNode.typeArguments ?? []
2756
- if (args.length !== 2) {
2757
- throw new Error(
2758
- '`In<>` takes a column and a source, as in `In<"site_id", MySites>`.',
2759
- )
2760
- }
2761
- const column = parseAccessOperand(args[0]!, sourceFile)
2762
- if (column["kind"] !== "column") {
2763
- throw new Error(
2764
- "`In<>`'s first argument must be a column name, the membership test is " +
2765
- "about a column of the row being checked.",
2766
- )
2767
- }
2768
- return {
2769
- type: "in",
2770
- column: column["name"],
2771
- source: parseMembershipSource(args[1]!, sourceFile, resolveCtx),
2772
- }
2773
- }
2774
- default: {
2775
- // A named alias: possibly parameterised, standing for a rule. Expanded
2776
- // before giving up, so `SiteAccess<"site_id">` works.
2777
- if (resolveCtx && depth < 16) {
2778
- const expanded = resolveAccessAliasNode(typeNode, sourceFile, resolveCtx)
2779
- if (expanded) return parseAccessRule(expanded, sourceFile, resolveCtx, depth + 1)
2780
- }
2781
-
2782
- // Falling back to `private` here would silently deny an operation the
2783
- // author believed they had granted, and with deny-by-default there is no
2784
- // longer any need for a permissive guess. Name the offending rule instead.
2785
- throw new Error(
2786
- `Unknown access rule "${ref}". Supported: Public, Private, LoggedIn, ` +
2787
- `Owner<"field">, OwnerFrom<"relation">, Role<"name">, ` +
2788
- `Any<[rule, …]>, All<[rule, …]>, Not<rule>, ` +
2789
- `Eq/Neq/Gt/Gte/Lt/Lte/Like<left, right>, IsNull<operand>, NotNull<operand>` +
2790
- ` (buckets also accept BucketPublic, BucketPrivate, BucketLoggedIn, BucketOwner, BucketRole).`,
2791
- )
2792
- }
2793
- }
2794
- }
2795
-
2796
- /**
2797
- * Expands a named alias to the type it stands for.
2798
- *
2799
- * This is what makes rules parameterisable, the type-level equivalent of
2800
- * Payload's access-control factory:
2801
- *
2802
- * ```typescript
2803
- * type SiteAccess<F extends string> = Any<[Role<"admin">, In<F, MySites>]>
2804
- * access: { update: SiteAccess<"site_id"> }
2805
- * ```
2806
- *
2807
- * Without it a rule had to be written inline at every use, and any alias, even an
2808
- * unparameterised one: was reported as an unknown rule.
2809
- */
2810
- function resolveAccessAliasNode(
2811
- typeNode: ts.TypeReferenceNode,
2812
- sourceFile: ts.SourceFile,
2813
- resolveCtx: ResolveContext,
2814
- ): ts.TypeNode | undefined {
2815
- const expanded = tryResolveTypeReference(typeNode, sourceFile, resolveCtx)
2816
- if (expanded && expanded !== typeNode) return expanded
2817
-
2818
- if (needsChecker(typeNode)) {
2819
- const resolved = resolveTypeNode(typeNode, sourceFile, resolveCtx)
2820
- if (resolved !== typeNode) return resolved
2821
- }
2822
- return undefined
2823
- }
2824
-
2825
- /**
2826
- * The set on the right of an `In<>`.
2827
- *
2828
- * Resolved through the same alias machinery as rules, so a shared
2829
- * `type MySites = Rows<…>` can be reused across models, the parameterisation the
2830
- * plan calls the type-level equivalent of Payload's access factory.
2831
- */
2832
- function parseMembershipSource(
2833
- typeNode: ts.TypeNode,
2834
- sourceFile: ts.SourceFile,
2835
- resolveCtx?: ResolveContext,
2836
- ): Record<string, unknown> {
2837
- if (ts.isIndexedAccessTypeNode(typeNode) && resolveCtx) {
2838
- const member = resolveIndexedAccessRule(typeNode, sourceFile, resolveCtx)
2839
- if (member) return parseMembershipSource(member, sourceFile, resolveCtx)
2840
- }
2841
-
2842
- if (ts.isTypeReferenceNode(typeNode) && !ts.isQualifiedName(typeNode.typeName)) {
2843
- const ref = ownerText(typeNode.typeName, sourceFile)
2844
- const args = typeNode.typeArguments ?? []
2845
-
2846
- if (ref === "Claim") {
2847
- return parseAccessOperand(typeNode, sourceFile)
2848
- }
2849
-
2850
- if (ref === "Rows") {
2851
- const table = stringLiteralArg(args[0], "Rows", "table name")
2852
- const column = stringLiteralArg(args[1], "Rows", "column name")
2853
- const source: Record<string, unknown> = { kind: "rows", table, column }
2854
- // The third argument narrows the source rows. Absent means "every row",
2855
- // which is a lookup rather than a membership check, allowed, but rarely
2856
- // what was meant, so it stays explicit rather than being defaulted.
2857
- if (args[2]) {
2858
- source["where"] = parseAccessRule(args[2], sourceFile, resolveCtx)
2859
- }
2860
- return source
2861
- }
2862
-
2863
- if (ref === "Values") {
2864
- const listArg = args[0]
2865
- if (!listArg || !ts.isTupleTypeNode(listArg)) {
2866
- throw new Error('`Values<>` takes a tuple, as in `Values<["draft", "review"]>`.')
2867
- }
2868
- if (listArg.elements.length === 0) {
2869
- throw new Error("`Values<[]>` matches nothing. List the values, or use `Private`.")
2870
- }
2871
- // Not `parseAccessOperand`: there, a bare string is a *column*, which is
2872
- // right for a comparison and wrong here. Inside a value list a string can
2873
- // only be a value, so it is read as one, no `Literal<>` wrapper needed.
2874
- return {
2875
- kind: "literal",
2876
- values: listArg.elements.map((element) => literalFromNode(element, sourceFile)),
2877
- }
2878
- }
2879
-
2880
- // A named alias for a source: `type MySites = Rows<…>`.
2881
- if (resolveCtx) {
2882
- const resolved = resolveAccessAliasNode(typeNode, sourceFile, resolveCtx)
2883
- if (resolved) return parseMembershipSource(resolved, sourceFile, resolveCtx)
2884
- }
2885
- }
2886
-
2887
- throw new Error(
2888
- `\`${ownerText(typeNode, sourceFile)}\` is not a valid membership source. Use ` +
2889
- `Rows<"table", "column", Where>, Claim<"path"> or Values<[…]>.`,
2890
- )
2891
- }
2892
-
2893
- /** Interval units, matching `TimeUnit` in `@supatype/types` and the engine. */
2894
- const TIME_UNITS = [
2895
- "seconds",
2896
- "minutes",
2897
- "hours",
2898
- "days",
2899
- "weeks",
2900
- "months",
2901
- "years",
2902
- ] as const
2903
-
2904
- /** Granularities for `StartOf<>`. */
2905
- const TRUNC_UNITS = ["day", "week", "month", "year"] as const
2906
-
2907
- /**
2908
- * `After<Base, { days: 30, hours: 9 }>` / `Before<...>`: a point in time plus or minus a
2909
- * multi-unit duration.
2910
- *
2911
- * The interval is re-assembled from parsed integers and matched keywords, exactly as
2912
- * `parseDurationOperand` does, so no author-supplied text reaches Postgres. A permissive
2913
- * `"30 days 9 hours"` string would be raw SQL by another name.
2914
- *
2915
- * Direction is in the operand name rather than the sign of a component, which is the rule
2916
- * `Ago`/`FromNow` already follow: a negative amount is refused with a message naming the
2917
- * opposite operand, because relying on a double negative reads wrongly.
2918
- */
2919
- function parseOffsetOperand(
2920
- ref: "After" | "Before",
2921
- args: readonly ts.TypeNode[],
2922
- sourceFile: ts.SourceFile,
2923
- ): Record<string, unknown> {
2924
- if (args.length !== 2) {
2925
- throw new Error(
2926
- `\`${ref}<>\` takes a base and an interval, as in ` +
2927
- `\`${ref}<StartOf<"day">, { days: 30, hours: 9 }>\`.`,
2928
- )
2929
- }
2930
-
2931
- const base = parseAccessOperand(args[0]!, sourceFile)
2932
- const baseKind = typeof base["kind"] === "string" ? base["kind"] : ""
2933
- if (baseKind !== "now" && baseKind !== "startOf") {
2934
- throw new Error(
2935
- `\`${ref}<>\` measures from a point in time, so its base must be \`Now\` or ` +
2936
- `\`StartOf<unit>\`. A column or a claim depends on the row or the caller and ` +
2937
- `cannot be offset.`,
2938
- )
2939
- }
2940
-
2941
- const intervalNode = args[1]!
2942
- if (!ts.isTypeLiteralNode(intervalNode)) {
2943
- throw new Error(
2944
- `\`${ref}<>\` takes the interval as an object, as in \`{ days: 30, hours: 9 }\`.`,
2945
- )
2946
- }
2947
-
2948
- const opposite = ref === "After" ? "Before" : "After"
2949
- const interval: Record<string, number> = {}
2950
-
2951
- for (const member of intervalNode.members) {
2952
- if (!ts.isPropertySignature(member) || !member.name || !member.type) {
2953
- throw new Error(`\`${ref}<>\` interval members must be \`unit: amount\` pairs.`)
2954
- }
2955
- const unit = member.name.getText(sourceFile).replace(/["']/g, "")
2956
- if (!TIME_UNITS.includes(unit as (typeof TIME_UNITS)[number])) {
2957
- throw new Error(
2958
- `\`${unit}\` is not a unit of time. Use one of: ${TIME_UNITS.join(", ")} (plural).`,
2959
- )
2960
- }
2961
-
2962
- const amountNode = member.type
2963
- // A negative literal is a prefix-unary expression, not a numeric literal, so it has
2964
- // to be recognised separately or it is refused for the wrong reason and the message
2965
- // misses the real advice.
2966
- if (
2967
- ts.isLiteralTypeNode(amountNode) &&
2968
- ts.isPrefixUnaryExpression(amountNode.literal) &&
2969
- amountNode.literal.operator === ts.SyntaxKind.MinusToken
2970
- ) {
2971
- throw new Error(
2972
- `\`${ref}<>\` does not take a negative amount. For the other direction use ` +
2973
- `\`${opposite}<>\`, which reads correctly instead of relying on a double negative.`,
2974
- )
2975
- }
2976
- if (!ts.isLiteralTypeNode(amountNode) || !ts.isNumericLiteral(amountNode.literal)) {
2977
- throw new Error(`\`${unit}\` needs a number literal amount, as in \`{ ${unit}: 30 }\`.`)
2978
- }
2979
- const amount = Number(amountNode.literal.text)
2980
- if (!Number.isInteger(amount)) {
2981
- throw new Error(
2982
- `\`{ ${unit}: ${amount} }\` must be a whole number of units: Postgres intervals ` +
2983
- `take integers, so a fraction would be silently truncated or rejected.`,
2984
- )
2985
- }
2986
- if (unit in interval) {
2987
- throw new Error(`\`${ref}<>\` names \`${unit}\` twice; give each unit once.`)
2988
- }
2989
- interval[unit] = amount
2990
- }
2991
-
2992
- // An all-zero interval means the base unchanged, which is never what an author wrote.
2993
- // The engine refuses it too, but saying so here names the operand at the point it was
2994
- // written rather than at push.
2995
- if (Object.values(interval).every((amount) => amount === 0)) {
2996
- throw new Error(
2997
- `\`${ref}<>\` was given an empty interval, which means the base unchanged. ` +
2998
- `Give at least one non-zero unit, as in \`{ days: 30 }\`.`,
2999
- )
3000
- }
3001
-
3002
- return { kind: ref === "After" ? "after" : "before", base, interval }
3003
- }
3004
-
3005
- /**
3006
- * `Ago<30, "days">` / `FromNow<7, "days">`.
3007
- *
3008
- * The amount and unit are validated here and the interval is re-assembled from the
3009
- * parsed integer and the matched keyword, so no author-supplied text reaches
3010
- * Postgres. That is what keeps this from being a small escape hatch: a permissive
3011
- * `"30 days"` string would be raw SQL by another name.
3012
- */
3013
- function parseDurationOperand(
3014
- ref: "Ago" | "FromNow",
3015
- args: readonly ts.TypeNode[],
3016
- sourceFile: ts.SourceFile,
3017
- ): Record<string, unknown> {
3018
- if (args.length !== 2) {
3019
- throw new Error(`\`${ref}<>\` takes an amount and a unit, as in \`${ref}<30, "days">\`.`)
3020
- }
3021
-
3022
- const amountNode = args[0]!
3023
- const opposite = ref === "Ago" ? "FromNow" : "Ago"
3024
-
3025
- // A negative literal is a prefix-unary expression in the TypeScript AST, not a
3026
- // numeric literal, so it has to be recognised separately, otherwise `Ago<-5, …>`
3027
- // is refused for the wrong reason and the message misses the real advice.
3028
- if (
3029
- ts.isLiteralTypeNode(amountNode) &&
3030
- ts.isPrefixUnaryExpression(amountNode.literal) &&
3031
- amountNode.literal.operator === ts.SyntaxKind.MinusToken
3032
- ) {
3033
- throw new Error(
3034
- `\`${ref}<>\` does not take a negative amount. For the other direction use ` +
3035
- `\`${opposite}<>\`, which reads correctly instead of relying on a double negative.`,
3036
- )
3037
- }
3038
-
3039
- if (!ts.isLiteralTypeNode(amountNode) || !ts.isNumericLiteral(amountNode.literal)) {
3040
- throw new Error(`\`${ref}<>\` needs a number literal amount, as in \`${ref}<30, "days">\`.`)
3041
- }
3042
- const amount = Number(amountNode.literal.text)
3043
- if (!Number.isInteger(amount)) {
3044
- throw new Error(
3045
- `\`${ref}<${amount}, …>\` must be a whole number of units, Postgres intervals ` +
3046
- `take integers, so a fraction would be silently truncated or rejected.`,
3047
- )
3048
- }
3049
-
3050
- const unit = stringLiteralArg(args[1], ref, "unit")
3051
- if (!TIME_UNITS.includes(unit as (typeof TIME_UNITS)[number])) {
3052
- throw new Error(
3053
- `\`${ref}<${amount}, "${unit}">\` is not a valid unit. Use one of: ` +
3054
- `${TIME_UNITS.join(", ")} (plural).`,
3055
- )
3056
- }
3057
-
3058
- void sourceFile
3059
- return { kind: ref === "Ago" ? "ago" : "fromNow", amount, unit }
3060
- }
3061
-
3062
- /** A string, number or boolean literal as its plain JS value. */
3063
- function literalFromNode(
3064
- node: ts.TypeNode,
3065
- sourceFile: ts.SourceFile,
3066
- ): string | number | boolean {
3067
- if (ts.isLiteralTypeNode(node)) {
3068
- const literal = node.literal
3069
- if (ts.isStringLiteral(literal)) return literal.text
3070
- if (ts.isNumericLiteral(literal)) return Number(literal.text)
3071
- if (literal.kind === ts.SyntaxKind.TrueKeyword) return true
3072
- if (literal.kind === ts.SyntaxKind.FalseKeyword) return false
3073
- }
3074
- throw new Error(
3075
- `\`${ownerText(node, sourceFile)}\` is not a string, number or boolean literal.`,
3076
- )
3077
- }
3078
-
3079
- function stringLiteralArg(
3080
- node: ts.TypeNode | undefined,
3081
- owner: string,
3082
- what: string,
3083
- ): string {
3084
- if (!node || !ts.isLiteralTypeNode(node) || !ts.isStringLiteral(node.literal)) {
3085
- throw new Error(`\`${owner}<>\` needs a ${what} as a string literal.`)
3086
- }
3087
- const value = node.literal.text.trim()
3088
- // Rendered as a SQL identifier, so refuse anything that is not one.
3089
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) {
3090
- throw new Error(`"${value}" is not a valid ${what}.`)
3091
- }
3092
- return value
3093
- }
3094
-
3095
- /**
3096
- * One side of a comparison.
3097
- *
3098
- * A bare string literal is a **column** on the model the rule is attached to.
3099
- * That is the common case by a wide margin, and making it the default keeps
3100
- * `Eq<"author_id", AuthUid>` readable; a constant is written `Literal<"x">` so the
3101
- * two can never be confused. Numbers and booleans are unambiguous, so they are
3102
- * taken as constants directly.
3103
- */
3104
- function parseAccessOperand(
3105
- typeNode: ts.TypeNode,
3106
- sourceFile: ts.SourceFile,
3107
- ): Record<string, unknown> {
3108
- if (ts.isLiteralTypeNode(typeNode)) {
3109
- const literal = typeNode.literal
3110
- if (ts.isStringLiteral(literal)) {
3111
- const name = literal.text.trim()
3112
- if (name === "") {
3113
- throw new Error("An empty column name is not a valid operand.")
3114
- }
3115
- // Rendered into SQL as an identifier, so refuse anything that is not one
3116
- // rather than letting it through to the policy.
3117
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
3118
- throw new Error(
3119
- `"${name}" is not a valid column name. Use \`Literal<"${name}">\` for a ` +
3120
- `constant, or quote a real column.`,
3121
- )
3122
- }
3123
- return { kind: "column", name }
3124
- }
3125
- if (ts.isNumericLiteral(literal)) {
3126
- return { kind: "literal", value: Number(literal.text) }
3127
- }
3128
- if (literal.kind === ts.SyntaxKind.TrueKeyword) return { kind: "literal", value: true }
3129
- if (literal.kind === ts.SyntaxKind.FalseKeyword) return { kind: "literal", value: false }
3130
- }
3131
-
3132
- if (ts.isTypeReferenceNode(typeNode) && !ts.isQualifiedName(typeNode.typeName)) {
3133
- const ref = ownerText(typeNode.typeName, sourceFile)
3134
- const operandArgs = typeNode.typeArguments ?? []
3135
- switch (ref) {
3136
- case "Length":
3137
- case "ItemCount": {
3138
- const column = stringLiteralArg(operandArgs[0], ref, "column")
3139
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(column)) {
3140
- throw new Error(`\`${ref}<"${column}">\` does not name a valid column.`)
3141
- }
3142
- return { kind: ref === "Length" ? "length" : "itemCount", column }
3143
- }
3144
- case "AuthUid":
3145
- return { kind: "authUid" }
3146
- case "AuthRole":
3147
- return { kind: "authRole" }
3148
- case "Now":
3149
- return { kind: "now" }
3150
- case "StartOf": {
3151
- const unit = stringLiteralArg(operandArgs[0], "StartOf", "unit")
3152
- if (!TRUNC_UNITS.includes(unit as (typeof TRUNC_UNITS)[number])) {
3153
- throw new Error(
3154
- `\`StartOf<"${unit}">\` is not a valid granularity. Use one of: ` +
3155
- `${TRUNC_UNITS.join(", ")}.`,
3156
- )
3157
- }
3158
- return { kind: "startOf", unit }
3159
- }
3160
- case "Ago":
3161
- case "FromNow":
3162
- return parseDurationOperand(ref, operandArgs, sourceFile)
3163
- case "After":
3164
- case "Before":
3165
- return parseOffsetOperand(ref, operandArgs, sourceFile)
3166
- case "Claim": {
3167
- const pathArg = typeNode.typeArguments?.[0]
3168
- if (!pathArg || !ts.isLiteralTypeNode(pathArg) || !ts.isStringLiteral(pathArg.literal)) {
3169
- throw new Error('`Claim<>` takes a dotted path literal, as in `Claim<"app_metadata.tier">`.')
3170
- }
3171
- const path = pathArg.literal.text.trim()
3172
- // The path is split on dots to walk the claims object, so an empty
3173
- // segment would silently look up a key that cannot exist.
3174
- if (path === "" || path.split(".").some((segment) => segment.trim() === "")) {
3175
- throw new Error(
3176
- `\`Claim<"${path}">\` is not a valid claim path, use dotted segments, ` +
3177
- `as in \`Claim<"app_metadata.tier">\`.`,
3178
- )
3179
- }
3180
- return { kind: "claim", path }
3181
- }
3182
- case "Literal": {
3183
- const valueArg = typeNode.typeArguments?.[0]
3184
- if (!valueArg || !ts.isLiteralTypeNode(valueArg)) {
3185
- throw new Error('`Literal<>` takes a string, number or boolean, as in `Literal<"published">`.')
3186
- }
3187
- const literal = valueArg.literal
3188
- if (ts.isStringLiteral(literal)) return { kind: "literal", value: literal.text }
3189
- if (ts.isNumericLiteral(literal)) return { kind: "literal", value: Number(literal.text) }
3190
- if (literal.kind === ts.SyntaxKind.TrueKeyword) return { kind: "literal", value: true }
3191
- if (literal.kind === ts.SyntaxKind.FalseKeyword) return { kind: "literal", value: false }
3192
- throw new Error('`Literal<>` takes a string, number or boolean.')
3193
- }
3194
- }
3195
- }
3196
-
3197
- throw new Error(
3198
- `\`${ownerText(typeNode, sourceFile)}\` is not a valid operand. Use a column name ` +
3199
- `("author_id"), AuthUid, AuthRole, Claim<"path"> or Literal<value>.`,
3200
- )
3201
- }
3202
-
3203
- interface ParsedRelationOptions {
3204
- required?: boolean
3205
- onDelete?: string
3206
- onUpdate?: string
3207
- through?: string
3208
- }
3209
-
3210
- function parseRelationOptions(
3211
- optsArg: ts.TypeNode | undefined,
3212
- sourceFile: ts.SourceFile,
3213
- ): ParsedRelationOptions {
3214
- const out: ParsedRelationOptions = {}
3215
- if (!optsArg || !ts.isTypeLiteralNode(optsArg)) return out
3216
-
3217
- for (const member of optsArg.members) {
3218
- if (!ts.isPropertySignature(member) || !member.name || !member.type) continue
3219
- const key = getPropertyName(member.name)
3220
- if (!key) continue
3221
-
3222
- if (key === "required" && isBooleanLiteralType(member.type, true)) {
3223
- out.required = true
3224
- continue
3225
- }
3226
-
3227
- if (key === "onDelete" || key === "onUpdate" || key === "through") {
3228
- const text = literalStringType(member.type)
3229
- if (text !== null) out[key] = text
3230
- }
3231
- }
3232
-
3233
- return out
3234
- }
3235
-
3236
- function relationOptionsKernel(
3237
- opts: ParsedRelationOptions,
3238
- ): Pick<KernelFieldFacts, "required" | "onDelete" | "onUpdate" | "through"> {
3239
- return {
3240
- ...(opts.required === true && { required: true }),
3241
- ...(opts.onDelete !== undefined && { onDelete: opts.onDelete }),
3242
- ...(opts.onUpdate !== undefined && { onUpdate: opts.onUpdate }),
3243
- ...(opts.through !== undefined && { through: opts.through }),
3244
- }
3245
- }
3246
-
3247
- function parseNumericTypeArg(typeArg: ts.TypeNode | undefined, sourceFile: ts.SourceFile): number | undefined {
3248
- if (!typeArg) return undefined
3249
- if (ts.isLiteralTypeNode(typeArg) && ts.isNumericLiteral(typeArg.literal)) {
3250
- const value = Number(typeArg.literal.text)
3251
- return Number.isFinite(value) ? value : undefined
3252
- }
3253
- if (ts.isLiteralTypeNode(typeArg) && ts.isStringLiteral(typeArg.literal)) {
3254
- const value = Number(typeArg.literal.text)
3255
- return Number.isFinite(value) ? value : undefined
3256
- }
3257
- const raw = typeArg.getText(sourceFile).trim()
3258
- const value = Number(raw)
3259
- return Number.isFinite(value) ? value : undefined
3260
- }
3261
-
3262
- function mergeCheckConstraint(existing: string | undefined, next: string): string {
3263
- if (!existing) return next
3264
- return `(${existing}) AND (${next})`
3265
- }
3266
-
3267
- function relationTargetFromTypeArg(typeArg: ts.TypeNode | undefined, sourceFile: ts.SourceFile): string {
3268
- if (!typeArg) return "unknown"
3269
- const raw = typeArg.getText(sourceFile).replace(/\s/g, "")
3270
- if (raw === "SupatypeAuthUser") return "supatype:user"
3271
- return raw.replace(/\W/g, "")
3272
- }
3273
-
3274
- function toSnakeCase(s: string): string {
3275
- return s.replace(/([A-Z])/g, "_$1").replace(/^_/, "").toLowerCase()
3276
- }
3277
-
3278
- function relationForeignKeyFromField(fieldName: string): string {
3279
- const snake = fieldName
3280
- .replace(/([A-Z]+)([A-Z][a-z])/g, "$1_$2")
3281
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
3282
- .toLowerCase()
3283
- const base = snake.replace(/_id$/i, "")
3284
- return `${base}_id`
3285
- }
3286
-
3287
- /** Resolve `Rules["read"]` to the rule type declared for that member. */
3288
- function resolveIndexedAccessRule(
3289
- node: ts.IndexedAccessTypeNode,
3290
- sourceFile: ts.SourceFile,
3291
- resolveCtx: ResolveContext,
3292
- ): ts.TypeNode | undefined {
3293
- const literal = resolveAccessLiteral(node.objectType, sourceFile, resolveCtx)
3294
- if (!literal) return undefined
3295
- if (!ts.isLiteralTypeNode(node.indexType) || !ts.isStringLiteral(node.indexType.literal)) {
3296
- return undefined
3297
- }
3298
- const key = node.indexType.literal.text
3299
- for (const member of literal.members) {
3300
- if (ts.isPropertySignature(member) && getPropertyName(member.name) === key) {
3301
- return member.type
3302
- }
3303
- }
3304
- return undefined
3305
- }
3306
-
3307
- // ─── cache declaration (P8, plan §13) ────────────────────────────────────────
3308
-
3309
- /** The parsed `cache` block. Absent entirely when the model declared none. */
3310
- export interface ParsedModelCache {
3311
- enabled?: boolean
3312
- maxTtl?: number
3313
- public?: boolean
3314
- rows?: boolean
3315
- }
3316
-
3317
- /**
3318
- * Parse `cache: { ... }` off a model's meta argument.
3319
- *
3320
- * Shaped like `parseModelHooks`, and travelling the same way: onto the route manifest beside
3321
- * `hooks`, not into `annotations.platform`. The schema engine re-serialises its own parsed AST
3322
- * (`serde_json::to_value(&ast)`), and `PlatformModelAnnotations` carries only `access` and
3323
- * `search_fields` with no catch-all, so a key placed there is silently dropped on the way to the
3324
- * server rather than riding through. Verified rather than assumed; see plan §13.1.
3325
- */
3326
- function parseModelCache(
3327
- metaArg: ts.TypeNode | undefined,
3328
- sourceFile: ts.SourceFile,
3329
- ): ParsedModelCache | undefined {
3330
- if (!metaArg || !ts.isTypeLiteralNode(metaArg)) return undefined
3331
-
3332
- const prop = metaArg.members.find(
3333
- (member) => ts.isPropertySignature(member) && getPropertyName(member.name) === "cache",
3334
- )
3335
- if (!prop || !ts.isPropertySignature(prop) || !prop.type) return undefined
3336
- if (!ts.isTypeLiteralNode(prop.type)) return undefined
3337
-
3338
- const parsed: ParsedModelCache = {}
3339
- for (const member of prop.type.members) {
3340
- if (!ts.isPropertySignature(member) || !member.type) continue
3341
- switch (getPropertyName(member.name)) {
3342
- case "enabled":
3343
- if (isBooleanLiteralType(member.type, true)) parsed.enabled = true
3344
- else if (isBooleanLiteralType(member.type, false)) parsed.enabled = false
3345
- break
3346
- case "public":
3347
- if (isBooleanLiteralType(member.type, true)) parsed.public = true
3348
- else if (isBooleanLiteralType(member.type, false)) parsed.public = false
3349
- break
3350
- case "rows":
3351
- if (isBooleanLiteralType(member.type, true)) parsed.rows = true
3352
- else if (isBooleanLiteralType(member.type, false)) parsed.rows = false
3353
- break
3354
- case "maxTtl": {
3355
- const ttl = parseNumericTypeArg(member.type, sourceFile)
3356
- if (ttl !== undefined) parsed.maxTtl = ttl
3357
- break
3358
- }
3359
- }
3360
- }
3361
- // A `cache: {}` with nothing readable in it is not a declaration. Returning an empty object
3362
- // would make the model "declared but permitting nothing", which reads the same as no block at
3363
- // all and would put an empty entry in every manifest.
3364
- return Object.keys(parsed).length > 0 ? parsed : undefined
3365
- }