@facilis.dev/nitro 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (267) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +18 -2
  3. package/dist/config.d.ts +30 -0
  4. package/dist/config.js +112 -0
  5. package/dist/constants.d.ts +24 -0
  6. package/dist/constants.js +24 -0
  7. package/dist/facade.d.ts +37 -0
  8. package/dist/facade.js +121 -0
  9. package/dist/index.d.ts +17 -0
  10. package/dist/index.js +14 -0
  11. package/dist/middleware/context.d.ts +5 -0
  12. package/dist/middleware/context.js +86 -0
  13. package/dist/middleware/cors.d.ts +10 -0
  14. package/dist/middleware/cors.js +34 -0
  15. package/dist/middleware/session.d.ts +9 -0
  16. package/dist/middleware/session.js +18 -0
  17. package/dist/module.d.ts +7 -0
  18. package/dist/module.js +234 -0
  19. package/dist/rolldown-parser.d.ts +3 -0
  20. package/dist/rolldown-parser.js +66 -0
  21. package/dist/route-metadata.d.ts +22 -0
  22. package/dist/route-metadata.js +161 -0
  23. package/dist/routes/dev-query.post.d.ts +10 -0
  24. package/dist/routes/dev-query.post.js +49 -0
  25. package/dist/routes/dev-schema.get.d.ts +9 -0
  26. package/dist/routes/dev-schema.get.js +34 -0
  27. package/dist/routes/dev-view.post.d.ts +11 -0
  28. package/dist/routes/dev-view.post.js +61 -0
  29. package/dist/routes/health.get.d.ts +8 -0
  30. package/dist/routes/health.get.js +18 -0
  31. package/dist/routes/manifest-revision.get.d.ts +8 -0
  32. package/dist/routes/manifest-revision.get.js +26 -0
  33. package/dist/routes/manifest.get.d.ts +8 -0
  34. package/dist/routes/manifest.get.js +68 -0
  35. package/dist/routes/openapi.get.d.ts +8 -0
  36. package/dist/routes/openapi.get.js +29 -0
  37. package/dist/routes/sso.d.ts +2 -0
  38. package/dist/routes/sso.js +216 -0
  39. package/dist/routes/token.post.d.ts +10 -0
  40. package/dist/routes/token.post.js +75 -0
  41. package/dist/runtime/boot-runtimes.d.ts +21 -0
  42. package/dist/runtime/boot-runtimes.js +38 -0
  43. package/dist/runtime/bootstrap.d.ts +47 -0
  44. package/dist/runtime/bootstrap.js +214 -0
  45. package/dist/runtime/config.d.ts +27 -0
  46. package/dist/runtime/config.js +44 -0
  47. package/dist/runtime/cors-policy.d.ts +16 -0
  48. package/dist/runtime/cors-policy.js +88 -0
  49. package/dist/runtime/db-bootstrap.d.ts +9 -0
  50. package/dist/runtime/db-bootstrap.js +87 -0
  51. package/dist/runtime/db-target.d.ts +21 -0
  52. package/dist/runtime/db-target.js +52 -0
  53. package/dist/runtime/dev-db-persistence.d.ts +39 -0
  54. package/dist/runtime/dev-db-persistence.js +124 -0
  55. package/dist/runtime/dev-query.d.ts +38 -0
  56. package/dist/runtime/dev-query.js +87 -0
  57. package/dist/runtime/env.d.ts +9 -0
  58. package/dist/runtime/env.js +14 -0
  59. package/dist/runtime/http-guard.d.ts +16 -0
  60. package/dist/runtime/http-guard.js +42 -0
  61. package/dist/runtime/http.d.ts +11 -0
  62. package/dist/runtime/http.js +18 -0
  63. package/dist/runtime/jobs/boot.d.ts +20 -0
  64. package/dist/runtime/jobs/boot.js +77 -0
  65. package/dist/runtime/jobs/contracts.d.ts +161 -0
  66. package/dist/runtime/jobs/contracts.js +1 -0
  67. package/dist/runtime/jobs/db-store.d.ts +21 -0
  68. package/dist/runtime/jobs/db-store.js +210 -0
  69. package/dist/runtime/jobs/definitions.d.ts +14 -0
  70. package/dist/runtime/jobs/definitions.js +31 -0
  71. package/dist/runtime/jobs/engine-support.d.ts +22 -0
  72. package/dist/runtime/jobs/engine-support.js +32 -0
  73. package/dist/runtime/jobs/engine.d.ts +6 -0
  74. package/dist/runtime/jobs/engine.js +261 -0
  75. package/dist/runtime/jobs/executor.d.ts +11 -0
  76. package/dist/runtime/jobs/executor.js +27 -0
  77. package/dist/runtime/jobs/memory-store.d.ts +7 -0
  78. package/dist/runtime/jobs/memory-store.js +183 -0
  79. package/dist/runtime/jobs/row-mapping.d.ts +28 -0
  80. package/dist/runtime/jobs/row-mapping.js +61 -0
  81. package/dist/runtime/jobs/runtime.d.ts +24 -0
  82. package/dist/runtime/jobs/runtime.js +86 -0
  83. package/dist/runtime/logging/audit-chain.d.ts +54 -0
  84. package/dist/runtime/logging/audit-chain.js +102 -0
  85. package/dist/runtime/logging/bootstrap-logging.d.ts +28 -0
  86. package/dist/runtime/logging/bootstrap-logging.js +26 -0
  87. package/dist/runtime/logging/entry.d.ts +14 -0
  88. package/dist/runtime/logging/entry.js +85 -0
  89. package/dist/runtime/logging/file-sink.d.ts +24 -0
  90. package/dist/runtime/logging/file-sink.js +128 -0
  91. package/dist/runtime/logging/log-settings.d.ts +52 -0
  92. package/dist/runtime/logging/log-settings.js +93 -0
  93. package/dist/runtime/logging/log-sink.d.ts +18 -0
  94. package/dist/runtime/logging/log-sink.js +22 -0
  95. package/dist/runtime/logging/redact.d.ts +31 -0
  96. package/dist/runtime/logging/redact.js +106 -0
  97. package/dist/runtime/logging/runtime.d.ts +25 -0
  98. package/dist/runtime/logging/runtime.js +114 -0
  99. package/dist/runtime/logging/sudo-bridge.d.ts +13 -0
  100. package/dist/runtime/logging/sudo-bridge.js +38 -0
  101. package/dist/runtime/manifest-data.d.ts +28 -0
  102. package/dist/runtime/manifest-data.js +70 -0
  103. package/dist/runtime/manifest-response.d.ts +45 -0
  104. package/dist/runtime/manifest-response.js +50 -0
  105. package/dist/runtime/manifest-sections.d.ts +20 -0
  106. package/dist/runtime/manifest-sections.js +59 -0
  107. package/dist/runtime/manifest-service.d.ts +16 -0
  108. package/dist/runtime/manifest-service.js +66 -0
  109. package/dist/runtime/project-config.d.ts +8 -0
  110. package/dist/runtime/project-config.js +22 -0
  111. package/dist/runtime/project-files.d.ts +12 -0
  112. package/dist/runtime/project-files.js +99 -0
  113. package/dist/runtime/rate-limit.d.ts +6 -0
  114. package/dist/runtime/rate-limit.js +6 -0
  115. package/dist/runtime/revision-service.d.ts +15 -0
  116. package/dist/runtime/revision-service.js +26 -0
  117. package/dist/runtime/sql.d.ts +8 -0
  118. package/dist/runtime/sql.js +23 -0
  119. package/dist/runtime/sso.d.ts +40 -0
  120. package/dist/runtime/sso.js +98 -0
  121. package/dist/runtime/state.d.ts +7 -0
  122. package/dist/runtime/state.js +7 -0
  123. package/dist/runtime/storage-keys.d.ts +9 -0
  124. package/dist/runtime/storage-keys.js +82 -0
  125. package/dist/runtime/storage-target.d.ts +25 -0
  126. package/dist/runtime/storage-target.js +155 -0
  127. package/dist/runtime/system-role.d.ts +9 -0
  128. package/dist/runtime/system-role.js +21 -0
  129. package/dist/runtime/tasks/boot.d.ts +20 -0
  130. package/dist/runtime/tasks/boot.js +32 -0
  131. package/dist/runtime/tasks/contracts.d.ts +70 -0
  132. package/dist/runtime/tasks/contracts.js +1 -0
  133. package/dist/runtime/tasks/db-store.d.ts +18 -0
  134. package/dist/runtime/tasks/db-store.js +139 -0
  135. package/dist/runtime/tasks/row-mapping.d.ts +11 -0
  136. package/dist/runtime/tasks/row-mapping.js +69 -0
  137. package/dist/runtime/tasks/runtime.d.ts +7 -0
  138. package/dist/runtime/tasks/runtime.js +162 -0
  139. package/dist/runtime/tasks/tasks-test-harness.d.ts +16 -0
  140. package/dist/runtime/tasks/tasks-test-harness.js +70 -0
  141. package/dist/runtime/tenant.d.ts +10 -0
  142. package/dist/runtime/tenant.js +13 -0
  143. package/dist/runtime/workflows/boot.d.ts +25 -0
  144. package/dist/runtime/workflows/boot.js +75 -0
  145. package/dist/runtime/workflows/contracts.d.ts +96 -0
  146. package/dist/runtime/workflows/contracts.js +1 -0
  147. package/dist/runtime/workflows/db-store.d.ts +18 -0
  148. package/dist/runtime/workflows/db-store.js +128 -0
  149. package/dist/runtime/workflows/definitions.d.ts +14 -0
  150. package/dist/runtime/workflows/definitions.js +50 -0
  151. package/dist/runtime/workflows/dispatch.d.ts +4 -0
  152. package/dist/runtime/workflows/dispatch.js +119 -0
  153. package/dist/runtime/workflows/row-mapping.d.ts +5 -0
  154. package/dist/runtime/workflows/row-mapping.js +38 -0
  155. package/dist/runtime/workflows/runner.d.ts +15 -0
  156. package/dist/runtime/workflows/runner.js +89 -0
  157. package/dist/runtime/workflows/runtime.d.ts +14 -0
  158. package/dist/runtime/workflows/runtime.js +129 -0
  159. package/dist/runtime/workflows/steps.d.ts +14 -0
  160. package/dist/runtime/workflows/steps.js +49 -0
  161. package/dist/runtime/workflows/support.d.ts +20 -0
  162. package/dist/runtime/workflows/support.js +36 -0
  163. package/dist/runtime/workflows/transitions.d.ts +8 -0
  164. package/dist/runtime/workflows/transitions.js +184 -0
  165. package/dist/runtime/workflows/workflows-test-harness.d.ts +62 -0
  166. package/dist/runtime/workflows/workflows-test-harness.js +178 -0
  167. package/dist/session-cookie.d.ts +13 -0
  168. package/dist/session-cookie.js +48 -0
  169. package/dist/storage.d.ts +50 -0
  170. package/dist/storage.js +118 -0
  171. package/dist/types.d.ts +44 -0
  172. package/dist/types.js +1 -0
  173. package/dist/virtual-ids.d.ts +17 -0
  174. package/dist/virtual-ids.js +17 -0
  175. package/dist/vite.d.ts +22 -0
  176. package/dist/vite.js +135 -0
  177. package/package.json +61 -4
  178. package/src/config.ts +120 -0
  179. package/src/constants.ts +24 -0
  180. package/src/facade.ts +153 -0
  181. package/src/index.ts +44 -0
  182. package/src/middleware/context.ts +106 -0
  183. package/src/middleware/cors.ts +42 -0
  184. package/src/middleware/session.ts +23 -0
  185. package/src/module.ts +278 -0
  186. package/src/rolldown-parser.ts +79 -0
  187. package/src/route-metadata-test-harness.ts +62 -0
  188. package/src/route-metadata.ts +194 -0
  189. package/src/routes/dev-query.post.ts +53 -0
  190. package/src/routes/dev-schema.get.ts +43 -0
  191. package/src/routes/dev-view.post.ts +66 -0
  192. package/src/routes/health.get.ts +26 -0
  193. package/src/routes/manifest-revision.get.ts +38 -0
  194. package/src/routes/manifest.get.ts +111 -0
  195. package/src/routes/openapi.get.ts +34 -0
  196. package/src/routes/sso.ts +247 -0
  197. package/src/routes/token.post.ts +89 -0
  198. package/src/runtime/boot-runtimes.ts +69 -0
  199. package/src/runtime/bootstrap.ts +300 -0
  200. package/src/runtime/config.ts +60 -0
  201. package/src/runtime/cors-policy.ts +107 -0
  202. package/src/runtime/db-bootstrap.ts +99 -0
  203. package/src/runtime/db-target.ts +87 -0
  204. package/src/runtime/dev-db-persistence.ts +146 -0
  205. package/src/runtime/dev-query.ts +124 -0
  206. package/src/runtime/env.ts +18 -0
  207. package/src/runtime/http-guard.ts +50 -0
  208. package/src/runtime/http.ts +30 -0
  209. package/src/runtime/jobs/boot.ts +97 -0
  210. package/src/runtime/jobs/contracts.ts +165 -0
  211. package/src/runtime/jobs/db-store-test-harness.ts +98 -0
  212. package/src/runtime/jobs/db-store.ts +273 -0
  213. package/src/runtime/jobs/definitions.ts +42 -0
  214. package/src/runtime/jobs/engine-support.ts +44 -0
  215. package/src/runtime/jobs/engine.ts +296 -0
  216. package/src/runtime/jobs/executor.ts +37 -0
  217. package/src/runtime/jobs/memory-store.ts +222 -0
  218. package/src/runtime/jobs/row-mapping.ts +67 -0
  219. package/src/runtime/jobs/runtime.ts +110 -0
  220. package/src/runtime/logging/audit-chain.ts +135 -0
  221. package/src/runtime/logging/bootstrap-logging.ts +62 -0
  222. package/src/runtime/logging/entry.ts +99 -0
  223. package/src/runtime/logging/file-sink.ts +157 -0
  224. package/src/runtime/logging/log-settings.ts +166 -0
  225. package/src/runtime/logging/log-sink.ts +31 -0
  226. package/src/runtime/logging/redact.ts +108 -0
  227. package/src/runtime/logging/runtime.ts +163 -0
  228. package/src/runtime/logging/sudo-bridge.ts +41 -0
  229. package/src/runtime/manifest-data.ts +103 -0
  230. package/src/runtime/manifest-response.ts +95 -0
  231. package/src/runtime/manifest-sections.ts +79 -0
  232. package/src/runtime/manifest-service.ts +83 -0
  233. package/src/runtime/project-config.ts +25 -0
  234. package/src/runtime/project-files.ts +103 -0
  235. package/src/runtime/rate-limit.ts +12 -0
  236. package/src/runtime/revision-service.ts +38 -0
  237. package/src/runtime/sql.ts +24 -0
  238. package/src/runtime/sso.ts +153 -0
  239. package/src/runtime/state.ts +7 -0
  240. package/src/runtime/storage-keys.ts +95 -0
  241. package/src/runtime/storage-target.ts +238 -0
  242. package/src/runtime/system-role.ts +26 -0
  243. package/src/runtime/tasks/boot.ts +49 -0
  244. package/src/runtime/tasks/contracts.ts +77 -0
  245. package/src/runtime/tasks/db-store.ts +191 -0
  246. package/src/runtime/tasks/row-mapping.ts +75 -0
  247. package/src/runtime/tasks/runtime.ts +192 -0
  248. package/src/runtime/tasks/tasks-test-harness.ts +92 -0
  249. package/src/runtime/tenant.ts +15 -0
  250. package/src/runtime/workflows/boot.ts +97 -0
  251. package/src/runtime/workflows/contracts.ts +114 -0
  252. package/src/runtime/workflows/db-store.ts +156 -0
  253. package/src/runtime/workflows/definitions.ts +75 -0
  254. package/src/runtime/workflows/dispatch.ts +148 -0
  255. package/src/runtime/workflows/row-mapping.ts +54 -0
  256. package/src/runtime/workflows/runner.ts +105 -0
  257. package/src/runtime/workflows/runtime.ts +161 -0
  258. package/src/runtime/workflows/steps.ts +74 -0
  259. package/src/runtime/workflows/support.ts +60 -0
  260. package/src/runtime/workflows/transitions.ts +259 -0
  261. package/src/runtime/workflows/workflows-test-harness.ts +238 -0
  262. package/src/session-cookie.ts +69 -0
  263. package/src/storage.ts +173 -0
  264. package/src/types.ts +51 -0
  265. package/src/virtual-ids.ts +18 -0
  266. package/src/virtual-modules.d.ts +53 -0
  267. package/src/vite.ts +175 -0
