@sentry/cloudflare 11.0.0-beta.0 → 11.0.0-beta.2

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 (95) hide show
  1. package/build/cjs/dev/durableobject.js +6 -2
  2. package/build/cjs/dev/durableobject.js.map +1 -1
  3. package/build/cjs/dev/index.js +15 -13
  4. package/build/cjs/dev/index.js.map +1 -1
  5. package/build/cjs/dev/instrument.js +4 -0
  6. package/build/cjs/dev/instrument.js.map +1 -1
  7. package/build/cjs/dev/instrumentations/instrumentSqlStorage.js +3 -3
  8. package/build/cjs/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
  9. package/build/cjs/dev/instrumentations/instrumentWorkerEntrypoint.js +4 -1
  10. package/build/cjs/dev/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
  11. package/build/cjs/dev/instrumentations/worker/instrumentD1.js +2 -2
  12. package/build/cjs/dev/instrumentations/worker/instrumentD1.js.map +1 -1
  13. package/build/cjs/dev/vite/agentClass.js +3 -2
  14. package/build/cjs/dev/vite/agentClass.js.map +1 -1
  15. package/build/cjs/dev/vite/autoInstrument.js +1 -1
  16. package/build/cjs/dev/vite/autoInstrument.js.map +1 -1
  17. package/build/cjs/dev/vite/transform.js +79 -16
  18. package/build/cjs/dev/vite/transform.js.map +1 -1
  19. package/build/cjs/dev/workflows.js +4 -1
  20. package/build/cjs/dev/workflows.js.map +1 -1
  21. package/build/cjs/prod/durableobject.js +6 -2
  22. package/build/cjs/prod/durableobject.js.map +1 -1
  23. package/build/cjs/prod/index.js +15 -13
  24. package/build/cjs/prod/index.js.map +1 -1
  25. package/build/cjs/prod/instrument.js +4 -0
  26. package/build/cjs/prod/instrument.js.map +1 -1
  27. package/build/cjs/prod/instrumentations/instrumentSqlStorage.js +3 -3
  28. package/build/cjs/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
  29. package/build/cjs/prod/instrumentations/instrumentWorkerEntrypoint.js +4 -1
  30. package/build/cjs/prod/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
  31. package/build/cjs/prod/instrumentations/worker/instrumentD1.js +2 -2
  32. package/build/cjs/prod/instrumentations/worker/instrumentD1.js.map +1 -1
  33. package/build/cjs/prod/vite/agentClass.js +3 -2
  34. package/build/cjs/prod/vite/agentClass.js.map +1 -1
  35. package/build/cjs/prod/vite/autoInstrument.js +1 -1
  36. package/build/cjs/prod/vite/autoInstrument.js.map +1 -1
  37. package/build/cjs/prod/vite/transform.js +79 -16
  38. package/build/cjs/prod/vite/transform.js.map +1 -1
  39. package/build/cjs/prod/workflows.js +4 -1
  40. package/build/cjs/prod/workflows.js.map +1 -1
  41. package/build/esm/dev/durableobject.js +6 -2
  42. package/build/esm/dev/durableobject.js.map +1 -1
  43. package/build/esm/dev/index.js +3 -2
  44. package/build/esm/dev/index.js.map +1 -1
  45. package/build/esm/dev/instrument.js +4 -1
  46. package/build/esm/dev/instrument.js.map +1 -1
  47. package/build/esm/dev/instrumentations/instrumentSqlStorage.js +3 -3
  48. package/build/esm/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
  49. package/build/esm/dev/instrumentations/instrumentWorkerEntrypoint.js +4 -1
  50. package/build/esm/dev/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
  51. package/build/esm/dev/instrumentations/worker/instrumentD1.js +2 -2
  52. package/build/esm/dev/instrumentations/worker/instrumentD1.js.map +1 -1
  53. package/build/esm/dev/package.json +1 -1
  54. package/build/esm/dev/vite/agentClass.js +3 -2
  55. package/build/esm/dev/vite/agentClass.js.map +1 -1
  56. package/build/esm/dev/vite/autoInstrument.js +1 -1
  57. package/build/esm/dev/vite/autoInstrument.js.map +1 -1
  58. package/build/esm/dev/vite/transform.js +79 -16
  59. package/build/esm/dev/vite/transform.js.map +1 -1
  60. package/build/esm/dev/workflows.js +4 -1
  61. package/build/esm/dev/workflows.js.map +1 -1
  62. package/build/esm/prod/durableobject.js +6 -2
  63. package/build/esm/prod/durableobject.js.map +1 -1
  64. package/build/esm/prod/index.js +3 -2
  65. package/build/esm/prod/index.js.map +1 -1
  66. package/build/esm/prod/instrument.js +4 -1
  67. package/build/esm/prod/instrument.js.map +1 -1
  68. package/build/esm/prod/instrumentations/instrumentSqlStorage.js +3 -3
  69. package/build/esm/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
  70. package/build/esm/prod/instrumentations/instrumentWorkerEntrypoint.js +4 -1
  71. package/build/esm/prod/instrumentations/instrumentWorkerEntrypoint.js.map +1 -1
  72. package/build/esm/prod/instrumentations/worker/instrumentD1.js +2 -2
  73. package/build/esm/prod/instrumentations/worker/instrumentD1.js.map +1 -1
  74. package/build/esm/prod/package.json +1 -1
  75. package/build/esm/prod/vite/agentClass.js +3 -2
  76. package/build/esm/prod/vite/agentClass.js.map +1 -1
  77. package/build/esm/prod/vite/autoInstrument.js +1 -1
  78. package/build/esm/prod/vite/autoInstrument.js.map +1 -1
  79. package/build/esm/prod/vite/transform.js +79 -16
  80. package/build/esm/prod/vite/transform.js.map +1 -1
  81. package/build/esm/prod/workflows.js +4 -1
  82. package/build/esm/prod/workflows.js.map +1 -1
  83. package/build/types/durableobject.d.ts.map +1 -1
  84. package/build/types/index.d.ts +3 -1
  85. package/build/types/index.d.ts.map +1 -1
  86. package/build/types/instrument.d.ts +10 -0
  87. package/build/types/instrument.d.ts.map +1 -1
  88. package/build/types/instrumentations/instrumentWorkerEntrypoint.d.ts.map +1 -1
  89. package/build/types/vite/agentClass.d.ts +4 -3
  90. package/build/types/vite/agentClass.d.ts.map +1 -1
  91. package/build/types/vite/autoInstrument.d.ts.map +1 -1
  92. package/build/types/vite/transform.d.ts +5 -4
  93. package/build/types/vite/transform.d.ts.map +1 -1
  94. package/build/types/workflows.d.ts.map +1 -1
  95. package/package.json +4 -4
@@ -1,7 +1,7 @@
1
1
  import { SENTRY_OP } from '@sentry/conventions/attributes';
2
2
  import { DB_QUERY } from '@sentry/conventions/op';
