workers-start 0.9.0 → 0.12.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.
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Rate limiting on the Workers rate limiting binding, with one answer for
3
+ * every app: the client is keyed by a salted hash of its IP (never the raw
4
+ * address) or by an API key the app names, a missing binding fails open and
5
+ * says so once per isolate, and a limited request gets a 429 problem
6
+ * (RFC 9457) with `Retry-After`, the IETF `RateLimit-Policy` and `RateLimit`
7
+ * headers, and `cache-control: no-store`.
8
+ *
9
+ * The binding counts per Cloudflare location over 10 or 60 seconds. Quotas
10
+ * over hours or days (a plan's daily allowance) are product rules, not abuse
11
+ * limits; keep those in the app's database.
12
+ */
13
+ /** The `ratelimits` binding, structurally. */
14
+ export interface RateLimitBinding {
15
+ limit(options: {
16
+ key: string;
17
+ }): Promise<{
18
+ success: boolean;
19
+ }>;
20
+ }
21
+ export interface RateLimitPolicy {
22
+ /** Names the limit in the headers, such as `api` or `join`. */
23
+ name: string;
24
+ /** Requests allowed per period. Must match the binding's wrangler config. */
25
+ limit: number;
26
+ /** The binding's period: 10 or 60 seconds. */
27
+ periodSeconds: 10 | 60;
28
+ }
29
+ /**
30
+ * A stable, anonymous key for the client: the SHA-256 of `salt` and the
31
+ * client IP (`cf-connecting-ip`), hex, 32 characters. Without an IP (a
32
+ * request from a test or a service binding) the key is `anon`.
33
+ */
34
+ export declare function clientKey(request: Request, { salt }?: {
35
+ salt?: string;
36
+ }): Promise<string>;
37
+ /**
38
+ * Whether the request may go ahead. A missing binding allows it (failing
39
+ * closed would take the site down over a config slip) and calls `onUnbound`
40
+ * once per isolate so the slip is seen. So does a binding that throws.
41
+ */
42
+ export declare function checkRateLimit(binding: RateLimitBinding | undefined | null, key: string, { onUnbound }?: {
43
+ onUnbound?: (error?: unknown) => void;
44
+ }): Promise<boolean>;
45
+ /** The IETF rate limit headers for a limited response, with `Retry-After`. */
46
+ export declare function rateLimitHeaders(policy: RateLimitPolicy): Record<string, string>;
47
+ /** The 429 problem for `policy`. `detail` replaces the default sentence. */
48
+ export declare function tooManyRequests(policy: RateLimitPolicy, { detail }?: {
49
+ detail?: string;
50
+ }): Response;
51
+ export interface RateLimitOptions {
52
+ /** The key to count by. Defaults to `clientKey(request, { salt })`. */
53
+ key?: string;
54
+ /** Salt for the default IP key, such as a secret from the env. */
55
+ salt?: string;
56
+ /** Let verified bots (`request.cf.verifiedBotCategory`) through uncounted. */
57
+ allowVerifiedBots?: boolean;
58
+ /** Called once per isolate when the binding is missing or fails. */
59
+ onUnbound?: (error?: unknown) => void;
60
+ /** Detail for the 429. */
61
+ detail?: string;
62
+ }
63
+ /**
64
+ * Counts the request against `policy` and returns the 429 to send, or null
65
+ * to go ahead.
66
+ *
67
+ * const limited = await rateLimit(request, env.API_LIMIT, API_POLICY);
68
+ * if (limited) return limited;
69
+ */
70
+ export declare function rateLimit(request: Request, binding: RateLimitBinding | undefined | null, policy: RateLimitPolicy, options?: RateLimitOptions): Promise<Response | null>;
71
+ //# sourceMappingURL=rate-limit.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,8CAA8C;AAC9C,MAAM,WAAW,gBAAgB;IAC/B,KAAK,CAAC,OAAO,EAAE;QAAE,GAAG,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,OAAO,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;CAChE;AAED,MAAM,WAAW,eAAe;IAC9B,+DAA+D;IAC/D,IAAI,EAAE,MAAM,CAAC;IACb,6EAA6E;IAC7E,KAAK,EAAE,MAAM,CAAC;IACd,8CAA8C;IAC9C,aAAa,EAAE,EAAE,GAAG,EAAE,CAAC;CACxB;AAID;;;;GAIG;AACH,wBAAsB,SAAS,CAC7B,OAAO,EAAE,OAAO,EAChB,EAAE,IAAS,EAA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yed by a salted hash of its IP (never the raw
4
+ * address) or by an API key the app names, a missing binding fails open and
5
+ * says so once per isolate, and a limited request gets a 429 problem
6
+ * (RFC 9457) with `Retry-After`, the IETF `RateLimit-Policy` and `RateLimit`
7
+ * headers, and `cache-control: no-store`.
8
+ *
9
+ * The binding counts per Cloudflare location over 10 or 60 seconds. Quotas
10
+ * over hours or days (a plan's daily allowance) are product rules, not abuse
11
+ * limits; keep those in the app's database.
12
+ */
13
+ const encoder = new TextEncoder();
14
+ /**
15
+ * A stable, anonymous key for the client: the SHA-256 of `salt` and the
16
+ * client IP (`cf-connecting-ip`), hex, 32 characters. Without an IP (a
17
+ * request from a test or a service binding) the key is `anon`.
18
+ */
19
+ export async function clientKey(request, { salt = "" } = {}) {
20
+ const ip = request.headers.get("cf-connecting-ip")?.trim();
21
+ if (!ip)
22
+ return "anon";
23
+ const digest = await crypto.subtle.digest("SHA-256", encoder.encode(`${salt}\n${ip}`));
24
+ return [...new Uint8Array(digest).slice(0, 16)]
25
+ .map((b) => b.toString(16).padStart(2, "0"))
26
+ .join("");
27
+ }
28
+ const reported = new WeakSet();
29
+ let reportedUnbound = false;
30
+ /**
31
+ * Whether the request may go ahead. A missing binding allows it (failing
32
+ * closed would take the site down over a config slip) and calls `onUnbound`
33
+ * once per isolate so the slip is seen. So does a binding that throws.
34
+ */
35
+ export async function checkRateLimit(binding, key, { onUnbound } = {}) {
36
+ if (!binding) {
37
+ if (!reportedUnbound) {
38
+ reportedUnbound = true;
39
+ onUnbound?.();
40
+ }
41
+ return true;
42
+ }
43
+ try {
44
+ return (await binding.limit({ key })).success;
45
+ }
46
+ catch (error) {
47
+ if (!reported.has(binding)) {
48
+ reported.add(binding);
49
+ onUnbound?.(error);
50
+ }
51
+ return true;
52
+ }
53
+ }
54
+ /** The IETF rate limit headers for a limited response, with `Retry-After`. */
55
+ export function rateLimitHeaders(policy) {
56
+ const name = JSON.stringify(policy.name);
57
+ return {
58
+ "retry-after": String(policy.periodSeconds),
59
+ "ratelimit-policy": `${name};q=${policy.limit};w=${policy.periodSeconds}`,
60
+ ratelimit: `${name};r=0;t=${policy.periodSeconds}`,
61
+ };
62
+ }
63
+ /** The 429 problem for `policy`. `detail` replaces the default sentence. */
64
+ export function tooManyRequests(policy, { detail } = {}) {
65
+ const body = {
66
+ type: "about:blank",
67
+ title: "Too Many Requests",
68
+ status: 429,
69
+ code: "rate_limited",
70
+ detail: detail ??
71
+ `Too many requests. Try again in ${policy.periodSeconds} seconds.`,
72
+ };
73
+ return new Response(JSON.stringify(body), {
74
+ status: 429,
75
+ headers: {
76
+ "content-type": "application/problem+json",
77
+ "cache-control": "no-store",
78
+ ...rateLimitHeaders(policy),
79
+ },
80
+ });
81
+ }
82
+ /**
83
+ * Counts the request against `policy` and returns the 429 to send, or null
84
+ * to go ahead.
85
+ *
86
+ * const limited = await rateLimit(request, env.API_LIMIT, API_POLICY);
87
+ * if (limited) return limited;
88
+ */
89
+ export async function rateLimit(request, binding, policy, options = {}) {
90
+ if (options.allowVerifiedBots) {
91
+ const cf = request.cf;
92
+ if (cf?.verifiedBotCategory)
93
+ return null;
94
+ }
95
+ const key = options.key ??
96
+ (await clientKey(request, options.salt ? { salt: options.salt } : {}));
97
+ const allowed = await checkRateLimit(binding, `${policy.name}:${key}`, options.onUnbound ? { onUnbound: options.onUnbound } : {});
98
+ return allowed
99
+ ? null
100
+ : tooManyRequests(policy, options.detail ? { detail: options.detail } : {});
101
+ }
102
+ //# sourceMappingURL=rate-limit.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rate-limit.js","sourceRoot":"","sources":["../src/rate-limit.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAgBH,MAAM,OAAO,GAAG,IAAI,WAAW,EAAE,CAAC;AAElC;;;;GAIG;AACH,MAAM,CAAC,KAAK,UAAU,SAAS,CAC7B,OAAgB,EAChB,EAAE,IAAI,GAAG,EAAE,EAAE,GAAsB,EAAE;IAErC,MAAM,EAAE,GAAG,OAAO,CAA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IAC3C,CAAC;IACD,MAAM,GAAG,GACP,OAAO,CAAC,GAAG;QACX,CAAC,MAAM,SAAS,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACzE,MAAM,OAAO,GAAG,MAAM,cAAc,CAClC,OAAO,EACP,GAAG,MAAM,CAAC,IAAI,IAAI,GAAG,EAAE,EACvB,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,OAAO,CAAC,SAAS,EAAE,CAAC,CAAC,CAAC,EAAE,CAC1D,CAAC;IACF,OAAO,OAAO;QACZ,CAAC,CAAC,IAAI;QACN,CAAC,CAAC,eAAe,CAAC,MAAM,EAAE,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC;AAChF,CAAC"}
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Sentry options for a Worker and its pages, without importing an SDK: the
3
+ * objects here go straight into `withSentry` from `@sentry/cloudflare` and
4
+ * `Sentry.init` from a browser SDK.
5
+ *
6
+ * What every app had written for itself: no DSN means no SDK traffic, events
7
+ * from a local server (`wrangler dev`, `vite preview`) never reach the
8
+ * production project, and in the browser the noise that is not the app's to
9
+ * fix (requests that never left the device, extension and injected wallet
10
+ * scripts, users declining a wallet prompt) is dropped. The Worker side gets
11
+ * no message filters: browser wording describes nothing workerd says, so a
12
+ * filter there could only hide a real failure.
13
+ *
14
+ * Release and environment are left unset unless given, so
15
+ * `@sentry/cloudflare` reads `SENTRY_RELEASE` (or `CF_VERSION_METADATA`) and
16
+ * `SENTRY_ENVIRONMENT` from the Worker's env itself.
17
+ */
18
+ /** The part of a Sentry event the filters read. */
19
+ export interface SentryEventLike {
20
+ request?: {
21
+ url?: string;
22
+ };
23
+ message?: string;
24
+ logentry?: {
25
+ message?: string;
26
+ };
27
+ exception?: {
28
+ values?: {
29
+ value?: string;
30
+ type?: string;
31
+ }[];
32
+ };
33
+ }
34
+ type AnyEvent = any;
35
+ type BeforeSend = (event: AnyEvent, hint: AnyEvent) => AnyEvent;
36
+ /** Whether the event's request was served from this machine. An event with no request (a cron run, a workflow step) is not local. */
37
+ export declare function isLocalEvent(event: SentryEventLike): boolean;
38
+ /** A `beforeSend` that drops local events and keeps the rest. */
39
+ export declare function dropLocalEvents<T extends SentryEventLike>(event: T): T | null;
40
+ /** Browser wording for a request that never left the device: Chrome, Safari, Firefox. */
41
+ export declare const NETWORK_ERROR: RegExp;
42
+ /** Errors thrown by extension content scripts and injected wallets. */
43
+ export declare const EXTENSION_ERROR: RegExp;
44
+ /** A person declining a wallet prompt. */
45
+ export declare const USER_REJECTION: RegExp;
46
+ /** Scripts other people inject into the page: extensions, wallets and Google Translate's proxy. */
47
+ export declare const BROWSER_DENY_URLS: readonly RegExp[];
48
+ /** Whether a browser event is noise that is not the app's to fix. `extra` adds patterns matched against its messages. */
49
+ export declare function isBrowserNoise(event: SentryEventLike, extra?: readonly RegExp[]): boolean;
50
+ /** A DSN worth using: an `https://` URL. Anything else (empty, `off`, a placeholder) turns Sentry off. */
51
+ export declare function validDsn(dsn: string | null | undefined): string | undefined;
52
+ interface CommonOptions {
53
+ /** Overrides the DSN read from the env. */
54
+ dsn?: string | undefined;
55
+ /** Left unset by default: an unset rate means no tracing at all, where 0 still creates unsampled spans. */
56
+ tracesSampleRate?: number;
57
+ /** Runs after the built-in filters. */
58
+ beforeSend?: BeforeSend;
59
+ /** Tags set on every event, such as `{ runtime: "worker", worker: "api" }`. */
60
+ tags?: Record<string, string>;
61
+ release?: string;
62
+ environment?: string;
63
+ }
64
+ export interface WorkerSentryOptions {
65
+ dsn: string | undefined;
66
+ enabled: boolean;
67
+ tracesSampleRate?: number;
68
+ beforeSend: BeforeSend;
69
+ beforeSendTransaction: BeforeSend;
70
+ initialScope?: {
71
+ tags: Record<string, string>;
72
+ };
73
+ release?: string;
74
+ environment?: string;
75
+ }
76
+ /**
77
+ * Options for `withSentry`, `instrumentWorkflowWithSentry` and
78
+ * `instrumentDurableObjectWithSentry`. Reads `SENTRY_DSN` from the env;
79
+ * spread the result and add anything app-specific (integrations, samplers).
80
+ */
81
+ export declare function workerSentryOptions(env: {
82
+ SENTRY_DSN?: string | undefined;
83
+ }, options?: CommonOptions): WorkerSentryOptions;
84
+ export interface BrowserSentryOptions extends WorkerSentryOptions {
85
+ denyUrls: RegExp[];
86
+ }
87
+ /**
88
+ * Options for a browser SDK's `Sentry.init`. Pass the DSN (from the build),
89
+ * and `enabled: false` for dev builds, which the browser cannot tell from
90
+ * the env.
91
+ */
92
+ export declare function browserSentryOptions(options?: CommonOptions & {
93
+ enabled?: boolean;
94
+ /** More script URLs to ignore. */
95
+ denyUrls?: readonly RegExp[];
96
+ /** More messages that are noise. */
97
+ noise?: readonly RegExp[];
98
+ /** Events to keep even when they read like noise, such as handled captures from a wallet flow. */
99
+ keep?: (event: AnyEvent) => boolean;
100
+ }): BrowserSentryOptions;
101
+ export {};
102
+ //# sourceMappingURL=sentry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sentry.d.ts","sourceRoot":"","sources":["../src/sentry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,mDAAmD;AACnD,MAAM,WAAW,eAAe;IAC9B,OAAO,CAAC,EAAE;QAAE,GAAG,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,QAAQ,CAAC,EAAE;QAAE,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IAChC,SAAS,CAAC,EAAE;QAAE,MAAM,CAAC,EAAE;YAAE,KAAK,CAAC,EAAE,MAAM,CAAC;YAAC,IAAI,CAAC,EAAE,MAAM,CAAA;SAAE,EAAE,CAAA;KAAE,CAAC;CAC9D;A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B,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,UAAU,EAAE,UAAU,CAAC;IACvB,qBAAqB,EAAE,UAAU,CAAC;IAClC,YAAY,CAAC,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;KAAE,CAAC;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,GAAG,EAAE;IAAE,UAAU,CAAC,EAAE,MAAM,GAAG,SAAS,CAAA;CAAE,EACxC,OAAO,GAAE,aAAkB,GAC1B,mBAAmB,CAcrB;AAED,MAAM,WAAW,oBAAqB,SAAQ,mBAAmB;IAC/D,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAClC,OAAO,GAAE,aAAa,GAAG;IACvB,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,kCAAkC;IAClC,QAAQ,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC7B,oCAAoC;IACpC,KAAK,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1B,kGAAkG;IAClG,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,QAAQ,KAAK,OAAO,CAAC;CAChC,GACL,oBAAoB,CAoBtB"}
package/dist/sentry.js ADDED
@@ -0,0 +1,137 @@
1
+ /**
2
+ * Sentry options for a Worker and its pages, without importing an SDK: the
3
+ * objects here go straight into `withSentry` from `@sentry/cloudflare` and
4
+ * `Sentry.init` from a browser SDK.
5
+ *
6
+ * What every app had written for itself: no DSN means no SDK traffic, events
7
+ * from a local server (`wrangler dev`, `vite preview`) never reach the
8
+ * production project, and in the browser the noise that is not the app's to
9
+ * fix (requests that never left the device, extension and injected wallet
10
+ * scripts, users declining a wallet prompt) is dropped. The Worker side gets
11
+ * no message filters: browser wording describes nothing workerd says, so a
12
+ * filter there could only hide a real failure.
13
+ *
14
+ * Release and environment are left unset unless given, so
15
+ * `@sentry/cloudflare` reads `SENTRY_RELEASE` (or `CF_VERSION_METADATA`) and
16
+ * `SENTRY_ENVIRONMENT` from the Worker's env itself.
17
+ */
18
+ const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]", "::1"]);
19
+ /** Whether the event's request was served from this machine. An event with no request (a cron run, a workflow step) is not local. */
20
+ export function isLocalEvent(event) {
21
+ const url = event.request?.url;
22
+ if (!url)
23
+ return false;
24
+ try {
25
+ const host = new URL(url).hostname;
26
+ return LOCAL_HOSTS.has(host) || host.endsWith(".localhost");
27
+ }
28
+ catch {
29
+ return false;
30
+ }
31
+ }
32
+ /** A `beforeSend` that drops local events and keeps the rest. */
33
+ export function dropLocalEvents(event) {
34
+ return isLocalEvent(event) ? null : event;
35
+ }
36
+ /** Browser wording for a request that never left the device: Chrome, Safari, Firefox. */
37
+ export const NETWORK_ERROR = /failed to fetch|load failed|network ?error/i;
38
+ /** Errors thrown by extension content scripts and injected wallets. */
39
+ export const EXTENSION_ERROR = /func \w+ not found|tronlink|trap returned falsish|origin not allowed|object captured as promise rejection with keys: (?=[^\n]*\bcode\b)(?=[^\n]*\bmessage\b)/i;
40
+ /** A person declining a wallet prompt. */
41
+ export const USER_REJECTION = /user rejected|user denied|rejected the request/i;
42
+ /** Scripts other people inject into the page: extensions, wallets and Google Translate's proxy. */
43
+ export const BROWSER_DENY_URLS = [
44
+ /\/_\/translate_http\//i,
45
+ /injected\.js/i,
46
+ /inpage\.js/i,
47
+ /contentscript/i,
48
+ /chrome-extension:\/\//i,
49
+ /moz-extension:\/\//i,
50
+ /safari-(web-)?extension:\/\//i,
51
+ /ms-browser-extension:\/\//i,
52
+ /webkit-masked-url:/i,
53
+ ];
54
+ /** The texts the noise check reads: the exception value, the message and the log entry. */
55
+ function messagesOf(event) {
56
+ return [
57
+ event.exception?.values?.[0]?.value,
58
+ event.message,
59
+ event.logentry?.message,
60
+ ].filter((m) => typeof m === "string" && m !== "");
61
+ }
62
+ /** Whether a browser event is noise that is not the app's to fix. `extra` adds patterns matched against its messages. */
63
+ export function isBrowserNoise(event, extra = []) {
64
+ const patterns = [NETWORK_ERROR, EXTENSION_ERROR, USER_REJECTION, ...extra];
65
+ return messagesOf(event).some((m) => patterns.some((re) => re.test(m)));
66
+ }
67
+ /** A DSN worth using: an `https://` URL. Anything else (empty, `off`, a placeholder) turns Sentry off. */
68
+ export function validDsn(dsn) {
69
+ const value = dsn?.trim();
70
+ return value?.startsWith("https://") ? value : undefined;
71
+ }
72
+ function chain(...steps) {
73
+ return (event, hint) => {
74
+ let current = event;
75
+ for (const step of steps) {
76
+ if (!step || current === null)
77
+ continue;
78
+ current = step(current, hint);
79
+ }
80
+ return current;
81
+ };
82
+ }
83
+ /**
84
+ * Options for `withSentry`, `instrumentWorkflowWithSentry` and
85
+ * `instrumentDurableObjectWithSentry`. Reads `SENTRY_DSN` from the env;
86
+ * spread the result and add anything app-specific (integrations, samplers).
87
+ */
88
+ export function workerSentryOptions(env, options = {}) {
89
+ const dsn = validDsn(options.dsn ?? env.SENTRY_DSN);
90
+ const out = {
91
+ dsn,
92
+ enabled: dsn !== undefined,
93
+ beforeSend: chain(dropLocalEvents, options.beforeSend),
94
+ beforeSendTransaction: dropLocalEvents,
95
+ };
96
+ if (options.tracesSampleRate !== undefined)
97
+ out.tracesSampleRate = options.tracesSampleRate;
98
+ if (options.tags)
99
+ out.initialScope = { tags: options.tags };
100
+ if (options.release)
101
+ out.release = options.release;
102
+ if (options.environment)
103
+ out.environment = options.environment;
104
+ return out;
105
+ }
106
+ /**
107
+ * Options for a browser SDK's `Sentry.init`. Pass the DSN (from the build),
108
+ * and `enabled: false` for dev builds, which the browser cannot tell from
109
+ * the env.
110
+ */
111
+ export function browserSentryOptions(options = {}) {
112
+ const dsn = validDsn(options.dsn);
113
+ const noise = options.noise ?? [];
114
+ const out = {
115
+ dsn,
116
+ enabled: dsn !== undefined && options.enabled !== false,
117
+ denyUrls: [...BROWSER_DENY_URLS, ...(options.denyUrls ?? [])],
118
+ beforeSend: chain((event) => {
119
+ if (isLocalEvent(event))
120
+ return null;
121
+ if (options.keep?.(event))
122
+ return event;
123
+ return isBrowserNoise(event, noise) ? null : event;
124
+ }, options.beforeSend),
125
+ beforeSendTransaction: dropLocalEvents,
126
+ };
127
+ if (options.tracesSampleRate !== undefined)
128
+ out.tracesSampleRate = options.tracesSampleRate;
129
+ if (options.tags)
130
+ out.initialScope = { tags: options.tags };
131
+ if (options.release)
132
+ out.release = options.release;
133
+ if (options.environment)
134
+ out.environment = options.environment;
135
+ return out;
136
+ }
137
+ //# sourceMappingURL=sentry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sentry.js","sourceRoot":"","sources":["../src/sentry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAcH,MAAM,WAAW,GAAG,IAAI,GAAG,CAAC,CAAC,WAAW,EAAE,WAAW,EAAE,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC;AAExE,qIAAqI;AACrI,MAAM,UAAU,YAAY,CAAC,KAAsB;IACjD,MAAM,GAAG,GAAG,KAAK,CAAC,OAAO,EAAE,GAAG,CAAC;IAC/B,IAAI,CAAC,GAAG;QAAE,OAAO,KAAK,CAAC;IACvB,IAAI,CAAC;QACH,MAAM,IAAI,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC;QACnC,OAAO,WAAW,CAAC,GAAG,CAAC,IAAI,CAAC,IAAI,IAAI,CAAC,QAAQ,CAAC,YAAY,CAAC,CAAC;IAC9D,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,KAAK,CAAC;IACf,CAAC;AACH,CAAC;AAED,iEAAiE;AACjE,MAAM,UAAU,eAAe,CAA4B,KAAQ;IACjE,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,KAAK,CAAC;AAC5C,CAAC;AAED,yFAAyF;A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
+ "version": "0.12.0",
4
4
  "description": "The parts every TanStack Start app on Cloudflare Workers ends up writing: Markdown for agents on the same URL, a head helper that stops share cards leaking between pages, lazy Workers bindings, and a check that no local secret ships in the build.",
