@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
@@ -0,0 +1,178 @@
1
+ // Shared PGlite fixture for the workflow suite (D-135). It creates both real table
2
+ // definitions, their policies and the tenant defaults, so the store and runner are exercised
3
+ // through the same RLS boundary the runtime uses in dev.
4
+ import { randomUUID } from "node:crypto";
5
+ import { sql } from "drizzle-orm";
6
+ import { getTableConfig, PgDialect } from "drizzle-orm/pg-core";
7
+ import { createDb, ensureAppRole, facilisTasks, facilisWorkflows, policyCreateSql, tenantDefaultSql, } from "@facilis.dev/db";
8
+ import { createDbTaskStore } from "../tasks/db-store.js";
9
+ import { createDbWorkflowStore } from "./db-store.js";
10
+ /** Deployment tenant; a second tenant proves the RLS boundary cannot be crossed. */
11
+ export const TENANT_ID = "eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee";
12
+ export const OTHER_TENANT = "ffffffff-ffff-ffff-ffff-ffffffffffff";
13
+ export const BASE = new Date("2026-11-10T12:00:00.000Z");
14
+ /**
15
+ * The runner only needs enqueue/get/cancel from the queue; this fake lets a test decide when
16
+ * a step job succeeds, fails or disappears (boot recovery) without a real scheduler.
17
+ */
18
+ export class FakeJobs {
19
+ jobs = new Map();
20
+ sequence = 0;
21
+ async start() { }
22
+ async stop() { }
23
+ async enqueue(name, data) {
24
+ this.sequence += 1;
25
+ const id = randomUUID();
26
+ const at = new Date(BASE.getTime() + this.sequence * 1000);
27
+ this.jobs.set(id, {
28
+ id,
29
+ name,
30
+ status: "queued",
31
+ input: data,
32
+ output: null,
33
+ error: null,
34
+ attempts: 0,
35
+ maxAttempts: 2,
36
+ timeoutMs: 30_000,
37
+ runAt: at,
38
+ createdAt: at,
39
+ startedAt: null,
40
+ finishedAt: null,
41
+ });
42
+ return { id };
43
+ }
44
+ async get(id) {
45
+ return this.jobs.get(id) ?? null;
46
+ }
47
+ async list() {
48
+ return [...this.jobs.values()];
49
+ }
50
+ async queue() {
51
+ return this.list();
52
+ }
53
+ async running() {
54
+ return this.list();
55
+ }
56
+ async cancel(id) {
57
+ const job = this.jobs.get(id);
58
+ if (job === undefined || isTerminal(job.status))
59
+ return false;
60
+ job.status = "cancelled";
61
+ job.finishedAt = new Date(BASE.getTime() + this.sequence * 1000);
62
+ return true;
63
+ }
64
+ async stats() {
65
+ return { queued: 0, running: 0, succeeded: 0, failed: 0, cancelled: 0 };
66
+ }
67
+ scoped() {
68
+ return this;
69
+ }
70
+ /** The job row remains but settles as succeeded (what advance() reads on the next tick). */
71
+ succeed(id, output = null) {
72
+ const job = this.required(id);
73
+ job.status = "succeeded";
74
+ job.output = output;
75
+ job.finishedAt = new Date();
76
+ }
77
+ fail(id, error) {
78
+ const job = this.required(id);
79
+ job.status = "failed";
80
+ job.error = error;
81
+ job.finishedAt = new Date();
82
+ }
83
+ /** Boot recovery case: the queue lost the row entirely. */
84
+ forget(id) {
85
+ this.jobs.delete(id);
86
+ }
87
+ /** A definition the runner validates a dangling step against. */
88
+ static definitions(...names) {
89
+ return new Map(names.map((name) => [
90
+ name,
91
+ {
92
+ name,
93
+ input: { safeParse: (value) => ({ success: true, data: value }) },
94
+ output: { safeParse: (value) => ({ success: true, data: value }) },
95
+ run: () => undefined,
96
+ },
97
+ ]));
98
+ }
99
+ lastEnqueuedName() {
100
+ const jobs = [...this.jobs.values()];
101
+ return jobs.length === 0 ? null : (jobs[jobs.length - 1]?.name ?? null);
102
+ }
103
+ get latest() {
104
+ const jobs = [...this.jobs.values()];
105
+ return jobs[jobs.length - 1];
106
+ }
107
+ required(id) {
108
+ const job = this.jobs.get(id);
109
+ if (job === undefined)
110
+ throw new Error("unknown fake job " + id);
111
+ return job;
112
+ }
113
+ }
114
+ function isTerminal(status) {
115
+ return status === "succeeded" || status === "failed" || status === "cancelled";
116
+ }
117
+ export async function createWorkflowsTestContext() {
118
+ const db = await createDb();
119
+ const tenantDefault = new PgDialect().sqlToQuery(tenantDefaultSql()).sql;
120
+ const statements = [
121
+ `CREATE TABLE facilis_tasks (
122
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
123
+ workflow_id uuid,
124
+ step_index integer,
125
+ kind text NOT NULL,
126
+ status text NOT NULL,
127
+ decision text,
128
+ title_key text NOT NULL,
129
+ title_params jsonb NOT NULL DEFAULT '{}'::jsonb,
130
+ payload jsonb,
131
+ requested_by text,
132
+ assigned_permission text,
133
+ expires_at timestamptz,
134
+ decided_by text,
135
+ decided_at timestamptz,
136
+ comment text,
137
+ created_at timestamptz NOT NULL DEFAULT now(),
138
+ tenant_id uuid NOT NULL DEFAULT ${tenantDefault}
139
+ )`,
140
+ "ALTER TABLE facilis_tasks ENABLE ROW LEVEL SECURITY",
141
+ `CREATE TABLE facilis_workflows (
142
+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
143
+ name text NOT NULL,
144
+ status text NOT NULL,
145
+ input jsonb NOT NULL,
146
+ progress jsonb NOT NULL DEFAULT '[]'::jsonb,
147
+ plan jsonb NOT NULL DEFAULT '[]'::jsonb,
148
+ current_step integer NOT NULL DEFAULT 0,
149
+ current_job_id uuid,
150
+ waiting_task_id uuid,
151
+ attempts integer NOT NULL DEFAULT 0,
152
+ output jsonb,
153
+ error text,
154
+ started_at timestamptz NOT NULL DEFAULT now(),
155
+ finished_at timestamptz,
156
+ created_at timestamptz NOT NULL DEFAULT now(),
157
+ tenant_id uuid NOT NULL DEFAULT ${tenantDefault}
158
+ )`,
159
+ "ALTER TABLE facilis_workflows ENABLE ROW LEVEL SECURITY",
160
+ ...getTableConfig(facilisTasks).policies.map((policy) => policyCreateSql("facilis_tasks", policy)),
161
+ ...getTableConfig(facilisWorkflows).policies.map((policy) => policyCreateSql("facilis_workflows", policy)),
162
+ ];
163
+ await db.db.transaction(async (tx) => {
164
+ for (const statement of statements)
165
+ await tx.execute(sql.raw(statement));
166
+ });
167
+ await ensureAppRole(db);
168
+ return {
169
+ db,
170
+ workflows: createDbWorkflowStore({ db, tenantId: TENANT_ID }),
171
+ tasks: createDbTaskStore({ db, tenantId: TENANT_ID }),
172
+ jobs: new FakeJobs(),
173
+ };
174
+ }
175
+ export async function clearWorkflows(db) {
176
+ await db.db.execute(sql.raw("delete from facilis_workflows"));
177
+ await db.db.execute(sql.raw("delete from facilis_tasks"));
178
+ }
@@ -0,0 +1,13 @@
1
+ import type { FacilisHandlerEvent } from "@facilis.dev/core";
2
+ export interface SessionCookieOptions {
3
+ /** Session lifetime: the cookie must expire with the `sessions` row (config.auth.sessionDurationMs). */
4
+ readonly ttlMs: number;
5
+ /** `Secure` attribute; defaults to the fail-closed production check (D-146). */
6
+ readonly secure?: boolean;
7
+ }
8
+ /** Sets `facilis_session` on the response of the current request. */
9
+ export declare function setSessionCookie(event: FacilisHandlerEvent, sessionId: string, options: SessionCookieOptions): void;
10
+ /** Expires `facilis_session` on the response of the current request (logout). */
11
+ export declare function clearSessionCookie(event: FacilisHandlerEvent): void;
12
+ /** Reads the session id from the request; `null` when the request carries no session. */
13
+ export declare function sessionIdFromRequest(event: FacilisHandlerEvent): string | null;
@@ -0,0 +1,48 @@
1
+ import { SESSION_COOKIE_NAME } from "@facilis.dev/auth";
2
+ import { deleteCookie, getCookie, setCookie } from "nitro/h3";
3
+ import { isProductionEnvironment } from "./runtime/env.js";
4
+ /**
5
+ * Session-cookie helpers for route handlers (contracts §4.4, D-038).
6
+ *
7
+ * h3 owns the cookie surface: `setCookie`/`deleteCookie` serialise the attributes and
8
+ * write them to the EVENT's response headers, which is the only place a cookie is merged
9
+ * into the response by this server (a `Set-Cookie` on a returned `Response` is dropped
10
+ * in the in-VM Nitro dev path — D-038). They also APPEND rather than replace, so a cookie
11
+ * another handler staged on the same response is not clobbered.
12
+ *
13
+ * The attribute set is the framework's, not the app's: every Facilis app that logs a user
14
+ * in must emit the same `facilis_session` cookie (HttpOnly, Path=/, SameSite=Lax, Secure
15
+ * in production), so apps call these helpers instead of h3's setters directly.
16
+ */
17
+ const COOKIE_PATH = "/";
18
+ const MS_PER_SECOND = 1000;
19
+ /**
20
+ * Nitro hands handlers a real `H3Event`, but the route contract is core's structural
21
+ * event: core, auth and db never import h3, so a handler can be reused by any Fetch
22
+ * runtime (contracts §4.1). The cast is the one place that narrows back to the runtime.
23
+ */
24
+ function h3Event(event) {
25
+ if (event.res === undefined) {
26
+ throw new Error("facilis: the server event has no response headers to stage the session cookie on");
27
+ }
28
+ return event;
29
+ }
30
+ /** Sets `facilis_session` on the response of the current request. */
31
+ export function setSessionCookie(event, sessionId, options) {
32
+ setCookie(h3Event(event), SESSION_COOKIE_NAME, sessionId, {
33
+ httpOnly: true,
34
+ path: COOKIE_PATH,
35
+ sameSite: "lax",
36
+ secure: options.secure ?? isProductionEnvironment(),
37
+ maxAge: Math.max(0, Math.floor(options.ttlMs / MS_PER_SECOND)),
38
+ });
39
+ }
40
+ /** Expires `facilis_session` on the response of the current request (logout). */
41
+ export function clearSessionCookie(event) {
42
+ deleteCookie(h3Event(event), SESSION_COOKIE_NAME, { path: COOKIE_PATH });
43
+ }
44
+ /** Reads the session id from the request; `null` when the request carries no session. */
45
+ export function sessionIdFromRequest(event) {
46
+ const value = getCookie(event, SESSION_COOKIE_NAME);
47
+ return value === undefined || value.length === 0 ? null : value;
48
+ }
@@ -0,0 +1,50 @@
1
+ import { type AuthContext, type FacilisHandlerEvent, type StorageApi } from "@facilis.dev/core";
2
+ import { type PolicyScopedDatabase } from "@facilis.dev/db";
3
+ /**
4
+ * Route-facing helpers for binary uploads (D-053, SPEC §5.10).
5
+ *
6
+ * The framework stores the bytes and the `facilis_files` metadata; the app's own route
7
+ * declares the permissions, decides which entity the file belongs to and inserts the
8
+ * generated link row (`fileLinks`). The download route is token-only, so it can stay a
9
+ * public route (`permission: []`) and serve `<img>`/shared links without a cookie.
10
+ */
11
+ export interface StoredFile {
12
+ readonly id: string;
13
+ readonly name: string;
14
+ readonly mime: string;
15
+ readonly size: number;
16
+ /** Signed, app-relative download URL (default TTL: storage.tokenTtlSeconds). */
17
+ readonly url: string;
18
+ }
19
+ export interface StoreUploadInput {
20
+ readonly event: FacilisHandlerEvent;
21
+ readonly db: PolicyScopedDatabase;
22
+ readonly storage: StorageApi;
23
+ readonly auth: AuthContext | null;
24
+ readonly file: File;
25
+ }
26
+ export interface SendStoredFileInput {
27
+ readonly db: PolicyScopedDatabase;
28
+ readonly storage: StorageApi;
29
+ readonly fileId: string;
30
+ readonly token: string;
31
+ readonly tenantId?: string;
32
+ /** Override the `content-disposition` filename (defaults to the stored name). */
33
+ readonly responseName?: string;
34
+ }
35
+ /** Store the uploaded bytes and their metadata row; the caller inserts the link row. */
36
+ export declare function storeUpload(input: StoreUploadInput): Promise<StoredFile | Response>;
37
+ /**
38
+ * Validate the signed token, load the metadata row and return the bytes.
39
+ *
40
+ * The token binds the file id (and optionally the tenant); the row lookup runs under the
41
+ * request's policy scope, so a token from another deployment cannot reach a foreign row.
42
+ * Production streams through a driver-presigned redirect when the driver supports it.
43
+ */
44
+ export declare function sendStoredFile(input: SendStoredFileInput): Promise<Response>;
45
+ /** Headers that make a user-uploaded blob safe to serve from the app origin. */
46
+ export declare function fileHeaders(mime: string, name: string, length: number): Headers;
47
+ /** Strip path separators/control characters; keep the display name users already saw. */
48
+ export declare function sanitizeFileName(value: string): string;
49
+ /** Only a syntactically valid MIME type is echoed back; anything else is octet-stream. */
50
+ export declare function sanitizeMime(value: string): string;
@@ -0,0 +1,118 @@
1
+ import { Readable } from "node:stream";
2
+ import { eq } from "drizzle-orm";
3
+ import { DEFAULT_TENANT_ID, fail, } from "@facilis.dev/core";
4
+ import { facilisFiles } from "@facilis.dev/db";
5
+ const DEFAULT_FILE_NAME = "file";
6
+ const MAX_FILE_NAME = 180;
7
+ const DEFAULT_MIME = "application/octet-stream";
8
+ const SAFE_MIME = /^[\w.+-]+\/[\w.+-]+$/;
9
+ /** Store the uploaded bytes and their metadata row; the caller inserts the link row. */
10
+ export async function storeUpload(input) {
11
+ const { event, db, storage, auth, file } = input;
12
+ if (!storage.available)
13
+ return fail("storage_unavailable");
14
+ if (auth === null)
15
+ return fail("unauthorized");
16
+ // Reject before reading the body into memory: the limit is the framework's, not the UI's.
17
+ if (file.size > storage.maxUploadBytes) {
18
+ return fail("file_too_large", { maxBytes: storage.maxUploadBytes, size: file.size });
19
+ }
20
+ const name = sanitizeFileName(file.name);
21
+ const mime = sanitizeMime(file.type);
22
+ // Stream the multipart file straight into storage (D-117): no full-file buffer here.
23
+ const put = await storage.put(Readable.fromWeb(file.stream()));
24
+ const [row] = await db
25
+ .insert(facilisFiles)
26
+ .values({ hash: put.hash, name, mime, size: put.size, ownerId: auth.userId })
27
+ .returning({ id: facilisFiles.id });
28
+ if (row === undefined)
29
+ return fail("internal_error");
30
+ const tenantId = event.context.facilis?.defaultTenantId ?? DEFAULT_TENANT_ID;
31
+ return {
32
+ id: row.id,
33
+ name,
34
+ mime,
35
+ size: put.size,
36
+ url: storage.buildDownloadUrl(row.id, { tenantId, subject: auth.userId }),
37
+ };
38
+ }
39
+ /**
40
+ * Validate the signed token, load the metadata row and return the bytes.
41
+ *
42
+ * The token binds the file id (and optionally the tenant); the row lookup runs under the
43
+ * request's policy scope, so a token from another deployment cannot reach a foreign row.
44
+ * Production streams through a driver-presigned redirect when the driver supports it.
45
+ */
46
+ export async function sendStoredFile(input) {
47
+ const { db, storage, fileId, token, tenantId } = input;
48
+ if (!storage.available)
49
+ return fail("storage_unavailable");
50
+ const payload = storage.verifyDownloadToken(token, fileId);
51
+ if (payload === null)
52
+ return fail("not_found");
53
+ if (payload.tenantId !== undefined && tenantId !== undefined && payload.tenantId !== tenantId) {
54
+ return fail("not_found");
55
+ }
56
+ const [row] = await db
57
+ .select({
58
+ hash: facilisFiles.hash,
59
+ name: facilisFiles.name,
60
+ mime: facilisFiles.mime,
61
+ size: facilisFiles.size,
62
+ })
63
+ .from(facilisFiles)
64
+ .where(eq(facilisFiles.id, fileId))
65
+ .limit(1);
66
+ if (row === undefined)
67
+ return fail("not_found");
68
+ const name = sanitizeFileName(input.responseName ?? row.name);
69
+ if (storage.presignedGetUrl !== undefined) {
70
+ const location = await storage.presignedGetUrl(row.hash, { responseName: name });
71
+ return new Response(null, { status: 302, headers: { location } });
72
+ }
73
+ // Stream the plaintext straight into the response: the size header comes from the
74
+ // metadata row, so neither encrypted nor plaintext downloads are ever buffered whole.
75
+ const source = await storage.get(row.hash);
76
+ const body = Readable.toWeb(Readable.from(source));
77
+ return new Response(body, {
78
+ status: 200,
79
+ headers: fileHeaders(sanitizeMime(row.mime), name, row.size),
80
+ });
81
+ }
82
+ /** Headers that make a user-uploaded blob safe to serve from the app origin. */
83
+ export function fileHeaders(mime, name, length) {
84
+ return new Headers({
85
+ "content-type": mime,
86
+ "content-length": String(length),
87
+ // Never render an uploaded HTML/SVG document on the app origin; attachment downloads
88
+ // still work for links, and <img> subresources ignore the disposition.
89
+ "content-disposition": contentDisposition(name),
90
+ "x-content-type-options": "nosniff",
91
+ "content-security-policy": "sandbox",
92
+ "cache-control": "private, max-age=60",
93
+ });
94
+ }
95
+ /** Strip path separators/control characters; keep the display name users already saw. */
96
+ export function sanitizeFileName(value) {
97
+ const base = value.split(/[\\/]/).pop() ?? "";
98
+ const cleaned = stripControlCharacters(base).trim().slice(0, MAX_FILE_NAME);
99
+ return cleaned.length === 0 ? DEFAULT_FILE_NAME : cleaned;
100
+ }
101
+ /** Drop C0 controls and DEL without a control-character regex (lint forbids one). */
102
+ function stripControlCharacters(value) {
103
+ let out = "";
104
+ for (const character of value) {
105
+ const code = character.codePointAt(0) ?? 0;
106
+ if (code >= 0x20 && code !== 0x7f)
107
+ out += character;
108
+ }
109
+ return out;
110
+ }
111
+ /** Only a syntactically valid MIME type is echoed back; anything else is octet-stream. */
112
+ export function sanitizeMime(value) {
113
+ return SAFE_MIME.test(value) ? value.toLowerCase() : DEFAULT_MIME;
114
+ }
115
+ function contentDisposition(name) {
116
+ const ascii = name.replace(/[^\x20-\x7e]/g, "_").replace(/["\\]/g, "_");
117
+ return `attachment; filename="${ascii}"; filename*=UTF-8''${encodeURIComponent(name)}`;
118
+ }
@@ -0,0 +1,44 @@
1
+ import type { ManifestWarning } from "@facilis.dev/core";
2
+ /** HTTP methods a Facilis route file can declare (SPEC §7.3 RouteMeta.method). */
3
+ export type HttpMethod = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
4
+ /** Config keys the route metadata pass can extract; anything else is ignored. */
5
+ export type MetadataField = "permission" | "dbTables" | "dbColumns" | "description" | "crossSite" | "rawSql";
6
+ /**
7
+ * One route's statically extracted metadata.
8
+ *
9
+ * `unresolved` records which fields were not statically readable, so the OpenAPI
10
+ * facade can omit them instead of publishing a wrong value (SPEC §13 risk 3 / §6.9).
11
+ */
12
+ export interface RouteMetadata {
13
+ method: HttpMethod;
14
+ /** OpenAPI-style path, e.g. `/api/todos/{id}`. */
15
+ path: string;
16
+ permission?: string | readonly string[];
17
+ /** True when the route is declared callable from another origin; omitted otherwise. */
18
+ crossSite?: boolean;
19
+ /** `rawSql: true` allows `db.execute` (D-157); false when absent, undefined when unreadable. */
20
+ rawSql?: boolean;
21
+ /** `[]` when the config declares none or the value is not statically readable. */
22
+ dbTables: readonly string[];
23
+ dbColumns: readonly string[];
24
+ description?: string;
25
+ unresolved: readonly MetadataField[];
26
+ /** Project-relative path for editor jump-to (RouteMeta.sourceFile). */
27
+ sourceFile?: string;
28
+ warnings: readonly ManifestWarning[];
29
+ }
30
+ /** Map keyed by OpenAPI path first, then lower-case method (OpenAPI's own casing). */
31
+ export type RouteMetadataMap = Readonly<Record<string, Readonly<Record<string, RouteMetadata>>>>;
32
+ export interface ScanOptions {
33
+ /** Absolute project root; the analyzer owns the project's DSL layout (D-092). */
34
+ rootDir: string;
35
+ /** Receives warnings that belong to no route (parse/config diagnostics). */
36
+ onWarning?: (warning: ManifestWarning) => void;
37
+ }
38
+ /**
39
+ * Reserved plugin options.
40
+ *
41
+ * The analyzer derives the route layout (`server/routes/**`) from the project root (D-092),
42
+ * so `facilis()` takes no options today; the type stays exported for the documented API.
43
+ */
44
+ export type FacilisOptions = Record<string, never>;
package/dist/types.js ADDED
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Virtual module identifiers shared by the Vite plugin (producer) and the Nitro
3
+ * module/runtime (consumers).
4
+ *
5
+ * The Vite plugin owns `#facilis/openapi-meta` because it needs HMR invalidation
6
+ * when a project source file changes: the analyzer reads the config and the consts route
7
+ * configs import, so routes are not the only input (D-092, SPEC §6.9 consequence); the
8
+ * Nitro module only needs a build-time fallback for the standalone `nitro.config.ts` case.
9
+ */
10
+ export declare const VIRTUAL_CONFIG_ID = "#facilis/config";
11
+ export declare const VIRTUAL_DB_SCHEMA_ID = "#facilis/db-schema";
12
+ export declare const VIRTUAL_DB_VIEWS_ID = "#facilis/db-views";
13
+ export declare const VIRTUAL_JOBS_ID = "#facilis/jobs";
14
+ export declare const VIRTUAL_WORKFLOWS_ID = "#facilis/workflows";
15
+ export declare const VIRTUAL_OPENAPI_META_ID = "#facilis/openapi-meta";
16
+ /** Resolved ids must start with \0 so no on-disk file can shadow them. */
17
+ export declare const RESOLVED_OPENAPI_META_ID = "\0facilis:openapi-meta";
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Virtual module identifiers shared by the Vite plugin (producer) and the Nitro
3
+ * module/runtime (consumers).
4
+ *
5
+ * The Vite plugin owns `#facilis/openapi-meta` because it needs HMR invalidation
6
+ * when a project source file changes: the analyzer reads the config and the consts route
7
+ * configs import, so routes are not the only input (D-092, SPEC §6.9 consequence); the
8
+ * Nitro module only needs a build-time fallback for the standalone `nitro.config.ts` case.
9
+ */
10
+ export const VIRTUAL_CONFIG_ID = "#facilis/config";
11
+ export const VIRTUAL_DB_SCHEMA_ID = "#facilis/db-schema";
12
+ export const VIRTUAL_DB_VIEWS_ID = "#facilis/db-views";
13
+ export const VIRTUAL_JOBS_ID = "#facilis/jobs";
14
+ export const VIRTUAL_WORKFLOWS_ID = "#facilis/workflows";
15
+ export const VIRTUAL_OPENAPI_META_ID = "#facilis/openapi-meta";
16
+ /** Resolved ids must start with \0 so no on-disk file can shadow them. */
17
+ export const RESOLVED_OPENAPI_META_ID = "\0facilis:openapi-meta";
package/dist/vite.d.ts ADDED
@@ -0,0 +1,22 @@
1
+ import type { Plugin } from "vite";
2
+ import type { NitroModule } from "nitro/types";
3
+ export interface FacilisVitePlugin extends Plugin {
4
+ /** The Nitro module Vite exposes on the plugin object (SPEC §5.6). */
5
+ readonly nitro: NitroModule;
6
+ }
7
+ /**
8
+ * `facilis()`'s return value: the framework plugin first, then Nitro's own Vite plugins.
9
+ *
10
+ * Nitro is mounted by `facilis()` so a project never imports `nitro/vite` itself and never
11
+ * keeps a `nitro.config.ts` (D-034): its options come from `facilis.config.ts`.
12
+ */
13
+ export type FacilisPlugins = [FacilisVitePlugin, ...Plugin[]];
14
+ /**
15
+ * The Facilis Vite plugin (SPEC §5.6, Appendix E), plus the Nitro plugins it mounts.
16
+ *
17
+ * Three jobs: carry the Nitro module, deliver the project's Nitro options to Nitro, and own
18
+ * the framework route-metadata pass. The pass is a virtual module so project edits can be
19
+ * invalidated through Vite's module graph and HMR keeps /_openapi.json and
20
+ * /__facilis/manifest fresh (SPEC §6.9, contracts §8).
21
+ */
22
+ export declare function facilis(): FacilisPlugins;
package/dist/vite.js ADDED
@@ -0,0 +1,135 @@
1
+ import { isAbsolute, relative, resolve, sep } from "node:path";
2
+ import { nitro } from "nitro/vite";
3
+ import { loadNitroOptions } from "./config.js";
4
+ import { createFacilisNitroModule } from "./module.js";
5
+ import { analyzeProjectRoutes, routeMetadataFromAnalysis } from "./route-metadata.js";
6
+ import { RESOLVED_OPENAPI_META_ID, VIRTUAL_OPENAPI_META_ID } from "./virtual-ids.js";
7
+ /** Extensions the analyzer reads; a change to any of them can change the route facts. */
8
+ const PROJECT_FILE_PATTERN = /\.(?:[cm]?[jt]sx?|json)$/;
9
+ /** Directories the analyzer skips (its ALWAYS_SKIPPED set plus node_modules). */
10
+ const IGNORED_SEGMENTS = new Set([
11
+ ".facilis",
12
+ ".git",
13
+ ".output",
14
+ ".turbo",
15
+ "coverage",
16
+ "dist",
17
+ "node_modules",
18
+ ]);
19
+ /**
20
+ * The Facilis Vite plugin (SPEC §5.6, Appendix E), plus the Nitro plugins it mounts.
21
+ *
22
+ * Three jobs: carry the Nitro module, deliver the project's Nitro options to Nitro, and own
23
+ * the framework route-metadata pass. The pass is a virtual module so project edits can be
24
+ * invalidated through Vite's module graph and HMR keeps /_openapi.json and
25
+ * /__facilis/manifest fresh (SPEC §6.9, contracts §8).
26
+ */
27
+ export function facilis() {
28
+ let root = process.cwd();
29
+ // One analysis per revision of the project: the mapping is cheap, the analyzer is not.
30
+ let analysis;
31
+ let metadata;
32
+ const loadMetadata = (warn) => {
33
+ if (metadata !== undefined)
34
+ return metadata;
35
+ analysis ??= analyzeProjectRoutes(root);
36
+ metadata =
37
+ analysis === undefined
38
+ ? {}
39
+ : routeMetadataFromAnalysis(analysis, (warning) => warn?.(warning.message));
40
+ return metadata;
41
+ };
42
+ const invalidate = () => {
43
+ analysis = undefined;
44
+ metadata = undefined;
45
+ };
46
+ // The analyzer reads facilis.config.ts and any project module a route config imports
47
+ // (D-092), so every project source file can change the route facts, not just routes.
48
+ const onProjectSourceChanged = (file) => {
49
+ if (!isProjectSourceFile(file, root))
50
+ return false;
51
+ invalidate();
52
+ return true;
53
+ };
54
+ const plugin = {
55
+ name: "facilis",
56
+ enforce: "pre",
57
+ nitro: createFacilisNitroModule(),
58
+ // Deliver the project's Nitro options through Vite's own `nitro` user-config key,
59
+ // which is what Nitro's plugin reads. `enforce: "pre"` is what makes it work: config
60
+ // hooks run in plugin order, so this one has already merged the `nitro` key into the
61
+ // user config by the time nitro:init builds its Nitro instance. Nothing about the
62
+ // project's plugins array (e.g. facilis() before react()) can change that.
63
+ async config(userConfig) {
64
+ const projectRoot = userConfig.root === undefined ? process.cwd() : resolve(userConfig.root);
65
+ return { nitro: await loadNitroOptions(projectRoot) };
66
+ },
67
+ configResolved(config) {
68
+ root = config.root;
69
+ },
70
+ // Warm the analysis before the first request so a broken route file surfaces as a
71
+ // warning during startup, not as a surprising slow first spec fetch.
72
+ async buildStart() {
73
+ loadMetadata((message) => this.warn(message));
74
+ },
75
+ configureServer(server) {
76
+ // handleHotUpdate covers changed modules; add/unlink also need an invalidation
77
+ // because a brand-new or deleted project file may have no module-graph entry yet.
78
+ server.watcher.on("all", (event, file) => {
79
+ if (event !== "add" && event !== "unlink" && event !== "addDir")
80
+ return;
81
+ if (!onProjectSourceChanged(file))
82
+ return;
83
+ invalidateOpenApiMetaModule(server);
84
+ });
85
+ },
86
+ handleHotUpdate(context) {
87
+ if (!onProjectSourceChanged(context.file))
88
+ return;
89
+ invalidateOpenApiMetaModule(context.server);
90
+ // Returning void leaves the rest of the update pipeline (Nitro's own server
91
+ // reload for route handlers) untouched.
92
+ },
93
+ resolveId(id) {
94
+ if (id === VIRTUAL_OPENAPI_META_ID)
95
+ return RESOLVED_OPENAPI_META_ID;
96
+ return null;
97
+ },
98
+ async load(id) {
99
+ if (id !== RESOLVED_OPENAPI_META_ID)
100
+ return null;
101
+ return `export default ${JSON.stringify(loadMetadata((message) => this.warn(message)))};`;
102
+ },
103
+ };
104
+ return [plugin, ...nitro()];
105
+ }
106
+ /** True for a file the analyzer reads, excluding generated and dependency directories. */
107
+ function isProjectSourceFile(file, root) {
108
+ const projectRelative = relative(root, resolve(file));
109
+ if (projectRelative.length === 0 || isAbsolute(projectRelative))
110
+ return false;
111
+ const segments = projectRelative.split(sep);
112
+ if (segments[0] === "..")
113
+ return false;
114
+ if (segments.some((segment) => IGNORED_SEGMENTS.has(segment)))
115
+ return false;
116
+ return PROJECT_FILE_PATTERN.test(projectRelative);
117
+ }
118
+ /**
119
+ * Invalidate the virtual metadata module in every environment that may have imported
120
+ * it. Nitro's handlers live in an environment of their own, so the mixed (legacy)
121
+ * module graph alone is not enough.
122
+ */
123
+ function invalidateOpenApiMetaModule(server) {
124
+ for (const environment of Object.values(server.environments)) {
125
+ const graph = environment.moduleGraph;
126
+ if (graph === undefined)
127
+ continue;
128
+ const module = graph.getModuleById(RESOLVED_OPENAPI_META_ID);
129
+ if (module !== undefined)
130
+ graph.invalidateModule(module);
131
+ }
132
+ const legacy = server.moduleGraph.getModuleById(RESOLVED_OPENAPI_META_ID);
133
+ if (legacy !== undefined)
134
+ server.moduleGraph.invalidateModule(legacy);
135
+ }