@zveltio/sdk 2.0.8 → 3.0.0-beta.100

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 (157) hide show
  1. package/README.md +17 -4
  2. package/dist/build/index.d.ts +77 -0
  3. package/dist/build/index.d.ts.map +1 -0
  4. package/dist/build/index.js +157 -0
  5. package/dist/client.d.ts +103 -7
  6. package/dist/client.d.ts.map +1 -1
  7. package/dist/client.js +129 -28
  8. package/dist/core.d.ts.map +1 -1
  9. package/dist/core.js +21 -3
  10. package/dist/crdt.d.ts.map +1 -1
  11. package/dist/crdt.js +11 -2
  12. package/dist/ddl/index.d.ts +173 -0
  13. package/dist/ddl/index.d.ts.map +1 -0
  14. package/dist/ddl/index.js +33 -0
  15. package/dist/errors.d.ts +58 -0
  16. package/dist/errors.d.ts.map +1 -0
  17. package/dist/errors.js +124 -0
  18. package/dist/extension/action-refusal.d.ts +27 -0
  19. package/dist/extension/action-refusal.d.ts.map +1 -0
  20. package/dist/extension/action-refusal.js +29 -0
  21. package/dist/extension/capabilities.d.ts +71 -0
  22. package/dist/extension/capabilities.d.ts.map +1 -0
  23. package/dist/extension/capabilities.js +79 -0
  24. package/dist/extension/dates.d.ts +7 -0
  25. package/dist/extension/dates.d.ts.map +1 -0
  26. package/dist/extension/dates.js +14 -0
  27. package/dist/extension/index.d.ts +1570 -10
  28. package/dist/extension/index.d.ts.map +1 -1
  29. package/dist/extension/index.js +17 -1
  30. package/dist/extension/jsonb.d.ts +62 -0
  31. package/dist/extension/jsonb.d.ts.map +1 -0
  32. package/dist/extension/jsonb.js +64 -0
  33. package/dist/extension/multipart.d.ts +58 -0
  34. package/dist/extension/multipart.d.ts.map +1 -0
  35. package/dist/extension/multipart.js +61 -0
  36. package/dist/extension/numeric.d.ts +94 -0
  37. package/dist/extension/numeric.d.ts.map +1 -0
  38. package/dist/extension/numeric.js +162 -0
  39. package/dist/extension/permission-gate.d.ts +52 -0
  40. package/dist/extension/permission-gate.d.ts.map +1 -0
  41. package/dist/extension/permission-gate.js +125 -0
  42. package/dist/extension/reserved-paths.d.ts +10 -0
  43. package/dist/extension/reserved-paths.d.ts.map +1 -0
  44. package/dist/extension/reserved-paths.js +23 -0
  45. package/dist/index.d.ts +4 -2
  46. package/dist/index.d.ts.map +1 -1
  47. package/dist/index.js +1 -0
  48. package/dist/local-store.d.ts +14 -1
  49. package/dist/local-store.d.ts.map +1 -1
  50. package/dist/local-store.js +93 -16
  51. package/dist/offline/index.d.ts +75 -0
  52. package/dist/offline/index.d.ts.map +1 -0
  53. package/dist/offline/index.js +251 -0
  54. package/dist/publish/index.d.ts +94 -0
  55. package/dist/publish/index.d.ts.map +1 -0
  56. package/dist/publish/index.js +153 -0
  57. package/dist/realtime.d.ts +25 -1
  58. package/dist/realtime.d.ts.map +1 -1
  59. package/dist/realtime.js +53 -5
  60. package/dist/rpc/index.d.ts +68 -0
  61. package/dist/rpc/index.d.ts.map +1 -0
  62. package/dist/rpc/index.js +63 -0
  63. package/dist/schema-codegen.d.ts +84 -0
  64. package/dist/schema-codegen.d.ts.map +1 -0
  65. package/dist/schema-codegen.js +503 -0
  66. package/dist/schema-watcher.d.ts +10 -2
  67. package/dist/schema-watcher.d.ts.map +1 -1
  68. package/dist/schema-watcher.js +26 -13
  69. package/dist/studio/index.d.ts +85 -0
  70. package/dist/studio/index.d.ts.map +1 -0
  71. package/dist/studio/index.js +183 -0
  72. package/dist/studio/slot-owner-registry.d.ts +13 -0
  73. package/dist/studio/slot-owner-registry.d.ts.map +1 -0
  74. package/dist/studio/slot-owner-registry.js +21 -0
  75. package/dist/svelte.d.ts +1 -1
  76. package/dist/svelte.d.ts.map +1 -1
  77. package/dist/svelte.js +4 -2
  78. package/dist/sync-manager.d.ts +49 -4
  79. package/dist/sync-manager.d.ts.map +1 -1
  80. package/dist/sync-manager.js +175 -24
  81. package/dist/testing/index.d.ts +121 -0
  82. package/dist/testing/index.d.ts.map +1 -0
  83. package/dist/testing/index.js +305 -0
  84. package/dist/testing/with-test-db.d.ts +119 -0
  85. package/dist/testing/with-test-db.d.ts.map +1 -0
  86. package/dist/testing/with-test-db.js +320 -0
  87. package/dist/tests/action-refusal.test.d.ts +2 -0
  88. package/dist/tests/action-refusal.test.d.ts.map +1 -0
  89. package/dist/tests/action-refusal.test.js +13 -0
  90. package/dist/tests/client.test.d.ts +2 -0
  91. package/dist/tests/client.test.d.ts.map +1 -0
  92. package/dist/tests/client.test.js +164 -0
  93. package/dist/tests/crdt-orset.test.d.ts +2 -0
  94. package/dist/tests/crdt-orset.test.d.ts.map +1 -0
  95. package/dist/tests/crdt-orset.test.js +23 -0
  96. package/dist/tests/local-store.test.js +44 -0
  97. package/dist/tests/migration-parse.test.d.ts +2 -0
  98. package/dist/tests/migration-parse.test.d.ts.map +1 -0
  99. package/dist/tests/migration-parse.test.js +17 -0
  100. package/dist/tests/multipart.test.d.ts +2 -0
  101. package/dist/tests/multipart.test.d.ts.map +1 -0
  102. package/dist/tests/multipart.test.js +37 -0
  103. package/dist/tests/offline-provider-crdt.test.d.ts +2 -0
  104. package/dist/tests/offline-provider-crdt.test.d.ts.map +1 -0
  105. package/dist/tests/offline-provider-crdt.test.js +206 -0
  106. package/dist/tests/realtime.test.d.ts +2 -0
  107. package/dist/tests/realtime.test.d.ts.map +1 -0
  108. package/dist/tests/realtime.test.js +220 -0
  109. package/dist/tests/reserved-paths.test.d.ts +2 -0
  110. package/dist/tests/reserved-paths.test.d.ts.map +1 -0
  111. package/dist/tests/reserved-paths.test.js +21 -0
  112. package/dist/tests/sync-manager.test.d.ts +2 -0
  113. package/dist/tests/sync-manager.test.d.ts.map +1 -0
  114. package/dist/tests/sync-manager.test.js +123 -0
  115. package/dist/tests/today-in.test.d.ts +2 -0
  116. package/dist/tests/today-in.test.d.ts.map +1 -0
  117. package/dist/tests/today-in.test.js +14 -0
  118. package/dist/tests/validate-manifest-actions.test.d.ts +2 -0
  119. package/dist/tests/validate-manifest-actions.test.d.ts.map +1 -0
  120. package/dist/tests/validate-manifest-actions.test.js +82 -0
  121. package/dist/tests/validate-manifest-dependencies.test.d.ts +2 -0
  122. package/dist/tests/validate-manifest-dependencies.test.d.ts.map +1 -0
  123. package/dist/tests/validate-manifest-dependencies.test.js +27 -0
  124. package/dist/tests/validate-manifest-forward-credentials.test.d.ts +2 -0
  125. package/dist/tests/validate-manifest-forward-credentials.test.d.ts.map +1 -0
  126. package/dist/tests/validate-manifest-forward-credentials.test.js +35 -0
  127. package/dist/tests/validate-sdui-data-endpoints.test.d.ts +2 -0
  128. package/dist/tests/validate-sdui-data-endpoints.test.d.ts.map +1 -0
  129. package/dist/tests/validate-sdui-data-endpoints.test.js +41 -0
  130. package/dist/tests/with-test-db.test.d.ts +2 -0
  131. package/dist/tests/with-test-db.test.d.ts.map +1 -0
  132. package/dist/tests/with-test-db.test.js +57 -0
  133. package/dist/types/index.d.ts.map +1 -1
  134. package/dist/utils.d.ts.map +1 -1
  135. package/dist/utils.js +3 -1
  136. package/dist/validate/index.d.ts +148 -0
  137. package/dist/validate/index.d.ts.map +1 -0
  138. package/dist/validate/index.js +887 -0
  139. package/dist/validate/migration-parse.d.ts +22 -0
  140. package/dist/validate/migration-parse.d.ts.map +1 -0
  141. package/dist/validate/migration-parse.js +11 -0
  142. package/dist/validate/shared-message-keys.d.ts +16 -0
  143. package/dist/validate/shared-message-keys.d.ts.map +1 -0
  144. package/dist/validate/shared-message-keys.js +227 -0
  145. package/package.json +56 -4
  146. package/dist/client/Auth.d.ts +0 -19
  147. package/dist/client/Auth.d.ts.map +0 -1
  148. package/dist/client/Auth.js +0 -45
  149. package/dist/client/QueryBuilder.d.ts +0 -17
  150. package/dist/client/QueryBuilder.d.ts.map +0 -1
  151. package/dist/client/QueryBuilder.js +0 -76
  152. package/dist/client/RealtimeClient.d.ts +0 -22
  153. package/dist/client/RealtimeClient.d.ts.map +0 -1
  154. package/dist/client/RealtimeClient.js +0 -96
  155. package/dist/client/ZveltioClient.d.ts +0 -20
  156. package/dist/client/ZveltioClient.d.ts.map +0 -1
  157. package/dist/client/ZveltioClient.js +0 -78
