@rebasepro/server-core 0.7.0 → 0.8.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 (155) hide show
  1. package/build-errors.txt +52 -0
  2. package/dist/api/ast-schema-editor.d.ts +21 -0
  3. package/dist/api/collections_for_test/callbacks_test_collection.d.ts +2 -0
  4. package/dist/api/errors.d.ts +53 -0
  5. package/dist/api/graphql/graphql-schema-generator.d.ts +44 -0
  6. package/dist/api/graphql/index.d.ts +1 -0
  7. package/dist/api/index.d.ts +9 -0
  8. package/dist/api/logs-routes.d.ts +37 -0
  9. package/dist/api/openapi-generator.d.ts +16 -0
  10. package/dist/api/rest/api-generator.d.ts +76 -0
  11. package/dist/api/rest/index.d.ts +1 -0
  12. package/dist/api/rest/query-parser.d.ts +8 -0
  13. package/dist/api/schema-editor-routes.d.ts +3 -0
  14. package/dist/api/server.d.ts +40 -0
  15. package/dist/api/types.d.ts +104 -0
  16. package/dist/auth/adapter-middleware.d.ts +43 -0
  17. package/dist/auth/admin-roles-route.d.ts +18 -0
  18. package/dist/auth/admin-user-ops.d.ts +79 -0
  19. package/dist/auth/admin-users-route.d.ts +28 -0
  20. package/dist/auth/api-keys/api-key-middleware.d.ts +39 -0
  21. package/dist/auth/api-keys/api-key-permission-guard.d.ts +32 -0
  22. package/dist/auth/api-keys/api-key-routes.d.ts +20 -0
  23. package/dist/auth/api-keys/api-key-store.d.ts +35 -0
  24. package/dist/auth/api-keys/api-key-types.d.ts +96 -0
  25. package/dist/auth/api-keys/index.d.ts +17 -0
  26. package/dist/auth/apple-oauth.d.ts +30 -0
  27. package/dist/auth/auth-hooks.d.ts +242 -0
  28. package/dist/auth/bitbucket-oauth.d.ts +11 -0
  29. package/dist/auth/builtin-auth-adapter.d.ts +51 -0
  30. package/dist/auth/crypto-utils.d.ts +16 -0
  31. package/dist/auth/custom-auth-adapter.d.ts +39 -0
  32. package/dist/auth/discord-oauth.d.ts +14 -0
  33. package/dist/auth/facebook-oauth.d.ts +14 -0
  34. package/dist/auth/github-oauth.d.ts +15 -0
  35. package/dist/auth/gitlab-oauth.d.ts +13 -0
  36. package/dist/auth/google-oauth.d.ts +47 -0
  37. package/dist/auth/index.d.ts +37 -0
  38. package/dist/auth/interfaces.d.ts +431 -0
  39. package/dist/auth/jwt.d.ts +55 -0
  40. package/dist/auth/linkedin-oauth.d.ts +18 -0
  41. package/dist/auth/magic-link-routes.d.ts +30 -0
  42. package/dist/auth/mfa-crypto.d.ts +23 -0
  43. package/dist/auth/mfa-routes.d.ts +7 -0
  44. package/dist/auth/mfa.d.ts +49 -0
  45. package/dist/auth/microsoft-oauth.d.ts +16 -0
  46. package/dist/auth/middleware.d.ts +113 -0
  47. package/dist/auth/password.d.ts +22 -0
  48. package/dist/auth/rate-limiter.d.ts +50 -0
  49. package/dist/auth/reset-password-admin.d.ts +29 -0
  50. package/dist/auth/rls-scope.d.ts +31 -0
  51. package/dist/auth/routes.d.ts +35 -0
  52. package/dist/auth/session-routes.d.ts +27 -0
  53. package/dist/auth/slack-oauth.d.ts +12 -0
  54. package/dist/auth/spotify-oauth.d.ts +12 -0
  55. package/dist/auth/twitter-oauth.d.ts +18 -0
  56. package/dist/backend-CIxN4FVm.js +15 -0
  57. package/dist/backend-CIxN4FVm.js.map +1 -0
  58. package/dist/base64-js-C_frYBkI.js +1687 -0
  59. package/dist/base64-js-C_frYBkI.js.map +1 -0
  60. package/dist/chunk-Dze3rakg.js +42 -0
  61. package/dist/collections/BackendCollectionRegistry.d.ts +13 -0
  62. package/dist/collections/loader.d.ts +5 -0
  63. package/dist/cron/cron-loader.d.ts +17 -0
  64. package/dist/cron/cron-routes.d.ts +14 -0
  65. package/dist/cron/cron-scheduler.d.ts +106 -0
  66. package/dist/cron/cron-store.d.ts +32 -0
  67. package/dist/cron/index.d.ts +6 -0
  68. package/dist/db/interfaces.d.ts +18 -0
  69. package/dist/dist-DMO-zF6D.js +832 -0
  70. package/dist/dist-DMO-zF6D.js.map +1 -0
  71. package/dist/email/index.d.ts +6 -0
  72. package/dist/email/smtp-email-service.d.ts +25 -0
  73. package/dist/email/templates.d.ts +50 -0
  74. package/dist/email/types.d.ts +126 -0
  75. package/dist/env.d.ts +102 -0
  76. package/dist/from-VbwD7xRf.js +3849 -0
  77. package/dist/from-VbwD7xRf.js.map +1 -0
  78. package/dist/functions/define-function.d.ts +50 -0
  79. package/dist/functions/function-loader.d.ts +17 -0
  80. package/dist/functions/function-routes.d.ts +10 -0
  81. package/dist/functions/index.d.ts +5 -0
  82. package/dist/history/history-routes.d.ts +23 -0
  83. package/dist/history/index.d.ts +1 -0
  84. package/dist/index.d.ts +31 -0
  85. package/dist/index.es.js +61322 -0
  86. package/dist/index.es.js.map +1 -0
  87. package/dist/index.umd.js +103633 -0
  88. package/dist/index.umd.js.map +1 -0
  89. package/dist/init/docs.d.ts +4 -0
  90. package/dist/init/health.d.ts +2 -0
  91. package/dist/init/middlewares.d.ts +10 -0
  92. package/dist/init/shutdown.d.ts +11 -0
  93. package/dist/init/storage.d.ts +5 -0
  94. package/dist/init.d.ts +314 -0
  95. package/dist/jws-BqRRaK11.js +616 -0
  96. package/dist/jws-BqRRaK11.js.map +1 -0
  97. package/dist/jwt-BETC8a1J.js +3560 -0
  98. package/dist/jwt-BETC8a1J.js.map +1 -0
  99. package/dist/logger-BYU66ENZ.js +94 -0
  100. package/dist/logger-BYU66ENZ.js.map +1 -0
  101. package/dist/ms-BeBSuOXN.js +125 -0
  102. package/dist/ms-BeBSuOXN.js.map +1 -0
  103. package/dist/multipart-parser-CedBDOeC.js +299 -0
  104. package/dist/multipart-parser-CedBDOeC.js.map +1 -0
  105. package/dist/serve-spa.d.ts +30 -0
  106. package/dist/services/driver-registry.d.ts +78 -0
  107. package/dist/services/routed-realtime-service.d.ts +43 -0
  108. package/dist/services/webhook-service.d.ts +29 -0
  109. package/dist/singleton.d.ts +35 -0
  110. package/dist/src-CB2PIpBe.js +1182 -0
  111. package/dist/src-CB2PIpBe.js.map +1 -0
  112. package/dist/src-DjzOT1kG.js +29746 -0
  113. package/dist/src-DjzOT1kG.js.map +1 -0
  114. package/dist/storage/GCSStorageController.d.ts +43 -0
  115. package/dist/storage/LocalStorageController.d.ts +46 -0
  116. package/dist/storage/S3StorageController.d.ts +36 -0
  117. package/dist/storage/image-transform.d.ts +50 -0
  118. package/dist/storage/index.d.ts +31 -0
  119. package/dist/storage/routes.d.ts +70 -0
  120. package/dist/storage/storage-registry.d.ts +78 -0
  121. package/dist/storage/tus-handler.d.ts +53 -0
  122. package/dist/storage/types.d.ts +128 -0
  123. package/dist/types/index.d.ts +11 -0
  124. package/dist/utils/dev-port.d.ts +37 -0
  125. package/dist/utils/logger.d.ts +31 -0
  126. package/dist/utils/logging.d.ts +9 -0
  127. package/dist/utils/request-id.d.ts +4 -0
  128. package/dist/utils/request-logger.d.ts +19 -0
  129. package/dist/utils/sql.d.ts +27 -0
  130. package/package.json +22 -14
  131. package/src/api/graphql/graphql-schema-generator.ts +5 -5
  132. package/src/api/openapi-generator.ts +2 -2
  133. package/src/api/rest/api-generator.ts +44 -123
  134. package/src/api/rest/query-parser.ts +6 -23
  135. package/src/api/types.ts +2 -2
  136. package/src/auth/auth-hooks.ts +1 -1
  137. package/src/auth/builtin-auth-adapter.ts +1 -2
  138. package/src/auth/interfaces.ts +11 -2
  139. package/src/auth/middleware.ts +4 -4
  140. package/src/auth/routes.ts +1 -2
  141. package/src/functions/define-function.ts +59 -0
  142. package/src/functions/function-loader.ts +16 -0
  143. package/src/functions/index.ts +2 -0
  144. package/src/index.ts +70 -37
  145. package/src/init.ts +78 -21
  146. package/src/storage/GCSStorageController.ts +334 -0
  147. package/src/storage/index.ts +9 -3
  148. package/src/storage/routes.ts +191 -23
  149. package/src/storage/tus-handler.ts +16 -4
  150. package/src/storage/types.ts +25 -3
  151. package/test/api-generator.test.ts +1 -1
  152. package/test/auth-config-types.test.ts +40 -0
  153. package/test/define-function.test.ts +45 -0
  154. package/test/storage-routes.test.ts +160 -0
  155. package/test/backend-hooks-data.test.ts +0 -477
