reguard 0.7.1 → 0.8.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.
Files changed (44) hide show
  1. package/README.md +51 -31
  2. package/dist/chunks/chunk-3AYS7WSY.js +350 -0
  3. package/dist/chunks/chunk-KNKCUJL3.js +969 -0
  4. package/dist/chunks/{chunk-W56LN2M5.js → chunk-PA46KSOR.js} +385 -33
  5. package/dist/chunks/chunk-YDDBWUPV.js +438 -0
  6. package/dist/cjs/fastify.cjs +2109 -0
  7. package/dist/cjs/fetch.cjs +1453 -0
  8. package/dist/cjs/index.cjs +2074 -0
  9. package/dist/cjs/next.cjs +1518 -0
  10. package/dist/cjs/testing.cjs +214 -0
  11. package/dist/fastify.js +59 -0
  12. package/dist/fetch.js +13 -0
  13. package/dist/index.js +15 -716
  14. package/dist/next.js +41 -52
  15. package/dist/testing.js +39 -0
  16. package/dist/types/node/src/config.d.ts +107 -0
  17. package/dist/types/node/src/core.d.ts +66 -72
  18. package/dist/types/node/src/fastify.d.ts +41 -0
  19. package/dist/types/node/src/fetch.d.ts +76 -0
  20. package/dist/types/node/src/health.d.ts +41 -0
  21. package/dist/types/node/src/index.d.ts +114 -34
  22. package/dist/types/node/src/next.d.ts +40 -27
  23. package/dist/types/node/src/testing.d.ts +25 -0
  24. package/dist/types/shared/src/address.d.ts +81 -0
  25. package/dist/types/shared/src/index.d.ts +6 -0
  26. package/dist/types/shared/src/paths.d.ts +32 -0
  27. package/dist/types-cjs/node/src/config.d.cts +107 -0
  28. package/dist/types-cjs/node/src/core.d.cts +107 -0
  29. package/dist/types-cjs/node/src/fastify.d.cts +41 -0
  30. package/dist/types-cjs/node/src/fetch.d.cts +76 -0
  31. package/dist/types-cjs/node/src/health.d.cts +41 -0
  32. package/dist/types-cjs/node/src/index.d.cts +203 -0
  33. package/dist/types-cjs/node/src/next.d.cts +85 -0
  34. package/dist/types-cjs/node/src/testing.d.cts +25 -0
  35. package/dist/types-cjs/shared/src/address.d.cts +81 -0
  36. package/dist/types-cjs/shared/src/allowance.d.cts +17 -0
  37. package/dist/types-cjs/shared/src/collect.d.cts +52 -0
  38. package/dist/types-cjs/shared/src/exchange.d.cts +69 -0
  39. package/dist/types-cjs/shared/src/index.d.cts +105 -0
  40. package/dist/types-cjs/shared/src/keys.d.cts +13 -0
  41. package/dist/types-cjs/shared/src/paths.d.cts +32 -0
  42. package/dist/types-cjs/shared/src/tools.d.cts +101 -0
  43. package/dist/types-cjs/shared/src/verdict.d.cts +37 -0
  44. package/package.json +73 -10