package/dist/module.js ADDED
@@ -0,0 +1,234 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { createRequire } from "node:module";
3
+ import { join, relative, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { DEV_QUERY_ROUTE, DEV_SCHEMA_ROUTE, DEV_VIEW_ROUTE, HEALTH_ROUTE, MANIFEST_REVISION_ROUTE, MANIFEST_ROUTE, NATIVE_OPENAPI_ROUTE, OPENAPI_FACADE_ROUTE, SSO_ROUTE, TOKEN_ROUTE, } from "./constants.js";
6
+ import { VIRTUAL_CONFIG_ID, VIRTUAL_DB_SCHEMA_ID, VIRTUAL_DB_VIEWS_ID, VIRTUAL_JOBS_ID, VIRTUAL_WORKFLOWS_ID, } from "./virtual-ids.js";
7
+ const ROUTES_DIR = new URL("./routes/", import.meta.url);
8
+ const MIDDLEWARE_DIR = new URL("./middleware/", import.meta.url);
9
+ // The package ships twice: src/*.ts from the workspace (bundlers strip the types) and
10
+ // dist/*.js in a packed tarball, which a published or URL-installed project loads with a
11
+ // plain ESM loader. Nitro needs real file paths for its handlers, so derive the extension
12
+ // from THIS module rather than hardcoding ".ts" — otherwise a dist build registers handler
13
+ // files that do not exist (dist/routes/manifest.get.ts).
14
+ const RUNTIME_EXT = import.meta.url.endsWith(".ts") ? ".ts" : ".js";
15
+ const APPLICATION_ENTRY = "facilis.config.ts";
16
+ const DB_SCHEMA_ENTRY = join("db", "schema.ts");
17
+ const DEV_ENV = "dev";
18
+ /**
19
+ * Facilis Nitro module (SPEC §5.6; nitro v3 has no defineNitroModule/kit, so it is a
20
+ * plain object). Carried by the `nitro` key of the `facilis()` Vite plugin.
21
+ */
22
+ export function createFacilisNitroModule() {
23
+ return {
24
+ name: "facilis",
25
+ setup(nitro) {
26
+ const rootDir = nitro.options.rootDir;
27
+ registerProjectAlias(nitro, rootDir);
28
+ registerVirtualModules(nitro, rootDir);
29
+ relocateNativeOpenApi(nitro);
30
+ registerRuntimeHandlers(nitro);
31
+ },
32
+ };
33
+ }
34
+ export const facilisNitroModule = createFacilisNitroModule();
35
+ /**
36
+ * SPEC Appendix C uses the `~` alias for project imports in server routes; Nitro must
37
+ * resolve it too or route files would only work on the client.
38
+ */
39
+ function registerProjectAlias(nitro, rootDir) {
40
+ nitro.options.alias ??= {};
41
+ if (nitro.options.alias["~"] === undefined) {
42
+ nitro.options.alias["~"] = rootDir.replace(/[\\/]+$/, "");
43
+ }
44
+ }
45
+ function registerVirtualModules(nitro, rootDir) {
46
+ const versions = readFrameworkVersions();
47
+ nitro.options.virtual ??= {};
48
+ nitro.options.virtual[VIRTUAL_CONFIG_ID] = () => renderConfigModule(rootDir, versions);
49
+ nitro.options.virtual[VIRTUAL_DB_SCHEMA_ID] = () => renderDbSchemaModule(rootDir);
50
+ nitro.options.virtual[VIRTUAL_DB_VIEWS_ID] = () => renderDbViewsModule(rootDir);
51
+ nitro.options.virtual[VIRTUAL_JOBS_ID] = () => renderJobsModule(rootDir);
52
+ nitro.options.virtual[VIRTUAL_WORKFLOWS_ID] = () => renderWorkflowsModule(rootDir);
53
+ // `#facilis/openapi-meta` is deliberately NOT registered here: Nitro's virtual plugin
54
+ // runs before user Vite plugins inside the nitro environment, so a Nitro virtual would
55
+ // shadow the `facilis()` plugin's module and route-file edits would never invalidate it
56
+ // (verified: HMR served stale metadata). The Vite plugin owns that module.
57
+ }
58
+ function renderConfigModule(rootDir, versions) {
59
+ const configPath = join(rootDir, APPLICATION_ENTRY);
60
+ const source = readTextFile(configPath);
61
+ const metadata = [
62
+ `export const projectRoot = ${JSON.stringify(rootDir)};`,
63
+ `export const configPath = ${JSON.stringify(configPath)};`,
64
+ `export const configSource = ${JSON.stringify(source ?? "")};`,
65
+ `export const configError = ${source === null ? JSON.stringify(`facilis.config.ts not found at ${configPath}`) : "undefined"};`,
66
+ `export const coreVersion = ${JSON.stringify(versions.coreVersion)};`,
67
+ `export const nitroVersion = ${JSON.stringify(versions.nitroVersion)};`,
68
+ ];
69
+ const body = source === null
70
+ ? ["export default {};"]
71
+ : [`import config from ${JSON.stringify(configPath)};`, "export default config;"];
72
+ return [...body, ...metadata].join("\n");
73
+ }
74
+ function renderDbSchemaModule(rootDir) {
75
+ const schemaPath = join(rootDir, DB_SCHEMA_ENTRY);
76
+ if (!existsSync(schemaPath))
77
+ return "export default {};";
78
+ return `import * as schema from ${JSON.stringify(schemaPath)};\nexport default schema;`;
79
+ }
80
+ const DB_VIEWS_ENTRY = join("db", "views.ts");
81
+ const DB_VIEWS_DIR = join("db", "views");
82
+ /**
83
+ * db/views/*.ts (and the single-file db/views.ts form) as one array of namespaces, so the
84
+ * runtime can create every declared view without importing the project's module graph.
85
+ * A missing directory renders as an empty array: a project without views is valid.
86
+ */
87
+ function renderDbViewsModule(rootDir) {
88
+ const files = [];
89
+ const single = join(rootDir, DB_VIEWS_ENTRY);
90
+ if (existsSync(single))
91
+ files.push(single);
92
+ const directory = join(rootDir, DB_VIEWS_DIR);
93
+ if (existsSync(directory)) {
94
+ for (const name of readdirSync(directory).toSorted()) {
95
+ if (name.endsWith(".ts") && !name.endsWith(".test.ts"))
96
+ files.push(join(directory, name));
97
+ }
98
+ }
99
+ if (files.length === 0)
100
+ return "export default [];";
101
+ const imports = files.map((file, index) => `import * as v${index} from ${JSON.stringify(file)};`);
102
+ const list = files.map((_file, index) => `v${index}`).join(", ");
103
+ return [...imports, `export default [${list}];`].join("\n");
104
+ }
105
+ const JOBS_ENTRY = join("server", "jobs");
106
+ const WORKFLOWS_ENTRY = join("server", "workflows");
107
+ /**
108
+ * server/jobs/**\/*.ts as `JobModule` entries (D-107, docs/JOBS.md §5): one default export
109
+ * per file, nested directories allowed, colocated `*.test.ts` ignored. A project without
110
+ * jobs is valid, so a missing directory renders as an empty array.
111
+ */
112
+ function renderJobsModule(rootDir) {
113
+ return renderDefinitionModule(rootDir, JOBS_ENTRY, "job");
114
+ }
115
+ /**
116
+ * server/workflows/**\/*.ts as `WorkflowModule` entries (D-135): same shape as jobs, one
117
+ * default export per file; a project without workflows renders an empty array.
118
+ */
119
+ function renderWorkflowsModule(rootDir) {
120
+ return renderDefinitionModule(rootDir, WORKFLOWS_ENTRY, "workflow");
121
+ }
122
+ /** Shared renderer for a definition directory; `prefix` names the generated bindings. */
123
+ function renderDefinitionModule(rootDir, entry, prefix) {
124
+ const files = collectDefinitionFiles(join(rootDir, entry));
125
+ if (files.length === 0)
126
+ return "export default [];";
127
+ const imports = files.map((file, index) => `import ${prefix}${index} from ${JSON.stringify(file)};`);
128
+ const entries = files.map((file, index) => {
129
+ const projectPath = relative(rootDir, file).split(sep).join("/");
130
+ return `{ file: ${JSON.stringify(projectPath)}, definition: ${prefix}${index} }`;
131
+ });
132
+ return [...imports, `export default [${entries.join(", ")}];`].join("\n");
133
+ }
134
+ /** Depth-first, explicitly sorted so the registry (and its warnings) is deterministic. */
135
+ function collectDefinitionFiles(directory) {
136
+ let entries;
137
+ try {
138
+ entries = readdirSync(directory, { withFileTypes: true });
139
+ }
140
+ catch {
141
+ return [];
142
+ }
143
+ const files = [];
144
+ for (const entry of entries.toSorted((a, b) => a.name.localeCompare(b.name))) {
145
+ const filePath = join(directory, entry.name);
146
+ if (entry.isDirectory()) {
147
+ files.push(...collectDefinitionFiles(filePath));
148
+ }
149
+ else if (entry.isFile() && entry.name.endsWith(".ts") && !entry.name.endsWith(".test.ts")) {
150
+ files.push(filePath);
151
+ }
152
+ }
153
+ return files;
154
+ }
155
+ function readTextFile(filePath) {
156
+ try {
157
+ return readFileSync(filePath, "utf8");
158
+ }
159
+ catch {
160
+ return null;
161
+ }
162
+ }
163
+ function readFrameworkVersions() {
164
+ const require = createRequire(import.meta.url);
165
+ return {
166
+ coreVersion: readPackageVersion(require, "@facilis.dev/core/package.json"),
167
+ nitroVersion: readPackageVersion(require, "nitro/package.json"),
168
+ };
169
+ }
170
+ function readPackageVersion(require, request) {
171
+ try {
172
+ const packageJson = require(request);
173
+ return typeof packageJson.version === "string" ? packageJson.version : "0.0.0";
174
+ }
175
+ catch {
176
+ return "0.0.0";
177
+ }
178
+ }
179
+ /**
180
+ * Keep Nitro's own OpenAPI generator intact but move its route off the public path
181
+ * (SPEC §6.9): `/_openapi.json` becomes the AST-augmented facade, the native document
182
+ * stays available on `/_facilis/openapi.json` and is what the facade reads.
183
+ */
184
+ function relocateNativeOpenApi(nitro) {
185
+ for (const handler of nitro.options.handlers) {
186
+ if (/internal[\\/]routes[\\/]openapi/.test(handler.handler)) {
187
+ handler.route = NATIVE_OPENAPI_ROUTE;
188
+ }
189
+ }
190
+ if (nitro.options.openAPI !== undefined) {
191
+ nitro.options.openAPI.route = NATIVE_OPENAPI_ROUTE;
192
+ }
193
+ }
194
+ function registerRuntimeHandlers(nitro) {
195
+ const dev = nitro.options.dev === true;
196
+ const handlers = nitro.options.handlers;
197
+ const add = (route, handler, env) => {
198
+ handlers.push(env === undefined ? { route, handler } : { route, handler, env });
199
+ };
200
+ if (dev) {
201
+ add(MANIFEST_ROUTE, routeFile("manifest.get.ts"), DEV_ENV);
202
+ add(MANIFEST_REVISION_ROUTE, routeFile("manifest-revision.get.ts"), DEV_ENV);
203
+ add(HEALTH_ROUTE, routeFile("health.get.ts"), DEV_ENV);
204
+ add(DEV_SCHEMA_ROUTE, routeFile("dev-schema.get.ts"), DEV_ENV);
205
+ add(DEV_QUERY_ROUTE, routeFile("dev-query.post.ts"), DEV_ENV);
206
+ add(DEV_VIEW_ROUTE, routeFile("dev-view.post.ts"), DEV_ENV);
207
+ }
208
+ // The facade is dev-only unless the project explicitly enables OpenAPI in production.
209
+ if (dev)
210
+ add(OPENAPI_FACADE_ROUTE, routeFile("openapi.get.ts"), DEV_ENV);
211
+ else if (nitro.options.openAPI?.production)
212
+ add(OPENAPI_FACADE_ROUTE, routeFile("openapi.get.ts"));
213
+ // The SSO namespace is framework auth in every environment (D-120): with no providers
214
+ // configured every path answers not_found, so the handler exists unconditionally and the
215
+ // app never ships its own copy. It is reserved to the framework (SPEC §5.3).
216
+ add(SSO_ROUTE, routeFile("sso.ts"));
217
+ // The token endpoint is framework auth in every environment (v3a): with apiClients disabled
218
+ // it answers not_found, so the app never ships its own copy (reserved to the framework).
219
+ add(TOKEN_ROUTE, routeFile("token.post.ts"));
220
+ // Middleware order is significant: cors answers preflight before anything boots, then
221
+ // context (db) before session (auth) (contracts §4.1).
222
+ handlers.push({ route: "/**", middleware: true, handler: middlewareFile("cors.ts") });
223
+ handlers.push({ route: "/**", middleware: true, handler: middlewareFile("context.ts") });
224
+ handlers.push({ route: "/**", middleware: true, handler: middlewareFile("session.ts") });
225
+ }
226
+ function routeFile(name) {
227
+ return fileURLToPath(new URL(withRuntimeExt(name), ROUTES_DIR));
228
+ }
229
+ function middlewareFile(name) {
230
+ return fileURLToPath(new URL(withRuntimeExt(name), MIDDLEWARE_DIR));
231
+ }
232
+ function withRuntimeExt(name) {
233
+ return name.replace(/\.ts$/, RUNTIME_EXT);
234
+ }
@@ -0,0 +1,3 @@
1
+ import type { Parser } from "@facilis.dev/analyze";
2
+ /** The analyzer's injected parser: rolldown's oxc build, the parser proven in the VM. */
3
+ export declare function createRolldownParser(): Parser;
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Analyzer parser adapter over rolldown's oxc parser (`rolldown/utils`).
3
+ *
4
+ * The Nitro Vite plugin also runs inside the Studio's WebContainer, where the analyzer's
5
+ * Node subpath (its native oxc-parser adapter) is not proven (D-092). rolldown/utils is the
6
+ * parser the previous AST pass used in that VM, so the analyzer's main entry gets it injected
7
+ * here instead of importing a parser package itself.
8
+ */
9
+ import { parseSync } from "rolldown/utils";
10
+ function languageOf(filename) {
11
+ if (filename.endsWith(".tsx"))
12
+ return "tsx";
13
+ if (filename.endsWith(".jsx"))
14
+ return "jsx";
15
+ if (filename.endsWith(".js") || filename.endsWith(".mjs") || filename.endsWith(".cjs"))
16
+ return "js";
17
+ return "ts";
18
+ }
19
+ /** 1-based line of an offset; `@facilis.dev/analyze` keeps its own helper internal. */
20
+ function lineOf(source, offset) {
21
+ let line = 1;
22
+ const end = Math.min(Math.max(offset, 0), source.length);
23
+ for (let index = 0; index < end; index += 1) {
24
+ if (source.charCodeAt(index) === 10)
25
+ line += 1;
26
+ }
27
+ return line;
28
+ }
29
+ function toParseError(filename, source, error) {
30
+ const label = error.labels?.[0];
31
+ const start = label?.start ?? null;
32
+ return {
33
+ message: error.message,
34
+ start,
35
+ end: label?.end ?? null,
36
+ source: { file: filename, line: start === null ? 1 : lineOf(source, start) },
37
+ };
38
+ }
39
+ /** The analyzer's injected parser: rolldown's oxc build, the parser proven in the VM. */
40
+ export function createRolldownParser() {
41
+ return {
42
+ parse(filename, source) {
43
+ // Parse TypeScript directly (no transform step): rolldown returns TS-ESTree, so
44
+ // `as const` / type annotations survive for the analyzer's structural readers.
45
+ const result = parseSync(filename, source, {
46
+ lang: languageOf(filename),
47
+ sourceType: "module",
48
+ preserveParens: true,
49
+ });
50
+ return {
51
+ program: toProgram(result.program),
52
+ errors: result.errors.map((error) => toParseError(filename, source, error)),
53
+ };
54
+ },
55
+ };
56
+ }
57
+ function toProgram(value) {
58
+ if (typeof value !== "object" || value === null) {
59
+ throw new Error("rolldown's oxc parser returned no program");
60
+ }
61
+ const type = value.type;
62
+ if (typeof type !== "string") {
63
+ throw new Error("rolldown's oxc parser returned an invalid program");
64
+ }
65
+ return value;
66
+ }
@@ -0,0 +1,22 @@
1
+ import type { Analysis } from "@facilis.dev/analyze";
2
+ import type { ManifestWarning } from "@facilis.dev/core";
3
+ import type { RouteMetadataMap, ScanOptions } from "./types.js";
4
+ /**
5
+ * Analyze the project once. Undefined when the root does not exist: there is nothing to
6
+ * read, and the fs loader would throw on the missing directory.
7
+ *
8
+ * The analyzer's main entry is parser-injected: this adapter supplies rolldown's oxc parser so
9
+ * the Vite plugin never loads the analyzer's native-node parser in the Studio's WebContainer
10
+ * (D-092). The file walker is the parser-free `@facilis.dev/analyze/fs` subpath.
11
+ */
12
+ export declare function analyzeProjectRoutes(rootDir: string): Analysis | undefined;
13
+ /** Run the analyzer over `options.rootDir` and map its route facts to the metadata contract. */
14
+ export declare function scanRouteMetadata(options: ScanOptions): RouteMetadataMap;
15
+ /**
16
+ * Map an analysis onto the manifest/OpenAPI contract.
17
+ *
18
+ * Facts the analyzer could not determine are null; they become `unresolved` entries (so the
19
+ * facade omits the field) while the map's arrays keep their historical `[]` fallback. A
20
+ * null field is never turned into a guessed value: "unknown" must not look "public".
21
+ */
22
+ export declare function routeMetadataFromAnalysis(analysis: Analysis, onWarning?: (warning: ManifestWarning) => void): RouteMetadataMap;
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Route facts -> manifest/OpenAPI metadata adapter (D-092).
3
+ *
4
+ * @facilis.dev/analyze owns the route DSL: it parses the project with oxc and reports one
5
+ * RouteFact per route file, including files that do not use the wrapper. This module is the
6
+ * only place @facilis.dev/nitro touches the analyzer; it maps that fact model onto the
7
+ * RouteMetadataMap contract the facade and manifest still consume.
8
+ */
9
+ import { existsSync } from "node:fs";
10
+ import { analyzeProject } from "@facilis.dev/analyze";
11
+ import { loadProjectFiles } from "@facilis.dev/analyze/fs";
12
+ import { createRolldownParser } from "./rolldown-parser.js";
13
+ /** The directories the analyzer treats as the route table (its DSL layout). */
14
+ const ROUTE_DIRS = ["server/routes/", "server/api/"];
15
+ /**
16
+ * Core's RouteMeta.HttpMethod is the manifest contract. The analyzer also knows
17
+ * HEAD/OPTIONS/TRACE/CONNECT/ALL; widening a cross-package contract is a separate change, so
18
+ * those routes are omitted here (with a warning) instead of entering the map under a method
19
+ * the manifest cannot type.
20
+ */
21
+ const MANIFEST_METHODS = new Set([
22
+ "GET",
23
+ "POST",
24
+ "PUT",
25
+ "PATCH",
26
+ "DELETE",
27
+ ]);
28
+ /** Framework sources are shipped code: their diagnostics are not the project's. */
29
+ const FRAMEWORK_PREFIX = "node_modules/";
30
+ /** Diagnostics outside the route pass that the plugin reports at startup/build. */
31
+ function isProjectLevelDiagnostic(code) {
32
+ return code === "parse-error" || code.startsWith("config-");
33
+ }
34
+ function isManifestMethod(method) {
35
+ return MANIFEST_METHODS.has(method);
36
+ }
37
+ /** Narrow a route fact to the five methods the manifest contract models. */
38
+ function isManifestRoute(fact) {
39
+ return isManifestMethod(fact.method);
40
+ }
41
+ function isFrameworkFile(file) {
42
+ return file.startsWith(FRAMEWORK_PREFIX);
43
+ }
44
+ function isRouteFile(file) {
45
+ return ROUTE_DIRS.some((directory) => file.startsWith(directory));
46
+ }
47
+ /**
48
+ * Analyze the project once. Undefined when the root does not exist: there is nothing to
49
+ * read, and the fs loader would throw on the missing directory.
50
+ *
51
+ * The analyzer's main entry is parser-injected: this adapter supplies rolldown's oxc parser so
52
+ * the Vite plugin never loads the analyzer's native-node parser in the Studio's WebContainer
53
+ * (D-092). The file walker is the parser-free `@facilis.dev/analyze/fs` subpath.
54
+ */
55
+ export function analyzeProjectRoutes(rootDir) {
56
+ if (!existsSync(rootDir))
57
+ return undefined;
58
+ return analyzeProject({ files: loadProjectFiles(rootDir), parser: createRolldownParser() });
59
+ }
60
+ /** Run the analyzer over `options.rootDir` and map its route facts to the metadata contract. */
61
+ export function scanRouteMetadata(options) {
62
+ const analysis = analyzeProjectRoutes(options.rootDir);
63
+ if (analysis === undefined)
64
+ return {};
65
+ return routeMetadataFromAnalysis(analysis, options.onWarning);
66
+ }
67
+ /**
68
+ * Map an analysis onto the manifest/OpenAPI contract.
69
+ *
70
+ * Facts the analyzer could not determine are null; they become `unresolved` entries (so the
71
+ * facade omits the field) while the map's arrays keep their historical `[]` fallback. A
72
+ * null field is never turned into a guessed value: "unknown" must not look "public".
73
+ */
74
+ export function routeMetadataFromAnalysis(analysis, onWarning) {
75
+ const routesByFile = new Map();
76
+ const routeFiles = new Set(analysis.routes.map((fact) => fact.sourceFile));
77
+ const supportedFacts = analysis.routes.filter(isManifestRoute);
78
+ for (const fact of analysis.routes) {
79
+ if (isManifestMethod(fact.method))
80
+ continue;
81
+ // Route facts only ever come from project route files, but the guard keeps the
82
+ // "framework sources are never reported" rule explicit.
83
+ if (!isFrameworkFile(fact.sourceFile)) {
84
+ report(onWarning, {
85
+ code: "route-method-unsupported",
86
+ message: `Route ${fact.sourceFile} declares ${fact.method}, outside the manifest's ` +
87
+ `HttpMethod contract; it is omitted from the route metadata.`,
88
+ section: "routes",
89
+ sourceFile: fact.sourceFile,
90
+ });
91
+ }
92
+ }
93
+ const mappedFiles = new Set(supportedFacts.map((fact) => fact.sourceFile));
94
+ for (const diagnostic of analysis.diagnostics) {
95
+ const file = diagnostic.source?.file;
96
+ if (file !== undefined && isFrameworkFile(file))
97
+ continue;
98
+ const belongsToRouteFile = file !== undefined && (routeFiles.has(file) || isRouteFile(file));
99
+ if (belongsToRouteFile) {
100
+ const warning = toWarning(diagnostic, file);
101
+ const mapped = mappedFiles.has(file);
102
+ if (!mapped) {
103
+ // No RouteMetadata to attach to (e.g. the method is not in the manifest contract),
104
+ // so the warning is reported at file level instead of being dropped.
105
+ report(onWarning, warning);
106
+ continue;
107
+ }
108
+ const warnings = routesByFile.get(file) ?? [];
109
+ warnings.push(warning);
110
+ routesByFile.set(file, warnings);
111
+ continue;
112
+ }
113
+ if (isProjectLevelDiagnostic(diagnostic.code)) {
114
+ report(onWarning, toWarning(diagnostic, file));
115
+ }
116
+ }
117
+ const map = {};
118
+ for (const fact of supportedFacts) {
119
+ const operations = (map[fact.path] ??= {});
120
+ operations[fact.method.toLowerCase()] = toRouteMetadata(fact, routesByFile.get(fact.sourceFile) ?? []);
121
+ }
122
+ return map;
123
+ }
124
+ function toRouteMetadata(fact, warnings) {
125
+ const unresolved = [];
126
+ if (fact.permission === null)
127
+ unresolved.push("permission");
128
+ if (fact.dbTables === null)
129
+ unresolved.push("dbTables");
130
+ if (fact.dbColumns === null)
131
+ unresolved.push("dbColumns");
132
+ if (fact.crossSite === null)
133
+ unresolved.push("crossSite");
134
+ if (fact.rawSql === null)
135
+ unresolved.push("rawSql");
136
+ return {
137
+ method: fact.method,
138
+ path: fact.path,
139
+ ...(fact.permission === null ? {} : { permission: fact.permission }),
140
+ ...(fact.crossSite === true ? { crossSite: true } : {}),
141
+ // A null rawSql is "unreadable" (unresolved), never "false": the facade then omits it.
142
+ rawSql: fact.rawSql ?? false,
143
+ dbTables: fact.dbTables ?? [],
144
+ dbColumns: fact.dbColumns ?? [],
145
+ ...(fact.description === null ? {} : { description: fact.description }),
146
+ unresolved,
147
+ sourceFile: fact.sourceFile,
148
+ warnings,
149
+ };
150
+ }
151
+ function toWarning(diagnostic, sourceFile) {
152
+ return {
153
+ code: diagnostic.code,
154
+ message: diagnostic.message,
155
+ section: "routes",
156
+ ...(sourceFile === undefined ? {} : { sourceFile }),
157
+ };
158
+ }
159
+ function report(onWarning, warning) {
160
+ onWarning?.(warning);
161
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * POST /__facilis/dev/query — the Data Explorer's read-only SQL console (SPEC §11.2, D-097).
3
+ *
4
+ * 200 `{ columns, rows, rowCount, elapsedMs, truncated }`, 400 for a bad body / statement /
5
+ * failed query, 403 on an origin mismatch, 404 in production, 503 when the runtime has no
6
+ * database. A console query runs as the connecting superuser: the response is a developer
7
+ * preview, not a permissions view (created views are security_invoker).
8
+ */
9
+ declare const _default: import("nitro").EventHandlerWithFetch<import("nitro").EventHandlerRequest, Promise<Response>>;
10
+ export default _default;
@@ -0,0 +1,49 @@
1
+ import { defineHandler } from "nitro";
2
+ import { getBootstrap } from "../runtime/bootstrap.js";
3
+ import { DevQueryError, parseQueryBody, runQuery } from "../runtime/dev-query.js";
4
+ import { guardDevRequest } from "../runtime/http-guard.js";
5
+ import { jsonResult, toResponse } from "../runtime/http.js";
6
+ const NO_CACHE = { "cache-control": "no-cache" };
7
+ /**
8
+ * POST /__facilis/dev/query — the Data Explorer's read-only SQL console (SPEC §11.2, D-097).
9
+ *
10
+ * 200 `{ columns, rows, rowCount, elapsedMs, truncated }`, 400 for a bad body / statement /
11
+ * failed query, 403 on an origin mismatch, 404 in production, 503 when the runtime has no
12
+ * database. A console query runs as the connecting superuser: the response is a developer
13
+ * preview, not a permissions view (created views are security_invoker).
14
+ */
15
+ export default defineHandler(async (event) => {
16
+ const guard = guardDevRequest(event.req.headers);
17
+ if (guard)
18
+ return toResponse(guard);
19
+ const state = await getBootstrap();
20
+ if (state.db === null)
21
+ return response(503, { code: "db_unavailable" });
22
+ const body = await readJsonBody(event);
23
+ if (!body.ok)
24
+ return response(400, { code: "invalid_body" });
25
+ const parsed = parseQueryBody(body.value);
26
+ if (!parsed.ok)
27
+ return response(400, { code: parsed.error.code, message: parsed.error.message });
28
+ try {
29
+ return response(200, await runQuery(state.db, parsed.request));
30
+ }
31
+ catch (error) {
32
+ if (error instanceof DevQueryError) {
33
+ return response(400, { code: error.code, message: error.message });
34
+ }
35
+ console.error("facilis: dev query failed", error);
36
+ return response(400, { code: "query_failed" });
37
+ }
38
+ });
39
+ async function readJsonBody(event) {
40
+ try {
41
+ return { ok: true, value: await event.req.json() };
42
+ }
43
+ catch {
44
+ return { ok: false };
45
+ }
46
+ }
47
+ function response(status, body) {
48
+ return toResponse(jsonResult(status, body, { ...NO_CACHE }));
49
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * GET /__facilis/dev/schema — code↔live schema introspection (SPEC §6.3/§11.1/§11.4).
3
+ *
4
+ * 200 `{ code, live, drift, warnings }`, 403 on an origin mismatch, 404 in production,
5
+ * 503 `{ code: "db_unavailable" }` when the runtime has no usable database (still booting,
6
+ * a failed migration, or a catalog query that cannot answer).
7
+ */
8
+ declare const _default: import("nitro").EventHandlerWithFetch<import("nitro").EventHandlerRequest, Promise<Response>>;
9
+ export default _default;
@@ -0,0 +1,34 @@
1
+ import { defineHandler } from "nitro";
2
+ import { diffSchemaSnapshots, liveSchemaSnapshot, schemaSnapshot } from "@facilis.dev/db";
3
+ import { getBootstrap } from "../runtime/bootstrap.js";
4
+ import { guardDevRequest } from "../runtime/http-guard.js";
5
+ import { jsonResult, toResponse } from "../runtime/http.js";
6
+ const NO_CACHE = { "cache-control": "no-cache" };
7
+ /**
8
+ * GET /__facilis/dev/schema — code↔live schema introspection (SPEC §6.3/§11.1/§11.4).
9
+ *
10
+ * 200 `{ code, live, drift, warnings }`, 403 on an origin mismatch, 404 in production,
11
+ * 503 `{ code: "db_unavailable" }` when the runtime has no usable database (still booting,
12
+ * a failed migration, or a catalog query that cannot answer).
13
+ */
14
+ export default defineHandler(async (event) => {
15
+ const guard = guardDevRequest(event.req.headers);
16
+ if (guard)
17
+ return toResponse(guard);
18
+ const state = await getBootstrap();
19
+ if (state.db === null)
20
+ return unavailable();
21
+ try {
22
+ const code = await schemaSnapshot(state.db);
23
+ const live = await liveSchemaSnapshot(state.db);
24
+ return toResponse(jsonResult(200, { code, live, drift: diffSchemaSnapshots(code, live), warnings: state.warnings }, { ...NO_CACHE }));
25
+ }
26
+ catch {
27
+ // Boot can succeed while a catalog query fails (a closed or broken cluster): answer
28
+ // "no database" instead of leaking the driver error as an opaque 500.
29
+ return unavailable();
30
+ }
31
+ });
32
+ function unavailable() {
33
+ return toResponse(jsonResult(503, { code: "db_unavailable" }, { ...NO_CACHE }));
34
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * POST /__facilis/dev/view — create (or replace) a view from the query console (D-097/D-098).
3
+ *
4
+ * The Studio writes db/views/<name>.ts afterwards; this endpoint makes the view usable
5
+ * immediately. Without a permission the view is `security_invoker = true` (base tables' RLS);
6
+ * with one it is a definer view gated by that permission, which must already be declared in
7
+ * facilis.config.ts — the console cannot invent a new permission. Dev-only,
8
+ * origin-allowlisted, 404 in production.
9
+ */
10
+ declare const _default: import("nitro").EventHandlerWithFetch<import("nitro").EventHandlerRequest, Promise<Response>>;
11
+ export default _default;
@@ -0,0 +1,61 @@
1
+ import { defineHandler } from "nitro";
2
+ import { getBootstrap } from "../runtime/bootstrap.js";
3
+ import { createView, DevQueryError, parseViewBody } from "../runtime/dev-query.js";
4
+ import { guardDevRequest } from "../runtime/http-guard.js";
5
+ import { jsonResult, toResponse } from "../runtime/http.js";
6
+ const NO_CACHE = { "cache-control": "no-cache" };
7
+ /**
8
+ * POST /__facilis/dev/view — create (or replace) a view from the query console (D-097/D-098).
9
+ *
10
+ * The Studio writes db/views/<name>.ts afterwards; this endpoint makes the view usable
11
+ * immediately. Without a permission the view is `security_invoker = true` (base tables' RLS);
12
+ * with one it is a definer view gated by that permission, which must already be declared in
13
+ * facilis.config.ts — the console cannot invent a new permission. Dev-only,
14
+ * origin-allowlisted, 404 in production.
15
+ */
16
+ export default defineHandler(async (event) => {
17
+ const guard = guardDevRequest(event.req.headers);
18
+ if (guard)
19
+ return toResponse(guard);
20
+ const state = await getBootstrap();
21
+ if (state.db === null)
22
+ return response(503, { code: "db_unavailable" });
23
+ const body = await readJsonBody(event);
24
+ if (!body.ok)
25
+ return response(400, { code: "invalid_body" });
26
+ const parsed = parseViewBody(body.value);
27
+ if (!parsed.ok)
28
+ return response(400, { code: parsed.error.code, message: parsed.error.message });
29
+ const permission = parsed.request.permission;
30
+ if (permission !== null) {
31
+ const declared = state.config?.auth.permissions ?? [];
32
+ if (!declared.includes(permission)) {
33
+ return response(400, {
34
+ code: "invalid_permission",
35
+ message: `Permission "${permission}" is not declared in facilis.config.ts.`,
36
+ });
37
+ }
38
+ }
39
+ try {
40
+ await createView(state.db, parsed.request);
41
+ return response(200, { name: parsed.request.name });
42
+ }
43
+ catch (error) {
44
+ if (error instanceof DevQueryError) {
45
+ return response(400, { code: error.code, message: error.message });
46
+ }
47
+ console.error("facilis: dev view creation failed", error);
48
+ return response(400, { code: "create_failed" });
49
+ }
50
+ });
51
+ async function readJsonBody(event) {
52
+ try {
53
+ return { ok: true, value: await event.req.json() };
54
+ }
55
+ catch {
56
+ return { ok: false };
57
+ }
58
+ }
59
+ function response(status, body) {
60
+ return toResponse(jsonResult(status, body, { ...NO_CACHE }));
61
+ }