3
3
  import { getClient, startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
4
- import { _INTERNAL_sanitizeSqlQuery, _INTERNAL_getSqlQuerySummary } from '@sentry/core/server';
4
+ import { sanitizeSqlQuery, getSqlQuerySummary } from '@sentry/server-utils';
5
5
  import { targetsCloudflareInternalTable } from '../utils/internalSqlQuery.js';
6
6
 
7
7
  function instrumentSqlStorage(sql) {
@@ -13,8 +13,8 @@ function instrumentSqlStorage(sql) {
13
13
  }
14
14
  return function(...args) {
15
15
  const [query, ...bindings] = args;
16
- const sanitizedQuery = _INTERNAL_sanitizeSqlQuery(query);
17
- const querySummary = _INTERNAL_getSqlQuerySummary(sanitizedQuery);
16
+ const sanitizedQuery = sanitizeSqlQuery(query);
17
+ const querySummary = getSqlQuerySummary(sanitizedQuery);
18
18
  const allowlist = getClient()?.getOptions()?.durableObjectSqlSpanAllowlist;
19
19
  if (targetsCloudflareInternalTable(querySummary, allowlist, sanitizedQuery)) {
20
20
  return original.apply(target, args);
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentSqlStorage.js","sources":["../../../../src/instrumentations/instrumentSqlStorage.ts"],"sourcesContent":["import type { SqlStorage } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport { getClient, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\nimport { _INTERNAL_getSqlQuerySummary, _INTERNAL_sanitizeSqlQuery } from '@sentry/core/server';\nimport type { CloudflareClientOptions } from '../client';\nimport { targetsCloudflareInternalTable } from '../utils/internalSqlQuery';\n\n/**\n * Instruments the Durable Object SqlStorage `exec` method with Sentry spans.\n *\n * @param sql - The SqlStorage instance to instrument\n * @returns An instrumented SqlStorage instance\n */\nexport function instrumentSqlStorage(sql: SqlStorage): SqlStorage {\n return new Proxy(sql, {\n get(target, prop, _receiver) {\n const original = Reflect.get(target, prop, target);\n\n if (prop !== 'exec' || typeof original !== 'function') {\n return original;\n }\n\n return function (this: unknown, ...args: unknown[]) {\n const [query, ...bindings] = args as [string, ...unknown[]];\n\n const sanitizedQuery = _INTERNAL_sanitizeSqlQuery(query);\n const querySummary = _INTERNAL_getSqlQuerySummary(sanitizedQuery);\n\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- rule false positive: the cast reaches the Cloudflare-only `durableObjectSqlSpanAllowlist`; tsc errors without it\n const allowlist = (getClient()?.getOptions() as CloudflareClientOptions | undefined)\n ?.durableObjectSqlSpanAllowlist;\n\n if (targetsCloudflareInternalTable(querySummary, allowlist, sanitizedQuery)) {\n return (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args);\n }\n\n return startSpan(\n {\n name: querySummary || sanitizedQuery,\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object.sql',\n 'db.system.name': 'cloudflare-durable-object-sql',\n 'db.operation.name': 'exec',\n 'db.query.text': sanitizedQuery,\n 'db.query.summary': querySummary,\n 'cloudflare.durable_object.query.bindings': bindings.length,\n },\n },\n () => (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args),\n );\n };\n },\n });\n}\n"],"names":[],"mappings":";;;;;;AAcO,SAAS,qBAAqB,GAAA,EAA6B;AAChE,EAAA,OAAO,IAAI,MAAM,GAAA,EAAK;AAAA,IACpB,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAW;AAC3B,MAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,MAAM,CAAA;AAEjD,MAAA,IAAI,IAAA,KAAS,MAAA,IAAU,OAAO,QAAA,KAAa,UAAA,EAAY;AACrD,QAAA,OAAO,QAAA;AAAA,MACT;AAEA,MAAA,OAAO,YAA4B,IAAA,EAAiB;AAClD,QAAA,MAAM,CAAC,KAAA,EAAO,GAAG,QAAQ,CAAA,GAAI,IAAA;AAE7B,QAAA,MAAM,cAAA,GAAiB,2BAA2B,KAAK,CAAA;AACvD,QAAA,MAAM,YAAA,GAAe,6BAA6B,cAAc,CAAA;AAGhE,QAAA,MAAM,SAAA,GAAa,SAAA,EAAU,EAAG,UAAA,EAAW,EACvC,6BAAA;AAEJ,QAAA,IAAI,8BAAA,CAA+B,YAAA,EAAc,SAAA,EAAW,cAAc,CAAA,EAAG;AAC3E,UAAA,OAAQ,QAAA,CAAiE,KAAA,CAAM,MAAA,EAAQ,IAAI,CAAA;AAAA,QAC7F;AAEA,QAAA,OAAO,SAAA;AAAA,UACL;AAAA,YACE,MAAM,YAAA,IAAgB,cAAA;AAAA,YACtB,UAAA,EAAY;AAAA,cACV,CAAC,SAAS,GAAG,QAAA;AAAA,cACb,CAAC,gCAAgC,GAAG,uCAAA;AAAA,cACpC,gBAAA,EAAkB,+BAAA;AAAA,cAClB,mBAAA,EAAqB,MAAA;AAAA,cACrB,eAAA,EAAiB,cAAA;AAAA,cACjB,kBAAA,EAAoB,YAAA;AAAA,cACpB,4CAA4C,QAAA,CAAS;AAAA;AACvD,WACF;AAAA,UACA,MAAO,QAAA,CAAiE,KAAA,CAAM,MAAA,EAAQ,IAAI;AAAA,SAC5F;AAAA,MACF,CAAA;AAAA,IACF;AAAA,GACD,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"instrumentSqlStorage.js","sources":["../../../../src/instrumentations/instrumentSqlStorage.ts"],"sourcesContent":["import type { SqlStorage } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport { getClient, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\nimport { getSqlQuerySummary, sanitizeSqlQuery } from '@sentry/server-utils';\nimport type { CloudflareClientOptions } from '../client';\nimport { targetsCloudflareInternalTable } from '../utils/internalSqlQuery';\n\n/**\n * Instruments the Durable Object SqlStorage `exec` method with Sentry spans.\n *\n * @param sql - The SqlStorage instance to instrument\n * @returns An instrumented SqlStorage instance\n */\nexport function instrumentSqlStorage(sql: SqlStorage): SqlStorage {\n return new Proxy(sql, {\n get(target, prop, _receiver) {\n const original = Reflect.get(target, prop, target);\n\n if (prop !== 'exec' || typeof original !== 'function') {\n return original;\n }\n\n return function (this: unknown, ...args: unknown[]) {\n const [query, ...bindings] = args as [string, ...unknown[]];\n\n const sanitizedQuery = sanitizeSqlQuery(query);\n const querySummary = getSqlQuerySummary(sanitizedQuery);\n\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- rule false positive: the cast reaches the Cloudflare-only `durableObjectSqlSpanAllowlist`; tsc errors without it\n const allowlist = (getClient()?.getOptions() as CloudflareClientOptions | undefined)\n ?.durableObjectSqlSpanAllowlist;\n\n if (targetsCloudflareInternalTable(querySummary, allowlist, sanitizedQuery)) {\n return (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args);\n }\n\n return startSpan(\n {\n name: querySummary || sanitizedQuery,\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object.sql',\n 'db.system.name': 'cloudflare-durable-object-sql',\n 'db.operation.name': 'exec',\n 'db.query.text': sanitizedQuery,\n 'db.query.summary': querySummary,\n 'cloudflare.durable_object.query.bindings': bindings.length,\n },\n },\n () => (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args),\n );\n };\n },\n });\n}\n"],"names":[],"mappings":";;;;;;AAcO,SAAS,qBAAqB,GAAA,EAA6B;AAChE,EAAA,OAAO,IAAI,MAAM,GAAA,EAAK;AAAA,IACpB,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAW;AAC3B,MAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,MAAM,CAAA;AAEjD,MAAA,IAAI,IAAA,KAAS,MAAA,IAAU,OAAO,QAAA,KAAa,UAAA,EAAY;AACrD,QAAA,OAAO,QAAA;AAAA,MACT;AAEA,MAAA,OAAO,YAA4B,IAAA,EAAiB;AAClD,QAAA,MAAM,CAAC,KAAA,EAAO,GAAG,QAAQ,CAAA,GAAI,IAAA;AAE7B,QAAA,MAAM,cAAA,GAAiB,iBAAiB,KAAK,CAAA;AAC7C,QAAA,MAAM,YAAA,GAAe,mBAAmB,cAAc,CAAA;AAGtD,QAAA,MAAM,SAAA,GAAa,SAAA,EAAU,EAAG,UAAA,EAAW,EACvC,6BAAA;AAEJ,QAAA,IAAI,8BAAA,CAA+B,YAAA,EAAc,SAAA,EAAW,cAAc,CAAA,EAAG;AAC3E,UAAA,OAAQ,QAAA,CAAiE,KAAA,CAAM,MAAA,EAAQ,IAAI,CAAA;AAAA,QAC7F;AAEA,QAAA,OAAO,SAAA;AAAA,UACL;AAAA,YACE,MAAM,YAAA,IAAgB,cAAA;AAAA,YACtB,UAAA,EAAY;AAAA,cACV,CAAC,SAAS,GAAG,QAAA;AAAA,cACb,CAAC,gCAAgC,GAAG,uCAAA;AAAA,cACpC,gBAAA,EAAkB,+BAAA;AAAA,cAClB,mBAAA,EAAqB,MAAA;AAAA,cACrB,eAAA,EAAiB,cAAA;AAAA,cACjB,kBAAA,EAAoB,YAAA;AAAA,cACpB,4CAA4C,QAAA,CAAS;AAAA;AACvD,WACF;AAAA,UACA,MAAO,QAAA,CAAiE,KAAA,CAAM,MAAA,EAAQ,IAAI;AAAA,SAC5F;AAAA,MACF,CAAA;AAAA,IACF;AAAA,GACD,CAAA;AACH;;;;"}
@@ -1,5 +1,6 @@
1
1
  import { RPC } from '@sentry/conventions/op';
2
2
  import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';
3
+ import { markAsInstrumented } from '../instrument.js';
3
4
  import { getFinalOptions } from '../options.js';
4
5
  import { instrumentContext } from '../utils/instrumentContext.js';
5
6
  import { wrapMethodWithSentry } from '../wrapMethodWithSentry.js';
@@ -65,7 +66,7 @@ function instrumentMethod(instance, proxy, prop, method, options, context) {
65
66
  }
66
67
  function instrumentWorkerEntrypoint(optionsCallback, WorkerEntrypointClass) {
67
68
  setAsyncLocalStorageAsyncContextStrategy();
68
- return new Proxy(WorkerEntrypointClass, {
69
+ const InstrumentedClass = new Proxy(WorkerEntrypointClass, {
69
70
  construct(target, [ctx, env]) {
70
71
  const context = instrumentContext(ctx);
71
72
  const options = getFinalOptions(optionsCallback(env), env);
@@ -124,6 +125,8 @@ function instrumentWorkerEntrypoint(optionsCallback, WorkerEntrypointClass) {
124
125
  return proxy;
125
126
  }
126
127
  });
128
+ markAsInstrumented(InstrumentedClass);
129
+ return InstrumentedClass;
127
130
  }
128
131
 
129
132
  export { instrumentWorkerEntrypoint };
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentWorkerEntrypoint.js","sources":["../../../../src/instrumentations/instrumentWorkerEntrypoint.ts"],"sourcesContent":["import type { RpcStub, WorkerEntrypoint } from 'cloudflare:workers';\nimport { RPC } from '@sentry/conventions/op';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\nimport type { CloudflareOptions } from '../client';\nimport { getFinalOptions } from '../options';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from '../types';\nimport { instrumentContext } from '../utils/instrumentContext';\nimport { type UncheckedMethod, wrapMethodWithSentry } from '../wrapMethodWithSentry';\nimport { instrumentEnv } from './worker/instrumentEnv';\nimport { instrumentWorkerEntrypointFetch } from './worker/instrumentFetch';\nimport { instrumentWorkerEntrypointQueue } from './worker/instrumentQueue';\nimport { instrumentWorkerEntrypointScheduled } from './worker/instrumentScheduled';\nimport { instrumentWorkerEntrypointTail } from './worker/instrumentTail';\n\nconst WORKER_ENTRYPOINT_ORIGIN = 'auto.faas.cloudflare.worker_entrypoint';\n\ntype ReservedMethod =\n | Exclude<Extract<keyof WorkerEntrypoint, string>, '__WORKER_ENTRYPOINT_BRAND'>\n | Extract<keyof ExportedHandler, string>\n | Exclude<Extract<keyof RpcStub<(...args: unknown[]) => unknown>, string>, '__RPC_STUB_BRAND'>\n | 'constructor';\n\nconst RESERVED_METHODS = new Set<string>([\n 'connect',\n 'constructor',\n 'dup',\n 'email',\n 'fetch',\n 'queue',\n 'scheduled',\n 'tail',\n 'tailStream',\n 'test',\n 'trace',\n] satisfies ReservedMethod[]);\n\ninterface CachedMethod {\n source: UncheckedMethod;\n wrapped: UncheckedMethod;\n}\n\nexport type WorkerEntrypointConstructor<Env = unknown, Props = {}> = new (\n ctx: ExecutionContext,\n // WorkerEntrypoint subclasses can define different `env` shapes, so this constructor must accept all of them.\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n) => InstanceType<typeof WorkerEntrypoint<Env, Props>>;\n\nfunction isPrototypeMethod(instance: object, prop: string, method: UncheckedMethod): boolean {\n let prototype = Object.getPrototypeOf(instance);\n\n while (prototype && prototype !== Object.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, prop);\n if (descriptor) {\n return descriptor.value === method;\n }\n prototype = Object.getPrototypeOf(prototype);\n }\n\n return false;\n}\n\nfunction bindToInstance(instance: object, proxy: object, method: UncheckedMethod): UncheckedMethod {\n return new Proxy(method, {\n apply(target, thisArg, args) {\n return Reflect.apply(target, thisArg === proxy ? instance : thisArg, args);\n },\n });\n}\n\nfunction instrumentMethod(\n instance: object,\n proxy: object,\n prop: PropertyKey,\n method: UncheckedMethod,\n options: CloudflareOptions,\n context: ExecutionContext,\n): UncheckedMethod {\n const ownDescriptor = Object.getOwnPropertyDescriptor(instance, prop);\n if (ownDescriptor && 'value' in ownDescriptor && !ownDescriptor.configurable && !ownDescriptor.writable) {\n return method;\n }\n\n const boundMethod = bindToInstance(instance, proxy, method);\n\n if (typeof prop !== 'string' || RESERVED_METHODS.has(prop) || !isPrototypeMethod(instance, prop, method)) {\n return boundMethod;\n }\n\n return wrapMethodWithSentry(\n {\n options,\n context,\n spanName: rpcMeta => (rpcMeta ? prop : undefined),\n spanOp: RPC,\n origin: WORKER_ENTRYPOINT_ORIGIN,\n },\n boundMethod,\n undefined,\n true,\n );\n}\n\n/**\n * Instruments a WorkerEntrypoint class to capture errors and performance data.\n *\n * Instruments the following methods (same as `withSentry` for ExportedHandler):\n * - fetch (HTTP requests)\n * - scheduled (cron triggers)\n * - queue (queue consumers)\n * - email (email handlers)\n * - tail (tail workers)\n *\n * as well as any other public RPC methods on the WorkerEntrypoint instance.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param WorkerEntrypointClass The WorkerEntrypoint class to instrument.\n * @returns The instrumented WorkerEntrypoint class.\n *\n * @example\n * ```ts\n * class MyWorkerBase extends WorkerEntrypoint<Env> {\n * async fetch(request: Request): Promise<Response> {\n * return new Response('Hello World!');\n * }\n *\n * async myRpcMethod(arg: string): Promise<string> {\n * return `Hello ${arg}!`;\n * }\n * }\n *\n * export default instrumentWorkerEntrypoint(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyWorkerBase,\n * );\n * ```\n */\nexport function instrumentWorkerEntrypoint<\n Env = DefaultEnv,\n Props = {},\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkerEntrypoint<any, any> = WorkerEntrypoint<Env, Props>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => T = new (ctx: ExecutionContext, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O> | undefined, WorkerEntrypointClass: C): C {\n // Set up AsyncLocalStorage strategy ONCE at instrumentation time, not per-request\n // This is critical - calling this per-request would create a new AsyncLocalStorage\n // each time, breaking scope isolation for concurrent requests\n setAsyncLocalStorageAsyncContextStrategy();\n\n return new Proxy(WorkerEntrypointClass, {\n construct(target, [ctx, env]) {\n const context = instrumentContext(ctx);\n const options = getFinalOptions(optionsCallback(env), env);\n const instrumentedEnv = instrumentEnv(env, options);\n const obj = new target(context, instrumentedEnv);\n\n // Override this.ctx to ensure the instrumented context is used\n // This is necessary because the base WorkerEntrypoint class sets this.ctx\n // from the constructor parameter, but we want users accessing this.ctx\n // to get the instrumented version\n if ('ctx' in obj) {\n Object.defineProperty(obj, 'ctx', {\n value: context,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n\n if ('env' in obj) {\n Object.defineProperty(obj, 'env', {\n value: instrumentedEnv,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n\n Object.defineProperty(obj, '__SENTRY_CONTEXT__', {\n value: context,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n Object.defineProperty(obj, '__SENTRY_OPTIONS__', {\n value: options,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n const entrypoint = obj as WorkerEntrypoint;\n instrumentWorkerEntrypointFetch(entrypoint, options, context);\n instrumentWorkerEntrypointScheduled(entrypoint, options, context);\n instrumentWorkerEntrypointQueue(entrypoint, options, context);\n instrumentWorkerEntrypointTail(entrypoint, options, context);\n\n // workerd resolves RPC methods through property access.\n const methodCache = new Map<PropertyKey, CachedMethod>();\n\n const proxy: typeof obj = new Proxy(obj, {\n get(instance, prop) {\n const value = Reflect.get(instance, prop, instance);\n\n if (typeof value !== 'function') {\n return value;\n }\n\n const method = value as UncheckedMethod;\n\n const cached = methodCache.get(prop);\n if (cached?.source === method) {\n return cached.wrapped;\n }\n\n const wrapped = instrumentMethod(instance, proxy, prop, method, options, context);\n methodCache.set(prop, { source: method, wrapped });\n return wrapped;\n },\n });\n\n return proxy;\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;AAcA,MAAM,wBAAA,GAA2B,wCAAA;AAQjC,MAAM,gBAAA,uBAAuB,GAAA,CAAY;AAAA,EACvC,SAAA;AAAA,EACA,aAAA;AAAA,EACA,KAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,MAAA;AAAA,EACA,YAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF,CAA4B,CAAA;AAc5B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,UAAU,gBAAA,CAAiB,QAAA,EAAU,OAAO,IAAA,EAAM,MAAA,EAAQ,SAAS,OAAO,CAAA;AAChF,UAAA,WAAA,CAAY,IAAI,IAAA,EAAM,EAAE,MAAA,EAAQ,MAAA,EAAQ,SAAS,CAAA;AACjD,UAAA,OAAO,OAAA;AAAA,QACT;AAAA,OACD,CAAA;AAED,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,GACD,CAAA;AACH;;;;"}
1
+ {"version":3,"file":"instrumentWorkerEntrypoint.js","sources":["../../../../src/instrumentations/instrumentWorkerEntrypoint.ts"],"sourcesContent":["import type { RpcStub, WorkerEntrypoint } from 'cloudflare:workers';\nimport { RPC } from '@sentry/conventions/op';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\nimport type { CloudflareOptions } from '../client';\nimport { markAsInstrumented } from '../instrument';\nimport { getFinalOptions } from '../options';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from '../types';\nimport { instrumentContext } from '../utils/instrumentContext';\nimport { type UncheckedMethod, wrapMethodWithSentry } from '../wrapMethodWithSentry';\nimport { instrumentEnv } from './worker/instrumentEnv';\nimport { instrumentWorkerEntrypointFetch } from './worker/instrumentFetch';\nimport { instrumentWorkerEntrypointQueue } from './worker/instrumentQueue';\nimport { instrumentWorkerEntrypointScheduled } from './worker/instrumentScheduled';\nimport { instrumentWorkerEntrypointTail } from './worker/instrumentTail';\n\nconst WORKER_ENTRYPOINT_ORIGIN = 'auto.faas.cloudflare.worker_entrypoint';\n\ntype ReservedMethod =\n | Exclude<Extract<keyof WorkerEntrypoint, string>, '__WORKER_ENTRYPOINT_BRAND'>\n | Extract<keyof ExportedHandler, string>\n | Exclude<Extract<keyof RpcStub<(...args: unknown[]) => unknown>, string>, '__RPC_STUB_BRAND'>\n | 'constructor';\n\nconst RESERVED_METHODS = new Set<string>([\n 'connect',\n 'constructor',\n 'dup',\n 'email',\n 'fetch',\n 'queue',\n 'scheduled',\n 'tail',\n 'tailStream',\n 'test',\n 'trace',\n] satisfies ReservedMethod[]);\n\ninterface CachedMethod {\n source: UncheckedMethod;\n wrapped: UncheckedMethod;\n}\n\nexport type WorkerEntrypointConstructor<Env = unknown, Props = {}> = new (\n ctx: ExecutionContext,\n // WorkerEntrypoint subclasses can define different `env` shapes, so this constructor must accept all of them.\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n) => InstanceType<typeof WorkerEntrypoint<Env, Props>>;\n\nfunction isPrototypeMethod(instance: object, prop: string, method: UncheckedMethod): boolean {\n let prototype = Object.getPrototypeOf(instance);\n\n while (prototype && prototype !== Object.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, prop);\n if (descriptor) {\n return descriptor.value === method;\n }\n prototype = Object.getPrototypeOf(prototype);\n }\n\n return false;\n}\n\nfunction bindToInstance(instance: object, proxy: object, method: UncheckedMethod): UncheckedMethod {\n return new Proxy(method, {\n apply(target, thisArg, args) {\n return Reflect.apply(target, thisArg === proxy ? instance : thisArg, args);\n },\n });\n}\n\nfunction instrumentMethod(\n instance: object,\n proxy: object,\n prop: PropertyKey,\n method: UncheckedMethod,\n options: CloudflareOptions,\n context: ExecutionContext,\n): UncheckedMethod {\n const ownDescriptor = Object.getOwnPropertyDescriptor(instance, prop);\n if (ownDescriptor && 'value' in ownDescriptor && !ownDescriptor.configurable && !ownDescriptor.writable) {\n return method;\n }\n\n const boundMethod = bindToInstance(instance, proxy, method);\n\n if (typeof prop !== 'string' || RESERVED_METHODS.has(prop) || !isPrototypeMethod(instance, prop, method)) {\n return boundMethod;\n }\n\n return wrapMethodWithSentry(\n {\n options,\n context,\n spanName: rpcMeta => (rpcMeta ? prop : undefined),\n spanOp: RPC,\n origin: WORKER_ENTRYPOINT_ORIGIN,\n },\n boundMethod,\n undefined,\n true,\n );\n}\n\n/**\n * Instruments a WorkerEntrypoint class to capture errors and performance data.\n *\n * Instruments the following methods (same as `withSentry` for ExportedHandler):\n * - fetch (HTTP requests)\n * - scheduled (cron triggers)\n * - queue (queue consumers)\n * - email (email handlers)\n * - tail (tail workers)\n *\n * as well as any other public RPC methods on the WorkerEntrypoint instance.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param WorkerEntrypointClass The WorkerEntrypoint class to instrument.\n * @returns The instrumented WorkerEntrypoint class.\n *\n * @example\n * ```ts\n * class MyWorkerBase extends WorkerEntrypoint<Env> {\n * async fetch(request: Request): Promise<Response> {\n * return new Response('Hello World!');\n * }\n *\n * async myRpcMethod(arg: string): Promise<string> {\n * return `Hello ${arg}!`;\n * }\n * }\n *\n * export default instrumentWorkerEntrypoint(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyWorkerBase,\n * );\n * ```\n */\nexport function instrumentWorkerEntrypoint<\n Env = DefaultEnv,\n Props = {},\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkerEntrypoint<any, any> = WorkerEntrypoint<Env, Props>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => T = new (ctx: ExecutionContext, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O> | undefined, WorkerEntrypointClass: C): C {\n // Set up AsyncLocalStorage strategy ONCE at instrumentation time, not per-request\n // This is critical - calling this per-request would create a new AsyncLocalStorage\n // each time, breaking scope isolation for concurrent requests\n setAsyncLocalStorageAsyncContextStrategy();\n\n const InstrumentedClass = new Proxy(WorkerEntrypointClass, {\n construct(target, [ctx, env]) {\n const context = instrumentContext(ctx);\n const options = getFinalOptions(optionsCallback(env), env);\n const instrumentedEnv = instrumentEnv(env, options);\n const obj = new target(context, instrumentedEnv);\n\n // Override this.ctx to ensure the instrumented context is used\n // This is necessary because the base WorkerEntrypoint class sets this.ctx\n // from the constructor parameter, but we want users accessing this.ctx\n // to get the instrumented version\n if ('ctx' in obj) {\n Object.defineProperty(obj, 'ctx', {\n value: context,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n\n if ('env' in obj) {\n Object.defineProperty(obj, 'env', {\n value: instrumentedEnv,\n writable: true,\n enumerable: true,\n configurable: true,\n });\n }\n\n Object.defineProperty(obj, '__SENTRY_CONTEXT__', {\n value: context,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n Object.defineProperty(obj, '__SENTRY_OPTIONS__', {\n value: options,\n enumerable: false,\n writable: false,\n configurable: false,\n });\n\n const entrypoint = obj as WorkerEntrypoint;\n instrumentWorkerEntrypointFetch(entrypoint, options, context);\n instrumentWorkerEntrypointScheduled(entrypoint, options, context);\n instrumentWorkerEntrypointQueue(entrypoint, options, context);\n instrumentWorkerEntrypointTail(entrypoint, options, context);\n\n // workerd resolves RPC methods through property access.\n const methodCache = new Map<PropertyKey, CachedMethod>();\n\n const proxy: typeof obj = new Proxy(obj, {\n get(instance, prop) {\n const value = Reflect.get(instance, prop, instance);\n\n if (typeof value !== 'function') {\n return value;\n }\n\n const method = value as UncheckedMethod;\n\n const cached = methodCache.get(prop);\n if (cached?.source === method) {\n return cached.wrapped;\n }\n\n const wrapped = instrumentMethod(instance, proxy, prop, method, options, context);\n methodCache.set(prop, { source: method, wrapped });\n return wrapped;\n },\n });\n\n return proxy;\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAeA,MAAM,wBAAA,GAA2B,wCAAA;AAQjC,MAAM,gBAAA,uBAAuB,GAAA,CAAY;AAAA,EACvC,SAAA;AAAA,EACA,aAAA;AAAA,EACA,KAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA,OAAA;AAAA,EACA,WAAA;AAAA,EACA,MAAA;AAAA,EACA,YAAA;AAAA,EACA,MAAA;AAAA,EACA;AACF,CAA4B,CAAA;AAc5B,SAAS,iBAAA,CAAkB,QAAA,EAAkB,IAAA,EA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AAA,EAAU,OAAO,IAAA,EAAM,MAAA,EAAQ,SAAS,OAAO,CAAA;AAChF,UAAA,WAAA,CAAY,IAAI,IAAA,EAAM,EAAE,MAAA,EAAQ,MAAA,EAAQ,SAAS,CAAA;AACjD,UAAA,OAAO,OAAA;AAAA,QACT;AAAA,OACD,CAAA;AAED,MAAA,OAAO,KAAA;AAAA,IACT;AAAA,GACD,CAAA;AAED,EAAA,kBAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;;;;"}
@@ -1,7 +1,7 @@
1
1
  import { SENTRY_OP } from '@sentry/conventions/attributes';
2
2
  import { DB_QUERY } from '@sentry/conventions/op';
3
3
  import { startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getClient, hasSpanStreamingEnabled, addBreadcrumb, SPAN_STATUS_ERROR } from '@sentry/core';
4
- import { _INTERNAL_getSqlQuerySummary, _INTERNAL_sanitizeSqlQuery } from '@sentry/core/server';
4
+ import { getSqlQuerySummary, sanitizeSqlQuery } from '@sentry/server-utils';
5
5
  import { ensureInstrumented } from '../../instrument.js';
6
6
 
7
7
  const patchedStatement = /* @__PURE__ */ new WeakSet();
@@ -82,7 +82,7 @@ function createD1Breadcrumb(query, type, d1Result) {
82
82
  });
83
83
  }
84
84
  function createStartSpanOptions(query, type) {
85
- const querySummary = query ? _INTERNAL_getSqlQuerySummary(_INTERNAL_sanitizeSqlQuery(query)) : void 0;
85
+ const querySummary = query ? getSqlQuerySummary(sanitizeSqlQuery(query)) : void 0;
86
86
  const client = getClient();
87
87
  const name = client && hasSpanStreamingEnabled(client) ? querySummary || "cloudflare-d1" : query;
88
88
  return {
@@ -1 +1 @@
1
- {"version":3,"file":"instrumentD1.js","sources":["../../../../../src/instrumentations/worker/instrumentD1.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport type { D1Database, D1DatabaseSession, D1PreparedStatement, D1Response } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes, StartSpanOptions } from '@sentry/core';\nimport {\n addBreadcrumb,\n getClient,\n hasSpanStreamingEnabled,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n startSpan,\n} from '@sentry/core';\nimport { _INTERNAL_getSqlQuerySummary, _INTERNAL_sanitizeSqlQuery } from '@sentry/core/server';\nimport { ensureInstrumented } from '../../instrument';\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\ntype D1QueryType = 'first' | 'run' | 'all' | 'raw' | 'batch' | 'exec';\n\nfunction createD1Breadcrumb(query: string, type: D1QueryType, d1Result?: D1Response): void {\n addBreadcrumb({\n category: 'query',\n message: query,\n data: {\n ...(d1Result ? getAttributesFromD1Response(d1Result) : {}),\n 'db.operation.name': type,\n },\n });\n}\n\nfunction createStartSpanOptions(query: string, type: D1QueryType): StartSpanOptions {\n const querySummary = query ? _INTERNAL_getSqlQuerySummary(_INTERNAL_sanitizeSqlQuery(query)) : undefined;\n\n const client = getClient();\n const name = client && hasSpanStreamingEnabled(client) ? querySummary || 'cloudflare-d1' : query;\n\n return {\n name,\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n 'db.system.name': 'cloudflare-d1',\n 'db.operation.name': type,\n 'db.query.text': query,\n 'db.query.summary': querySummary,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n };\n}\n\nfunction instrumentPrepare(\n prepare: D1Database['prepare'] | D1DatabaseSession['prepare'],\n): D1Database['prepare'] | D1DatabaseSession['prepare'] {\n return new Proxy(prepare, {\n apply(target, thisArg, args: Parameters<typeof prepare>) {\n const [query] = args;\n return instrumentD1PreparedStatement(Reflect.apply(target, thisArg, args), query);\n },\n });\n}\n\nfunction instrumentBatch(\n batch: D1Database['batch'] | D1DatabaseSession['batch'],\n): D1Database['batch'] | D1DatabaseSession['batch'] {\n return new Proxy(batch, {\n apply(target, thisArg, args: Parameters<typeof batch>) {\n const statements = args[0];\n // D1PreparedStatement exposes a `statement` property at runtime, but it's not in @cloudflare/workers-types.\n // https://github.com/cloudflare/workerd/blob/dc12d7650b4f5d4f9ba6a47aa45fad769cdf8db4/src/cloudflare/internal/d1-api.ts#L210\n const queryText = statements\n .map(statement => (statement as unknown as { statement?: string }).statement ?? '')\n .filter(Boolean)\n .join('\\n');\n\n return startSpan(\n {\n name: 'D1 batch',\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n 'db.system.name': 'cloudflare-d1',\n 'db.operation.name': 'batch',\n 'db.query.text': queryText || undefined,\n 'db.operation.batch.size': statements.length,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n },\n async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb('D1 batch', 'batch');\n return res;\n },\n );\n },\n });\n}\n\nfunction instrumentD1Session(session: D1DatabaseSession): D1DatabaseSession {\n session.prepare = instrumentPrepare(session.prepare);\n session.batch = instrumentBatch(session.batch);\n return session;\n}\n\nfunction _instrumentD1(db: D1Database): D1Database {\n db.prepare = instrumentPrepare(db.prepare);\n db.batch = instrumentBatch(db.batch);\n\n db.exec = new Proxy(db.exec, {\n apply(target, thisArg, args: Parameters<typeof db.exec>) {\n const [query] = args;\n return startSpan(createStartSpanOptions(query, 'exec'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(query, 'exec');\n return res;\n });\n },\n });\n\n if ('withSession' in db && typeof db.withSession === 'function') {\n db.withSession = new Proxy(db.withSession, {\n apply(target, thisArg, args: [unknown]) {\n return instrumentD1Session(Reflect.apply(target, thisArg, args) as D1DatabaseSession);\n },\n });\n }\n\n return db;\n}\n\nexport function instrumentD1(db: D1Database): D1Database {\n return ensureInstrumented(db, _instrumentD1);\n}\n"],"names":[],"mappings":";;;;;;AAmBA,MAAM,gBAAA,uBAAuB,OAAA,EAA6B;AAK1D,SAAS,oCAAA,CAAqC,WAAgC,KAAA,EAAoC;AAChH,EAAA,IAAI,gBAAA,CAAiB,GAAA,CAAI,SAAS,CAAA,EAAG;AACnC,IAAA,OAAO,SAAA;AAAA,EACT;AAGA,EAAA,SAAA,CAAU,KAAA,GAAQ,IAAI,KAAA,CAAM,SAAA,CAAU,KAAA,EAAO;AAAA,IAC3C,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAA,EAA0C;AAC/D,MAAA,OAAO,SAAA,CAAU,sBAAA,CAAuB,KAAA,EAAO,OAAO,GAAG,YAAY;AACnE,QAAA,MAAM,MAAM,MAAM,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,SAAS,IAAI,CAAA;AACrD,QAAA,kBAAA,CAAmB,OAAO,OAAO,CAAA;AACjC,QAAA,OAAO,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MAAA,EAAQ,OAAA,EAAS,IAAA,EAAkC;AACvD,MAAA,MAAM,CAAC,KAAK,CAAA,GAAI,IAAA;AAChB,MAAA,OAAO,SAAA,CAAU,sBAAA,CAAuB,KAAA,EAAO,MAAM,GAAG,YAAY;AAClE,QAAA,MAAM,MAAM,MAAM,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,SAAS,IAAI,CAAA;AACrD,QAAA,kBAAA,CAAmB,OAAO,MAAM,CAAA;AAChC,QAAA,OAAO,GAAA;AAAA,MACT,CAAC,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AAED,EAAA,IAAI,aAAA,IAAiB,EAAA,IAAM,OAAO,EAAA,CAAG,gBAAgB,UAAA,EAAY;AAC/D,IAAA,EAAA,CAAG,WAAA,GAAc,IAAI,KAAA,CAAM,EAAA,CAAG,WAAA,EAAa;AAAA,MACzC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAiB;AACtC,QAAA,OAAO,oBAAoB,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAI,CAAsB,CAAA;AAAA,MACtF;AAAA,KACD,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,EAAA;AACT;AAEO,SAAS,aAAa,EAAA,EAA4B;AACvD,EAAA,OAAO,kBAAA,CAAmB,IAAI,aAAa,CAAA;AAC7C;;;;"}
1
+ {"version":3,"file":"instrumentD1.js","sources":["../../../../../src/instrumentations/worker/instrumentD1.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport type { D1Database, D1DatabaseSession, D1PreparedStatement, D1Response } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes, StartSpanOptions } from '@sentry/core';\nimport {\n addBreadcrumb,\n getClient,\n hasSpanStreamingEnabled,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n startSpan,\n} from '@sentry/core';\nimport { getSqlQuerySummary, sanitizeSqlQuery } from '@sentry/server-utils';\nimport { ensureInstrumented } from '../../instrument';\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\ntype D1QueryType = 'first' | 'run' | 'all' | 'raw' | 'batch' | 'exec';\n\nfunction createD1Breadcrumb(query: string, type: D1QueryType, d1Result?: D1Response): void {\n addBreadcrumb({\n category: 'query',\n message: query,\n data: {\n ...(d1Result ? getAttributesFromD1Response(d1Result) : {}),\n 'db.operation.name': type,\n },\n });\n}\n\nfunction createStartSpanOptions(query: string, type: D1QueryType): StartSpanOptions {\n const querySummary = query ? getSqlQuerySummary(sanitizeSqlQuery(query)) : undefined;\n\n const client = getClient();\n const name = client && hasSpanStreamingEnabled(client) ? querySummary || 'cloudflare-d1' : query;\n\n return {\n name,\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n 'db.system.name': 'cloudflare-d1',\n 'db.operation.name': type,\n 'db.query.text': query,\n 'db.query.summary': querySummary,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n };\n}\n\nfunction instrumentPrepare(\n prepare: D1Database['prepare'] | D1DatabaseSession['prepare'],\n): D1Database['prepare'] | D1DatabaseSession['prepare'] {\n return new Proxy(prepare, {\n apply(target, thisArg, args: Parameters<typeof prepare>) {\n const [query] = args;\n return instrumentD1PreparedStatement(Reflect.apply(target, thisArg, args), query);\n },\n });\n}\n\nfunction instrumentBatch(\n batch: D1Database['batch'] | D1DatabaseSession['batch'],\n): D1Database['batch'] | D1DatabaseSession['batch'] {\n return new Proxy(batch, {\n apply(target, thisArg, args: Parameters<typeof batch>) {\n const statements = args[0];\n // D1PreparedStatement exposes a `statement` property at runtime, but it's not in @cloudflare/workers-types.\n // https://github.com/cloudflare/workerd/blob/dc12d7650b4f5d4f9ba6a47aa45fad769cdf8db4/src/cloudflare/internal/d1-api.ts#L210\n const queryText = statements\n .map(statement => (statement as unknown as { statement?: string }).statement ?? '')\n .filter(Boolean)\n .join('\\n');\n\n return startSpan(\n {\n name: 'D1 batch',\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n 'db.system.name': 'cloudflare-d1',\n 'db.operation.name': 'batch',\n 'db.query.text': queryText || undefined,\n 'db.operation.batch.size': statements.length,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n },\n async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb('D1 batch', 'batch');\n return res;\n },\n );\n },\n });\n}\n\nfunction instrumentD1Session(session: D1DatabaseSession): D1DatabaseSession {\n session.prepare = instrumentPrepare(session.prepare);\n session.batch = instrumentBatch(session.batch);\n return session;\n}\n\nfunction _instrumentD1(db: D1Database): D1Database {\n db.prepare = instrumentPrepare(db.prepare);\n db.batch = instrumentBatch(db.batch);\n\n db.exec = new Proxy(db.exec, {\n apply(target, thisArg, args: Parameters<typeof db.exec>) {\n const [query] = args;\n return startSpan(createStartSpanOptions(query, 'exec'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(query, 'exec');\n return res;\n });\n },\n });\n\n if ('withSession' in db && typeof db.withSession === 'function') {\n db.withSession = new Proxy(db.withSession, {\n apply(target, thisArg, args: [unknown]) {\n return instrumentD1Session(Reflect.apply(target, thisArg, args) as D1DatabaseSession);\n },\n });\n }\n\n return db;\n}\n\nexport function instrumentD1(db: D1Database): D1Database {\n return ensureInstrumented(db, _instrumentD1);\n}\n"],"names":[],"mappings":";;;;;;AAmBA,MAAM,gBAAA,uBAAuB,OAAA,EAA6B;AAK1D,SAAS,oCAAA,CAAqC,WAAgC,KAAA,EAAoC;AAChH,EAAA,IAAI,gBAAA,CAAiB,GAAA,CAAI,SAAS,CAAA,EAAG;AACnC,IAAA,OAAO,SAAA;AAAA,EACT;AAGA,EAAA,SAAA,CAAU,KAAA,GAAQ,IAAI,KAAA,CAAM,SAAA,CAAU,KAAA,EAAO;AAAA,IAC3C,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAA,EAA0C;AAC/D,MAAA,OAAO,SAAA,CAAU,sBAAA,CAAuB,KAAA,EAAO,OAAO,GAAG,YAAY;AACnE,QAAA,MAAM,MAAM,MAAM,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,SAAS,IAAI,CAAA;AACrD,QAAA,kBAAA,CAAmB,OAAO,OAAO,CAAA;AACjC,QAAA,OAAO,GAAA;AAAA,MACT,CAAC,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AAGD,EAAA,SAAA,CAAU,GAAA,GAAM,IAAI,KAAA,CAAM,SAAA,CAAU,GAAA,EAAK;AAAA,IACvC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAwC;AAC7D,MAAA,OAAO,UAAU,sBAA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,SAAS,IAAI,CAAA;AACrD,QAAA,kBAAA,CAAmB,OAAO,MAAM,CAAA;AAChC,QAAA,OAAO,GAAA;AAAA,MACT,CAAC,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AAED,EAAA,IAAI,aAAA,IAAiB,EAAA,IAAM,OAAO,EAAA,CAAG,gBAAgB,UAAA,EAAY;AAC/D,IAAA,EAAA,CAAG,WAAA,GAAc,IAAI,KAAA,CAAM,EAAA,CAAG,WAAA,EAAa;AAAA,MACzC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAiB;AACtC,QAAA,OAAO,oBAAoB,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAI,CAAsB,CAAA;AAAA,MACtF;AAAA,KACD,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,EAAA;AACT;AAEO,SAAS,aAAa,EAAA,EAA4B;AACvD,EAAA,OAAO,kBAAA,CAAmB,IAAI,aAAa,CAAA;AAC7C;;;;"}
@@ -1 +1 @@
1
- {"type":"module","version":"11.0.0-beta.0","sideEffects":false}
1
+ {"type":"module","version":"11.0.0-beta.2","sideEffects":false}
@@ -21,12 +21,13 @@ async function detectAgentClasses(ast, entryId, candidates, resolver) {
21
21
  function collectAgentCandidates(ast, configuredNames) {
22
22
  const shape = shapeFromAst(ast);
23
23
  const candidates = /* @__PURE__ */ new Set();
24
+ const isResolvable = (name) => shape.classes.has(name) || shape.imports.has(name) || shape.reexports.has(name);
24
25
  for (const configured of configuredNames) {
25
- if (shape.classes.has(configured)) {
26
+ if (isResolvable(configured)) {
26
27
  candidates.add(configured);
27
28
  }
28
29
  const local = shape.localExports.get(configured);
29
- if (local && shape.classes.has(local)) {
30
+ if (local && isResolvable(local)) {
30
31
  candidates.add(local);
31
32
  }
32
33
  }
@@ -1 +1 @@
1
- {"version":3,"file":"agentClass.js","sources":["../../../../src/vite/agentClass.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { DEFAULT_EXPORT, type ModuleShape, shapeFromAst, shapeFromSource, type SuperRef } from './moduleShape';\nimport type { ProgramBody } from './transform';\n\n/**\n * Agent base classes, keyed by the module specifier they are imported from. A class extending any\n * of these — directly or through a chain of local/imported subclasses — is an `agents` Agent rather\n * than a plain Durable Object.\n *\n * `McpAgent`, `AIChatAgent` and `Think` all extend `Agent` themselves, but they live in packages\n * whose sources we never walk into (see {@link followImport}), so each needs its own entry.\n */\nconst AGENT_BASE_CLASSES: Record<string, ReadonlySet<string>> = {\n agents: new Set(['Agent']),\n 'agents/mcp': new Set(['McpAgent']),\n '@cloudflare/ai-chat': new Set(['AIChatAgent']),\n '@cloudflare/think': new Set(['Think']),\n};\n\n/**\n * How many modules deep the base-class chain is followed. Guards against pathological module graphs;\n * real Agent hierarchies are only a few levels deep.\n */\nconst MAX_DEPTH = 8;\n\n/**\n * The subset of the Vite/Rollup plugin context needed to walk the module graph.\n *\n * `resolve` is optional: without it detection still works, but only for base-class chains declared\n * inside the entry module itself. `readFile` is injectable for tests and defaults to reading disk.\n *\n * Deliberately **no `load`**: awaiting the plugin context's `load()` from inside a `transform` hook\n * deadlocks the build — the module cannot finish loading while its own transform is still pending\n * (Rollup documents this hazard, and Vite's Rolldown pipeline is stricter still). Sibling modules\n * are therefore read straight off disk; see {@link getModuleShape}.\n */\nexport interface ModuleResolver {\n parse(code: string): ProgramBody;\n resolve?(source: string, importer: string): Promise<{ id: string } | null | undefined>;\n readFile?(id: string): string | undefined;\n}\n\ninterface DetectContext {\n resolver: ModuleResolver;\n modules: Map<string, ModuleShape | undefined>;\n}\n\n/**\n * Find which of `candidates` (top-level class names in the entry module) are Cloudflare\n * [`agents`](https://www.npmjs.com/package/agents) Agents.\n *\n * An Agent is a Durable Object under the hood, so wrangler configures it as one and the transform\n * would otherwise reach for `instrumentDurableObjectWithSentry`. Detecting the Agent base chain lets\n * it pick `instrumentAgentWithSentry` instead, which adds the Agent-specific telemetry on top.\n *\n * Unlike `WorkerEntrypoint` detection, the chain is followed *across* modules: base classes commonly\n * live in their own file (`import { MyBase } from './base'`), and there is no runtime fallback that\n * would catch a missed one. Resolution stops at package boundaries — a base class imported from\n * `node_modules` is only recognized when it is one of {@link AGENT_BASE_CLASSES}.\n */\nexport async function detectAgentClasses(\n ast: ProgramBody,\n entryId: string,\n candidates: Iterable<string>,\n resolver: ModuleResolver,\n): Promise<Set<string>> {\n // The entry's shape comes from the AST Vite already handed us (TypeScript stripped, full\n // fidelity); only sibling modules fall back to source scanning.\n const ctx: DetectContext = { resolver, modules: new Map([[entryId, shapeFromAst(ast)]]) };\n\n const detected = new Set<string>();\n for (const name of candidates) {\n // A fresh cycle guard per candidate: a shared one would record \"not an Agent\" for bindings\n // visited while resolving an earlier candidate that turned out to be unrelated.\n if (await isAgentBinding(ctx, entryId, name, 0, new Set())) {\n detected.add(name);\n }\n }\n return detected;\n}\n\n/**\n * The local class names in the entry that a configured class name could refer to — either declared\n * under that name directly, or aliased to it by an `export { Local as Configured }` specifier.\n *\n * Keeps detection (which reads and scans other modules) off classes that no binding points at.\n */\nexport function collectAgentCandidates(ast: ProgramBody, configuredNames: Iterable<string>): Set<string> {\n const shape = shapeFromAst(ast);\n const candidates = new Set<string>();\n\n for (const configured of configuredNames) {\n if (shape.classes.has(configured)) {\n candidates.add(configured);\n }\n const local = shape.localExports.get(configured);\n if (local && shape.classes.has(local)) {\n candidates.add(local);\n }\n }\n\n return candidates;\n}\n\nasync function isAgentBinding(\n ctx: DetectContext,\n moduleId: string,\n name: string,\n depth: number,\n visited: Set<string>,\n): Promise<boolean> {\n if (depth > MAX_DEPTH) return false;\n\n const key = `${moduleId} ${name}`;\n if (visited.has(key)) return false;\n visited.add(key);\n\n const shape = await getModuleShape(ctx, moduleId);\n if (!shape) return false;\n\n if (shape.classes.has(name)) {\n return extendsAgent(ctx, shape, moduleId, shape.classes.get(name), depth, visited);\n }\n\n const imported = shape.imports.get(name);\n if (imported) {\n return followImport(ctx, moduleId, imported.source, imported.imported, depth, visited);\n }\n\n if (name === DEFAULT_EXPORT) {\n if (shape.defaultExportIsClass) {\n return extendsAgent(ctx, shape, moduleId, shape.defaultExportSuper, depth, visited);\n }\n if (shape.defaultExportName) {\n return isAgentBinding(ctx, moduleId, shape.defaultExportName, depth + 1, visited);\n }\n }\n\n // `export { Local as Requested }` — the caller asked by exported name.\n const localName = shape.localExports.get(name);\n if (localName) {\n return isAgentBinding(ctx, moduleId, localName, depth + 1, visited);\n }\n\n const reexport = shape.reexports.get(name);\n if (reexport) {\n return followImport(ctx, moduleId, reexport.source, reexport.imported, depth, visited);\n }\n\n // Barrel modules (`export * from './base'`) don't name the binding, so every star source is a\n // candidate home for it.\n for (const source of shape.starExports) {\n if (await followImport(ctx, moduleId, source, name, depth, visited)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Whether a superclass reference resolves to an Agent base — a bare identifier (imported, or a\n * subclass declared in the same module) or `ns.Agent` off a namespace import.\n */\nasync function extendsAgent(\n ctx: DetectContext,\n shape: ModuleShape,\n moduleId: string,\n superClass: SuperRef | undefined,\n depth: number,\n visited: Set<string>,\n): Promise<boolean> {\n if (!superClass) return false;\n\n if (superClass.kind === 'identifier') {\n return isAgentBinding(ctx, moduleId, superClass.name, depth + 1, visited);\n }\n\n const source = shape.namespaces.get(superClass.object);\n if (source) {\n return followImport(ctx, moduleId, source, superClass.property, depth, visited);\n }\n\n return false;\n}\n\n/** Resolve an import to its module and continue the search there, stopping at package boundaries. */\nasync function followImport(\n ctx: DetectContext,\n importerId: string,\n source: string,\n importedName: string,\n depth: number,\n visited: Set<string>,\n): Promise<boolean> {\n if (AGENT_BASE_CLASSES[source]?.has(importedName)) return true;\n\n if (!ctx.resolver.resolve) return false;\n\n let resolved: { id: string } | null | undefined;\n try {\n resolved = await ctx.resolver.resolve(source, importerId);\n } catch {\n return false;\n }\n if (!resolved?.id) return false;\n\n // Third-party sources are not walked: they are large, may not be plain JS by the time we see\n // them, and any Agent base worth knowing about is listed in AGENT_BASE_CLASSES.\n if (resolved.id.includes('/node_modules/') || resolved.id.includes('\\\\node_modules\\\\')) return false;\n\n return isAgentBinding(ctx, resolved.id, importedName, depth + 1, visited);\n}\n\nasync function getModuleShape(ctx: DetectContext, moduleId: string): Promise<ModuleShape | undefined> {\n if (ctx.modules.has(moduleId)) return ctx.modules.get(moduleId);\n\n let shape: ModuleShape | undefined;\n try {\n const code = ctx.resolver.readFile\n ? ctx.resolver.readFile(moduleId)\n : readFileSync(moduleId.replace(/[?#].*$/, ''), 'utf8');\n if (typeof code === 'string') {\n shape = shapeFromSource(code);\n }\n } catch {\n // Unreadable or not a source file — treat as \"not an Agent\" rather than failing the build.\n }\n\n ctx.modules.set(moduleId, shape);\n return shape;\n}\n"],"names":[],"mappings":";;;AAYA,MAAM,kBAAA,GAA0D;AAAA,EAC9D,MAAA,kBAAQ,IAAI,GAAA,CAAI,CAAC,OAAO,CAAC,CAAA;AAAA,EACzB,YAAA,kBAAc,IAAI,GAAA,CAAI,CAAC,UAAU,CAAC,CAAA;AAAA,EAClC,qBAAA,kBAAuB,IAAI,GAAA,CAAI,CAAC,aAAa,CAAC,CAAA;AAAA,EAC9C,mBAAA,kBAAqB,IAAI,GAAA,CAAI,CAAC,OAAO,CAAC;AACxC,CAAA;AAMA,MAAM,SAAA,GAAY,CAAA;AAqClB,eAAsB,kBAAA,CACpB,GAAA,EACA,OAAA,EACA,UAAA,EACA,QAAA,EACsB;AAGtB,EAAA,MAAM,GAAA,GAAqB,EAAE,QAAA,EAAU,OAAA,sBAAa,GAAA,CAAI,CAAC,CAAC,OAAA,EAAS,YAAA,CAAa,GAAG,CAAC,CAAC,CAAC,CAAA,EAAE;AAExF,EAAA,MAAM,QAAA,uBAAe,GAAA,EAAY;AACjC,EAAA,KAAA,MAAW,QAAQ,UAAA,EAAY;AAG7B,IAAA,IAAI,MAAM,eAAe,GAAA,EAAK,OAAA,EAAS,MAAM,CAAA,kBAAG,IAAI,GAAA,EAAK,CAAA,EAAG;AAC1D,MAAA,QAAA,CAAS,I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CAAA,EAAG,OAAO,KAAA;AAE/F,EAAA,OAAO,eAAe,GAAA,EAAK,QAAA,CAAS,IAAI,YAAA,EAAc,KAAA,GAAQ,GAAG,OAAO,CAAA;AAC1E;AAEA,eAAe,cAAA,CAAe,KAAoB,QAAA,EAAoD;AACpG,EAAA,IAAI,GAAA,CAAI,QAAQ,GAAA,CAAI,QAAQ,GAAG,OAAO,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAA;AAE9D,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,GAAA,CAAI,QAAA,CAAS,QAAA,GACtB,IAAI,QAAA,CAAS,QAAA,CAAS,QAAQ,CAAA,GAC9B,aAAa,QAAA,CAAS,OAAA,CAAQ,SAAA,EAAW,EAAE,GAAG,MAAM,CAAA;AACxD,IAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,MAAA,KAAA,GAAQ,gBAAgB,IAAI,CAAA;AAAA,IAC9B;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,EAAU,KAAK,CAAA;AAC/B,EAAA,OAAO,KAAA;AACT;;;;"}
1
+ {"version":3,"file":"agentClass.js","sources":["../../../../src/vite/agentClass.ts"],"sourcesContent":["import { readFileSync } from 'node:fs';\nimport { DEFAULT_EXPORT, type ModuleShape, shapeFromAst, shapeFromSource, type SuperRef } from './moduleShape';\nimport type { ProgramBody } from './transform';\n\n/**\n * Agent base classes, keyed by the module specifier they are imported from. A class extending any\n * of these — directly or through a chain of local/imported subclasses — is an `agents` Agent rather\n * than a plain Durable Object.\n *\n * `McpAgent`, `AIChatAgent` and `Think` all extend `Agent` themselves, but they live in packages\n * whose sources we never walk into (see {@link followImport}), so each needs its own entry.\n */\nconst AGENT_BASE_CLASSES: Record<string, ReadonlySet<string>> = {\n agents: new Set(['Agent']),\n 'agents/mcp': new Set(['McpAgent']),\n '@cloudflare/ai-chat': new Set(['AIChatAgent']),\n '@cloudflare/think': new Set(['Think']),\n};\n\n/**\n * How many modules deep the base-class chain is followed. Guards against pathological module graphs;\n * real Agent hierarchies are only a few levels deep.\n */\nconst MAX_DEPTH = 8;\n\n/**\n * The subset of the Vite/Rollup plugin context needed to walk the module graph.\n *\n * `resolve` is optional: without it detection still works, but only for base-class chains declared\n * inside the entry module itself. `readFile` is injectable for tests and defaults to reading disk.\n *\n * Deliberately **no `load`**: awaiting the plugin context's `load()` from inside a `transform` hook\n * deadlocks the build — the module cannot finish loading while its own transform is still pending\n * (Rollup documents this hazard, and Vite's Rolldown pipeline is stricter still). Sibling modules\n * are therefore read straight off disk; see {@link getModuleShape}.\n */\nexport interface ModuleResolver {\n parse(code: string): ProgramBody;\n resolve?(source: string, importer: string): Promise<{ id: string } | null | undefined>;\n readFile?(id: string): string | undefined;\n}\n\ninterface DetectContext {\n resolver: ModuleResolver;\n modules: Map<string, ModuleShape | undefined>;\n}\n\n/**\n * Find which of `candidates` (top-level class names in the entry module) are Cloudflare\n * [`agents`](https://www.npmjs.com/package/agents) Agents.\n *\n * An Agent is a Durable Object under the hood, so wrangler configures it as one and the transform\n * would otherwise reach for `instrumentDurableObjectWithSentry`. Detecting the Agent base chain lets\n * it pick `instrumentAgentWithSentry` instead, which adds the Agent-specific telemetry on top.\n *\n * Unlike `WorkerEntrypoint` detection, the chain is followed *across* modules: base classes commonly\n * live in their own file (`import { MyBase } from './base'`), and there is no runtime fallback that\n * would catch a missed one. Resolution stops at package boundaries — a base class imported from\n * `node_modules` is only recognized when it is one of {@link AGENT_BASE_CLASSES}.\n */\nexport async function detectAgentClasses(\n ast: ProgramBody,\n entryId: string,\n candidates: Iterable<string>,\n resolver: ModuleResolver,\n): Promise<Set<string>> {\n // The entry's shape comes from the AST Vite already handed us (TypeScript stripped, full\n // fidelity); only sibling modules fall back to source scanning.\n const ctx: DetectContext = { resolver, modules: new Map([[entryId, shapeFromAst(ast)]]) };\n\n const detected = new Set<string>();\n for (const name of candidates) {\n // A fresh cycle guard per candidate: a shared one would record \"not an Agent\" for bindings\n // visited while resolving an earlier candidate that turned out to be unrelated.\n if (await isAgentBinding(ctx, entryId, name, 0, new Set())) {\n detected.add(name);\n }\n }\n return detected;\n}\n\n/**\n * The entry-module binding names a configured class name could refer to — a class declared under\n * that name, an import of it from another module, a `export { X } from './x'` re-export, or the\n * local binding an `export { Local as Configured }` specifier aliases.\n *\n * Keeps detection (which reads and scans other modules) off names no binding points at.\n */\nexport function collectAgentCandidates(ast: ProgramBody, configuredNames: Iterable<string>): Set<string> {\n const shape = shapeFromAst(ast);\n const candidates = new Set<string>();\n\n const isResolvable = (name: string): boolean =>\n shape.classes.has(name) || shape.imports.has(name) || shape.reexports.has(name);\n\n for (const configured of configuredNames) {\n if (isResolvable(configured)) {\n candidates.add(configured);\n }\n const local = shape.localExports.get(configured);\n if (local && isResolvable(local)) {\n candidates.add(local);\n }\n }\n\n return candidates;\n}\n\nasync function isAgentBinding(\n ctx: DetectContext,\n moduleId: string,\n name: string,\n depth: number,\n visited: Set<string>,\n): Promise<boolean> {\n if (depth > MAX_DEPTH) return false;\n\n const key = `${moduleId} ${name}`;\n if (visited.has(key)) return false;\n visited.add(key);\n\n const shape = await getModuleShape(ctx, moduleId);\n if (!shape) return false;\n\n if (shape.classes.has(name)) {\n return extendsAgent(ctx, shape, moduleId, shape.classes.get(name), depth, visited);\n }\n\n const imported = shape.imports.get(name);\n if (imported) {\n return followImport(ctx, moduleId, imported.source, imported.imported, depth, visited);\n }\n\n if (name === DEFAULT_EXPORT) {\n if (shape.defaultExportIsClass) {\n return extendsAgent(ctx, shape, moduleId, shape.defaultExportSuper, depth, visited);\n }\n if (shape.defaultExportName) {\n return isAgentBinding(ctx, moduleId, shape.defaultExportName, depth + 1, visited);\n }\n }\n\n // `export { Local as Requested }` — the caller asked by exported name.\n const localName = shape.localExports.get(name);\n if (localName) {\n return isAgentBinding(ctx, moduleId, localName, depth + 1, visited);\n }\n\n const reexport = shape.reexports.get(name);\n if (reexport) {\n return followImport(ctx, moduleId, reexport.source, reexport.imported, depth, visited);\n }\n\n // Barrel modules (`export * from './base'`) don't name the binding, so every star source is a\n // candidate home for it.\n for (const source of shape.starExports) {\n if (await followImport(ctx, moduleId, source, name, depth, visited)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Whether a superclass reference resolves to an Agent base — a bare identifier (imported, or a\n * subclass declared in the same module) or `ns.Agent` off a namespace import.\n */\nasync function extendsAgent(\n ctx: DetectContext,\n shape: ModuleShape,\n moduleId: string,\n superClass: SuperRef | undefined,\n depth: number,\n visited: Set<string>,\n): Promise<boolean> {\n if (!superClass) return false;\n\n if (superClass.kind === 'identifier') {\n return isAgentBinding(ctx, moduleId, superClass.name, depth + 1, visited);\n }\n\n const source = shape.namespaces.get(superClass.object);\n if (source) {\n return followImport(ctx, moduleId, source, superClass.property, depth, visited);\n }\n\n return false;\n}\n\n/** Resolve an import to its module and continue the search there, stopping at package boundaries. */\nasync function followImport(\n ctx: DetectContext,\n importerId: string,\n source: string,\n importedName: string,\n depth: number,\n visited: Set<string>,\n): Promise<boolean> {\n if (AGENT_BASE_CLASSES[source]?.has(importedName)) return true;\n\n if (!ctx.resolver.resolve) return false;\n\n let resolved: { id: string } | null | undefined;\n try {\n resolved = await ctx.resolver.resolve(source, importerId);\n } catch {\n return false;\n }\n if (!resolved?.id) return false;\n\n // Third-party sources are not walked: they are large, may not be plain JS by the time we see\n // them, and any Agent base worth knowing about is listed in AGENT_BASE_CLASSES.\n if (resolved.id.includes('/node_modules/') || resolved.id.includes('\\\\node_modules\\\\')) return false;\n\n return isAgentBinding(ctx, resolved.id, importedName, depth + 1, visited);\n}\n\nasync function getModuleShape(ctx: DetectContext, moduleId: string): Promise<ModuleShape | undefined> {\n if (ctx.modules.has(moduleId)) return ctx.modules.get(moduleId);\n\n let shape: ModuleShape | undefined;\n try {\n const code = ctx.resolver.readFile\n ? ctx.resolver.readFile(moduleId)\n : readFileSync(moduleId.replace(/[?#].*$/, ''), 'utf8');\n if (typeof code === 'string') {\n shape = shapeFromSource(code);\n }\n } catch {\n // Unreadable or not a source file — treat as \"not an Agent\" rather than failing the build.\n }\n\n ctx.modules.set(moduleId, shape);\n return shape;\n}\n"],"names":[],"mappings":";;;AAYA,MAAM,kBAAA,GAA0D;AAAA,EAC9D,MAAA,kBAAQ,IAAI,GAAA,CAAI,CAAC,OAAO,CAAC,CAAA;AAAA,EACzB,YAAA,kBAAc,IAAI,GAAA,CAAI,CAAC,UAAU,CAAC,CAAA;AAAA,EAClC,qBAAA,kBAAuB,IAAI,GAAA,CAAI,CAAC,aAAa,CAAC,CAAA;AAAA,EAC9C,mBAAA,kBAAqB,IAAI,GAAA,CAAI,CAAC,OAAO,CAAC;AACxC,CAAA;AAMA,MAAM,SAAA,GAAY,CAAA;AAqClB,eAAsB,kBAAA,CACpB,GAAA,EACA,OAAA,EACA,UAAA,EACA,QAAA,EACsB;AAGtB,EAAA,MAAM,GAAA,GAAqB,EAAE,QAAA,EAAU,OAAA,sBAAa,GAAA,CAAI,CAAC,CAAC,OAAA,EAAS,YAAA,CAAa,GAAG,CAAC,CAAC,CAAC,CAAA,EAAE;AAExF,EAAA,MAAM,QAAA,uBAAe,GAAA,EAAY;AACjC,EAAA,KAAA,MAAW,QAAQ,UAAA,EAAY;AAG7B,IAAA,IAAI,MAAM,eAAe,GAAA,EAAK,OAAA,EAAS,MAAM,CAAA,kBAAG,IAAI,GAAA,EAAK,CAAA,EAAG;AAC1D,MAAA,QAAA,CAAS,IAAI,IAAI,CAAA;AAAA,IACnB;AAAA,EACF;AACA,EAAA,OAAO,QAAA;AACT;AASO,SAAS,sBAAA,CAAuB,KAAkB,eAAA,EAAgD;AACvG,EAAA,MAAM,KAAA,GAAQ,aAAa,GAAG,CAAA;AAC9B,EAAA,MAAM,UAAA,uBAAiB,GAAA,EAAY;AAEnC,EAAA,MAAM,eAAe,CAAC,IAAA,KACpB,KAAA,CAAM,OAAA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,eAAe,cAAA,CAAe,KAAoB,QAAA,EAAoD;AACpG,EAAA,IAAI,GAAA,CAAI,QAAQ,GAAA,CAAI,QAAQ,GAAG,OAAO,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,QAAQ,CAAA;AAE9D,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAM,IAAA,GAAO,GAAA,CAAI,QAAA,CAAS,QAAA,GACtB,IAAI,QAAA,CAAS,QAAA,CAAS,QAAQ,CAAA,GAC9B,aAAa,QAAA,CAAS,OAAA,CAAQ,SAAA,EAAW,EAAE,GAAG,MAAM,CAAA;AACxD,IAAA,IAAI,OAAO,SAAS,QAAA,EAAU;AAC5B,MAAA,KAAA,GAAQ,gBAAgB,IAAI,CAAA;AAAA,IAC9B;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAER;AAEA,EAAA,GAAA,CAAI,OAAA,CAAQ,GAAA,CAAI,QAAA,EAAU,KAAK,CAAA;AAC/B,EAAA,OAAO,KAAA;AACT;;;;"}
@@ -81,7 +81,7 @@ function sentryCloudflareAutoInstrumentPlugin(options = {}) {
81
81
  const missing = [...classWrappers.keys()].filter((name) => !wrappedClasses.has(name));
82
82
  if (missing.length > 0) {
83
83
  this.warn?.(
84
- `[sentry] Could not auto-instrument class(es) ${missing.join(", ")}: no matching exported class declaration found in the worker entry (re-exports from other modules cannot be wrapped automatically). Wrap them manually with the matching \`instrument*WithSentry\` helper.`
84
+ `[sentry] Could not auto-instrument ${missing.join(", ")}.The worker entry has no export matching them. Star re-exports (\`export * from "./do"\`) are not matched. Export them by name or wrap them manually with corresponding \`instrument*WithSentry\` helpers.`
85
85
  );
86
86
  }
87
87
  return result ?? void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"autoInstrument.js","sources":["../../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n\n let optionsFn = ENV_FALLBACK_OPTIONS_FN;\n let optionsImport: string | undefined;\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: { root: string; logger?: { warn(msg: string): void } }): void {\n const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);\n if (!result) {\n // An explicit path that fails is a misconfiguration worth naming;\n // without one, hint at the option so custom-named configs (e.g. a\n // `configPath` handed to @cloudflare/vite-plugin) are discoverable.\n config.logger?.warn(\n options.wranglerConfigPath\n ? `[sentry] Could not find or parse the wrangler config \"${basename(options.wranglerConfigPath)}\" ` +\n '(resolved against the Vite root) — auto-instrumentation disabled.'\n : '[sentry] No parseable wrangler config found — auto-instrumentation disabled. ' +\n 'Set `wranglerConfigPath` if your config uses a custom name.',\n );\n return;\n }\n\n wranglerConfig = result.config;\n if (wranglerConfig.main) {\n // `main` is already absolute (wrangler resolves it); just normalize\n // separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(wranglerConfig.main);\n }\n\n if (entryFilePath) {\n const instrumentFilePath = resolveInstrumentFile(entryFilePath);\n if (instrumentFilePath) {\n const built = buildOptionsImport(entryFilePath, instrumentFilePath);\n optionsFn = built.optionsFn;\n optionsImport = built.importStmt;\n }\n }\n },\n\n async transform(\n this: ModuleResolver & { warn?(msg: string): void; environment?: { name?: string } },\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || !entryFilePath) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryFilePath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryFilePath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryFilePath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only\n // its base-class chain tells the two apart. Detection walks the module graph (base classes\n // usually live in their own file), so it is limited to the configured DO classes.\n //\n // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform\n // hook deadlocks the build, since the module can't finish loading while this transform is\n // still pending. `agentClass` reads sibling modules off disk instead.\n const agentCandidates = collectAgentCandidates(\n ast,\n [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),\n );\n const agentClasses =\n agentCandidates.size > 0\n ? await detectAgentClasses(ast, normalizedId, agentCandidates, {\n parse: code => this.parse(code),\n resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined,\n })\n : undefined;\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n agentClasses,\n optionsFn,\n optionsImport,\n sameWorkerBindings: wranglerConfig.sameWorkerBindings,\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0) {\n this.warn?.(\n `[sentry] Could not auto-instrument class(es) ${missing.join(', ')}: no matching exported class ` +\n 'declaration found in the worker entry (re-exports from other modules cannot be wrapped ' +\n 'automatically). Wrap them manually with the matching `instrument*WithSentry` helper.',\n );\n }\n\n return result ?? undefined;\n },\n };\n}\n"],"names":["code"],"mappings":";;;;;;AAQA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA;AAChC;AAKA,MAAM,kBAAA,GAAqB,iBAAA;AAEpB,SAAS,oCAAA,CAAqC,OAAA,GAA2C,EAAC,EAAG;AAClG,EAAA,IAAI,cAAA;AACJ,EAAA,IAAI,aAAA;AAEJ,EAAA,IAAI,SAAA,GAAY,uBAAA;AAChB,EAAA,IAAI,aAAA;AAEJ,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,mCAAA;AAAA,IAEN,eAAe,MAAA,EAAsE;AACnF,MAAA,MAAM,MAAA,GAAS,qBAAA,CAAsB,MAAA,CAAO,IAAA,EAAM,QAAQ,kBAAkB,CAAA;AAC5E,MAAA,IAAI,CAAC,MAAA,EAAQ;AAIX,QAAA,MAAA,CAAO,MAAA,EAAQ,IAAA;AAAA,UACb,QAAQ,kBAAA,GACJ,CAAA,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A;AAAA,QACA,YAAA;AAAA,QACA,SAAA;AAAA,QACA,aAAA;AAAA,QACA,oBAAoB,cAAA,CAAe;AAAA,OACpC,CAAA;AAED,MAAA,MAAM,cAAA,GAAiB,MAAA,EAAQ,cAAA,oBAAkB,IAAI,GAAA,EAAY;AACjE,MAAA,MAAM,OAAA,GAAU,CAAC,GAAG,aAAA,CAAc,IAAA,EAAM,CAAA,CAAE,MAAA,CAAO,CAAA,IAAA,KAAQ,CAAC,cAAA,CAAe,GAAA,CAAI,IAAI,CAAC,CAAA;AAClF,MAAA,IAAI,OAAA,CAAQ,SAAS,CAAA,EAAG;AACtB,QAAA,IAAA,CAAK,IAAA;AAAA,UACH,CAAA,6CAAA,EAAgD,OAAA,CAAQ,IAAA,CAAK,IAAI,CAAC,CAAA,0MAAA;AAAA,SAGpE;AAAA,MACF;AAEA,MAAA,OAAO,MAAA,IAAU,MAAA;AAAA,IACnB;AAAA,GACF;AACF;;;;"}
1
+ {"version":3,"file":"autoInstrument.js","sources":["../../../../src/vite/autoInstrument.ts"],"sourcesContent":["import { basename } from 'node:path';\nimport { collectAgentCandidates, detectAgentClasses, type ModuleResolver } from './agentClass';\nimport { buildOptionsImport, ENV_FALLBACK_OPTIONS_FN, resolveInstrumentFile } from './instrumentFile';\nimport { applyAutoInstrumentTransforms, type ClassWrapperKind, type ProgramBody } from './transform';\nimport { resolveWranglerConfig, type WranglerConfig } from './wranglerConfig';\n\n// Vite normalizes module IDs to posix separators even on Windows, while\n// `path.resolve` yields backslashes there — normalize before comparing.\nfunction normalizePath(path: string): string {\n return path.replace(/\\\\/g, '/');\n}\n\n// Extensions the entry-module match may tolerate swapping (e.g. wrangler's\n// `main` says `.ts` but the served module is `.js`). Anything else — `.css`,\n// `.html`, … — sharing the entry's basename must never be treated as the entry.\nconst JS_EXTENSION_REGEX = /\\.[cm]?[jt]sx?$/;\n\nexport function sentryCloudflareAutoInstrumentPlugin(options: { wranglerConfigPath?: string } = {}) {\n let wranglerConfig: WranglerConfig | undefined;\n let entryFilePath: string | undefined;\n\n let optionsFn = ENV_FALLBACK_OPTIONS_FN;\n let optionsImport: string | undefined;\n\n return {\n name: 'sentry-cloudflare-auto-instrument',\n\n configResolved(config: { root: string; logger?: { warn(msg: string): void } }): void {\n const result = resolveWranglerConfig(config.root, options.wranglerConfigPath);\n if (!result) {\n // An explicit path that fails is a misconfiguration worth naming;\n // without one, hint at the option so custom-named configs (e.g. a\n // `configPath` handed to @cloudflare/vite-plugin) are discoverable.\n config.logger?.warn(\n options.wranglerConfigPath\n ? `[sentry] Could not find or parse the wrangler config \"${basename(options.wranglerConfigPath)}\" ` +\n '(resolved against the Vite root) — auto-instrumentation disabled.'\n : '[sentry] No parseable wrangler config found — auto-instrumentation disabled. ' +\n 'Set `wranglerConfigPath` if your config uses a custom name.',\n );\n return;\n }\n\n wranglerConfig = result.config;\n if (wranglerConfig.main) {\n // `main` is already absolute (wrangler resolves it); just normalize\n // separators so the entry-module comparison holds on Windows.\n entryFilePath = normalizePath(wranglerConfig.main);\n }\n\n if (entryFilePath) {\n const instrumentFilePath = resolveInstrumentFile(entryFilePath);\n if (instrumentFilePath) {\n const built = buildOptionsImport(entryFilePath, instrumentFilePath);\n optionsFn = built.optionsFn;\n optionsImport = built.importStmt;\n }\n }\n },\n\n async transform(\n this: ModuleResolver & { warn?(msg: string): void; environment?: { name?: string } },\n code: string,\n id: string,\n ): Promise<{ code: string; map: unknown } | undefined> {\n if (!wranglerConfig || !entryFilePath) return undefined;\n\n // The worker entry never belongs to the client (browser) environment.\n // Skipping it keeps a same-basename sibling (e.g. a `src/index.tsx`\n // client entry next to a `src/index.ts` worker) out of the browser bundle.\n if (this.environment?.name === 'client') return undefined;\n\n // Vite may append query/hash params to the module ID.\n const normalizedId = normalizePath(id.replace(/[?#].*$/, ''));\n if (normalizedId !== entryFilePath) {\n // Tolerate a differing JS-flavored extension (e.g. `.js` vs `.ts`).\n if (!JS_EXTENSION_REGEX.test(normalizedId) || !JS_EXTENSION_REGEX.test(entryFilePath)) return undefined;\n if (normalizedId.replace(JS_EXTENSION_REGEX, '') !== entryFilePath.replace(JS_EXTENSION_REGEX, '')) {\n return undefined;\n }\n }\n\n let ast: ProgramBody;\n try {\n ast = this.parse(code);\n } catch {\n // Raw TypeScript or syntax error — esbuild hasn't run yet (unlikely)\n // or the file is genuinely broken. Either way, skip silently.\n return undefined;\n }\n\n const classWrappers = new Map<string, ClassWrapperKind>();\n for (const { className } of wranglerConfig.durableObjects) {\n classWrappers.set(className, 'durableObject');\n }\n for (const { className } of wranglerConfig.workflows) {\n classWrappers.set(className, 'workflow');\n }\n for (const className of wranglerConfig.workerEntrypoints) {\n classWrappers.set(className, 'workerEntrypoint');\n }\n\n // An `agents` Agent is a Durable Object, so wrangler lists it among the DO bindings and only\n // its base-class chain tells the two apart. Detection walks the module graph (base classes\n // usually live in their own file), so it is limited to the configured DO classes.\n //\n // Only `resolve` is handed over — never `load`: awaiting `load()` from inside a transform\n // hook deadlocks the build, since the module can't finish loading while this transform is\n // still pending. `agentClass` reads sibling modules off disk instead.\n const agentCandidates = collectAgentCandidates(\n ast,\n [...classWrappers].filter(([, kind]) => kind === 'durableObject').map(([name]) => name),\n );\n const agentClasses =\n agentCandidates.size > 0\n ? await detectAgentClasses(ast, normalizedId, agentCandidates, {\n parse: code => this.parse(code),\n resolve: this.resolve ? (source, importer) => this.resolve!(source, importer) : undefined,\n })\n : undefined;\n\n // No registration import is injected here: the orchestrion plugin's\n // subscribe-injection makes each bundled package self-register its channel\n // subscriber on the global marker, so wrapping the entry with `withSentry`\n // is all this plugin needs to do.\n const result = applyAutoInstrumentTransforms(code, ast, {\n classWrappers,\n agentClasses,\n optionsFn,\n optionsImport,\n sameWorkerBindings: wranglerConfig.sameWorkerBindings,\n });\n\n const wrappedClasses = result?.wrappedClasses ?? new Set<string>();\n const missing = [...classWrappers.keys()].filter(name => !wrappedClasses.has(name));\n if (missing.length > 0) {\n this.warn?.(\n `[sentry] Could not auto-instrument ${missing.join(', ')}.` +\n 'The worker entry has no export matching them. ' +\n 'Star re-exports (`export * from \"./do\"`) are not matched. ' +\n 'Export them by name or wrap them manually with corresponding `instrument*WithSentry` helpers.',\n );\n }\n\n return result ?? undefined;\n },\n };\n}\n"],"names":["code"],"mappings":";;;;;;AAQA,SAAS,cAAc,IAAA,EAAsB;AAC3C,EAAA,OAAO,IAAA,CAAK,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA;AAChC;AAKA,MAAM,kBAAA,GAAqB,iBAAA;AAEpB,SAAS,oCAAA,CAAqC,OAAA,GAA2C,EAAC,EAAG;AAClG,EAAA,IAAI,cAAA;AACJ,EAAA,IAAI,aAAA;AAEJ,EAAA,IAAI,SAAA,GAAY,uBAAA;AAChB,EAAA,IAAI,aAAA;AAEJ,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,mCAAA;AAAA,IAEN,eAAe,MAAA,EAAsE;AACnF,MAAA,MAAM,MAAA,GAAS,qBAAA,CAAsB,MAAA,CAAO,IAAA,EAAM,QAAQ,kBAAkB,CAAA;AAC5E,MAAA,IAAI,CAAC,MAAA,EAAQ;AAIX,QAAA,MAAA,CAAO,MAAA,EAAQ,IAAA;AAAA,UACb,QAAQ,kBAAA,GACJ,CAAA,sDAAA,EAAyD,SAAS,OAAA,CAAQ,kBAAkB,CAAC,CAAA,wEAAA,CAAA,GAE7F;AAAA,SAEN;AACA,QAAA;AAAA,MACF;AAEA,MAAA,cAAA,GAAiB,MAAA,CAAO,MAAA;AACxB,MAAA,IAAI,eAAe,IAAA,EAAM;AAGvB,QAAA,aAAA,GAAgB,aAAA,CAAc,eAAe,IAAI,CAAA;AAAA,MACnD;AAEA,MAAA,IAAI,aAAA,EAAe;AACjB,QAAA,MAAM,kBAAA,GAAqB,sBAAsB,aAAa,CAAA;AAC9D,QAAA,IAAI,kBAAA,EAAoB;AACtB,UAAA,MAAM,KAAA,GAAQ,kBAAA,CAAmB,aAAA,EAAe,kBAAkB,CAAA;AAClE,UAAA,SAAA,GAAY,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K,IAAI,CAAC,CAAA,0MAAA;AAAA,SAI1D;AAAA,MACF;AAEA,MAAA,OAAO,MAAA,IAAU,MAAA;AAAA,IACnB;AAAA,GACF;AACF;;;;"}
@@ -10,6 +10,7 @@ function isCallToMethod(node, methodName) {
10
10
  if (callee.type === "Identifier" && callee.name === methodName) return true;
11
11
  return callee.type === "MemberExpression" && callee.property?.type === "Identifier" && callee.property.name === methodName;
12
12
  }
13
+ const DEFAULT_IMPORT = "default";
13
14
  const WRAPPER_METHODS = {
14
15
  durableObject: "instrumentDurableObjectWithSentry",
15
16
  agent: "instrumentAgentWithSentry",
@@ -31,7 +32,8 @@ function applyAutoInstrumentTransforms(code, ast, ctx) {
31
32
  workerEntrypointClasses: detectWorkerEntrypointClasses(ast),
32
33
  // The identifier must be chosen before wrapping, which bindings survive is only known after.
33
34
  optionsFn: sameWorkerBindings.length > 0 ? MERGED_OPTIONS_IDENTIFIER : ctx.optionsFn,
34
- autoWrapped: /* @__PURE__ */ new Set()
35
+ autoWrapped: /* @__PURE__ */ new Set(),
36
+ manuallyWrappedLocals: collectManuallyWrappedLocals(ast)
35
37
  };
36
38
  const { wrappedClasses } = state;
37
39
  for (const node of ast.body) {
@@ -71,11 +73,28 @@ function buildMergedOptionsDeclaration(sameWorkerBindings, optionsFn, state) {
71
73
  }
72
74
  function resolveWrapperKind(exportedName, localName, state) {
73
75
  const configured = state.classWrappers.get(exportedName);
74
- if (configured === "durableObject" && localName && state.agentClasses.has(localName)) return "agent";
76
+ if (configured === "durableObject" && (localName && state.agentClasses.has(localName) || state.agentClasses.has(exportedName))) {
77
+ return "agent";
78
+ }
75
79
  if (configured) return configured;
76
80
  if (localName && state.workerEntrypointClasses.has(localName)) return "workerEntrypoint";
77
81
  return void 0;
78
82
  }
83
+ function collectManuallyWrappedLocals(ast) {
84
+ const wrapperMethods = Object.values(WRAPPER_METHODS);
85
+ const locals = /* @__PURE__ */ new Set();
86
+ for (const node of ast.body) {
87
+ if (node.type !== "VariableDeclaration") continue;
88
+ for (const declarator of node.declarations ?? []) {
89
+ const name = declarator.id?.type === "Identifier" ? declarator.id.name : void 0;
90
+ const init = declarator.init;
91
+ if (name && init && wrapperMethods.some((method) => isCallToMethod(init, method))) {
92
+ locals.add(name);
93
+ }
94
+ }
95
+ }
96
+ return locals;
97
+ }
79
98
  function collectTopLevelClasses(ast) {
80
99
  const classes = /* @__PURE__ */ new Map();
81
100
  for (const node of ast.body) {
@@ -109,10 +128,7 @@ function handleNamedExport(node, ctx, state) {
109
128
  wrapInlineClassExport(node, decl, ctx, state);
110
129
  return;
111
130
  }
112
- if (node.source) return;
113
- for (const specifier of node.specifiers ?? []) {
114
- wrapSpecifierExport(specifier, ctx, state);
115
- }
131
+ wrapSpecifierExports(node, ctx, state);
116
132
  }
117
133
  function collectManuallyWrappedClassExports(varDecl, ctx, state) {
118
134
  for (const declarator of varDecl.declarations ?? []) {
@@ -144,22 +160,69 @@ export const ${className} = __SENTRY__.${WRAPPER_METHODS[kind]}(${state.optionsF
144
160
  state.renamedLocals.add(className);
145
161
  state.needsImport = true;
146
162
  }
147
- function wrapSpecifierExport(specifier, ctx, state) {
148
- if (specifier.type !== "ExportSpecifier" || specifier.exported?.type !== "Identifier") return;
149
- const exportedName = specifier.exported.name;
150
- if (!exportedName) return;
163
+ function wrapSpecifierExports(node, ctx, state) {
164
+ const specifiers = node.specifiers ?? [];
165
+ if (specifiers.length === 0) return;
166
+ const sourceLiteral = node.source ? state.ms.original.slice(node.source.start, node.source.end) : void 0;
167
+ const prelude = [];
168
+ const wrappedPairs = [];
169
+ const kept = [];
170
+ for (const specifier of specifiers) {
171
+ const pair = wrapCrossModuleSpecifier(specifier, sourceLiteral, ctx, state, prelude);
172
+ if (pair) {
173
+ wrappedPairs.push(pair);
174
+ } else {
175
+ kept.push(state.ms.original.slice(specifier.start, specifier.end));
176
+ }
177
+ }
178
+ if (wrappedPairs.length === 0) return;
179
+ const statements = [...prelude, `export { ${wrappedPairs.join(", ")} };`];
180
+ if (kept.length > 0) {
181
+ const clause = `export { ${kept.join(", ")} }`;
182
+ statements.push(sourceLiteral ? `${clause} from ${sourceLiteral};` : `${clause};`);
183
+ }
184
+ state.ms.overwrite(node.start, node.end, statements.join("\n"));
185
+ }
186
+ function wrapCrossModuleSpecifier(specifier, sourceLiteral, ctx, state, prelude) {
187
+ const exportedName = specifier.type === "ExportSpecifier" && specifier.exported?.type === "Identifier" ? specifier.exported.name : void 0;
151
188
  const localName = specifier.local?.type === "Identifier" ? specifier.local.name : void 0;
152
- const kind = resolveWrapperKind(exportedName, localName, state);
153
- if (!kind) return;
154
- const localClass = localName ? state.topLevelClasses.get(localName) : void 0;
155
- if (!localName || !localClass?.id) return;
189
+ const kind = exportedName ? resolveWrapperKind(exportedName, sourceLiteral ? void 0 : localName, state) : void 0;
190
+ if (!exportedName || !localName || !kind) return void 0;
191
+ if (!sourceLiteral) {
192
+ const localClass = state.topLevelClasses.get(localName);
193
+ if (localClass?.id) {
194
+ wrapLocalClassExport(localName, localClass, kind, ctx, state);
195
+ state.wrappedClasses.add(exportedName);
196
+ state.needsImport = true;
197
+ return void 0;
198
+ }
199
+ if (state.manuallyWrappedLocals.has(localName)) {
200
+ state.wrappedClasses.add(exportedName);
201
+ return void 0;
202
+ }
203
+ }
204
+ let target = localName;
205
+ if (sourceLiteral) {
206
+ target = `__SENTRY_REEXPORT_${exportedName}__`;
207
+ prelude.push(
208
+ localName === DEFAULT_IMPORT ? `import ${target} from ${sourceLiteral};` : `import { ${localName} as ${target} } from ${sourceLiteral};`
209
+ );
210
+ }
211
+ const wrappedName = `__SENTRY_WRAPPED_${exportedName}__`;
212
+ prelude.push(
213
+ `const ${wrappedName} = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.${WRAPPER_METHODS[kind]}, ${state.optionsFn}, ${target});`
214
+ );
156
215
  state.wrappedClasses.add(exportedName);
157
216
  state.autoWrapped.add(exportedName);
158
217
  state.needsImport = true;
159
- if (state.renamedLocals.has(localName)) return;
218
+ return `${wrappedName} as ${exportedName}`;
219
+ }
220
+ function wrapLocalClassExport(localName, localClass, kind, ctx, state) {
221
+ const classId = localClass.id;
222
+ if (!classId || state.renamedLocals.has(localName)) return;
160
223
  state.renamedLocals.add(localName);
161
224
  const renamedClass = `__SENTRY_ORIGINAL_${localName}__`;
162
- state.ms.overwrite(localClass.id.start, localClass.id.end, renamedClass);
225
+ state.ms.overwrite(classId.start, classId.end, renamedClass);
163
226
  state.ms.appendLeft(
164
227
  localClass.end,
165
228
  `