5
5
  "license": "MIT",
6
6
  "author": "Ryan Ghods",
@@ -23,7 +23,11 @@
23
23
  "markdown",
24
24
  "llms",
25
25
  "google-analytics",
26
- "search-console"
26
+ "search-console",
27
+ "sentry",
28
+ "email",
29
+ "resend",
30
+ "rate-limit"
27
31
  ],
28
32
  "type": "module",
29
33
  "sideEffects": false,
@@ -88,6 +92,21 @@
88
92
  "import": "./dist/google.js",
89
93
  "default": "./dist/google.js"
90
94
  },
95
+ "./sentry": {
96
+ "types": "./dist/sentry.d.ts",
97
+ "import": "./dist/sentry.js",
98
+ "default": "./dist/sentry.js"
99
+ },
100
+ "./mail": {
101
+ "types": "./dist/mail.d.ts",
102
+ "import": "./dist/mail.js",
103
+ "default": "./dist/mail.js"
104
+ },
105
+ "./rate-limit": {
106
+ "types": "./dist/rate-limit.d.ts",
107
+ "import": "./dist/rate-limit.js",
108
+ "default": "./dist/rate-limit.js"
109
+ },
91
110
  "./package.json": "./package.json"
92
111
  },
93
112
  "bin": {
package/src/google.ts CHANGED
@@ -344,12 +344,15 @@ export function ga4Rows(
344
344
  });