@@ -13,6 +13,7 @@ import { Hono } from "hono";
13
13
  import { HonoEnv } from "../src/api/types";
14
14
  import { errorHandler } from "../src/api/errors";
15
15
  import { LocalStorageController } from "../src/storage/LocalStorageController";
16
+ import { DefaultStorageRegistry } from "../src/storage/storage-registry";
16
17
  import { createStorageRoutes, extractWildcardPath } from "../src/storage/routes";
17
18
 
18
19
  // ──────────────────────────────────────────────────────────────────────
@@ -191,6 +192,38 @@ force: true });
191
192
  });
192
193
  });
193
194
 
195
+ describe("GET /sources", () => {
196
+ it("returns the default source in single-controller mode", async () => {
197
+ const res = await app.fetch(new Request("http://localhost/api/storage/sources"));
198
+ expect(res.status).toBe(200);
199
+ const body = await res.json() as { success: boolean; data: Array<{ key: string; engine: string; transport: string }> };
200
+ expect(body.success).toBe(true);
201
+ expect(body.data).toEqual([
202
+ { key: "(default)", engine: "local", transport: "server" }
203
+ ]);
204
+ });
205
+
206
+ it("merges declared definitions, including direct sources and labels", async () => {
207
+ const declaredApp = new Hono<HonoEnv>();
208
+ declaredApp.onError(errorHandler);
209
+ const routes = createStorageRoutes({
210
+ controller,
211
+ requireAuth: false,
212
+ sources: [
213
+ { key: "(default)", engine: "local", transport: "server", label: "Local" },
214
+ { key: "firebase", engine: "firebase", transport: "direct", label: "Firebase Storage" }
215
+ ]
216
+ });
217
+ declaredApp.route("/api/storage", routes);
218
+
219
+ const res = await declaredApp.fetch(new Request("http://localhost/api/storage/sources"));
220
+ expect(res.status).toBe(200);
221
+ const body = await res.json() as { success: boolean; data: Array<{ key: string; engine: string; transport: string; label?: string }> };
222
+ expect(body.data).toContainEqual({ key: "(default)", engine: "local", transport: "server", label: "Local" });
223
+ expect(body.data).toContainEqual({ key: "firebase", engine: "firebase", transport: "direct", label: "Firebase Storage" });
224
+ });
225
+ });
226
+
194
227
  describe("DELETE /file/*", () => {
195
228
  it("should delete an existing file", async () => {
196
229
  // Upload another file to delete
@@ -220,3 +253,130 @@ key: "photos/deleteme.txt" });
220
253
  });