@@ -0,0 +1,320 @@
1
+ /**
2
+ * Postgres-backed integration test helper (S4-06 follow-up).
3
+ *
4
+ * `withTestDb(fn)` spins up a real Postgres container via `testcontainers`,
5
+ * yields a Kysely instance connected to it, runs the user's callback, then
6
+ * tears the container down. Use this when `mockDb` is insufficient — e.g.
7
+ * when an extension hook chains a real SELECT through `ctx.db`, or when you
8
+ * want to verify migrations apply cleanly.
9
+ *
10
+ * Requires:
11
+ * - Docker / Podman running on the test host.
12
+ * - `testcontainers` installed (peer dep — declare as devDep in the
13
+ * extension's package.json). We import it dynamically so unit-test
14
+ * workflows that never call `withTestDb` don't take the heavy hit.
15
+ *
16
+ * Cost model:
17
+ * - First call: ~3-5s (image pull + container start). Subsequent calls
18
+ * reuse the cached image, ~1-2s. Use one container across a `describe()`
19
+ * block when you can — the wrapper supports nesting via `reuse`.
20
+ *
21
+ * Why a peer dep + dynamic import:
22
+ * - `testcontainers` pulls `dockerode` + a bunch of Node-ish modules. We
23
+ * don't want every consumer of `@zveltio/sdk/testing` to inherit that
24
+ * weight just to use `mockDb`. By importing lazily, the cost is
25
+ * opt-in at the call site.
26
+ */
27
+ import { parseMigrationSql } from '../validate/migration-parse.js';
28
+ // ── Module-level reuse cache ────────────────────────────────────────────────
29
+ //
30
+ // When `reuse: true`, we keep a single container alive for the process
31
+ // lifetime. The first call to `withTestDb` boots it; subsequent calls open
32
+ // fresh DBs *inside* the same container (CREATE DATABASE per-call), so
33
+ // tests stay isolated without paying the container-start cost again.
34
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
35
+ let _sharedContainer = null;
36
+ async function loadPgContainer() {
37
+ try {
38
+ return await import('@testcontainers/postgresql');
39
+ }
40
+ catch {
41
+ throw new Error(`withTestDb requires the '@testcontainers/postgresql' npm package. ` +
42
+ `Install it as a devDep in your extension:\n` +
43
+ ` bun add -d @testcontainers/postgresql pg @types/pg`);
44
+ }
45
+ }
46
+ async function loadKysely() {
47
+ return await import('kysely');
48
+ }
49
+ /**
50
+ * Spin up Postgres, optionally run migrations, return a `TestDb` handle.
51
+ * The caller is responsible for calling `cleanup()` (typically inside an
52
+ * `afterAll`/`afterEach`).
53
+ *
54
+ * For the more common "scope the lifecycle to a test/describe block"
55
+ * pattern, prefer `withTestDb(fn)` below.
56
+ */
57
+ export async function startTestDb(opts = {}) {
58
+ const image = opts.image ?? 'pgvector/pgvector:pg18';
59
+ const database = opts.database ?? `zveltio_test_${Date.now()}_${Math.floor(Math.random() * 10_000)}`;
60
+ const startupTimeoutMs = opts.startupTimeoutMs ?? 60_000;
61
+ const tc = await loadPgContainer();
62
+ const { Kysely, PostgresDialect } = await loadKysely();
63
+ let host;
64
+ let port;
65
+ let username;
66
+ let password;
67
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
68
+ let createdContainer = null;
69
+ if (opts.reuse && _sharedContainer) {
70
+ host = _sharedContainer.getHost();
71
+ port = _sharedContainer.getMappedPort(5432);
72
+ username = _sharedContainer.getUsername();
73
+ password = _sharedContainer.getPassword();
74
+ }
75
+ else {
76
+ const builder = new tc.PostgreSqlContainer(image).withStartupTimeout(startupTimeoutMs);
77
+ createdContainer = await builder.start();
78
+ if (opts.reuse)
79
+ _sharedContainer = createdContainer;
80
+ host = createdContainer.getHost();
81
+ port = createdContainer.getMappedPort(5432);
82
+ username = createdContainer.getUsername();
83
+ password = createdContainer.getPassword();
84
+ }
85
+ // testcontainers' default db is `test`. Create our own so multiple
86
+ // reuse=true calls don't share state.
87
+ const adminConnStr = `postgres://${username}:${password}@${host}:${port}/postgres`;
88
+ const adminPool = await openPgPool(adminConnStr);
89
+ try {
90
+ await adminPool.query(`CREATE DATABASE "${database}"`);
91
+ }
92
+ finally {
93
+ await adminPool.end();
94
+ }
95
+ const connectionString = `postgres://${username}:${password}@${host}:${port}/${database}`;
96
+ const pool = await openPgPool(connectionString);
97
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
98
+ const db = new Kysely({
99
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
100
+ dialect: new PostgresDialect({ pool: pool }),
101
+ });
102
+ if (opts.migrations && opts.migrations.length > 0) {
103
+ await applyMigrationStrings(db, opts.migrations);
104
+ }
105
+ return {
106
+ db,
107
+ connectionString,
108
+ async cleanup() {
109
+ try {
110
+ await db.destroy();
111
+ }
112
+ catch {
113
+ /* */
114
+ }
115
+ try {
116
+ await pool.end();
117
+ }
118
+ catch {
119
+ /* */
120
+ }
121
+ if (createdContainer && !opts.reuse) {
122
+ try {
123
+ await createdContainer.stop();
124
+ }
125
+ catch {
126
+ /* */
127
+ }
128
+ }
129
+ },
130
+ };
131
+ }
132
+ /**
133
+ * Convenience wrapper: starts a TestDb, runs `fn`, always cleans up. The
134
+ * 95% case for integration tests. Returns whatever `fn` returns.
135
+ *
136
+ * @example
137
+ * import { withTestDb } from '@zveltio/sdk/testing';
138
+ * import myExtension from '../engine';
139
+ *
140
+ * test('extension creates contact rows', async () => {
141
+ * await withTestDb(async (db) => {
142
+ * await db.schema.createTable('zvd_contacts').addColumn(...).execute();
143
+ * const ctx = createTestContext({ db });
144
+ * const app = await createTestApp(myExtension, { ctx });
145
+ * const res = await app.request('/ext/my/contacts', { method: 'POST', ... });
146
+ * expect(res.status).toBe(201);
147
+ * const rows = await db.selectFrom('zvd_contacts').selectAll().execute();
148
+ * expect(rows).toHaveLength(1);
149
+ * });
150
+ * });
151
+ */
152
+ export async function withTestDb(
153
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
154
+ fnOrOpts,
155
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
156
+ maybeFn) {
157
+ const opts = typeof fnOrOpts === 'function' ? {} : fnOrOpts;
158
+ const fn = typeof fnOrOpts === 'function' ? fnOrOpts : maybeFn;
159
+ if (typeof fn !== 'function') {
160
+ throw new Error('withTestDb: callback is required');
161
+ }
162
+ const handle = await startTestDb(opts);
163
+ try {
164
+ return await fn(handle.db);
165
+ }
166
+ finally {
167
+ await handle.cleanup();
168
+ }
169
+ }
170
+ /**
171
+ * Apply an ordered list of SQL strings against the db. Each entry runs in
172
+ * its own statement; semicolons in the source string split into multiple
173
+ * statements. Useful for replaying engine + extension migrations against
174
+ * the test db.
175
+ *
176
+ * @example
177
+ * import { readFileSync } from 'fs';
178
+ * import { sync as glob } from 'glob';
179
+ * const files = glob('engine/migrations/*.sql').map((p) => readFileSync(p, 'utf8'));
180
+ * await applyMigrationStrings(db, files);
181
+ */
182
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
183
+ export async function applyMigrationStrings(db, sqlStrings) {
184
+ const { sql } = await loadKysely();
185
+ for (const raw of sqlStrings) {
186
+ // Only the UP half. A Zveltio migration keeps its rollback in the same file
187
+ // behind a `-- DOWN` marker, and the runner that applies it in production
188
+ // splits on that marker — this helper did not, so the documented example
189
+ // (glob `engine/migrations/*.sql`, hand them all to this function) created
190
+ // the schema and then dropped it again, in the same call. Every assertion
191
+ // after it failed on a table that had existed a statement earlier.
192
+ const statements = splitStatements(parseMigrationSql(raw).up);
193
+ for (const stmt of statements) {
194
+ const trimmed = stmt.trim();
195
+ if (!trimmed)
196
+ continue;
197
+ await sql.raw(trimmed).execute(db);
198
+ }
199
+ }
200
+ }
201
+ /**
202
+ * Same as `applyMigrationStrings` but takes file paths. Reads each file
203
+ * synchronously, applies in order. Bun-native — uses `Bun.file()`.
204
+ */
205
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
206
+ export async function applyMigrationFiles(db, paths) {
207
+ // Bun.file().text() returns a Promise<string>.
208
+ const contents = await Promise.all(paths.map((p) => Bun.file(p).text()));
209
+ return applyMigrationStrings(db, contents);
210
+ }
211
+ /**
212
+ * Stop any reuse-cached container. Call this from a `globalTeardown` /
213
+ * `afterAll` so test runs don't leave dangling containers. No-op when no
214
+ * reuse container is active.
215
+ */
216
+ export async function stopReusedTestDb() {
217
+ if (_sharedContainer) {
218
+ try {
219
+ await _sharedContainer.stop();
220
+ }
221
+ catch {
222
+ /* */
223
+ }
224
+ _sharedContainer = null;
225
+ }
226
+ }
227
+ // ── Internals ───────────────────────────────────────────────────────────────
228
+ /** Open a pg connection pool. Uses `pg` (peer dep with testcontainers). */
229
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
230
+ async function openPgPool(connectionString) {
231
+ const pg = await import('pg').catch(() => {
232
+ throw new Error(`withTestDb requires the 'pg' npm package. Install it alongside testcontainers:\n` +
233
+ ` bun add -d testcontainers pg @types/pg`);
234
+ });
235
+ // pg's Pool — the Kysely PostgresDialect accepts this directly.
236
+ // biome-ignore lint/suspicious/noExplicitAny: legacy any; tracked in hardening plan item H-01
237
+ return new pg.Pool({ connectionString });
238
+ }
239
+ /**
240
+ * Naive SQL statement splitter: splits on `;` outside of single-quoted
241
+ * strings and dollar-quoted blocks (`$$...$$`). Handles the migration-file
242
+ * styles Zveltio ships; not a full SQL parser.
243
+ *
244
+ * Public so tests can pin its behavior. Not part of the documented surface.
245
+ */
246
+ export function splitStatements(src) {
247
+ const out = [];
248
+ let buf = '';
249
+ let i = 0;
250
+ while (i < src.length) {
251
+ const ch = src[i];
252
+ // Comments: -- to end of line
253
+ if (ch === '-' && src[i + 1] === '-') {
254
+ while (i < src.length && src[i] !== '\n') {
255
+ buf += src[i++];
256
+ }
257
+ continue;
258
+ }
259
+ // Block comments: /* ... */
260
+ if (ch === '/' && src[i + 1] === '*') {
261
+ buf += src[i++];
262
+ buf += src[i++];
263
+ while (i < src.length && !(src[i] === '*' && src[i + 1] === '/')) {
264
+ buf += src[i++];
265
+ }
266
+ if (i < src.length) {
267
+ buf += src[i++];
268
+ buf += src[i++];
269
+ }
270
+ continue;
271
+ }
272
+ // Single-quoted strings: handle escaped quotes.
273
+ if (ch === "'") {
274
+ buf += src[i++];
275
+ while (i < src.length) {
276
+ if (src[i] === "'" && src[i + 1] === "'") {
277
+ buf += src[i++];
278
+ buf += src[i++];
279
+ continue;
280
+ }
281
+ if (src[i] === "'") {
282
+ buf += src[i++];
283
+ break;
284
+ }
285
+ buf += src[i++];
286
+ }
287
+ continue;
288
+ }
289
+ // Dollar-quoted blocks: $$ ... $$ or $tag$ ... $tag$.
290
+ if (ch === '$') {
291
+ const tagMatch = src.slice(i).match(/^\$[a-zA-Z0-9_]*\$/);
292
+ if (tagMatch) {
293
+ const tag = tagMatch[0];
294
+ buf += tag;
295
+ i += tag.length;
296
+ const endIdx = src.indexOf(tag, i);
297
+ if (endIdx < 0) {
298
+ buf += src.slice(i);
299
+ i = src.length;
300
+ break;
301
+ }
302
+ buf += src.slice(i, endIdx + tag.length);
303
+ i = endIdx + tag.length;
304
+ continue;
305
+ }
306
+ }
307
+ if (ch === ';') {
308
+ out.push(buf);
309
+ buf = '';
310
+ i++;
311
+ continue;
312
+ }
313
+ buf += src[i++];
314
+ }
315
+ if (buf.trim())
316
+ out.push(buf);
317
+ return out;
318
+ }
319
+ // ── Internal helpers for tests only ────────────────────────────────────────
320
+ export const _internalForTests = { splitStatements };
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=action-refusal.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"action-refusal.test.d.ts","sourceRoot":"","sources":["../../src/tests/action-refusal.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,13 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { ACTION_REFUSAL, ActionRefusal } from '../extension/action-refusal.js';
3
+ // extension-api v1: the engine recognises a refusal by this registered key,
4
+ // not by `instanceof` (each extension bundles its own SDK copy). Changing the
5
+ // key silently turns every v1 extension's refusal into a 500.
6
+ describe('ActionRefusal (extension-api v1)', () => {
7
+ it('marks itself with the registered key the engine reads', () => {
8
+ expect(ACTION_REFUSAL).toBe(Symbol.for('zveltio.extension.action-refusal'));
9
+ const r = new ActionRefusal(409, 'already_paid', 'Invoice already paid');
10
+ expect(r[ACTION_REFUSAL]).toBe(true);
11
+ expect([r.status, r.code, r.message]).toEqual([409, 'already_paid', 'Invoice already paid']);
12
+ });
13
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=client.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.test.d.ts","sourceRoot":"","sources":["../../src/tests/client.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,164 @@
1
+ import { describe, it, expect, afterEach } from 'bun:test';
2
+ import { createZveltioClient } from '../client.js';
3
+ const realFetch = globalThis.fetch;
4
+ afterEach(() => {
5
+ globalThis.fetch = realFetch;
6
+ });
7
+ /** Records the URL each call is given and answers `{}` without a network hop. */
8
+ function captureUrls() {
9
+ const urls = [];
10
+ globalThis.fetch = (async (input) => {
11
+ urls.push(String(input));
12
+ return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });
13
+ });
14
+ return urls;
15
+ }
16
+ describe('ZveltioClient URL building', () => {
17
+ it('encodes a record id into a single path segment', async () => {
18
+ const urls = captureUrls();
19
+ const client = createZveltioClient({ baseUrl: 'https://engine.test' });
20
+ const products = client.collection('products');
21
+ await products.get('a/b');
22
+ await products.update('a/b', { name: 'x' });
23
+ await products.delete('a/b');
24
+ expect(urls).toEqual([
25
+ 'https://engine.test/api/data/products/a%2Fb',
26
+ 'https://engine.test/api/data/products/a%2Fb',
27
+ 'https://engine.test/api/data/products/a%2Fb',
28
+ ]);
29
+ });
30
+ it('asks the engine who its key is at the route that answers it', async () => {
31
+ const urls = captureUrls();
32
+ const client = createZveltioClient({ baseUrl: 'https://engine.test', apiKey: 'zvk_x' });
33
+ await client.auth.apiKey();
34
+ expect(urls).toEqual(['https://engine.test/api/api-keys/self']);
35
+ });
36
+ it("reaches the member's own keys at /api/me/api-keys", async () => {
37
+ const urls = captureUrls();
38
+ const client = createZveltioClient({ baseUrl: 'https://engine.test' });
39
+ await client.auth.apiKeys.list();
40
+ await client.auth.apiKeys.revoke('a/b');
41
+ expect(urls).toEqual([
42
+ 'https://engine.test/api/me/api-keys',
43
+ 'https://engine.test/api/me/api-keys/a%2Fb',
44
+ ]);
45
+ });
46
+ it('encodes the storage folder into the query string', async () => {
47
+ const urls = captureUrls();
48
+ const client = createZveltioClient({ baseUrl: 'https://engine.test' });
49
+ await client.storage.list('invoices&limit=9999');
50
+ expect(urls).toEqual(['https://engine.test/api/storage?folder_id=invoices%26limit%3D9999']);
51
+ });
52
+ it('sends the upload folder under the field name the engine reads', async () => {
53
+ let body;
54
+ globalThis.fetch = (async (_input, init) => {
55
+ body = init?.body;
56
+ return new Response('{}', { status: 200, headers: { 'content-type': 'application/json' } });
57
+ });
58
+ const client = createZveltioClient({ baseUrl: 'https://engine.test' });
59
+ await client.storage.upload(new File(['x'], 'a.txt'), 'folder-uuid');
60
+ expect(body?.get('folder_id')).toBe('folder-uuid');
61
+ expect(body?.has('folder')).toBe(false);
62
+ });
63
+ it('leaves an ordinary id and collection name untouched', async () => {
64
+ const urls = captureUrls();
65
+ const client = createZveltioClient({ baseUrl: 'https://engine.test/' });
66
+ await client.collection('order_items').get('018f2a1e-0000-7000-8000-000000000000');
67
+ expect(urls).toEqual([
68
+ 'https://engine.test/api/data/order_items/018f2a1e-0000-7000-8000-000000000000',
69
+ ]);
70
+ });
71
+ });
72
+ describe('ZveltioClient session token (bearer mode)', () => {
73
+ function engine(issue) {
74
+ const sent = [];
75
+ globalThis.fetch = (async (_input, init) => {
76
+ sent.push({
77
+ auth: new Headers(init?.headers).get('Authorization'),
78
+ credentials: init?.credentials,
79
+ });
80
+ const headers = { 'content-type': 'application/json' };
81
+ if (issue)
82
+ headers['set-auth-token'] = issue;
83
+ return new Response('{}', { status: 200, headers });
84
+ });
85
+ return sent;
86
+ }
87
+ it('captures the token at sign-in, sends it as a bearer, and forgets it on logout', async () => {
88
+ const seen = [];
89
+ const sent = engine('tok.sig');
90
+ const client = createZveltioClient({
91
+ baseUrl: 'https://engine.test',
92
+ onSessionToken: (t) => seen.push(t),
93
+ });
94
+ await client.auth.login('a@b.c', 'pw');
95
+ const next = engine(null);
96
+ await client.collection('products').list();
97
+ await client.auth.logout();
98
+ await client.collection('products').list();
99
+ expect(sent[0]).toEqual({ auth: null, credentials: 'omit' });
100
+ expect(next.map((s) => s.auth)).toEqual(['Bearer tok.sig', 'Bearer tok.sig', null]);
101
+ expect(seen).toEqual(['tok.sig', null]);
102
+ expect(client.getSessionToken()).toBeNull();
103
+ });
104
+ it('a browser client keeps cookies and ignores an issued token', async () => {
105
+ const sent = engine('tok.sig');
106
+ const client = createZveltioClient({ baseUrl: 'https://engine.test' });
107
+ await client.auth.login('a@b.c', 'pw');
108
+ await client.collection('products').list();
109
+ expect(sent.map((s) => [s.auth, s.credentials])).toEqual([
110
+ [null, 'include'],
111
+ [null, 'include'],
112
+ ]);
113
+ });
114
+ });
115
+ describe('ZveltioClient step-up', () => {
116
+ function engine() {
117
+ const sent = [];
118
+ globalThis.fetch = (async (_input, init) => {
119
+ const token = new Headers(init?.headers).get('X-Zveltio-Step-Up');
120
+ sent.push(token);
121
+ if (token === 'su-1')
122
+ return new Response('{"ok":true}', { status: 200 });
123
+ return new Response(JSON.stringify({
124
+ type: 'about:blank',
125
+ title: 'Forbidden',
126
+ status: 403,
127
+ code: 'step_up_required',
128
+ errors: { action: 'config' },
129
+ }), { status: 403, headers: { 'content-type': 'application/problem+json' } });
130
+ });
131
+ return sent;
132
+ }
133
+ it('asks for a step-up on 403 step_up_required and sends once more with the token', async () => {
134
+ const sent = engine();
135
+ const asked = [];
136
+ const client = createZveltioClient({
137
+ baseUrl: 'https://engine.test',
138
+ onStepUpRequired: async (action) => {
139
+ asked.push(action);
140
+ return 'su-1';
141
+ },
142
+ });
143
+ expect(await client.post('/api/collections', { name: 'x' })).toEqual({
144
+ ok: true,
145
+ });
146
+ expect(asked).toEqual(['config']);
147
+ expect(sent).toEqual([null, 'su-1']);
148
+ });
149
+ it('throws the 403 when the hook gives up, and without a hook', async () => {
150
+ const sent = engine();
151
+ const giveUp = createZveltioClient({
152
+ baseUrl: 'https://engine.test',
153
+ onStepUpRequired: async () => null,
154
+ });
155
+ await expect(giveUp.post('/api/collections', {})).rejects.toMatchObject({
156
+ code: 'step_up_required',
157
+ });
158
+ const plain = createZveltioClient({ baseUrl: 'https://engine.test' });
159
+ await expect(plain.post('/api/collections', {})).rejects.toMatchObject({
160
+ code: 'step_up_required',
161
+ });
162
+ expect(sent).toEqual([null, null]);
163
+ });
164
+ });
@@ -0,0 +1,2 @@
1
+ import './setup';
2
+ //# sourceMappingURL=crdt-orset.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"crdt-orset.test.d.ts","sourceRoot":"","sources":["../../src/tests/crdt-orset.test.ts"],"names":[],"mappings":"AAAA,OAAO,SAAS,CAAC"}
@@ -0,0 +1,23 @@
1
+ import './setup';
2
+ import { describe, it, expect } from 'bun:test';
3
+ import { orSetAdd, orSetRemove, orSetMerge, orSetValues } from '../crdt.js';
4
+ describe('OR-Set — removal survives a merge with a stale replica', () => {
5
+ it('does not resurrect an element that one replica removed', () => {
6
+ const added = orSetAdd([], 'x');
7
+ const uid = added[0].uid;
8
+ const stale = [...added]; // a replica that never saw the removal
9
+ const removed = orSetRemove(added, uid);
10
+ const first = orSetMerge(removed, stale);
11
+ expect(orSetValues(first)).toEqual([]);
12
+ // The stale replica syncs again. Without its tombstone the merged set has
13
+ // no record of the removal, so the element reads as a fresh addition.
14
+ const second = orSetMerge(first, stale);
15
+ expect(orSetValues(second), 'the removed element came back').toEqual([]);
16
+ });
17
+ it('an element added after a removal is kept', () => {
18
+ const first = orSetAdd([], 'x');
19
+ const removed = orSetRemove(first, first[0].uid);
20
+ const readded = orSetAdd(removed, 'x');
21
+ expect(orSetValues(orSetMerge(readded, removed))).toEqual(['x']);
22
+ });
23
+ });
@@ -74,3 +74,47 @@ describe('LocalStore — conflict detection', () => {
74
74
  expect(rec?._conflictData).toBeUndefined();
75
75
  });
76
76
  });
