@facilis.dev/nitro 0.0.0-stage → 0.1.2

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
@@ -0,0 +1,87 @@
1
+ import type { FacilisConfig, ManifestWarning } from "@facilis.dev/core";
2
+
3
+ import { isProductionEnvironment } from "./env.ts";
4
+
5
+ /** Driver a booting project can open; mirrors @facilis.dev/db's `DbDriver`. */
6
+ export type DbTargetDriver = "pglite" | "postgres";
7
+
8
+ /** The database the runtime must open. `url` is set for a postgres target only. */
9
+ export interface DbTarget {
10
+ readonly driver: DbTargetDriver;
11
+ readonly url?: string;
12
+ }
13
+
14
+ export interface ResolvedDbTarget {
15
+ readonly target: DbTarget | null;
16
+ readonly warnings: readonly ManifestWarning[];
17
+ }
18
+
19
+ /**
20
+ * Decide which database the runtime opens (SPEC §5.2/§7.1, D-068).
21
+ *
22
+ * A connection string wins over the project config so a deployment can point any project at
23
+ * its Postgres without editing source. Every refusal returns a null target plus a warning:
24
+ * the boot then degrades to "no database" (manifest warning, no session) instead of crashing
25
+ * or, worse, silently writing a production app to the in-memory PGlite cluster.
26
+ */
27
+ export function resolveDbTarget(
28
+ config: FacilisConfig | null,
29
+ env: NodeJS.ProcessEnv,
30
+ ): ResolvedDbTarget {
31
+ // A hosting panel that defines the variable but leaves it blank is "not configured": an
32
+ // empty URL would otherwise reach the driver and surface as a confusing connection error.
33
+ const url = readUrl(env["FACILIS_DATABASE_URL"]) ?? readUrl(env["DATABASE_URL"]);
34
+ if (url !== undefined) {
35
+ return { target: { driver: "postgres", url }, warnings: [] };
36
+ }
37
+
38
+ const mode = config?.db.mode ?? "pglite";
39
+
40
+ if (mode === "pglite") {
41
+ if (isProductionEnvironment(env)) {
42
+ return {
43
+ target: null,
44
+ warnings: [
45
+ warning(
46
+ "db_pglite_in_production",
47
+ "Production refuses the in-memory PGlite driver: set FACILIS_DATABASE_URL (or DATABASE_URL) to a Postgres connection string.",
48
+ ),
49
+ ],
50
+ };
51
+ }
52
+ return { target: { driver: "pglite" }, warnings: [] };
53
+ }
54
+
55
+ if (mode === "postgres") {
56
+ return {
57
+ target: null,
58
+ warnings: [
59
+ warning(
60
+ "db_url_missing",
61
+ 'db.mode is "postgres" but neither FACILIS_DATABASE_URL nor DATABASE_URL is set.',
62
+ ),
63
+ ],
64
+ };
65
+ }
66
+
67
+ // "json" is a declared config mode (SPEC §7.1) with no runtime driver yet.
68
+ return {
69
+ target: null,
70
+ warnings: [
71
+ warning(
72
+ "db_mode_unsupported",
73
+ `db.mode "${mode}" has no runtime driver; use "pglite" or "postgres".`,
74
+ ),
75
+ ],
76
+ };
77
+ }
78
+
79
+ /** Trimmed connection string, or undefined when unset or blank. */
80
+ function readUrl(value: string | undefined): string | undefined {
81
+ const trimmed = value?.trim();
82
+ return trimmed === undefined || trimmed.length === 0 ? undefined : trimmed;
83
+ }
84
+
85
+ function warning(code: string, message: string): ManifestWarning {
86
+ return { code, message };
87
+ }
@@ -0,0 +1,146 @@
1
+ // Dev database persistence (D-052).
2
+ //
3
+ // PGlite runs in memory for speed, but a memory-only dev database is wiped every time
4
+ // the Nitro worker restarts — which happens on every edit to a server route. That made
5
+ // "register a user, change a handler, log in again" the normal loop. This module keeps a
6
+ // single snapshot archive in the project's `.facilis/db` directory:
7
+ //
8
+ // boot: read `.facilis/db/snapshot.tar.gz` -> `createDb({ loadSnapshot })`
9
+ // run: every tick, if the cluster changed, `dumpDataDir('gzip')` -> write atomically
10
+ // stop: flush()
11
+ //
12
+ // One file, ~5 MB for a small app, so it crosses the VFS/OPFS mirror cheaply and the
13
+ // project's scoped restore (D-036) replays exactly one path. The directory is per-project
14
+ // state, never source: `.facilis/.gitignore` ignores the whole tree for git, and the IDE
15
+ // hides it from the Explorer/index/export.
16
+ import { access, mkdir, readFile, rename, writeFile } from "node:fs/promises";
17
+ import { dirname, join } from "node:path";
18
+ import type { FacilisDb } from "@facilis.dev/db";
19
+
20
+ /** Per-project, non-source state directory (dev database, binary blobs). */
21
+ export const FACILIS_STATE_DIR = ".facilis";
22
+ /** The dev database snapshot, relative to the project root. */
23
+ export const DEV_DB_SNAPSHOT_FILE = join(FACILIS_STATE_DIR, "db", "snapshot.tar.gz");
24
+ const SNAPSHOT_INTERVAL_MS = 1_000;
25
+
26
+ /** What the snapshotter needs from the database handle. */
27
+ export type SnapshotSource = Pick<FacilisDb, "activity" | "snapshot">;
28
+
29
+ export interface DevDbSnapshotter {
30
+ /** Write a snapshot now if the cluster changed since the last one. */
31
+ flush(): Promise<void>;
32
+ stop(): void;
33
+ /** Epoch ms of the last successful snapshot, or null before the first one. */
34
+ lastSnapshotAt(): number | null;
35
+ }
36
+
37
+ export function devDbSnapshotPath(projectRoot: string): string {
38
+ return join(projectRoot, DEV_DB_SNAPSHOT_FILE);
39
+ }
40
+
41
+ /**
42
+ * Create `.facilis` and its self-ignoring `.gitignore`.
43
+ *
44
+ * The folder must persist in the VFS (that is how it survives a reload), but it is not
45
+ * source: a `.gitignore` containing `*` ignores the whole tree even when the project's
46
+ * own .gitignore was written before this directory existed. Written idempotently, and
47
+ * never overwriting a file the user may have edited.
48
+ */
49
+ export async function ensureFacilisStateDir(projectRoot: string): Promise<void> {
50
+ const dir = join(projectRoot, FACILIS_STATE_DIR);
51
+ await mkdir(dir, { recursive: true });
52
+ const ignore = join(dir, ".gitignore");
53
+ try {
54
+ await access(ignore);
55
+ } catch {
56
+ await writeFile(ignore, "*\n");
57
+ }
58
+ }
59
+
60
+ /** Read the dev snapshot; null when the project has none yet. */
61
+ export async function readDevDbSnapshot(path: string): Promise<Uint8Array | null> {
62
+ try {
63
+ return new Uint8Array(await readFile(path));
64
+ } catch (error) {
65
+ if ((error as NodeJS.ErrnoException | null)?.code === "ENOENT") return null;
66
+ throw error;
67
+ }
68
+ }
69
+
70
+ export interface DevDbSnapshotterOptions {
71
+ readonly db: SnapshotSource;
72
+ readonly projectRoot: string;
73
+ readonly snapshotPath?: string;
74
+ readonly intervalMs?: number;
75
+ /** Called with a failed dump/write; the previous snapshot stays valid. */
76
+ readonly onError?: (error: unknown) => void;
77
+ }
78
+
79
+ /**
80
+ * Start snapshotting a dev database. Only a changed cluster is dumped (`activity()`),
81
+ * so an idle project never pays for a dump, and a failed write keeps the last good file.
82
+ */
83
+ export function installDevDbSnapshotter(options: DevDbSnapshotterOptions): DevDbSnapshotter {
84
+ const { db, projectRoot } = options;
85
+ const snapshotPath = options.snapshotPath ?? devDbSnapshotPath(projectRoot);
86
+ const intervalMs = options.intervalMs ?? SNAPSHOT_INTERVAL_MS;
87
+ // Nothing has been dumped yet: the first tick persists the boot state (migrations,
88
+ // seeds), not just the first request-driven write after it.
89
+ let seen = 0;
90
+ let saving = false;
91
+ let dirty = false;
92
+ let stopped = false;
93
+ let lastSnapshotAt: number | null = null;
94
+
95
+ const save = async (): Promise<void> => {
96
+ if (saving) {
97
+ dirty = true;
98
+ return;
99
+ }
100
+ saving = true;
101
+ const activityAtStart = db.activity();
102
+ try {
103
+ const bytes = await db.snapshot();
104
+ await ensureFacilisStateDir(projectRoot);
105
+ await writeAtomic(snapshotPath, bytes);
106
+ seen = activityAtStart;
107
+ lastSnapshotAt = Date.now();
108
+ } catch (error) {
109
+ options.onError?.(error);
110
+ } finally {
111
+ saving = false;
112
+ if (dirty && !stopped) {
113
+ dirty = false;
114
+ void save();
115
+ }
116
+ }
117
+ };
118
+
119
+ const tick = (): void => {
120
+ if (stopped || saving) return;
121
+ if (db.activity() === seen) return;
122
+ void save();
123
+ };
124
+
125
+ const timer = setInterval(tick, intervalMs);
126
+ // Never keep the process (or a test run) alive for the snapshot ticker alone.
127
+ (timer as { unref?: () => void }).unref?.();
128
+ return {
129
+ async flush() {
130
+ if (db.activity() !== seen) await save();
131
+ },
132
+ stop() {
133
+ stopped = true;
134
+ clearInterval(timer);
135
+ },
136
+ lastSnapshotAt: () => lastSnapshotAt,
137
+ };
138
+ }
139
+
140
+ /** Write via a sibling temp file + rename, so a killed process never truncates the snapshot. */
141
+ async function writeAtomic(path: string, bytes: Uint8Array): Promise<void> {
142
+ await mkdir(dirname(path), { recursive: true });
143
+ const temp = path + ".tmp";
144
+ await writeFile(temp, bytes);
145
+ await rename(temp, path);
146
+ }
@@ -0,0 +1,124 @@
1
+ // Dev-only SQL console + live view creation: transport parsing for the two dev routes
2
+ // (SPEC §11.2, D-097). The SQL itself lives in @facilis.dev/db (security rule 5); this module
3
+ // narrows the request bodies and maps database failures to the route's 400 codes.
4
+
5
+ import {
6
+ createLiveView,
7
+ QueryExecutionError,
8
+ runReadOnlyQuery,
9
+ type FacilisDb,
10
+ type QueryExecution,
11
+ } from "@facilis.dev/db";
12
+
13
+ export const DEFAULT_QUERY_LIMIT = 100;
14
+ export const MAX_QUERY_LIMIT = 500;
15
+
16
+ export type DevQueryErrorCode =
17
+ | "invalid_body"
18
+ | "invalid_name"
19
+ | "invalid_sql"
20
+ | "invalid_permission"
21
+ | "query_failed"
22
+ | "create_failed";
23
+
24
+ /** A request the console can render; the code is the body's `code` field. */
25
+ export class DevQueryError extends Error {
26
+ readonly code: DevQueryErrorCode;
27
+
28
+ constructor(code: DevQueryErrorCode, message: string) {
29
+ super(message);
30
+ this.name = "DevQueryError";
31
+ this.code = code;
32
+ }
33
+ }
34
+
35
+ export interface QueryRequest {
36
+ readonly sql: string;
37
+ readonly limit: number;
38
+ }
39
+
40
+ export interface ViewRequest {
41
+ readonly name: string;
42
+ readonly sql: string;
43
+ /** The view's own permission (D-098); null keeps the invoker form. */
44
+ readonly permission: string | null;
45
+ }
46
+
47
+ function isRecord(value: unknown): value is Record<string, unknown> {
48
+ return typeof value === "object" && value !== null && !Array.isArray(value);
49
+ }
50
+
51
+ function readLimit(value: unknown): number | null {
52
+ if (value === undefined) return DEFAULT_QUERY_LIMIT;
53
+ if (typeof value !== "number" || !Number.isInteger(value) || value < 1) return null;
54
+ return Math.min(value, MAX_QUERY_LIMIT);
55
+ }
56
+
57
+ /** Narrow the console body, or a typed error whose code the route returns as-is. */
58
+ export function parseQueryBody(
59
+ body: unknown,
60
+ ): { ok: true; request: QueryRequest } | { ok: false; error: DevQueryError } {
61
+ if (!isRecord(body)) return { ok: false, error: invalidBody("Expected a JSON object body.") };
62
+ const sqlText = body["sql"];
63
+ if (typeof sqlText !== "string" || sqlText.trim().length === 0) {
64
+ return { ok: false, error: invalidBody('"sql" must be a non-empty string.') };
65
+ }
66
+ const limit = readLimit(body["limit"]);
67
+ if (limit === null) {
68
+ return { ok: false, error: invalidBody('"limit" must be a positive integer.') };
69
+ }
70
+ return { ok: true, request: { sql: sqlText, limit } };
71
+ }
72
+
73
+ export function parseViewBody(
74
+ body: unknown,
75
+ ): { ok: true; request: ViewRequest } | { ok: false; error: DevQueryError } {
76
+ if (!isRecord(body)) return { ok: false, error: invalidBody("Expected a JSON object body.") };
77
+ const name = body["name"];
78
+ const sqlText = body["sql"];
79
+ if (typeof name !== "string" || name.length === 0) {
80
+ return { ok: false, error: invalidBody('"name" must be a non-empty string.') };
81
+ }
82
+ if (typeof sqlText !== "string" || sqlText.trim().length === 0) {
83
+ return { ok: false, error: invalidBody('"sql" must be a non-empty string.') };
84
+ }
85
+ const permission = body["permission"];
86
+ if (
87
+ permission !== undefined &&
88
+ permission !== null &&
89
+ (typeof permission !== "string" || permission.length === 0)
90
+ ) {
91
+ return { ok: false, error: invalidBody('"permission" must be a non-empty string.') };
92
+ }
93
+ return {
94
+ ok: true,
95
+ request: { name, sql: sqlText, permission: typeof permission === "string" ? permission : null },
96
+ };
97
+ }
98
+
99
+ /** Execute a parsed query, mapping the database's codes onto the route's codes. */
100
+ export async function runQuery(db: FacilisDb, request: QueryRequest): Promise<QueryExecution> {
101
+ try {
102
+ return await runReadOnlyQuery(db, request.sql, request.limit);
103
+ } catch (error) {
104
+ throw toDevError(error);
105
+ }
106
+ }
107
+
108
+ /** Create a live view from a parsed request, mapping declaration/database failures. */
109
+ export async function createView(db: FacilisDb, request: ViewRequest): Promise<void> {
110
+ try {
111
+ await createLiveView(db, request.name, request.sql, request.permission ?? undefined);
112
+ } catch (error) {
113
+ throw toDevError(error);
114
+ }
115
+ }
116
+
117
+ function toDevError(error: unknown): unknown {
118
+ if (error instanceof QueryExecutionError) return new DevQueryError(error.code, error.message);
119
+ return error;
120
+ }
121
+
122
+ function invalidBody(message: string): DevQueryError {
123
+ return new DevQueryError("invalid_body", message);
124
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Environment access is centralised so the dev-only guards have one definition.
3
+ *
4
+ * The default is **fail-closed** (D-146): only an explicit `development` or `test` counts as
5
+ * non-production, so a deploy that forgets NODE_ENV still gets the production guards (404 dev
6
+ * endpoints, Secure cookies, no in-memory PGlite) instead of exposing them.
7
+ */
8
+ export function isProductionEnvironment(environment: NodeJS.ProcessEnv = process.env): boolean {
9
+ const nodeEnv = environment["NODE_ENV"];
10
+ return nodeEnv !== "development" && nodeEnv !== "test";
11
+ }
12
+
13
+ export function readEnvironment(
14
+ name: string,
15
+ environment: NodeJS.ProcessEnv = process.env,
16
+ ): string | undefined {
17
+ return environment[name];
18
+ }
@@ -0,0 +1,50 @@
1
+ import { isProductionEnvironment } from "./env.ts";
2
+ import { jsonResult, type HttpResult } from "./http.ts";
3
+
4
+ /** Structural header reader: H3Event.req.headers and Headers both satisfy it. */
5
+ export interface HeaderReader {
6
+ get(name: string): string | null;
7
+ }
8
+
9
+ const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "::1", "[::1]"]);
10
+ const DEV_HEADERS = { "cache-control": "no-cache" } as const;
11
+
12
+ /**
13
+ * SPEC §6.8/§8.5 origin allowlist: the request must come from the page the dev
14
+ * server serves. Browsers omit Origin on same-origin GETs, so a missing Origin is
15
+ * allowed; anything present must be loopback or the request host itself.
16
+ */
17
+ export function isOriginAllowed(headers: HeaderReader): boolean {
18
+ const origin = headers.get("origin");
19
+ if (origin === null || origin === "") return true;
20
+ if (origin === "null") return false;
21
+
22
+ let originUrl: URL;
23
+ try {
24
+ originUrl = new URL(origin);
25
+ } catch {
26
+ return false;
27
+ }
28
+ if (originUrl.protocol !== "http:" && originUrl.protocol !== "https:") return false;
29
+ if (LOOPBACK_HOSTNAMES.has(originUrl.hostname)) return true;
30
+
31
+ const host = headers.get("host");
32
+ return host !== null && host !== "" && originUrl.host === host;
33
+ }
34
+
35
+ /**
36
+ * Guard a dev-only endpoint. Returns the error response to short-circuit with, or
37
+ * null when the request may proceed (404 in production, 403 on origin mismatch).
38
+ */
39
+ export function guardDevRequest(
40
+ headers: HeaderReader,
41
+ environment: NodeJS.ProcessEnv = process.env,
42
+ ): HttpResult | null {
43
+ if (isProductionEnvironment(environment)) {
44
+ return jsonResult(404, { code: "not_found" }, { ...DEV_HEADERS });
45
+ }
46
+ if (!isOriginAllowed(headers)) {
47
+ return jsonResult(403, { code: "forbidden" }, { ...DEV_HEADERS });
48
+ }
49
+ return null;
50
+ }
@@ -0,0 +1,30 @@
1
+ /** Environment-independent response envelope used by pure builders and route adapters. */
2
+ export interface HttpResult {
3
+ status: number;
4
+ headers: Record<string, string>;
5
+ body?: unknown;
6
+ }
7
+
8
+ export function jsonResult(
9
+ status: number,
10
+ body: unknown,
11
+ headers: Record<string, string> = {},
12
+ ): HttpResult {
13
+ return {
14
+ status,
15
+ headers: { "content-type": "application/json; charset=utf-8", ...headers },
16
+ body,
17
+ };
18
+ }
19
+
20
+ /** Adapter from the pure builders to a web Response (Nitro v3/h3 v2 accept it). */
21
+ export function toResponse(result: HttpResult): Response {
22
+ const headers = new Headers(result.headers);
23
+ if (result.body === undefined) return new Response(null, { status: result.status, headers });
24
+ return new Response(JSON.stringify(result.body), { status: result.status, headers });
25
+ }
26
+
27
+ /** Request URLs are origin-relative in Nitro; a dummy base only lets URL parse them. */
28
+ export function parseRequestUrl(rawUrl: string): URL {
29
+ return new URL(rawUrl, "http://localhost");
30
+ }
@@ -0,0 +1,97 @@
1
+ import type { FacilisJobsConfig, ManifestWarning } from "@facilis.dev/core";
2
+ import type { FacilisDb } from "@facilis.dev/db";
3
+
4
+ import type { JobModule, JobStore } from "./contracts.ts";
5
+ import { createDbJobStore, isJobsTableAvailable } from "./db-store.ts";
6
+ import { buildJobRegistry } from "./definitions.ts";
7
+ import { createJobEngine } from "./engine.ts";
8
+ import { createSystemJobExecutor } from "./executor.ts";
9
+ import { createMemoryJobStore } from "./memory-store.ts";
10
+ import { createJobsApi, type JobsRuntime } from "./runtime.ts";
11
+
12
+ export interface BootJobsOptions {
13
+ readonly db: FacilisDb;
14
+ readonly jobsConfig: FacilisJobsConfig;
15
+ readonly modules: readonly JobModule[];
16
+ readonly tenantId: string;
17
+ /** Session-wide manifest warnings; boot pushes into it instead of throwing. */
18
+ readonly warnings: ManifestWarning[];
19
+ }
20
+
21
+ /**
22
+ * Boots the background-job runtime (D-107, docs/JOBS.md §8).
23
+ *
24
+ * Never throws: a broken queue degrades to "no jobs" with a manifest warning, because the
25
+ * dev server must still serve the project (contracts §8). The returned runtime is carried by
26
+ * `BootstrapState` and exposed as `ctx.jobs`.
27
+ */
28
+ export async function bootJobs(options: BootJobsOptions): Promise<JobsRuntime | null> {
29
+ const { db, jobsConfig, modules, tenantId, warnings } = options;
30
+ try {
31
+ const registry = buildJobRegistry(modules);
32
+ warnings.push(...registry.warnings);
33
+
34
+ const store = await selectStore(db, jobsConfig, tenantId, warnings);
35
+ // One warning per failing context is enough: a broken store would otherwise flood the
36
+ // manifest on every tick.
37
+ const reportedErrors = new Set<string>();
38
+ const engine = createJobEngine({
39
+ definitions: registry.definitions,
40
+ store,
41
+ config: {
42
+ maxConcurrent: jobsConfig.maxConcurrent,
43
+ maxAttempts: jobsConfig.maxAttempts,
44
+ retryDelayMs: jobsConfig.retryDelayMs,
45
+ timeoutMs: jobsConfig.timeoutMs,
46
+ pollIntervalMs: jobsConfig.pollIntervalMs,
47
+ },
48
+ executor: createSystemJobExecutor(db),
49
+ onError: (error, context) => {
50
+ if (reportedErrors.has(context)) return;
51
+ reportedErrors.add(context);
52
+ warnings.push({
53
+ code: "jobs_runtime_error",
54
+ message: `Background-job scheduler error (${context}): ${describe(error)}`,
55
+ });
56
+ },
57
+ });
58
+
59
+ const runtime: JobsRuntime = {
60
+ api: createJobsApi(engine, jobsConfig.maxConcurrent),
61
+ engine,
62
+ definitions: registry.definitions,
63
+ start: () => engine.start(),
64
+ stop: () => engine.stop(),
65
+ };
66
+ await runtime.start();
67
+ return runtime;
68
+ } catch (error) {
69
+ warnings.push({
70
+ code: "jobs_boot_failed",
71
+ message: `Background jobs are disabled: ${describe(error)}`,
72
+ });
73
+ return null;
74
+ }
75
+ }
76
+
77
+ async function selectStore(
78
+ db: FacilisDb,
79
+ jobsConfig: FacilisJobsConfig,
80
+ tenantId: string,
81
+ warnings: ManifestWarning[],
82
+ ): Promise<JobStore> {
83
+ if (!jobsConfig.persist) return createMemoryJobStore();
84
+ if (await isJobsTableAvailable(db)) return createDbJobStore({ db, tenantId });
85
+ // The project has not applied the framework migration yet: jobs still work, but queued
86
+ // work is lost on the next reload (docs/JOBS.md §8).
87
+ warnings.push({
88
+ code: "jobs_table_missing",
89
+ message:
90
+ "facilis_jobs is missing; background jobs fall back to the in-memory queue. Re-export the table from db/schema.ts and apply the framework migration to persist them.",
91
+ });
92
+ return createMemoryJobStore();
93
+ }
94
+
95
+ function describe(error: unknown): string {
96
+ return error instanceof Error ? error.message : String(error);
97
+ }