221
254
  });
222
255
  });
256
+
257
+ // ──────────────────────────────────────────────────────────────────────
258
+ // Multi-backend routing through the StorageRegistry
259
+ // ──────────────────────────────────────────────────────────────────────
260
+ describe("Storage routes — multi-backend routing (registry)", () => {
261
+ let app: Hono<HonoEnv>;
262
+ let defaultDir: string;
263
+ let secondaryDir: string;
264
+
265
+ beforeEach(async () => {
266
+ defaultDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "rebase-default-"));
267
+ secondaryDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "rebase-secondary-"));
268
+
269
+ const registry = DefaultStorageRegistry.create({
270
+ "(default)": new LocalStorageController({ basePath: defaultDir }),
271
+ secondary: new LocalStorageController({ basePath: secondaryDir })
272
+ });
273
+
274
+ app = new Hono<HonoEnv>();
275
+ app.onError(errorHandler);
276
+ app.route("/api/storage", createStorageRoutes({
277
+ registry,
278
+ requireAuth: false,
279
+ sources: [
280
+ { key: "(default)", engine: "local", transport: "server" },
281
+ { key: "secondary", engine: "local", transport: "server", label: "Secondary" }
282
+ ]
283
+ }));
284
+ });
285
+
286
+ afterEach(async () => {
287
+ await fs.promises.rm(defaultDir, { recursive: true, force: true });
288
+ await fs.promises.rm(secondaryDir, { recursive: true, force: true });
289
+ });
290
+
291
+ async function upload(storageId: string | undefined, key: string, content: string) {
292
+ const fd = new FormData();
293
+ fd.append("file", new File([Buffer.from(content)], "file.txt", { type: "text/plain" }));
294
+ fd.append("key", key);
295
+ if (storageId) fd.append("storageId", storageId);
296
+ return app.fetch(new Request("http://localhost/api/storage/upload", { method: "POST", body: fd }));
297
+ }
298
+
299
+ it("routes an upload to the backend named by storageId", async () => {
300
+ const res = await upload("secondary", "docs/secret.txt", "in-secondary");
301
+ expect(res.ok).toBe(true);
302
+
303
+ // It physically landed in the secondary backend, not the default one.
304
+ const inSecondary = await app.fetch(
305
+ new Request("http://localhost/api/storage/file/default/docs/secret.txt?storageId=secondary")
306
+ );
307
+ expect(inSecondary.status).toBe(200);
308
+ expect(await inSecondary.text()).toBe("in-secondary");
309
+
310
+ // The default backend does not have it.
311
+ const inDefault = await app.fetch(
312
+ new Request("http://localhost/api/storage/file/default/docs/secret.txt")
313
+ );
314
+ expect(inDefault.status).toBe(404);
315
+ });
316
+
317
+ it("keeps the same key isolated per backend", async () => {
318
+ await upload(undefined, "shared.txt", "from-default");
319
+ await upload("secondary", "shared.txt", "from-secondary");
320
+
321
+ const d = await app.fetch(new Request("http://localhost/api/storage/file/default/shared.txt"));
322
+ const s = await app.fetch(new Request("http://localhost/api/storage/file/default/shared.txt?storageId=secondary"));
323
+ expect(await d.text()).toBe("from-default");
324
+ expect(await s.text()).toBe("from-secondary");
325
+ });
326
+
327
+ it("serves metadata from the backend named by storageId", async () => {
328
+ await upload("secondary", "m.txt", "x");
329
+ const res = await app.fetch(
330
+ new Request("http://localhost/api/storage/metadata/default/m.txt?storageId=secondary")
331
+ );
332
+ expect(res.status).toBe(200);
333
+ const body = await res.json() as { success: boolean; data: { contentType: string } };
334
+ expect(body.success).toBe(true);
335
+ expect(body.data.contentType).toBe("text/plain");
336
+ });
337
+
338
+ it("lists only the targeted backend's contents", async () => {
339
+ await upload(undefined, "only-default.txt", "a");
340
+ await upload("secondary", "only-secondary.txt", "b");
341
+
342
+ const res = await app.fetch(new Request("http://localhost/api/storage/list?storageId=secondary"));
343
+ const body = await res.json() as { data: { items: Array<{ name: string }> } };
344
+ const names = body.data.items.map((i) => i.name);
345
+ expect(names).toContain("only-secondary.txt");
346
+ expect(names).not.toContain("only-default.txt");
347
+ });
348
+
349
+ it("deletes from the backend named by storageId", async () => {
350
+ await upload("secondary", "del.txt", "bye");
351
+
352
+ const del = await app.fetch(
353
+ new Request("http://localhost/api/storage/file/default/del.txt?storageId=secondary", { method: "DELETE" })
354
+ );
355
+ expect(del.status).toBe(200);
356
+
357
+ const after = await app.fetch(
358
+ new Request("http://localhost/api/storage/file/default/del.txt?storageId=secondary")
359
+ );
360
+ expect(after.status).toBe(404);
361
+ });
362
+
363
+ it("falls back to the default backend for an unknown storageId", async () => {
364
+ const res = await upload("does-not-exist", "fallback.txt", "fell-back");
365
+ expect(res.ok).toBe(true);
366
+
367
+ // Unknown id falls back to default, so the file is in the default backend.
368
+ const inDefault = await app.fetch(
369
+ new Request("http://localhost/api/storage/file/default/fallback.txt")
370
+ );
371
+ expect(inDefault.status).toBe(200);
372
+ expect(await inDefault.text()).toBe("fell-back");
373
+ });
374
+
375
+ it("lists both backends via GET /sources", async () => {
376
+ const res = await app.fetch(new Request("http://localhost/api/storage/sources"));
377
+ const body = await res.json() as { data: Array<{ key: string; engine: string; label?: string }> };
378
+ const keys = body.data.map((s) => s.key);
379
+ expect(keys).toEqual(expect.arrayContaining(["(default)", "secondary"]));
380
+ expect(body.data.find((s) => s.key === "secondary")?.label).toBe("Secondary");
381
+ });
382
+ });
@@ -1,477 +0,0 @@
1
- /**
2
- * BackendHooks — Data (REST API) Integration Tests
3
- *
4
- * Verifies that DataHooks are correctly applied within RestApiGenerator
5
- * for all collection CRUD operations.
6
- */
7
-
8
- import { Hono } from "hono";
9
- import { RestApiGenerator } from "../src/api/rest/api-generator";
10
- import { errorHandler } from "../src/api/errors";
11
- import type { DataDriver } from "@rebasepro/types";
12
- import type { EntityCollection } from "@rebasepro/types";
13
- import type { DataHooks } from "@rebasepro/types";
14
-
15
- // ── Helpers ─────────────────────────────────────────────────────────────────
16
-
17
- function createMockDriver(): jest.Mocked<DataDriver> {
18
- return {
19
- key: "postgres",
20
- initialised: true,
21
- fetchCollection: jest.fn(),
22
- listenCollection: jest.fn(),
23
- fetchEntity: jest.fn(),
24
- listenEntity: jest.fn(),
25
- saveEntity: jest.fn(),
26
- deleteEntity: jest.fn(),
27
- checkUniqueField: jest.fn(),
28
- countEntities: jest.fn(),
29
- withAuth: jest.fn(),
30
- admin: {} as any
31
- } as unknown as jest.Mocked<DataDriver>;
32
- }
33
-
34
- const mockCollections: EntityCollection[] = [
35
- { slug: "products",
36
- name: "Products",
37
- singularName: "Product",
38
- properties: {} } as any,
39
- { slug: "orders",
40
- name: "Orders",
41
- singularName: "Order",
42
- properties: {} } as any
43
- ];
44
-
45
- function createApp(mockDriver: jest.Mocked<DataDriver>, hooks?: DataHooks) {
46
- const app = new Hono();
47
- app.onError(errorHandler);
48
- // RestApiGenerator.getScopedDriver reads from c.get("driver") which is
49
- // normally set by auth middleware. Replicate that here for tests.
50
- app.use("/api/*", async (c, next) => {
51
- c.set("driver", mockDriver);
52
- await next();
53
- });
54
- const generator = new RestApiGenerator(mockCollections, mockDriver, hooks);
55
- app.route("/api", generator.generateRoutes());
56
- return app;
57
- }
58
-
59
- // ═════════════════════════════════════════════════════════════════════════════
60
- // TESTS
61
- // ═════════════════════════════════════════════════════════════════════════════
62
-
63
- describe("DataHooks — REST API", () => {
64
- let mockDriver: jest.Mocked<DataDriver>;
65
-
66
- beforeEach(() => {
67
- mockDriver = createMockDriver();
68
- });
69
-
70
- // ── afterRead ─────────────────────────────────────────────────────
71
- describe("data.afterRead", () => {
72
- it("transforms entities in GET list response", async () => {
73
- const hooks: DataHooks = {
74
- afterRead(slug, entity) {
75
- // Mask price for non-premium entities
76
- if (slug === "products") {
77
- return { ...entity,
78
- price: "***" };
79
- }
80
- return entity;
81
- }
82
- };
83
- const app = createApp(mockDriver, hooks);
84
-
85
- mockDriver.fetchCollection.mockResolvedValue([
86
- { id: "p1",
87
- path: "products",
88
- values: { name: "Widget",
89
- price: 99 } } as any,
90
- { id: "p2",
91
- path: "products",
92
- values: { name: "Gadget",
93
- price: 199 } } as any
94
- ]);
95
- mockDriver.countEntities!.mockResolvedValue(2);
96
-
97
- const res = await app.request("/api/products");
98
- expect(res.status).toBe(200);
99
-
100
- const body = await res.json() as any;
101
- expect(body.data).toHaveLength(2);
102
- expect(body.data[0].price).toBe("***");
103
- expect(body.data[1].price).toBe("***");
104
- // Original field should still be there
105
- expect(body.data[0].name).toBe("Widget");
106
- });
107
-
108
- it("filters out entities by returning null", async () => {
109
- const hooks: DataHooks = {
110
- afterRead(slug, entity) {
111
- // Hide draft products
112
- if (entity.status === "draft") return null;
113
- return entity;
114
- }
115
- };
116
- const app = createApp(mockDriver, hooks);
117
-
118
- mockDriver.fetchCollection.mockResolvedValue([
119
- { id: "p1",
120
- path: "products",
121
- values: { name: "Published",
122
- status: "active" } } as any,
123
- { id: "p2",
124
- path: "products",
125
- values: { name: "Draft",
126
- status: "draft" } } as any,
127
- { id: "p3",
128
- path: "products",
129
- values: { name: "Also Published",
130
- status: "active" } } as any
131
- ]);
132
- mockDriver.countEntities!.mockResolvedValue(3);
133
-
134
- const res = await app.request("/api/products");
135
- const body = await res.json() as any;
136
- expect(body.data).toHaveLength(2);
137
- expect(body.data.map((d: any) => d.name)).toEqual(["Published", "Also Published"]);
138
- });
139
-
140
- it("transforms single entity GET response", async () => {
141
- const hooks: DataHooks = {
142
- afterRead(slug, entity) {
143
- return { ...entity,
144
- _readAt: "2024-01-01" };
145
- }
146
- };
147
- const app = createApp(mockDriver, hooks);
148
-
149
- mockDriver.fetchEntity.mockResolvedValue(
150
- { id: "p1",
151
- path: "products",
152
- values: { name: "Widget" } } as any
153
- );
154
-
155
- const res = await app.request("/api/products/p1");
156
- expect(res.status).toBe(200);
157
-
158
- const body = await res.json() as any;
159
- expect(body.name).toBe("Widget");
160
- expect(body._readAt).toBe("2024-01-01");
161
- });
162
-
163
- it("returns 404 when afterRead filters a single entity", async () => {
164
- const hooks: DataHooks = {
165
- afterRead(slug, entity) {
166
- if (entity.id === "hidden") return null;
167
- return entity;
168
- }
169
- };
170
- const app = createApp(mockDriver, hooks);
171
-
172
- mockDriver.fetchEntity.mockResolvedValue(
173
- { id: "hidden",
174
- path: "products",
175
- values: { name: "Secret" } } as any
176
- );
177
-
178
- const res = await app.request("/api/products/hidden");
179
- expect(res.status).toBe(404);
180
- });
181
-
182
- it("only affects targeted collection slug", async () => {
183
- const hooks: DataHooks = {
184
- afterRead(slug, entity) {
185
- if (slug === "products") {
186
- return { ...entity,
187
- hooked: true };
188
- }
189
- return entity;
190
- }
191
- };
192
- const app = createApp(mockDriver, hooks);
193
-
194
- // Products should be hooked
195
- mockDriver.fetchEntity.mockResolvedValueOnce(
196
- { id: "p1",
197
- path: "products",
198
- values: { name: "Widget" } } as any
199
- );
200
- const prodRes = await app.request("/api/products/p1");
201
- const prodBody = await prodRes.json() as any;
202
- expect(prodBody.hooked).toBe(true);
203
-
204
- // Orders should NOT be hooked
205
- mockDriver.fetchEntity.mockResolvedValueOnce(
206
- { id: "o1",
207
- path: "orders",
208
- values: { total: 42 } } as any
209
- );
210
- const orderRes = await app.request("/api/orders/o1");
211
- const orderBody = await orderRes.json() as any;
212
- expect(orderBody.hooked).toBeUndefined();
213
- });
214
- });
215
-
216
- // ── beforeSave ────────────────────────────────────────────────────
217
- describe("data.beforeSave", () => {
218
- it("transforms values before POST (create)", async () => {
219
- const hooks: DataHooks = {
220
- beforeSave(slug, values, entityId) {
221
- return { ...values,
222
- slug: values.name?.toString().toLowerCase().replace(/\s+/g, "-") };
223
- }
224
- };
225
- const app = createApp(mockDriver, hooks);
226
-
227
- mockDriver.saveEntity.mockResolvedValue(
228
- { id: "new-1",
229
- path: "products",
230
- values: { name: "Cool Widget",
231
- slug: "cool-widget" } } as any
232
- );
233
-
234
- const res = await app.request("/api/products", {
235
- method: "POST",
236
- headers: { "Content-Type": "application/json" },
237
- body: JSON.stringify({ name: "Cool Widget" })
238
- });
239
-
240
- expect(res.status).toBe(201);
241
- expect(mockDriver.saveEntity).toHaveBeenCalledWith(
242
- expect.objectContaining({
243
- values: expect.objectContaining({ slug: "cool-widget" })
244
- })
245
- );
246
- });
247
-
248
- it("transforms values before PUT (update)", async () => {
249
- const hooks: DataHooks = {
250
- beforeSave(slug, values, entityId) {
251
- // Add an updatedBy field
252
- return { ...values,
253
- updatedBy: "hook" };
254
- }
255
- };
256
- const app = createApp(mockDriver, hooks);
257
-
258
- mockDriver.fetchEntity.mockResolvedValue({ id: "p1",
259
- path: "products",
260
- values: {} } as any);
261
- mockDriver.saveEntity.mockResolvedValue(
262
- { id: "p1",
263
- path: "products",
264
- values: { name: "Updated",
265
- updatedBy: "hook" } } as any
266
- );
267
-
268
- const res = await app.request("/api/products/p1", {
269
- method: "PUT",
270
- headers: { "Content-Type": "application/json" },
271
- body: JSON.stringify({ name: "Updated" })
272
- });
273
-
274
- expect(res.status).toBe(200);
275
- expect(mockDriver.saveEntity).toHaveBeenCalledWith(
276
- expect.objectContaining({
277
- values: expect.objectContaining({ updatedBy: "hook" })
278
- })
279
- );
280
- });
281
-
282
- it("receives entityId=undefined on POST, actual id on PUT", async () => {
283
- const beforeSaveSpy = jest.fn((slug, values, entityId) => values);
284
- const hooks: DataHooks = { beforeSave: beforeSaveSpy };
285
- const app = createApp(mockDriver, hooks);
286
-
287
- // POST
288
- mockDriver.saveEntity.mockResolvedValueOnce(
289
- { id: "new-1",
290
- path: "products",
291
- values: { name: "A" } } as any
292
- );
293
- await app.request("/api/products", {
294
- method: "POST",
295
- headers: { "Content-Type": "application/json" },
296
- body: JSON.stringify({ name: "A" })
297
- });
298
- expect(beforeSaveSpy.mock.calls[0][2]).toBeUndefined(); // entityId
299
-
300
- // PUT
301
- mockDriver.fetchEntity.mockResolvedValueOnce({ id: "p1",
302
- path: "products",
303
- values: {} } as any);
304
- mockDriver.saveEntity.mockResolvedValueOnce(
305
- { id: "p1",
306
- path: "products",
307
- values: { name: "B" } } as any
308
- );
309
- await app.request("/api/products/p1", {
310
- method: "PUT",
311
- headers: { "Content-Type": "application/json" },
312
- body: JSON.stringify({ name: "B" })
313
- });
314
- expect(beforeSaveSpy.mock.calls[1][2]).toBe("p1"); // entityId
315
- });
316
-
317
- it("aborts save when beforeSave throws", async () => {
318
- const hooks: DataHooks = {
319
- beforeSave(slug, values) {
320
- if (!values.name) throw new Error("Name is required");
321
- return values;
322
- }
323
- };
324
- const app = createApp(mockDriver, hooks);
325
-
326
- const res = await app.request("/api/products", {
327
- method: "POST",
328
- headers: { "Content-Type": "application/json" },
329
- body: JSON.stringify({ price: 99 })
330
- });
331
-
332
- // Should get an error status
333
- expect(res.status).toBeGreaterThanOrEqual(400);
334
- expect(mockDriver.saveEntity).not.toHaveBeenCalled();
335
- });
336
- });
337
-
338
- // ── afterSave ─────────────────────────────────────────────────────
339
- describe("data.afterSave", () => {
340
- it("fires afterSave after POST", async () => {
341
- const afterSaveSpy = jest.fn();
342
- const hooks: DataHooks = { afterSave: afterSaveSpy };
343
- const app = createApp(mockDriver, hooks);
344
-
345
- mockDriver.saveEntity.mockResolvedValue(
346
- { id: "new-1",
347
- path: "products",
348
- values: { name: "Widget" } } as any
349
- );
350
-
351
- const res = await app.request("/api/products", {
352
- method: "POST",
353
- headers: { "Content-Type": "application/json" },
354
- body: JSON.stringify({ name: "Widget" })
355
- });
356
-
357
- expect(res.status).toBe(201);
358
- await new Promise(r => setTimeout(r, 50));
359
- expect(afterSaveSpy).toHaveBeenCalledTimes(1);
360
- expect(afterSaveSpy).toHaveBeenCalledWith(
361
- "products",
362
- expect.objectContaining({ id: "new-1",
363
- name: "Widget" }),
364
- expect.objectContaining({ method: "POST" })
365
- );
366
- });
367
-
368
- it("fires afterSave after PUT", async () => {
369
- const afterSaveSpy = jest.fn();
370
- const hooks: DataHooks = { afterSave: afterSaveSpy };
371
- const app = createApp(mockDriver, hooks);
372
-
373
- mockDriver.fetchEntity.mockResolvedValue({ id: "p1",
374
- path: "products",
375
- values: {} } as any);
376
- mockDriver.saveEntity.mockResolvedValue(
377
- { id: "p1",
378
- path: "products",
379
- values: { name: "Updated" } } as any
380
- );
381
-
382
- await app.request("/api/products/p1", {
383
- method: "PUT",
384
- headers: { "Content-Type": "application/json" },
385
- body: JSON.stringify({ name: "Updated" })
386
- });
387
-
388
- await new Promise(r => setTimeout(r, 50));
389
- expect(afterSaveSpy).toHaveBeenCalledWith(
390
- "products",
391
- expect.objectContaining({ id: "p1" }),
392
- expect.objectContaining({ method: "PUT" })
393
- );
394
- });
395
- });
396
-
397
- // ── beforeDelete / afterDelete ───────────────────────────────────
398
- describe("data.beforeDelete / afterDelete", () => {
399
- it("aborts deletion when beforeDelete throws", async () => {
400
- const hooks: DataHooks = {
401
- beforeDelete(slug, entityId) {
402
- if (entityId === "protected") {
403
- throw new Error("Cannot delete protected entity");
404
- }
405
- }
406
- };
407
- const app = createApp(mockDriver, hooks);
408
-
409
- mockDriver.fetchEntity.mockResolvedValue(
410
- { id: "protected",
411
- path: "products",
412
- values: {} } as any
413
- );
414
-
415
- const res = await app.request("/api/products/protected", { method: "DELETE" });
416
- expect(res.status).toBe(500);
417
- expect(mockDriver.deleteEntity).not.toHaveBeenCalled();
418
- });
419
-
420
- it("allows deletion when beforeDelete does not throw", async () => {
421
- const beforeDeleteSpy = jest.fn();
422
- const hooks: DataHooks = { beforeDelete: beforeDeleteSpy };
423
- const app = createApp(mockDriver, hooks);
424
-
425
- const existingEntity = { id: "p1",
426
- path: "products",
427
- values: {} } as any;
428
- mockDriver.fetchEntity.mockResolvedValue(existingEntity);
429
- mockDriver.deleteEntity.mockResolvedValue();
430
-
431
- const res = await app.request("/api/products/p1", { method: "DELETE" });
432
- expect(res.status).toBe(204);
433
- expect(beforeDeleteSpy).toHaveBeenCalledWith(
434
- "products", "p1", expect.objectContaining({ method: "DELETE" })
435
- );
436
- expect(mockDriver.deleteEntity).toHaveBeenCalled();
437
- });
438
-
439
- it("fires afterDelete after successful deletion", async () => {
440
- const afterDeleteSpy = jest.fn();
441
- const hooks: DataHooks = { afterDelete: afterDeleteSpy };
442
- const app = createApp(mockDriver, hooks);
443
-
444
- mockDriver.fetchEntity.mockResolvedValue({ id: "p1",
445
- path: "products",
446
- values: {} } as any);
447
- mockDriver.deleteEntity.mockResolvedValue();
448
-
449
- await app.request("/api/products/p1", { method: "DELETE" });
450
- await new Promise(r => setTimeout(r, 50));
451
-
452
- expect(afterDeleteSpy).toHaveBeenCalledWith(
453
- "products", "p1", expect.objectContaining({ method: "DELETE" })
454
- );
455
- });
456
- });
457
-
458
- // ── no hooks (passthrough) ──────────────────────────────────────
459
- describe("no hooks configured", () => {
460
- it("returns data unchanged when no hooks are provided", async () => {
461
- const app = createApp(mockDriver); // no hooks
462
- mockDriver.fetchCollection.mockResolvedValue([
463
- { id: "p1",
464
- path: "products",
465
- values: { name: "Widget" } } as any
466
- ]);
467
- mockDriver.countEntities!.mockResolvedValue(1);
468
-
469
- const res = await app.request("/api/products");
470
- expect(res.status).toBe(200);
471
-
472
- const body = await res.json() as any;
473
- expect(body.data).toHaveLength(1);
474
- expect(body.data[0].name).toBe("Widget");
475
- });
476
- });
477
- });