@cardonjs/testing 0.0.0-stage → 0.6.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 +21 -0
- package/README.md +504 -2
- package/THIRD_PARTY_NOTICES.md +72 -0
- package/dist/access-token-contract.d.ts +26 -0
- package/dist/access-token-contract.d.ts.map +1 -0
- package/dist/access-token-contract.js +252 -0
- package/dist/access-token-contract.js.map +1 -0
- package/dist/assertion.d.ts +7 -0
- package/dist/assertion.d.ts.map +1 -0
- package/dist/assertion.js +11 -0
- package/dist/assertion.js.map +1 -0
- package/dist/contract.d.ts +14 -0
- package/dist/contract.d.ts.map +1 -0
- package/dist/contract.js +8 -0
- package/dist/contract.js.map +1 -0
- package/dist/envelopes.d.ts +33 -0
- package/dist/envelopes.d.ts.map +1 -0
- package/dist/envelopes.js +121 -0
- package/dist/envelopes.js.map +1 -0
- package/dist/idempotency-contract.d.ts +19 -0
- package/dist/idempotency-contract.d.ts.map +1 -0
- package/dist/idempotency-contract.js +234 -0
- package/dist/idempotency-contract.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/logs.d.ts +18 -0
- package/dist/logs.d.ts.map +1 -0
- package/dist/logs.js +20 -0
- package/dist/logs.js.map +1 -0
- package/dist/miniflare/bindings.d.ts +43 -0
- package/dist/miniflare/bindings.d.ts.map +1 -0
- package/dist/miniflare/bindings.js +90 -0
- package/dist/miniflare/bindings.js.map +1 -0
- package/dist/miniflare/broken.d.ts +12 -0
- package/dist/miniflare/broken.d.ts.map +1 -0
- package/dist/miniflare/broken.js +27 -0
- package/dist/miniflare/broken.js.map +1 -0
- package/dist/miniflare/executor-channel.d.ts +37 -0
- package/dist/miniflare/executor-channel.d.ts.map +1 -0
- package/dist/miniflare/executor-channel.js +144 -0
- package/dist/miniflare/executor-channel.js.map +1 -0
- package/dist/miniflare/executor.d.ts +42 -0
- package/dist/miniflare/executor.d.ts.map +1 -0
- package/dist/miniflare/executor.js +121 -0
- package/dist/miniflare/executor.js.map +1 -0
- package/dist/miniflare/index.d.ts +10 -0
- package/dist/miniflare/index.d.ts.map +1 -0
- package/dist/miniflare/index.js +10 -0
- package/dist/miniflare/index.js.map +1 -0
- package/dist/miniflare/migrations.d.ts +23 -0
- package/dist/miniflare/migrations.d.ts.map +1 -0
- package/dist/miniflare/migrations.js +43 -0
- package/dist/miniflare/migrations.js.map +1 -0
- package/dist/miniflare/one-call-d1.d.ts +12 -0
- package/dist/miniflare/one-call-d1.d.ts.map +1 -0
- package/dist/miniflare/one-call-d1.js +223 -0
- package/dist/miniflare/one-call-d1.js.map +1 -0
- package/dist/miniflare/statements.d.ts +18 -0
- package/dist/miniflare/statements.d.ts.map +1 -0
- package/dist/miniflare/statements.js +175 -0
- package/dist/miniflare/statements.js.map +1 -0
- package/dist/miniflare/storage.d.ts +58 -0
- package/dist/miniflare/storage.d.ts.map +1 -0
- package/dist/miniflare/storage.js +129 -0
- package/dist/miniflare/storage.js.map +1 -0
- package/dist/miniflare/types.d.ts +25 -0
- package/dist/miniflare/types.d.ts.map +1 -0
- package/dist/miniflare/types.js +2 -0
- package/dist/miniflare/types.js.map +1 -0
- package/dist/miniflare/worker.d.ts +70 -0
- package/dist/miniflare/worker.d.ts.map +1 -0
- package/dist/miniflare/worker.js +137 -0
- package/dist/miniflare/worker.js.map +1 -0
- package/dist/push-subscription-contract.d.ts +54 -0
- package/dist/push-subscription-contract.d.ts.map +1 -0
- package/dist/push-subscription-contract.js +735 -0
- package/dist/push-subscription-contract.js.map +1 -0
- package/dist/routes.d.ts +72 -0
- package/dist/routes.d.ts.map +1 -0
- package/dist/routes.js +196 -0
- package/dist/routes.js.map +1 -0
- package/llms.txt +225 -0
- package/package.json +69 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Matias Terradas
|
|
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,505 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cardonjs/testing
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Test helpers for Cardón apps: a guard that every route is documented in the OpenAPI spec, an
|
|
4
|
+
in-memory logger to assert on logs, and assertions for the `{ data }` and `{ error }` envelopes
|
|
5
|
+
of `@cardonjs/core`, plus the building blocks of shared adapter contract suites (`defineContract`,
|
|
6
|
+
`fail`) the contract of core's idempotency store (`idempotencyStoreContract`) and the contract of
|
|
7
|
+
the `@cardonjs/access-tokens` store (`accessTokenStoreContract`) and the contract of the
|
|
8
|
+
`@cardonjs/notify-webpush` push subscription store (`pushSubscriptionStoreContract`). They do
|
|
9
|
+
not depend on a test runner: a failed assertion throws a plain `Error` named `AssertionError`
|
|
10
|
+
whose message lists every problem, so they work in Vitest, `node:test` or anything else. Standard web APIs only (Workers, Node, Bun, Deno).
|
|
11
|
+
|
|
12
|
+
Peer dependencies: `@cardonjs/core`, `hono`, `@hono/zod-openapi`; optional, for
|
|
13
|
+
`@cardonjs/testing/miniflare` only: `miniflare`, `rolldown` and `@cloudflare/workers-types`.
|
|
14
|
+
|
|
15
|
+
For coding agents: `llms.txt`, shipped next to this README in the package, is a compact usage guide (public API, a minimal example, common mistakes).
|
|
16
|
+
|
|
17
|
+
A second entry point, `@cardonjs/testing/miniflare`, gives tests real Cloudflare bindings (D1,
|
|
18
|
+
R2, Durable Objects, Workflows) from Miniflare running in Node: see
|
|
19
|
+
[Real bindings](#real-bindings-cardonjstestingminiflare). It is the only part that needs
|
|
20
|
+
`miniflare` (and `rolldown` for `startWorker`); the main entry works without them.
|
|
21
|
+
|
|
22
|
+
## Example
|
|
23
|
+
|
|
24
|
+
```ts
|
|
25
|
+
import { createApp } from "@cardonjs/core";
|
|
26
|
+
import { assertRoutesDocumented, captureLogs, expectData, expectError } from "@cardonjs/testing";
|
|
27
|
+
import { expect, it } from "vitest";
|
|
28
|
+
import { ordersModule } from "./orders.js";
|
|
29
|
+
|
|
30
|
+
const { logger, records, clear } = captureLogs();
|
|
31
|
+
const app = createApp(() => ({}), { logger }).register(ordersModule);
|
|
32
|
+
|
|
33
|
+
it("documents every route", () => {
|
|
34
|
+
assertRoutesDocumented(app, { ignore: ["POST /webhooks/legacy"] });
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it("gets an order", async () => {
|
|
38
|
+
const { data } = await expectData<{ id: string }>(await app.request("/v1/orders/1"), {
|
|
39
|
+
status: 200,
|
|
40
|
+
});
|
|
41
|
+
expect(data.id).toBe("1");
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
it("answers 404 for an unknown order", async () => {
|
|
45
|
+
clear();
|
|
46
|
+
const error = await expectError(await app.request("/v1/orders/nope"), {
|
|
47
|
+
status: 404,
|
|
48
|
+
code: "NOT_FOUND",
|
|
49
|
+
});
|
|
50
|
+
expect(records.find((r) => r.msg === "request")?.requestId).toBe(error.requestId);
|
|
51
|
+
});
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## API
|
|
55
|
+
|
|
56
|
+
### `assertRoutesDocumented(app, { ignore?, errorResponses? })`
|
|
57
|
+
|
|
58
|
+
Throws if a route is registered outside OpenAPI or its operation lacks the required metadata.
|
|
59
|
+
Works on any `OpenAPIHono`, a `CardonApp` included, and reads the spec from the app
|
|
60
|
+
(`getOpenAPI31Document`), never over HTTP, so the docs `access` and the environment do not matter.
|
|
61
|
+
|
|
62
|
+
- Checks every entry of `app.routes` with an HTTP method, once per method and path, with its
|
|
63
|
+
full path (module prefixes included). Entries with method `ALL` are skipped: that is how Hono
|
|
64
|
+
lists `use()` middleware, and `all()` and `mount()` routes look the same, so **they are not
|
|
65
|
+
checked**. Routes on methods OpenAPI cannot describe (e.g. `PURGE`) are reported.
|
|
66
|
+
- Each problem is one line, `METHOD /path: <problem>`, with the path as registered in Hono:
|
|
67
|
+
`undocumented`, `missing summary`, `missing tag`, `missing responses`. The shared error
|
|
68
|
+
responses a Cardón app adds to every operation (`$ref`s to `components.responses`) do not
|
|
69
|
+
count as the operation's own responses.
|
|
70
|
+
- Hono path params map to OpenAPI: `:id` and `:id{regex}` → `{id}`. A trailing optional param
|
|
71
|
+
(`/files/:name?`) answers two paths, so both `/files` and `/files/{name}` must be documented.
|
|
72
|
+
Wildcards (`/static/*`) cannot be documented: list them in `ignore`.
|
|
73
|
+
- `ignore`: `"METHOD /path"` strings in Hono path syntax, exactly as registered
|
|
74
|
+
(`"GET /legacy/:id"`); the method is case-insensitive.
|
|
75
|
+
- `errorResponses: true` (default `false`) also requires every operation that is not public
|
|
76
|
+
(its `security` is not `[]`) to document `500`, and `401` when it has security
|
|
77
|
+
requirements (`missing error responses (401, 500)`). A status counts when the operation has
|
|
78
|
+
it, its range (`5XX`) or `default`. A Cardón app documents these itself, so the check
|
|
79
|
+
catches routes or apps that do not.
|
|
80
|
+
|
|
81
|
+
### `undocumentedRoutes(routes, document, { ignore? })`
|
|
82
|
+
|
|
83
|
+
The part of `assertRoutesDocumented` that decides which routes are undocumented, as a pure
|
|
84
|
+
function over data: `routes` is `app.routes` (or any `{ method, path }` list, e.g. from a route
|
|
85
|
+
manifest) and `document` an OpenAPI document (only its `paths` is read). Returns, in route order
|
|
86
|
+
and once each, `{ method, path, describable, missing }`: `missing` lists the OpenAPI paths the
|
|
87
|
+
route answers that have no operation for its method; `describable` is `false` for a method
|
|
88
|
+
OpenAPI cannot describe (e.g. `PURGE`). Same rules as the assertion: `ALL` entries are skipped,
|
|
89
|
+
`ignore` works the same way, and system routes need no exception (a Cardón app documents them).
|
|
90
|
+
`cardon doctor` applies the same rule to a project's route manifest. `toOpenApiPaths(path)` is
|
|
91
|
+
exported too: the OpenAPI path(s) a Hono path answers.
|
|
92
|
+
|
|
93
|
+
### `captureLogs({ level?, fields? })`
|
|
94
|
+
|
|
95
|
+
Returns `{ logger, records, clear() }`: a core `Logger` (level `"debug"` by default, `fields` as
|
|
96
|
+
in `createLogger`) and the live array of `LogRecord`s it wrote. `clear()` empties that same array.
|
|
97
|
+
|
|
98
|
+
### `expectData(res, { status? })`
|
|
99
|
+
|
|
100
|
+
Asserts a success envelope and resolves to its parsed body `{ data, meta? }`: the status (any 2xx
|
|
101
|
+
by default), a JSON content type (`application/json` or `+json`), a `data` key and no `error`
|
|
102
|
+
key. The type parameters (`expectData<T, M>`) are not validated.
|
|
103
|
+
|
|
104
|
+
### `expectError(res, { status, code })`
|
|
105
|
+
|
|
106
|
+
Asserts a core error envelope and resolves to its `error` object `{ code, message, details?,
|
|
107
|
+
requestId }`: the status, a JSON content type, `error.code` (typed as core's `ErrorCode`), a
|
|
108
|
+
non-empty `error.message`, and `error.requestId` equal to the `X-Request-Id` response header.
|
|
109
|
+
|
|
110
|
+
Both envelope helpers read the response body.
|
|
111
|
+
|
|
112
|
+
### `fail(title, problems?)`
|
|
113
|
+
|
|
114
|
+
Throws the same `AssertionError` the helpers above throw: the message is `title` followed by one
|
|
115
|
+
line per problem. Use it in your own assertions and in contract cases.
|
|
116
|
+
|
|
117
|
+
### `defineContract(cases)` and `ContractCase<H>`
|
|
118
|
+
|
|
119
|
+
A shared contract suite is a list of cases, `{ name, run(harness) }`, that every adapter of an
|
|
120
|
+
interface must pass. `H` is the harness the adapter provides (how to create a fresh instance, a
|
|
121
|
+
broken one, and so on); a case fails by throwing, usually with `fail`. `defineContract` only types
|
|
122
|
+
the list. The suite does not pick a runner: each adapter runs the cases with its own.
|
|
123
|
+
|
|
124
|
+
```ts
|
|
125
|
+
import { defineContract, fail } from "@cardonjs/testing";
|
|
126
|
+
|
|
127
|
+
interface CounterHarness {
|
|
128
|
+
create(): { value(): number; increment(): void };
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export const counterContract = defineContract<CounterHarness>([
|
|
132
|
+
{
|
|
133
|
+
name: "starts at zero",
|
|
134
|
+
run: (h) => {
|
|
135
|
+
const value = h.create().value();
|
|
136
|
+
if (value !== 0) fail("a new counter must start at zero", [`got ${value}`]);
|
|
137
|
+
},
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
name: "increment adds one",
|
|
141
|
+
run: (h) => {
|
|
142
|
+
const counter = h.create();
|
|
143
|
+
counter.increment();
|
|
144
|
+
if (counter.value() !== 1) fail("increment must add one");
|
|
145
|
+
},
|
|
146
|
+
},
|
|
147
|
+
]);
|
|
148
|
+
|
|
149
|
+
// In an adapter's tests (Vitest):
|
|
150
|
+
it.each(counterContract.map((c) => [c.name, c] as const))("%s", (_, c) => c.run(harness));
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
### `idempotencyStoreContract`
|
|
154
|
+
|
|
155
|
+
The cases every `IdempotencyStore` (the store behind core's `idempotency` middleware) must
|
|
156
|
+
pass, with the harness `IdempotencyStoreContractHarness` (`{ create() }`, a fresh empty store
|
|
157
|
+
per call). It lives here rather than in core because this package already depends on core. The
|
|
158
|
+
cases cover `begin` (started with a token, `in_progress` while the lock holds, `mismatch` for
|
|
159
|
+
another fingerprint, `completed` with the stored response byte for byte, a new token when an
|
|
160
|
+
expired lock is taken over, the TTL counted from `complete`), `complete` with the owning token
|
|
161
|
+
after the lock expired but before a takeover (it succeeds), `complete` and `release` with a
|
|
162
|
+
stale token, concurrent `begin` calls (exactly one `started`, also when taking over an expired
|
|
163
|
+
record), `purge` (only expired records, at most `limit`) and independent keys. Dates are passed
|
|
164
|
+
in, so no case waits. The concurrency case only tests atomicity on a store whose `begin` awaits
|
|
165
|
+
I/O between reading and writing (D1, a database); an in-memory store that never awaits inside
|
|
166
|
+
`begin` cannot interleave, so it passes that case trivially.
|
|
167
|
+
|
|
168
|
+
```ts
|
|
169
|
+
import { memoryIdempotencyStore } from "@cardonjs/core";
|
|
170
|
+
import { idempotencyStoreContract } from "@cardonjs/testing";
|
|
171
|
+
|
|
172
|
+
it.each(idempotencyStoreContract.map((c) => [c.name, c] as const))("%s", (_, c) =>
|
|
173
|
+
c.run({ create: () => memoryIdempotencyStore() }),
|
|
174
|
+
);
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
### `accessTokenStoreContract`
|
|
178
|
+
|
|
179
|
+
The cases every `AccessTokenStore` (the store behind `@cardonjs/access-tokens`) must pass, with
|
|
180
|
+
the harness `AccessTokenStoreContractHarness` (`{ create() }`, a fresh empty store per call). The
|
|
181
|
+
store and record types are repeated here structurally (`AccessTokenStoreUnderTest`,
|
|
182
|
+
`AccessTokenStoreRecord`), so this package does not depend on `@cardonjs/access-tokens`. The
|
|
183
|
+
cases cover `insert` and `findByHash` (every field back, dates to the millisecond, scopes in
|
|
184
|
+
order; nothing for an unknown hash), duplicate hashes and ids rejected, expired and revoked
|
|
185
|
+
records still found until purged, `revoke` (once, on that record only, the first `revokedAt`
|
|
186
|
+
kept), `revokeForResource` (every unrevoked record of exactly that resource, counted), no
|
|
187
|
+
cross-resource leak (other types, ids, case, `LIKE` wildcards and prefixes untouched),
|
|
188
|
+
`purgeExpired` (records expired at or before the time, counted; revoked live ones kept) and
|
|
189
|
+
copies (changing a record after `insert` or `findByHash` changes nothing stored).
|
|
190
|
+
|
|
191
|
+
```ts
|
|
192
|
+
import { memoryAccessTokenStore } from "@cardonjs/access-tokens/testing";
|
|
193
|
+
import { accessTokenStoreContract } from "@cardonjs/testing";
|
|
194
|
+
|
|
195
|
+
it.each(accessTokenStoreContract.map((c) => [c.name, c] as const))("%s", (_, c) =>
|
|
196
|
+
c.run({ create: () => memoryAccessTokenStore() }),
|
|
197
|
+
);
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### `pushSubscriptionStoreContract`
|
|
201
|
+
|
|
202
|
+
The cases every `PushSubscriptionStore` (`@cardonjs/notify-webpush`) must pass, with the harness
|
|
203
|
+
`PushSubscriptionStoreContractHarness` (`{ create({ now }) }`: a fresh empty store per call,
|
|
204
|
+
whose saves are dated, and expiry decided, by `now`, the clock the cases move). The store types
|
|
205
|
+
are repeated here structurally (`PushSubscriptionStoreUnderTest`, `PushSubscriptionStoreOwner`,
|
|
206
|
+
`PushSubscriptionStoreSubscription`, `PushSubscriptionStoreSaveOptions`,
|
|
207
|
+
`PushSubscriptionStoreSaveResult`, `PushSubscriptionStoreRefusal`), so this package does not depend on
|
|
208
|
+
`@cardonjs/notify-webpush`. The cases cover: `save` and `listForOwner` (newest first, ties by
|
|
209
|
+
endpoint, the keys back, nothing for another owner); one endpoint under several owners (all list
|
|
210
|
+
it; `deleteForOwner` leaves the others; `delete` removes it for all); another `auth` for a stored
|
|
211
|
+
endpoint refused as `taken` under any owner, the same one included, and an `auth` differing only
|
|
212
|
+
in letter case, changing nothing; the same `auth` with a new `p256dh` updating what every owner
|
|
213
|
+
lists, and `=` padding being the same secret; `whenFull: "evict"` (the newest `max`, default 10,
|
|
214
|
+
the saved one always kept, never another owner's) and `"refuse"` (`owner_full`, nothing changed;
|
|
215
|
+
re-saving one's own never refused); a refused save never evicting at the cap; `owner_full` with
|
|
216
|
+
`exclusive` running no exclusive delete; the per-endpoint cap of 50 owners (`endpoint_full`,
|
|
217
|
+
nothing evicted, nor with `exclusive` and `max: 1`; answered before `source_full`); the cap per
|
|
218
|
+
source (`maxPerSource` answering `source_full` and changing nothing with either `whenFull`, with
|
|
219
|
+
`exclusive` and with `max: 1`, while the owner is not full; answered after `taken` and before
|
|
220
|
+
`owner_full`; counting only the owner's live subscriptions with that source, never the endpoint
|
|
221
|
+
saved again; a re-save moving the endpoint to another source, or clearing it, freeing the slot;
|
|
222
|
+
the source never listed); `exclusive` (other owners of the same type only); expiry (skipped by `listForOwner`, not counted against `max`, deleted by `purgeExpired`,
|
|
223
|
+
replaced by a new save); `purgeExpired` bounded by `limit`, earliest expiry first, keeping a
|
|
224
|
+
browser another owner uses; deletes matching endpoints exactly and an endpoint no owner uses any more
|
|
225
|
+
being free for other keys; `deleteAllForOwner` scoped to exactly that owner (counted); no leak
|
|
226
|
+
between owners of different types with the same id; and malformed owners, subscriptions, options
|
|
227
|
+
(a malformed `source`, `maxPerSource` without one) and dates rejected with a `TypeError` that never holds the value. Failure messages name
|
|
228
|
+
subscriptions by a label, never by their endpoint or keys.
|
|
229
|
+
|
|
230
|
+
```ts
|
|
231
|
+
import { memoryPushSubscriptionStore } from "@cardonjs/notify-webpush/testing";
|
|
232
|
+
import { pushSubscriptionStoreContract } from "@cardonjs/testing";
|
|
233
|
+
|
|
234
|
+
it.each(pushSubscriptionStoreContract.map((c) => [c.name, c] as const))("%s", (_, c) =>
|
|
235
|
+
c.run({ create: ({ now }) => memoryPushSubscriptionStore({ now }) }),
|
|
236
|
+
);
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
## Real bindings (`@cardonjs/testing/miniflare`)
|
|
240
|
+
|
|
241
|
+
Tests against real bindings catch what a mock cannot: SQL that SQLite refuses, a batch that is
|
|
242
|
+
not atomic, a Durable Object that loses its state when it hibernates. This entry point starts
|
|
243
|
+
them from Miniflare, in Node, with plain async functions (no test runner involved).
|
|
244
|
+
|
|
245
|
+
```sh
|
|
246
|
+
pnpm add -D @cardonjs/testing miniflare # startBindings, applyMigrations
|
|
247
|
+
pnpm add -D rolldown # startWorker, to bundle a Worker entry
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
The harness works with Miniflare 4 (`^4.20260730.0`) and with Miniflare 5, a beta today.
|
|
251
|
+
Cardón's own suites run on Miniflare 4 in CI; Miniflare 5 was checked by hand on
|
|
252
|
+
`5.20261119.0-beta` on 2026-11-22 (Windows), not in CI. Wrangler releases after 4.116.0 bring
|
|
253
|
+
Miniflare 5, so a project on Miniflare 4 installs two copies and `wrangler dev` runs a newer
|
|
254
|
+
runtime than its tests. A project that wants one copy and one runtime can pin, in its
|
|
255
|
+
`devDependencies`, the Miniflare version its Wrangler brings.
|
|
256
|
+
|
|
257
|
+
The peer range is `^4.20260730.0 || ^5.20261119.0-beta`: Miniflare 4, the beta that was
|
|
258
|
+
checked, and Miniflare 5 once it is stable. A semver range cannot cover every beta (a
|
|
259
|
+
prerelease only matches a range that names its exact version), so with any other Miniflare 5
|
|
260
|
+
beta npm refuses the install (`ERESOLVE`) unless the project adds an `overrides` entry for
|
|
261
|
+
`miniflare` or installs with `--legacy-peer-deps`; pnpm installs it. Other betas were not
|
|
262
|
+
checked.
|
|
263
|
+
|
|
264
|
+
`miniflare` and `rolldown` are optional peer dependencies: only this entry point imports
|
|
265
|
+
`miniflare`, and only `startWorker` imports `rolldown` (when it bundles an `entry`). The helpers
|
|
266
|
+
return the types a Worker receives (`D1Database`, `R2Bucket`, `DurableObjectNamespace`),
|
|
267
|
+
imported from `@cloudflare/workers-types` (an optional peer dependency too, needed by this entry
|
|
268
|
+
only), so they are the same types whether or not the project's `tsconfig.json` lists the
|
|
269
|
+
Workers types as ambient. Without the package installed, a binding's type is
|
|
270
|
+
`WorkersTypesMissing` and the first use of it fails to type-check, rather than becoming `any`
|
|
271
|
+
(which `skipLibCheck` would hide). The main entry's types do not use it.
|
|
272
|
+
|
|
273
|
+
```ts
|
|
274
|
+
import { applyMigrations, startBindings, type TestBindings } from "@cardonjs/testing/miniflare";
|
|
275
|
+
import { afterAll, beforeAll, expect, it } from "vitest";
|
|
276
|
+
|
|
277
|
+
let bindings: TestBindings;
|
|
278
|
+
beforeAll(async () => {
|
|
279
|
+
bindings = await startBindings({ d1: 8, r2: 2 }); // one Miniflare per test file
|
|
280
|
+
});
|
|
281
|
+
afterAll(async () => {
|
|
282
|
+
await bindings?.dispose();
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it("stores a note", async () => {
|
|
286
|
+
const db = await bindings.d1(); // a new, empty database
|
|
287
|
+
await applyMigrations(db, { dir: new URL("../migrations/", import.meta.url) });
|
|
288
|
+
await db.prepare("INSERT INTO notes (id, body) VALUES (?, ?)").bind("n1", "hello").run();
|
|
289
|
+
expect(await db.prepare("SELECT body FROM notes").first("body")).toBe("hello");
|
|
290
|
+
});
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
### `startBindings({ d1?, r2?, d1Binding? })`
|
|
294
|
+
|
|
295
|
+
Starts one Miniflare with a pool of `d1` D1 databases and `r2` R2 buckets (0 each by default;
|
|
296
|
+
at least one in total) and resolves to `{ d1(), r2(), directory, dispose() }`. Each `d1()` or
|
|
297
|
+
`r2()` call resolves to a binding no one used before: a new, empty database or bucket. Asking
|
|
298
|
+
for more than the pool holds rejects with an error that says so (`the pool of 8 D1 databases is
|
|
299
|
+
used up; ask for more with { d1: n }`); a used binding is never handed out again. Size the pool
|
|
300
|
+
for the file: every database is created when Miniflare starts.
|
|
301
|
+
|
|
302
|
+
The databases `d1()` hands out are **one-call D1s** by default: a `D1Database` whose `prepare`
|
|
303
|
+
and `bind` run in Node and whose every execution (`all`, `run`, `raw`, `first`, `batch`,
|
|
304
|
+
`exec`) is one request to a small Worker in the same Miniflare, which runs it on the real D1
|
|
305
|
+
binding. The SQL still runs on D1 and SQLite in workerd; only the way Node reaches it changes.
|
|
306
|
+
Miniflare's own binding object is a proxy on which every call, `prepare` and `bind` included,
|
|
307
|
+
is a blocking round trip to workerd: a Drizzle query (`prepare().bind().raw()`) costs several
|
|
308
|
+
of them, about 80 ms on Windows and 12 ms on Linux, against 5 and 3 ms as one request.
|
|
309
|
+
|
|
310
|
+
- Every execution runs on the real D1 binding in workerd: results and `meta`, `raw` with and
|
|
311
|
+
without column names, `batch` (in order, and atomic: a failing statement rolls the batch
|
|
312
|
+
back), `exec`, BLOBs (arrays of bytes, as from D1) and D1's errors, with the same messages
|
|
313
|
+
(`D1_ERROR: UNIQUE constraint failed: ...`) and causes.
|
|
314
|
+
- What D1's binding does before a query leaves a Worker runs in Node, with the same code:
|
|
315
|
+
`bind` checks and converts the values with D1's rules and throws `D1_TYPE_ERROR` at once for
|
|
316
|
+
one D1 refuses (`ArrayBuffer`s and views become arrays of bytes, booleans 1 and 0, a plain
|
|
317
|
+
array is kept, not copied, as D1 keeps it); a statement has D1's `statement` and `params`
|
|
318
|
+
fields; each execution sends them as D1 serialises them, when the method is called; `first`
|
|
319
|
+
looks the column up on the row as D1 does.
|
|
320
|
+
- Executions on one database are sent one at a time, in the order they were called, as they
|
|
321
|
+
reach D1 from a Worker (`Promise.all` of a write and a read sees the write).
|
|
322
|
+
- A parity suite in this package runs the same scenarios inside a Worker on its real binding
|
|
323
|
+
and on a one-call D1 and compares every step's value or error (and the scenarios Miniflare's
|
|
324
|
+
binding can carry also on that binding).
|
|
325
|
+
|
|
326
|
+
What differs from D1 in a Worker:
|
|
327
|
+
|
|
328
|
+
- `withSession` and `dump` are not supported: they throw an error that says how to get the
|
|
329
|
+
direct binding.
|
|
330
|
+
- Errors are rebuilt in Node: the same standard class, name, message and causes, with the stack
|
|
331
|
+
of your call, not workerd's. Values come from Node's realm (`first("constructor")` gives
|
|
332
|
+
Node's `Object`, as a Worker gives its own).
|
|
333
|
+
- A statement has no `dbSession` field (D1's points to its session object), and `batch` takes
|
|
334
|
+
only statements of a one-call D1 (D1 reads `statement` and `params` from any object).
|
|
335
|
+
- A value whose text depends on the time zone (binding a `Date`, which D1 refuses with the date
|
|
336
|
+
in its message) reads in Node's time zone; workerd's is UTC.
|
|
337
|
+
|
|
338
|
+
Where Miniflare's own binding (below) and a Worker differ, the one-call D1 does what the Worker
|
|
339
|
+
does: a lone surrogate in a string reaches D1 as it is (the proxy turns it into U+FFFD), and a
|
|
340
|
+
`SharedArrayBuffer` gets D1's `D1_TYPE_ERROR` (the proxy cannot carry it); a bound array
|
|
341
|
+
changed before the execution, or a sparse one, also behaves as in a Worker (the proxy copies
|
|
342
|
+
the values at `bind`).
|
|
343
|
+
|
|
344
|
+
`d1Binding: "direct"` (`startBindings({ d1: 4, d1Binding: "direct" })`) hands out Miniflare's
|
|
345
|
+
own binding object instead. Use it to test code against the binding object itself (an adapter's
|
|
346
|
+
own suite, as `@cardonjs/db-d1`'s are) or to use `withSession` or `dump`; it is slower for
|
|
347
|
+
everything else.
|
|
348
|
+
|
|
349
|
+
The one-call D1 reaches its Worker on a socket of that Worker's own in workerd, over a few
|
|
350
|
+
connections kept open between requests (one per database sending at the same moment, closed
|
|
351
|
+
after 2 seconds idle). That Worker answers only the harness that started it (anything else on
|
|
352
|
+
the machine, a web page included, is refused), and a one-call D1 used after `dispose()` rejects
|
|
353
|
+
with `startBindings: the harness was disposed; ...` (or `startWorker: ...`). Everything else reaches workerd through Miniflare, which opens a new
|
|
354
|
+
connection for each asynchronous call and closes it: a request with `fetch` of `startWorker`,
|
|
355
|
+
an `await` on an R2 bucket, a Durable Object or the direct D1 binding (see "Many connections on
|
|
356
|
+
Windows" below).
|
|
357
|
+
|
|
358
|
+
Storage lives in a temporary directory of its own (`directory`, `cardon-XXXXXX` under the OS
|
|
359
|
+
temp folder, a short name: on Windows, a deep path makes local Workflows lose instances past the
|
|
360
|
+
260-character limit), removed by `dispose()`. Miniflare listens on a random port, so test files
|
|
361
|
+
run in parallel. A second `dispose()` does nothing.
|
|
362
|
+
|
|
363
|
+
When a process ends without reaching `dispose()` (a crash, Ctrl+C in watch mode, a `beforeAll`
|
|
364
|
+
that timed out, a missing `afterAll`), one `exit` listener removes the directories that process
|
|
365
|
+
created and has not removed (never another process's `cardon-*` folders: another test run may be
|
|
366
|
+
using them). It adds no signal handlers; a process killed outright (SIGKILL) leaves its
|
|
367
|
+
directories behind. If `dispose()` cannot remove the directory after its retries (on Windows,
|
|
368
|
+
workerd or an antivirus may still hold a file), it resolves anyway and emits one process warning
|
|
369
|
+
(`CARDON_TEST_STORAGE`) naming it; the `exit` listener tries again.
|
|
370
|
+
|
|
371
|
+
### `applyMigrations(db, { dir } | { files })`
|
|
372
|
+
|
|
373
|
+
Applies migration files to a D1 database as `wrangler d1 migrations apply` does, and resolves to
|
|
374
|
+
the file names in the order applied:
|
|
375
|
+
|
|
376
|
+
- `dir`: a folder (a path, or a file URL such as `new URL("../migrations/", import.meta.url)`);
|
|
377
|
+
its `.sql` files are read, other files are ignored. `files`: file name → SQL, for migrations
|
|
378
|
+
loaded another way (a bundler's glob import).
|
|
379
|
+
- Files run in name order, each one in a single `batch`, so a file applies whole or not at all.
|
|
380
|
+
On a one-call D1 that is one request per file, whatever its number of statements; on the
|
|
381
|
+
direct binding each statement's `prepare` is a round trip too.
|
|
382
|
+
- A failing file rejects with `applyMigrations: <file> failed: <reason>` (the database's error is
|
|
383
|
+
its `cause`); the files after it are not applied. No files at all is an error too (a wrong
|
|
384
|
+
folder, say).
|
|
385
|
+
|
|
386
|
+
`statementsOf(sql)` is the split it uses, exported for code that runs a migration (or a seed
|
|
387
|
+
file) another way. It reads the file as SQL and follows Wrangler's split for Drizzle Kit output
|
|
388
|
+
and hand-written SQLite migrations:
|
|
389
|
+
|
|
390
|
+
- Strings (`'...'`, with `''` inside), quoted names (`"..."`, `` `...` ``, `[...]`), `--` line
|
|
391
|
+
comments and `/* */` block comments are recognised. Comments are dropped, outside strings
|
|
392
|
+
only: a `--` line inside a multi-line string stays, and a `;` inside a string, a name or a
|
|
393
|
+
comment never splits.
|
|
394
|
+
- A file with Drizzle Kit's `--> statement-breakpoint` is split on those only (each statement
|
|
395
|
+
keeps its `;`). A file without any is split on every `;`, except inside the `BEGIN ... END` of
|
|
396
|
+
a `CREATE TRIGGER`, so a trigger with several statements in its body is one statement.
|
|
397
|
+
- Windows line endings and a byte order mark are accepted; empty statements are skipped.
|
|
398
|
+
- It never throws: an unterminated string, name or block comment makes the rest of the file one
|
|
399
|
+
statement, so the database reports the error.
|
|
400
|
+
|
|
401
|
+
What it does not do: record the files applied (Wrangler's `d1_migrations` table), so
|
|
402
|
+
`applyMigrations` is for a fresh test database, applied once; and remove `BEGIN TRANSACTION` /
|
|
403
|
+
`COMMIT` (D1 refuses them in a migration).
|
|
404
|
+
|
|
405
|
+
### `startWorker(options)`
|
|
406
|
+
|
|
407
|
+
Bundles a Worker entry with rolldown and runs it in workerd through Miniflare, for what only the
|
|
408
|
+
runtime has: Durable Objects (hibernation included), Workflows, `nodejs_compat`.
|
|
409
|
+
|
|
410
|
+
```ts
|
|
411
|
+
import { startWorker, type TestWorker } from "@cardonjs/testing/miniflare";
|
|
412
|
+
|
|
413
|
+
let worker: TestWorker;
|
|
414
|
+
beforeAll(async () => {
|
|
415
|
+
worker = await startWorker({
|
|
416
|
+
entry: new URL("./test-worker.ts", import.meta.url),
|
|
417
|
+
compatibilityDate: "2026-07-01",
|
|
418
|
+
compatibilityFlags: ["nodejs_compat"], // only if the Worker needs it
|
|
419
|
+
durableObjects: { COUNTERS: "Counter" }, // binding → exported class
|
|
420
|
+
workflows: { ECHO: { name: "echo", className: "Echo" } },
|
|
421
|
+
d1: ["DB"],
|
|
422
|
+
bindings: { LABEL: "test-env" }, // vars
|
|
423
|
+
});
|
|
424
|
+
}, 60_000); // bundling and starting workerd take a few seconds
|
|
425
|
+
afterAll(async () => {
|
|
426
|
+
await worker?.dispose();
|
|
427
|
+
});
|
|
428
|
+
|
|
429
|
+
it("counts", async () => {
|
|
430
|
+
const res = await worker.fetch("/count/a", { method: "POST" }); // relative to worker.url
|
|
431
|
+
expect(await res.json()).toEqual({ value: 1 });
|
|
432
|
+
});
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
- Options: `entry` (a file URL or a path; bundled as Wrangler would for workerd: `cloudflare:*`
|
|
436
|
+
and `node:*` stay external, the `workerd` export condition first) or `script` (one ES module,
|
|
437
|
+
bundled already: no bundling); `compatibilityDate` (required, so a test does not change with
|
|
438
|
+
the runtime) and `compatibilityFlags`; `bindings` (string vars), `d1` and `r2` (binding
|
|
439
|
+
names, each a new, empty database or bucket; a D1 binding may not be named
|
|
440
|
+
`CARDON_ONE_CALL_D1_TOKEN`, which the one-call D1 reserves), `durableObjects` (binding → class name,
|
|
441
|
+
SQLite-backed) and `workflows` (binding → `{ name, className }`).
|
|
442
|
+
- The result: `fetch(input, init?)` (Miniflare's `dispatchFetch`; a relative URL is resolved
|
|
443
|
+
against `url`; a WebSocket upgrade answers with `response.webSocket`), `url` (where workerd
|
|
444
|
+
listens, for clients over real HTTP or raw TCP), `d1(name)`, `r2(name)` and
|
|
445
|
+
`durableObject(name)` (the Worker's bindings seen from Node), `script` (the bundle: start the
|
|
446
|
+
same Worker with other options without bundling again), `directory` and `dispose()`.
|
|
447
|
+
- `d1(name)` is a one-call D1 over the Worker's database (its executor runs next to the Worker,
|
|
448
|
+
with the same databases bound and the Worker's compatibility date and flags), unless
|
|
449
|
+
`d1Binding: "direct"` is set; the Worker itself always uses the real binding.
|
|
450
|
+
- It rejects when workerd refuses the Worker (a `node:` import without `nodejs_compat`, for
|
|
451
|
+
example), and leaves nothing running then.
|
|
452
|
+
|
|
453
|
+
A relative string `entry`, or a relative `dir` of `applyMigrations`, is resolved against the
|
|
454
|
+
process's working directory (where the test runner was started), not against the test file:
|
|
455
|
+
prefer a URL relative to the file, `new URL("./test-worker.ts", import.meta.url)`.
|
|
456
|
+
|
|
457
|
+
Vitest's watch mode re-runs a test when a module it imports changes. Migrations read from disk
|
|
458
|
+
(`{ dir }`) are not modules, so add them to `forceRerunTriggers` in `vitest.config.ts` to re-run
|
|
459
|
+
the tests when one changes (the starter does):
|
|
460
|
+
|
|
461
|
+
```ts
|
|
462
|
+
import { configDefaults, defineConfig } from "vitest/config";
|
|
463
|
+
|
|
464
|
+
export default defineConfig({
|
|
465
|
+
test: {
|
|
466
|
+
forceRerunTriggers: [...configDefaults.forceRerunTriggers, "**/migrations/**/*.sql"],
|
|
467
|
+
},
|
|
468
|
+
});
|
|
469
|
+
```
|
|
470
|
+
|
|
471
|
+
### `brokenD1()` and `brokenR2()`
|
|
472
|
+
|
|
473
|
+
Bindings with the shape of the real ones whose every call rejects (`D1_ERROR: Network
|
|
474
|
+
connection lost.`, `R2_ERROR: ...`), like a database or bucket that lost its connection: for
|
|
475
|
+
the error paths of code that uses them (a readiness check, a store that must report a failure
|
|
476
|
+
without leaking it). A binding from a disposed Miniflare cannot stand in: it throws on any
|
|
477
|
+
property access.
|
|
478
|
+
|
|
479
|
+
### Many connections on Windows
|
|
480
|
+
|
|
481
|
+
Every closed connection stays in the operating system's `TIME_WAIT` state for a while (up to a
|
|
482
|
+
few minutes on Windows), holding a local port. Miniflare closes the connection after each
|
|
483
|
+
asynchronous call it carries (its `dispatchFetch` marks every request to workerd
|
|
484
|
+
`connection: close`; a caller cannot change it), so a suite that makes many such calls (R2,
|
|
485
|
+
Durable Objects, the direct D1 binding, requests to a test Worker) leaves that many connections
|
|
486
|
+
behind. The one-call D1 does not go through it, so D1 executions, usually most of the calls,
|
|
487
|
+
leave almost none.
|
|
488
|
+
|
|
489
|
+
On Windows, several heavy runs back to back can still use up the local ports. Tests that pass
|
|
490
|
+
alone then fail with `connect EADDRINUSE`, `fetch failed` or an error from Miniflare's proxy,
|
|
491
|
+
in tests that have nothing to do with the change, and at different places from one run to the
|
|
492
|
+
next. To tell it from a real failure, count the connections waiting (PowerShell
|
|
493
|
+
`(Get-NetTCPConnection -State TimeWait).Count`, or `netstat -an -p tcp | find /c "TIME_WAIT"`):
|
|
494
|
+
in the thousands, wait until it drops (a few minutes) and run again. A failure that stays at the
|
|
495
|
+
same test once the count is low is a real one.
|
|
496
|
+
|
|
497
|
+
### When a fake is the better choice
|
|
498
|
+
|
|
499
|
+
Real bindings are for code whose correctness depends on the platform: SQL and migrations,
|
|
500
|
+
atomic batches, conditional writes, R2 metadata and ranges, Durable Object storage. Use the
|
|
501
|
+
in-memory fakes each interface package ships at `./testing` (`@cardonjs/storage/testing`,
|
|
502
|
+
`@cardonjs/realtime-do/testing`, `@cardonjs/workflows-cf/testing`, ...) when the test is about
|
|
503
|
+
your own logic around a binding: a route that publishes to a room, a workflow driven step by
|
|
504
|
+
step with `settle` and `timeOut`, a provider that leaves the machine (payments, email, push).
|
|
505
|
+
They are faster, need no Miniflare and let a test control time.
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
# Third-party notices
|
|
2
|
+
|
|
3
|
+
`@cardonjs/testing` is licensed under the MIT licence (see `LICENSE`). One part of it is adapted
|
|
4
|
+
from another project and stays under that project's licence.
|
|
5
|
+
|
|
6
|
+
## workerd
|
|
7
|
+
|
|
8
|
+
The one-call D1 of `@cardonjs/testing/miniflare` (`dist/miniflare/one-call-d1.js`) reproduces in
|
|
9
|
+
Node what D1's binding does before a query leaves a Worker. Its parameter conversion (`d1Value`)
|
|
10
|
+
and the way `first` looks up a column are adapted from the D1 binding of
|
|
11
|
+
[workerd](https://github.com/cloudflare/workerd) (`src/cloudflare/internal/d1-api.ts`),
|
|
12
|
+
Copyright (c) Cloudflare, Inc., licensed under the Apache License, Version 2.0. The adapted code
|
|
13
|
+
was rewritten in this package's style and typed for Node; its behaviour is kept the same on
|
|
14
|
+
purpose.
|
|
15
|
+
|
|
16
|
+
```
|
|
17
|
+
Apache License
|
|
18
|
+
|
|
19
|
+
Version 2.0, January 2004
|
|
20
|
+
|
|
21
|
+
http://www.apache.org/licenses/
|
|
22
|
+
|
|
23
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
24
|
+
|
|
25
|
+
1. Definitions.
|
|
26
|
+
|
|
27
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
28
|
+
|
|
29
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
30
|
+
|
|
31
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
32
|
+
|
|
33
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
34
|
+
|
|
35
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
36
|
+
|
|
37
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
38
|
+
|
|
39
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
42
|
+
|
|
43
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
44
|
+
|
|
45
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
46
|
+
|
|
47
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
48
|
+
|
|
49
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
50
|
+
|
|
51
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
52
|
+
|
|
53
|
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
54
|
+
|
|
55
|
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
56
|
+
|
|
57
|
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
58
|
+
|
|
59
|
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
60
|
+
|
|
61
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
62
|
+
|
|
63
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
64
|
+
|
|
65
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
66
|
+
|
|
67
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
68
|
+
|
|
69
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
70
|
+
|
|
71
|
+
END OF TERMS AND CONDITIONS
|
|
72
|
+
```
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { type ContractCase } from "./contract.js";
|
|
2
|
+
/** A record as an access token store keeps it (`AccessTokenRecord` in `@cardonjs/access-tokens`). */
|
|
3
|
+
export interface AccessTokenStoreRecord {
|
|
4
|
+
readonly id: string;
|
|
5
|
+
readonly tokenHash: string;
|
|
6
|
+
readonly resourceType: string;
|
|
7
|
+
readonly resourceId: string;
|
|
8
|
+
readonly scopes: readonly string[];
|
|
9
|
+
readonly createdAt: Date;
|
|
10
|
+
readonly expiresAt: Date;
|
|
11
|
+
readonly revokedAt?: Date;
|
|
12
|
+
}
|
|
13
|
+
/** The store under test (`AccessTokenStore` in `@cardonjs/access-tokens`). */
|
|
14
|
+
export interface AccessTokenStoreUnderTest {
|
|
15
|
+
insert(record: AccessTokenStoreRecord): Promise<void>;
|
|
16
|
+
findByHash(tokenHash: string): Promise<AccessTokenStoreRecord | undefined>;
|
|
17
|
+
revoke(id: string, at: Date): Promise<boolean>;
|
|
18
|
+
revokeForResource(resourceType: string, resourceId: string, at: Date): Promise<number>;
|
|
19
|
+
purgeExpired(before: Date): Promise<number>;
|
|
20
|
+
}
|
|
21
|
+
export interface AccessTokenStoreContractHarness {
|
|
22
|
+
/** An empty store. Fresh per call. */
|
|
23
|
+
create(): AccessTokenStoreUnderTest | Promise<AccessTokenStoreUnderTest>;
|
|
24
|
+
}
|
|
25
|
+
export declare const accessTokenStoreContract: readonly ContractCase<AccessTokenStoreContractHarness>[];
|
|
26
|
+
//# sourceMappingURL=access-token-contract.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"access-token-contract.d.ts","sourceRoot":"","sources":["../src/access-token-contract.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,KAAK,YAAY,EAAkB,MAAM,eAAe,CAAC;AAElE,qGAAqG;AACrG,MAAM,WAAW,sBAAsB;IACrC,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;IAC9B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAC;IAC5B,QAAQ,CAAC,MAAM,EAAE,SAAS,MAAM,EAAE,CAAC;IACnC,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;IACzB,QAAQ,CAAC,SAAS,EAAE,IAAI,CAAC;IACzB,QAAQ,CAAC,SAAS,CAAC,EAAE,IAAI,CAAC;CAC3B;AAED,8EAA8E;AAC9E,MAAM,WAAW,yBAAyB;IACxC,MAAM,CAAC,MAAM,EAAE,sBAAsB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IACtD,UAAU,CAAC,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,sBAAsB,GAAG,SAAS,CAAC,CAAC;IAC3E,MAAM,CAAC,EAAE,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC/C,iBAAiB,CAAC,YAAY,EAAE,MAAM,EAAE,UAAU,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;IACvF,YAAY,CAAC,MAAM,EAAE,IAAI,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC7C;AAED,MAAM,WAAW,+BAA+B;IAC9C,sCAAsC;IACtC,MAAM,IAAI,yBAAyB,GAAG,OAAO,CAAC,yBAAyB,CAAC,CAAC;CAC1E;AAsFD,eAAO,MAAM,wBAAwB,EAAE,SAAS,YAAY,CAAC,+BAA+B,CAAC,EA8OzF,CAAC"}
|