@sentry/cloudflare 8.21.0 → 8.23.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 (51) hide show
  1. package/README.md +132 -8
  2. package/build/cjs/d1.js +157 -0
  3. package/build/cjs/d1.js.map +1 -0
  4. package/build/cjs/handler.js +45 -75
  5. package/build/cjs/handler.js.map +1 -1
  6. package/build/cjs/index.js +7 -0
  7. package/build/cjs/index.js.map +1 -1
  8. package/build/cjs/pages-plugin.js +52 -0
  9. package/build/cjs/pages-plugin.js.map +1 -0
  10. package/build/cjs/request.js +84 -0
  11. package/build/cjs/request.js.map +1 -0
  12. package/build/cjs/scope-utils.js +33 -0
  13. package/build/cjs/scope-utils.js.map +1 -0
  14. package/build/cjs/sdk.js +8 -3
  15. package/build/cjs/sdk.js.map +1 -1
  16. package/build/esm/d1.js +155 -0
  17. package/build/esm/d1.js.map +1 -0
  18. package/build/esm/handler.js +43 -73
  19. package/build/esm/handler.js.map +1 -1
  20. package/build/esm/index.js +4 -1
  21. package/build/esm/index.js.map +1 -1
  22. package/build/esm/pages-plugin.js +50 -0
  23. package/build/esm/pages-plugin.js.map +1 -0
  24. package/build/esm/request.js +82 -0
  25. package/build/esm/request.js.map +1 -0
  26. package/build/esm/scope-utils.js +29 -0
  27. package/build/esm/scope-utils.js.map +1 -0
  28. package/build/esm/sdk.js +5 -3
  29. package/build/esm/sdk.js.map +1 -1
  30. package/build/types/d1.d.ts +17 -0
  31. package/build/types/d1.d.ts.map +1 -0
  32. package/build/types/handler.d.ts +2 -2
  33. package/build/types/handler.d.ts.map +1 -1
  34. package/build/types/index.d.ts +4 -1
  35. package/build/types/index.d.ts.map +1 -1
  36. package/build/types/pages-plugin.d.ts +35 -0
  37. package/build/types/pages-plugin.d.ts.map +1 -0
  38. package/build/types/request.d.ts +13 -0
  39. package/build/types/request.d.ts.map +1 -0
  40. package/build/types/scope-utils.d.ts +15 -0
  41. package/build/types/scope-utils.d.ts.map +1 -0
  42. package/build/types/sdk.d.ts +4 -3
  43. package/build/types/sdk.d.ts.map +1 -1
  44. package/build/types-ts3.8/d1.d.ts +17 -0
  45. package/build/types-ts3.8/handler.d.ts +2 -2
  46. package/build/types-ts3.8/index.d.ts +4 -1
  47. package/build/types-ts3.8/pages-plugin.d.ts +35 -0
  48. package/build/types-ts3.8/request.d.ts +13 -0
  49. package/build/types-ts3.8/scope-utils.d.ts +15 -0
  50. package/build/types-ts3.8/sdk.d.ts +4 -3
  51. package/package.json +6 -7
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
  </a>
5
5
  </p>
6
6
 
7
- # Official Sentry SDK for Cloudflare [UNRELEASED]
7
+ # Official Sentry SDK for Cloudflare
8
8
 
