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