foldkit-plus 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +241 -28
- package/dist/cli.mjs +10930 -35
- package/dist/cli.mjs.map +1 -1
- package/dist/docs.d.mts +89 -0
- package/dist/docs.d.mts.map +1 -0
- package/dist/docs.mjs +290 -0
- package/dist/docs.mjs.map +1 -0
- package/dist/project.d.mts +45 -0
- package/dist/project.d.mts.map +1 -0
- package/dist/project.mjs +221 -0
- package/dist/project.mjs.map +1 -0
- package/dist/remote/filter.d.mts +1 -0
- package/dist/remote/filter.mjs +2 -0
- package/dist/remote/live.d.mts +1 -0
- package/dist/remote/live.mjs +2 -0
- package/dist/remote/outbox.d.mts +1 -0
- package/dist/remote/outbox.mjs +2 -0
- package/dist/remote/overlay.d.mts +1 -0
- package/dist/remote/overlay.mjs +2 -0
- package/dist/remote/persistence.d.mts +1 -0
- package/dist/remote/persistence.mjs +2 -0
- package/dist/remote/testing.d.mts +1 -0
- package/dist/remote/testing.mjs +2 -0
- package/dist/remote/why.d.mts +1 -0
- package/dist/remote/why.mjs +2 -0
- package/dist/setup.d.mts +45 -7
- package/dist/setup.d.mts.map +1 -1
- package/dist/setup.mjs +168 -25
- package/dist/setup.mjs.map +1 -1
- package/dist/testing/peer.d.mts +8 -0
- package/dist/testing/peer.d.mts.map +1 -0
- package/dist/testing/peer.mjs +19 -0
- package/dist/testing/peer.mjs.map +1 -0
- package/dist/testing/playwright.d.mts +84 -0
- package/dist/testing/playwright.d.mts.map +1 -0
- package/dist/testing/playwright.mjs +327 -0
- package/dist/testing/playwright.mjs.map +1 -0
- package/dist/testing/workers.d.mts +177 -0
- package/dist/testing/workers.d.mts.map +1 -0
- package/dist/testing/workers.mjs +593 -0
- package/dist/testing/workers.mjs.map +1 -0
- package/package.json +126 -59
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
import { Duration, Option, Schema } from "effect";
|
|
2
|
+
import { RemoteJsonRequest } from "foldkit-remote";
|
|
3
|
+
// src/testing/playwright.ts
|
|
4
|
+
/**
|
|
5
|
+
* `foldkit-plus/testing/playwright`: what a user sees, asserted on a running
|
|
6
|
+
* page. A write shows before the server answers, holds still until it is
|
|
7
|
+
* answered, and stays after; a step never shows a given text, at any moment;
|
|
8
|
+
* the page logs no error.
|
|
9
|
+
*
|
|
10
|
+
* Each checks the page as drawn, over the real network: it proves that the
|
|
11
|
+
* whole application (server, hydration, persistence, the Worker) delivers a
|
|
12
|
+
* property. Which Message breaks a read's property is
|
|
13
|
+
* `foldkit-plus/remote/testing`'s `Trace`, which records every Model without
|
|
14
|
+
* a browser; reach for it once one of these fails.
|
|
15
|
+
*
|
|
16
|
+
* Playwright is an optional peer of `foldkit-plus`, needed only for its types:
|
|
17
|
+
* this module calls nothing but the `Page` it is given.
|
|
18
|
+
*/
|
|
19
|
+
const decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest));
|
|
20
|
+
/** The operation of a Remote request over HTTP, by the JSON request `Remote.http` sends. */
|
|
21
|
+
const remoteOperation = (request) => {
|
|
22
|
+
const body = request.method() === "POST" ? request.postData() : null;
|
|
23
|
+
return body === null ? Option.none() : Option.map(decodeRequest(body), (sent) => sent.operation);
|
|
24
|
+
};
|
|
25
|
+
const isRemoteMutation = (request) => Option.contains(remoteOperation(request), "mutate");
|
|
26
|
+
const millis = (input) => Duration.toMillis(Duration.fromInputUnsafe(input));
|
|
27
|
+
/**
|
|
28
|
+
* How long `act` may take at least before it is taken to wait for its own
|
|
29
|
+
* write's answer. Only that case needs a limit, so it is far longer than a
|
|
30
|
+
* click takes on a loaded runner, whatever `hold` is.
|
|
31
|
+
*/
|
|
32
|
+
const ACT_LIMIT = 1e4;
|
|
33
|
+
/**
|
|
34
|
+
* Resolves once three frames in a row pass with no change to the document,
|
|
35
|
+
* or after two seconds of changes: a Message an answer caused has been drawn.
|
|
36
|
+
*/
|
|
37
|
+
const quiet = (page) => page.evaluate(() => new Promise((resolve) => {
|
|
38
|
+
let calm = 0;
|
|
39
|
+
const observer = new MutationObserver(() => {
|
|
40
|
+
calm = 0;
|
|
41
|
+
});
|
|
42
|
+
const done = () => {
|
|
43
|
+
observer.disconnect();
|
|
44
|
+
resolve();
|
|
45
|
+
};
|
|
46
|
+
observer.observe(document, {
|
|
47
|
+
childList: true,
|
|
48
|
+
subtree: true,
|
|
49
|
+
characterData: true,
|
|
50
|
+
attributes: true
|
|
51
|
+
});
|
|
52
|
+
setTimeout(done, 2e3);
|
|
53
|
+
const frame = () => {
|
|
54
|
+
calm += 1;
|
|
55
|
+
if (calm >= 3) done();
|
|
56
|
+
else requestAnimationFrame(frame);
|
|
57
|
+
};
|
|
58
|
+
requestAnimationFrame(frame);
|
|
59
|
+
}));
|
|
60
|
+
const watchStill = (elements, { key }) => {
|
|
61
|
+
const started = performance.now();
|
|
62
|
+
const where = (element) => {
|
|
63
|
+
const box = element.getBoundingClientRect();
|
|
64
|
+
return {
|
|
65
|
+
x: box.left + window.scrollX,
|
|
66
|
+
y: box.top + window.scrollY
|
|
67
|
+
};
|
|
68
|
+
};
|
|
69
|
+
const named = (element) => {
|
|
70
|
+
const html = element.outerHTML.replace(/\s+/g, " ");
|
|
71
|
+
return html.length > 80 ? `${html.slice(0, 77)}...` : html;
|
|
72
|
+
};
|
|
73
|
+
const watched = elements.map((element) => {
|
|
74
|
+
const lineage = /* @__PURE__ */ new Set();
|
|
75
|
+
for (let node = element; node !== null; node = node.parentNode) lineage.add(node);
|
|
76
|
+
return {
|
|
77
|
+
element,
|
|
78
|
+
lineage,
|
|
79
|
+
first: where(element),
|
|
80
|
+
faults: /* @__PURE__ */ new Map()
|
|
81
|
+
};
|
|
82
|
+
});
|
|
83
|
+
const fault = (each, kind, words) => {
|
|
84
|
+
if (!each.faults.has(kind)) each.faults.set(kind, `${named(each.element)} ${words}, ${Math.round(performance.now() - started)} ms after it showed`);
|
|
85
|
+
};
|
|
86
|
+
const observer = new MutationObserver((records) => {
|
|
87
|
+
for (const record of records) for (const each of watched) {
|
|
88
|
+
if ([...record.removedNodes].some((node) => each.lineage.has(node))) fault(each, "removed", "was taken out of the page");
|
|
89
|
+
if (record.type === "attributes" && record.attributeName === "hidden" && record.oldValue === null && each.lineage.has(record.target)) fault(each, "hidden", "was hidden");
|
|
90
|
+
}
|
|
91
|
+
for (const each of watched) if (each.faults.has("removed") && each.element.isConnected) fault(each, "moved", "was taken out and put back");
|
|
92
|
+
});
|
|
93
|
+
observer.observe(document, {
|
|
94
|
+
childList: true,
|
|
95
|
+
subtree: true,
|
|
96
|
+
attributes: true,
|
|
97
|
+
attributeFilter: ["hidden"],
|
|
98
|
+
attributeOldValue: true
|
|
99
|
+
});
|
|
100
|
+
let frame = 0;
|
|
101
|
+
const sample = () => {
|
|
102
|
+
for (const each of watched) {
|
|
103
|
+
if (!each.element.isConnected) continue;
|
|
104
|
+
if (!each.element.checkVisibility({ visibilityProperty: true })) fault(each, "hidden", "was hidden");
|
|
105
|
+
const now = where(each.element);
|
|
106
|
+
const dx = now.x - each.first.x;
|
|
107
|
+
const dy = now.y - each.first.y;
|
|
108
|
+
const away = [...Math.abs(dx) > 1 ? [`${Math.round(Math.abs(dx))}px ${dx < 0 ? "left" : "right"}`] : [], ...Math.abs(dy) > 1 ? [`${Math.round(Math.abs(dy))}px ${dy < 0 ? "up" : "down"}`] : []];
|
|
109
|
+
if (away.length > 0) fault(each, "shifted", `moved ${away.join(" and ")}`);
|
|
110
|
+
}
|
|
111
|
+
frame = requestAnimationFrame(sample);
|
|
112
|
+
};
|
|
113
|
+
sample();
|
|
114
|
+
Reflect.set(window, key, () => {
|
|
115
|
+
Reflect.deleteProperty(window, key);
|
|
116
|
+
observer.disconnect();
|
|
117
|
+
cancelAnimationFrame(frame);
|
|
118
|
+
return watched.map((each) => ({
|
|
119
|
+
element: each.element,
|
|
120
|
+
name: named(each.element),
|
|
121
|
+
faults: each.faults
|
|
122
|
+
}));
|
|
123
|
+
});
|
|
124
|
+
return elements.length;
|
|
125
|
+
};
|
|
126
|
+
/**
|
|
127
|
+
* Stops the watch and lists what went wrong. `now` is what the locator
|
|
128
|
+
* resolves to once settled: a watched element gone from the page while one
|
|
129
|
+
* that was not watched stands there was replaced, not only removed.
|
|
130
|
+
*/
|
|
131
|
+
const stopStill = (now, { key }) => {
|
|
132
|
+
const report = Reflect.apply(Reflect.get(window, key), void 0, []);
|
|
133
|
+
const newcomer = now.some((element) => !report.some((each) => each.element === element));
|
|
134
|
+
return report.flatMap((each) => {
|
|
135
|
+
const replaced = newcomer && !each.element.isConnected;
|
|
136
|
+
return [...[...each.faults].flatMap(([kind, words]) => replaced && kind === "removed" ? [] : [words]), ...replaced ? [`${each.name} was replaced by a new element`] : []];
|
|
137
|
+
});
|
|
138
|
+
};
|
|
139
|
+
const stopIfWatching = ({ key }) => {
|
|
140
|
+
const stop = Reflect.get(window, key);
|
|
141
|
+
if (typeof stop === "function") stop();
|
|
142
|
+
};
|
|
143
|
+
/**
|
|
144
|
+
* The write shows before the server answers, holds still until it has been
|
|
145
|
+
* answered and drawn, and still shows after.
|
|
146
|
+
*
|
|
147
|
+
* Every Remote mutation the page sends is held at the network until `act`
|
|
148
|
+
* has ended and `shows` has been looked for, and for `hold` at least, so
|
|
149
|
+
* what shows was drawn before any answer however long `act` takes;
|
|
150
|
+
* `shows` must be visible within `within` of `act` beginning. From
|
|
151
|
+
* then until settled, what `stays` names must stay in the page as the same
|
|
152
|
+
* nodes, in the same place in their parent, within 1px of where they were
|
|
153
|
+
* drawn, and visible. Settled is evidence, not a wait: no Remote request of
|
|
154
|
+
* the page in flight (an answer can lead to more, such as a placed list's
|
|
155
|
+
* first page under `verifyPredictions`), or `writes.answered`, then the page
|
|
156
|
+
* quiet for three frames. An error the page logs meanwhile fails it too: a
|
|
157
|
+
* `PredictionMismatch` is logged as one. Throws otherwise, when `act` sent
|
|
158
|
+
* no Remote mutation over HTTP, since nothing was then held, and when `act`
|
|
159
|
+
* has not ended 10 seconds (or `hold`, if longer) after it began: one that
|
|
160
|
+
* waits for its own write's answer would wait for good.
|
|
161
|
+
*/
|
|
162
|
+
const optimistic = async (page, options) => {
|
|
163
|
+
const writes = options.writes ?? "http";
|
|
164
|
+
const hold = millis(options.hold ?? "3 seconds");
|
|
165
|
+
const within = millis(options.within ?? "1 second");
|
|
166
|
+
let release = () => {};
|
|
167
|
+
const looked = new Promise((resolve) => {
|
|
168
|
+
release = resolve;
|
|
169
|
+
});
|
|
170
|
+
const held = [];
|
|
171
|
+
const inFlight = /* @__PURE__ */ new Set();
|
|
172
|
+
const sent = (request) => {
|
|
173
|
+
if (Option.isSome(remoteOperation(request))) inFlight.add(request);
|
|
174
|
+
};
|
|
175
|
+
let answers = 0;
|
|
176
|
+
const done = (request) => {
|
|
177
|
+
if (inFlight.delete(request)) answers += 1;
|
|
178
|
+
};
|
|
179
|
+
const errors = [];
|
|
180
|
+
const logged = (message) => {
|
|
181
|
+
if (message.type() === "error") errors.push(message.text());
|
|
182
|
+
};
|
|
183
|
+
const thrown = (error) => errors.push(String(error));
|
|
184
|
+
const letThrough = async (route) => {
|
|
185
|
+
await Promise.all([new Promise((resume) => setTimeout(resume, hold)), looked]);
|
|
186
|
+
await route.fallback();
|
|
187
|
+
};
|
|
188
|
+
const answered = async (request) => {
|
|
189
|
+
const response = await request.response();
|
|
190
|
+
if (response !== null) await response.finished();
|
|
191
|
+
};
|
|
192
|
+
const route = await page.route("**/*", (route, request) => {
|
|
193
|
+
if (writes !== "http" || !isRemoteMutation(request)) return route.fallback();
|
|
194
|
+
held.push(answered(request));
|
|
195
|
+
return letThrough(route);
|
|
196
|
+
});
|
|
197
|
+
page.on("request", sent);
|
|
198
|
+
page.on("requestfinished", done);
|
|
199
|
+
page.on("requestfailed", done);
|
|
200
|
+
page.on("console", logged);
|
|
201
|
+
page.on("pageerror", thrown);
|
|
202
|
+
const shows = String(options.shows);
|
|
203
|
+
const stays = options.stays ?? "put";
|
|
204
|
+
const watched = stays === "shown" ? Option.none() : Option.some(stays === "put" ? options.shows : stays);
|
|
205
|
+
const watch = { key: `__foldkitStill${crypto.randomUUID().replaceAll("-", "")}` };
|
|
206
|
+
let overdue;
|
|
207
|
+
try {
|
|
208
|
+
const shown = options.shows.waitFor({
|
|
209
|
+
state: "visible",
|
|
210
|
+
timeout: within
|
|
211
|
+
}).then(() => Option.none(), (error) => Option.some(error));
|
|
212
|
+
const acted = Promise.resolve().then(options.act);
|
|
213
|
+
const deadline = writes === "http" ? new Promise((resolve) => {
|
|
214
|
+
overdue = setTimeout(resolve, Math.max(hold, ACT_LIMIT), false);
|
|
215
|
+
}) : new Promise(() => {});
|
|
216
|
+
if (!await Promise.race([acted.then(() => true), deadline])) {
|
|
217
|
+
release();
|
|
218
|
+
await acted;
|
|
219
|
+
throw new Error(`optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`);
|
|
220
|
+
}
|
|
221
|
+
const missed = await shown;
|
|
222
|
+
if (Option.isSome(missed)) throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, { cause: missed.value });
|
|
223
|
+
if (Option.isSome(watched) && await watched.value.evaluateAll(watchStill, watch) === 0) throw new Error(`optimistic: ${String(watched.value)}, what stays, matches nothing`);
|
|
224
|
+
release();
|
|
225
|
+
if (writes === "http") {
|
|
226
|
+
if (held.length === 0) throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`);
|
|
227
|
+
} else await writes.answered();
|
|
228
|
+
for (;;) {
|
|
229
|
+
const before = answers;
|
|
230
|
+
await quiet(page);
|
|
231
|
+
if (inFlight.size === 0 && answers === before) break;
|
|
232
|
+
}
|
|
233
|
+
if (Option.isSome(watched)) {
|
|
234
|
+
const faults = await watched.value.evaluateAll(stopStill, watch);
|
|
235
|
+
if (faults.length > 0) throw new Error(`optimistic: ${String(watched.value)} did not hold still until the write settled:\n ${faults.join("\n ")}`);
|
|
236
|
+
}
|
|
237
|
+
if (!await options.shows.isVisible()) throw new Error(`optimistic: ${shows} showed while the write was held, but not after its answer`);
|
|
238
|
+
if (errors.length > 0) throw new Error(`optimistic: the page logged an error while the write settled:\n ${errors.join("\n ")}`);
|
|
239
|
+
} finally {
|
|
240
|
+
clearTimeout(overdue);
|
|
241
|
+
release();
|
|
242
|
+
if (!page.isClosed()) await page.evaluate(stopIfWatching, watch);
|
|
243
|
+
page.off("request", sent);
|
|
244
|
+
page.off("requestfinished", done);
|
|
245
|
+
page.off("requestfailed", done);
|
|
246
|
+
page.off("console", logged);
|
|
247
|
+
page.off("pageerror", thrown);
|
|
248
|
+
await route.dispose();
|
|
249
|
+
await Promise.allSettled(held);
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
const watchText = ({ key, source, flags }) => {
|
|
253
|
+
if (window !== window.top) return;
|
|
254
|
+
const pattern = new RegExp(source, flags);
|
|
255
|
+
let reported = false;
|
|
256
|
+
const check = () => {
|
|
257
|
+
if (reported) return;
|
|
258
|
+
const line = (document.body?.innerText ?? "").split("\n").find((each) => pattern.test(each));
|
|
259
|
+
if (line === void 0) return;
|
|
260
|
+
reported = true;
|
|
261
|
+
Reflect.apply(Reflect.get(window, key), void 0, [line]);
|
|
262
|
+
};
|
|
263
|
+
const observer = new MutationObserver(check);
|
|
264
|
+
observer.observe(document, {
|
|
265
|
+
childList: true,
|
|
266
|
+
subtree: true,
|
|
267
|
+
characterData: true,
|
|
268
|
+
attributes: true
|
|
269
|
+
});
|
|
270
|
+
Reflect.set(window, `${key}Stop`, () => observer.disconnect());
|
|
271
|
+
check();
|
|
272
|
+
};
|
|
273
|
+
const stopWatching = (key) => Reflect.apply(Reflect.get(window, `${key}Stop`), void 0, []);
|
|
274
|
+
/**
|
|
275
|
+
* The page never shows `text` while `during` runs, nor until the page is
|
|
276
|
+
* quiet after it: a cached page revisited never reads "Loading…", even for
|
|
277
|
+
* one frame. Throws with the line that showed.
|
|
278
|
+
*/
|
|
279
|
+
const neverShows = async (page, options) => {
|
|
280
|
+
const key = `__foldkitNeverShows${crypto.randomUUID().replaceAll("-", "")}`;
|
|
281
|
+
const { text } = options;
|
|
282
|
+
const watch = typeof text === "string" ? {
|
|
283
|
+
key,
|
|
284
|
+
source: text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"),
|
|
285
|
+
flags: ""
|
|
286
|
+
} : {
|
|
287
|
+
key,
|
|
288
|
+
source: text.source,
|
|
289
|
+
flags: text.flags
|
|
290
|
+
};
|
|
291
|
+
const shown = [];
|
|
292
|
+
const binding = await page.exposeBinding(key, (_, line) => {
|
|
293
|
+
shown.push(line);
|
|
294
|
+
});
|
|
295
|
+
const script = await page.addInitScript(watchText, watch);
|
|
296
|
+
try {
|
|
297
|
+
await page.evaluate(watchText, watch);
|
|
298
|
+
await options.during();
|
|
299
|
+
await quiet(page);
|
|
300
|
+
} finally {
|
|
301
|
+
await script.dispose();
|
|
302
|
+
if (!page.isClosed()) await page.evaluate(stopWatching, key);
|
|
303
|
+
await binding.dispose();
|
|
304
|
+
}
|
|
305
|
+
if (shown.length > 0) throw new Error(`neverShows: the page showed ${String(text)}: "${shown[0]}"`);
|
|
306
|
+
};
|
|
307
|
+
/**
|
|
308
|
+
* Collects every error the page logs (`console.error`) and every exception it
|
|
309
|
+
* does not catch, from now until the page closes. Read the list at the end.
|
|
310
|
+
*/
|
|
311
|
+
const consoleErrors = (page) => {
|
|
312
|
+
const errors = [];
|
|
313
|
+
page.on("console", (message) => {
|
|
314
|
+
if (message.type() === "error") errors.push(message.text());
|
|
315
|
+
});
|
|
316
|
+
page.on("pageerror", (error) => errors.push(String(error)));
|
|
317
|
+
return () => [...errors];
|
|
318
|
+
};
|
|
319
|
+
/** Assertions on what a running page shows, for Playwright. */
|
|
320
|
+
const Behaviors = {
|
|
321
|
+
optimistic,
|
|
322
|
+
neverShows,
|
|
323
|
+
consoleErrors
|
|
324
|
+
};
|
|
325
|
+
export { Behaviors };
|
|
326
|
+
|
|
327
|
+
//# sourceMappingURL=playwright.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"playwright.mjs","names":[],"sources":["../../src/testing/playwright.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/playwright`: what a user sees, asserted on a running\n * page. A write shows before the server answers, holds still until it is\n * answered, and stays after; a step never shows a given text, at any moment;\n * the page logs no error.\n *\n * Each checks the page as drawn, over the real network: it proves that the\n * whole application (server, hydration, persistence, the Worker) delivers a\n * property. Which Message breaks a read's property is\n * `foldkit-plus/remote/testing`'s `Trace`, which records every Model without\n * a browser; reach for it once one of these fails.\n *\n * Playwright is an optional peer of `foldkit-plus`, needed only for its types:\n * this module calls nothing but the `Page` it is given.\n */\nimport { Duration, Option, Schema } from 'effect'\nimport { RemoteJsonRequest } from 'foldkit-remote'\nimport type { ConsoleMessage, Locator, Page, Request, Route } from 'playwright'\n\nconst decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest))\n\n/** The operation of a Remote request over HTTP, by the JSON request `Remote.http` sends. */\nconst remoteOperation = (request: Request): Option.Option<RemoteJsonRequest['operation']> => {\n const body = request.method() === 'POST' ? request.postData() : null\n return body === null ? Option.none() : Option.map(decodeRequest(body), sent => sent.operation)\n}\n\nconst isRemoteMutation = (request: Request): boolean =>\n Option.contains(remoteOperation(request), 'mutate')\n\nconst millis = (input: Duration.Input) => Duration.toMillis(Duration.fromInputUnsafe(input))\n\n/**\n * How long `act` may take at least before it is taken to wait for its own\n * write's answer. Only that case needs a limit, so it is far longer than a\n * click takes on a loaded runner, whatever `hold` is.\n */\nconst ACT_LIMIT = 10_000\n\n/**\n * Resolves once three frames in a row pass with no change to the document,\n * or after two seconds of changes: a Message an answer caused has been drawn.\n */\nconst quiet = (page: Page): Promise<void> =>\n page.evaluate(\n () =>\n new Promise<void>(resolve => {\n let calm = 0\n const observer = new MutationObserver(() => {\n calm = 0\n })\n const done = () => {\n observer.disconnect()\n resolve()\n }\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n setTimeout(done, 2000)\n const frame = () => {\n calm += 1\n if (calm >= 3) done()\n else requestAnimationFrame(frame)\n }\n requestAnimationFrame(frame)\n }),\n )\n\n/**\n * Writes that reach the server some way other than `Remote.http` (a port to a\n * SharedWorker, a sandbox in the page). The page holds its own answers (the\n * test opened it so), and `answered` resolves on the page's own evidence that\n * nothing it wrote is pending: an outbox emptied, a status gone.\n */\nexport interface PageWrites {\n readonly answered: () => Promise<unknown>\n}\n\nexport interface OptimisticOptions {\n /** The user's action that writes: a click, a key. */\n readonly act: () => Promise<unknown>\n /** What the page shows once the write is made. */\n readonly shows: Locator\n /**\n * What must hold still from the moment `shows` shows until the write is\n * answered and drawn: `'put'` (the default), each element `shows` resolves\n * to; a `Locator`, what it resolves to instead (the list around a row its\n * answer deliberately draws again); `'shown'`, nothing, so only that\n * `shows` shows again after the answer.\n */\n readonly stays?: 'put' | 'shown' | Locator\n /** How the writes travel: `'http'` (the default), `Remote.http`'s requests, held at the network. */\n readonly writes?: 'http' | PageWrites\n /**\n * How long each Remote mutation is held at the network at least: it is held\n * on until `act` has ended and `shows` has been looked for. `'3 seconds'`\n * unless given.\n */\n readonly hold?: Duration.Input\n /** How soon after `act` begins `shows` must show, while every write is held. `'1 second'` unless given. */\n readonly within?: Duration.Input\n}\n\n/** What the page script needs to keep what it watches apart from another watch's. */\ninterface StillWatch {\n readonly key: string\n}\n\n// Runs in the page over the elements to keep still. A node removed and put\n// back in one batch reads as attached in the callback, so removals and\n// `hidden` are replayed from the records; layout and visibility are sampled\n// every frame, as a reader sees them. Each element reports each kind of fault once.\nconst watchStill = (elements: ReadonlyArray<Element>, { key }: StillWatch): number => {\n const started = performance.now()\n const where = (element: Element) => {\n const box = element.getBoundingClientRect()\n return { x: box.left + window.scrollX, y: box.top + window.scrollY }\n }\n const named = (element: Element) => {\n const html = element.outerHTML.replace(/\\s+/g, ' ')\n return html.length > 80 ? `${html.slice(0, 77)}...` : html\n }\n const watched = elements.map(element => {\n const lineage = new Set<Node>()\n for (let node: Node | null = element; node !== null; node = node.parentNode) lineage.add(node)\n return { element, lineage, first: where(element), faults: new Map<string, string>() }\n })\n const fault = (each: (typeof watched)[number], kind: string, words: string) => {\n if (!each.faults.has(kind))\n each.faults.set(\n kind,\n `${named(each.element)} ${words}, ${Math.round(performance.now() - started)} ms after it showed`,\n )\n }\n const observer = new MutationObserver(records => {\n for (const record of records)\n for (const each of watched) {\n if ([...record.removedNodes].some(node => each.lineage.has(node)))\n fault(each, 'removed', 'was taken out of the page')\n if (\n record.type === 'attributes' &&\n record.attributeName === 'hidden' &&\n record.oldValue === null &&\n each.lineage.has(record.target)\n )\n fault(each, 'hidden', 'was hidden')\n }\n for (const each of watched)\n if (each.faults.has('removed') && each.element.isConnected)\n fault(each, 'moved', 'was taken out and put back')\n })\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['hidden'],\n attributeOldValue: true,\n })\n let frame = 0\n const sample = () => {\n for (const each of watched) {\n if (!each.element.isConnected) continue\n if (!each.element.checkVisibility({ visibilityProperty: true }))\n fault(each, 'hidden', 'was hidden')\n const now = where(each.element)\n const dx = now.x - each.first.x\n const dy = now.y - each.first.y\n const away = [\n ...(Math.abs(dx) > 1 ? [`${Math.round(Math.abs(dx))}px ${dx < 0 ? 'left' : 'right'}`] : []),\n ...(Math.abs(dy) > 1 ? [`${Math.round(Math.abs(dy))}px ${dy < 0 ? 'up' : 'down'}`] : []),\n ]\n if (away.length > 0) fault(each, 'shifted', `moved ${away.join(' and ')}`)\n }\n frame = requestAnimationFrame(sample)\n }\n sample()\n Reflect.set(window, key, () => {\n Reflect.deleteProperty(window, key)\n observer.disconnect()\n cancelAnimationFrame(frame)\n return watched.map(each => ({\n element: each.element,\n name: named(each.element),\n faults: each.faults,\n }))\n })\n return elements.length\n}\n\n/**\n * Stops the watch and lists what went wrong. `now` is what the locator\n * resolves to once settled: a watched element gone from the page while one\n * that was not watched stands there was replaced, not only removed.\n */\nconst stopStill = (now: ReadonlyArray<Element>, { key }: StillWatch): ReadonlyArray<string> => {\n const report: ReadonlyArray<{\n readonly element: Element\n readonly name: string\n readonly faults: ReadonlyMap<string, string>\n }> = Reflect.apply(Reflect.get(window, key), undefined, [])\n const newcomer = now.some(element => !report.some(each => each.element === element))\n return report.flatMap(each => {\n const replaced = newcomer && !each.element.isConnected\n return [\n ...[...each.faults].flatMap(([kind, words]) =>\n replaced && kind === 'removed' ? [] : [words],\n ),\n ...(replaced ? [`${each.name} was replaced by a new element`] : []),\n ]\n })\n}\n\nconst stopIfWatching = ({ key }: StillWatch) => {\n const stop: unknown = Reflect.get(window, key)\n if (typeof stop === 'function') stop()\n}\n\n/**\n * The write shows before the server answers, holds still until it has been\n * answered and drawn, and still shows after.\n *\n * Every Remote mutation the page sends is held at the network until `act`\n * has ended and `shows` has been looked for, and for `hold` at least, so\n * what shows was drawn before any answer however long `act` takes;\n * `shows` must be visible within `within` of `act` beginning. From\n * then until settled, what `stays` names must stay in the page as the same\n * nodes, in the same place in their parent, within 1px of where they were\n * drawn, and visible. Settled is evidence, not a wait: no Remote request of\n * the page in flight (an answer can lead to more, such as a placed list's\n * first page under `verifyPredictions`), or `writes.answered`, then the page\n * quiet for three frames. An error the page logs meanwhile fails it too: a\n * `PredictionMismatch` is logged as one. Throws otherwise, when `act` sent\n * no Remote mutation over HTTP, since nothing was then held, and when `act`\n * has not ended 10 seconds (or `hold`, if longer) after it began: one that\n * waits for its own write's answer would wait for good.\n */\nconst optimistic = async (page: Page, options: OptimisticOptions): Promise<void> => {\n const writes = options.writes ?? 'http'\n const hold = millis(options.hold ?? '3 seconds')\n const within = millis(options.within ?? '1 second')\n // Opened once `shows` has been looked for and is watched: no write is\n // answered before, so nothing shown by then is an answer.\n let release = () => {}\n const looked = new Promise<void>(resolve => {\n release = resolve\n })\n const held: Array<Promise<void>> = []\n // Every Remote request from `act` on that is not yet answered.\n const inFlight = new Set<Request>()\n const sent = (request: Request) => {\n if (Option.isSome(remoteOperation(request))) inFlight.add(request)\n }\n // How many have been answered: a quiet that began before the last answer\n // may have ended before the page drew it.\n let answers = 0\n const done = (request: Request) => {\n if (inFlight.delete(request)) answers += 1\n }\n const errors: Array<string> = []\n const logged = (message: ConsoleMessage) => {\n if (message.type() === 'error') errors.push(message.text())\n }\n const thrown = (error: Error) => errors.push(String(error))\n // Let through after `hold`, once looked. The answer is awaited apart from the\n // handler: Playwright passes a request on to the next handler only once this one returns.\n const letThrough = async (route: Route) => {\n await Promise.all([new Promise(resume => setTimeout(resume, hold)), looked])\n await route.fallback()\n }\n const answered = async (request: Request) => {\n const response = await request.response()\n if (response !== null) await response.finished()\n }\n const route = await page.route('**/*', (route, request) => {\n if (writes !== 'http' || !isRemoteMutation(request)) return route.fallback()\n held.push(answered(request))\n return letThrough(route)\n })\n page.on('request', sent)\n page.on('requestfinished', done)\n page.on('requestfailed', done)\n page.on('console', logged)\n page.on('pageerror', thrown)\n const shows = String(options.shows)\n const stays = options.stays ?? 'put'\n const watched =\n stays === 'shown'\n ? Option.none<Locator>()\n : Option.some(stays === 'put' ? options.shows : stays)\n const watch: StillWatch = { key: `__foldkitStill${crypto.randomUUID().replaceAll('-', '')}` }\n let overdue: ReturnType<typeof setTimeout> | undefined\n try {\n const shown = options.shows.waitFor({ state: 'visible', timeout: within }).then(\n () => Option.none<unknown>(),\n (error: unknown) => Option.some(error),\n )\n const acted = Promise.resolve().then(options.act)\n // An action waiting for its own write's answer would wait for good.\n const deadline =\n writes === 'http'\n ? new Promise<false>(resolve => {\n overdue = setTimeout(resolve, Math.max(hold, ACT_LIMIT), false)\n })\n : new Promise<never>(() => {})\n const ended = await Promise.race([acted.then(() => true), deadline])\n if (!ended) {\n release()\n await acted\n throw new Error(\n `optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`,\n )\n }\n const missed = await shown\n if (Option.isSome(missed))\n throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, {\n cause: missed.value,\n })\n if (Option.isSome(watched) && (await watched.value.evaluateAll(watchStill, watch)) === 0)\n throw new Error(`optimistic: ${String(watched.value)}, what stays, matches nothing`)\n release()\n if (writes === 'http') {\n if (held.length === 0)\n throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`)\n } else {\n await writes.answered()\n }\n // Every held write is in flight until answered, and an answer drawn can ask\n // for more: settled once the page asks nothing and stays quiet from after\n // the last answer. The network finishes before the page reads the answer,\n // and an app draws it on a later frame.\n for (;;) {\n const before = answers\n await quiet(page)\n if (inFlight.size === 0 && answers === before) break\n }\n if (Option.isSome(watched)) {\n const faults = await watched.value.evaluateAll(stopStill, watch)\n if (faults.length > 0)\n throw new Error(\n `optimistic: ${String(watched.value)} did not hold still until the write settled:\\n ${faults.join('\\n ')}`,\n )\n }\n if (!(await options.shows.isVisible()))\n throw new Error(\n `optimistic: ${shows} showed while the write was held, but not after its answer`,\n )\n if (errors.length > 0)\n throw new Error(\n `optimistic: the page logged an error while the write settled:\\n ${errors.join('\\n ')}`,\n )\n } finally {\n clearTimeout(overdue)\n release()\n // A check that failed before reading the watch leaves it sampling every frame.\n if (!page.isClosed()) await page.evaluate(stopIfWatching, watch)\n page.off('request', sent)\n page.off('requestfinished', done)\n page.off('requestfailed', done)\n page.off('console', logged)\n page.off('pageerror', thrown)\n await route.dispose()\n await Promise.allSettled(held)\n }\n}\n\nexport interface NeverShowsOptions {\n /** What the page must not show at any moment of `during`. */\n readonly text: string | RegExp\n /**\n * The steps to watch: a reload, a navigation away and back. End it on what\n * the page waits for (an answer, a row), since watching stops once it ends\n * and the page is quiet.\n */\n readonly during: () => Promise<unknown>\n}\n\n/** What the page script needs: the binding to report through, and the text as a pattern. */\ninterface Watch {\n readonly key: string\n readonly source: string\n readonly flags: string\n}\n\n// Runs in the page, in the open document and in each one loaded after: after\n// every change to the document, the rendered text (`innerText` leaves hidden\n// text out) is searched, so a text shown for one frame is seen, not sampled.\nconst watchText = ({ key, source, flags }: Watch) => {\n if (window !== window.top) return\n const pattern = new RegExp(source, flags)\n let reported = false\n const check = () => {\n if (reported) return\n const line = (document.body?.innerText ?? '').split('\\n').find(each => pattern.test(each))\n if (line === undefined) return\n reported = true\n Reflect.apply(Reflect.get(window, key), undefined, [line])\n }\n const observer = new MutationObserver(check)\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n Reflect.set(window, `${key}Stop`, () => observer.disconnect())\n check()\n}\n\nconst stopWatching = (key: string) =>\n Reflect.apply(Reflect.get(window, `${key}Stop`), undefined, [])\n\n/**\n * The page never shows `text` while `during` runs, nor until the page is\n * quiet after it: a cached page revisited never reads \"Loading…\", even for\n * one frame. Throws with the line that showed.\n */\nconst neverShows = async (page: Page, options: NeverShowsOptions): Promise<void> => {\n const key = `__foldkitNeverShows${crypto.randomUUID().replaceAll('-', '')}`\n const { text } = options\n const watch: Watch =\n typeof text === 'string'\n ? { key, source: text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), flags: '' }\n : { key, source: text.source, flags: text.flags }\n const shown: Array<string> = []\n const binding = await page.exposeBinding(key, (_, line: string) => {\n shown.push(line)\n })\n const script = await page.addInitScript(watchText, watch)\n try {\n await page.evaluate(watchText, watch)\n await options.during()\n await quiet(page)\n } finally {\n await script.dispose()\n if (!page.isClosed()) await page.evaluate(stopWatching, key)\n await binding.dispose()\n }\n if (shown.length > 0)\n throw new Error(`neverShows: the page showed ${String(text)}: \"${shown[0]}\"`)\n}\n\n/**\n * Collects every error the page logs (`console.error`) and every exception it\n * does not catch, from now until the page closes. Read the list at the end.\n */\nconst consoleErrors = (page: Page): (() => ReadonlyArray<string>) => {\n const errors: Array<string> = []\n page.on('console', message => {\n if (message.type() === 'error') errors.push(message.text())\n })\n page.on('pageerror', error => errors.push(String(error)))\n return () => [...errors]\n}\n\n/** Assertions on what a running page shows, for Playwright. */\nexport const Behaviors = { optimistic, neverShows, consoleErrors } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAM,gBAAgB,OAAO,oBAA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AAQ,QAAQ;CACxB;CACA,IAAI,MAAM,SAAS,GACjB,MAAM,IAAI,MAAM,+BAA+B,OAAO,IAAI,EAAE,KAAK,MAAM,GAAG,EAAE;AAChF;;;;;AAMA,MAAM,iBAAiB,SAA8C;CACnE,MAAM,SAAwB,CAAC;CAC/B,KAAK,GAAG,YAAW,YAAW;EAC5B,IAAI,QAAQ,KAAK,MAAM,SAAS,OAAO,KAAK,QAAQ,KAAK,CAAC;CAC5D,CAAC;CACD,KAAK,GAAG,cAAa,UAAS,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC;CACxD,aAAa,CAAC,GAAG,MAAM;AACzB;;AAGA,MAAa,YAAY;CAAE;CAAY;CAAY;AAAc"}
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { Plugin } from "esbuild";
|
|
2
|
+
import { WorkerHandle } from "wrangler";
|
|
3
|
+
export interface StackOptions {
|
|
4
|
+
/** The Worker's Wrangler configuration (`wrangler.toml`, `.json` or `.jsonc`). */
|
|
5
|
+
readonly wrangler: string;
|
|
6
|
+
/** The source esbuild bundles into what `main` names. */
|
|
7
|
+
readonly entry: string;
|
|
8
|
+
/**
|
|
9
|
+
* Local values for vars the deployed Worker is given elsewhere. As a
|
|
10
|
+
* function, of the origin the stack answers at: the Worker has them from
|
|
11
|
+
* its first request (`origin => ({ ORIGIN: origin })`).
|
|
12
|
+
*/
|
|
13
|
+
readonly vars?: Vars | ((origin: string) => Vars);
|
|
14
|
+
/** Local values for secrets, over any in `.dev.vars`. */
|
|
15
|
+
readonly secrets?: Readonly<Record<string, string>>;
|
|
16
|
+
/**
|
|
17
|
+
* esbuild plugins for the bundle, the deploy's and the stack's alike. A
|
|
18
|
+
* module one loads is branded with view identities as one read from disk is.
|
|
19
|
+
*/
|
|
20
|
+
readonly plugins?: ReadonlyArray<Plugin>;
|
|
21
|
+
/**
|
|
22
|
+
* The Vite root of the page the Worker renders; by default the folder of
|
|
23
|
+
* the Wrangler configuration. Each view is named by its module's path from
|
|
24
|
+
* here, as `@foldkit/vite-plugin` names the page's.
|
|
25
|
+
*/
|
|
26
|
+
readonly pageRoot?: string;
|
|
27
|
+
/**
|
|
28
|
+
* Whether each line the Worker writes to its console is printed here, by
|
|
29
|
+
* its level, as it arrives (`'print'`, the default). `logs()` keeps them either way.
|
|
30
|
+
*/
|
|
31
|
+
readonly console?: 'print' | 'quiet';
|
|
32
|
+
}
|
|
33
|
+
type Vars = Readonly<Record<string, string>>;
|
|
34
|
+
/** A line the Worker wrote to its console. An `Error` logged carries its stack in `message`. */
|
|
35
|
+
export interface WorkerLog {
|
|
36
|
+
/** As workerd names it: `debug`, `info`, `log`, `warn` or `error`. */
|
|
37
|
+
readonly level: string;
|
|
38
|
+
readonly message: string;
|
|
39
|
+
readonly timestamp: number;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* What a watched stack reports after each change to the bundle's sources or
|
|
43
|
+
* to the Wrangler configuration.
|
|
44
|
+
*/
|
|
45
|
+
export interface WatchListener {
|
|
46
|
+
/** The new Worker answers at the same origin, over the same storage. */
|
|
47
|
+
readonly onSwap: () => void;
|
|
48
|
+
/**
|
|
49
|
+
* The change was not swapped in, and the Worker running keeps answering
|
|
50
|
+
* over the same storage. It did not build, built no code (as an entry saved
|
|
51
|
+
* in place reads for a moment), did not start when tried on a workerd of
|
|
52
|
+
* its own, or is a configuration the stack refuses. Or it was swapped in,
|
|
53
|
+
* and a D1 migration then failed on the running database; the message says so.
|
|
54
|
+
*/
|
|
55
|
+
readonly onRefused: (message: string) => void;
|
|
56
|
+
/**
|
|
57
|
+
* A Worker that started when tried did not start in the stack. Wrangler's
|
|
58
|
+
* harness tears its runtime down with it, storage included, so the stack
|
|
59
|
+
* has stopped answering and watches no more: call `stop`, and start again.
|
|
60
|
+
*/
|
|
61
|
+
readonly onStopped: (message: string) => void;
|
|
62
|
+
}
|
|
63
|
+
export interface Stack<Env> {
|
|
64
|
+
/** Where the Worker answers over real HTTP. */
|
|
65
|
+
readonly origin: string;
|
|
66
|
+
/**
|
|
67
|
+
* The Worker's bindings, as the Worker sees them. A swap retires the ones
|
|
68
|
+
* read before it (Miniflare's "poisoned stub"), so read them after.
|
|
69
|
+
*/
|
|
70
|
+
readonly env: () => Promise<Env>;
|
|
71
|
+
/** A request straight to the Worker; an upgrade answers with its socket. */
|
|
72
|
+
readonly dispatch: WorkerHandle['fetch'];
|
|
73
|
+
/**
|
|
74
|
+
* Takes what the Worker wrote to its console since the last call, oldest
|
|
75
|
+
* first. The lines come from workerd beside the response, not on it, so a
|
|
76
|
+
* line written for a request may arrive after it: poll.
|
|
77
|
+
*/
|
|
78
|
+
readonly logs: () => ReadonlyArray<WorkerLog>;
|
|
79
|
+
/**
|
|
80
|
+
* Requests sent straight to the Worker, metered for `Cpu.budget` by how
|
|
81
|
+
* long workerd's main thread runs, read from the operating system since
|
|
82
|
+
* workerd reports no CPU (Linux and Windows). That counts the Worker's code
|
|
83
|
+
* and what workerd does on the thread around it, D1's SQLite included,
|
|
84
|
+
* which a deployed Worker's CPU time leaves out.
|
|
85
|
+
*/
|
|
86
|
+
readonly cpu: CpuMeter;
|
|
87
|
+
/**
|
|
88
|
+
* Rebuilds on every change to a file the bundle read, and rereads the
|
|
89
|
+
* Wrangler configuration when it changes. Each change is first started on
|
|
90
|
+
* a workerd of its own, then swapped in at the same origin, and the D1
|
|
91
|
+
* migrations not yet applied are applied. D1, R2 and Durable Object storage stay.
|
|
92
|
+
*/
|
|
93
|
+
readonly watch: (listener: WatchListener) => Promise<void>;
|
|
94
|
+
/**
|
|
95
|
+
* Stops watching, stops workerd and removes the bundle's directory, each
|
|
96
|
+
* even when one before it failed. A change not yet being tried swaps
|
|
97
|
+
* nothing and reports nothing; one being tried finishes first. A second
|
|
98
|
+
* call returns the first one's promise.
|
|
99
|
+
*/
|
|
100
|
+
readonly stop: () => Promise<void>;
|
|
101
|
+
}
|
|
102
|
+
/** What a meter answers: a `Response`, or Miniflare's own. */
|
|
103
|
+
export type CpuAnswer = Pick<Response, 'status' | 'arrayBuffer'>;
|
|
104
|
+
/** Answers requests, and reads how much CPU time the code answering them has spent. */
|
|
105
|
+
export interface CpuMeter {
|
|
106
|
+
/** What a route given as a path is resolved against. */
|
|
107
|
+
readonly origin: string;
|
|
108
|
+
readonly fetch: (request: Request) => Promise<CpuAnswer>;
|
|
109
|
+
/** Milliseconds of CPU time spent so far, from a fixed point of the meter's own. */
|
|
110
|
+
readonly spent: () => Promise<number>;
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* A route `Cpu.budget` asks: a path or URL to `GET`, or a function making
|
|
114
|
+
* a new request for each run, since a request's body is read once.
|
|
115
|
+
*/
|
|
116
|
+
export type CpuRoute = string | (() => Request);
|
|
117
|
+
/** What one route cost, in milliseconds of CPU time. */
|
|
118
|
+
export interface CpuReading {
|
|
119
|
+
readonly route: string;
|
|
120
|
+
/** The last response's status. */
|
|
121
|
+
readonly status: number;
|
|
122
|
+
/** The route's first request in this call: in a fresh stack, a cold isolate's. */
|
|
123
|
+
readonly cold: number;
|
|
124
|
+
/** The mean of the requests after the first. */
|
|
125
|
+
readonly warm: number;
|
|
126
|
+
}
|
|
127
|
+
export interface CpuBudget {
|
|
128
|
+
/** The routes, by the name a failure reports them with. */
|
|
129
|
+
readonly routes: Readonly<Record<string, CpuRoute>>;
|
|
130
|
+
/** Milliseconds a warm request may spend. */
|
|
131
|
+
readonly warm: number;
|
|
132
|
+
/** Milliseconds the first request may spend; unchecked when not given. */
|
|
133
|
+
readonly cold?: number;
|
|
134
|
+
/** Requests after the first, each answered in full before the next; default 5. */
|
|
135
|
+
readonly runs?: number;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* Asks each route once, then `runs` times more, one request at a time, each
|
|
139
|
+
* response read in full, and reads what each cost. Throws listing every
|
|
140
|
+
* reading when a route spends more than the budget, or answers a 5xx, whose
|
|
141
|
+
* cost says nothing of the route's.
|
|
142
|
+
*/
|
|
143
|
+
declare const budget: (meter: CpuMeter, { routes, warm, cold, runs }: CpuBudget) => Promise<ReadonlyArray<CpuReading>>;
|
|
144
|
+
/**
|
|
145
|
+
* A meter over `answer` run in this process, by this thread's CPU time: for
|
|
146
|
+
* a Worker's handler Node can run (no D1 or other binding of workerd's),
|
|
147
|
+
* whose work happens on the thread that awaits it.
|
|
148
|
+
*/
|
|
149
|
+
declare const inThread: (answer: (request: Request) => Promise<CpuAnswer>, origin?: string) => CpuMeter;
|
|
150
|
+
/**
|
|
151
|
+
* What a request costs in CPU time, which Miniflare neither limits nor
|
|
152
|
+
* reports, while a deployed Worker fails past its plan's limit (error 1102).
|
|
153
|
+
* `Cpu.budget` reads routes through a meter: a stack's `cpu`, or `Cpu.inThread`.
|
|
154
|
+
*/
|
|
155
|
+
export declare const Cpu: {
|
|
156
|
+
readonly budget: typeof budget;
|
|
157
|
+
readonly inThread: typeof inThread;
|
|
158
|
+
};
|
|
159
|
+
/** Writes the bundle where `main` says, for `wrangler deploy`. */
|
|
160
|
+
declare const writeBundle: (options: Omit<StackOptions, 'vars' | 'secrets'>) => Promise<void>;
|
|
161
|
+
/**
|
|
162
|
+
* Starts the Worker with a fresh, migrated D1 for each `[[d1_databases]]`,
|
|
163
|
+
* and empty R2 and Durable Object storage. Each call is a stack of its own,
|
|
164
|
+
* so test files running side by side share nothing.
|
|
165
|
+
*/
|
|
166
|
+
declare const start: <Env>(options: StackOptions) => Promise<Stack<Env>>;
|
|
167
|
+
/**
|
|
168
|
+
* The local Workers stack. `Stack.start` runs the Worker for tests and
|
|
169
|
+
* development; `Stack.writeBundle` writes what `wrangler deploy` uploads,
|
|
170
|
+
* bundled the same way.
|
|
171
|
+
*/
|
|
172
|
+
export declare const Stack: {
|
|
173
|
+
readonly start: typeof start;
|
|
174
|
+
readonly writeBundle: typeof writeBundle;
|
|
175
|
+
};
|
|
176
|
+
export {};
|
|
177
|
+
//# sourceMappingURL=workers.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"workers.d.mts","names":[],"sources":["../../src/testing/workers.ts"],"mappings":";;iBA2CiB;;WAEN;;WAEA;;;;;;WAMA,OAAO,SAAS,mBAAmB;;WAEnC,UAAU,SAAS;;;;;WAKnB,UAAU,cAAc;;;;;;WAMxB;;;;;WAKA;;KAGN,OAAO,SAAS;;iBAGJ;;WAEN;WACA;WACA;;;;;;iBAOM;;WAEN;;;;;;;;WAQA,YAAY;;;;;;WAMZ,YAAY;;iBAGN,MAAM;;WAEZ;;;;;WAKA,WAAW,QAAQ;;WAEnB,UAAU;;;;;;WAMV,YAAY,cAAc;;;;;;;;WAQ1B,KAAK;;;;;;;WAOL,QAAQ,UAAU,kBAAkB;;;;;;;WAOpC,YAAY;;;YAIX,YAAY,KAAK;;iBAGZ;;WAEN;WACA,QAAQ,SAAS,YAAY,QAAQ;;WAErC,aAAa;;;;;;YAOZ,2BAA2B;;iBAGtB;WACN;;WAEA;;WAEA;;WAEA;;iBAGM;;WAEN,QAAQ,SAAS,eAAe;;WAEhC;;WAEA;;WAEA;;;;;;;;cA8IL,SAAM,OACH,YAAQ,QAAA,MAAA,MAAA,QACmB,cACjC,QAAQ,cAAc;;;;;;cA8DnB,WAAQ,SACH,SAAS,YAAY,QAAQ,YAAU,oBAE/C;;;;;;qBAOU;;;;;cAyMP,cAAW,SAAmB,KAAK,sCAAoC;;;;;;cAyBvE,QAAe,KAAG,SAAW,iBAAe,QAAQ,MAAM;;;;;;qBA2PnD"}
|