9
9
  [![npm version](https://img.shields.io/npm/v/@sentry/cloudflare.svg)](https://www.npmjs.com/package/@sentry/cloudflare)
10
10
  [![npm dm](https://img.shields.io/npm/dm/@sentry/cloudflare.svg)](https://www.npmjs.com/package/@sentry/cloudflare)
@@ -15,12 +15,10 @@
15
15
  - [Official SDK Docs](https://docs.sentry.io/quickstart/)
16
16
  - [TypeDoc](http://getsentry.github.io/sentry-javascript/)
17
17
 
18
- **Note: This SDK is unreleased. Please follow the
18
+ **Note: This SDK is in an alpha state. Please follow the
19
19
  [tracking GH issue](https://github.com/getsentry/sentry-javascript/issues/12620) for updates.**
20
20
 
21
- Below details the setup for the Cloudflare Workers. Cloudflare Pages support is in active development.
22
-
23
- ## Setup (Cloudflare Workers)
21
+ ## Install
24
22
 
25
23
  To get started, first install the `@sentry/cloudflare` package:
26
24
 
@@ -36,6 +34,77 @@ compatibility_flags = ["nodejs_compat"]
36
34
  # compatibility_flags = ["nodejs_als"]
37
35
  ```
38
36
 
37
+ Then you can either setup up the SDK for [Cloudflare Pages](#setup-cloudflare-pages) or
38
+ [Cloudflare Workers](#setup-cloudflare-workers).
39
+
40
+ ## Setup (Cloudflare Pages)
41
+
42
+ To use this SDK, add the `sentryPagesPlugin` as
43
+ [middleware to your Cloudflare Pages application](https://developers.cloudflare.com/pages/functions/middleware/).
44
+
45
+ We recommend adding a `functions/_middleware.js` for the middleware setup so that Sentry is initialized for your entire
46
+ app.
47
+
48
+ ```javascript
49
+ // functions/_middleware.js
50
+ import * as Sentry from '@sentry/cloudflare';
51
+
52
+ export const onRequest = Sentry.sentryPagesPlugin({
53
+ dsn: process.env.SENTRY_DSN,
54
+ // Set tracesSampleRate to 1.0 to capture 100% of spans for tracing.
55
+ tracesSampleRate: 1.0,
56
+ });
57
+ ```
58
+
59
+ If you need to to chain multiple middlewares, you can do so by exporting an array of middlewares. Make sure the Sentry
60
+ middleware is the first one in the array.
61
+
62
+ ```javascript
63
+ import * as Sentry from '@sentry/cloudflare';
64
+
65
+ export const onRequest = [
66
+ // Make sure Sentry is the first middleware
67
+ Sentry.sentryPagesPlugin({
68
+ dsn: process.env.SENTRY_DSN,
69
+ tracesSampleRate: 1.0,
70
+ }),
71
+ // Add more middlewares here
72
+ ];
73
+ ```
74
+
75
+ If you need to access the `context` object (for example to grab environmental variables), you can pass a function to
76
+ `sentryPagesPlugin` that takes the `context` object as an argument and returns `init` options:
77
+
78
+ ```javascript
79
+ export const onRequest = Sentry.sentryPagesPlugin(context => ({
80
+ dsn: context.env.SENTRY_DSN,
81
+ tracesSampleRate: 1.0,
82
+ }));
83
+ ```
84
+
85
+ If you do not have access to the `onRequest` middleware API, you can use the `wrapRequestHandler` API instead.
86
+
87
+ Here is an example with SvelteKit:
88
+
89
+ ```javascript
90
+ // hooks.server.js
91
+ import * as Sentry from '@sentry/cloudflare';
92
+
93
+ export const handle = ({ event, resolve }) => {
94
+ const requestHandlerOptions = {
95
+ options: {
96
+ dsn: event.platform.env.SENTRY_DSN,
97
+ tracesSampleRate: 1.0,
98
+ },
99
+ request: event.request,
100
+ context: event.platform.ctx,
101
+ };
102
+ return Sentry.wrapRequestHandler(requestHandlerOptions, () => resolve(event));
103
+ };
104
+ ```
105
+
106
+ ## Setup (Cloudflare Workers)
107
+
39
108
  To use this SDK, wrap your handler with the `withSentry` function. This will initialize the SDK and hook into the
40
109
  environment. Note that you can turn off almost all side effects using the respective options.
41
110
 
@@ -58,7 +127,7 @@ export default withSentry(
58
127
  );
59
128
  ```
60
129
 
61
- ### Sourcemaps (Cloudflare Workers)
130
+ ### Sourcemaps
62
131
 
63
132
  Configure uploading sourcemaps via the Sentry Wizard:
64
133
 
@@ -68,10 +137,11 @@ npx @sentry/wizard@latest -i sourcemaps
68
137
 
69
138
  See more details in our [docs](https://docs.sentry.io/platforms/javascript/sourcemaps/).
70
139
 
71
- ## Usage (Cloudflare Workers)
140
+ ## Usage
72
141
 
73
142
  To set context information or send manual events, use the exported functions of `@sentry/cloudflare`. Note that these
74
- functions will require your exported handler to be wrapped in `withSentry`.
143
+ functions will require the usage of the Sentry helpers, either `withSentry` function for Cloudflare Workers or the
144
+ `sentryPagesPlugin` middleware for Cloudflare Pages.
75
145
 
76
146
  ```javascript
77
147
  import * as Sentry from '@sentry/cloudflare';
@@ -97,3 +167,57 @@ Sentry.captureEvent({
97
167
  ],
98
168
  });
99
169
  ```
170
+
171
+ ## Cloudflare D1 Instrumentation
172
+
173
+ You can use the `instrumentD1WithSentry` method to instrument [Cloudflare D1](https://developers.cloudflare.com/d1/),
174
+ Cloudflare's serverless SQL database with Sentry.
175
+
176
+ ```javascript
177
+ import * as Sentry from '@sentry/cloudflare';
178
+
179
+ // env.DB is the D1 DB binding configured in your `wrangler.toml`
180
+ const db = Sentry.instrumentD1WithSentry(env.DB);
181
+ // Now you can use the database as usual
182
+ await db.prepare('SELECT * FROM table WHERE id = ?').bind(1).run();
183
+ ```
184
+
185
+ ## Cron Monitoring (Cloudflare Workers)
186
+
187
+ [Sentry Crons](https://docs.sentry.io/product/crons/) allows you to monitor the uptime and performance of any scheduled,
188
+ recurring job in your application.
189
+
190
+ To instrument your cron triggers, use the `Sentry.withMonitor` API in your
191
+ [`Scheduled` handler](https://developers.cloudflare.com/workers/runtime-apis/handlers/scheduled/).
192
+
193
+ ```js
194
+ export default {
195
+ async scheduled(event, env, ctx) {
196
+ ctx.waitUntil(
197
+ Sentry.withMonitor('your-cron-name', () => {
198
+ return doSomeTaskOnASchedule();
199
+ }),
200
+ );
201
+ },
202
+ };
203
+ ```
204
+
205
+ You can also use supply a monitor config to upsert cron monitors with additional metadata:
206
+
207
+ ```js
208
+ const monitorConfig = {
209
+ schedule: {
210
+ type: 'crontab',
211
+ value: '* * * * *',
212
+ },
213
+ checkinMargin: 2, // In minutes. Optional.
214
+ maxRuntime: 10, // In minutes. Optional.
215
+ timezone: 'America/Los_Angeles', // Optional.
216
+ };
217
+
218
+ export default {
219
+ async scheduled(event, env, ctx) {
220
+ Sentry.withMonitor('your-cron-name', () => doSomeTaskOnASchedule(), monitorConfig);
221
+ },
222
+ };
223
+ ```
@@ -0,0 +1,157 @@
1
+ Object.defineProperty(exports, '__esModule', { value: true });
2
+
3
+ const core = require('@sentry/core');
4
+
5
+ // Patching is based on internal Cloudflare D1 API
6
+ // https://github.com/cloudflare/workerd/blob/cd5279e7b305003f1d9c851e73efa9d67e4b68b2/src/cloudflare/internal/d1-api.ts
7
+
8
+ const patchedStatement = new WeakSet();
9
+
10
+ /**
11
+ * Patches the query methods of a Cloudflare D1 prepared statement with Sentry.
12
+ */
13
+ function instrumentD1PreparedStatementQueries(statement, query) {
14
+ if (patchedStatement.has(statement)) {
15
+ return statement;
16
+ }
17
+
18
+ // eslint-disable-next-line @typescript-eslint/unbound-method
19
+ statement.first = new Proxy(statement.first, {
20
+ apply(target, thisArg, args) {
21
+ return core.startSpan(createStartSpanOptions(query, 'first'), async () => {
22
+ const res = await Reflect.apply(target, thisArg, args);
23
+ createD1Breadcrumb(query, 'first');
24
+ return res;
25
+ });
26
+ },
27
+ });
28
+
29
+ // eslint-disable-next-line @typescript-eslint/unbound-method
30
+ statement.run = new Proxy(statement.run, {
31
+ apply(target, thisArg, args) {
32
+ return core.startSpan(createStartSpanOptions(query, 'run'), async span => {
33
+ const d1Response = await Reflect.apply(target, thisArg, args);
34
+ applyD1ReturnObjectToSpan(span, d1Response);
35
+ createD1Breadcrumb(query, 'run', d1Response);
36
+ return d1Response;
37
+ });
38
+ },
39
+ });
40
+
41
+ // eslint-disable-next-line @typescript-eslint/unbound-method
42
+ statement.all = new Proxy(statement.all, {
43
+ apply(target, thisArg, args) {
44
+ return core.startSpan(createStartSpanOptions(query, 'all'), async span => {
45
+ const d1Result = await Reflect.apply(target, thisArg, args);
46
+ applyD1ReturnObjectToSpan(span, d1Result);
47
+ createD1Breadcrumb(query, 'all', d1Result);
48
+ return d1Result;
49
+ });
50
+ },
51
+ });
52
+
53
+ // eslint-disable-next-line @typescript-eslint/unbound-method
54
+ statement.raw = new Proxy(statement.raw, {
55
+ apply(target, thisArg, args) {
56
+ return core.startSpan(createStartSpanOptions(query, 'raw'), async () => {
57
+ const res = await Reflect.apply(target, thisArg, args);
58
+ createD1Breadcrumb(query, 'raw');
59
+ return res;
60
+ });
61
+ },
62
+ });
63
+
64
+ patchedStatement.add(statement);
65
+
66
+ return statement;
67
+ }
68
+
69
+ /**
70
+ * Instruments a Cloudflare D1 prepared statement with Sentry.
71
+ *
72
+ * This is meant to be used as a top-level call, under the hood it calls `instrumentD1PreparedStatementQueries`
73
+ * to patch the query methods. The reason for this abstraction is to ensure that the `bind` method is also patched.
74
+ */
75
+ function instrumentD1PreparedStatement(statement, query) {
76
+ // statement.bind() returns a new instance of D1PreparedStatement, so we have to patch it as well.
77
+ // eslint-disable-next-line @typescript-eslint/unbound-method
78
+ statement.bind = new Proxy(statement.bind, {
79
+ apply(target, thisArg, args) {
80
+ return instrumentD1PreparedStatementQueries(Reflect.apply(target, thisArg, args), query);
81
+ },
82
+ });
83
+
84
+ return instrumentD1PreparedStatementQueries(statement, query);
85
+ }
86
+
87
+ /**
88
+ * Add D1Response meta information to a span.
89
+ *
90
+ * See: https://developers.cloudflare.com/d1/build-with-d1/d1-client-api/#return-object
91
+ */
92
+ function applyD1ReturnObjectToSpan(span, d1Result) {
93
+ if (!d1Result.success) {
94
+ span.setStatus({ code: core.SPAN_STATUS_ERROR });
95
+ }
96
+
97
+ span.setAttributes(getAttributesFromD1Response(d1Result));
98
+ }
99
+
100
+ function getAttributesFromD1Response(d1Result) {
101
+ return {
102
+ 'cloudflare.d1.duration': d1Result.meta.duration,
103
+ 'cloudflare.d1.rows_read': d1Result.meta.rows_read,
104
+ 'cloudflare.d1.rows_written': d1Result.meta.rows_written,
105
+ };
106
+ }
107
+
108
+ function createD1Breadcrumb(query, type, d1Result) {
109
+ core.addBreadcrumb({
110
+ category: 'query',
111
+ message: query,
112
+ data: {
113
+ ...(d1Result ? getAttributesFromD1Response(d1Result) : {}),
114
+ 'cloudflare.d1.query_type': type,
115
+ },
116
+ });
117
+ }
118
+
119
+ function createStartSpanOptions(query, type) {
120
+ return {
121
+ op: 'db.query',
122
+ name: query,
123
+ attributes: {
124
+ 'cloudflare.d1.query_type': type,
125
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',
126
+ },
127
+ };
128
+ }
129
+
130
+ /**
131
+ * Instruments Cloudflare D1 bindings with Sentry.
132
+ *
133
+ * Currently, only prepared statements are instrumented. `db.exec` and `db.batch` are not instrumented.
134
+ *
135
+ * @example
136
+ *
137
+ * ```js
138
+ * // env.DB is the D1 DB binding configured in your `wrangler.toml`
139
+ * const db = instrumentD1WithSentry(env.DB);
140
+ * // Now you can use the database as usual
141
+ * await db.prepare('SELECT * FROM table WHERE id = ?').bind(1).run();
142
+ * ```
143
+ */
144
+ function instrumentD1WithSentry(db) {
145
+ // eslint-disable-next-line @typescript-eslint/unbound-method
146
+ db.prepare = new Proxy(db.prepare, {
147
+ apply(target, thisArg, args) {
148
+ const [query] = args;
149
+ return instrumentD1PreparedStatement(Reflect.apply(target, thisArg, args), query);
150
+ },
151
+ });
152
+
153
+ return db;
154
+ }
155
+
156
+ exports.instrumentD1WithSentry = instrumentD1WithSentry;
157
+ //# sourceMappingURL=d1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"d1.js","sources":["../../src/d1.ts"],"sourcesContent":["import type { D1Database, D1PreparedStatement, D1Response } from '@cloudflare/workers-types';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SPAN_STATUS_ERROR, addBreadcrumb, startSpan } from '@sentry/core';\nimport type { Span, SpanAttributes, StartSpanOptions } from '@sentry/types';\n\n// Patching is based on internal Cloudflare D1 API\n// https://github.com/cloudflare/workerd/blob/cd5279e7b305003f1d9c851e73efa9d67e4b68b2/src/cloudflare/internal/d1-api.ts\n\nconst patchedStatement = new WeakSet<D1PreparedStatement>();\n\n/**\n * Patches the query methods of a Cloudflare D1 prepared statement with Sentry.\n */\nfunction instrumentD1PreparedStatementQueries(statement: D1PreparedStatement, query: string): D1PreparedStatement {\n if (patchedStatement.has(statement)) {\n return statement;\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.first = new Proxy(statement.first, {\n apply(target, thisArg, args: Parameters<typeof statement.first>) {\n return startSpan(createStartSpanOptions(query, 'first'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(query, 'first');\n return res;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.run = new Proxy(statement.run, {\n apply(target, thisArg, args: Parameters<typeof statement.run>) {\n return startSpan(createStartSpanOptions(query, 'run'), async span => {\n const d1Response = await Reflect.apply(target, thisArg, args);\n applyD1ReturnObjectToSpan(span, d1Response);\n createD1Breadcrumb(query, 'run', d1Response);\n return d1Response;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.all = new Proxy(statement.all, {\n apply(target, thisArg, args: Parameters<typeof statement.all>) {\n return startSpan(createStartSpanOptions(query, 'all'), async span => {\n const d1Result = await Reflect.apply(target, thisArg, args);\n applyD1ReturnObjectToSpan(span, d1Result);\n createD1Breadcrumb(query, 'all', d1Result);\n return d1Result;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.raw = new Proxy(statement.raw, {\n apply(target, thisArg, args: Parameters<typeof statement.raw>) {\n return startSpan(createStartSpanOptions(query, 'raw'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(query, 'raw');\n return res;\n });\n },\n });\n\n patchedStatement.add(statement);\n\n return statement;\n}\n\n/**\n * Instruments a Cloudflare D1 prepared statement with Sentry.\n *\n * This is meant to be used as a top-level call, under the hood it calls `instrumentD1PreparedStatementQueries`\n * to patch the query methods. The reason for this abstraction is to ensure that the `bind` method is also patched.\n */\nfunction instrumentD1PreparedStatement(statement: D1PreparedStatement, query: string): D1PreparedStatement {\n // statement.bind() returns a new instance of D1PreparedStatement, so we have to patch it as well.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.bind = new Proxy(statement.bind, {\n apply(target, thisArg, args: Parameters<typeof statement.bind>) {\n return instrumentD1PreparedStatementQueries(Reflect.apply(target, thisArg, args), query);\n },\n });\n\n return instrumentD1PreparedStatementQueries(statement, query);\n}\n\n/**\n * Add D1Response meta information to a span.\n *\n * See: https://developers.cloudflare.com/d1/build-with-d1/d1-client-api/#return-object\n */\nfunction applyD1ReturnObjectToSpan(span: Span, d1Result: D1Response): void {\n if (!d1Result.success) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n\n span.setAttributes(getAttributesFromD1Response(d1Result));\n}\n\nfunction getAttributesFromD1Response(d1Result: D1Response): SpanAttributes {\n return {\n 'cloudflare.d1.duration': d1Result.meta.duration,\n 'cloudflare.d1.rows_read': d1Result.meta.rows_read,\n 'cloudflare.d1.rows_written': d1Result.meta.rows_written,\n };\n}\n\nfunction createD1Breadcrumb(query: string, type: 'first' | 'run' | 'all' | 'raw', d1Result?: D1Response): void {\n addBreadcrumb({\n category: 'query',\n message: query,\n data: {\n ...(d1Result ? getAttributesFromD1Response(d1Result) : {}),\n 'cloudflare.d1.query_type': type,\n },\n });\n}\n\nfunction createStartSpanOptions(query: string, type: 'first' | 'run' | 'all' | 'raw'): StartSpanOptions {\n return {\n op: 'db.query',\n name: query,\n attributes: {\n 'cloudflare.d1.query_type': type,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n };\n}\n\n/**\n * Instruments Cloudflare D1 bindings with Sentry.\n *\n * Currently, only prepared statements are instrumented. `db.exec` and `db.batch` are not instrumented.\n *\n * @example\n *\n * ```js\n * // env.DB is the D1 DB binding configured in your `wrangler.toml`\n * const db = instrumentD1WithSentry(env.DB);\n * // Now you can use the database as usual\n * await db.prepare('SELECT * FROM table WHERE id = ?').bind(1).run();\n * ```\n */\nexport function instrumentD1WithSentry(db: D1Database): D1Database {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n db.prepare = new Proxy(db.prepare, {\n apply(target, thisArg, args: Parameters<typeof db.prepare>) {\n const [query] = args;\n return instrumentD1PreparedStatement(Reflect.apply(target, thisArg, args), query);\n },\n });\n\n return db;\n}\n"],"names":["startSpan","SPAN_STATUS_ERROR","addBreadcrumb","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN"],"mappings":";;;;AAIA;AACA;AACA;AACA,MAAM,gBAAiB,GAAE,IAAI,OAAO,EAAuB,CAAA;AAC3D;AACA;AACA;AACA;AACA,SAAS,oCAAoC,CAAC,SAAS,EAAuB,KAAK,EAA+B;AAClH,EAAE,IAAI,gBAAgB,CAAC,GAAG,CAAC,SAAS,CAAC,EAAE;AACvC,IAAI,OAAO,SAAS,CAAA;AACpB,GAAE;AACF;AACA;AACA,EAAE,SAAS,CAAC,KAAA,GAAQ,IAAI,KAAK,CAAC,SAAS,CAAC,KAAK,EAAE;AAC/C,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAsC;AACrE,MAAM,OAAOA,cAAS,CAAC,sBAAsB,CAAC,KAAK,EAAE,OAAO,CAAC,EAAE,YAAY;AAC3E,QAAQ,MAAM,GAAA,GAAM,MAAM,OAAO,CAAC,KAAK,CAAC,M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A,EAAE,EAAE,CAAC,OAAA,GAAU,IAAI,KAAK,CAAC,EAAE,CAAC,OAAO,EAAE;AACrC,IAAI,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAAiC;AAChE,MAAM,MAAM,CAAC,KAAK,CAAA,GAAI,IAAI,CAAA;AAC1B,MAAM,OAAO,6BAA6B,CAAC,OAAO,CAAC,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,KAAK,CAAC,CAAA;AACvF,KAAK;AACL,GAAG,CAAC,CAAA;AACJ;AACA,EAAE,OAAO,EAAE,CAAA;AACX;;;;"}
@@ -1,8 +1,9 @@
1
1
  Object.defineProperty(exports, '__esModule', { value: true });
2
2
 
3
3
  const core = require('@sentry/core');
4
- const utils = require('@sentry/utils');
5
4
  const async = require('./async.js');
5
+ const request = require('./request.js');
6
+ const scopeUtils = require('./scope-utils.js');
6
7
  const sdk = require('./sdk.js');
7
8
 
8
9
  /**
@@ -31,68 +32,53 @@ function withSentry(
31
32
  if ('fetch' in handler && typeof handler.fetch === 'function' && !(handler.fetch ).__SENTRY_INSTRUMENTED__) {
32
33
  handler.fetch = new Proxy(handler.fetch, {
33
34
  apply(target, thisArg, args) {
34
- const [request, env, context] = args;
35
+ const [request$1, env, context] = args;
36
+ const options = optionsCallback(env);
37
+ return request.wrapRequestHandler({ options, request: request$1, context }, () => target.apply(thisArg, args));
38
+ },
39
+ });
40
+
41
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
42
+ (handler.fetch ).__SENTRY_INSTRUMENTED__ = true;
43
+ }
44
+
45
+ if (
46
+ 'scheduled' in handler &&
47
+ typeof handler.scheduled === 'function' &&
48
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
49
+ !(handler.scheduled ).__SENTRY_INSTRUMENTED__
50
+ ) {
51
+ handler.scheduled = new Proxy(handler.scheduled, {
52
+ apply(target, thisArg, args) {
53
+ const [event, env, context] = args;
35
54
  return core.withIsolationScope(isolationScope => {
36
55
  const options = optionsCallback(env);
37
56
  const client = sdk.init(options);
38
57
  isolationScope.setClient(client);
39
58
 
40
- const attributes = {
41
- [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.cloudflare-worker',
42
- [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',
43
- [core.SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',
44
- ['http.request.method']: request.method,
45
- ['url.full']: request.url,
46
- };
47
-
48
- const contentLength = request.headers.get('content-length');
49
- if (contentLength) {
50
- attributes['http.request.body.size'] = parseInt(contentLength, 10);
51
- }
52
-
53
- let pathname = '';
54
- try {
55
- const url = new URL(request.url);
56
- pathname = url.pathname;
57
- attributes['server.address'] = url.hostname;
58
- attributes['url.scheme'] = url.protocol.replace(':', '');
59
- } catch (e2) {
60
- // skip
61
- }
62
-
63
- addRequest(isolationScope, request);
64
- addCloudResourceContext(isolationScope);
65
- if (request.cf) {
66
- addCultureContext(isolationScope, request.cf);
67
- attributes['network.protocol.name'] = request.cf.httpProtocol;
68
- }
69
-
70
- const routeName = `${request.method} ${pathname ? utils.stripUrlQueryAndFragment(pathname) : '/'}`;
71
-
72
- return core.continueTrace(
73
- { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },
74
- () => {
75
- // Note: This span will not have a duration unless I/O happens in the handler. This is
76
- // because of how the cloudflare workers runtime works.
77
- // See: https://developers.cloudflare.com/workers/runtime-apis/performance/
78
- return core.startSpan(
79
- {
80
- name: routeName,
81
- attributes,
82
- },
83
- async span => {
84
- try {
85
- const res = await (target.apply(thisArg, args) );
86
- core.setHttpStatus(span, res.status);
87
- return res;
88
- } catch (e) {
89
- core.captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });
90
- throw e;
91
- } finally {
92
- context.waitUntil(core.flush(2000));
93
- }
94
- },
95
- );
59
+ scopeUtils.addCloudResourceContext(isolationScope);
60
+
61
+ return core.startSpan(
62
+ {
63
+ op: 'faas.cron',
64
+ name: `Scheduled Cron ${event.cron}`,
65
+ attributes: {
66
+ 'faas.cron': event.cron,
67
+ 'faas.time': new Date(event.scheduledTime).toISOString(),
68
+ 'faas.trigger': 'timer',
69
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare',
70
+ [core.SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',
71
+ },
72
+ },
73
+ async () => {
74
+ try {
75
+ return await (target.apply(thisArg, args) );
76
+ } catch (e) {
77
+ core.captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });
78
+ throw e;
79
+ } finally {
80
+ context.waitUntil(core.flush(2000));
81
+ }
96
82
  },
97
83
  );
98
84
  });
@@ -100,27 +86,11 @@ function withSentry(
100
86
  });
101
87
 
102
88
  // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
103
- (handler.fetch ).__SENTRY_INSTRUMENTED__ = true;
89
+ (handler.scheduled ).__SENTRY_INSTRUMENTED__ = true;
104
90
  }
105
91
 
106
92
  return handler;
107
93
  }
108
94
 
109
- function addCloudResourceContext(isolationScope) {
110
- isolationScope.setContext('cloud_resource', {
111
- 'cloud.provider': 'cloudflare',
112
- });
113
- }
114
-
115
- function addCultureContext(isolationScope, cf) {
116
- isolationScope.setContext('culture', {
117
- timezone: cf.timezone,
118
- });
119
- }
120
-
121
- function addRequest(isolationScope, request) {
122
- isolationScope.setSDKProcessingMetadata({ request: utils.winterCGRequestToRequestData(request) });
123
- }
124
-
125
95
  exports.withSentry = withSentry;
126
96
  //# sourceMappingURL=handler.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"handler.js","sources":["../../src/handler.ts"],"sourcesContent":["import type {\n ExportedHandler,\n ExportedHandlerFetchHandler,\n IncomingRequestCfProperties,\n} from '@cloudflare/workers-types';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n captureException,\n continueTrace,\n flush,\n setHttpStatus,\n startSpan,\n withIsolationScope,\n} from '@sentry/core';\nimport type { Options, Scope, SpanAttributes } from '@sentry/types';\nimport { stripUrlQueryAndFragment, winterCGRequestToRequestData } from '@sentry/utils';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport { init } from './sdk';\n\n/**\n * Extract environment generic from exported handler.\n */\ntype ExtractEnv<P> = P extends ExportedHandler<infer Env> ? Env : never;\n\n/**\n * Wrapper for Cloudflare handlers.\n *\n * Initializes the SDK and wraps the handler with Sentry instrumentation.\n *\n * Automatically instruments the `fetch` method of the handler.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param handler {ExportedHandler} The handler to wrap.\n * @returns The wrapped handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function withSentry<E extends ExportedHandler<any>>(\n optionsCallback: (env: ExtractEnv<E>) => Options,\n handler: E,\n): E {\n setAsyncLocalStorageAsyncContextStrategy();\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if ('fetch' in handler && typeof handler.fetch === 'function' && !(handler.fetch as any).__SENTRY_INSTRUMENTED__) {\n handler.fetch = new Proxy(handler.fetch, {\n apply(target, thisArg, args: Parameters<ExportedHandlerFetchHandler<ExtractEnv<E>>>) {\n const [request, env, context] = args;\n return withIsolationScope(isolationScope => {\n const options = optionsCallback(env);\n const client = init(options);\n isolationScope.setClient(client);\n\n const attributes: SpanAttributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.http.cloudflare-worker',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.server',\n ['http.request.method']: request.method,\n ['url.full']: request.url,\n };\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n let pathname = '';\n try {\n const url = new URL(request.url);\n pathname = url.pathname;\n attributes['server.address'] = url.hostname;\n attributes['url.scheme'] = url.protocol.replace(':', '');\n } catch {\n // skip\n }\n\n addRequest(isolationScope, request);\n addCloudResourceContext(isolationScope);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n attributes['network.protocol.name'] = request.cf.httpProtocol;\n }\n\n const routeName = `${request.method} ${pathname ? stripUrlQueryAndFragment(pathname) : '/'}`;\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n return startSpan(\n {\n name: routeName,\n attributes,\n },\n async span => {\n try {\n const res = await (target.apply(thisArg, args) as ReturnType<typeof target>);\n setHttpStatus(span, res.status);\n return res;\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });\n throw e;\n } finally {\n context.waitUntil(flush(2000));\n }\n },\n );\n },\n );\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (handler.fetch as any).__SENTRY_INSTRUMENTED__ = true;\n }\n\n return handler;\n}\n\nfunction addCloudResourceContext(isolationScope: Scope): void {\n isolationScope.setContext('cloud_resource', {\n 'cloud.provider': 'cloudflare',\n });\n}\n\nfunction addCultureContext(isolationScope: Scope, cf: IncomingRequestCfProperties): void {\n isolationScope.setContext('culture', {\n timezone: cf.timezone,\n });\n}\n\nfunction addRequest(isolationScope: Scope, request: Request): void {\n isolationScope.setSDKProcessingMetadata({ request: winterCGRequestToRequestData(request) });\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","withIsolationScope","init","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_OP","stripUrlQueryAndFragment","continueTrace","startSpan","setHttpStatus","captureException","flush","winterCGRequestToRequestData"],"mappings":";;;;;;;AAqBA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,UAAU;AAC1B,EAAE,eAAe;AACjB,EAAE,OAAO;AACT,EAAK;AACL,EAAEA,8CAAwC,EAAE,CAAA;AAC5C;AACA;AACA,EAAE,IAAI,OAAQ,IAAG,WAAW,OAAO,OAAO,CAAC,KAAA,KAAU,UAAW,IAAG,CAAC,CAAC,OAAO,CAAC,KAAM,GAAQ,uBAAuB,EAAE;AACpH,IAAI,OAAO,CAAC,KAAA,GAAQ,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE;AAC7C,MAAM,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE,IAAI,EAA0D;AAC3F,QAAQ,MAAM,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,CAAE,GAAE,IAAI,CAAA;AAC5C,QAAQ,OAAOC,uBAAkB,CAAC,cAAA,IAAkB;AACpD,UAAU,MAAM,OAAQ,GAAE,eAAe,CAAC,GAAG,CAAC,CAAA;AAC9C,UAAU,MAAM,MAAO,GAAEC,QAAI,CAAC,OAAO,CAAC,CAAA;AACtC,UAAU,cAAc,CAAC,SAAS,CAAC,MAAM,CAAC,CAAA;AAC1C;AACA,UAAU,MAAM,UAAU,GAAmB;AAC7C,YAAY,CAACC,qCAAgC,GAAG,6BAA6B;AAC7E,YAAY,CAACC,qCAAgC,GAAG,KAAK;AACrD,YAAY,CAACC,iCAA4B,GAAG,aAAa;AACzD,YAAY,CAAC,qBAAqB,GAAG,OAAO,CAAC,MAAM;AACnD,YAAY,CAAC,UAAU,GAAG,OAAO,CAAC,GAAG;AACrC,WAAW,CAAA;AACX;AACA,UAAU,MAAM,aAAc,GAAE,OAAO,CAAC,OAAO,CAAC,GAAG,CAAC,gBAAgB,CAAC,CAAA;AACrE,UAAU,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AAA;AACA,EAAA,cAAA,CAAA,wBAAA,CAAA,EAAA,OAAA,EAAAC,kCAAA,CAAA,OAAA,CAAA,EAAA,CAAA,CAAA;AACA;;;;"}
1
+ {"version":3,"file":"handler.js","sources":["../../src/handler.ts"],"sourcesContent":["import type {\n ExportedHandler,\n ExportedHandlerFetchHandler,\n ExportedHandlerScheduledHandler,\n} from '@cloudflare/workers-types';\nimport {\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,\n captureException,\n flush,\n startSpan,\n withIsolationScope,\n} from '@sentry/core';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { wrapRequestHandler } from './request';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\n\n/**\n * Extract environment generic from exported handler.\n */\ntype ExtractEnv<P> = P extends ExportedHandler<infer Env> ? Env : never;\n\n/**\n * Wrapper for Cloudflare handlers.\n *\n * Initializes the SDK and wraps the handler with Sentry instrumentation.\n *\n * Automatically instruments the `fetch` method of the handler.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param handler {ExportedHandler} The handler to wrap.\n * @returns The wrapped handler.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport function withSentry<E extends ExportedHandler<any>>(\n optionsCallback: (env: ExtractEnv<E>) => CloudflareOptions,\n handler: E,\n): E {\n setAsyncLocalStorageAsyncContextStrategy();\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n if ('fetch' in handler && typeof handler.fetch === 'function' && !(handler.fetch as any).__SENTRY_INSTRUMENTED__) {\n handler.fetch = new Proxy(handler.fetch, {\n apply(target, thisArg, args: Parameters<ExportedHandlerFetchHandler<ExtractEnv<E>>>) {\n const [request, env, context] = args;\n const options = optionsCallback(env);\n return wrapRequestHandler({ options, request, context }, () => target.apply(thisArg, args));\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (handler.fetch as any).__SENTRY_INSTRUMENTED__ = true;\n }\n\n if (\n 'scheduled' in handler &&\n typeof handler.scheduled === 'function' &&\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n !(handler.scheduled as any).__SENTRY_INSTRUMENTED__\n ) {\n handler.scheduled = new Proxy(handler.scheduled, {\n apply(target, thisArg, args: Parameters<ExportedHandlerScheduledHandler<ExtractEnv<E>>>) {\n const [event, env, context] = args;\n return withIsolationScope(isolationScope => {\n const options = optionsCallback(env);\n const client = init(options);\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return startSpan(\n {\n op: 'faas.cron',\n name: `Scheduled Cron ${event.cron}`,\n attributes: {\n 'faas.cron': event.cron,\n 'faas.time': new Date(event.scheduledTime).toISOString(),\n 'faas.trigger': 'timer',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare',\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',\n },\n },\n async () => {\n try {\n return await (target.apply(thisArg, args) as ReturnType<typeof target>);\n } catch (e) {\n captureException(e, { mechanism: { handled: false, type: 'cloudflare' } });\n throw e;\n } finally {\n context.waitUntil(flush(2000));\n }\n },\n );\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any\n (handler.scheduled as any).__SENTRY_INSTRUMENTED__ = true;\n }\n\n return handler;\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","request","wrapRequestHandler","withIsolationScope","init","addCloudResourceContext","startSpan","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","captureException","flush"],"mappings":";;;;;;;;AAmBA;AACA;AACA;;AAGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,UAAU;AAC1B,EAAE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,OAAA,OAAA,CAAA;AACA;;;;"}
@@ -2,9 +2,12 @@ Object.defineProperty(exports, '__esModule', { value: true });
2
2
 
3
3
  const core = require('@sentry/core');
4
4
  const handler = require('./handler.js');
5
+ const pagesPlugin = require('./pages-plugin.js');
6
+ const request = require('./request.js');
5
7
  const client = require('./client.js');
6
8
  const sdk = require('./sdk.js');
7
9
  const fetch = require('./integrations/fetch.js');
10
+ const d1 = require('./d1.js');
8
11
 
9
12
 
10
13
 
@@ -39,6 +42,7 @@ exports.getIsolationScope = core.getIsolationScope;
39
42
  exports.getRootSpan = core.getRootSpan;
40
43
  exports.getSpanDescendants = core.getSpanDescendants;
41
44
  exports.getSpanStatusFromHttpCode = core.getSpanStatusFromHttpCode;
45
+ exports.getTraceData = core.getTraceData;
42
46
  exports.inboundFiltersIntegration = core.inboundFiltersIntegration;
43
47
  exports.isInitialized = core.isInitialized;
44
48
  exports.lastEventId = core.lastEventId;
@@ -70,7 +74,10 @@ exports.withMonitor = core.withMonitor;
70
74
  exports.withScope = core.withScope;
71
75
  exports.zodErrorsIntegration = core.zodErrorsIntegration;
72
76
  exports.withSentry = handler.withSentry;
77
+ exports.sentryPagesPlugin = pagesPlugin.sentryPagesPlugin;
78
+ exports.wrapRequestHandler = request.wrapRequestHandler;
73
79
  exports.CloudflareClient = client.CloudflareClient;
74
80
  exports.getDefaultIntegrations = sdk.getDefaultIntegrations;
75
81
  exports.fetchIntegration = fetch.fetchIntegration;
82
+ exports.instrumentD1WithSentry = d1.instrumentD1WithSentry;
76
83
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
@@ -0,0 +1,52 @@
1
+ Object.defineProperty(exports, '__esModule', { value: true });
2
+
3
+ const async = require('./async.js');
4
+ const request = require('./request.js');
5
+
6
+ /**
7
+ * Plugin middleware for Cloudflare Pages.
8
+ *
9
+ * Initializes the SDK and wraps cloudflare pages requests with SDK instrumentation.
10
+ *
11
+ * @example Simple usage
12
+ *
13
+ * ```javascript
14
+ * // functions/_middleware.js
15
+ * import * as Sentry from '@sentry/cloudflare';
16
+ *
17
+ * export const onRequest = Sentry.sentryPagesPlugin({
18
+ * dsn: process.env.SENTRY_DSN,
19
+ * tracesSampleRate: 1.0,
20
+ * });
21
+ * ```
22
+ *
23
+ * @example Usage with handler function to access context for environmental variables
24
+ *
25
+ * ```javascript
26
+ * import * as Sentry from '@sentry/cloudflare';
27
+ *
28
+ * const const onRequest = Sentry.sentryPagesPlugin((context) => ({
29
+ * dsn: context.env.SENTRY_DSN,
30
+ * tracesSampleRate: 1.0,
31
+ * })
32
+ * ```
33
+ *
34
+ * @param handlerOrOptions Configuration options or a function that returns configuration options.
35
+ * @returns A plugin function that can be used in Cloudflare Pages.
36
+ */
37
+ function sentryPagesPlugin
38
+
39
+ (
40
+ handlerOrOptions
41
+
42
+ ,
43
+ ) {
44
+ async.setAsyncLocalStorageAsyncContextStrategy();
45
+ return context => {
46
+ const options = typeof handlerOrOptions === 'function' ? handlerOrOptions(context) : handlerOrOptions;
47
+ return request.wrapRequestHandler({ options, request: context.request, context }, () => context.next());
48
+ };
49
+ }
50
+
51
+ exports.sentryPagesPlugin = sentryPagesPlugin;
52
+ //# sourceMappingURL=pages-plugin.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pages-plugin.js","sources":["../../src/pages-plugin.ts"],"sourcesContent":["import { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { wrapRequestHandler } from './request';\n\n/**\n * Plugin middleware for Cloudflare Pages.\n *\n * Initializes the SDK and wraps cloudflare pages requests with SDK instrumentation.\n *\n * @example Simple usage\n *\n * ```javascript\n * // functions/_middleware.js\n * import * as Sentry from '@sentry/cloudflare';\n *\n * export const onRequest = Sentry.sentryPagesPlugin({\n * dsn: process.env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * });\n * ```\n *\n * @example Usage with handler function to access context for environmental variables\n *\n * ```javascript\n * import * as Sentry from '@sentry/cloudflare';\n *\n * const const onRequest = Sentry.sentryPagesPlugin((context) => ({\n * dsn: context.env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * })\n * ```\n *\n * @param handlerOrOptions Configuration options or a function that returns configuration options.\n * @returns A plugin function that can be used in Cloudflare Pages.\n */\nexport function sentryPagesPlugin<\n Env = unknown,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n Params extends string = any,\n Data extends Record<string, unknown> = Record<string, unknown>,\n // Although it is not ideal to use `any` here, it makes usage more flexible for different setups.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n PluginParams = any,\n>(\n handlerOrOptions:\n | CloudflareOptions\n | ((context: EventPluginContext<Env, Params, Data, PluginParams>) => CloudflareOptions),\n): PagesPluginFunction<Env, Params, Data, PluginParams> {\n setAsyncLocalStorageAsyncContextStrategy();\n return context => {\n const options = typeof handlerOrOptions === 'function' ? handlerOrOptions(context) : handlerOrOptions;\n return wrapRequestHandler({ options, request: context.request, context }, () => context.next());\n };\n}\n"],"names":["setAsyncLocalStorageAsyncContextStrategy","wrapRequestHandler"],"mappings":";;;;;AAIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,iBAAiB;;AAQjC;AACA,EAAE,gBAAgB;AACd;AACA;AACJ,EAAwD;AACxD,EAAEA,8CAAwC,EAAE,CAAA;AAC5C,EAAE,OAAO,WAAW;AACpB,IAAI,MAAM,OAAA,GAAU,OAAO,gBAAiB,KAAI,UAAW,GAAE,gBAAgB,CAAC,OAAO,CAAA,GAAI,gBAAgB,CAAA;AACzG,IAAI,OAAOC,0BAAkB,CAAC,EAAE,OAAO,EAAE,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,OAAQ,EAAC,EAAE,MAAM,OAAO,CAAC,IAAI,EAAE,CAAC,CAAA;AACnG,GAAG,CAAA;AACH;;;;"}