345
345
  }
346
346
 
347
- /** A filter matching a dimension against a list of values. */
347
+ /** A filter matching a dimension against a list of values. Google matches case-sensitively unless `caseSensitive: false`. */
348
348
  export function inListFilter(
349
349
  fieldName: string,
350
350
  values: readonly string[],
351
+ { caseSensitive }: { caseSensitive?: boolean } = {},
351
352
  ): Ga4FilterExpression {
352
- return { filter: { fieldName, inListFilter: { values: [...values] } } };
353
+ const inList: Record<string, unknown> = { values: [...values] };
354
+ if (caseSensitive !== undefined) inList.caseSensitive = caseSensitive;
355
+ return { filter: { fieldName, inListFilter: inList } };
353
356
  }
354
357
 
355
358
  // Search Console
package/src/index.ts CHANGED
@@ -76,6 +76,35 @@ export type {
76
76
  SiteHead,
77
77
  } from "./head.js";
78
78
  export { createPageHead, jsonLdScript } from "./head.js";
79
+ export type {
80
+ MailAddress,
81
+ MailAttachment,
82
+ Mailer,
83
+ MailMessage,
84
+ MailResult,
85
+ ResendOptions,
86
+ SendEmailBinding,
87
+ } from "./mail.js";
88
+ export {
89
+ checkMessage,
90
+ cloudflareMailer,
91
+ escapeHtml,
92
+ MailError,
93
+ recordingMailer,
94
+ resendMailer,
95
+ } from "./mail.js";
96
+ export type {
97
+ RateLimitBinding,
98
+ RateLimitOptions,
99
+ RateLimitPolicy,
100
+ } from "./rate-limit.js";
101
+ export {
102
+ checkRateLimit,
103
+ clientKey,
104
+ rateLimit,
105
+ rateLimitHeaders,
106
+ tooManyRequests,
107
+ } from "./rate-limit.js";
79
108
  export type {
80
109
  AnalyticsScriptOptions,
81
110
  GaEventParams,
@@ -89,6 +118,23 @@ export {
89
118
  tagManagerScript,
90
119
  themeScript,
91
120
  } from "./scripts.js";
121
+ export type {
122
+ BrowserSentryOptions,
123
+ SentryEventLike,
124
+ WorkerSentryOptions,
125
+ } from "./sentry.js";
126
+ export {
127
+ BROWSER_DENY_URLS,
128
+ browserSentryOptions,
129
+ dropLocalEvents,
130
+ EXTENSION_ERROR,
131
+ isBrowserNoise,
132
+ isLocalEvent,
133
+ NETWORK_ERROR,
134
+ USER_REJECTION,
135
+ validDsn,
136
+ workerSentryOptions,
137
+ } from "./sentry.js";
92
138
  export type { RobotsOptions, RobotsRule, SitemapEntry } from "./seo.js";
93
139
  export { escapeXml, robotsTxt, sitemapXml } from "./seo.js";
94
140
  export type { WorkersModule } from "./workers.js";