@solobrand/testing 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.
package/README.md CHANGED
@@ -1,3 +1,152 @@
1
- # Temporary Holding Version
1
+ # @solobrand/testing
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Tests on the real Workers runtime: factories, per-test D1, actingAs.
4
+
5
+ Part of the [SoloBrand framework](../../README.md). Public API: `src/index.ts` (frozen types, see CONTRIBUTING.md).
6
+
7
+ ```ts
8
+ import { createTestApp, defineFactory, assertStatus, assertJsonPath, assertValidationError, assertDatabaseHas } from '@solobrand/testing';
9
+ import { kernel } from '../src/kernel';
10
+ import { migrations } from '../database/migrations';
11
+
12
+ const users = defineFactory('users', (n) => ({ email: `user${n}@example.test`, name: `User ${n}` }));
13
+
14
+ it('creates a post', async () => {
15
+ const t = await createTestApp({ kernel, migrations }); // fresh D1, migrations applied
16
+ const ana = await users.create(t.db);
17
+
18
+ const res = await t.actingAs(ana).request('/api/posts', { json: { title: 'Hola' } });
19
+ await assertStatus(res, 201);
20
+ await assertJsonPath(res, 'data.title', 'Hola');
21
+ await assertDatabaseHas(t.db, 'posts', { title: 'Hola', user_id: ana.id });
22
+
23
+ await assertStatus(await t.anotherClient().request(`/api/posts/${ana.id}`), 401); // another browser
24
+ await assertValidationError(await t.request('/api/posts', { json: {} }), 'title');
25
+ });
26
+ ```
27
+
28
+ ## The client
29
+
30
+ `createTestApp({ kernel, migrations, env? })` builds a fresh app per call:
31
+
32
+ - **D1** — a fresh in-memory SQLite (`better-sqlite3`, Node only, loaded lazily) behind the
33
+ `D1Database` interface, with D1's behaviour where a test can tell: foreign keys on,
34
+ booleans bound as 0/1, `undefined` refused, `batch()` all or nothing, errors prefixed
35
+ `D1_ERROR:`. Pass `env: { DB }` to use another D1 instead (see vitest-pool-workers below).
36
+ `t.db` is `createDatabase(d1)` from `@solobrand/db`; the migrations run through
37
+ `createMigrator(db, migrations).migrate()`.
38
+ - **env** — `{ SOLOBRAND_TESTING: '1', SOLOBRAND_TEST_KEY: <random>, ...options.env, DB }`.
39
+ Your values win, so `env: { SOLOBRAND_TESTING: '0' }` runs the app as production would.
40
+ - **`request(path, init)`** — goes straight through `kernel.fetch` on `https://app.test`.
41
+ `json: value` serializes the body, sets `content-type`, and makes the method POST unless
42
+ you give one. `accept: application/json` by default. Cookies (`Set-Cookie`) persist
43
+ between calls (path, `Max-Age`, `Expires` honoured). `ctx.waitUntil` work is awaited
44
+ before `request()` resolves, so its side effects are visible to the next assertion. The
45
+ response body can be read any number of times.
46
+ - **CSRF, like the React kit** — the client picks up the token ONLY from the `X-CSRF-Token`
47
+ response header (login and `GET /auth/csrf` send it); on POST/PUT/PATCH/DELETE it sends it
48
+ back in `X-CSRF-Token` with `Origin` and `Sec-Fetch-Site: same-origin`. A header you pass
49
+ yourself wins (send a forged one to test the 419).
50
+ - **`actingAs(user, { via?, scopes? })`** — mutates this client and returns it. Session
51
+ principal by default (`scopes: '*'`); `via: 'token'` carries the given scopes (default
52
+ none). `emailVerifiedAt` is "now" unless the user object has `emailVerifiedAt` or
53
+ `email_verified_at` (pass `null` to test `verified`).
54
+ - **`anotherClient()`** — another browser: same app and db, empty cookie jar, no principal.
55
+ - **`app`** — return `{ kernel, app }` from your kernel factory and `t.app` is the kernel's
56
+ own application, booted before `createTestApp` resolves. With a bare `Kernel`, it is a
57
+ separate `Application` over the same env with `t.db` bound, built on first use.
58
+
59
+ ### The actingAs hook (security)
60
+
61
+ `actingAs` does not forge cookies: it sends two headers, and the app's guard honours them
62
+ **only** when the app runs with `env.SOLOBRAND_TESTING === '1'` (exactly the string) **and**
63
+ `env.SOLOBRAND_TEST_KEY` is ≥ 32 chars and equals the key header (constant-time compare).
64
+
65
+ ```
66
+ X-SoloBrand-Test-Principal: base64url(JSON Principal)
67
+ X-SoloBrand-Test-Key: the app's SOLOBRAND_TEST_KEY
68
+ ```
69
+
70
+ `createTestApp` generates a fresh key per app; deploys never set these vars, so in
71
+ production the headers are inert. The reader is `readTestPrincipal(request, env)` from
72
+ `@solobrand/http` (re-exported by `@solobrand/testing` and `@solobrand/testing/hook`) — a
73
+ guard calls it first and falls back to its real credential check on `null`.
74
+ `testPrincipalMiddleware` does the same as a global middleware. The writer (the headers
75
+ `actingAs` sends) is this package's client. Tests prove the hook is ignored with the flag missing / `'0'` /
76
+ `'true'` / `1`, without a key, with a short or wrong key, and with a malformed principal.
77
+
78
+ ## Factories
79
+
80
+ ```ts
81
+ const posts = defineFactory('posts', (n) => ({ title: `Post ${n}`, user_id: 1 }));
82
+ posts.make({ title: 'x' }); // a row, not inserted
83
+ await posts.create(db, { user_id: 2 }); // inserted (values bound), returns { ...row, id }
84
+ await posts.count(3).createMany(db); // all three rows with their ids
85
+ posts.count(3).makeMany(); // three rows, not inserted
86
+ ```
87
+
88
+ The sequence starts at 1 and never repeats within a factory (`count()` views share it).
89
+ `factory.count(n).create(db)` inserts n rows and resolves to the last; `createMany` /
90
+ `makeMany` return all of them (also exported as functions `createMany(factory, db)`). Table and column names
91
+ are validated as identifiers; values are always bound.
92
+
93
+ ## Assertions
94
+
95
+ `assertStatus` is synchronous; the rest are async (they read the body or the db). They throw `TestAssertionError` with the
96
+ body or the table's first rows in the message:
97
+
98
+ | | |
99
+ |---|---|
100
+ | `assertStatus(res, 201)` | |
101
+ | `assertJsonPath(res, 'data.items.0.id', 3)` | deep equality, or a predicate `(v) => boolean`; returns the value |
102
+ | `assertValidationError(res, 'email', key?)` | 422 with `errors.email` non-empty (and containing `key`) |
103
+ | `assertNoValidationError(res, 'email')` | |
104
+ | `assertDatabaseHas(db, 'posts', { title: 'Hola', deleted_at: null })` | `null` matches `IS NULL`; booleans as 0/1 |
105
+ | `assertDatabaseMissing(db, table, where)` / `assertDatabaseCount(db, table, n, where?)` | |
106
+
107
+ ## On @cloudflare/vitest-pool-workers
108
+
109
+ better-sqlite3 is native and does not load in workerd. On the Workers pool, give
110
+ `createTestApp` the pool's D1 — with `isolatedStorage: true` every test gets its own copy,
111
+ which is the "fresh D1 per test":
112
+
113
+ ```ts
114
+ // vitest.config.ts
115
+ import { defineWorkersConfig } from '@cloudflare/vitest-pool-workers/config';
116
+ export default defineWorkersConfig({
117
+ test: { poolOptions: { workers: { isolatedStorage: true, wrangler: { configPath: './wrangler.jsonc' } } } },
118
+ });
119
+
120
+ // a test
121
+ import { env } from 'cloudflare:test';
122
+ const t = await createTestApp({ kernel, migrations, env: { DB: env.DB } });
123
+ ```
124
+
125
+ The SQLite adapter is only imported (dynamically) when no `env.DB` is given; if your
126
+ bundler still tries to resolve it, alias `better-sqlite3` to an empty module in the
127
+ Workers config. Do not set `SOLOBRAND_TESTING` in `wrangler` vars of a deployed env.
128
+
129
+ ## Status
130
+
131
+ - **Implemented**: `createTestApp` (fresh SQLite D1 or given `env.DB`, migrations, env flags,
132
+ kernel factory returning `Kernel` or `{ kernel, app }`, cookie-jar client, `json` sugar,
133
+ CSRF from the `X-CSRF-Token` response header only, `waitUntil` awaited, re-readable
134
+ bodies), `actingAs` (session/token, scopes, verified state) writing the keyed test-hook
135
+ headers, `anotherClient`, `defineFactory` with sequences and `makeMany`/`createMany`, the
136
+ assertions, `SqliteD1Database` (`@solobrand/testing/sqlite-d1`). The hook READER is
137
+ `@solobrand/http`'s `readTestPrincipal`, re-exported (no copy of its own).
138
+ - **Tested**: unit tests against fakes of the db contract and of `createApplication` (D1
139
+ adapter, the re-exported reader's refusal paths, client, factories incl. injection
140
+ attempts, assertions, cookie jar) and **end to end against the real core/http/db/auth**
141
+ (`test/e2e.test.ts`): register → login (CSRF header) → `/auth/me` → protected route →
142
+ forged CSRF 419 → another client 401 → logout; validation envelope; `actingAs` session and
143
+ token read by the **real guards alone** (no extra middleware; F3 wired the reader under
144
+ `testHookAllowed`, SEC-013) and also with `testPrincipalMiddleware` in `global`; the real
145
+ guards ignore `actingAs` when `SOLOBRAND_TESTING` is not `'1'`;
146
+ `t.app` is the kernel's app. `npm run coverage` green (testing: 89–100 % lines per file).
147
+ - **Left (owner named)**:
148
+ - **F5 template**: nothing needed for `actingAs` any more (the guards read the hook);
149
+ returning `{ kernel, app }` from `app/kernel.ts` would give tests the real app.
150
+ - Running this package's own suite on vitest-pool-workers is not done.
151
+
152
+ TERMINADO 2026-11-28
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Laravel-like assertions. They throw an Error with the response body (or the
3
+ * table's rows) in the message, so a failing test says why.
4
+ *
5
+ * assertStatus(res, 201);
6
+ * await assertJsonPath(res, 'data.title', 'Hola');
7
+ * await assertValidationError(res, 'email');
8
+ * await assertDatabaseHas(db, 'posts', { title: 'Hola' });
9
+ */
10
+ import type { Database } from '@solobrand/db';
11
+ import type { TestResponse } from './index.js';
12
+ export declare class TestAssertionError extends Error {
13
+ readonly name = "TestAssertionError";
14
+ }
15
+ /** Synchronous (the status is known): `assertStatus(res, 200)` needs no await, though awaiting it is harmless. */
16
+ export declare function assertStatus(response: TestResponse, expected: number): void;
17
+ /** Reads `a.b.0.c` from a value; `undefined` when a step is missing. */
18
+ export declare function jsonPath(value: unknown, path: string): unknown;
19
+ /**
20
+ * `expected` may be a value (deep equality) or a predicate. Returns the value
21
+ * found, so a test can keep using it.
22
+ */
23
+ export declare function assertJsonPath(response: TestResponse, path: string, expected: unknown): Promise<unknown>;
24
+ /**
25
+ * 422 with `errors[field]` present (envelope `{ errors: { field: [keys] } }`).
26
+ * With `messageKey`, that key must be among the field's messages.
27
+ */
28
+ export declare function assertValidationError(response: TestResponse, field: string, messageKey?: string): Promise<void>;
29
+ /** The response has no error for `field` (it may still be another 422). */
30
+ export declare function assertNoValidationError(response: TestResponse, field: string): Promise<void>;
31
+ export declare function assertDatabaseHas(db: Database, table: string, conditions: Readonly<Record<string, unknown>>): Promise<void>;
32
+ export declare function assertDatabaseMissing(db: Database, table: string, conditions: Readonly<Record<string, unknown>>): Promise<void>;
33
+ export declare function assertDatabaseCount(db: Database, table: string, expected: number, conditions?: Readonly<Record<string, unknown>>): Promise<void>;
34
+ //# sourceMappingURL=assertions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assertions.d.ts","sourceRoot":"","sources":["../src/assertions.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAI/C,qBAAa,kBAAmB,SAAQ,KAAK;IAC3C,SAAkB,IAAI,wBAAwB;CAC/C;AAWD,kHAAkH;AAClH,wBAAgB,YAAY,CAAC,QAAQ,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI,CAK3E;AAED,wEAAwE;AACxE,wBAAgB,QAAQ,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAa9D;AAYD;;;GAGG;AACH,wBAAsB,cAAc,CAAC,QAAQ,EAAE,YAAY,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAQ9G;AAED;;;GAGG;AACH,wBAAsB,qBAAqB,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAYrH;AAED,2EAA2E;AAC3E,wBAAsB,uBAAuB,CAAC,QAAQ,EAAE,YAAY,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAMlG;AAaD,wBAAsB,iBAAiB,CAAC,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAIjI;AAED,wBAAsB,qBAAqB,CAAC,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAGrI;AAED,wBAAsB,mBAAmB,CAAC,EAAE,EAAE,QAAQ,EAAE,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,EAAE,UAAU,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAG1J"}
@@ -0,0 +1,117 @@
1
+ import { BufferedResponse } from './client.js';
2
+ import { identifier, whereClause } from './sql.js';
3
+ export class TestAssertionError extends Error {
4
+ name = 'TestAssertionError';
5
+ }
6
+ async function bodyPreview(response) {
7
+ try {
8
+ const text = await response.text();
9
+ return text.length > 500 ? `${text.slice(0, 500)}…` : text;
10
+ }
11
+ catch {
12
+ return '(body already read)';
13
+ }
14
+ }
15
+ /** Synchronous (the status is known): `assertStatus(res, 200)` needs no await, though awaiting it is harmless. */
16
+ export function assertStatus(response, expected) {
17
+ if (response.status !== expected) {
18
+ const body = response instanceof BufferedResponse ? response.bodyText : '(not a test client response)';
19
+ throw new TestAssertionError(`Expected status ${expected}, got ${response.status}. Body: ${body.length > 500 ? `${body.slice(0, 500)}…` : body}`);
20
+ }
21
+ }
22
+ /** Reads `a.b.0.c` from a value; `undefined` when a step is missing. */
23
+ export function jsonPath(value, path) {
24
+ let current = value;
25
+ for (const step of path === '' ? [] : path.split('.')) {
26
+ if (current === null || typeof current !== 'object')
27
+ return undefined;
28
+ if (Array.isArray(current)) {
29
+ if (!/^\d+$/.test(step))
30
+ return undefined;
31
+ current = current[Number(step)];
32
+ }
33
+ else {
34
+ if (!Object.prototype.hasOwnProperty.call(current, step))
35
+ return undefined;
36
+ current = current[step];
37
+ }
38
+ }
39
+ return current;
40
+ }
41
+ function deepEqual(a, b) {
42
+ if (Object.is(a, b))
43
+ return true;
44
+ if (typeof a !== 'object' || typeof b !== 'object' || a === null || b === null)
45
+ return false;
46
+ if (Array.isArray(a) !== Array.isArray(b))
47
+ return false;
48
+ const ka = Object.keys(a);
49
+ const kb = Object.keys(b);
50
+ if (ka.length !== kb.length)
51
+ return false;
52
+ return ka.every((k) => Object.prototype.hasOwnProperty.call(b, k) && deepEqual(a[k], b[k]));
53
+ }
54
+ /**
55
+ * `expected` may be a value (deep equality) or a predicate. Returns the value
56
+ * found, so a test can keep using it.
57
+ */
58
+ export async function assertJsonPath(response, path, expected) {
59
+ const actual = jsonPath(await response.json(), path);
60
+ const ok = typeof expected === 'function' ? expected(actual) === true : deepEqual(actual, expected);
61
+ if (!ok) {
62
+ const shown = typeof expected === 'function' ? 'a value matching the predicate' : JSON.stringify(expected);
63
+ throw new TestAssertionError(`Expected JSON path "${path}" to be ${shown}, got ${JSON.stringify(actual)}. Body: ${await bodyPreview(response)}`);
64
+ }
65
+ return actual;
66
+ }
67
+ /**
68
+ * 422 with `errors[field]` present (envelope `{ errors: { field: [keys] } }`).
69
+ * With `messageKey`, that key must be among the field's messages.
70
+ */
71
+ export async function assertValidationError(response, field, messageKey) {
72
+ if (response.status !== 422) {
73
+ throw new TestAssertionError(`Expected a 422 validation error on "${field}", got ${response.status}. Body: ${await bodyPreview(response)}`);
74
+ }
75
+ const errors = jsonPath(await response.json(), 'errors');
76
+ const messages = typeof errors === 'object' && errors !== null ? errors[field] : undefined;
77
+ if (!Array.isArray(messages) || messages.length === 0) {
78
+ throw new TestAssertionError(`Expected a validation error on "${field}". Body: ${await bodyPreview(response)}`);
79
+ }
80
+ if (messageKey !== undefined && !messages.includes(messageKey)) {
81
+ throw new TestAssertionError(`Expected "${field}" to fail with "${messageKey}", got ${JSON.stringify(messages)}`);
82
+ }
83
+ }
84
+ /** The response has no error for `field` (it may still be another 422). */
85
+ export async function assertNoValidationError(response, field) {
86
+ if (response.status !== 422)
87
+ return;
88
+ const messages = jsonPath(await response.json(), `errors.${field}`);
89
+ if (Array.isArray(messages) && messages.length > 0) {
90
+ throw new TestAssertionError(`Expected no validation error on "${field}", got ${JSON.stringify(messages)}`);
91
+ }
92
+ }
93
+ async function countMatching(db, table, conditions) {
94
+ const where = whereClause(conditions);
95
+ const row = await db.first(`SELECT COUNT(*) AS n FROM ${identifier(table)} WHERE ${where.sql}`, where.params);
96
+ return Number(row?.n ?? 0);
97
+ }
98
+ async function tablePreview(db, table) {
99
+ const rows = await db.select(`SELECT * FROM ${identifier(table)} LIMIT 10`);
100
+ return JSON.stringify(rows);
101
+ }
102
+ export async function assertDatabaseHas(db, table, conditions) {
103
+ if ((await countMatching(db, table, conditions)) === 0) {
104
+ throw new TestAssertionError(`Expected a row in "${table}" matching ${JSON.stringify(conditions)}. First rows: ${await tablePreview(db, table)}`);
105
+ }
106
+ }
107
+ export async function assertDatabaseMissing(db, table, conditions) {
108
+ const n = await countMatching(db, table, conditions);
109
+ if (n > 0)
110
+ throw new TestAssertionError(`Expected no row in "${table}" matching ${JSON.stringify(conditions)}, found ${n}.`);
111
+ }
112
+ export async function assertDatabaseCount(db, table, expected, conditions = {}) {
113
+ const n = await countMatching(db, table, conditions);
114
+ if (n !== expected)
115
+ throw new TestAssertionError(`Expected ${expected} rows in "${table}" matching ${JSON.stringify(conditions)}, found ${n}.`);
116
+ }
117
+ //# sourceMappingURL=assertions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"assertions.js","sourceRoot":"","sources":["../src/assertions.ts"],"names":[],"mappings":"AAWA,OAAO,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAC/C,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AAEnD,MAAM,OAAO,kBAAmB,SAAQ,KAAK;IACzB,IAAI,GAAG,oBAAoB,CAAC;CAC/C;AAED,KAAK,UAAU,WAAW,CAAC,QAAsB;IAC/C,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,OAAO,IAAI,CAAC,MAAM,GAAG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ch`; cookies persist between calls; the CSRF token is read from
4
+ * where the app hands it out and echoed on unsafe methods, as the React kit does.
5
+ */
6
+ import type { Application } from '@solobrand/core';
7
+ import type { Database } from '@solobrand/db';
8
+ import type { Kernel, Principal } from '@solobrand/http';
9
+ import type { TestApp, TestResponse } from './index.js';
10
+ export declare const BASE_URL = "https://app.test";
11
+ export declare const CSRF_HEADER = "x-csrf-token";
12
+ /** A minimal RFC 6265 jar for one origin: name+path keyed, Max-Age/Expires honoured. */
13
+ export declare class CookieJar {
14
+ private readonly cookies;
15
+ store(setCookie: string, now?: number): void;
16
+ /** The `Cookie` header for a path, or null when nothing applies. */
17
+ header(path: string, now?: number): string | null;
18
+ get(name: string): string | null;
19
+ names(): string[];
20
+ }
21
+ /** A response whose body can be read any number of times (assertions read it again). */
22
+ export declare class BufferedResponse implements TestResponse {
23
+ readonly status: number;
24
+ readonly headers: Headers;
25
+ private readonly body;
26
+ constructor(status: number, headers: Headers, body: string);
27
+ /** The body, synchronously (assertions use it). */
28
+ get bodyText(): string;
29
+ text(): Promise<string>;
30
+ json<T = unknown>(): Promise<T>;
31
+ }
32
+ /** Shared by a TestApp and every `anotherClient()` of it. */
33
+ export interface Runtime {
34
+ readonly kernel: Kernel;
35
+ readonly env: Readonly<Record<string, unknown>>;
36
+ readonly db: Database;
37
+ readonly app: () => Application;
38
+ }
39
+ export declare class TestClient implements TestApp {
40
+ private readonly runtime;
41
+ private readonly jar;
42
+ private csrf;
43
+ private principal;
44
+ constructor(runtime: Runtime);
45
+ get app(): Application;
46
+ get db(): Database;
47
+ /** The CSRF token this client will send next (null until the app handed one out). */
48
+ get csrfToken(): string | null;
49
+ /** The cookie jar (read it in tests: `client.cookies.get('__Host-sb_session')`). */
50
+ get cookies(): CookieJar;
51
+ actingAs(user: {
52
+ id: number;
53
+ email: string;
54
+ }, options?: {
55
+ via?: Principal['via'];
56
+ scopes?: readonly string[];
57
+ }): TestApp;
58
+ anotherClient(): TestApp;
59
+ request(path: string, init?: RequestInit & {
60
+ json?: unknown;
61
+ }): Promise<TestResponse>;
62
+ }
63
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACnD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAC9C,OAAO,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAEzD,OAAO,KAAK,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAExD,eAAO,MAAM,QAAQ,qBAAqB,CAAC;AAC3C,eAAO,MAAM,WAAW,iBAAiB,CAAC;AAS1C,wFAAwF;AACxF,qBAAa,SAAS;IACpB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAsD;IAE9E,KAAK,CAAC,SAAS,EAAE,MAAM,EAAE,GAAG,SAAa,GAAG,IAAI;IA0BhD,oEAAoE;IACpE,MAAM,CAAC,IAAI,EAAE,MAAM,EAAE,GAAG,SAAa,GAAG,MAAM,GAAG,IAAI;IAcrD,GAAG,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI;IAKhC,KAAK,IAAI,MAAM,EAAE;CAGlB;AAED,wFAAwF;AACxF,qBAAa,gBAAiB,YAAW,YAAY;IAEjD,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,OAAO,EAAE,OAAO;IACzB,OAAO,CAAC,QAAQ,CAAC,IAAI;gBAFZ,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,OAAO,EACR,IAAI,EAAE,MAAM;IAG/B,mDAAmD;IACnD,IAAI,QAAQ,IAAI,MAAM,CAErB;IAEK,IAAI,IAAI,OAAO,CAAC,MAAM,CAAC;IAIvB,IAAI,CAAC,CAAC,GAAG,OAAO,KAAK,OAAO,CAAC,CAAC,C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const CSRF_HEADER = 'x-csrf-token';
4
+ const UNSAFE = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
5
+ /** A minimal RFC 6265 jar for one origin: name+path keyed, Max-Age/Expires honoured. */
6
+ export class CookieJar {
7
+ cookies = new Map();
8
+ store(setCookie, now = Date.now()) {
9
+ const [pair = '', ...attributes] = setCookie.split(';');
10
+ const eq = pair.indexOf('=');
11
+ if (eq <= 0)
12
+ return;
13
+ const name = pair.slice(0, eq).trim();
14
+ const value = pair.slice(eq + 1).trim();
15
+ let path = '/';
16
+ let expiresAt = null;
17
+ for (const attribute of attributes) {
18
+ const [rawKey = '', ...rest] = attribute.split('=');
19
+ const key = rawKey.trim().toLowerCase();
20
+ const attrValue = rest.join('=').trim();
21
+ if (key === 'path' && attrValue.startsWith('/'))
22
+ path = attrValue;
23
+ else if (key === 'max-age') {
24
+ const seconds = Number(attrValue);
25
+ if (Number.isFinite(seconds))
26
+ expiresAt = now + seconds * 1000;
27
+ }
28
+ else if (key === 'expires' && expiresAt === null) {
29
+ const at = Date.parse(attrValue);
30
+ if (!Number.isNaN(at))
31
+ expiresAt = at;
32
+ }
33
+ }
34
+ const id = `${name};${path}`;
35
+ if (expiresAt !== null && expiresAt <= now)
36
+ this.cookies.delete(id);
37
+ else
38
+ this.cookies.set(id, { name, value, path, expiresAt });
39
+ }
40
+ /** The `Cookie` header for a path, or null when nothing applies. */
41
+ header(path, now = Date.now()) {
42
+ const parts = [];
43
+ for (const [id, cookie] of this.cookies) {
44
+ if (cookie.expiresAt !== null && cookie.expiresAt <= now) {
45
+ this.cookies.delete(id);
46
+ continue;
47
+ }
48
+ if (path === cookie.path || path.startsWith(cookie.path.endsWith('/') ? cookie.path : `${cookie.path}/`) || cookie.path === '/') {
49
+ parts.push(`${cookie.name}=${cookie.value}`);
50
+ }
51
+ }
52
+ return parts.length === 0 ? null : parts.join('; ');
53
+ }
54
+ get(name) {
55
+ for (const cookie of this.cookies.values())
56
+ if (cookie.name === name)
57
+ return cookie.value;
58
+ return null;
59
+ }
60
+ names() {
61
+ return [...new Set([...this.cookies.values()].map((c) => c.name))];
62
+ }
63
+ }
64
+ /** A response whose body can be read any number of times (assertions read it again). */
65
+ export class BufferedResponse {
66
+ status;
67
+ headers;
68
+ body;
69
+ constructor(status, headers, body) {
70
+ this.status = status;
71
+ this.headers = headers;
72
+ this.body = body;
73
+ }
74
+ /** The body, synchronously (assertions use it). */
75
+ get bodyText() {
76
+ return this.body;
77
+ }
78
+ async text() {
79
+ return this.body;
80
+ }
81
+ async json() {
82
+ try {
83
+ return JSON.parse(this.body);
84
+ }
85
+ catch {
86
+ throw new Error(`@solobrand/testing: response (${this.status}) is not JSON: ${this.body.slice(0, 200)}`);
87
+ }
88
+ }
89
+ }
90
+ export class TestClient {
91
+ runtime;
92
+ jar = new CookieJar();
93
+ csrf = null;
94
+ principal = null;
95
+ constructor(runtime) {
96
+ this.runtime = runtime;
97
+ }
98
+ get app() {
99
+ return this.runtime.app();
100
+ }
101
+ get db() {
102
+ return this.runtime.db;
103
+ }
104
+ /** The CSRF token this client will send next (null until the app handed one out). */
105
+ get csrfToken() {
106
+ return this.csrf;
107
+ }
108
+ /** The cookie jar (read it in tests: `client.cookies.get('__Host-sb_session')`). */
109
+ get cookies() {
110
+ return this.jar;
111
+ }
112
+ actingAs(user, options = {}) {
113
+ const via = options.via ?? 'session';
114
+ const record = user;
115
+ const verified = record.emailVerifiedAt !== undefined ? record.emailVerifiedAt : record.email_verified_at;
116
+ this.principal = {
117
+ id: user.id,
118
+ email: user.email,
119
+ emailVerifiedAt: verified === undefined ? new Date().toISOString() : typeof verified === 'string' ? verified : null,
120
+ via,
121
+ scopes: via === 'token' ? [...(options.scopes ?? [])] : options.scopes !== undefined ? [...options.scopes] : '*',
122
+ };
123
+ return this;
124
+ }
125
+ anotherClient() {
126
+ return new TestClient(this.runtime);
127
+ }
128
+ async request(path, init = {}) {
129
+ const { json, ...rest } = init;
130
+ const url = new URL(path, BASE_URL);
131
+ const method = (rest.method ?? (json !== undefined ? 'POST' : 'GET')).toUpperCase();
132
+ const headers = new Headers(rest.headers);
133
+ let body = rest.body;
134
+ if (json !== undefined) {
135
+ body = JSON.stringify(json);
136
+ if (!headers.has('content-type'))
137
+ headers.set('content-type', 'application/json');
138
+ }
139
+ if (!headers.has('accept'))
140
+ headers.set('accept', 'application/json');
141
+ const cookie = this.jar.header(url.pathname);
142
+ if (cookie !== null && !headers.has('cookie'))
143
+ headers.set('cookie', cookie);
144
+ if (UNSAFE.has(method)) {
145
+ if (!headers.has('origin'))
146
+ headers.set('origin', url.origin);
147
+ if (!headers.has('sec-fetch-site'))
148
+ headers.set('sec-fetch-site', 'same-origin');
149
+ if (this.csrf !== null && !headers.has(CSRF_HEADER))
150
+ headers.set(CSRF_HEADER, this.csrf);
151
+ }
152
+ if (this.principal !== null) {
153
+ headers.set(TEST_PRINCIPAL_HEADER, encodeTestPrincipal(this.principal));
154
+ const key = this.runtime.env[TESTING_KEY];
155
+ if (typeof key === 'string')
156
+ headers.set(TEST_KEY_HEADER, key);
157
+ }
158
+ const request = new Request(url, { ...rest, method, headers, body: body ?? null });
159
+ const pending = [];
160
+ const execution = {
161
+ waitUntil: (promise) => {
162
+ pending.push(promise);
163
+ },
164
+ passThroughOnException: () => { },
165
+ props: {},
166
+ };
167
+ const response = await this.runtime.kernel.fetch(request, this.runtime.env, execution);
168
+ const text = await response.text();
169
+ // Like a Worker, background work finishes; unlike one, the test waits for it.
170
+ await Promise.allSettled(pending);
171
+ for (const setCookie of response.headers.getSetCookie())
172
+ this.jar.store(setCookie);
173
+ // Like the React kit: the token comes ONLY in the X-CSRF-Token response header (login, GET /auth/csrf).
174
+ this.csrf = response.headers.get(CSRF_HEADER) ?? this.csrf;
175
+ return new BufferedResponse(response.status, response.headers, text);
176
+ }
177
+ }
178
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAQA,OAAO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,GAAG,CAAC,eAAe,EAAE,GAAG,CAAC,CAAC;QACjE,CAAC;QACD,MAAM,OAAO,GAAG,IAAI,OAAO,CAAC,GAAG,EAAE,EAAE,GAAG,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,IAAI,EAAE,IAAI,IAAI,IAAI,EAAE,CAAC,CAAC;QAEnF,MAAM,OAAO,GAAuB,EAAE,CAAC;QACvC,MAAM,SAAS,GAAG;YAChB,SAAS,EAAE,CAAC,OAAyB,EAAE,EAAE;gBACvC,OAAO,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACxB,CAAC;YACD,sBAAsB,EAAE,GAAG,EAAE,GAAE,CAAC;YAChC,KAAK,EAAE,EAAE;SACqB,CAAC;QAEjC,MAAM,QAAQ,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,OAAO,EAAE,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QACvF,MAAM,IAAI,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE,CAAC;QACnC,8EAA8E;QAC9E,MAAM,OAAO,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;QAElC,KAAK,MAAM,SAAS,IAAI,QAAQ,CAAC,OAAO,CAAC,YAAY,EAAE;YAAE,IAAI,CAAC,GAAG,CAAC,KAAK,CAAC,SAAS,CAAC,CAAC;QACnF,wGAAwG;QACxG,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,WAAW,CAAC,IAAI,IAAI,CAAC,IAAI,CAAC;QAC3D,OAAO,IAAI,gBAAgB,CAAC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC,OAAO,EAAE,IAAI,CAAC,CAAC;IACvE,CAAC;CACF"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Factories with sequences, Laravel style:
3
+ *
4
+ * const users = defineFactory('users', (n) => ({ email: `user${n}@example.test`, name: `User ${n}` }));
5
+ * const one = await users.create(db, { name: 'Ana' });
6
+ * const three = await createMany(users.count(3), db);
7
+ */
8
+ import type { Database, Row } from '@solobrand/db';
9
+ import type { Factory } from './index.js';
10
+ export declare function defineFactoryImpl<T extends Row>(table: string, definition: (seq: number) => T): Factory<T>;
11
+ /** Same as `factory.makeMany()` (kept as a function for code written before the method existed). */
12
+ export declare function makeMany<T extends Row>(factory: Factory<T>, overrides?: Partial<T>): T[];
13
+ /** Same as `factory.createMany(db)`. */
14
+ export declare function createMany<T extends Row>(factory: Factory<T>, db: Database, overrides?: Partial<T>): Promise<(T & {
15
+ id: number;
16
+ })[]>;
17
+ //# sourceMappingURL=factory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,QAAQ,EAAa,GAAG,EAAE,MAAM,eAAe,CAAC;AAC9D,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAyD1C,wBAAgB,iBAAiB,CAAC,CAAC,SAAS,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAG1G;AAED,oGAAoG;AACpG,wBAAgB,QAAQ,CAAC,CAAC,SAAS,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,SAAS,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAExF;AAED,wCAAwC;AACxC,wBAAsB,UAAU,CAAC,CAAC,SAAS,GAAG,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC,CAAC,EAAE,EAAE,EAAE,QAAQ,EAAE,SAAS,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG;IAAE,EAAE,EAAE,MAAM,CAAA;CAAE,CAAC,EAAE,CAAC,CAE1I"}
@@ -0,0 +1,65 @@
1
+ import { identifier, toPrimitive } from './sql.js';
2
+ function insertRow(db, table, row) {
3
+ const entries = Object.entries(row).filter(([, v]) => v !== undefined);
4
+ if (entries.length === 0)
5
+ return db.execute(`INSERT INTO ${identifier(table)} DEFAULT VALUES`);
6
+ const columns = entries.map(([column]) => identifier(column)).join(', ');
7
+ const placeholders = entries.map(() => '?').join(', ');
8
+ const params = entries.map(([, value]) => toPrimitive(value));
9
+ return db.execute(`INSERT INTO ${identifier(table)} (${columns}) VALUES (${placeholders})`, params);
10
+ }
11
+ function build(state, times) {
12
+ const makeOne = (overrides) => {
13
+ const seq = state.sequence.next++;
14
+ return { ...state.definition(seq), ...(overrides ?? {}) };
15
+ };
16
+ const createOne = async (db, overrides) => {
17
+ const row = makeOne(overrides);
18
+ const result = await insertRow(db, state.table, row);
19
+ const explicitId = row['id'];
20
+ const id = typeof explicitId === 'number' ? explicitId : result.lastRowId;
21
+ if (id === null)
22
+ throw new Error(`@solobrand/testing: insert into ${state.table} returned no row id`);
23
+ return { ...row, id };
24
+ };
25
+ const factory = {
26
+ makeMany: (overrides) => Array.from({ length: times }, () => makeOne(overrides)),
27
+ createMany: async (db, overrides) => {
28
+ const rows = [];
29
+ for (let i = 0; i < times; i++)
30
+ rows.push(await createOne(db, overrides));
31
+ return rows;
32
+ },
33
+ make: (overrides) => {
34
+ let last = makeOne(overrides);
35
+ for (let i = 1; i < times; i++)
36
+ last = makeOne(overrides);
37
+ return last;
38
+ },
39
+ create: async (db, overrides) => {
40
+ let last = await createOne(db, overrides);
41
+ for (let i = 1; i < times; i++)
42
+ last = await createOne(db, overrides);
43
+ return last;
44
+ },
45
+ count: (n) => {
46
+ if (!Number.isInteger(n) || n < 1)
47
+ throw new Error('@solobrand/testing: count(n) needs an integer n ≥ 1');
48
+ return build(state, n);
49
+ },
50
+ };
51
+ return factory;
52
+ }
53
+ export function defineFactoryImpl(table, definition) {
54
+ identifier(table);
55
+ return build({ table, definition, sequence: { next: 1 } }, 1);
56
+ }
57
+ /** Same as `factory.makeMany()` (kept as a function for code written before the method existed). */
58
+ export function makeMany(factory, overrides) {
59
+ return factory.makeMany(overrides);
60
+ }
61
+ /** Same as `factory.createMany(db)`. */
62
+ export async function createMany(factory, db, overrides) {
63
+ return factory.createMany(db, overrides);
64
+ }
65
+ //# sourceMappingURL=factory.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory.js","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AASnD,SAAS,SAAS,CAAC,EAAY,EAAE,KAAa,EAAE,GAAQ;IACtD,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,KAAK,SAAS,CAAC,CAAC;IACvE,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC,OAAO,CAAC,eAAe,UAAU,CAAC,KAAK,CAAC,iBAAiB,CAAC,CAAC;IAC/F,MAAM,OAAO,GAAG,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,MAAM,CAAC,EAAE,EAAE,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACzE,MAAM,YAAY,GAAG,OAAO,CAAC,GAAG,CAAC,GAAG,EAAE,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;IACvD,MAAM,MAAM,GAAgB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,EAAE,EAAE,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,CAAC;IAC3E,OAAO,EAAE,CAAC,OAAO,CAAC,eAAe,UAAU,CAAC,KAAK,CAAC,KAAK,OAAO,aAAa,YAAY,GAAG,EAAE,MAAM,CAAC,C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pG,MAAM,UAAU,QAAQ,CAAgB,OAAmB,EAAE,SAAsB;IACjF,OAAO,OAAO,CAAC,QAAQ,CAAC,SAAS,CAAC,CAAC;AACrC,CAAC;AAED,wCAAwC;AACxC,MAAM,CAAC,KAAK,UAAU,UAAU,CAAgB,OAAmB,EAAE,EAAY,EAAE,SAAsB;IACvG,OAAO,OAAO,CAAC,UAAU,CAAC,EAAE,EAAE,SAAS,CAAC,CAAC;AAC3C,CAAC"}
package/dist/hook.d.ts ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The `actingAs()` test hook. The READER lives in @solobrand/http (the guards
3
+ * read it there; integrator decision, CONTRACT-CHANGES.md); this module
4
+ * re-exports it so `@solobrand/testing/hook` keeps working. The WRITER — the
5
+ * headers `TestApp.actingAs()` sends — is `src/client.ts`, using
6
+ * `encodeTestPrincipal` and the per-app `SOLOBRAND_TEST_KEY` from `createTestApp`.
7
+ *
8
+ * X-SoloBrand-Test-Principal: base64url(JSON principal)
9
+ * X-SoloBrand-Test-Key: the per-test-app random key (generateTestKey(): 64 hex chars)
10
+ *
11
+ * Honoured only when `env.SOLOBRAND_TESTING === '1'` and the key matches.
12
+ */
13
+ export { TEST_PRINCIPAL_HEADER, TEST_KEY_HEADER, TESTING_FLAG, TESTING_KEY, generateTestKey, encodeTestPrincipal, testHookEnabled, readTestPrincipal, testPrincipalMiddleware, } from '@solobrand/http';
14
+ //# sourceMappingURL=hook.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook.d.ts","sourceRoot":"","sources":["../src/hook.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,YAAY,EACZ,WAAW,EACX,eAAe,EACf,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,iBAAiB,CAAC"}
package/dist/hook.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The `actingAs()` test hook. The READER lives in @solobrand/http (the guards
3
+ * read it there; integrator decision, CONTRACT-CHANGES.md); this module
4
+ * re-exports it so `@solobrand/testing/hook` keeps working. The WRITER — the
5
+ * headers `TestApp.actingAs()` sends — is `src/client.ts`, using
6
+ * `encodeTestPrincipal` and the per-app `SOLOBRAND_TEST_KEY` from `createTestApp`.
7
+ *
8
+ * X-SoloBrand-Test-Principal: base64url(JSON principal)
9
+ * X-SoloBrand-Test-Key: the per-test-app random key (generateTestKey(): 64 hex chars)
10
+ *
11
+ * Honoured only when `env.SOLOBRAND_TESTING === '1'` and the key matches.
12
+ */
13
+ export { TEST_PRINCIPAL_HEADER, TEST_KEY_HEADER, TESTING_FLAG, TESTING_KEY, generateTestKey, encodeTestPrincipal, testHookEnabled, readTestPrincipal, testPrincipalMiddleware, } from '@solobrand/http';
14
+ //# sourceMappingURL=hook.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hook.js","sourceRoot":"","sources":["../src/hook.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AACH,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,YAAY,EACZ,WAAW,EACX,eAAe,EACf,mBAAmB,EACnB,eAAe,EACf,iBAAiB,EACjB,uBAAuB,GACxB,MAAM,iBAAiB,CAAC"}
@@ -0,0 +1,67 @@
1
+ /**
2
+ * @solobrand/testing — public contracts (FROZEN by F0) + stubs. Implemented by F2 (P24-57).
3
+ * Tests run on the real Workers runtime (@cloudflare/vitest-pool-workers), each with a fresh D1.
4
+ */
5
+ import { type Application } from '@solobrand/core';
6
+ import { type Database, type Migration, type Row } from '@solobrand/db';
7
+ import type { Kernel, Principal } from '@solobrand/http';
8
+ export interface TestApp {
9
+ readonly app: Application;
10
+ readonly db: Database;
11
+ /** Sends a request through the kernel, keeping cookies between calls like a browser. */
12
+ request(path: string, init?: RequestInit & {
13
+ json?: unknown;
14
+ }): Promise<TestResponse>;
15
+ /** Next requests authenticate as this user (session guard; `via: 'token'` for the token guard). */
16
+ actingAs(user: {
17
+ id: number;
18
+ email: string;
19
+ }, options?: {
20
+ via?: Principal['via'];
21
+ scopes?: readonly string[];
22
+ }): TestApp;
23
+ /** A second, independent client (another browser): for "someone else gets 404" tests. */
24
+ anotherClient(): TestApp;
25
+ }
26
+ export interface TestResponse {
27
+ readonly status: number;
28
+ readonly headers: Headers;
29
+ json<T = unknown>(): Promise<T>;
30
+ text(): Promise<string>;
31
+ }
32
+ export interface Factory<T extends Row> {
33
+ make(overrides?: Partial<T>): T;
34
+ create(db: Database, overrides?: Partial<T>): Promise<T & {
35
+ id: number;
36
+ }>;
37
+ count(n: number): Factory<T>;
38
+ /** Every row of `count(n)` (1 by default), not inserted. */
39
+ makeMany(overrides?: Partial<T>): T[];
40
+ /** Inserts every row of `count(n)` and returns them all, in order, with their ids. */
41
+ createMany(db: Database, overrides?: Partial<T>): Promise<(T & {
42
+ id: number;
43
+ })[]>;
44
+ }
45
+ /**
46
+ * A fresh app per call: a fresh D1 (in-memory SQLite in Node, or `env.DB` when
47
+ * you pass one — e.g. the isolated D1 of @cloudflare/vitest-pool-workers), the
48
+ * migrations applied, and `env.SOLOBRAND_TESTING = '1'` plus a random
49
+ * `SOLOBRAND_TEST_KEY` so `actingAs()` works. Values in `options.env` win
50
+ * (pass `SOLOBRAND_TESTING: '0'` to run as production would).
51
+ * Return `{ kernel, app }` from `kernel` and `t.app` is the kernel's own app.
52
+ */
53
+ export declare function createTestApp(options: {
54
+ kernel: (env: Record<string, unknown>) => Kernel | {
55
+ kernel: Kernel;
56
+ app: Application;
57
+ };
58
+ migrations: readonly Migration[];
59
+ env?: Record<string, unknown>;
60
+ }): Promise<TestApp>;
61
+ /** `(seq) => row`: seq starts at 1 and never repeats for this factory. */
62
+ export declare function defineFactory<T extends Row>(table: string, definition: (seq: number) => T): Factory<T>;
63
+ export { TestClient, CookieJar, BufferedResponse, BASE_URL, CSRF_HEADER } from './client.js';
64
+ export { makeMany, createMany } from './factory.js';
65
+ export { TestAssertionError, assertStatus, assertJsonPath, assertValidationError, assertNoValidationError, assertDatabaseHas, assertDatabaseMissing, assertDatabaseCount, jsonPath, } from './assertions.js';
66
+ export { TEST_PRINCIPAL_HEADER, TEST_KEY_HEADER, TESTING_FLAG, TESTING_KEY, readTestPrincipal, testHookEnabled, testPrincipalMiddleware, encodeTestPrincipal, generateTestKey, } from './hook.js';
67
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAqB,KAAK,WAAW,EAAE,MAAM,iBAAiB,CAAC;AACtE,OAAO,EAA4C,KAAK,QAAQ,EAAE,KAAK,SAAS,EAAE,KAAK,GAAG,EAAE,MAAM,eAAe,CAAC;AAClH,OAAO,KAAK,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAKzD,MAAM,WAAW,OAAO;IACtB,QAAQ,CAAC,GAAG,EAAE,WAAW,CAAC;IAC1B,QAAQ,CAAC,EAAE,EAAE,QAAQ,CAAC;IACtB,wFAAwF;IACxF,OAAO,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,CAAC,EAAE,WAAW,GAAG;QAAE,IAAI,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,YAAY,CAAC,CAAC;IACtF,mGAAmG;IACnG,QAAQ,CAAC,IAAI,EAAE;QAAE,EAAE,EAAE,MAAM,CAAC;QAAC,KAAK,EAAE,MAAM,CAAA;KAAE,EAAE,OAAO,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC;QAAC,MAAM,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;KAAE,GAAG,OAAO,CAAC;IACzH,yFAAyF;IACzF,aAAa,IAAI,OAAO,CAAC;CAC1B;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,O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AC,SAAS,GAAG,EAAE,KAAK,EAAE,MAAM,EAAE,UAAU,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAEtG;AAED,OAAO,EAAE,UAAU,EAAE,SAAS,EAAE,gBAAgB,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC7F,OAAO,EAAE,QAAQ,EAAE,UAAU,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EACL,kBAAkB,EAClB,YAAY,EACZ,cAAc,EACd,qBAAqB,EACrB,uBAAuB,EACvB,iBAAiB,EACjB,qBAAqB,EACrB,mBAAmB,EACnB,QAAQ,GACT,MAAM,iBAAiB,CAAC;AACzB,OAAO,EACL,qBAAqB,EACrB,eAAe,EACf,YAAY,EACZ,WAAW,EACX,iBAAiB,EACjB,eAAe,EACf,uBAAuB,EACvB,mBAAmB,EACnB,eAAe,GAChB,MAAM,WAAW,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @solobrand/testing — public contracts (FROZEN by F0) + stubs. Implemented by F2 (P24-57).
3
+ * Tests run on the real Workers runtime (@cloudflare/vitest-pool-workers), each with a fresh D1.
4
+ */
5
+ import { createApplication } from '@solobrand/core';
6
+ import { createDatabase, createMigrator, dbTokens } from '@solobrand/db';
7
+ import { TestClient } from './client.js';
8
+ import { defineFactoryImpl } from './factory.js';
9
+ import { generateTestKey, TESTING_FLAG, TESTING_KEY } from './hook.js';
10
+ function isD1(value) {
11
+ return typeof value === 'object' && value !== null && typeof value.prepare === 'function' && typeof value.batch === 'function';
12
+ }
13
+ /**
14
+ * A fresh app per call: a fresh D1 (in-memory SQLite in Node, or `env.DB` when
15
+ * you pass one — e.g. the isolated D1 of @cloudflare/vitest-pool-workers), the
16
+ * migrations applied, and `env.SOLOBRAND_TESTING = '1'` plus a random
17
+ * `SOLOBRAND_TEST_KEY` so `actingAs()` works. Values in `options.env` win
18
+ * (pass `SOLOBRAND_TESTING: '0'` to run as production would).
19
+ * Return `{ kernel, app }` from `kernel` and `t.app` is the kernel's own app.
20
+ */
21
+ export async function createTestApp(options) {
22
+ const given = options.env ?? {};
23
+ const d1 = isD1(given['DB']) ? given['DB'] : (await import('./sqlite-d1.js')).createSqliteD1();
24
+ const env = { [TESTING_FLAG]: '1', [TESTING_KEY]: generateTestKey(), ...given, DB: d1 };
25
+ const db = createDatabase(d1);
26
+ await createMigrator(db, options.migrations).migrate();
27
+ const built = options.kernel(env);
28
+ const kernel = 'fetch' in built ? built : built.kernel;
29
+ let app = 'fetch' in built ? null : built.app;
30
+ // Boot it now (idempotent) so `t.app.make(...)` works before the first request.
31
+ if (app !== null)
32
+ await app.boot();
33
+ return new TestClient({
34
+ kernel,
35
+ env,
36
+ db,
37
+ // The kernel's own app when given; otherwise built on first use over the same env with this db bound.
38
+ app: () => {
39
+ if (app === null) {
40
+ app = createApplication({ env });
41
+ app.instance(dbTokens.database, db);
42
+ }
43
+ return app;
44
+ },
45
+ });
46
+ }
47
+ /** `(seq) => row`: seq starts at 1 and never repeats for this factory. */
48
+ export function defineFactory(table, definition) {
49
+ return defineFactoryImpl(table, definition);
50
+ }
51
+ export { TestClient, CookieJar, BufferedResponse, BASE_URL, CSRF_HEADER } from './client.js';
52
+ export { makeMany, createMany } from './factory.js';
53
+ export { TestAssertionError, assertStatus, assertJsonPath, assertValidationError, assertNoValidationError, assertDatabaseHas, assertDatabaseMissing, assertDatabaseCount, jsonPath, } from './assertions.js';
54
+ export { TEST_PRINCIPAL_HEADER, TEST_KEY_HEADER, TESTING_FLAG, TESTING_KEY, readTestPrincipal, testHookEnabled, testPrincipalMiddleware, encodeTestPrincipal, generateTestKey, } from './hook.js';
55
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,EAAE,iBAAiB,EAAoB,MAAM,iBAAiB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QL helpers for factories and assertions: identifiers validated, values always bound. */
2
+ import type { Primitive } from '@solobrand/db';
3
+ /** Quotes a table/column name after validating it; anything odd is refused, never escaped. */
4
+ export declare function identifier(name: string): string;
5
+ /** A value as D1 binds it (booleans → 0/1, Date → ISO, objects → JSON). */
6
+ export declare function toPrimitive(value: unknown): Primitive;
7
+ /** `"a" = ? AND "b" IS NULL` and its params. */
8
+ export declare function whereClause(conditions: Readonly<Record<string, unknown>>): {
9
+ sql: string;
10
+ params: Primitive[];
11
+ };
12
+ //# sourceMappingURL=sql.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql.d.ts","sourceRoot":"","sources":["../src/sql.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAI/C,8FAA8F;AAC9F,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAG/C;AAED,2EAA2E;AAC3E,wBAAgB,WAAW,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,CAOrD;AAED,gDAAgD;AAChD,wBAAgB,WAAW,CAAC,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,GAAG;IAAE,GAAG,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,SAAS,EAAE,CAAA;CAAE,CAY/G"}
package/dist/sql.js ADDED
@@ -0,0 +1,37 @@
1
+ const IDENTIFIER = /^[A-Za-z_][A-Za-z0-9_]*$/;
2
+ /** Quotes a table/column name after validating it; anything odd is refused, never escaped. */
3
+ export function identifier(name) {
4
+ if (!IDENTIFIER.test(name))
5
+ throw new Error(`@solobrand/testing: invalid SQL identifier ${JSON.stringify(name)}`);
6
+ return `"${name}"`;
7
+ }
8
+ /** A value as D1 binds it (booleans → 0/1, Date → ISO, objects → JSON). */
9
+ export function toPrimitive(value) {
10
+ if (value === null || value === undefined)
11
+ return null;
12
+ if (typeof value === 'string' || typeof value === 'number')
13
+ return value;
14
+ if (typeof value === 'boolean')
15
+ return value ? 1 : 0;
16
+ if (value instanceof Date)
17
+ return value.toISOString();
18
+ if (typeof value === 'bigint')
19
+ return Number(value);
20
+ return JSON.stringify(value);
21
+ }
22
+ /** `"a" = ? AND "b" IS NULL` and its params. */
23
+ export function whereClause(conditions) {
24
+ const parts = [];
25
+ const params = [];
26
+ for (const [column, raw] of Object.entries(conditions)) {
27
+ const value = toPrimitive(raw);
28
+ if (value === null)
29
+ parts.push(`${identifier(column)} IS NULL`);
30
+ else {
31
+ parts.push(`${identifier(column)} = ?`);
32
+ params.push(value);
33
+ }
34
+ }
35
+ return { sql: parts.length === 0 ? '1 = 1' : parts.join(' AND '), params };
36
+ }
37
+ //# sourceMappingURL=sql.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sql.js","sourceRoot":"","sources":["../src/sql.ts"],"names":[],"mappings":"AAGA,MAAM,UAAU,GAAG,0BAA0B,CAAC;AAE9C,8FAA8F;AAC9F,MAAM,UAAU,UAAU,CAAC,IAAY;IACrC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,IAAI,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,8CAA8C,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAClH,OAAO,IAAI,IAAI,GAAG,CAAC;AACrB,CAAC;AAED,2EAA2E;AAC3E,MAAM,UAAU,WAAW,CAAC,KAAc;IACxC,IAAI,KAAK,KAAK,IAAI,IAAI,KAAK,KAAK,SAAS;QAAE,OAAO,IAAI,CAAC;IACvD,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACzE,IAAI,OAAO,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrD,IAAI,KAAK,YAAY,IAAI;QAAE,OAAO,KAAK,CAAC,WAAW,EAAE,CAAC;IACtD,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACpD,OAAO,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAED,gDAAgD;AAChD,MAAM,UAAU,WAAW,CAAC,UAA6C;IACvE,MAAM,KAAK,GAAa,EAAE,CAAC;IAC3B,MAAM,MAAM,GAAgB,EAAE,CAAC;IAC/B,KAAK,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,UAAU,CAAC,EAAE,CAAC;QACvD,MAAM,KAAK,GAAG,WAAW,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,KAAK,KAAK,IAAI;YAAE,KAAK,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC;aAC3D,CAAC;YACJ,KAAK,CAAC,IAAI,CAAC,GAAG,UAAU,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC;YACxC,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;QACrB,CAAC;IACH,CAAC;IACD,OAAO,EAAE,GAAG,EAAE,KAAK,CAAC,MAAM,KAAK,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;AAC7E,CAAC"}
@@ -0,0 +1,26 @@
1
+ /**
2
+ * An in-memory D1 for Node tests: the `D1Database` interface over better-sqlite3.
3
+ *
4
+ * NODE ONLY (better-sqlite3 is native). It is loaded lazily by `createTestApp`
5
+ * so a Worker bundle that imports `@solobrand/testing` never pulls it in; under
6
+ * `@cloudflare/vitest-pool-workers` pass the real `env.DB` instead (see README).
7
+ *
8
+ * Behaves like D1 where tests can tell: foreign keys ON, booleans bound as 0/1,
9
+ * `undefined` refused, `batch` all-or-nothing, errors prefixed `D1_ERROR:`.
10
+ */
11
+ import BetterSqlite3 from 'better-sqlite3';
12
+ type SqliteDb = BetterSqlite3.Database;
13
+ export declare class SqliteD1Database implements D1Database {
14
+ readonly sqlite: SqliteDb;
15
+ constructor(filename?: string);
16
+ prepare(query: string): D1PreparedStatement;
17
+ batch<T = unknown>(statements: D1PreparedStatement[]): Promise<D1Result<T>[]>;
18
+ exec(query: string): Promise<D1ExecResult>;
19
+ withSession(_constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint): D1DatabaseSession;
20
+ dump(): Promise<ArrayBuffer>;
21
+ close(): void;
22
+ }
23
+ /** A fresh, empty, in-memory D1 (one per test). */
24
+ export declare function createSqliteD1(): SqliteD1Database;
25
+ export {};
26
+ //# sourceMappingURL=sqlite-d1.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-d1.d.ts","sourceRoot":"","sources":["../src/sqlite-d1.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,aAAa,MAAM,gBAAgB,CAAC;AAE3C,KAAK,QAAQ,GAAG,aAAa,CAAC,QAAQ,CAAC;AA+FvC,qBAAa,gBAAiB,YAAW,UAAU;IACjD,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC;gBAEd,QAAQ,SAAa;IAKjC,OAAO,CAAC,KAAK,EAAE,MAAM,GAAG,mBAAmB;IAIrC,KAAK,CAAC,CAAC,GAAG,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC,CAAC,EAAE,CAAC;IAS7E,IAAI,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,YAAY,CAAC;IAWhD,WAAW,CAAC,qBAAqB,CAAC,EAAE,iBAAiB,GAAG,mBAAmB,GAAG,iBAAiB;IAQzF,IAAI,IAAI,OAAO,CAAC,WAAW,CAAC;IAIlC,KAAK,IAAI,IAAI;CAGd;AAED,mDAAmD;AACnD,wBAAgB,cAAc,IAAI,gBAAgB,CAEjD"}
@@ -0,0 +1,151 @@
1
+ /**
2
+ * An in-memory D1 for Node tests: the `D1Database` interface over better-sqlite3.
3
+ *
4
+ * NODE ONLY (better-sqlite3 is native). It is loaded lazily by `createTestApp`
5
+ * so a Worker bundle that imports `@solobrand/testing` never pulls it in; under
6
+ * `@cloudflare/vitest-pool-workers` pass the real `env.DB` instead (see README).
7
+ *
8
+ * Behaves like D1 where tests can tell: foreign keys ON, booleans bound as 0/1,
9
+ * `undefined` refused, `batch` all-or-nothing, errors prefixed `D1_ERROR:`.
10
+ */
11
+ import BetterSqlite3 from 'better-sqlite3';
12
+ function toSqlite(value, index) {
13
+ if (value === null)
14
+ return null;
15
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'bigint')
16
+ return value;
17
+ if (typeof value === 'boolean')
18
+ return value ? 1 : 0;
19
+ if (value instanceof ArrayBuffer)
20
+ return Buffer.from(value);
21
+ if (ArrayBuffer.isView(value))
22
+ return Buffer.from(value.buffer, value.byteOffset, value.byteLength);
23
+ throw new Error(`D1_TYPE_ERROR: Type '${typeof value}' not supported for value '${String(value)}' at position ${index + 1}`);
24
+ }
25
+ function d1Error(error) {
26
+ if (error instanceof Error) {
27
+ const code = error.code;
28
+ return new Error(`D1_ERROR: ${error.message}${typeof code === 'string' ? `: ${code}` : ''}`, { cause: error });
29
+ }
30
+ return new Error(`D1_ERROR: ${String(error)}`);
31
+ }
32
+ function meta(changes, lastRowId, started) {
33
+ return {
34
+ duration: Date.now() - started,
35
+ size_after: 0,
36
+ rows_read: 0,
37
+ rows_written: changes,
38
+ last_row_id: lastRowId,
39
+ changed_db: changes > 0,
40
+ changes,
41
+ };
42
+ }
43
+ class SqlitePreparedStatement {
44
+ db;
45
+ sql;
46
+ params;
47
+ constructor(db, sql, params = []) {
48
+ this.db = db;
49
+ this.sql = sql;
50
+ this.params = params;
51
+ }
52
+ bind(...values) {
53
+ return new SqlitePreparedStatement(this.db, this.sql, values.map(toSqlite));
54
+ }
55
+ /** Runs synchronously (used by `batch` inside a transaction). */
56
+ execute() {
57
+ const started = Date.now();
58
+ try {
59
+ const statement = this.db.prepare(this.sql);
60
+ if (statement.reader) {
61
+ const results = statement.all(...this.params);
62
+ return { success: true, meta: meta(0, 0, started), results };
63
+ }
64
+ const info = statement.run(...this.params);
65
+ return { success: true, meta: meta(info.changes, Number(info.lastInsertRowid), started), results: [] };
66
+ }
67
+ catch (error) {
68
+ throw d1Error(error);
69
+ }
70
+ }
71
+ async first(colName) {
72
+ const row = this.execute().results[0];
73
+ if (row === undefined)
74
+ return null;
75
+ if (colName === undefined)
76
+ return row;
77
+ if (!(colName in row))
78
+ throw new Error(`D1_COLUMN_NOTFOUND: Column not found (${colName})`);
79
+ return row[colName];
80
+ }
81
+ async run() {
82
+ return this.execute();
83
+ }
84
+ async all() {
85
+ return this.execute();
86
+ }
87
+ async raw(options) {
88
+ try {
89
+ const statement = this.db.prepare(this.sql);
90
+ if (!statement.reader) {
91
+ statement.run(...this.params);
92
+ return options?.columnNames === true ? [[]] : [];
93
+ }
94
+ const rows = statement.raw(true).all(...this.params);
95
+ if (options?.columnNames === true)
96
+ return [statement.columns().map((c) => c.name), ...rows];
97
+ return rows;
98
+ }
99
+ catch (error) {
100
+ throw d1Error(error);
101
+ }
102
+ }
103
+ }
104
+ export class SqliteD1Database {
105
+ sqlite;
106
+ constructor(filename = ':memory:') {
107
+ this.sqlite = new BetterSqlite3(filename);
108
+ this.sqlite.pragma('foreign_keys = ON');
109
+ }
110
+ prepare(query) {
111
+ return new SqlitePreparedStatement(this.sqlite, query);
112
+ }
113
+ async batch(statements) {
114
+ const own = statements.map((s) => {
115
+ if (!(s instanceof SqlitePreparedStatement))
116
+ throw new Error('D1_ERROR: statement from another database');
117
+ return s;
118
+ });
119
+ const run = this.sqlite.transaction(() => own.map((s) => s.execute()));
120
+ return run();
121
+ }
122
+ async exec(query) {
123
+ const started = Date.now();
124
+ const count = query.split(';').filter((part) => part.trim() !== '').length;
125
+ try {
126
+ this.sqlite.exec(query);
127
+ }
128
+ catch (error) {
129
+ throw d1Error(error);
130
+ }
131
+ return { count, duration: Date.now() - started };
132
+ }
133
+ withSession(_constraintOrBookmark) {
134
+ return {
135
+ prepare: (query) => this.prepare(query),
136
+ batch: (statements) => this.batch(statements),
137
+ getBookmark: () => null,
138
+ };
139
+ }
140
+ async dump() {
141
+ throw new Error('D1_ERROR: dump() is not supported');
142
+ }
143
+ close() {
144
+ this.sqlite.close();
145
+ }
146
+ }
147
+ /** A fresh, empty, in-memory D1 (one per test). */
148
+ export function createSqliteD1() {
149
+ return new SqliteD1Database();
150
+ }
151
+ //# sourceMappingURL=sqlite-d1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sqlite-d1.js","sourceRoot":"","sources":["../src/sqlite-d1.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AACH,OAAO,aAAa,MAAM,gBAAgB,CAAC;AAK3C,SAAS,QAAQ,CAAC,KAAc,EAAE,KAAa;IAC7C,IAAI,KAAK,KAAK,IAAI;QAAE,OAAO,IAAI,CAAC;IAChC,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,OAAO,KAAK,KAAK,QAAQ;QAAE,OAAO,KAAK,CAAC;IACtG,IAAI,OAAO,KAAK,KAAK,SAAS;QAAE,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;IACrD,IAAI,KAAK,YAAY,WAAW;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC5D,IAAI,WAAW,CAAC,MAAM,CAAC,KAAK,CAAC;QAAE,OAAO,MAAM,CAAC,IAAI,CAAC,KAAK,CAAC,MAAM,EAAE,KAAK,CAAC,UAAU,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;IACpG,MAAM,IAAI,KAAK,CAAC,wBAAwB,OAAO,KAAK,8BAA8B,MAAM,CAAC,KAAK,CAAC,iBAAiB,KAAK,GAAG,CAAC,EAAE,CAAC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CAAC,IAAI;QACR,MAAM,IAAI,KAAK,CAAC,mCAAmC,CAAC,CAAC;IACvD,CAAC;IAED,KAAK;QACH,IAAI,CAAC,MAAM,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACF;AAED,mDAAmD;AACnD,MAAM,UAAU,cAAc;IAC5B,OAAO,IAAI,gBAAgB,EAAE,CAAC;AAChC,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,51 @@
1
1
  {
2
2
  "name": "@solobrand/testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Tests on the real Workers runtime: factories, per-test D1, actingAs.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ },
14
+ "./hook": {
15
+ "types": "./dist/hook.d.ts",
16
+ "import": "./dist/hook.js"
17
+ },
18
+ "./sqlite-d1": {
19
+ "types": "./dist/sqlite-d1.d.ts",
20
+ "import": "./dist/sqlite-d1.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md"
26
+ ],
27
+ "sideEffects": false,
28
+ "scripts": {
29
+ "build": "tsc -b",
30
+ "test": "vitest run",
31
+ "typecheck": "tsc -b --noEmit && tsc -p tsconfig.test.json"
32
+ },
33
+ "dependencies": {
34
+ "@solobrand/auth": "0.1.0",
35
+ "@solobrand/core": "0.1.0",
36
+ "@solobrand/db": "0.1.0",
37
+ "@solobrand/http": "0.1.0",
38
+ "better-sqlite3": "^13.2.0"
39
+ },
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "https://github.com/innoboxrr/solobrand-framework.git",
43
+ "directory": "packages/testing"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public"
47
+ },
48
+ "devDependencies": {
49
+ "@types/better-sqlite3": "^9.6.0"
50
+ }
51
+ }