77
+ describe('LocalStore — what the SyncManager actually passes', () => {
78
+ let store;
79
+ beforeEach(async () => {
80
+ store = new LocalStore();
81
+ await store.open();
82
+ await store.clear();
83
+ });
84
+ afterEach(async () => {
85
+ await store.close();
86
+ });
87
+ it('flags a conflict when the confirmed server version is an epoch timestamp', async () => {
88
+ // `syncNow()` and `pull()` both pass `Date.now()` as the server version —
89
+ // the collections API returns no version column. From the first ACK on,
90
+ // `_serverVersion` is ~1.79e12 and `_localVersion` is still a small counter,
91
+ // so the version comparison alone can never be true again and every local
92
+ // edit was overwritten in silence.
93
+ await store.put('posts', 'rec-ts', { title: 'v1' });
94
+ const [op] = await store.getPendingOps();
95
+ await store.markSynced(op.id, 'posts', 'rec-ts', Date.now());
96
+ await store.put('posts', 'rec-ts', { title: 'local edit' });
97
+ await store.applyServerUpdate('posts', 'rec-ts', { title: 'server wins' }, Date.now());
98
+ const after = await store.get('posts', 'rec-ts');
99
+ expect(after?._syncStatus).toBe('conflict');
100
+ expect(after?.data).toEqual({ title: 'local edit' });
101
+ expect(after?._conflictData).toEqual({ title: 'server wins' });
102
+ });
103
+ it('queues the resolved row, so a resolution reaches the server', async () => {
104
+ await store.applyServerUpdate('posts', 'rec-res', { title: 'server' }, Date.now());
105
+ await store.resolveConflict('posts', 'rec-res', { title: 'resolved' });
106
+ const ops = await store.getPendingOps();
107
+ const mine = ops.filter((o) => o.recordId === 'rec-res');
108
+ expect(mine, 'the resolution was never queued').toHaveLength(1);
109
+ expect(mine[0].payload).toEqual({ title: 'resolved' });
110
+ expect(mine[0].operation).toBe('update');
111
+ });
112
+ it('keeps the CRDT document across a clean server update', async () => {
113
+ await store.put('posts', 'rec-crdt', { title: 'local' });
114
+ const [op] = await store.getPendingOps();
115
+ await store.markSynced(op.id, 'posts', 'rec-crdt', Date.now());
116
+ await store.applyServerUpdate('posts', 'rec-crdt', { title: 'server' }, Date.now());
117
+ const after = await store.get('posts', 'rec-crdt');
118
+ expect(after?._crdtDoc, 'the CRDT document was dropped, so no later merge can run').toBeDefined();
119
+ });
120
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=migration-parse.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migration-parse.test.d.ts","sourceRoot":"","sources":["../../src/tests/migration-parse.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,17 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { parseMigrationSql } from '../validate/migration-parse.js';
3
+ describe('parseMigrationSql', () => {
4
+ it('splits on a line that is exactly -- DOWN', () => {
5
+ expect(parseMigrationSql('CREATE TABLE a (id int);\n-- DOWN\nDROP TABLE a;')).toEqual({
6
+ up: 'CREATE TABLE a (id int);',
7
+ down: 'DROP TABLE a;',
8
+ });
9
+ });
10
+ it('does not end UP at a comment that only starts with -- DOWN', () => {
11
+ const raw = 'CREATE TABLE a (id int);\n-- DOWN: manual rollback required\nCREATE TABLE b (id int);';
12
+ expect(parseMigrationSql(raw)).toEqual({ up: raw, down: null });
13
+ });
14
+ it('accepts case and trailing spaces, like the engine', () => {
15
+ expect(parseMigrationSql('SELECT 1;\n-- down \nSELECT 2;').down).toBe('SELECT 2;');
16
+ });
17
+ });
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=multipart.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"multipart.test.d.ts","sourceRoot":"","sources":["../../src/tests/multipart.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,37 @@
1
+ import { describe, expect, it } from 'bun:test';
2
+ import { MULTIPART_REQUIRED, readMultipart } from '../extension/multipart.js';
3
+ /**
4
+ * Six upload handlers opened with a bare `await c.req.formData()` and put their
5
+ * "no file provided" 400 on the line after it. `formData()` throws when the body
6
+ * is not multipart, so that 400 was unreachable for exactly the requests it was
7
+ * written for, and they came back as a bare 500 instead.
8
+ *
9
+ * Both directions are asserted here. A guard that rejects everything would also
10
+ * make the suite green, and would break every upload in the product.
11
+ */
12
+ const ctxWith = (body, headers = {}) => {
13
+ const req = new Request('http://x/upload', { method: 'POST', body, headers });
14
+ return { req: { formData: () => req.formData() } };
15
+ };
16
+ describe('readMultipart', () => {
17
+ it('parses a real multipart body, fields and files alike', async () => {
18
+ const fd = new FormData();
19
+ fd.append('file', new File(['salut'], 'a.txt', { type: 'text/plain' }));
20
+ fd.append('path', '/docs');
21
+ const form = await readMultipart(ctxWith(fd));
22
+ expect(form).not.toBeNull();
23
+ expect(form?.get('file')?.name).toBe('a.txt');
24
+ expect(form?.get('path')).toBe('/docs');
25
+ });
26
+ it('answers null for every body shape that used to throw', async () => {
27
+ expect(await readMultipart(ctxWith('{}', { 'content-type': 'application/json' }))).toBeNull();
28
+ expect(await readMultipart(ctxWith(null))).toBeNull();
29
+ expect(await readMultipart(ctxWith('salut', { 'content-type': 'text/plain' }))).toBeNull();
30
+ });
31
+ it('does not leak the parser own message to the caller', async () => {
32
+ // The body parser's error reads like "FormData parse error" — nothing a
33
+ // caller can act on, and echoing a parser's internals over HTTP is how
34
+ // request contents end up in error strings.
35
+ expect(MULTIPART_REQUIRED).toEqual({ error: 'Expected a multipart/form-data body.' });
36
+ });
37
+ });