@@ -0,0 +1,438 @@
1
+ import {
2
+ BLOCK_REASONS,
3
+ Health,
4
+ ReguardConfigError,
5
+ checkBlock,
6
+ checkBoolean,
7
+ checkClientIp,
8
+ checkCollect,
9
+ checkCollector,
10
+ checkCookieDomain,
11
+ checkFunction,
12
+ checkLogger,
13
+ checkNumber,
14
+ makeLog
15
+ } from "./chunk-3AYS7WSY.js";
16
+ import {
17
+ Allowance,
18
+ BENIGN_TOOL_FAMILIES,
19
+ RETRY_AFTER,
20
+ SESSION_COOKIE,
21
+ canonicalPath,
22
+ collectReport,
23
+ collectorBase,
24
+ cookieValue,
25
+ defaultAnswer,
26
+ describeExchange,
27
+ detectPlatform,
28
+ envValue,
29
+ isApiLike,
30
+ isPublicIp,
31
+ isReguardPath,
32
+ isSourceMapPath,
33
+ isSpeculativeHeaders,
34
+ matchesBoth,
35
+ matchesEither,
36
+ mergeVerdicts,
37
+ normalizeIp,
38
+ parseSiteKey,
39
+ pathTraits,
40
+ privateUrl,
41
+ pushedVerdict,
42
+ readVerdictFrom,
43
+ renderScriptTag,
44
+ requestKind,
45
+ resolveClientAddress,
46
+ skipMatcher,
47
+ toolOf,
48
+ wantsPage,
49
+ watchworthy
50
+ } from "./chunk-PA46KSOR.js";
51
+
52
+ // src/fetch.ts
53
+ var OPTION_KEYS = [
54
+ "key",
55
+ "previousKey",
56
+ "collector",
57
+ "block",
58
+ "sourceMaps",
59
+ "ignore",
60
+ "collect",
61
+ "watchSessionless",
62
+ "clientIp",
63
+ "cookieDomain",
64
+ "debug",
65
+ "logger",
66
+ "timeoutMs",
67
+ "flushIntervalMs",
68
+ "platform",
69
+ "fetch",
70
+ "onError"
71
+ ];
72
+ var enc = new TextEncoder();
73
+ var keys = /* @__PURE__ */ new Map();
74
+ async function hmac(secret, text, length) {
75
+ let k = keys.get(secret);
76
+ if (!k) {
77
+ k = crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
78
+ keys.set(secret, k);
79
+ }
80
+ const sig = new Uint8Array(await crypto.subtle.sign("HMAC", await k, enc.encode(text)));
81
+ let s = "";
82
+ for (const b of sig) s += String.fromCharCode(b);
83
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "").slice(0, length);
84
+ }
85
+ var NOT_FORWARDED = /^(?:connection|keep-alive|proxy-authenticate|proxy-authorization|te|trailer|transfer-encoding|upgrade|host|content-length|expect|accept-encoding|cookie|authorization|referer)$|^x-reguard-/;
86
+ var ADDRESS_HEADER = /^(?:x-forwarded-for|forwarded|x-real-ip|x-original-forwarded-for|x-envoy-external-address|x-nf-client-connection-ip|x-vercel-forwarded-for|x-vercel-proxied-for|fly-client-ip)$|client-?ip|connecting-ip|^cf-ip|^cf-(?:region|metro|postal|timezone)|^x-vercel-ip-|^cloudfront-viewer-|^x-appengine-(?:user-ip|city|country|region)/;
87
+ var STRIP_FROM_RESPONSE = /* @__PURE__ */ new Set(["content-encoding", "content-length", "transfer-encoding", "connection", "keep-alive"]);
88
+ function defaultBlockAnswer(request, decision) {
89
+ const a = defaultAnswer(decision.reason, wantsPage((n) => request.headers.get(n)));
90
+ return new Response(a.body, { status: decision.status, headers: { "content-type": a.contentType, "retry-after": String(decision.retryAfter), "cache-control": "no-store" } });
91
+ }
92
+ function findWaitUntil(args) {
93
+ for (const a of args) {
94
+ const w = a?.waitUntil;
95
+ if (typeof w === "function") return w.bind(a);
96
+ }
97
+ return void 0;
98
+ }
99
+ function reguardFetch(options = {}) {
100
+ if (options === null || typeof options !== "object") throw new ReguardConfigError("options", "invalid_type", "must be an object");
101
+ for (const k of Object.keys(options))
102
+ if (options[k] !== void 0 && !OPTION_KEYS.includes(k))
103
+ throw new ReguardConfigError(k, k === "forward" ? "removed_option" : "unknown_option", k === "forward" ? "was removed: use collect: { requests: false }" : "isn't an option");
104
+ const block = checkBlock(options.block, "block", "fetch");
105
+ const collect = checkCollect(options.collect);
106
+ const clientIp = checkClientIp(options.clientIp);
107
+ const cookieDomain = checkCookieDomain(options.cookieDomain);
108
+ const timeoutMs = checkNumber(options.timeoutMs, "timeoutMs", 100, 12e4) ?? 1e4;
109
+ const flushIntervalMs = checkNumber(options.flushIntervalMs, "flushIntervalMs", 10, 36e5) ?? 2e3;
110
+ checkCollector(options.collector);
111
+ checkFunction(options.fetch, "fetch");
112
+ checkFunction(options.onError, "onError");
113
+ const log = makeLog(checkLogger(options.logger), checkBoolean(options.debug, "debug") ?? /^(?:1|true|yes)$/i.test(envValue("REGUARD_DEBUG") ?? ""));
114
+ const ignore = options.ignore?.length ? skipMatcher(options.ignore) : void 0;
115
+ const key = (options.key ?? envValue("REGUARD_KEY"))?.trim();
116
+ const parsed = parseSiteKey(key);
117
+ const doFetch = options.fetch ?? ((input, init) => fetch(input, init));
118
+ const onError = options.onError ?? (() => {
119
+ });
120
+ const verdicts = /* @__PURE__ */ new WeakMap();
121
+ const decisions = /* @__PURE__ */ new WeakMap();
122
+ if (!parsed?.site) {
123
+ log.once("no-key", "warn", "REGUARD_KEY is not set (or isn't an rgk.\u2026 key): passing every request through.");
124
+ return {
125
+ site: void 0,
126
+ handle: async () => void 0,
127
+ record: () => {
128
+ },
129
+ wrap: (h) => h,
130
+ verdict: async () => null,
131
+ decision: () => null,
132
+ scriptTag: () => "",
133
+ flush: async () => {
134
+ }
135
+ };
136
+ }
137
+ const site = parsed.site;
138
+ const secrets = [parsed.secret];
139
+ const prev = parseSiteKey((options.previousKey ?? envValue("REGUARD_KEY_PREVIOUS"))?.trim());
140
+ if (prev?.site === site && prev.secret !== parsed.secret) secrets.push(prev.secret);
141
+ const collector = collectorBase(options.collector ?? envValue("REGUARD_COLLECTOR"));
142
+ const platform = options.platform ?? detectPlatform(typeof process !== "undefined" ? process.env : void 0) ?? (typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers" ? "workers" : null);
143
+ const health = new Health(log);
144
+ const allDry = !block || BLOCK_REASONS.every((r) => block.dryRun.has(r));
145
+ const denyMaps = (options.sourceMaps ?? (allDry ? "allow" : "deny")) === "deny";
146
+ const allowList = block?.allow.length ? skipMatcher(block.allow) : void 0;
147
+ const skipped = skipMatcher(collect.skip);
148
+ const tagSettings = { site, collect, cookieDomain };
149
+ const pace = block?.pace;
150
+ const pages = pace ? new Allowance(pace.documents.burst, pace.documents.perSecond / 1e3, 5e4) : void 0;
151
+ const addressFor = (request) => {
152
+ const get = (n) => request.headers.get(n) ?? void 0;
153
+ if (typeof clientIp === "function") {
154
+ let ip = null;
155
+ try {
156
+ ip = normalizeIp(clientIp(request) ?? void 0);
157
+ } catch (e) {
158
+ log.once("clientIp-threw", "warn", `clientIp threw: ${e?.message ?? e}`);
159
+ }
160
+ return ip ? { address: ip, internal: !isPublicIp(ip), via: "custom" } : { address: "", internal: false, via: "none" };
161
+ }
162
+ return resolveClientAddress({ peer: "", header: get }, clientIp, platform);
163
+ };
164
+ const readVerdict = async (cookie) => {
165
+ for (const s of secrets) {
166
+ const v = await readVerdictFrom(s, site, cookie).catch(() => null);
167
+ if (v) return v;
168
+ }
169
+ return null;
170
+ };
171
+ const pushed = /* @__PURE__ */ new Map();
172
+ const queue = [];
173
+ let inflight;
174
+ let lastFlush = 0;
175
+ const flush = async () => {
176
+ while (queue.length && health.canSend()) {
177
+ const events = queue.splice(0, 500);
178
+ lastFlush = Date.now();
179
+ try {
180
+ const res = await doFetch(`${collector}/_s/v1/server`, {
181
+ method: "POST",
182
+ headers: { "content-type": "application/json", authorization: `Bearer ${key}` },
183
+ body: JSON.stringify({ site, collect: collectReport(collect), events }),
184
+ signal: AbortSignal.timeout(timeoutMs)
185
+ });
186
+ if (res.status === 429) health.paused();
187
+ else if (res.status === 401 || res.status === 403) health.rejected(res.status);
188
+ else if (res.status >= 500) health.failing(`HTTP ${res.status}`);
189
+ else if (res.ok) {
190
+ health.ok();
191
+ const f = (await res.json().catch(() => null))?.flagged;
192
+ const now = Date.now();
193
+ for (const x of f?.sessions ?? []) if (typeof x.sid === "string" && Array.isArray(x.claims)) pushed.set(`s:${x.sid}`, { claims: x.claims, until: now + 6e5 });
194
+ for (const x of f?.visitors ?? []) if (typeof x.visitor === "string" && Array.isArray(x.claims)) pushed.set(`v:${x.visitor}`, { claims: x.claims, until: now + 6e5 });
195
+ if (pushed.size > 5e4) pushed.clear();
196
+ }
197
+ if (!res.ok) onError(new Error(`collector answered ${res.status} to /v1/server`));
198
+ } catch (e) {
199
+ health.failing(e?.name === "TimeoutError" ? `no answer within ${timeoutMs} ms` : String(e?.message ?? e));
200
+ onError(e);
201
+ }
202
+ }
203
+ if (!health.canSend()) queue.length = 0;
204
+ };
205
+ const flushSoon = (waitUntil, now = false) => {
206
+ if (!queue.length || inflight) return;
207
+ if (!now && Date.now() - lastFlush < flushIntervalMs && queue.length < 100) return;
208
+ inflight = flush().finally(() => inflight = void 0);
209
+ waitUntil?.(inflight);
210
+ };
211
+ const pushedFor = async (request, verified) => {
212
+ if (!pushed.size) return null;
213
+ const sid = cookieValue(request.headers.get("cookie"), SESSION_COOKIE);
214
+ const a = addressFor(request);
215
+ const now = Date.now();
216
+ const claims = [];
217
+ const k = [sid ? `s:${sid}` : ""];
218
+ if (collect.addresses !== "off" && !verified && !a.internal && a.address) k.push(`v:${await hmac(parsed.secret, `visitor:${a.address}`, 22)}`);
219
+ for (const x of k) {
220
+ const e = x ? pushed.get(x) : void 0;
221
+ if (e && e.until > now) claims.push(...e.claims);
222
+ }
223
+ return claims.length ? pushedVerdict(sid ?? "", site, claims, now) : null;
224
+ };
225
+ const proxy = async (request, p) => {
226
+ const url = new URL(request.url);
227
+ const headers = new Headers();
228
+ request.headers.forEach((v, k) => {
229
+ if (!NOT_FORWARDED.test(k) && !ADDRESS_HEADER.test(k)) headers.set(k, v);
230
+ });
231
+ const ref = request.headers.get("referer");
232
+ if (ref) {
233
+ try {
234
+ const o = new URL(ref).origin;
235
+ if (o !== "null") headers.set("referer", `${o}/`);
236
+ } catch {
237
+ }
238
+ }
239
+ const sid = cookieValue(request.headers.get("cookie"), SESSION_COOKIE);
240
+ if (sid && /^[\w-]{1,64}$/.test(sid)) headers.set("cookie", `${SESSION_COOKIE}=${sid}`);
241
+ headers.set("x-reguard-site", `${site}.${await hmac(parsed.secret, `prefix:${site}`, 16)}`);
242
+ const a = addressFor(request);
243
+ const value = collect.addresses === "off" || !a.address ? "-" : await hmac(parsed.secret, `visitor:${a.address}`, 22);
244
+ headers.set("x-reguard-visitor", `${value}.${await hmac(parsed.secret, `visitor-header:${value}`, 16)}`);
245
+ try {
246
+ const init = { method: request.method, headers, redirect: "manual", signal: AbortSignal.timeout(timeoutMs) };
247
+ if (request.method !== "GET" && request.method !== "HEAD" && request.body) {
248
+ init.body = request.body;
249
+ init.duplex = "half";
250
+ }
251
+ const r = await doFetch(`${collector}${p.decoded}${url.search}`, init);
252
+ const out = new Headers();
253
+ r.headers.forEach((v, k) => {
254
+ if (!STRIP_FROM_RESPONSE.has(k) && k !== "set-cookie") out.set(k, v);
255
+ });
256
+ for (const c of r.headers.getSetCookie?.() ?? []) out.append("set-cookie", c);
257
+ return new Response(request.method === "HEAD" ? null : r.body, { status: r.status, headers: out });
258
+ } catch (e) {
259
+ onError(e);
260
+ log.once("proxy-failed", "warn", `couldn't pass /_s/* to Reguard (${e?.message ?? e}): pages load without Reguard's script until it answers`);
261
+ return new Response(null, { status: 502 });
262
+ }
263
+ };
264
+ const decide = (request, reason, p, verdict, paceKind) => ({
265
+ reason,
266
+ dryRun: block.dryRun.has(reason),
267
+ status: reason === "pace" ? 429 : block.status,
268
+ retryAfter: RETRY_AFTER[reason],
269
+ ...paceKind ? { pace: paceKind } : {},
270
+ claims: reason === "pace" ? [] : verdict?.claims ?? [],
271
+ verdict,
272
+ path: p.decoded,
273
+ clientIp: addressFor(request).address
274
+ });
275
+ const act = async (request, d) => {
276
+ decisions.set(request, d);
277
+ try {
278
+ block.onBlock?.(d, request);
279
+ } catch (e) {
280
+ log.once("onBlock-threw", "warn", `block.onBlock threw: ${e?.message ?? e}`);
281
+ }
282
+ log.debug(`${d.dryRun ? "would block" : "blocked"} ${request.method} ${d.path}: ${d.reason}`);
283
+ if (d.dryRun) return void 0;
284
+ const respond = block.respond;
285
+ if (respond) {
286
+ try {
287
+ const r = await respond(request, d);
288
+ if (r instanceof Response) return r;
289
+ log.once("respond-silent", "warn", "block.respond didn't return a Response: sent the default answer");
290
+ } catch (e) {
291
+ log.once("respond-threw", "error", `block.respond threw (${e?.message ?? e}): sent the default answer instead`);
292
+ }
293
+ }
294
+ return defaultBlockAnswer(request, d);
295
+ };
296
+ const handle = async (request) => {
297
+ const p = canonicalPath(new URL(request.url).pathname);
298
+ if (isReguardPath(p.decoded)) return proxy(request, p);
299
+ if (denyMaps && isSourceMapPath(p)) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
300
+ const cookie = request.headers.get("cookie");
301
+ const pending = (async () => {
302
+ const browser = await readVerdict(cookie);
303
+ const pushedV = await pushedFor(request, !!browser);
304
+ return { browser, pushed: pushedV, merged: mergeVerdicts(browser, pushedV) };
305
+ })();
306
+ verdicts.set(request, pending);
307
+ if (!block) return void 0;
308
+ const allowed = (allowList ? matchesBoth(allowList, p) : false) || (() => {
309
+ try {
310
+ return block.allowIf?.(request) === true;
311
+ } catch {
312
+ return false;
313
+ }
314
+ })();
315
+ if (allowed) return void 0;
316
+ const get = (n) => request.headers.get(n) ?? void 0;
317
+ if (pages && get("sec-fetch-dest") === void 0 && (request.method === "GET" || request.method === "HEAD") && requestKind(p.decoded) === "document" && !isSpeculativeHeaders(get)) {
318
+ const tool = toolOf(get("user-agent"));
319
+ const a = addressFor(request);
320
+ if (!(tool && BENIGN_TOOL_FAMILIES.has(tool.family)) && a.address && !a.internal && !pages.take(a.address)) {
321
+ const answered = await act(request, decide(request, "pace", p, null, "document"));
322
+ if (answered) return answered;
323
+ }
324
+ }
325
+ const v = await pending;
326
+ const opt = { labels: block.labels, minStage: block.minStage };
327
+ const reason = v.browser?.flagged(opt) ? "flagged" : v.pushed?.flagged(opt) ? "flagged_server" : void 0;
328
+ if (reason) {
329
+ const d = decide(request, reason, p, v.merged);
330
+ if (!d.dryRun || !decisions.has(request)) return act(request, d);
331
+ }
332
+ return void 0;
333
+ };
334
+ const record = (request, response, ctx) => {
335
+ if (!collect.requests) return;
336
+ void (async () => {
337
+ try {
338
+ const url = new URL(request.url);
339
+ const p = canonicalPath(url.pathname);
340
+ if (isReguardPath(p.decoded) || matchesEither(skipped, p) || ignore && matchesEither(ignore, p)) return;
341
+ const get = (n) => request.headers.get(n) ?? void 0;
342
+ const sid = cookieValue(get("cookie"), SESSION_COOKIE);
343
+ const decision = decisions.get(request);
344
+ const target = `${url.pathname}${url.search}`;
345
+ if (!sid && !decision) {
346
+ if (options.watchSessionless === false || collect.addresses === "off") return;
347
+ const secure = url.protocol === "https:" ? true : void 0;
348
+ if (!watchworthy({ userAgent: get("user-agent") ?? "", acceptLanguage: get("accept-language"), accept: get("accept"), secFetchMode: get("sec-fetch-mode"), secChUa: get("sec-ch-ua"), secure, path: url.pathname, status: response.status })) return;
349
+ }
350
+ const a = addressFor(request);
351
+ const hash = (s) => hmac(parsed.secret, s, 16);
352
+ const contentType = response.headers.get("content-type") ?? "";
353
+ const responseBytes = Number(response.headers.get("content-length") ?? 0) || 0;
354
+ const requestBytes = Number(get("content-length") ?? 0) || 0;
355
+ let exchange;
356
+ if (!isSpeculativeHeaders(get) && isApiLike(target, contentType, requestBytes)) {
357
+ const input = { method: request.method, url: target, requestContentType: get("content-type") ?? "", requestBody: "", requestBytes, status: response.status, responseContentType: contentType, responseBytes };
358
+ const wanted = /* @__PURE__ */ new Set();
359
+ describeExchange((s) => (wanted.add(s), ""), input);
360
+ const memo = new Map(await Promise.all([...wanted].map(async (s) => [s, await hash(s)])));
361
+ const d = describeExchange((s) => memo.get(s) ?? "", input);
362
+ if (collect.pages === "masked") exchange = d;
363
+ else if (collect.pages === "hashed") exchange = { ...d, endpoint: `~${await hash(`endpoint:${d.endpoint}`)}` };
364
+ else {
365
+ const { item: _item, ...rest } = d;
366
+ exchange = { ...rest, endpoint: "" };
367
+ }
368
+ }
369
+ queue.push({
370
+ ...sid ? { sid } : {},
371
+ at: Date.now(),
372
+ method: request.method,
373
+ url: collect.pages === "masked" ? privateUrl(target) : "",
374
+ ...collect.pages !== "off" ? { item: await hash(`path:${url.pathname}`) } : {},
375
+ ...collect.pages !== "masked" ? { traits: pathTraits(target, get("rsc") === "1") } : {},
376
+ status: response.status,
377
+ headers: Object.fromEntries(["rsc", "next-router-prefetch", "sec-purpose", "purpose"].flatMap((n) => get(n) !== void 0 ? [[n, get(n)]] : [])),
378
+ client: {
379
+ ua: get("user-agent") ?? "",
380
+ accept: get("accept") ?? "",
381
+ acceptLanguage: get("accept-language") ?? "",
382
+ secFetchMode: get("sec-fetch-mode"),
383
+ secFetchSite: get("sec-fetch-site"),
384
+ secFetchDest: get("sec-fetch-dest"),
385
+ secChUa: get("sec-ch-ua"),
386
+ hasCookie: !!get("cookie"),
387
+ hasReferer: !!get("referer"),
388
+ ...url.protocol === "https:" ? { secure: true } : {}
389
+ },
390
+ ...!sid && a.address && collect.addresses !== "off" ? { visitor: await hmac(parsed.secret, `visitor:${a.address}`, 22) } : {},
391
+ ...exchange ? { exchange } : {},
392
+ ...decision?.pace ? { pace: decision.pace } : {},
393
+ ...decision ? { decision: { reason: decision.reason, dryRun: decision.dryRun } } : {},
394
+ ...a.internal ? { internal: true } : {}
395
+ });
396
+ if (queue.length > 5e3) queue.splice(0, queue.length - 5e3);
397
+ flushSoon(ctx?.waitUntil, !!decision);
398
+ } catch (e) {
399
+ onError(e);
400
+ }
401
+ })();
402
+ };
403
+ const timer = typeof setInterval === "function" ? setInterval(() => flushSoon(void 0, true), flushIntervalMs) : void 0;
404
+ timer?.unref?.();
405
+ return {
406
+ site,
407
+ handle: (request) => handle(request),
408
+ record,
409
+ wrap(handler) {
410
+ return async (request, ...rest) => {
411
+ const waitUntil = findWaitUntil(rest);
412
+ const early = await handle(request);
413
+ if (early) {
414
+ record(request, early, { waitUntil });
415
+ return early;
416
+ }
417
+ const res = await handler(request, ...rest);
418
+ record(request, res, { waitUntil });
419
+ return res;
420
+ };
421
+ },
422
+ verdict: async (request) => (await verdicts.get(request))?.merged ?? mergeVerdicts(await readVerdict(request.headers.get("cookie")), null),
423
+ decision: (request) => {
424
+ const d = decisions.get(request);
425
+ return d?.dryRun ? d : null;
426
+ },
427
+ scriptTag: (opts) => renderScriptTag(tagSettings, opts?.nonce),
428
+ flush: async () => {
429
+ await inflight;
430
+ await flush();
431
+ }
432
+ };
433
+ }
434
+
435
+ export {
436
+ defaultBlockAnswer,
437
+ reguardFetch
438
+ };