@rexezuge/testing 0.0.0-stage → 1.13.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rexezuge
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,104 @@
1
- # Temporary Holding Version
1
+ # @rexezuge/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
+ Test doubles for the Rexezuge-CloudflareWorkers family, in one **dev-only** package. Thirteen repos copied the
4
+ same `cloudflare:workers` mock, a dozen hand-rolled `{ prepare: vi.fn().mockReturnValue(stmt) }` D1 objects, and
5
+ each wrote its own Access-token signing for auth tests. This package is the one definition.
6
+
7
+ ```bash
8
+ pnpm add -D @rexezuge/testing
9
+ ```
10
+
11
+ Production code never imports it. `@rexezuge/http`, `@rexezuge/runtime` and `@rexezuge/shared` are its dependencies
12
+ (it re-exports their `/testing` seams and the `Clock` / `IdGenerator` doubles).
13
+
14
+ | Export | Replaces |
15
+ | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------- |
16
+ | `DurableObject`, `RpcTarget`, `WorkflowEntrypoint` | `test/mocks/cloudflare-workers.ts` (13 copies; also `/cloudflare-workers`) |
17
+ | `createMemoryD1()` | the hand-rolled fake D1 |
18
+ | `createMemoryKv({ now? })` | hand-rolled `KVNamespace` maps |
19
+ | `FixedClock`, `FixedIdGenerator` | local clocks and id queues (re-exported from `@rexezuge/shared`) |
20
+ | `forgeAccessJwt`, `accessJwksFetch`, `forgeAccessRequest`, `accessJwks` | `jose` `SignJWT` + a stubbed JWKS `fetch` |
21
+ | `createTestApp(app, { env, headers })`, `requestJson` | `app.fetch(new Request(...), env, ctx)` boilerplate |
22
+ | `resetAllForTests`, `resetRateLimitForTests`, `getRateLimitBucketCountForTests`, `resetBreakerForTests`, `resetLogLevelForTests` | the `/testing` seams of `http` and `runtime` |
23
+
24
+ ## The `cloudflare:workers` mock
25
+
26
+ A superset of every family copy: `DurableObject` and `WorkflowEntrypoint` store `ctx` and `env` (so a real subclass can be
27
+ constructed and driven without Miniflare), `RpcTarget` is empty (a missing base is a module-load failure, not a test failure), and
28
+ `WorkflowEntrypoint#run` is a no-op. **Delete your `test/mocks/cloudflare-workers.ts`**: `defineUnitVitestConfig` and
29
+ `defineRepoVitestConfig` from `@rexezuge/tooling` alias `cloudflare:workers` to this module when the repo has no copy of its own.
30
+ A repo that wants to keep the path re-exports it: `export * from '@rexezuge/testing/cloudflare-workers';`.
31
+
32
+ ## `createMemoryD1()`: a recording fake, not a SQL engine
33
+
34
+ No SQLite is available to the family's unit pool (no repo depends on `better-sqlite3`, `sql.js` or Miniflare in unit tests), and the unit
35
+ suites do not need one: they assert on the SQL a DAO prepares and feed it canned rows. `createMemoryD1` is that object, written once.
36
+ A test that needs **real SQL semantics** (constraints, joins, migrations) belongs in the integration pool, where `createMigrationHelper`
37
+ from `@rexezuge/tooling` runs the real migrations on workerd's D1.
38
+
39
+ ```ts
40
+ const db = createMemoryD1();
41
+ db.when(/FROM users WHERE id = \?/, { rows: [{ id: 'u1', email: 'a@example.com' }] });
42
+ db.when(/^DELETE FROM sessions/, { changes: 3 });
43
+ db.when('INSERT INTO audit', { error: 'constraint failed' }); // resolves { success: false }, as D1 does
44
+ db.when('FROM flaky', { throws: new Error('D1_ERROR'), once: true }); // rejects once
45
+
46
+ const dao = new UserDAO(db.asD1<D1Database>());
47
+ await dao.find('u1');
48
+ expect(db.calls[0]).toEqual({ sql: expect.stringContaining('FROM users'), params: ['u1'], method: 'first' });
49
+ ```
50
+
51
+ - `when(matcher, answer)`: `matcher` is a substring, a `RegExp` or `(call) => boolean`; the **latest** matching rule wins. `answer` is
52
+ `{ rows, first, changes, lastRowId, error, throws, once }`; `rows` and `first` may be functions of the call.
53
+ - Unmatched statements answer an empty database: no rows, `changes: 0`, `success: true`.
54
+ - `calls` records every statement in order (`sql`, `params`, `method`); `batches` records each `batch()`; `callsMatching(matcher)`, `reset()`.
55
+ - `batch`, `exec` and `withSession(bookmark?)` (with `getBookmark()`) are provided for `createApiApp({ d1: { bookmarks } })` tests.
56
+
57
+ ## `createMemoryKv({ now? })`
58
+
59
+ `get` (text / json / arrayBuffer), `getWithMetadata`, `put` with `expirationTtl` / `expiration` / `metadata`, `delete`, and a cursor-paged `list({ prefix })`.
60
+ It satisfies `KvCache`'s namespace port structurally (`new KvCache(createMemoryKv())`). Pass `now: () => clock.now()` and advance a `FixedClock`
61
+ to expire entries; there is no sleeping in a TTL test.
62
+
63
+ ## Cloudflare Access tokens
64
+
65
+ ```ts
66
+ const TEAM = 'https://team.example.com';
67
+ beforeEach(() => vi.stubGlobal('fetch', accessJwksFetch(TEAM)));
68
+ afterEach(() => vi.unstubAllGlobals());
69
+
70
+ const request = await forgeAccessRequest('https://app.example.com/user/me', {
71
+ email: 'alice@example.com',
72
+ aud: 'aud-123',
73
+ teamDomain: TEAM,
74
+ });
75
+ await expect(authenticateAccess(request, undefined, { teamDomain: TEAM, policyAud: 'aud-123' })).resolves.toBe('alice@example.com');
76
+ ```
77
+
78
+ Tokens are really RS256-signed (WebCrypto, one key pair per module instance) and the JWKS really travels through `fetch`, so the production
79
+ verifier runs end to end. Options: `emailVerified` (omitted from the token when unset, as Access does), `claims` (override anything),
80
+ `expiresInSeconds` (negative mints an expired token), `now`. No `jose` import is needed in the repo's tests; the strict lint rule that bans it
81
+ outside the http layer exempts tests anyway.
82
+
83
+ ## `createTestApp` / `requestJson`
84
+
85
+ ```ts
86
+ const app = createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, handlers) });
87
+ const api = createTestApp(app, { env: { DB: db.asD1() }, headers: { 'cf-access-jwt-assertion': token } });
88
+
89
+ const { status, body } = await api.json<{ id: string }>('/user/items/1');
90
+ const created = await api.json('/user/items', { body: { name: 'x' } }); // a body defaults the method to POST
91
+ await api.settled(); // every waitUntil promise the app registered
92
+ ```
93
+
94
+ The app is taken structurally (`{ fetch(request, env, ctx) }`), so the package imports neither `hono` nor `chanfana`. `body` is the parsed JSON,
95
+ or `null` for an empty response; `response` is the raw `Response`.
96
+
97
+ ## Extending
98
+
99
+ The doubles are open where a test varies and closed where fidelity matters (see the [design charter](../../docs/design-charter.md)).
100
+
101
+ - **Open:** D1 answer rules (`when`), the KV clock (`now`), the app `env` / `headers` / `baseUrl`, claim overrides on a forged token,
102
+ `accessJwksFetch(team, fallback)` for other URLs, any `{ fetch }` object as an app.
103
+ - **Closed:** a forged token is always really signed, the D1 double never answers `success: true` for a rule that says `error`, a programmed
104
+ `throws` always rejects the promise (D1 never throws synchronously), and KV expiry is always checked against the injected clock.
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Cloudflare Access test tokens: really signed, really fetched.
3
+ *
4
+ * `accessAuth` (and the verifier behind it) checks a signature against the
5
+ * team's JWKS, so a stub that skips verification tests nothing. This module
6
+ * mints RS256 tokens with WebCrypto and serves the matching JWKS from a `fetch`
7
+ * stub, so a test runs the production verifier end to end:
8
+ *
9
+ * ```ts
10
+ * const TEAM = 'https://team.example.com';
11
+ * beforeEach(() => vi.stubGlobal('fetch', accessJwksFetch(TEAM)));
12
+ * afterEach(() => vi.unstubAllGlobals());
13
+ *
14
+ * const token = await forgeAccessJwt({ email: 'alice@example.com', aud: 'aud-123', teamDomain: TEAM });
15
+ * const request = new Request('https://app.example.com/user/me', { headers: { [ACCESS_JWT_HEADER]: token } });
16
+ * ```
17
+ *
18
+ * It converges the helper AWS-AccessBridge wrote around `jose` (`SignJWT` +
19
+ * `generateKeyPair` + a stubbed `fetch`) so no repo needs `jose` in its tests.
20
+ * One key pair is generated per module instance (RSA keygen costs ~100 ms) and
21
+ * reused, which also matches how the verifier caches a JWKS per team domain.
22
+ */
23
+ /**
24
+ The header Access puts the token in.
25
+ */
26
+ export declare const ACCESS_JWT_HEADER = "cf-access-jwt-assertion";
27
+ /**
28
+ The `kid` of the shared test key.
29
+ */
30
+ export declare const ACCESS_TEST_KID = "rexezuge-test-key";
31
+ export interface ForgeAccessJwtOptions {
32
+ readonly email: string;
33
+ /**
34
+ The Access application's audience tag (`POLICY_AUD`).
35
+ */
36
+ readonly aud: string;
37
+ /**
38
+ The team domain, e.g. `https://team.example.com` (a trailing slash is ignored).
39
+ */
40
+ readonly teamDomain: string;
41
+ /**
42
+ Omitted from the token when `undefined`, which is what Access does for most IdPs.
43
+ */
44
+ readonly emailVerified?: boolean;
45
+ /**
46
+ Extra or overriding claims (`sub`, `iss`, `exp`, …), applied last.
47
+ */
48
+ readonly claims?: Readonly<Record<string, unknown>>;
49
+ /**
50
+ Lifetime in seconds from `now`; default 300. Negative mints an expired token.
51
+ */
52
+ readonly expiresInSeconds?: number;
53
+ /**
54
+ Epoch milliseconds for `iat`; default `Date.now()`.
55
+ */
56
+ readonly now?: number;
57
+ }
58
+ export interface AccessJwks {
59
+ readonly keys: readonly JsonWebKey[];
60
+ }
61
+ /**
62
+ The JWKS the forged tokens verify against.
63
+ */
64
+ export declare function accessJwks(): Promise<AccessJwks>;
65
+ /**
66
+ Mint an Access-shaped RS256 JWT.
67
+ */
68
+ export declare function forgeAccessJwt(options: ForgeAccessJwtOptions): Promise<string>;
69
+ /**
70
+ * A `fetch` that serves `<teamDomain>/cdn-cgi/access/certs` and answers 404 for
71
+ * anything else (or delegates to `fallback`). Install with `vi.stubGlobal('fetch', …)`.
72
+ */
73
+ export declare function accessJwksFetch(teamDomain: string, fallback?: typeof fetch): typeof fetch;
74
+ /**
75
+ A request carrying a forged token, for the common "authenticated call" case.
76
+ */
77
+ export declare function forgeAccessRequest(url: string, options: ForgeAccessJwtOptions, init?: RequestInit): Promise<Request>;
78
+ //# sourceMappingURL=access.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"access.d.ts","sourceRoot":"","sources":["../src/access.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH;;EAEE;AACF,eAAO,MAAM,iBAAiB,4BAA4B,CAAC;AAE3D;;EAEE;AACF,eAAO,MAAM,eAAe,sBAAsB,CAAC;AAEnD,MAAM,WAAW,qBAAqB;IACpC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB;;MAEE;IACF,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB;;MAEE;IACF,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B;;MAEE;IACF,QAAQ,CAAC,aAAa,CAAC,EAAE,OAAO,CAAC;IACjC;;MAEE;IACF,QAAQ,CAAC,MAAM,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;IACpD;;MAEE;IACF,QAAQ,CAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IACnC;;MAEE;IACF,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;CACvB;AAED,MAAM,WAAW,UAAU;IACzB,QAAQ,CAAC,IAAI,EAAE,SAAS,UAAU,EAAE,CAAC;CACtC;AAoCD;;EAEE;AACF,wBAAsB,UAAU,IAAI,OAAO,CAAC,UAAU,CAAC,CAEtD;AAED;;EAEE;AACF,wBAAsB,cAAc,CAAC,OAAO,EAAE,qBAAqB,GAAG,OAAO,CAAC,MAAM,CAAC,CAgBpF;AAED;;;GAGG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,OAAO,KAAK,GAAG,OAAO,KAAK,CAQzF;AAED;;EAEE;AACF,wBAAsB,kBAAkB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,qBAAqB,EAAE,IAAI,GAAE,WAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAI9H"}
package/dist/access.js ADDED
@@ -0,0 +1 @@
1
+ var f=Object.defineProperty;var s=(e,t)=>f(e,"name",{value:t,configurable:!0});const S="cf-access-jwt-assertion",i="rexezuge-test-key";let o;function u(){return o??=(async()=>{const e=await crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:2048,publicExponent:new Uint8Array([1,0,1]),hash:"SHA-256"},!0,["sign","verify"]),t=await crypto.subtle.exportKey("jwk",e.publicKey);return{privateKey:e.privateKey,jwks:{keys:[{...t,kid:i,alg:"RS256",use:"sig"}]}}})(),o}s(u,"keys");function l(e){let t="";for(const n of e)t+=String.fromCodePoint(n);return btoa(t).replaceAll("+","-").replaceAll("/","_").replaceAll("=","")}s(l,"base64Url");const w=s(e=>l(new TextEncoder().encode(JSON.stringify(e))),"encodeJson");function d(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return e.slice(0,t)}s(d,"trimTrailingSlashes");async function g(){return(await u()).jwks}s(g,"accessJwks");async function p(e){const{privateKey:t}=await u(),n=Math.floor((e.now??Date.now())/1e3),r={alg:"RS256",kid:i,typ:"JWT"},a={email:e.email,...e.emailVerified!==void 0&&{email_verified:e.emailVerified},iss:d(e.teamDomain.trim().toLowerCase()),aud:[e.aud],iat:n,exp:n+(e.expiresInSeconds??300),...e.claims},c=`${w(r)}.${w(a)}`,y=await crypto.subtle.sign("RSASSA-PKCS1-v1_5",t,new TextEncoder().encode(c));return`${c}.${l(new Uint8Array(y))}`}s(p,"forgeAccessJwt");function m(e,t){const n=`${d(e.trim().toLowerCase())}/cdn-cgi/access/certs`;return async(r,a)=>(r instanceof Request?r.url:String(r))===n?Response.json(await g()):t?t(r,a):new Response("not found",{status:404})}s(m,"accessJwksFetch");async function x(e,t,n={}){const r=new Headers(n.headers);return r.set(S,await p(t)),new Request(e,{...n,headers:r})}s(x,"forgeAccessRequest");export{S as ACCESS_JWT_HEADER,i as ACCESS_TEST_KID,g as accessJwks,m as accessJwksFetch,p as forgeAccessJwt,x as forgeAccessRequest};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/access.ts"],
4
+ "sourcesContent": ["/**\n * Cloudflare Access test tokens: really signed, really fetched.\n *\n * `accessAuth` (and the verifier behind it) checks a signature against the\n * team's JWKS, so a stub that skips verification tests nothing. This module\n * mints RS256 tokens with WebCrypto and serves the matching JWKS from a `fetch`\n * stub, so a test runs the production verifier end to end:\n *\n * ```ts\n * const TEAM = 'https://team.example.com';\n * beforeEach(() => vi.stubGlobal('fetch', accessJwksFetch(TEAM)));\n * afterEach(() => vi.unstubAllGlobals());\n *\n * const token = await forgeAccessJwt({ email: 'alice@example.com', aud: 'aud-123', teamDomain: TEAM });\n * const request = new Request('https://app.example.com/user/me', { headers: { [ACCESS_JWT_HEADER]: token } });\n * ```\n *\n * It converges the helper AWS-AccessBridge wrote around `jose` (`SignJWT` +\n * `generateKeyPair` + a stubbed `fetch`) so no repo needs `jose` in its tests.\n * One key pair is generated per module instance (RSA keygen costs ~100 ms) and\n * reused, which also matches how the verifier caches a JWKS per team domain.\n */\n\n/**\nThe header Access puts the token in.\n*/\nexport const ACCESS_JWT_HEADER = 'cf-access-jwt-assertion';\n\n/**\nThe `kid` of the shared test key.\n*/\nexport const ACCESS_TEST_KID = 'rexezuge-test-key';\n\nexport interface ForgeAccessJwtOptions {\n readonly email: string;\n /**\n The Access application's audience tag (`POLICY_AUD`).\n */\n readonly aud: string;\n /**\n The team domain, e.g. `https://team.example.com` (a trailing slash is ignored).\n */\n readonly teamDomain: string;\n /**\n Omitted from the token when `undefined`, which is what Access does for most IdPs.\n */\n readonly emailVerified?: boolean;\n /**\n Extra or overriding claims (`sub`, `iss`, `exp`, …), applied last.\n */\n readonly claims?: Readonly<Record<string, unknown>>;\n /**\n Lifetime in seconds from `now`; default 300. Negative mints an expired token.\n */\n readonly expiresInSeconds?: number;\n /**\n Epoch milliseconds for `iat`; default `Date.now()`.\n */\n readonly now?: number;\n}\n\nexport interface AccessJwks {\n readonly keys: readonly JsonWebKey[];\n}\n\ninterface KeyMaterial {\n readonly privateKey: CryptoKey;\n readonly jwks: AccessJwks;\n}\n\nlet keyMaterial: Promise<KeyMaterial> | undefined;\n\nfunction keys(): Promise<KeyMaterial> {\n keyMaterial ??= (async () => {\n const pair = await crypto.subtle.generateKey(\n { name: 'RSASSA-PKCS1-v1_5', modulusLength: 2048, publicExponent: new Uint8Array([1, 0, 1]), hash: 'SHA-256' },\n true,\n ['sign', 'verify'],\n );\n const publicJwk = await crypto.subtle.exportKey('jwk', pair.publicKey);\n return { privateKey: pair.privateKey, jwks: { keys: [{ ...publicJwk, kid: ACCESS_TEST_KID, alg: 'RS256', use: 'sig' }] } };\n })();\n return keyMaterial;\n}\n\nfunction base64Url(bytes: Uint8Array): string {\n let binary = '';\n for (const byte of bytes) binary += String.fromCodePoint(byte);\n return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');\n}\n\nconst encodeJson = (value: unknown): string => base64Url(new TextEncoder().encode(JSON.stringify(value)));\n\nfunction trimTrailingSlashes(value: string): string {\n let end = value.length;\n while (end > 0 && value[end - 1] === '/') end -= 1;\n return value.slice(0, end);\n}\n\n/**\nThe JWKS the forged tokens verify against.\n*/\nexport async function accessJwks(): Promise<AccessJwks> {\n return (await keys()).jwks;\n}\n\n/**\nMint an Access-shaped RS256 JWT.\n*/\nexport async function forgeAccessJwt(options: ForgeAccessJwtOptions): Promise<string> {\n const { privateKey } = await keys();\n const issuedAt = Math.floor((options.now ?? Date.now()) / 1000);\n const header = { alg: 'RS256', kid: ACCESS_TEST_KID, typ: 'JWT' };\n const payload = {\n email: options.email,\n ...(options.emailVerified !== undefined && { email_verified: options.emailVerified }),\n iss: trimTrailingSlashes(options.teamDomain.trim().toLowerCase()),\n aud: [options.aud],\n iat: issuedAt,\n exp: issuedAt + (options.expiresInSeconds ?? 300),\n ...options.claims,\n };\n const signingInput = `${encodeJson(header)}.${encodeJson(payload)}`;\n const signature = await crypto.subtle.sign('RSASSA-PKCS1-v1_5', privateKey, new TextEncoder().encode(signingInput));\n return `${signingInput}.${base64Url(new Uint8Array(signature))}`;\n}\n\n/**\n * A `fetch` that serves `<teamDomain>/cdn-cgi/access/certs` and answers 404 for\n * anything else (or delegates to `fallback`). Install with `vi.stubGlobal('fetch', …)`.\n */\nexport function accessJwksFetch(teamDomain: string, fallback?: typeof fetch): typeof fetch {\n const certs = `${trimTrailingSlashes(teamDomain.trim().toLowerCase())}/cdn-cgi/access/certs`;\n return async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n const url = input instanceof Request ? input.url : String(input);\n if (url === certs) return Response.json(await accessJwks());\n if (fallback) return fallback(input, init);\n return new Response('not found', { status: 404 });\n };\n}\n\n/**\nA request carrying a forged token, for the common \"authenticated call\" case.\n*/\nexport async function forgeAccessRequest(url: string, options: ForgeAccessJwtOptions, init: RequestInit = {}): Promise<Request> {\n const headers = new Headers(init.headers);\n headers.set(ACCESS_JWT_HEADER, await forgeAccessJwt(options));\n return new Request(url, { ...init, headers });\n}\n"],
5
+ "mappings": "+EA0BO,MAAMA,EAAoB,0BAKpBC,EAAkB,oBAuC/B,IAAIC,EAEJ,SAASC,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Url", "bytes", "binary", "byte", "encodeJson", "value", "trimTrailingSlashes", "end", "accessJwks", "forgeAccessJwt", "options", "privateKey", "issuedAt", "header", "payload", "signingInput", "signature", "accessJwksFetch", "teamDomain", "fallback", "certs", "input", "init", "forgeAccessRequest", "url", "headers"]
7
+ }
package/dist/app.d.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Helpers for driving a `createApiApp` app (or any `{ fetch }`) in a unit test,
3
+ * without a server and without importing Hono: the app is taken structurally.
4
+ *
5
+ * ```ts
6
+ * const app = createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, handlers) });
7
+ * const api = createTestApp(app, { env: { DB: db.asD1() }, headers: { [ACCESS_JWT_HEADER]: token } });
8
+ *
9
+ * const { status, body } = await api.json<{ id: string }>('/user/items/1');
10
+ * ```
11
+ */
12
+ /**
13
+ The structural shape of a Hono / chanfana app.
14
+ */
15
+ export interface FetchableApp<E = unknown> {
16
+ fetch(request: Request, env?: E, executionContext?: TestExecutionContext): Response | Promise<Response>;
17
+ }
18
+ /**
19
+ The slice of `ExecutionContext` a worker touches.
20
+ */
21
+ export interface TestExecutionContext {
22
+ waitUntil(promise: Promise<unknown>): void;
23
+ passThroughOnException(): void;
24
+ }
25
+ export interface TestAppOptions<E> {
26
+ /**
27
+ The Worker `env` handed to every request.
28
+ */
29
+ readonly env?: E;
30
+ /**
31
+ Origin the relative paths resolve against. Default `https://app.example.com`.
32
+ */
33
+ readonly baseUrl?: string;
34
+ /**
35
+ Headers added to every request (a per-call header of the same name wins).
36
+ */
37
+ readonly headers?: HeadersInit;
38
+ }
39
+ export interface JsonRequestOptions {
40
+ readonly method?: string;
41
+ /**
42
+ Serialised as JSON; sets `content-type: application/json` unless given.
43
+ */
44
+ readonly body?: unknown;
45
+ readonly headers?: HeadersInit;
46
+ }
47
+ export interface JsonResponse<T> {
48
+ readonly status: number;
49
+ readonly headers: Headers;
50
+ /**
51
+ The parsed JSON body, or `null` for an empty one (204).
52
+ */
53
+ readonly body: T;
54
+ readonly response: Response;
55
+ }
56
+ export interface TestApp {
57
+ /**
58
+ A raw request; `path` may be absolute or relative to `baseUrl`.
59
+ */
60
+ request(path: string, init?: RequestInit): Promise<Response>;
61
+ /**
62
+ A JSON round trip.
63
+ */
64
+ json<T = unknown>(path: string, options?: JsonRequestOptions): Promise<JsonResponse<T>>;
65
+ /**
66
+ Resolves when every `waitUntil` promise the app registered has settled.
67
+ */
68
+ settled(): Promise<void>;
69
+ }
70
+ /**
71
+ Wrap an app for requests. Each call gets a fresh execution context.
72
+ */
73
+ export declare function createTestApp<E = unknown>(app: FetchableApp<E>, options?: TestAppOptions<E>): TestApp;
74
+ /**
75
+ One-shot {@link TestApp.json}: `requestJson(app, '/user/me', { env })`.
76
+ */
77
+ export declare function requestJson<T = unknown, E = unknown>(app: FetchableApp<E>, path: string, options?: JsonRequestOptions & TestAppOptions<E>): Promise<JsonResponse<T>>;
78
+ //# sourceMappingURL=app.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"app.d.ts","sourceRoot":"","sources":["../src/app.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAEH;;EAEE;AACF,MAAM,WAAW,YAAY,CAAC,CAAC,GAAG,OAAO;IACvC,KAAK,CAAC,OAAO,EAAE,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC,EAAE,gBAAgB,CAAC,EAAE,oBAAoB,GAAG,QAAQ,GAAG,OAAO,CAAC,QAAQ,CAAC,CAAC;CACzG;AAED;;EAEE;AACF,MAAM,WAAW,oBAAoB;IACnC,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;IAC3C,sBAAsB,IAAI,IAAI,CAAC;CAChC;AAED,MAAM,WAAW,cAAc,CAAC,CAAC;IAC/B;;MAEE;IACF,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;IACjB;;MAEE;IACF,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B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YAAY,CAAC,CAAC,CAAC,CAAC,CAE1B"}
package/dist/app.js ADDED
@@ -0,0 +1 @@
1
+ var y=Object.defineProperty;var a=(r,e)=>y(r,"name",{value:e,configurable:!0});function i(r,e={}){const d=e.baseUrl??"https://app.example.com",u=[],p={waitUntil:a(o=>{u.push(o)},"waitUntil"),passThroughOnException:a(()=>{},"passThroughOnException")},h=a(async(o,t={})=>{const s=new Headers(e.headers);for(const[c,n]of new Headers(t.headers))s.set(c,n);return r.fetch(new Request(new URL(o,d),{...t,headers:s}),e.env,p)},"request");return{request:h,async json(o,t={}){const s=new Headers(t.headers),c=t.body!==void 0;c&&!s.has("content-type")&&s.set("content-type","application/json");const n=await h(o,{method:t.method??(c?"POST":"GET"),headers:s,...c&&{body:JSON.stringify(t.body)}}),l=await n.text();return{status:n.status,headers:n.headers,body:l===""?null:JSON.parse(l),response:n}},async settled(){await Promise.allSettled(u.splice(0))}}}a(i,"createTestApp");function f(r,e,d={}){return i(r,d).json(e,d)}a(f,"requestJson");export{i as createTestApp,f as requestJson};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/app.ts"],
4
+ "sourcesContent": ["/**\n * Helpers for driving a `createApiApp` app (or any `{ fetch }`) in a unit test,\n * without a server and without importing Hono: the app is taken structurally.\n *\n * ```ts\n * const app = createApiApp<Env>({ routes: (app) => registerContract(app, itemsContract, handlers) });\n * const api = createTestApp(app, { env: { DB: db.asD1() }, headers: { [ACCESS_JWT_HEADER]: token } });\n *\n * const { status, body } = await api.json<{ id: string }>('/user/items/1');\n * ```\n */\n\n/**\nThe structural shape of a Hono / chanfana app.\n*/\nexport interface FetchableApp<E = unknown> {\n fetch(request: Request, env?: E, executionContext?: TestExecutionContext): Response | Promise<Response>;\n}\n\n/**\nThe slice of `ExecutionContext` a worker touches.\n*/\nexport interface TestExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n passThroughOnException(): void;\n}\n\nexport interface TestAppOptions<E> {\n /**\n The Worker `env` handed to every request.\n */\n readonly env?: E;\n /**\n Origin the relative paths resolve against. Default `https://app.example.com`.\n */\n readonly baseUrl?: string;\n /**\n Headers added to every request (a per-call header of the same name wins).\n */\n readonly headers?: HeadersInit;\n}\n\nexport interface JsonRequestOptions {\n readonly method?: string;\n /**\n Serialised as JSON; sets `content-type: application/json` unless given.\n */\n readonly body?: unknown;\n readonly headers?: HeadersInit;\n}\n\nexport interface JsonResponse<T> {\n readonly status: number;\n readonly headers: Headers;\n /**\n The parsed JSON body, or `null` for an empty one (204).\n */\n readonly body: T;\n readonly response: Response;\n}\n\nexport interface TestApp {\n /**\n A raw request; `path` may be absolute or relative to `baseUrl`.\n */\n request(path: string, init?: RequestInit): Promise<Response>;\n /**\n A JSON round trip.\n */\n json<T = unknown>(path: string, options?: JsonRequestOptions): Promise<JsonResponse<T>>;\n /**\n Resolves when every `waitUntil` promise the app registered has settled.\n */\n settled(): Promise<void>;\n}\n\n/**\nWrap an app for requests. Each call gets a fresh execution context.\n*/\nexport function createTestApp<E = unknown>(app: FetchableApp<E>, options: TestAppOptions<E> = {}): TestApp {\n const baseUrl = options.baseUrl ?? 'https://app.example.com';\n const pending: Promise<unknown>[] = [];\n const executionContext: TestExecutionContext = {\n waitUntil: (promise) => {\n pending.push(promise);\n },\n passThroughOnException: () => {},\n };\n\n const request = async (path: string, init: RequestInit = {}): Promise<Response> => {\n const headers = new Headers(options.headers);\n for (const [name, value] of new Headers(init.headers)) headers.set(name, value);\n return app.fetch(new Request(new URL(path, baseUrl), { ...init, headers }), options.env, executionContext);\n };\n\n return {\n request,\n async json<T = unknown>(path: string, jsonOptions: JsonRequestOptions = {}): Promise<JsonResponse<T>> {\n const headers = new Headers(jsonOptions.headers);\n const hasBody = jsonOptions.body !== undefined;\n if (hasBody && !headers.has('content-type')) headers.set('content-type', 'application/json');\n const response = await request(path, {\n method: jsonOptions.method ?? (hasBody ? 'POST' : 'GET'),\n headers,\n ...(hasBody && { body: JSON.stringify(jsonOptions.body) }),\n });\n const text = await response.text();\n return { status: response.status, headers: response.headers, body: (text === '' ? null : JSON.parse(text)) as T, response };\n },\n async settled(): Promise<void> {\n await Promise.allSettled(pending.splice(0));\n },\n };\n}\n\n/**\nOne-shot {@link TestApp.json}: `requestJson(app, '/user/me', { env })`.\n*/\nexport function requestJson<T = unknown, E = unknown>(\n app: FetchableApp<E>,\n path: string,\n options: JsonRequestOptions & TestAppOptions<E> = {},\n): Promise<JsonResponse<T>> {\n return createTestApp(app, options).json<T>(path, options);\n}\n"],
5
+ "mappings": "+EA+EM,SAAUA,EAA2BC,EAAsBC,EAA6B,CAAA,EAAE,CAC9F,MAAMC,EAAUD,EAAQ,SAAW,0BAC7BE,EAA8B,CAAA,EAC9BC,EAAyC,CAC7C,UAAWC,EAACC,GAAW,CACrBH,EAAQ,KAAKG,CAAO,CACtB,EAFW,aAGX,uBAAwBD,EAAA,IAAK,CAAE,EAAP,2BAGpBE,EAAUF,EAAA,MAAOG,EAAcC,EAAoB,CAAA,IAAyB,CAChF,MAAMC,EAAU,IAAI,QAAQT,EAAQ,OAAO,EAC3C,SAAW,CAACU,EAAMC,CAAK,IAAK,IAAI,QAAQH,EAAK,OAAO,EAAGC,EAAQ,IAAIC,EAAMC,CAAK,EAC9E,OAAOZ,EAAI,MAAM,IAAI,QAAQ,IAAI,IAAIQ,EAAMN,CAAO,EAAG,CAAE,GAAGO,EAAM,QAAAC,CAAO,CAAE,EAAGT,EAAQ,IAAKG,CAAgB,CAC3G,EAJgB,WAMhB,MAAO,CACL,QAAAG,EACA,MAAM,KAAkBC,EAAcK,EAAkC,CAAA,EAAE,CACxE,MAAMH,EAAU,IAAI,QAAQG,EAAY,OAAO,EACzCC,EAAUD,EAAY,OAAS,OACjCC,GAAW,CAACJ,EAAQ,IAAI,cAAc,GAAGA,EAAQ,IAAI,eAAgB,kBAAkB,EAC3F,MAAMK,EAAW,MAAMR,EAAQC,EAAM,CACnC,OAAQK,EAAY,SAAWC,EAAU,OAAS,OAClD,QAAAJ,EACA,GAAII,GAAW,CAAE,KAAM,KAAK,UAAUD,EAAY,IAAI,CAAC,EACxD,EACKG,EAAO,MAAMD,EAAS,KAAI,EAChC,MAAO,CAAE,OAAQA,EAAS,OAAQ,QAASA,EAAS,QAAS,KAAOC,IAAS,GAAK,KAAO,KAAK,MAAMA,CAAI,EAAS,SAAAD,CAAQ,CAC3H,EACA,MAAM,SAAO,CACX,MAAM,QAAQ,WAAWZ,EAAQ,OAAO,CAAC,CAAC,CAC5C,EAEJ,CAlCgBE,EAAAN,EAAA,iBAuCV,SAAUkB,EACdjB,EACAQ,EACAP,EAAkD,CAAA,EAAE,CAEpD,OAAOF,EAAcC,EAAKC,CAAO,EAAE,KAAQO,EAAMP,CAAO,CAC1D,CANgBI,EAAAY,EAAA",
6
+ "names": ["createTestApp", "app", "options", "baseUrl", "pending", "executionContext", "__name", "promise", "request", "path", "init", "headers", "name", "value", "jsonOptions", "hasBody", "response", "text", "requestJson"]
7
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * The deterministic ports, re-exported so a test imports every double from one
3
+ * place. They live in `@rexezuge/shared` because production code takes the same
4
+ * `Clock` / `IdGenerator` ports.
5
+ */
6
+ export { FixedClock, FixedIdGenerator } from '@rexezuge/shared';
7
+ //# sourceMappingURL=clock.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clock.d.ts","sourceRoot":"","sources":["../src/clock.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAC"}
package/dist/clock.js ADDED
@@ -0,0 +1 @@
1
+ import{FixedClock as r,FixedIdGenerator as d}from"@rexezuge/shared";export{r as FixedClock,d as FixedIdGenerator};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/clock.ts"],
4
+ "sourcesContent": ["/**\n * The deterministic ports, re-exported so a test imports every double from one\n * place. They live in `@rexezuge/shared` because production code takes the same\n * `Clock` / `IdGenerator` ports.\n */\nexport { FixedClock, FixedIdGenerator } from '@rexezuge/shared';\n"],
5
+ "mappings": "AAKA,OAAS,cAAAA,EAAY,oBAAAC,MAAwB",
6
+ "names": ["FixedClock", "FixedIdGenerator"]
7
+ }
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Stand-in for the `cloudflare:workers` module, which has no Node equivalent.
3
+ *
4
+ * Provenance: converged from the eight copies at `test/mocks/cloudflare-workers.ts`
5
+ * (AWS-AccessBridge, CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Edge-Git,
6
+ * Edge-Sonic, Mail-Meow, Mail-Otter). All eight are the same twenty lines; the
7
+ * union is three base classes and the union exists because each repo discovered a
8
+ * missing one the hard way.
9
+ *
10
+ * ### What each source contributes
11
+ *
12
+ * - **DurableObject** — every copy. Stores `ctx` and `env` so a real DO class can
13
+ * be constructed and its lifecycle RPCs driven directly, without Miniflare.
14
+ * - **`RpcTarget`** — Durable-DAV's, and the reason is load-bearing rather than
15
+ * tidy: `dofs`' `Fs` class `extends RpcTarget`, so the module fails to evaluate
16
+ * with *"Class extends value undefined"* when the base is missing. That is a
17
+ * module-load error, not a test failure, so it surfaces as an unimportable
18
+ * `dav-store` barrel and no unit test can reach `DavRepository`. Deliberately
19
+ * empty: on the platform it marks which methods are callable across an RPC
20
+ * boundary, and nothing in a Node suite calls those through RPC. An empty base
21
+ * keeps the fake honest instead of pretending to implement dispatch.
22
+ * - **`WorkflowEntrypoint`** — Edge-Git, Edge-Sonic, Mail-Meow, Mail-Otter. A
23
+ * Workflow class extends it, so the mock must provide it or the module fails the
24
+ * same way — a **startup** error, which therefore takes down every suite that
25
+ * reaches `apps/background` for an unrelated reason. Edge-Sonic's is the shape
26
+ * kept: it stores `ctx` as well as `env`, because the failure policy under test
27
+ * in `runWorkflow` lives in a plain function precisely so it can be exercised
28
+ * without workerd, and that policy reads the execution context.
29
+ *
30
+ * ### Why the ambient types are declared here rather than imported
31
+ *
32
+ * The source repos name `DurableObjectState`, `ExecutionContext` and `Env`
33
+ * unqualified, which resolves only because `worker-configuration.d.ts` and
34
+ * `@cloudflare/workers-types` are ambient inside a Wrangler project. This copy is
35
+ * imported by the kit's own typecheck, where neither exists, so the two state
36
+ * shapes are declared locally and `TEnv` defaults to `unknown` instead of `Env`
37
+ * (Edge-Sonic's form). A local declaration shadows the ambient one inside this
38
+ * file only, so a consumer's copy typechecks against their generated types
39
+ * exactly as the original did.
40
+ *
41
+ * ### Usage in a consumer
42
+ *
43
+ * Delete the repo's own `test/mocks/cloudflare-workers.ts`: `defineUnitVitestConfig()`
44
+ * and `defineRepoVitestConfig()` alias `cloudflare:workers` to this module when
45
+ * the repo has no copy of its own. The file is a **superset** of the thirteen
46
+ * family copies (`DurableObject`, `RpcTarget`, `WorkflowEntrypoint` with a no-op
47
+ * `run`), so none of them has anything left to contribute. A repo that still
48
+ * wants a shim re-exports it:
49
+ *
50
+ * ```ts
51
+ * export * from '@rexezuge/testing/cloudflare-workers';
52
+ * ```
53
+ *
54
+ * Only what a test actually imports is exported. A symbol here that nothing
55
+ * imports is not a safety net; it is a claim that something depends on it.
56
+ */
57
+ /**
58
+ * The subset of `DurableObjectState` a Node test reaches.
59
+ *
60
+ * Declared structurally rather than imported: `id`, `storage` and `waitUntil` are
61
+ * the three a hand-driven lifecycle touches, and nothing here needs the rest.
62
+ */
63
+ export interface DurableObjectState {
64
+ readonly id: {
65
+ toString(): string;
66
+ readonly name?: string;
67
+ };
68
+ }
69
+ /**
70
+ * The subset of `ExecutionContext` a Node test reaches.
71
+ *
72
+ * `waitUntil` is present because a Workflow's `run()` is driven through it, and
73
+ * `passThroughOnException` is absent on purpose — nothing in a Node suite wires a
74
+ * request through it.
75
+ */
76
+ export interface ExecutionContext {
77
+ waitUntil(promise: Promise<unknown>): void;
78
+ }
79
+ /**
80
+ * The base class every Durable Object extends.
81
+ *
82
+ * `protected`, exactly as on the platform: a DO subclass reads `this.env` and
83
+ * `this.ctx`, and nothing outside it may.
84
+ */
85
+ declare class DurableObject<TEnv = unknown> {
86
+ protected ctx: DurableObjectState;
87
+ protected env: TEnv;
88
+ constructor(ctx: DurableObjectState, env: TEnv);
89
+ }
90
+ /**
91
+ * The base class `dofs`' `Fs` extends. See the header: an empty body is the
92
+ * whole point, and a missing class is a module-load failure.
93
+ */
94
+ declare class RpcTarget {
95
+ }
96
+ /**
97
+ * The base class every Workflow extends.
98
+ *
99
+ * `run` is a no-op that resolves `undefined` (CalDAV-Bridge's copy had it): a
100
+ * subclass overrides it, and a bare subclass can still be driven without
101
+ * throwing.
102
+ *
103
+ * `ctx` is `ExecutionContext` rather than `unknown` (Mail-Meow/Mail-Otter's
104
+ * form) because a Workflow's step code reads it; `void ctx` to silence the unused
105
+ * warning would be a lie about which of the two a subclass uses.
106
+ */
107
+ declare class WorkflowEntrypoint<TEnv = unknown> {
108
+ protected ctx: ExecutionContext;
109
+ protected env: TEnv;
110
+ constructor(ctx: ExecutionContext, env: TEnv);
111
+ run(_event: unknown, _step: unknown): Promise<unknown>;
112
+ }
113
+ export { DurableObject, RpcTarget, WorkflowEntrypoint };
114
+ //# sourceMappingURL=cloudflare-workers.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cloudflare-workers.d.ts","sourceRoot":"","sources":["../src/cloudflare-workers.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AAEH;;;;;GAKG;AACH,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,EAAE,EAAE;QAAE,QAAQ,IAAI,MAAM,CAAC;QAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;CAC7D;AAED;;;;;;GAMG;AACH,MAAM,WAAW,gBAAgB;IAC/B,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,GAAG,IAAI,CAAC;CAC5C;AAED;;;;;GAKG;AACH,cAAM,aAAa,CAAC,IAAI,GAAG,OAAO;IAChC,SAAS,CAAC,GAAG,EAAE,kBAAkB,CAAC;IAClC,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC;gBAER,GAAG,EAAE,kBAAkB,EAAE,GAAG,EAAE,IAAI;CAI/C;AAED;;;GAGG;AACH,cAAM,SAAS;CAAG;AAElB;;;;;;;;;;GAUG;AACH,cAAM,kBAAkB,CAAC,IAAI,GAAG,OAAO;IACrC,SAAS,CAAC,GAAG,EAAE,gBAAgB,CAAC;IAChC,SAAS,CAAC,GAAG,EAAE,IAAI,CAAC;gBAER,GAAG,EAAE,gBAAgB,EAAE,GAAG,EAAE,IAAI;IAK/B,GAAG,CAAC,MAAM,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC;CAGpE;AAED,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,kBAAkB,EAAE,CAAC"}
@@ -0,0 +1 @@
1
+ var s=Object.defineProperty;var n=(c,t)=>s(c,"name",{value:t,configurable:!0});class r{static{n(this,"DurableObject")}ctx;env;constructor(t,e){this.ctx=t,this.env=e}}class o{static{n(this,"RpcTarget")}}class a{static{n(this,"WorkflowEntrypoint")}ctx;env;constructor(t,e){this.ctx=t,this.env=e}async run(t,e){}}export{r as DurableObject,o as RpcTarget,a as WorkflowEntrypoint};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/cloudflare-workers.ts"],
4
+ "sourcesContent": ["/**\n * Stand-in for the `cloudflare:workers` module, which has no Node equivalent.\n *\n * Provenance: converged from the eight copies at `test/mocks/cloudflare-workers.ts`\n * (AWS-AccessBridge, CalDAV-Bridge, ChordDHT-Tracker, Durable-DAV, Edge-Git,\n * Edge-Sonic, Mail-Meow, Mail-Otter). All eight are the same twenty lines; the\n * union is three base classes and the union exists because each repo discovered a\n * missing one the hard way.\n *\n * ### What each source contributes\n *\n * - **DurableObject** — every copy. Stores `ctx` and `env` so a real DO class can\n * be constructed and its lifecycle RPCs driven directly, without Miniflare.\n * - **`RpcTarget`** — Durable-DAV's, and the reason is load-bearing rather than\n * tidy: `dofs`' `Fs` class `extends RpcTarget`, so the module fails to evaluate\n * with *\"Class extends value undefined\"* when the base is missing. That is a\n * module-load error, not a test failure, so it surfaces as an unimportable\n * `dav-store` barrel and no unit test can reach `DavRepository`. Deliberately\n * empty: on the platform it marks which methods are callable across an RPC\n * boundary, and nothing in a Node suite calls those through RPC. An empty base\n * keeps the fake honest instead of pretending to implement dispatch.\n * - **`WorkflowEntrypoint`** — Edge-Git, Edge-Sonic, Mail-Meow, Mail-Otter. A\n * Workflow class extends it, so the mock must provide it or the module fails the\n * same way — a **startup** error, which therefore takes down every suite that\n * reaches `apps/background` for an unrelated reason. Edge-Sonic's is the shape\n * kept: it stores `ctx` as well as `env`, because the failure policy under test\n * in `runWorkflow` lives in a plain function precisely so it can be exercised\n * without workerd, and that policy reads the execution context.\n *\n * ### Why the ambient types are declared here rather than imported\n *\n * The source repos name `DurableObjectState`, `ExecutionContext` and `Env`\n * unqualified, which resolves only because `worker-configuration.d.ts` and\n * `@cloudflare/workers-types` are ambient inside a Wrangler project. This copy is\n * imported by the kit's own typecheck, where neither exists, so the two state\n * shapes are declared locally and `TEnv` defaults to `unknown` instead of `Env`\n * (Edge-Sonic's form). A local declaration shadows the ambient one inside this\n * file only, so a consumer's copy typechecks against their generated types\n * exactly as the original did.\n *\n * ### Usage in a consumer\n *\n * Delete the repo's own `test/mocks/cloudflare-workers.ts`: `defineUnitVitestConfig()`\n * and `defineRepoVitestConfig()` alias `cloudflare:workers` to this module when\n * the repo has no copy of its own. The file is a **superset** of the thirteen\n * family copies (`DurableObject`, `RpcTarget`, `WorkflowEntrypoint` with a no-op\n * `run`), so none of them has anything left to contribute. A repo that still\n * wants a shim re-exports it:\n *\n * ```ts\n * export * from '@rexezuge/testing/cloudflare-workers';\n * ```\n *\n * Only what a test actually imports is exported. A symbol here that nothing\n * imports is not a safety net; it is a claim that something depends on it.\n */\n\n/**\n * The subset of `DurableObjectState` a Node test reaches.\n *\n * Declared structurally rather than imported: `id`, `storage` and `waitUntil` are\n * the three a hand-driven lifecycle touches, and nothing here needs the rest.\n */\nexport interface DurableObjectState {\n readonly id: { toString(): string; readonly name?: string };\n}\n\n/**\n * The subset of `ExecutionContext` a Node test reaches.\n *\n * `waitUntil` is present because a Workflow's `run()` is driven through it, and\n * `passThroughOnException` is absent on purpose — nothing in a Node suite wires a\n * request through it.\n */\nexport interface ExecutionContext {\n waitUntil(promise: Promise<unknown>): void;\n}\n\n/**\n * The base class every Durable Object extends.\n *\n * `protected`, exactly as on the platform: a DO subclass reads `this.env` and\n * `this.ctx`, and nothing outside it may.\n */\nclass DurableObject<TEnv = unknown> {\n protected ctx: DurableObjectState;\n protected env: TEnv;\n\n constructor(ctx: DurableObjectState, env: TEnv) {\n this.ctx = ctx;\n this.env = env;\n }\n}\n\n/**\n * The base class `dofs`' `Fs` extends. See the header: an empty body is the\n * whole point, and a missing class is a module-load failure.\n */\nclass RpcTarget {}\n\n/**\n * The base class every Workflow extends.\n *\n * `run` is a no-op that resolves `undefined` (CalDAV-Bridge's copy had it): a\n * subclass overrides it, and a bare subclass can still be driven without\n * throwing.\n *\n * `ctx` is `ExecutionContext` rather than `unknown` (Mail-Meow/Mail-Otter's\n * form) because a Workflow's step code reads it; `void ctx` to silence the unused\n * warning would be a lie about which of the two a subclass uses.\n */\nclass WorkflowEntrypoint<TEnv = unknown> {\n protected ctx: ExecutionContext;\n protected env: TEnv;\n\n constructor(ctx: ExecutionContext, env: TEnv) {\n this.ctx = ctx;\n this.env = env;\n }\n\n public async run(_event: unknown, _step: unknown): Promise<unknown> {\n return undefined;\n }\n}\n\nexport { DurableObject, RpcTarget, WorkflowEntrypoint };\n"],
5
+ "mappings": "+EAoFA,MAAMA,CAAa,CApFnB,MAoFmB,CAAAC,EAAA,sBACP,IACA,IAEV,YAAYC,EAAyBC,EAAS,CAC5C,KAAK,IAAMD,EACX,KAAK,IAAMC,CACb,EAOF,MAAMC,CAAS,CAlGf,MAkGe,CAAAH,EAAA,mBAaf,MAAMI,CAAkB,CA/GxB,MA+GwB,CAAAJ,EAAA,2BACZ,IACA,IAEV,YAAYC,EAAuBC,EAAS,CAC1C,KAAK,IAAMD,EACX,KAAK,IAAMC,CACb,CAEO,MAAM,IAAIG,EAAiBC,EAAc,CAEhD",
6
+ "names": ["DurableObject", "__name", "ctx", "env", "RpcTarget", "WorkflowEntrypoint", "_event", "_step"]
7
+ }
package/dist/d1.d.ts ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * An in-memory D1 double: a **statement-recording fake with programmable
3
+ * results**, not a SQL engine.
4
+ *
5
+ * No SQLite is available to the family's unit pool (no `better-sqlite3`, no
6
+ * `sql.js` in any repo), and the unit suites do not need one: every
7
+ * `test/dao/*.test.ts` hand-rolls the same object, `{ prepare: vi.fn().mockReturnValue(stmt) }`
8
+ * with a `bind` that returns the statement, and asserts on the SQL it was handed.
9
+ * This is that object, written once. A test that needs *real* SQL semantics
10
+ * (constraints, joins, migrations) belongs in the integration pool, where
11
+ * `createMigrationHelper` from `@rexezuge/tooling` runs the real migrations
12
+ * against workerd's D1.
13
+ *
14
+ * ```ts
15
+ * const db = createMemoryD1();
16
+ * db.when(/FROM users WHERE id = \?/, { rows: [{ id: 'u1', email: 'a@example.com' }] });
17
+ * db.when(/^DELETE FROM sessions/, { changes: 3 });
18
+ *
19
+ * const dao = new UserDAO(db.asD1<D1Database>());
20
+ * await dao.find('u1');
21
+ * expect(db.calls[0]).toMatchObject({ method: 'first', params: ['u1'] });
22
+ * ```
23
+ *
24
+ * Unmatched statements succeed with no rows and `changes: 0`, which is what an
25
+ * empty database answers, so a test programs only the statements it cares about.
26
+ */
27
+ /**
28
+ One value D1 accepts as a bound parameter.
29
+ */
30
+ export type D1Param = string | number | boolean | null | ArrayBuffer | Uint8Array;
31
+ /**
32
+ How a statement was executed.
33
+ */
34
+ export type D1Method = 'first' | 'all' | 'run' | 'raw';
35
+ /**
36
+ One executed statement, in order.
37
+ */
38
+ export interface D1Call {
39
+ readonly sql: string;
40
+ readonly params: readonly D1Param[];
41
+ readonly method: D1Method;
42
+ }
43
+ /**
44
+ The meta D1 reports; only the fields a DAO reads are modelled.
45
+ */
46
+ export interface D1Meta {
47
+ changes: number;
48
+ last_row_id: number;
49
+ rows_read: number;
50
+ rows_written: number;
51
+ duration: number;
52
+ }
53
+ /**
54
+ The result shape of `all()` / `run()`.
55
+ */
56
+ export interface D1ResultLike<T = Record<string, unknown>> {
57
+ success: boolean;
58
+ results: T[];
59
+ meta: D1Meta;
60
+ error?: string;
61
+ }
62
+ type Row = Record<string, unknown>;
63
+ /**
64
+ What a matching statement answers. Every field is optional.
65
+ */
66
+ export interface D1Answer {
67
+ /**
68
+ Rows for `all()` / `raw()`, and the source of `first()` unless `first` is given.
69
+ */
70
+ readonly rows?: readonly Row[] | ((call: D1Call) => readonly Row[]);
71
+ /**
72
+ Overrides `first()`: a row, or `null` for "no such row".
73
+ */
74
+ readonly first?: Row | null | ((call: D1Call) => Row | null);
75
+ /**
76
+ `meta.changes` for a write.
77
+ */
78
+ readonly changes?: number;
79
+ /**
80
+ `meta.last_row_id` for an insert.
81
+ */
82
+ readonly lastRowId?: number;
83
+ /**
84
+ Resolve `{ success: false, error }`, which is how D1 reports a failed write.
85
+ */
86
+ readonly error?: string;
87
+ /**
88
+ Reject with this, which is how D1 reports a transport failure.
89
+ */
90
+ readonly throws?: Error;
91
+ /**
92
+ Answer once, then fall through to earlier rules.
93
+ */
94
+ readonly once?: boolean;
95
+ }
96
+ /**
97
+ A statement matcher: substring, pattern, or predicate on the call.
98
+ */
99
+ export type D1Matcher = string | RegExp | ((call: D1Call) => boolean);
100
+ /**
101
+ A prepared statement: `bind` returns the statement itself, as the real builder does.
102
+ */
103
+ export declare class MemoryD1Statement {
104
+ private readonly db;
105
+ readonly sql: string;
106
+ private params;
107
+ constructor(db: MemoryD1, sql: string);
108
+ bind(...params: D1Param[]): this;
109
+ first<T = Row>(column?: string): Promise<T | null>;
110
+ all<T = Row>(): Promise<D1ResultLike<T>>;
111
+ run<T = Row>(): Promise<D1ResultLike<T>>;
112
+ raw<T = unknown[]>(): Promise<T[]>;
113
+ /**
114
+ Execute synchronously as `method`; used by `MemoryD1.batch` (as a `run`).
115
+ */
116
+ settle<T = Row>(method?: D1Method): D1ResultLike<T>;
117
+ }
118
+ export declare class MemoryD1 {
119
+ /**
120
+ Every executed statement, oldest first. `batch` records each member as a `run`.
121
+ */
122
+ readonly calls: D1Call[];
123
+ /**
124
+ The statements handed to each `batch()` call.
125
+ */
126
+ readonly batches: D1Call[][];
127
+ private rules;
128
+ /**
129
+ Program an answer. The most recently added matching rule wins.
130
+ */
131
+ when(matcher: D1Matcher, answer?: D1Answer): this;
132
+ /**
133
+ Forget the calls and the programmed answers.
134
+ */
135
+ reset(): void;
136
+ /**
137
+ The calls whose SQL matches.
138
+ */
139
+ callsMatching(matcher: D1Matcher): D1Call[];
140
+ prepare(sql: string): MemoryD1Statement;
141
+ batch<T = Row>(statements: readonly MemoryD1Statement[]): Promise<D1ResultLike<T>[]>;
142
+ exec(sql: string): Promise<{
143
+ count: number;
144
+ duration: number;
145
+ }>;
146
+ /**
147
+ * D1 Sessions: the same recorder, with a bookmark that advances per session.
148
+ * `createApiApp({ d1: { bookmarks } })` tests read it.
149
+ */
150
+ withSession(bookmark?: string): MemoryD1 & {
151
+ getBookmark(): string | null;
152
+ };
153
+ /**
154
+ Cast to the platform type: `db.asD1<D1Database>()` (the type is ambient in a consumer, not here).
155
+ */
156
+ asD1<T>(): T;
157
+ /**
158
+ @internal Used by {@link MemoryD1Statement}.
159
+ */
160
+ execute(sql: string, params: readonly D1Param[], method: D1Method): {
161
+ answer: D1Answer | null;
162
+ call: D1Call;
163
+ };
164
+ /**
165
+ @internal
166
+ */
167
+ rowsOf(answer: D1Answer | null, call: D1Call): readonly Row[];
168
+ /**
169
+ @internal
170
+ */
171
+ resultOf<T>(answer: D1Answer | null, call: D1Call): D1ResultLike<T>;
172
+ }
173
+ /**
174
+ A fresh, empty D1 double.
175
+ */
176
+ export declare function createMemoryD1(): MemoryD1;
177
+ export {};
178
+ //# sourceMappingURL=d1.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"d1.d.ts","sourceRoot":"","sources":["../src/d1.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAEH;;EAEE;AACF,MAAM,MAAM,OAAO,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,GAAG,WAAW,GAAG,UAAU,CAAC;AAElF;;EAEE;AACF,MAAM,MAAM,QAAQ,GAAG,OAAO,GAAG,KAAK,GAAG,KAAK,GAAG,KAAK,CAAC;AAEvD;;EAEE;AACF,MAAM,WAAW,MAAM;IACrB,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,MAAM,EAAE,SAAS,OAAO,EAAE,CAAC;IACpC,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC;CAC3B;AAED;;EAEE;AACF,MAAM,WAAW,MAAM;IACrB,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED;;EAEE;AACF,MAAM,WAAW,YAAY,CAAC,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;IACvD,OAAO,EAAE,OAAO,CAAC;IACjB,OAAO,EAAE,CAAC,EAAE,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,KAAK,GAAG,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEnC;;EAEE;AACF,MAAM,WAAW,QAAQ;IACvB;;MAEE;IACF,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,GAAG,EAAE,GA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AE,QAAQ,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,EAAE;IAK7D;;MAEE;IACF,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,QAAQ,GAAG,IAAI,EAAE,IAAI,EAAE,MAAM,GAAG,YAAY,CAAC,CAAC,CAAC;CAKpE;AAED;;EAEE;AACF,wBAAgB,cAAc,IAAI,QAAQ,CAEzC"}
package/dist/d1.js ADDED
@@ -0,0 +1 @@
1
+ var c=Object.defineProperty;var o=(e,t)=>c(e,"name",{value:t,configurable:!0});function a(e,t){return typeof e=="string"?t.sql.includes(e):typeof e=="function"?e(t):e.test(t.sql)}o(a,"matches");function h(e,t){const s=e?.changes??0;return{changes:s,last_row_id:e?.lastRowId??0,rows_read:t,rows_written:s,duration:0}}o(h,"metaFor");class f{static{o(this,"MemoryD1Statement")}db;sql;params=[];constructor(t,s){this.db=t,this.sql=s}bind(...t){return this.params=t,this}first(t){return u(()=>{const{answer:s,call:r}=this.db.execute(this.sql,this.params,"first"),n=this.db.rowsOf(s,r),i=s?.first===void 0?n[0]??null:typeof s.first=="function"?s.first(r):s.first;return i===null||t===void 0?i:i[t]})}all(){return u(()=>this.settle("all"))}run(){return u(()=>this.settle("run"))}raw(){return u(()=>{const{answer:t,call:s}=this.db.execute(this.sql,this.params,"raw");return this.db.rowsOf(t,s).map(r=>Object.values(r))})}settle(t="run"){const{answer:s,call:r}=this.db.execute(this.sql,this.params,t);return this.db.resultOf(s,r)}}function u(e){try{return Promise.resolve(e())}catch(t){return Promise.reject(t instanceof Error?t:new Error(String(t)))}}o(u,"attempt");class w{static{o(this,"MemoryD1")}calls=[];batches=[];rules=[];when(t,s={}){return this.rules.push({matcher:t,answer:s,spent:!1}),this}reset(){this.calls.length=0,this.batches.length=0,this.rules=[]}callsMatching(t){return this.calls.filter(s=>a(t,s))}prepare(t){return new f(this,t)}batch(t){const s=this.calls.length;return u(()=>{try{return t.map(r=>r.settle())}finally{this.batches.push(this.calls.slice(s))}})}exec(t){return this.calls.push({sql:t,params:[],method:"run"}),Promise.resolve({count:1,duration:0})}withSession(t){return Object.assign(Object.create(this),{getBookmark:o(()=>t??"bookmark-0","getBookmark")})}asD1(){return this}execute(t,s,r){const n={sql:t,params:[...s],method:r};this.calls.push(n);const i=this.rules.findLast(l=>!l.spent&&a(l.matcher,n));if(i?.answer.once&&(i.spent=!0),i?.answer.throws!==void 0)throw i.answer.throws;return{answer:i?.answer??null,call:n}}rowsOf(t,s){const r=t?.rows??[];return typeof r=="function"?r(s):r}resultOf(t,s){const r=this.rowsOf(t,s),n=t?.error!==void 0;return{success:!n,results:n?[]:r,meta:h(t,r.length),...n&&{error:t.error}}}}function d(){return new w}o(d,"createMemoryD1");export{w as MemoryD1,f as MemoryD1Statement,d as createMemoryD1};
package/dist/d1.js.map ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/d1.ts"],
4
+ "sourcesContent": ["/**\n * An in-memory D1 double: a **statement-recording fake with programmable\n * results**, not a SQL engine.\n *\n * No SQLite is available to the family's unit pool (no `better-sqlite3`, no\n * `sql.js` in any repo), and the unit suites do not need one: every\n * `test/dao/*.test.ts` hand-rolls the same object, `{ prepare: vi.fn().mockReturnValue(stmt) }`\n * with a `bind` that returns the statement, and asserts on the SQL it was handed.\n * This is that object, written once. A test that needs *real* SQL semantics\n * (constraints, joins, migrations) belongs in the integration pool, where\n * `createMigrationHelper` from `@rexezuge/tooling` runs the real migrations\n * against workerd's D1.\n *\n * ```ts\n * const db = createMemoryD1();\n * db.when(/FROM users WHERE id = \\?/, { rows: [{ id: 'u1', email: 'a@example.com' }] });\n * db.when(/^DELETE FROM sessions/, { changes: 3 });\n *\n * const dao = new UserDAO(db.asD1<D1Database>());\n * await dao.find('u1');\n * expect(db.calls[0]).toMatchObject({ method: 'first', params: ['u1'] });\n * ```\n *\n * Unmatched statements succeed with no rows and `changes: 0`, which is what an\n * empty database answers, so a test programs only the statements it cares about.\n */\n\n/**\nOne value D1 accepts as a bound parameter.\n*/\nexport type D1Param = string | number | boolean | null | ArrayBuffer | Uint8Array;\n\n/**\nHow a statement was executed.\n*/\nexport type D1Method = 'first' | 'all' | 'run' | 'raw';\n\n/**\nOne executed statement, in order.\n*/\nexport interface D1Call {\n readonly sql: string;\n readonly params: readonly D1Param[];\n readonly method: D1Method;\n}\n\n/**\nThe meta D1 reports; only the fields a DAO reads are modelled.\n*/\nexport interface D1Meta {\n changes: number;\n last_row_id: number;\n rows_read: number;\n rows_written: number;\n duration: number;\n}\n\n/**\nThe result shape of `all()` / `run()`.\n*/\nexport interface D1ResultLike<T = Record<string, unknown>> {\n success: boolean;\n results: T[];\n meta: D1Meta;\n error?: string;\n}\n\ntype Row = Record<string, unknown>;\n\n/**\nWhat a matching statement answers. Every field is optional.\n*/\nexport interface D1Answer {\n /**\n Rows for `all()` / `raw()`, and the source of `first()` unless `first` is given.\n */\n readonly rows?: readonly Row[] | ((call: D1Call) => readonly Row[]);\n /**\n Overrides `first()`: a row, or `null` for \"no such row\".\n */\n readonly first?: Row | null | ((call: D1Call) => Row | null);\n /**\n `meta.changes` for a write.\n */\n readonly changes?: number;\n /**\n `meta.last_row_id` for an insert.\n */\n readonly lastRowId?: number;\n /**\n Resolve `{ success: false, error }`, which is how D1 reports a failed write.\n */\n readonly error?: string;\n /**\n Reject with this, which is how D1 reports a transport failure.\n */\n readonly throws?: Error;\n /**\n Answer once, then fall through to earlier rules.\n */\n readonly once?: boolean;\n}\n\n/**\nA statement matcher: substring, pattern, or predicate on the call.\n*/\nexport type D1Matcher = string | RegExp | ((call: D1Call) => boolean);\n\ninterface Rule {\n readonly matcher: D1Matcher;\n readonly answer: D1Answer;\n spent: boolean;\n}\n\nfunction matches(matcher: D1Matcher, call: D1Call): boolean {\n if (typeof matcher === 'string') return call.sql.includes(matcher);\n if (typeof matcher === 'function') return matcher(call);\n return matcher.test(call.sql);\n}\n\nfunction metaFor(answer: D1Answer | null, rows: number): D1Meta {\n const changes = answer?.changes ?? 0;\n return { changes, last_row_id: answer?.lastRowId ?? 0, rows_read: rows, rows_written: changes, duration: 0 };\n}\n\n/**\nA prepared statement: `bind` returns the statement itself, as the real builder does.\n*/\nexport class MemoryD1Statement {\n private params: D1Param[] = [];\n\n constructor(\n private readonly db: MemoryD1,\n readonly sql: string,\n ) {}\n\n bind(...params: D1Param[]): this {\n this.params = params;\n return this;\n }\n\n first<T = Row>(column?: string): Promise<T | null> {\n return attempt(() => {\n const { answer, call } = this.db.execute(this.sql, this.params, 'first');\n const rows = this.db.rowsOf(answer, call);\n const row = answer?.first === undefined ? (rows[0] ?? null) : typeof answer.first === 'function' ? answer.first(call) : answer.first;\n if (row === null || column === undefined) return row as T | null;\n return row[column] as T;\n });\n }\n\n all<T = Row>(): Promise<D1ResultLike<T>> {\n return attempt(() => this.settle<T>('all'));\n }\n\n run<T = Row>(): Promise<D1ResultLike<T>> {\n return attempt(() => this.settle<T>('run'));\n }\n\n raw<T = unknown[]>(): Promise<T[]> {\n return attempt(() => {\n const { answer, call } = this.db.execute(this.sql, this.params, 'raw');\n return this.db.rowsOf(answer, call).map((row) => Object.values(row)) as T[];\n });\n }\n\n /**\n Execute synchronously as `method`; used by `MemoryD1.batch` (as a `run`).\n */\n settle<T = Row>(method: D1Method = 'run'): D1ResultLike<T> {\n const { answer, call } = this.db.execute(this.sql, this.params, method);\n return this.db.resultOf<T>(answer, call);\n }\n}\n\n/**\nA programmed `throws` rejects the returned promise rather than throwing at the call site, as D1 does.\n*/\nfunction attempt<T>(body: () => T): Promise<T> {\n try {\n return Promise.resolve(body());\n } catch (error) {\n return Promise.reject(error instanceof Error ? error : new Error(String(error)));\n }\n}\n\nexport class MemoryD1 {\n /**\n Every executed statement, oldest first. `batch` records each member as a `run`.\n */\n readonly calls: D1Call[] = [];\n /**\n The statements handed to each `batch()` call.\n */\n readonly batches: D1Call[][] = [];\n private rules: Rule[] = [];\n\n /**\n Program an answer. The most recently added matching rule wins.\n */\n when(matcher: D1Matcher, answer: D1Answer = {}): this {\n this.rules.push({ matcher, answer, spent: false });\n return this;\n }\n\n /**\n Forget the calls and the programmed answers.\n */\n reset(): void {\n this.calls.length = 0;\n this.batches.length = 0;\n this.rules = [];\n }\n\n /**\n The calls whose SQL matches.\n */\n callsMatching(matcher: D1Matcher): D1Call[] {\n return this.calls.filter((call) => matches(matcher, call));\n }\n\n prepare(sql: string): MemoryD1Statement {\n return new MemoryD1Statement(this, sql);\n }\n\n batch<T = Row>(statements: readonly MemoryD1Statement[]): Promise<D1ResultLike<T>[]> {\n const before = this.calls.length;\n return attempt(() => {\n try {\n return statements.map((statement) => statement.settle<T>());\n } finally {\n this.batches.push(this.calls.slice(before));\n }\n });\n }\n\n exec(sql: string): Promise<{ count: number; duration: number }> {\n this.calls.push({ sql, params: [], method: 'run' });\n return Promise.resolve({ count: 1, duration: 0 });\n }\n\n /**\n * D1 Sessions: the same recorder, with a bookmark that advances per session.\n * `createApiApp({ d1: { bookmarks } })` tests read it.\n */\n withSession(bookmark?: string): MemoryD1 & { getBookmark(): string | null } {\n const session = Object.assign(Object.create(this) as MemoryD1, { getBookmark: () => bookmark ?? 'bookmark-0' });\n return session;\n }\n\n /**\n Cast to the platform type: `db.asD1<D1Database>()` (the type is ambient in a consumer, not here).\n */\n asD1<T>(): T {\n return this as unknown as T;\n }\n\n /**\n @internal Used by {@link MemoryD1Statement}.\n */\n execute(sql: string, params: readonly D1Param[], method: D1Method): { answer: D1Answer | null; call: D1Call } {\n const call: D1Call = { sql, params: [...params], method };\n this.calls.push(call);\n const rule = this.rules.findLast((candidate) => !candidate.spent && matches(candidate.matcher, call));\n if (rule?.answer.once) rule.spent = true;\n if (rule?.answer.throws !== undefined) throw rule.answer.throws;\n return { answer: rule?.answer ?? null, call };\n }\n\n /**\n @internal\n */\n rowsOf(answer: D1Answer | null, call: D1Call): readonly Row[] {\n const rows = answer?.rows ?? [];\n return typeof rows === 'function' ? rows(call) : rows;\n }\n\n /**\n @internal\n */\n resultOf<T>(answer: D1Answer | null, call: D1Call): D1ResultLike<T> {\n const rows = this.rowsOf(answer, call) as T[];\n const failed = answer?.error !== undefined;\n return { success: !failed, results: failed ? [] : rows, meta: metaFor(answer, rows.length), ...(failed && { error: answer.error }) };\n }\n}\n\n/**\nA fresh, empty D1 double.\n*/\nexport function createMemoryD1(): MemoryD1 {\n return new MemoryD1();\n}\n"],
5
+ "mappings": "+EAkHA,SAASA,EAAQC,EAAoBC,EAAY,CAC/C,OAAI,OAAOD,GAAY,SAAiBC,EAAK,IAAI,SAASD,CAAO,EAC7D,OAAOA,GAAY,WAAmBA,EAAQC,CAAI,EAC/CD,EAAQ,KAAKC,EAAK,GAAG,CAC9B,CAJSC,EAAAH,EAAA,WAMT,SAASI,EAAQC,EAAyBC,EAAY,CACpD,MAAMC,EAAUF,GAAQ,SAAW,EACnC,MAAO,CAAE,QAAAE,EAAS,YAAaF,GAAQ,WAAa,EAAG,UAAWC,EAAM,aAAcC,EAAS,SAAU,CAAC,CAC5G,CAHSJ,EAAAC,EAAA,WAQH,MAAOI,CAAiB,CAhI9B,MAgI8B,CAAAL,EAAA,0BAIT,GACR,IAJH,OAAoB,CAAA,EAE5B,YACmBM,EACRC,EAAW,CADH,KAAA,GAAAD,EACR,KAAA,IAAAC,CACR,CAEH,QAAQC,EAAiB,CACvB,YAAK,OAASA,EACP,IACT,CAEA,MAAeC,EAAe,CAC5B,OAAOC,EAAQ,IAAK,CAClB,KAAM,CAAE,OAAAR,EAAQ,KAAAH,CAAI,EAAK,KAAK,GAAG,QAAQ,KAAK,IAAK,KAAK,OAAQ,OAAO,EACjEI,EAAO,KAAK,GAAG,OAAOD,EAAQH,CAAI,EAClCY,EAAMT,GAAQ,QAAU,OAAaC,EAAK,CAAC,GAAK,KAAQ,OAAOD,EAAO,OAAU,WAAaA,EAAO,MAAMH,CAAI,EAAIG,EAAO,MAC/H,OAAIS,IAAQ,MAAQF,IAAW,OAAkBE,EAC1CA,EAAIF,CAAM,CACnB,CAAC,CACH,CA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jC,MAAO,CAAE,QAAS,CAACoB,EAAQ,QAASA,EAAS,CAAA,EAAKnB,EAAM,KAAMF,EAAQC,EAAQC,EAAK,MAAM,EAAG,GAAImB,GAAU,CAAE,MAAOpB,EAAO,KAAK,CAAG,CACpI,EAMI,SAAUqB,GAAc,CAC5B,OAAO,IAAIR,CACb,CAFgBf,EAAAuB,EAAA",
6
+ "names": ["matches", "matcher", "call", "__name", "metaFor", "answer", "rows", "changes", "MemoryD1Statement", "db", "sql", "params", "column", "attempt", "row", "method", "body", "error", "MemoryD1", "statements", "before", "statement", "bookmark", "rule", "candidate", "failed", "createMemoryD1"]
7
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * `@rexezuge/testing`: the family's test doubles, in one dev-only package.
3
+ *
4
+ * | Export | What it replaces in a consumer |
5
+ * | ------------------------------------- | -------------------------------------------------------------- |
6
+ * | `DurableObject`, `RpcTarget`, `WorkflowEntrypoint` | `test/mocks/cloudflare-workers.ts` (13 copies) |
7
+ * | `createMemoryD1` | the hand-rolled `{ prepare: vi.fn() … }` D1 object |
8
+ * | `createMemoryKv` | hand-rolled `KVNamespace` maps |
9
+ * | `FixedClock`, `FixedIdGenerator` | local clocks and id queues |
10
+ * | `forgeAccessJwt`, `accessJwksFetch` | `jose` `SignJWT` + a stubbed JWKS `fetch` in auth tests |
11
+ * | `createTestApp`, `requestJson` | `app.fetch(new Request(…), env, ctx)` boilerplate |
12
+ * | `resetAllForTests` | the three `reset*ForTests` seams, called together |
13
+ *
14
+ * The `/testing` seams of `@rexezuge/http` and `@rexezuge/runtime` are
15
+ * re-exported, so a suite has one import for every reset.
16
+ */
17
+ export { DurableObject, RpcTarget, WorkflowEntrypoint } from './cloudflare-workers.ts';
18
+ export type { DurableObjectState, ExecutionContext } from './cloudflare-workers.ts';
19
+ export { createMemoryD1, MemoryD1, MemoryD1Statement } from './d1.ts';
20
+ export type { D1Answer, D1Call, D1Matcher, D1Meta, D1Method, D1Param, D1ResultLike } from './d1.ts';
21
+ export { createMemoryKv, MemoryKv } from './kv.ts';
22
+ export type { MemoryKvOptions, MemoryKvPutOptions } from './kv.ts';
23
+ export { FixedClock, FixedIdGenerator } from './clock.ts';
24
+ export { ACCESS_JWT_HEADER, ACCESS_TEST_KID, accessJwks, accessJwksFetch, forgeAccessJwt, forgeAccessRequest } from './access.ts';
25
+ export type { AccessJwks, ForgeAccessJwtOptions } from './access.ts';
26
+ export { createTestApp, requestJson } from './app.ts';
27
+ export type { FetchableApp, JsonRequestOptions, JsonResponse, TestApp, TestAppOptions, TestExecutionContext } from './app.ts';
28
+ export { resetAllForTests } from './reset.ts';
29
+ export { getRateLimitBucketCountForTests, resetRateLimitForTests } from '@rexezuge/http/testing';
30
+ export { resetBreakerForTests, resetLogLevelForTests } from '@rexezuge/runtime/testing';
31
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,aAAa,EAAE,SAAS,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AACvF,YAAY,EAAE,kBAAkB,EAAE,gBAAgB,EAAE,MAAM,yBAAyB,CAAC;AAEpF,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,iBAAiB,EAAE,MAAM,SAAS,CAAC;AACtE,YAAY,EAAE,QAAQ,EAAE,MAAM,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAEpG,OAAO,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnD,YAAY,EAAE,eAAe,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAEnE,OAAO,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAE1D,OAAO,EAAE,iBAAiB,EAAE,eAAe,EAAE,UAAU,EAAE,eAAe,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAClI,YAAY,EAAE,UAAU,EAAE,qBAAqB,EAAE,MAAM,aAAa,CAAC;AAErE,OAAO,EAAE,aAAa,EAAE,WAAW,EAAE,MAAM,UAAU,CAAC;AACtD,YAAY,EAAE,YAAY,EAAE,kBAAkB,EAAE,YAAY,EAAE,OAAO,EAAE,cAAc,EAAE,oBAAoB,EAAE,MAAM,UAAU,CAAC;AAE9H,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAC9C,OAAO,EAAE,+BAA+B,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AACjG,OAAO,EAAE,oBAAoB,EAAE,qBAAqB,EAAE,MAAM,2BAA2B,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1 @@
1
+ import{DurableObject as t,RpcTarget as o,WorkflowEntrypoint as s}from"./cloudflare-workers.js";import{createMemoryD1 as c,MemoryD1 as p,MemoryD1Statement as a}from"./d1.js";import{createMemoryKv as x,MemoryKv as T}from"./kv.js";import{FixedClock as i,FixedIdGenerator as A}from"./clock.js";import{ACCESS_JWT_HEADER as l,ACCESS_TEST_KID as n,accessJwks as y,accessJwksFetch as C,forgeAccessJwt as D,forgeAccessRequest as E}from"./access.js";import{createTestApp as g,requestJson as u}from"./app.js";import{resetAllForTests as M}from"./reset.js";import{getRateLimitBucketCountForTests as w,resetRateLimitForTests as L}from"@rexezuge/http/testing";import{resetBreakerForTests as d,resetLogLevelForTests as v}from"@rexezuge/runtime/testing";export{l as ACCESS_JWT_HEADER,n as ACCESS_TEST_KID,t as DurableObject,i as FixedClock,A as FixedIdGenerator,p as MemoryD1,a as MemoryD1Statement,T as MemoryKv,o as RpcTarget,s as WorkflowEntrypoint,y as accessJwks,C as accessJwksFetch,c as createMemoryD1,x as createMemoryKv,g as createTestApp,D as forgeAccessJwt,E as forgeAccessRequest,w as getRateLimitBucketCountForTests,u as requestJson,M as resetAllForTests,d as resetBreakerForTests,v as resetLogLevelForTests,L as resetRateLimitForTests};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/index.ts"],
4
+ "sourcesContent": ["/**\n * `@rexezuge/testing`: the family's test doubles, in one dev-only package.\n *\n * | Export | What it replaces in a consumer |\n * | ------------------------------------- | -------------------------------------------------------------- |\n * | `DurableObject`, `RpcTarget`, `WorkflowEntrypoint` | `test/mocks/cloudflare-workers.ts` (13 copies) |\n * | `createMemoryD1` | the hand-rolled `{ prepare: vi.fn() … }` D1 object |\n * | `createMemoryKv` | hand-rolled `KVNamespace` maps |\n * | `FixedClock`, `FixedIdGenerator` | local clocks and id queues |\n * | `forgeAccessJwt`, `accessJwksFetch` | `jose` `SignJWT` + a stubbed JWKS `fetch` in auth tests |\n * | `createTestApp`, `requestJson` | `app.fetch(new Request(…), env, ctx)` boilerplate |\n * | `resetAllForTests` | the three `reset*ForTests` seams, called together |\n *\n * The `/testing` seams of `@rexezuge/http` and `@rexezuge/runtime` are\n * re-exported, so a suite has one import for every reset.\n */\n\nexport { DurableObject, RpcTarget, WorkflowEntrypoint } from './cloudflare-workers.ts';\nexport type { DurableObjectState, ExecutionContext } from './cloudflare-workers.ts';\n\nexport { createMemoryD1, MemoryD1, MemoryD1Statement } from './d1.ts';\nexport type { D1Answer, D1Call, D1Matcher, D1Meta, D1Method, D1Param, D1ResultLike } from './d1.ts';\n\nexport { createMemoryKv, MemoryKv } from './kv.ts';\nexport type { MemoryKvOptions, MemoryKvPutOptions } from './kv.ts';\n\nexport { FixedClock, FixedIdGenerator } from './clock.ts';\n\nexport { ACCESS_JWT_HEADER, ACCESS_TEST_KID, accessJwks, accessJwksFetch, forgeAccessJwt, forgeAccessRequest } from './access.ts';\nexport type { AccessJwks, ForgeAccessJwtOptions } from './access.ts';\n\nexport { createTestApp, requestJson } from './app.ts';\nexport type { FetchableApp, JsonRequestOptions, JsonResponse, TestApp, TestAppOptions, TestExecutionContext } from './app.ts';\n\nexport { resetAllForTests } from './reset.ts';\nexport { getRateLimitBucketCountForTests, resetRateLimitForTests } from '@rexezuge/http/testing';\nexport { resetBreakerForTests, resetLogLevelForTests } from '@rexezuge/runtime/testing';\n"],
5
+ "mappings": "AAiBA,OAAS,iBAAAA,EAAe,aAAAC,EAAW,sBAAAC,MAA0B,0BAG7D,OAAS,kBAAAC,EAAgB,YAAAC,EAAU,qBAAAC,MAAyB,UAG5D,OAAS,kBAAAC,EAAgB,YAAAC,MAAgB,UAGzC,OAAS,cAAAC,EAAY,oBAAAC,MAAwB,aAE7C,OAAS,qBAAAC,EAAmB,mBAAAC,EAAiB,cAAAC,EAAY,mBAAAC,EAAiB,kBAAAC,EAAgB,sBAAAC,MAA0B,cAGpH,OAAS,iBAAAC,EAAe,eAAAC,MAAmB,WAG3C,OAAS,oBAAAC,MAAwB,aACjC,OAAS,mCAAAC,EAAiC,0BAAAC,MAA8B,yBACxE,OAAS,wBAAAC,EAAsB,yBAAAC,MAA6B",
6
+ "names": ["DurableObject", "RpcTarget", "WorkflowEntrypoint", "createMemoryD1", "MemoryD1", "MemoryD1Statement", "createMemoryKv", "MemoryKv", "FixedClock", "FixedIdGenerator", "ACCESS_JWT_HEADER", "ACCESS_TEST_KID", "accessJwks", "accessJwksFetch", "forgeAccessJwt", "forgeAccessRequest", "createTestApp", "requestJson", "resetAllForTests", "getRateLimitBucketCountForTests", "resetRateLimitForTests", "resetBreakerForTests", "resetLogLevelForTests"]
7
+ }
package/dist/kv.d.ts ADDED
@@ -0,0 +1,84 @@
1
+ /**
2
+ * An in-memory KV namespace: `get` (text, json, arrayBuffer), `getWithMetadata`,
3
+ * `put` with `expirationTtl` / `expiration` / `metadata`, `delete` and a
4
+ * prefix-paged `list`. It satisfies `@rexezuge/runtime`'s `KvNamespaceLike`
5
+ * structurally, so `new KvCache(createMemoryKv())` works as-is.
6
+ *
7
+ * Time is injected: pass `now` (milliseconds, e.g. `() => clock.now()`) and an
8
+ * entry past its expiry reads as absent, so a TTL test advances the clock rather
9
+ * than sleeping.
10
+ */
11
+ export interface MemoryKvOptions {
12
+ /**
13
+ Epoch milliseconds; defaults to `Date.now`.
14
+ */
15
+ readonly now?: () => number;
16
+ }
17
+ export interface MemoryKvPutOptions {
18
+ /**
19
+ Seconds from now.
20
+ */
21
+ readonly expirationTtl?: number;
22
+ /**
23
+ Absolute epoch seconds.
24
+ */
25
+ readonly expiration?: number;
26
+ readonly metadata?: unknown;
27
+ }
28
+ export declare class MemoryKv {
29
+ private readonly entries;
30
+ private readonly now;
31
+ constructor(options?: MemoryKvOptions);
32
+ /**
33
+ Live (unexpired) keys, sorted, for assertions.
34
+ */
35
+ keys(): string[];
36
+ /**
37
+ Drop everything.
38
+ */
39
+ clear(): void;
40
+ get(key: string): Promise<string | null>;
41
+ get(key: string, type: 'text'): Promise<string | null>;
42
+ get<T = unknown>(key: string, type: 'json' | {
43
+ type: 'json';
44
+ }): Promise<T | null>;
45
+ get(key: string, type: 'arrayBuffer'): Promise<ArrayBuffer | null>;
46
+ getWithMetadata<M = unknown>(key: string, type: 'arrayBuffer'): Promise<{
47
+ value: ArrayBuffer | null;
48
+ metadata: M | null;
49
+ }>;
50
+ getWithMetadata<M = unknown>(key: string, type?: 'text'): Promise<{
51
+ value: string | null;
52
+ metadata: M | null;
53
+ }>;
54
+ getWithMetadata<T = unknown, M = unknown>(key: string, type: 'json'): Promise<{
55
+ value: T | null;
56
+ metadata: M | null;
57
+ }>;
58
+ put(key: string, value: string | ArrayBuffer, options?: MemoryKvPutOptions): Promise<void>;
59
+ delete(key: string): Promise<void>;
60
+ list(options?: {
61
+ prefix?: string;
62
+ limit?: number;
63
+ cursor?: string;
64
+ }): Promise<{
65
+ keys: {
66
+ name: string;
67
+ expiration?: number;
68
+ metadata?: unknown;
69
+ }[];
70
+ list_complete: boolean;
71
+ cursor?: string;
72
+ }>;
73
+ /**
74
+ Cast to the platform type: `kv.asKv<KVNamespace>()`.
75
+ */
76
+ asKv<T>(): T;
77
+ private read;
78
+ private live;
79
+ }
80
+ /**
81
+ A fresh, empty KV namespace.
82
+ */
83
+ export declare function createMemoryKv(options?: MemoryKvOptions): MemoryKv;
84
+ //# sourceMappingURL=kv.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kv.d.ts","sourceRoot":"","sources":["../src/kv.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,MAAM,WAAW,eAAe;IAC9B;;MAEE;IACF,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CAC7B;AAED,MAAM,WAAW,kBAAkB;IACjC;;MAEE;IACF,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAChC;;MAEE;IACF,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAC;IAC7B,QAAQ,CAAC,QAAQ,CAAC,EAAE,OAAO,CAAC;CAC7B;AAqBD,qBAAa,QAAQ;IACnB,OAAO,CAAC,QAAQ,CAAC,OAAO,CAA4B;IACpD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAe;gBAEvB,OAAO,GAAE,eAAoB;IAIzC;;MAEE;IACF,IAAI,IAAI,MAAM,EAAE;IAIhB;;MAEE;IACF,KAAK,IAAI,IAAI;IAIb,GAAG,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IACxC,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC;IACtD,GAAG,CAAC,CAAC,GAAG,OAAO,EAAE,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC;IACjF,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC;IAMlE,eAAe,CAAC,CAAC,GAAG,OAAO,EAAE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,CAAC,IAAI;IAUZ,OAAO,CAAC,IAAI;CAQb;AAED;;EAEE;AACF,wBAAgB,cAAc,CAAC,OAAO,GAAE,eAAoB,GAAG,QAAQ,CAEtE"}
package/dist/kv.js ADDED
@@ -0,0 +1 @@
1
+ var m=Object.defineProperty;var i=(n,e)=>m(n,"name",{value:e,configurable:!0});function c(n){return typeof n=="string"?n:n?.type??"text"}i(c,"asType");function d(n,e){if(e==="arrayBuffer")return typeof n=="string"?new TextEncoder().encode(n).buffer:n.slice(0);const t=typeof n=="string"?n:new TextDecoder().decode(n);return e==="json"?JSON.parse(t):t}i(d,"decode");class h{static{i(this,"MemoryKv")}entries=new Map;now;constructor(e={}){this.now=e.now??Date.now}keys(){return this.live().map(([e])=>e)}clear(){this.entries.clear()}get(e,t){const r=this.read(e);return Promise.resolve(r?d(r.value,c(t)):null)}getWithMetadata(e,t){const r=this.read(e);return Promise.resolve({value:r?d(r.value,c(t)):null,metadata:r?.metadata??null})}put(e,t,r={}){let s=null;return r.expirationTtl!==void 0?s=this.now()+r.expirationTtl*1e3:r.expiration!==void 0&&(s=r.expiration*1e3),this.entries.set(e,{value:t,expiresAtMs:s,metadata:r.metadata??null}),Promise.resolve()}delete(e){return this.entries.delete(e),Promise.resolve()}list(e={}){const t=e.prefix??"",r=e.limit??1e3,s=e.cursor===void 0?0:Number(e.cursor),o=this.live().filter(([l])=>l.startsWith(t)),f=o.slice(s,s+r),u=s+r>=o.length;return Promise.resolve({keys:f.map(([l,a])=>({name:l,...a.expiresAtMs!==null&&{expiration:Math.floor(a.expiresAtMs/1e3)},...a.metadata!==null&&{metadata:a.metadata}})),list_complete:u,...!u&&{cursor:String(s+r)}})}asKv(){return this}read(e){const t=this.entries.get(e);return t?t.expiresAtMs!==null&&t.expiresAtMs<=this.now()?(this.entries.delete(e),null):t:null}live(){return[...this.entries.keys()].sort((e,t)=>e.localeCompare(t)).flatMap(e=>{const t=this.read(e);return t?[[e,t]]:[]})}}function p(n={}){return new h(n)}i(p,"createMemoryKv");export{h as MemoryKv,p as createMemoryKv};
package/dist/kv.js.map ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/kv.ts"],
4
+ "sourcesContent": ["/**\n * An in-memory KV namespace: `get` (text, json, arrayBuffer), `getWithMetadata`,\n * `put` with `expirationTtl` / `expiration` / `metadata`, `delete` and a\n * prefix-paged `list`. It satisfies `@rexezuge/runtime`'s `KvNamespaceLike`\n * structurally, so `new KvCache(createMemoryKv())` works as-is.\n *\n * Time is injected: pass `now` (milliseconds, e.g. `() => clock.now()`) and an\n * entry past its expiry reads as absent, so a TTL test advances the clock rather\n * than sleeping.\n */\n\nexport interface MemoryKvOptions {\n /**\n Epoch milliseconds; defaults to `Date.now`.\n */\n readonly now?: () => number;\n}\n\nexport interface MemoryKvPutOptions {\n /**\n Seconds from now.\n */\n readonly expirationTtl?: number;\n /**\n Absolute epoch seconds.\n */\n readonly expiration?: number;\n readonly metadata?: unknown;\n}\n\ninterface Entry {\n value: string | ArrayBuffer;\n expiresAtMs: number | null;\n metadata: unknown;\n}\n\ntype KvType = 'text' | 'json' | 'arrayBuffer';\n\nfunction asType(typeOrOptions: KvType | { type?: KvType } | undefined): KvType {\n if (typeof typeOrOptions === 'string') return typeOrOptions;\n return typeOrOptions?.type ?? 'text';\n}\n\nfunction decode(value: string | ArrayBuffer, type: KvType): unknown {\n if (type === 'arrayBuffer') return typeof value === 'string' ? new TextEncoder().encode(value).buffer : value.slice(0);\n const text = typeof value === 'string' ? value : new TextDecoder().decode(value);\n return type === 'json' ? JSON.parse(text) : text;\n}\n\nexport class MemoryKv {\n private readonly entries = new Map<string, Entry>();\n private readonly now: () => number;\n\n constructor(options: MemoryKvOptions = {}) {\n this.now = options.now ?? Date.now;\n }\n\n /**\n Live (unexpired) keys, sorted, for assertions.\n */\n keys(): string[] {\n return this.live().map(([key]) => key);\n }\n\n /**\n Drop everything.\n */\n clear(): void {\n this.entries.clear();\n }\n\n get(key: string): Promise<string | null>;\n get(key: string, type: 'text'): Promise<string | null>;\n get<T = unknown>(key: string, type: 'json' | { type: 'json' }): Promise<T | null>;\n get(key: string, type: 'arrayBuffer'): Promise<ArrayBuffer | null>;\n get(key: string, type?: KvType | { type?: KvType }): Promise<unknown> {\n const entry = this.read(key);\n return Promise.resolve(entry ? decode(entry.value, asType(type)) : null);\n }\n\n getWithMetadata<M = unknown>(key: string, type: 'arrayBuffer'): Promise<{ value: ArrayBuffer | null; metadata: M | null }>;\n getWithMetadata<M = unknown>(key: string, type?: 'text'): Promise<{ value: string | null; metadata: M | null }>;\n getWithMetadata<T = unknown, M = unknown>(key: string, type: 'json'): Promise<{ value: T | null; metadata: M | null }>;\n getWithMetadata(key: string, type?: KvType | { type?: KvType }): Promise<{ value: unknown; metadata: unknown }> {\n const entry = this.read(key);\n return Promise.resolve({ value: entry ? decode(entry.value, asType(type)) : null, metadata: entry?.metadata ?? null });\n }\n\n put(key: string, value: string | ArrayBuffer, options: MemoryKvPutOptions = {}): Promise<void> {\n let expiresAtMs: number | null = null;\n if (options.expirationTtl !== undefined) expiresAtMs = this.now() + options.expirationTtl * 1000;\n else if (options.expiration !== undefined) expiresAtMs = options.expiration * 1000;\n this.entries.set(key, { value, expiresAtMs, metadata: options.metadata ?? null });\n return Promise.resolve();\n }\n\n delete(key: string): Promise<void> {\n this.entries.delete(key);\n return Promise.resolve();\n }\n\n list(options: { prefix?: string; limit?: number; cursor?: string } = {}): Promise<{\n keys: { name: string; expiration?: number; metadata?: unknown }[];\n list_complete: boolean;\n cursor?: string;\n }> {\n const prefix = options.prefix ?? '';\n const limit = options.limit ?? 1000;\n const start = options.cursor === undefined ? 0 : Number(options.cursor);\n const matching = this.live().filter(([key]) => key.startsWith(prefix));\n const page = matching.slice(start, start + limit);\n const complete = start + limit >= matching.length;\n return Promise.resolve({\n keys: page.map(([name, entry]) => ({\n name,\n ...(entry.expiresAtMs !== null && { expiration: Math.floor(entry.expiresAtMs / 1000) }),\n ...(entry.metadata !== null && { metadata: entry.metadata }),\n })),\n list_complete: complete,\n ...(!complete && { cursor: String(start + limit) }),\n });\n }\n\n /**\n Cast to the platform type: `kv.asKv<KVNamespace>()`.\n */\n asKv<T>(): T {\n return this as unknown as T;\n }\n\n private read(key: string): Entry | null {\n const entry = this.entries.get(key);\n if (!entry) return null;\n if (entry.expiresAtMs !== null && entry.expiresAtMs <= this.now()) {\n this.entries.delete(key);\n return null;\n }\n return entry;\n }\n\n private live(): [string, Entry][] {\n return [...this.entries.keys()]\n .sort((a, b) => a.localeCompare(b))\n .flatMap((key) => {\n const entry = this.read(key);\n return entry ? [[key, entry] as [string, Entry]] : [];\n });\n }\n}\n\n/**\nA fresh, empty KV namespace.\n*/\nexport function createMemoryKv(options: MemoryKvOptions = {}): MemoryKv {\n return new MemoryKv(options);\n}\n"],
5
+ "mappings": "+EAsCA,SAASA,EAAOC,EAAqD,CACnE,OAAI,OAAOA,GAAkB,SAAiBA,EACvCA,GAAe,MAAQ,MAChC,CAHSC,EAAAF,EAAA,UAKT,SAASG,EAAOC,EAA6BC,EAAY,CACvD,GAAIA,IAAS,cAAe,OAAO,OAAOD,GAAU,SAAW,IAAI,YAAW,EAAG,OAAOA,CAAK,EAAE,OAASA,EAAM,MAAM,CAAC,EACrH,MAAME,EAAO,OAAOF,GAAU,SAAWA,EAAQ,IAAI,YAAW,EAAG,OAAOA,CAAK,EAC/E,OAAOC,IAAS,OAAS,KAAK,MAAMC,CAAI,EAAIA,CAC9C,CAJSJ,EAAAC,EAAA,UAMH,MAAOI,CAAQ,CAjDrB,MAiDqB,CAAAL,EAAA,iBACF,QAAU,IAAI,IACd,IAEjB,YAAYM,EAA2B,CAAA,EAAE,CACvC,KAAK,IAAMA,EAAQ,KAAO,KAAK,GACjC,CAKA,MAAI,CACF,OAAO,KAAK,KAAI,EAAG,IAAI,CAAC,CAACC,CAAG,IAAMA,CAAG,CACvC,CAKA,OAAK,CACH,KAAK,QAAQ,MAAK,CACpB,CAMA,IAAIA,EAAaJ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M,YAAc,GAAI,CAAC,EACpF,GAAIA,EAAM,WAAa,MAAQ,CAAE,SAAUA,EAAM,QAAQ,GACzD,EACF,cAAeO,EACf,GAAI,CAACA,GAAY,CAAE,OAAQ,OAAOH,EAAQD,CAAK,CAAC,EACjD,CACH,CAKA,MAAI,CACF,OAAO,IACT,CAEQ,KAAKJ,EAAW,CACtB,MAAMC,EAAQ,KAAK,QAAQ,IAAID,CAAG,EAClC,OAAKC,EACDA,EAAM,cAAgB,MAAQA,EAAM,aAAe,KAAK,IAAG,GAC7D,KAAK,QAAQ,OAAOD,CAAG,EAChB,MAEFC,EALY,IAMrB,CAEQ,MAAI,CACV,MAAO,CAAC,GAAG,KAAK,QAAQ,KAAI,CAAE,EAC3B,KAAK,CAACS,EAAGC,IAAMD,EAAE,cAAcC,CAAC,CAAC,EACjC,QAASX,GAAO,CACf,MAAMC,EAAQ,KAAK,KAAKD,CAAG,EAC3B,OAAOC,EAAQ,CAAC,CAACD,EAAKC,CAAK,CAAoB,EAAI,CAAA,CACrD,CAAC,CACL,EAMI,SAAUW,EAAeb,EAA2B,CAAA,EAAE,CAC1D,OAAO,IAAID,EAASC,CAAO,CAC7B,CAFgBN,EAAAmB,EAAA",
6
+ "names": ["asType", "typeOrOptions", "__name", "decode", "value", "type", "text", "MemoryKv", "options", "key", "entry", "expiresAtMs", "prefix", "limit", "start", "matching", "page", "complete", "name", "a", "b", "createMemoryKv"]
7
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Reset every module-level singleton the kit keeps: the rate limiter's buckets,
3
+ * the KV circuit breaker and the cached log level. Call from `beforeEach` in a
4
+ * suite that drives `createApiApp`, `KvCache` or the logger.
5
+ */
6
+ export declare function resetAllForTests(): void;
7
+ //# sourceMappingURL=reset.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reset.d.ts","sourceRoot":"","sources":["../src/reset.ts"],"names":[],"mappings":"AAGA;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,IAAI,CAIvC"}
package/dist/reset.js ADDED
@@ -0,0 +1 @@
1
+ var s=Object.defineProperty;var e=(r,t)=>s(r,"name",{value:t,configurable:!0});import{resetRateLimitForTests as o}from"@rexezuge/http/testing";import{resetBreakerForTests as i,resetLogLevelForTests as m}from"@rexezuge/runtime/testing";function l(){o(),i(),m()}e(l,"resetAllForTests");export{l as resetAllForTests};
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/reset.ts"],
4
+ "sourcesContent": ["import { resetRateLimitForTests } from '@rexezuge/http/testing';\nimport { resetBreakerForTests, resetLogLevelForTests } from '@rexezuge/runtime/testing';\n\n/**\n * Reset every module-level singleton the kit keeps: the rate limiter's buckets,\n * the KV circuit breaker and the cached log level. Call from `beforeEach` in a\n * suite that drives `createApiApp`, `KvCache` or the logger.\n */\nexport function resetAllForTests(): void {\n resetRateLimitForTests();\n resetBreakerForTests();\n resetLogLevelForTests();\n}\n"],
5
+ "mappings": "+EAAA,OAAS,0BAAAA,MAA8B,yBACvC,OAAS,wBAAAC,EAAsB,yBAAAC,MAA6B,4BAOtD,SAAUC,GAAgB,CAC9BH,EAAsB,EACtBC,EAAoB,EACpBC,EAAqB,CACvB,CAJgBE,EAAAD,EAAA",
6
+ "names": ["resetRateLimitForTests", "resetBreakerForTests", "resetLogLevelForTests", "resetAllForTests", "__name"]
7
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@rexezuge/testing",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.13.0",
4
+ "private": false,
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/Rexezuge-CloudflareWorkers/SDK.git",
9
+ "directory": "packages/testing"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./*": {
20
+ "types": "./dist/*.d.ts",
21
+ "default": "./dist/*.js"
22
+ }
23
+ },
24
+ "files": [
25
+ "dist"
26
+ ],
27
+ "devDependencies": {
28
+ "@types/node": "26.6.4",
29
+ "typescript": "6.0.3",
30
+ "vitest": "4.1.11"
31
+ },
32
+ "description": "Test doubles for the Rexezuge family: the cloudflare:workers mock, in-memory D1 and KV, an Access JWT forger, and createApiApp test helpers. Dev-only.",
33
+ "dependencies": {
34
+ "@rexezuge/http": "1.13.0",
35
+ "@rexezuge/shared": "1.13.0",
36
+ "@rexezuge/runtime": "1.13.0"
37
+ },
38
+ "scripts": {
39
+ "build": "tsc -p tsconfig.json && node ../../scripts/minify-dist.mjs",
40
+ "typecheck": "tsc -p tsconfig.test.json --noEmit",
41
+ "test": "vitest run",
42
+ "test:coverage": "vitest run --coverage"
43
+ }
6
44
  }