autotel-edge 3.17.1 → 3.17.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.
package/LICENSE CHANGED
@@ -1,21 +1,191 @@
1
- MIT License
2
-
3
- Copyright (c) Jag Reehal 2025
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the
13
+ copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other
16
+ entities that control, are controlled by, or are under common control with
17
+ that entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of such
19
+ entity, whether by contract or otherwise, or (ii) ownership of fifty
20
+ percent (50%) or more of the outstanding shares, or (iii) beneficial
21
+ ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation source,
28
+ and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical transformation
31
+ or translation of a Source form, including but not limited to compiled
32
+ object code, generated documentation, and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or Object form,
35
+ made available under the License, as indicated by a copyright notice that
36
+ is included in or attached to the work (an example is provided in the
37
+ Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object form,
40
+ that is based on (or derived from) the Work and for which the editorial
41
+ revisions, annotations, elaborations, or other modifications represent, as
42
+ a whole, an original work of authorship. For the purposes of this License,
43
+ Derivative Works shall not include works that remain separable from, or
44
+ merely link (or bind by name) to the interfaces of, the Work and Derivative
45
+ Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including the original
48
+ version of the Work and any modifications or additions to that Work or
49
+ Derivative Works thereof, that is intentionally submitted to Licensor for
50
+ inclusion in the Work by the copyright owner or by an individual or Legal
51
+ Entity authorized to submit on behalf of the copyright owner. For the
52
+ purposes of this definition, "submitted" means any form of electronic,
53
+ verbal, or written communication sent to the Licensor or its
54
+ representatives, including but not limited to communication on electronic
55
+ mailing lists, source code control systems, and issue tracking systems that
56
+ are managed by, or on behalf of, the Licensor for the purpose of discussing
57
+ and improving the Work, but excluding communication that is conspicuously
58
+ marked or otherwise designated in writing by the copyright owner as "Not a
59
+ Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity on
62
+ behalf of whom a Contribution has been received by Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
66
+ License, each Contributor hereby grants to You a perpetual, worldwide,
67
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
68
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
69
+ sublicense, and distribute the Work and such Derivative Works in Source or
70
+ Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of this
73
+ License, each Contributor hereby grants to You a perpetual, worldwide,
74
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in
75
+ this section) patent license to make, have made, use, offer to sell, sell,
76
+ import, and otherwise transfer the Work, where such license applies only to
77
+ those patent claims licensable by such Contributor that are necessarily
78
+ infringed by their Contribution(s) alone or by combination of their
79
+ Contribution(s) with the Work to which such Contribution(s) was submitted.
80
+ If You institute patent litigation against any entity (including a
81
+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a
82
+ Contribution incorporated within the Work constitutes direct or
83
+ contributory patent infringement, then any patent licenses granted to You
84
+ under this License for that Work shall terminate as of the date such
85
+ litigation is filed.
86
+
87
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
88
+ Derivative Works thereof in any medium, with or without modifications, and
89
+ in Source or Object form, provided that You meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative Works
92
+ a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works that
98
+ You distribute, all copyright, patent, trademark, and attribution notices
99
+ from the Source form of the Work, excluding those notices that do not
100
+ pertain to any part of the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, then any Derivative Works that You distribute must include a
104
+ readable copy of the attribution notices contained within such NOTICE file,
105
+ excluding those notices that do not pertain to any part of the Derivative
106
+ Works, in at least one of the following places: within a NOTICE text file
107
+ distributed as part of the Derivative Works; within the Source form or
108
+ documentation, if provided along with the Derivative Works; or, within a
109
+ display generated by the Derivative Works, if and wherever such third-party
110
+ notices normally appear. The contents of the NOTICE file are for
111
+ informational purposes only and do not modify the License. You may add Your
112
+ own attribution notices within Derivative Works that You distribute,
113
+ alongside or as an addendum to the NOTICE text from the Work, provided that
114
+ such additional attribution notices cannot be construed as modifying the
115
+ License.
116
+
117
+ You may add Your own copyright statement to Your modifications and may
118
+ provide additional or different license terms and conditions for use,
119
+ reproduction, or distribution of Your modifications, or for any such
120
+ Derivative Works as a whole, provided Your use, reproduction, and
121
+ distribution of the Work otherwise complies with the conditions stated in
122
+ this License.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
125
+ Contribution intentionally submitted for inclusion in the Work by You to
126
+ the Licensor shall be under the terms and conditions of this License,
127
+ without any additional terms or conditions. Notwithstanding the above,
128
+ nothing herein shall supersede or modify the terms of any separate license
129
+ agreement you may have executed with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor, except
133
+ as required for reasonable and customary use in describing the origin of
134
+ the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to
137
+ in writing, Licensor provides the Work (and each Contributor provides its
138
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
139
+ KIND, either express or implied, including, without limitation, any
140
+ warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or
141
+ FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for
142
+ determining the appropriateness of using or redistributing the Work and
143
+ assume any risks associated with Your exercise of permissions under this
144
+ License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory, whether
147
+ in tort (including negligence), contract, or otherwise, unless required by
148
+ applicable law (such as deliberate and grossly negligent acts) or agreed to
149
+ in writing, shall any Contributor be liable to You for damages, including
150
+ any direct, indirect, special, incidental, or consequential damages of any
151
+ character arising as a result of this License or out of the use or
152
+ inability to use the Work (including but not limited to damages for loss of
153
+ goodwill, work stoppage, computer failure or malfunction, or any and all
154
+ other commercial damages or losses), even if such Contributor has been
155
+ advised of the possibility of such damages.
156
+
157
+ 9. Accepting Warranty or Additional Liability. While redistributing the
158
+ Work or Derivative Works thereof, You may choose to offer, and charge a fee
159
+ for, acceptance of support, warranty, indemnity, or other liability
160
+ obligations and/or rights consistent with this License. However, in
161
+ accepting such obligations, You may act only on Your own behalf and on Your
162
+ sole responsibility, not on behalf of any other Contributor, and only if
163
+ You agree to indemnify, defend, and hold each Contributor harmless for any
164
+ liability incurred by, or claims asserted against, such Contributor by
165
+ reason of your accepting any such warranty or additional liability.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ APPENDIX: How to apply the Apache License to your work.
170
+
171
+ To apply the Apache License to your work, attach the following boilerplate
172
+ notice, with the fields enclosed by brackets "[]" replaced with your own
173
+ identifying information. (Don't include the brackets!) The text should be
174
+ enclosed in the appropriate comment syntax for the file format. We also
175
+ recommend that a file or class name and description of purpose be included
176
+ on the same "printed page" as the copyright notice for easier
177
+ identification within third-party archives.
178
+
179
+ Copyright [yyyy] [name of copyright owner]
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  [![npm version](https://badge.fury.io/js/autotel-edge.svg)](https://www.npmjs.com/package/autotel-edge)
6
6
  [![Bundle Size](https://img.shields.io/bundlephobia/minzip/autotel-edge)](https://bundlephobia.com/package/autotel-edge)
7
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ [![License: Apache 2.0](https://img.shields.io/badge/License-Apache_2.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
8
8
 
9
9
  ## Overview
10
10
 
@@ -368,7 +368,7 @@ trace waterfall in production and export over OTLP locally. Config:
368
368
 
369
369
  ## License
370
370
 
371
- MIT © [Jag Reehal](https://github.com/jagreehal)
371
+ Apache-2.0 © [Jag Reehal](https://github.com/jagreehal)
372
372
 
373
373
  ## Links
374
374
 
@@ -8,7 +8,7 @@ import { JsonTraceSerializer } from "@opentelemetry/otlp-transformer";
8
8
  const defaultHeaders = {
9
9
  accept: "application/json",
10
10
  "content-type": "application/json",
11
- "user-agent": `autotel-edge v3.17.1`
11
+ "user-agent": `autotel-edge v3.17.2`
12
12
  };
13
13
  /**
14
14
  * Minimal OTLP exporter using fetch()
@@ -288,4 +288,4 @@ function createInitialiser(config) {
288
288
 
289
289
  //#endregion
290
290
  export { OTLPExporter as a, setConfig as i, getActiveConfig as n, parseConfig as r, createInitialiser as t };
291
- //# sourceMappingURL=config-8ZqmWTBJ.js.map
291
+ //# sourceMappingURL=config-CFlfvmQ1.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"config-8ZqmWTBJ.js","names":["api_context"],"sources":["../src/core/exporter.ts","../src/types.ts","../src/core/spanprocessor.ts","../src/core/config.ts"],"sourcesContent":["/**\n * Lightweight OTLP exporter for edge environments\n * Ported and adapted from @microlabs/\n *\n * This exporter is much smaller than the standard @opentelemetry/exporter-trace-otlp-http\n * because it uses fetch() directly instead of Node.js http/https modules.\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport { OTLPExporterError } from '@opentelemetry/otlp-exporter-base';\nimport { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport type { OTLPExporterConfig } from '../types';\n\n// Version is injected at build time via tsup define\n// This avoids runtime filesystem access which isn't available in edge environments\nconst PACKAGE_VERSION = process.env.AUTOTEL_EDGE_VERSION || '0.1.1';\n\nconst defaultHeaders: Record<string, string> = {\n accept: 'application/json',\n 'content-type': 'application/json',\n 'user-agent': `autotel-edge v${PACKAGE_VERSION}`,\n};\n\n/**\n * Minimal OTLP exporter using fetch()\n */\nexport class OTLPExporter implements SpanExporter {\n private headers: Record<string, string>;\n private url: string;\n\n constructor(config: OTLPExporterConfig) {\n this.url = config.url;\n this.headers = Object.assign({}, defaultHeaders, config.headers);\n }\n\n export(items: any[], resultCallback: (result: ExportResult) => void): void {\n this._export(items)\n .then(() => {\n resultCallback({ code: ExportResultCode.SUCCESS });\n })\n .catch((error) => {\n resultCallback({ code: ExportResultCode.FAILED, error });\n });\n }\n\n private _export(items: any[]): Promise<unknown> {\n return new Promise<void>((resolve, reject) => {\n try {\n this.send(items, resolve, reject);\n } catch (error) {\n reject(error);\n }\n });\n }\n\n send(\n items: any[],\n onSuccess: () => void,\n onError: (error: OTLPExporterError) => void,\n ): void {\n const decoder = new TextDecoder();\n const exportMessage = JsonTraceSerializer.serializeRequest(items);\n\n const body = decoder.decode(exportMessage);\n const params: RequestInit = {\n method: 'POST',\n headers: this.headers,\n body,\n };\n\n fetch(this.url, params)\n .then((response) => {\n if (response.ok) {\n onSuccess();\n } else {\n onError(\n new OTLPExporterError(\n `Exporter received a statusCode: ${response.status}`,\n ),\n );\n }\n })\n .catch((error) => {\n onError(\n new OTLPExporterError(\n `Exception during export: ${error.toString()}`,\n error.code,\n error.stack,\n ),\n );\n });\n }\n\n async shutdown(): Promise<void> {\n // No-op for edge environments\n }\n}\n","/**\n * Shared types for autotel-edge\n */\n\nimport type {\n Attributes,\n Context,\n Span,\n SpanOptions,\n TextMapPropagator,\n} from '@opentelemetry/api';\nimport type {\n ReadableSpan,\n Sampler,\n SpanExporter,\n SpanProcessor,\n} from '@opentelemetry/sdk-trace-base';\n\n// Re-export commonly used types\n\n\n/**\n * Extended SpanOptions with per-span sampler support\n */\nexport interface ExtendedSpanOptions extends SpanOptions {\n sampler?: Sampler;\n}\n\n/**\n * Trigger types for edge handlers\n * Can be a Request or any vendor-specific trigger type\n */\nexport type Trigger =\n | Request\n | DOConstructorTrigger\n | WorkflowTrigger\n | 'do-alarm'\n | unknown;\n\nexport interface DOConstructorTrigger {\n id: string;\n name?: string;\n}\n\nexport interface WorkflowTrigger {\n type: 'workflow';\n name: string;\n}\n\n/**\n * Config types\n */\nexport interface OTLPExporterConfig {\n url: string;\n headers?: Record<string, string>;\n}\n\nexport type ExporterConfig = OTLPExporterConfig | SpanExporter;\n\nexport interface ServiceConfig {\n name: string;\n namespace?: string;\n version?: string;\n}\n\nexport interface ParentRatioSamplingConfig {\n acceptRemote?: boolean;\n ratio: number;\n}\n\ntype HeadSamplerConf = Sampler | ParentRatioSamplingConfig;\n\nexport interface SamplingConfig<HS extends HeadSamplerConf = HeadSamplerConf> {\n headSampler?: HS;\n tailSampler?: TailSampleFn;\n}\n\nexport interface InstrumentationOptions {\n instrumentGlobalFetch?: boolean;\n instrumentGlobalCache?: boolean;\n /**\n * Disable instrumentation entirely (useful for local development)\n * When enabled, the handler is returned as-is without any instrumentation\n * @default false\n */\n disabled?: boolean;\n}\n\n/**\n * Utility types\n */\nexport type OrPromise<T> = T | Promise<T>;\n\n/**\n * Adapter event types\n */\nexport type FunnelStepStatus =\n | 'started'\n | 'completed'\n | 'abandoned'\n | 'failed'\n | (string & {});\n\nexport type OutcomeStatus =\n | 'success'\n | 'failure'\n | 'partial'\n | (string & {});\n\nexport interface EdgeEventBase {\n [key: string]: unknown;\n service: string;\n timestamp: number;\n attributes: Record<string, unknown>;\n traceId?: string;\n spanId?: string;\n correlationId?: string;\n name: string; // Normalized event name for easy access\n}\n\nexport interface EdgeTrackEvent extends EdgeEventBase {\n type: 'event';\n event: string;\n}\n\nexport interface EdgeFunnelStepEvent extends EdgeEventBase {\n type: 'funnel-step';\n funnel: string;\n status: FunnelStepStatus;\n}\n\nexport interface EdgeOutcomeEvent extends EdgeEventBase {\n type: 'outcome';\n operation: string;\n outcome: OutcomeStatus;\n}\n\nexport interface EdgeValueEvent extends EdgeEventBase {\n type: 'value';\n metric: string;\n value: number;\n}\n\nexport type EdgeEvent =\n | EdgeTrackEvent\n | EdgeFunnelStepEvent\n | EdgeOutcomeEvent\n | EdgeValueEvent;\n\nexport type EdgeSubscriber = (event: EdgeEvent) => OrPromise<void>;\n\nexport interface FetcherConfig {\n includeTraceContext?: boolean | ((request: Request) => boolean);\n}\n\nexport interface RouteServiceConfig {\n service: string;\n}\n\nexport interface PostProcessParams {\n /**\n * The request object that was passed to the fetch handler.\n */\n request: Request;\n /**\n * The generated response object.\n */\n response: Response;\n /**\n * A readable version of the span object that can be used to access the span's attributes and events.\n */\n readable: ReadableSpan;\n}\n\nexport interface FetchHandlerConfig {\n /**\n * Whether to enable context propagation for incoming requests to `fetch`.\n * This enables or disables distributed tracing from W3C Trace Context headers.\n * @default true\n */\n acceptTraceContext?: boolean | ((request: Request) => boolean);\n /**\n * Allows further customization of the generated span, based on the request/response data.\n */\n postProcess?: (span: Span, ctx: PostProcessParams) => void;\n /**\n * Route patterns to include for fetch handler instrumentation.\n * Supports glob patterns like '/api/**'.\n * If not set, all routes are included.\n */\n include?: string[];\n /**\n * Route patterns to exclude from fetch handler instrumentation.\n * Supports glob patterns like '/health' and '/_internal/**'.\n * Exclusions take precedence over inclusions.\n */\n exclude?: string[];\n /**\n * Route-specific service mapping.\n * The first matching pattern wins based on object iteration order.\n */\n routes?: Record<string, RouteServiceConfig>;\n}\n\nexport interface HandlerConfig {\n fetch?: FetchHandlerConfig;\n}\n\nexport interface DataSafetyConfig {\n /** Redact query parameters from URL attributes (default: false) */\n redactQueryParams?: boolean;\n /** Control D1 SQL statement capture: 'full' (default), 'obfuscated', or 'off' */\n captureDbStatement?: 'off' | 'obfuscated' | 'full';\n /** Only capture these email headers (lowercase). When set, other headers are excluded. */\n emailHeaderAllowlist?: string[];\n}\n\n/**\n * Controls whether `span()` / `trace()` route to a platform-native tracer\n * (e.g. Cloudflare's `tracing.enterSpan()`) instead of autotel's own OTLP\n * pipeline.\n *\n * - `'auto'` (default): use the native tracer when one is detected at runtime,\n * otherwise fall back to autotel's OTLP exporter.\n * - `'on'`: always prefer the native tracer (the adapter warns once if none is\n * available and falls back).\n * - `'off'`: never use a native tracer — always use autotel's OTLP pipeline.\n * Useful for local `wrangler dev` streaming to autotel-devtools.\n */\nexport type NativeTracingMode = 'auto' | 'on' | 'off';\n\ninterface EdgeConfigBase {\n service: ServiceConfig;\n handlers?: HandlerConfig;\n fetch?: FetcherConfig;\n postProcessor?: PostProcessorFn;\n sampling?: SamplingConfig;\n propagator?: TextMapPropagator;\n instrumentation?: InstrumentationOptions;\n subscribers?: EdgeSubscriber[];\n /** Opt-in data safety controls for sensitive attribute capture */\n dataSafety?: DataSafetyConfig;\n /**\n * Native platform tracing mode. Defaults to `'auto'`.\n * @see NativeTracingMode\n */\n nativeTracing?: NativeTracingMode;\n}\n\ninterface EdgeConfigExporter extends EdgeConfigBase {\n exporter: ExporterConfig;\n}\n\ninterface EdgeConfigSpanProcessors extends EdgeConfigBase {\n spanProcessors: SpanProcessor | SpanProcessor[];\n}\n\nexport type EdgeConfig = EdgeConfigExporter | EdgeConfigSpanProcessors;\n\nexport function isSpanProcessorConfig(\n config: EdgeConfig,\n): config is EdgeConfigSpanProcessors {\n return !!(config as EdgeConfigSpanProcessors).spanProcessors;\n}\n\nexport interface ResolvedEdgeConfig extends EdgeConfigBase {\n handlers: Required<HandlerConfig>;\n fetch: Required<FetcherConfig>;\n postProcessor: PostProcessorFn;\n sampling: Required<SamplingConfig<Sampler>>;\n spanProcessors: SpanProcessor[];\n propagator: TextMapPropagator;\n instrumentation: InstrumentationOptions;\n subscribers: EdgeSubscriber[];\n nativeTracing: NativeTracingMode;\n}\n\n/**\n * Function types\n */\nexport type ResolveConfigFn<Env = any> = (\n env: Env,\n trigger: Trigger,\n) => EdgeConfig;\nexport type ConfigurationOption = EdgeConfig | ResolveConfigFn;\n\nexport type PostProcessorFn = (spans: ReadableSpan[]) => ReadableSpan[];\nexport type TailSampleFn = (traceInfo: LocalTrace) => boolean;\n\nexport interface LocalTrace {\n traceId: string;\n spans: ReadableSpan[];\n localRootSpan: ReadableSpan;\n}\n\n/**\n * Span processor with flush support\n */\nexport type TraceFlushableSpanProcessor = SpanProcessor & {\n forceFlush: (traceId?: string) => Promise<void>;\n};\n\n/**\n * Handler instrumentation\n */\nexport interface InitialSpanInfo {\n name: string;\n options: SpanOptions;\n context?: Context;\n}\n\nexport interface HandlerInstrumentation<T extends Trigger, R extends any> {\n getInitialSpanInfo: (trigger: T) => InitialSpanInfo;\n getAttributesFromResult?: (result: Awaited<R>) => Attributes;\n instrumentTrigger?: (trigger: T) => T;\n executionSucces?: (span: Span, trigger: T, result: Awaited<R>) => void;\n executionFailed?: (span: Span, trigger: T, error?: any) => void;\n}\n\n/**\n * Utility types\n */\n\nexport {type Attributes, type Context, type Span, type SpanOptions} from '@opentelemetry/api';\nexport {type ReadableSpan} from '@opentelemetry/sdk-trace-base';\n","/**\n * Span processor with flush and tail sampling support\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type {\n ReadableSpan,\n Span,\n SpanExporter,\n SpanProcessor,\n} from '@opentelemetry/sdk-trace-base';\nimport type { PostProcessorFn, TailSampleFn, LocalTrace } from '../types';\n\n/**\n * Span processor that supports flush by trace ID and tail sampling\n */\nexport class SpanProcessorWithFlush implements SpanProcessor {\n private exporter: SpanExporter;\n private postProcessor?: PostProcessorFn;\n private spans: Map<string, ReadableSpan[]> = new Map();\n\n constructor(exporter: SpanExporter, postProcessor?: PostProcessorFn) {\n this.exporter = exporter;\n this.postProcessor = postProcessor;\n }\n\n onStart(_span: Span, _parentContext: Context): void {\n // No-op for now\n }\n\n onEnd(span: ReadableSpan): void {\n const traceId = span.spanContext().traceId;\n\n if (!this.spans.has(traceId)) {\n this.spans.set(traceId, []);\n }\n\n this.spans.get(traceId)!.push(span);\n }\n\n /**\n * Force flush spans for a specific trace\n */\n async forceFlush(traceId?: string): Promise<void> {\n if (traceId) {\n const spans = this.spans.get(traceId);\n if (spans && spans.length > 0) {\n await this.exportSpans(spans);\n this.spans.delete(traceId);\n }\n } else {\n // Flush all traces\n const promises: Promise<void>[] = [];\n for (const [id, spans] of this.spans.entries()) {\n promises.push(this.exportSpans(spans));\n this.spans.delete(id);\n }\n await Promise.all(promises);\n }\n }\n\n async shutdown(): Promise<void> {\n await this.forceFlush();\n if (this.exporter) {\n await this.exporter.shutdown();\n }\n }\n\n /**\n * Export spans with post-processing\n * Errors are caught and logged but don't throw to prevent worker instability\n */\n private async exportSpans(spans: ReadableSpan[]): Promise<void> {\n if (spans.length === 0) return;\n if (!this.exporter) return; // No exporter configured (e.g., in tests)\n\n let processedSpans = spans;\n\n if (this.postProcessor) {\n try {\n processedSpans = this.postProcessor(spans);\n } catch (error) {\n // Post-processor errors should not prevent export\n console.error('[autotel-edge] Post-processor error:', error);\n // Continue with original spans\n processedSpans = spans;\n }\n }\n\n return new Promise((resolve) => {\n this.exporter.export(processedSpans, (result) => {\n if (result.code === 0) {\n // SUCCESS\n resolve();\n } else {\n // Log but don't reject - exporter failures shouldn't crash the worker\n console.error(\n '[autotel-edge] Exporter error:',\n result.error?.message || 'Unknown error',\n );\n resolve(); // Resolve instead of reject to prevent unhandled promise rejection\n }\n });\n });\n }\n}\n\n/**\n * Span processor that supports tail sampling decisions\n */\nexport class TailSamplingSpanProcessor implements SpanProcessor {\n private wrapped: SpanProcessorWithFlush;\n private tailSampler?: TailSampleFn;\n private traces: Map<string, LocalTrace> = new Map();\n\n constructor(\n exporter: SpanExporter,\n postProcessor?: PostProcessorFn,\n tailSampler?: TailSampleFn,\n ) {\n this.wrapped = new SpanProcessorWithFlush(exporter, postProcessor);\n this.tailSampler = tailSampler;\n }\n\n onStart(span: Span, parentContext: Context): void {\n this.wrapped.onStart(span, parentContext);\n }\n\n onEnd(span: ReadableSpan): void {\n const traceId = span.spanContext().traceId;\n const spanId = span.spanContext().spanId;\n const parentSpanId = 'parentSpanId' in span ? span.parentSpanId : undefined;\n\n // Initialize trace if not exists\n if (!this.traces.has(traceId)) {\n this.traces.set(traceId, {\n traceId,\n spans: [],\n localRootSpan: undefined as any, // Will be set when we identify the local root\n });\n }\n\n const trace = this.traces.get(traceId)!;\n\n // Determine if this span is a local root by checking if its parent is in buffered spans\n // A span is a local root if:\n // 1. It has no parentSpanId (definitive root)\n // 2. Its parentSpanId doesn't match any already-buffered span (remote parent = distributed trace entry)\n const hasLocalParent = parentSpanId &&\n trace.spans.some(s => s.spanContext().spanId === parentSpanId);\n\n // Set localRootSpan if this is the local root (no local parent found in buffer)\n if (!hasLocalParent) {\n trace.localRootSpan = span;\n }\n\n trace.spans.push(span); // Buffer the span AFTER checking parent relationships\n\n // Auto-flush decision: only auto-flush for normal traces (no parentSpanId at all)\n // For distributed traces (parentSpanId present), we rely on explicit forceFlush() from instrument.ts\n // This ensures we don't trigger before all spans have been buffered\n const isDefinitiveRoot = !parentSpanId;\n const shouldAutoFlush = isDefinitiveRoot && trace.localRootSpan &&\n trace.localRootSpan.spanContext().spanId === spanId;\n\n if (shouldAutoFlush) {\n if (this.tailSampler) {\n const shouldKeep = this.tailSampler(trace);\n\n if (shouldKeep) {\n // Export ALL buffered spans in the trace\n for (const bufferedSpan of trace.spans) {\n this.wrapped.onEnd(bufferedSpan);\n }\n // Force flush to actually export the spans\n void this.wrapped.forceFlush(traceId);\n }\n // If not keeping, just drop all spans (don't export)\n } else {\n // No tail sampler, export all buffered spans\n for (const bufferedSpan of trace.spans) {\n this.wrapped.onEnd(bufferedSpan);\n }\n // Force flush to actually export the spans\n void this.wrapped.forceFlush(traceId);\n }\n\n // Clean up trace after decision\n this.traces.delete(traceId);\n }\n // If not local root span, just buffer it - don't export yet\n }\n\n async forceFlush(traceId?: string): Promise<void> {\n if (traceId) {\n // Make tail sampling decision for this specific trace before flushing\n const trace = this.traces.get(traceId);\n if (trace) {\n // Ensure localRootSpan is set (fallback to first span if not)\n // This handles distributed traces where no span has undefined parentSpanId\n if (!trace.localRootSpan && trace.spans.length > 0) {\n trace.localRootSpan = trace.spans[0];\n }\n\n if (this.tailSampler) {\n const shouldKeep = this.tailSampler(trace);\n\n if (shouldKeep) {\n // Export ALL buffered spans in the trace\n for (const bufferedSpan of trace.spans) {\n this.wrapped.onEnd(bufferedSpan);\n }\n }\n } else {\n // No tail sampler, export all buffered spans\n for (const bufferedSpan of trace.spans) {\n this.wrapped.onEnd(bufferedSpan);\n }\n }\n\n // Clean up trace after decision\n this.traces.delete(traceId);\n }\n }\n return this.wrapped.forceFlush(traceId);\n }\n\n async shutdown(): Promise<void> {\n this.traces.clear();\n return this.wrapped.shutdown();\n }\n}\n","/**\n * Configuration system for autotel-edge\n */\n\nimport { W3CTraceContextPropagator } from '@opentelemetry/core';\nimport { ParentBasedSampler, AlwaysOnSampler } from '@opentelemetry/sdk-trace-base';\nimport { context as api_context, createContextKey, type Context } from '@opentelemetry/api';\nimport type {\n EdgeConfig,\n ResolvedEdgeConfig,\n ConfigurationOption,\n Trigger,\n ParentRatioSamplingConfig,\n} from '../types';\nimport { isSpanProcessorConfig } from '../types';\nimport { OTLPExporter } from './exporter';\nimport { TailSamplingSpanProcessor } from './spanprocessor';\n\n/**\n * Type for config initialization function\n */\nexport type Initialiser = (env: any, trigger: Trigger) => ResolvedEdgeConfig;\n\n/**\n * Context key for storing config (isolates config per-request)\n */\nconst CONFIG_KEY = createContextKey('autotel-edge-config');\n\n/**\n * Get the currently active config from context\n *\n * This reads the config from the active context, ensuring each request\n * has its own isolated config even when multiple requests are in-flight.\n */\nexport function getActiveConfig(): ResolvedEdgeConfig | null {\n const value = api_context.active().getValue(CONFIG_KEY) as\n | ResolvedEdgeConfig\n | null\n | undefined;\n return value ?? null;\n}\n\n/**\n * Set the active config in context\n *\n * Returns a new context with the config stored. This context should be\n * used with api_context.with() to ensure the config is isolated per-request.\n *\n * @example\n * ```typescript\n * const config = parseConfig({ service: { name: 'my-service' } });\n * const context = setConfig(config);\n *\n * api_context.with(context, () => {\n * // Config is available here via getActiveConfig()\n * });\n * ```\n */\nexport function setConfig(config: ResolvedEdgeConfig): Context {\n return api_context.active().setValue(CONFIG_KEY, config);\n}\n\n/**\n * Parse and validate configuration\n */\nexport function parseConfig(config: EdgeConfig): ResolvedEdgeConfig {\n // Parse head sampler\n const headSampler =\n config.sampling?.headSampler ??\n new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n\n const parsedHeadSampler =\n typeof headSampler === 'object' && 'ratio' in headSampler\n ? createParentRatioSampler(headSampler)\n : headSampler;\n\n // Parse tail sampler (default: keep sampled or error traces)\n const tailSampler =\n config.sampling?.tailSampler ??\n ((traceInfo) => {\n const localRootSpan = traceInfo.localRootSpan;\n const ctx = localRootSpan.spanContext();\n // Keep if sampled or if root span has error\n return (ctx.traceFlags & 1) === 1 || localRootSpan.status.code === 2; // SAMPLED flag | ERROR status\n });\n\n // Parse exporter - use TailSamplingSpanProcessor when tail sampler is present\n const spanProcessors = isSpanProcessorConfig(config)\n ? Array.isArray(config.spanProcessors)\n ? config.spanProcessors\n : [config.spanProcessors]\n : [\n // Use TailSamplingSpanProcessor to enable tail sampling\n new TailSamplingSpanProcessor(\n typeof config.exporter === 'object' && 'url' in config.exporter\n ? new OTLPExporter(config.exporter)\n : config.exporter,\n config.postProcessor,\n tailSampler, // Wire up the tail sampler!\n ),\n ];\n\n // Build resolved config\n const resolved: ResolvedEdgeConfig = {\n service: config.service,\n handlers: {\n fetch: config.handlers?.fetch ?? {},\n },\n fetch: {\n includeTraceContext: config.fetch?.includeTraceContext ?? true,\n },\n postProcessor: config.postProcessor ?? ((spans) => spans),\n sampling: {\n headSampler: parsedHeadSampler,\n tailSampler,\n },\n spanProcessors,\n propagator: config.propagator ?? new W3CTraceContextPropagator(),\n instrumentation: {\n instrumentGlobalFetch: config.instrumentation?.instrumentGlobalFetch ?? true,\n instrumentGlobalCache: config.instrumentation?.instrumentGlobalCache ?? false,\n disabled: config.instrumentation?.disabled ?? false,\n },\n subscribers: config.subscribers ?? [],\n dataSafety: config.dataSafety,\n nativeTracing: config.nativeTracing ?? 'auto',\n };\n\n return resolved;\n}\n\n/**\n * Create a parent-based ratio sampler\n */\nfunction createParentRatioSampler(config: ParentRatioSamplingConfig) {\n const { ratio, acceptRemote = true } = config;\n\n // Simple ratio sampler\n const ratioSampler = {\n shouldSample: () => ({\n decision: Math.random() < ratio ? 1 : 0, // RECORD_AND_SAMPLED : NOT_RECORD\n attributes: {},\n }),\n toString: () => `ParentRatioSampler{ratio=${ratio}}`,\n };\n\n if (acceptRemote) {\n return new ParentBasedSampler({ root: ratioSampler as any });\n }\n\n return ratioSampler;\n}\n\n/**\n * Create a config initializer function\n */\nexport function createInitialiser(config: ConfigurationOption): Initialiser {\n if (typeof config === 'function') {\n return (env, trigger) => {\n const conf = parseConfig(config(env, trigger));\n return conf;\n };\n } else {\n const parsed = parseConfig(config);\n return () => parsed;\n }\n}\n"],"mappings":";;;;;;;AAmBA,MAAM,iBAAyC;CAC7C,QAAQ;CACR,gBAAgB;CAChB,cAAc;AAChB;;;;AAKA,IAAa,eAAb,MAAkD;CAChD,AAAQ;CACR,AAAQ;CAER,YAAY,QAA4B;EACtC,KAAK,MAAM,OAAO;EAClB,KAAK,UAAU,OAAO,OAAO,CAAC,GAAG,gBAAgB,OAAO,OAAO;CACjE;CAEA,OAAO,OAAc,gBAAsD;EACzE,KAAK,QAAQ,KAAK,CAAC,CAChB,WAAW;GACV,eAAe,EAAE,MAAM,iBAAiB,QAAQ,CAAC;EACnD,CAAC,CAAC,CACD,OAAO,UAAU;GAChB,eAAe;IAAE,MAAM,iBAAiB;IAAQ;GAAM,CAAC;EACzD,CAAC;CACL;CAEA,AAAQ,QAAQ,OAAgC;EAC9C,OAAO,IAAI,SAAe,SAAS,WAAW;GAC5C,IAAI;IACF,KAAK,KAAK,OAAO,SAAS,MAAM;GAClC,SAAS,OAAO;IACd,OAAO,KAAK;GACd;EACF,CAAC;CACH;CAEA,KACE,OACA,WACA,SACM;EACN,MAAM,UAAU,IAAI,YAAY;EAChC,MAAM,gBAAgB,oBAAoB,iBAAiB,KAAK;EAEhE,MAAM,OAAO,QAAQ,OAAO,aAAa;EACzC,MAAM,SAAsB;GAC1B,Q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AI,cACF,OAAO,IAAI,mBAAmB,EAAE,MAAM,aAAoB,CAAC;CAG7D,OAAO;AACT;;;;AAKA,SAAgB,kBAAkB,QAA0C;CAC1E,IAAI,OAAO,WAAW,YACpB,QAAQ,KAAK,YAAY;EAEvB,OADa,YAAY,OAAO,KAAK,OAAO,CAClC;CACZ;MACK;EACL,MAAM,SAAS,YAAY,MAAM;EACjC,aAAa;CACf;AACF"}
1
+ {"version":3,"file":"config-CFlfvmQ1.js","names":["api_context"],"sources":["../src/core/exporter.ts","../src/types.ts","../src/core/spanprocessor.ts","../src/core/config.ts"],"sourcesContent":["/**\n * Lightweight OTLP exporter for edge environments\n * Ported and adapted from @microlabs/\n *\n * This exporter is much smaller than the standard @opentelemetry/exporter-trace-otlp-http\n * because it uses fetch() directly instead of Node.js http/https modules.\n */\n\nimport type { ExportResult } from '@opentelemetry/core';\nimport { ExportResultCode } from '@opentelemetry/core';\nimport { OTLPExporterError } from '@opentelemetry/otlp-exporter-base';\nimport { JsonTraceSerializer } from '@opentelemetry/otlp-transformer';\nimport type { SpanExporter } from '@opentelemetry/sdk-trace-base';\nimport type { OTLPExporterConfig } from '../types';\n\n// Version is injected at build time via tsup define\n// This avoids runtime filesystem access which isn't available in edge environments\nconst PACKAGE_VERSION = process.env.AUTOTEL_EDGE_VERSION || '0.1.1';\n\nconst defaultHeaders: Record<string, string> = {\n accept: 'application/json',\n 'content-type': 'application/json',\n 'user-agent': `autotel-edge v${PACKAGE_VERSION}`,\n};\n\n/**\n * Minimal OTLP exporter using fetch()\n */\nexport class OTLPExporter implements SpanExporter {\n private headers: Record<string, string>;\n private url: string;\n\n constructor(config: OTLPExporterConfig) {\n this.url = config.url;\n this.headers = Object.assign({}, defaultHeaders, config.headers);\n }\n\n export(items: any[], resultCallback: (result: ExportResult) => void): void {\n this._export(items)\n .then(() => {\n resultCallback({ code: ExportResultCode.SUCCESS });\n })\n .catch((error) => {\n resultCallback({ code: ExportResultCode.FAILED, error });\n });\n }\n\n private _export(items: any[]): Promise<unknown> {\n return new Promise<void>((resolve, reject) => {\n try {\n this.send(items, resolve, reject);\n } catch (error) {\n reject(error);\n }\n });\n }\n\n send(\n items: any[],\n onSuccess: () => void,\n onError: (error: OTLPExporterError) => void,\n ): void {\n const decoder = new TextDecoder();\n const exportMessage = JsonTraceSerializer.serializeRequest(items);\n\n const body = decoder.decode(exportMessage);\n const params: RequestInit = {\n method: 'POST',\n headers: this.headers,\n body,\n };\n\n fetch(this.url, params)\n .then((response) => {\n if (response.ok) {\n onSuccess();\n } else {\n onError(\n new OTLPExporterError(\n `Exporter received a statusCode: ${response.status}`,\n ),\n );\n }\n })\n .catch((error) => {\n onError(\n new OTLPExporterError(\n `Exception during export: ${error.toString()}`,\n error.code,\n error.stack,\n ),\n );\n });\n }\n\n async shutdown(): Promise<void> {\n // No-op for edge environments\n }\n}\n","/**\n * Shared types for autotel-edge\n */\n\nimport type {\n Attributes,\n Context,\n Span,\n SpanOptions,\n TextMapPropagator,\n} from '@opentelemetry/api';\nimport type {\n ReadableSpan,\n Sampler,\n SpanExporter,\n SpanProcessor,\n} from '@opentelemetry/sdk-trace-base';\n\n// Re-export commonly used types\n\n\n/**\n * Extended SpanOptions with per-span sampler support\n */\nexport interface ExtendedSpanOptions extends SpanOptions {\n sampler?: Sampler;\n}\n\n/**\n * Trigger types for edge handlers\n * Can be a Request or any vendor-specific trigger type\n */\nexport type Trigger =\n | Request\n | DOConstructorTrigger\n | WorkflowTrigger\n | 'do-alarm'\n | unknown;\n\nexport interface DOConstructorTrigger {\n id: string;\n name?: string;\n}\n\nexport interface WorkflowTrigger {\n type: 'workflow';\n name: string;\n}\n\n/**\n * Config types\n */\nexport interface OTLPExporterConfig {\n url: string;\n headers?: Record<string, string>;\n}\n\nexport type ExporterConfig = OTLPExporterConfig | SpanExporter;\n\nexport interface ServiceConfig {\n name: string;\n namespace?: string;\n version?: string;\n}\n\nexport interface ParentRatioSamplingConfig {\n acceptRemote?: boolean;\n ratio: number;\n}\n\ntype HeadSamplerConf = Sampler | ParentRatioSamplingConfig;\n\nexport interface SamplingConfig<HS extends HeadSamplerConf = HeadSamplerConf> {\n headSampler?: HS;\n tailSampler?: TailSampleFn;\n}\n\nexport interface InstrumentationOptions {\n instrumentGlobalFetch?: boolean;\n instrumentGlobalCache?: boolean;\n /**\n * Disable instrumentation entirely (useful for local development)\n * When enabled, the handler is returned as-is without any instrumentation\n * @default false\n */\n disabled?: boolean;\n}\n\n/**\n * Utility types\n */\nexport type OrPromise<T> = T | Promise<T>;\n\n/**\n * Adapter event types\n */\nexport type FunnelStepStatus =\n | 'started'\n | 'completed'\n | 'abandoned'\n | 'failed'\n | (string & {});\n\nexport type OutcomeStatus =\n | 'success'\n | 'failure'\n | 'partial'\n | (string & {});\n\nexport interface EdgeEventBase {\n [key: string]: unknown;\n service: string;\n timestamp: number;\n attributes: Record<string, unknown>;\n traceId?: string;\n spanId?: string;\n correlationId?: string;\n name: string; // Normalized event name for easy access\n}\n\nexport interface EdgeTrackEvent extends EdgeEventBase {\n type: 'event';\n event: string;\n}\n\nexport interface EdgeFunnelStepEvent extends EdgeEventBase {\n type: 'funnel-step';\n funnel: string;\n status: FunnelStepStatus;\n}\n\nexport interface EdgeOutcomeEvent extends EdgeEventBase {\n type: 'outcome';\n operation: string;\n outcome: OutcomeStatus;\n}\n\nexport interface EdgeValueEvent extends EdgeEventBase {\n type: 'value';\n metric: string;\n value: number;\n}\n\nexport type EdgeEvent =\n | EdgeTrackEvent\n | EdgeFunnelStepEvent\n | EdgeOutcomeEvent\n | EdgeValueEvent;\n\nexport type EdgeSubscriber = (event: EdgeEvent) => OrPromise<void>;\n\nexport interface FetcherConfig {\n includeTraceContext?: boolean | ((request: Request) => boolean);\n}\n\nexport interface RouteServiceConfig {\n service: string;\n}\n\nexport interface PostProcessParams {\n /**\n * The request object that was passed to the fetch handler.\n */\n request: Request;\n /**\n * The generated response object.\n */\n response: Response;\n /**\n * A readable version of the span object that can be used to access the span's attributes and events.\n */\n readable: ReadableSpan;\n}\n\nexport interface FetchHandlerConfig {\n /**\n * Whether to enable context propagation for incoming requests to `fetch`.\n * This enables or disables distributed tracing from W3C Trace Context headers.\n * @default true\n */\n acceptTraceContext?: boolean | ((request: Request) => boolean);\n /**\n * Allows further customization of the generated span, based on the request/response data.\n */\n postProcess?: (span: Span, ctx: PostProcessParams) => void;\n /**\n * Route patterns to include for fetch handler instrumentation.\n * Supports glob patterns like '/api/**'.\n * If not set, all routes are included.\n */\n include?: string[];\n /**\n * Route patterns to exclude from fetch handler instrumentation.\n * Supports glob patterns like '/health' and '/_internal/**'.\n * Exclusions take precedence over inclusions.\n */\n exclude?: string[];\n /**\n * Route-specific service mapping.\n * The first matching pattern wins based on object iteration order.\n */\n routes?: Record<string, RouteServiceConfig>;\n}\n\nexport interface HandlerConfig {\n fetch?: FetchHandlerConfig;\n}\n\nexport interface DataSafetyConfig {\n /** Redact query parameters from URL attributes (default: false) */\n redactQueryParams?: boolean;\n /** Control D1 SQL statement capture: 'full' (default), 'obfuscated', or 'off' */\n captureDbStatement?: 'off' | 'obfuscated' | 'full';\n /** Only capture these email headers (lowercase). When set, other headers are excluded. */\n emailHeaderAllowlist?: string[];\n}\n\n/**\n * Controls whether `span()` / `trace()` route to a platform-native tracer\n * (e.g. Cloudflare's `tracing.enterSpan()`) instead of autotel's own OTLP\n * pipeline.\n *\n * - `'auto'` (default): use the native tracer when one is detected at runtime,\n * otherwise fall back to autotel's OTLP exporter.\n * - `'on'`: always prefer the native tracer (the adapter warns once if none is\n * available and falls back).\n * - `'off'`: never use a native tracer — always use autotel's OTLP pipeline.\n * Useful for local `wrangler dev` streaming to autotel-devtools.\n */\nexport type NativeTracingMode = 'auto' | 'on' | 'off';\n\ninterface EdgeConfigBase {\n service: ServiceConfig;\n handlers?: HandlerConfig;\n fetch?: FetcherConfig;\n postProcessor?: PostProcessorFn;\n sampling?: SamplingConfig;\n propagator?: TextMapPropagator;\n instrumentation?: InstrumentationOptions;\n subscribers?: EdgeSubscriber[];\n /** Opt-in data safety controls for sensitive attribute capture */\n dataSafety?: DataSafetyConfig;\n /**\n * Native platform tracing mode. Defaults to `'auto'`.\n * @see NativeTracingMode\n */\n nativeTracing?: NativeTracingMode;\n}\n\ninterface EdgeConfigExporter extends EdgeConfigBase {\n exporter: ExporterConfig;\n}\n\ninterface EdgeConfigSpanProcessors extends EdgeConfigBase {\n spanProcessors: SpanProcessor | SpanProcessor[];\n}\n\nexport type EdgeConfig = EdgeConfigExporter | EdgeConfigSpanProcessors;\n\nexport function isSpanProcessorConfig(\n config: EdgeConfig,\n): config is EdgeConfigSpanProcessors {\n return !!(config as EdgeConfigSpanProcessors).spanProcessors;\n}\n\nexport interface ResolvedEdgeConfig extends EdgeConfigBase {\n handlers: Required<HandlerConfig>;\n fetch: Required<FetcherConfig>;\n postProcessor: PostProcessorFn;\n sampling: Required<SamplingConfig<Sampler>>;\n spanProcessors: SpanProcessor[];\n propagator: TextMapPropagator;\n instrumentation: InstrumentationOptions;\n subscribers: EdgeSubscriber[];\n nativeTracing: NativeTracingMode;\n}\n\n/**\n * Function types\n */\nexport type ResolveConfigFn<Env = any> = (\n env: Env,\n trigger: Trigger,\n) => EdgeConfig;\nexport type ConfigurationOption = EdgeConfig | ResolveConfigFn;\n\nexport type PostProcessorFn = (spans: ReadableSpan[]) => ReadableSpan[];\nexport type TailSampleFn = (traceInfo: LocalTrace) => boolean;\n\nexport interface LocalTrace {\n traceId: string;\n spans: ReadableSpan[];\n localRootSpan: ReadableSpan;\n}\n\n/**\n * Span processor with flush support\n */\nexport type TraceFlushableSpanProcessor = SpanProcessor & {\n forceFlush: (traceId?: string) => Promise<void>;\n};\n\n/**\n * Handler instrumentation\n */\nexport interface InitialSpanInfo {\n name: string;\n options: SpanOptions;\n context?: Context;\n}\n\nexport interface HandlerInstrumentation<T extends Trigger, R extends any> {\n getInitialSpanInfo: (trigger: T) => InitialSpanInfo;\n getAttributesFromResult?: (result: Awaited<R>) => Attributes;\n instrumentTrigger?: (trigger: T) => T;\n executionSucces?: (span: Span, trigger: T, result: Awaited<R>) => void;\n executionFailed?: (span: Span, trigger: T, error?: any) => void;\n}\n\n/**\n * Utility types\n */\n\nexport {type Attributes, type Context, type Span, type SpanOptions} from '@opentelemetry/api';\nexport {type ReadableSpan} from '@opentelemetry/sdk-trace-base';\n","/**\n * Span processor with flush and tail sampling support\n */\n\nimport type { Context } from '@opentelemetry/api';\nimport type {\n ReadableSpan,\n Span,\n SpanExporter,\n SpanProcessor,\n} from '@opentelemetry/sdk-trace-base';\nimport type { PostProcessorFn, TailSampleFn, LocalTrace } from '../types';\n\n/**\n * Span processor that supports flush by trace ID and tail sampling\n */\nexport class SpanProcessorWithFlush implements SpanProcessor {\n private exporter: SpanExporter;\n private postProcessor?: PostProcessorFn;\n private spans: Map<string, ReadableSpan[]> = new Map();\n\n constructor(exporter: SpanExporter, postProcessor?: PostProcessorFn) {\n this.exporter = exporter;\n this.postProcessor = postProcessor;\n }\n\n onStart(_span: Span, _parentContext: Context): void {\n // No-op for now\n }\n\n onEnd(span: ReadableSpan): void {\n const traceId = span.spanContext().traceId;\n\n if (!this.spans.has(traceId)) {\n this.spans.set(traceId, []);\n }\n\n this.spans.get(traceId)!.push(span);\n }\n\n /**\n * Force flush spans for a specific trace\n */\n async forceFlush(traceId?: string): Promise<void> {\n if (traceId) {\n const spans = this.spans.get(traceId);\n if (spans && spans.length > 0) {\n await this.exportSpans(spans);\n this.spans.delete(traceId);\n }\n } else {\n // Flush all traces\n const promises: Promise<void>[] = [];\n for (const [id, spans] of this.spans.entries()) {\n promises.push(this.exportSpans(spans));\n this.spans.delete(id);\n }\n await Promise.all(promises);\n }\n }\n\n async shutdown(): Promise<void> {\n await this.forceFlush();\n if (this.exporter) {\n await this.exporter.shutdown();\n }\n }\n\n /**\n * Export spans with post-processing\n * Errors are caught and logged but don't throw to prevent worker instability\n */\n private async exportSpans(spans: ReadableSpan[]): Promise<void> {\n if (spans.length === 0) return;\n if (!this.exporter) return; // No exporter configured (e.g., in tests)\n\n let processedSpans = spans;\n\n if (this.postProcessor) {\n try {\n processedSpans = this.postProcessor(spans);\n } catch (error) {\n // Post-processor errors should not prevent export\n console.error('[autotel-edge] Post-processor error:', error);\n // Continue with original spans\n processedSpans = spans;\n }\n }\n\n return new Promise((resolve) => {\n this.exporter.export(processedSpans, (result) => {\n if (result.code === 0) {\n // SUCCESS\n resolve();\n } else {\n // Log but don't reject - exporter failures shouldn't crash the worker\n console.error(\n '[autotel-edge] Exporter error:',\n result.error?.message || 'Unknown error',\n );\n resolve(); // Resolve instead of reject to prevent unhandled promise rejection\n }\n });\n });\n }\n}\n\n/**\n * Span processor that supports tail sampling decisions\n */\nexport class TailSamplingSpanProcessor implements SpanProcessor {\n private wrapped: SpanProcessorWithFlush;\n private tailSampler?: TailSampleFn;\n private traces: Map<string, LocalTrace> = new Map();\n\n constructor(\n exporter: SpanExporter,\n postProcessor?: PostProcessorFn,\n tailSampler?: TailSampleFn,\n ) {\n this.wrapped = new SpanProcessorWithFlush(exporter, postProcessor);\n this.tailSampler = tailSampler;\n }\n\n onStart(span: Span, parentContext: Context): void {\n this.wrapped.onStart(span, parentContext);\n }\n\n onEnd(span: ReadableSpan): void {\n const traceId = span.spanContext().traceId;\n const spanId = span.spanContext().spanId;\n const parentSpanId = 'parentSpanId' in span ? span.parentSpanId : undefined;\n\n // Initialize trace if not exists\n if (!this.traces.has(traceId)) {\n this.traces.set(traceId, {\n traceId,\n spans: [],\n localRootSpan: undefined as any, // Will be set when we identify the local root\n });\n }\n\n const trace = this.traces.get(traceId)!;\n\n // Determine if this span is a local root by checking if its parent is in buffered spans\n // A span is a local root if:\n // 1. It has no parentSpanId (definitive root)\n // 2. Its parentSpanId doesn't match any already-buffered span (remote parent = distributed trace entry)\n const hasLocalParent = parentSpanId &&\n trace.spans.some(s => s.spanContext().spanId === parentSpanId);\n\n // Set localRootSpan if this is the local root (no local parent found in buffer)\n if (!hasLocalParent) {\n trace.localRootSpan = span;\n }\n\n trace.spans.push(span); // Buffer the span AFTER checking parent relationships\n\n // Auto-flush decision: only auto-flush for normal traces (no parentSpanId at all)\n // For distributed traces (parentSpanId present), we rely on explicit forceFlush() from instrument.ts\n // This ensures we don't trigger before all spans have been buffered\n const isDefinitiveRoot = !parentSpanId;\n const shouldAutoFlush = isDefinitiveRoot && trace.localRootSpan &&\n trace.localRootSpan.spanContext().spanId === spanId;\n\n if (shouldAutoFlush) {\n if (this.tailSampler) {\n const shouldKeep = this.tailSampler(trace);\n\n if (shouldKeep) {\n // Export ALL buffered spans in the trace\n for (const bufferedSpan of trace.spans) {\n this.wrapped.onEnd(bufferedSpan);\n }\n // Force flush to actually export the spans\n void this.wrapped.forceFlush(traceId);\n }\n // If not keeping, just drop all spans (don't export)\n } else {\n // No tail sampler, export all buffered spans\n for (const bufferedSpan of trace.spans) {\n this.wrapped.onEnd(bufferedSpan);\n }\n // Force flush to actually export the spans\n void this.wrapped.forceFlush(traceId);\n }\n\n // Clean up trace after decision\n this.traces.delete(traceId);\n }\n // If not local root span, just buffer it - don't export yet\n }\n\n async forceFlush(traceId?: string): Promise<void> {\n if (traceId) {\n // Make tail sampling decision for this specific trace before flushing\n const trace = this.traces.get(traceId);\n if (trace) {\n // Ensure localRootSpan is set (fallback to first span if not)\n // This handles distributed traces where no span has undefined parentSpanId\n if (!trace.localRootSpan && trace.spans.length > 0) {\n trace.localRootSpan = trace.spans[0];\n }\n\n if (this.tailSampler) {\n const shouldKeep = this.tailSampler(trace);\n\n if (shouldKeep) {\n // Export ALL buffered spans in the trace\n for (const bufferedSpan of trace.spans) {\n this.wrapped.onEnd(bufferedSpan);\n }\n }\n } else {\n // No tail sampler, export all buffered spans\n for (const bufferedSpan of trace.spans) {\n this.wrapped.onEnd(bufferedSpan);\n }\n }\n\n // Clean up trace after decision\n this.traces.delete(traceId);\n }\n }\n return this.wrapped.forceFlush(traceId);\n }\n\n async shutdown(): Promise<void> {\n this.traces.clear();\n return this.wrapped.shutdown();\n }\n}\n","/**\n * Configuration system for autotel-edge\n */\n\nimport { W3CTraceContextPropagator } from '@opentelemetry/core';\nimport { ParentBasedSampler, AlwaysOnSampler } from '@opentelemetry/sdk-trace-base';\nimport { context as api_context, createContextKey, type Context } from '@opentelemetry/api';\nimport type {\n EdgeConfig,\n ResolvedEdgeConfig,\n ConfigurationOption,\n Trigger,\n ParentRatioSamplingConfig,\n} from '../types';\nimport { isSpanProcessorConfig } from '../types';\nimport { OTLPExporter } from './exporter';\nimport { TailSamplingSpanProcessor } from './spanprocessor';\n\n/**\n * Type for config initialization function\n */\nexport type Initialiser = (env: any, trigger: Trigger) => ResolvedEdgeConfig;\n\n/**\n * Context key for storing config (isolates config per-request)\n */\nconst CONFIG_KEY = createContextKey('autotel-edge-config');\n\n/**\n * Get the currently active config from context\n *\n * This reads the config from the active context, ensuring each request\n * has its own isolated config even when multiple requests are in-flight.\n */\nexport function getActiveConfig(): ResolvedEdgeConfig | null {\n const value = api_context.active().getValue(CONFIG_KEY) as\n | ResolvedEdgeConfig\n | null\n | undefined;\n return value ?? null;\n}\n\n/**\n * Set the active config in context\n *\n * Returns a new context with the config stored. This context should be\n * used with api_context.with() to ensure the config is isolated per-request.\n *\n * @example\n * ```typescript\n * const config = parseConfig({ service: { name: 'my-service' } });\n * const context = setConfig(config);\n *\n * api_context.with(context, () => {\n * // Config is available here via getActiveConfig()\n * });\n * ```\n */\nexport function setConfig(config: ResolvedEdgeConfig): Context {\n return api_context.active().setValue(CONFIG_KEY, config);\n}\n\n/**\n * Parse and validate configuration\n */\nexport function parseConfig(config: EdgeConfig): ResolvedEdgeConfig {\n // Parse head sampler\n const headSampler =\n config.sampling?.headSampler ??\n new ParentBasedSampler({\n root: new AlwaysOnSampler(),\n });\n\n const parsedHeadSampler =\n typeof headSampler === 'object' && 'ratio' in headSampler\n ? createParentRatioSampler(headSampler)\n : headSampler;\n\n // Parse tail sampler (default: keep sampled or error traces)\n const tailSampler =\n config.sampling?.tailSampler ??\n ((traceInfo) => {\n const localRootSpan = traceInfo.localRootSpan;\n const ctx = localRootSpan.spanContext();\n // Keep if sampled or if root span has error\n return (ctx.traceFlags & 1) === 1 || localRootSpan.status.code === 2; // SAMPLED flag | ERROR status\n });\n\n // Parse exporter - use TailSamplingSpanProcessor when tail sampler is present\n const spanProcessors = isSpanProcessorConfig(config)\n ? Array.isArray(config.spanProcessors)\n ? config.spanProcessors\n : [config.spanProcessors]\n : [\n // Use TailSamplingSpanProcessor to enable tail sampling\n new TailSamplingSpanProcessor(\n typeof config.exporter === 'object' && 'url' in config.exporter\n ? new OTLPExporter(config.exporter)\n : config.exporter,\n config.postProcessor,\n tailSampler, // Wire up the tail sampler!\n ),\n ];\n\n // Build resolved config\n const resolved: ResolvedEdgeConfig = {\n service: config.service,\n handlers: {\n fetch: config.handlers?.fetch ?? {},\n },\n fetch: {\n includeTraceContext: config.fetch?.includeTraceContext ?? true,\n },\n postProcessor: config.postProcessor ?? ((spans) => spans),\n sampling: {\n headSampler: parsedHeadSampler,\n tailSampler,\n },\n spanProcessors,\n propagator: config.propagator ?? new W3CTraceContextPropagator(),\n instrumentation: {\n instrumentGlobalFetch: config.instrumentation?.instrumentGlobalFetch ?? true,\n instrumentGlobalCache: config.instrumentation?.instrumentGlobalCache ?? false,\n disabled: config.instrumentation?.disabled ?? false,\n },\n subscribers: config.subscribers ?? [],\n dataSafety: config.dataSafety,\n nativeTracing: config.nativeTracing ?? 'auto',\n };\n\n return resolved;\n}\n\n/**\n * Create a parent-based ratio sampler\n */\nfunction createParentRatioSampler(config: ParentRatioSamplingConfig) {\n const { ratio, acceptRemote = true } = config;\n\n // Simple ratio sampler\n const ratioSampler = {\n shouldSample: () => ({\n decision: Math.random() < ratio ? 1 : 0, // RECORD_AND_SAMPLED : NOT_RECORD\n attributes: {},\n }),\n toString: () => `ParentRatioSampler{ratio=${ratio}}`,\n };\n\n if (acceptRemote) {\n return new ParentBasedSampler({ root: ratioSampler as any });\n }\n\n return ratioSampler;\n}\n\n/**\n * Create a config initializer function\n */\nexport function createInitialiser(config: ConfigurationOption): Initialiser {\n if (typeof config === 'function') {\n return (env, trigger) => {\n const conf = parseConfig(config(env, trigger));\n return conf;\n };\n } else {\n const parsed = parseConfig(config);\n return () => parsed;\n }\n}\n"],"mappings":";;;;;;;AAmBA,MAAM,iBAAyC;CAC7C,QAAQ;CACR,gBAAgB;CAChB,cAAc;AAChB;;;;AAKA,IAAa,eAAb,MAAkD;CAChD,AAAQ;CACR,AAAQ;CAER,YAAY,QAA4B;EACtC,KAAK,MAAM,OAAO;EAClB,KAAK,UAAU,OAAO,OAAO,CAAC,GAAG,gBAAgB,OAAO,OAAO;CACjE;CAEA,OAAO,OAAc,gBAAsD;EACzE,KAAK,QAAQ,KAAK,CAAC,CAChB,WAAW;GACV,eAAe,EAAE,MAAM,iBAAiB,QAAQ,CAAC;EACnD,CAAC,CAAC,CACD,OAAO,UAAU;GAChB,eAAe;IAAE,MAAM,iBAAiB;IAAQ;GAAM,CAAC;EACzD,CAAC;CACL;CAEA,AAAQ,QAAQ,OAAgC;EAC9C,OAAO,IAAI,SAAe,SAAS,WAAW;GAC5C,IAAI;IACF,KAAK,KAAK,OAAO,SAAS,MAAM;GAClC,SAAS,OAAO;IACd,OAAO,KAAK;GACd;EACF,CAAC;CACH;CAEA,KACE,OACA,WACA,SACM;EACN,MAAM,UAAU,IAAI,YAAY;EAChC,MAAM,gBAAgB,oBAAoB,iBAAiB,KAAK;EAEhE,MAAM,OAAO,QAAQ,OAAO,aAAa;EACzC,MAAM,SAAsB;GAC1B,QAAQ;GACR,SAAS,KAAK;GACd;EACF;EAEA,MAAM,KAAK,KAAK,MAAM,CAAC,CACpB,MAAM,aAAa;GAClB,IAAI,SAAS,IACX,UAAU;QAEV,QACE,IAAI,kBACF,mCAAmC,SAAS,QAC9C,CACF;EAEJ,CAAC,CAAC,CACD,OAAO,UAAU;GAChB,QACE,IAAI,kBACF,4BAA4B,MAAM,SAAS,KAC3C,MAAM,MACN,MAAM,KACR,CACF;EACF,CAAC;CACL;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@@
1
- import { n as getActiveConfig } from "./config-8ZqmWTBJ.js";
1
+ import { n as getActiveConfig } from "./config-CFlfvmQ1.js";
2
2
  import { trace } from "@opentelemetry/api";
3
3
 
4
4
  //#region src/events/index.ts
@@ -68,39 +68,43 @@ function createSubscribersInstance(options, bindings = {}) {
68
68
  return deliverResult(options.transport(event), event, delivery, waitUntil, options);
69
69
  };
70
70
  const trackEvent = (eventName, attributes, callOptions) => {
71
- return dispatch({
71
+ const event = {
72
72
  ...createBaseEvent(attributes, options),
73
73
  type: "event",
74
74
  event: eventName,
75
75
  name: eventName
76
- }, callOptions);
76
+ };
77
+ return dispatch(event, callOptions);
77
78
  };
78
79
  const trackFunnelStep = (funnel, status, attributes, callOptions) => {
79
- return dispatch({
80
+ const event = {
80
81
  ...createBaseEvent(attributes, options),
81
82
  type: "funnel-step",
82
83
  funnel,
83
84
  status,
84
85
  name: `funnel-step.${status}`
85
- }, callOptions);
86
+ };
87
+ return dispatch(event, callOptions);
86
88
  };
87
89
  const trackOutcome = (operation, outcome, attributes, callOptions) => {
88
- return dispatch({
90
+ const event = {
89
91
  ...createBaseEvent(attributes, options),
90
92
  type: "outcome",
91
93
  operation,
92
94
  outcome,
93
95
  name: `outcome.${outcome}`
94
- }, callOptions);
96
+ };
97
+ return dispatch(event, callOptions);
95
98
  };
96
99
  const trackValue = (metric, value, attributes, callOptions) => {
97
- return dispatch({
100
+ const event = {
98
101
  ...createBaseEvent(attributes, options),
99
102
  type: "value",
100
103
  metric,
101
104
  value,
102
105
  name: `value.${metric}`
103
- }, callOptions);
106
+ };
107
+ return dispatch(event, callOptions);
104
108
  };
105
109
  return {
106
110
  trackEvent,
@@ -1 +1 @@
1
- {"version":3,"file":"events.js","names":[],"sources":["../src/events/index.ts"],"sourcesContent":["import { trace } from '@opentelemetry/api';\nimport { getActiveConfig } from '../core/config';\nimport type {\n OrPromise,\n EdgeEvent,\n FunnelStepStatus,\n OutcomeStatus,\n EdgeTrackEvent,\n EdgeFunnelStepEvent,\n EdgeOutcomeEvent,\n EdgeValueEvent,\n EdgeEventBase,\n} from '../types';\n\nexport type SubscriberDeliveryMode = 'fire-and-forget' | 'await';\n\n// Re-export event types for convenience\n\n\nexport type EdgeTransport = (event: EdgeEvent) => OrPromise<void>;\n\nexport interface EdgeDispatchOptions {\n delivery?: SubscriberDeliveryMode;\n waitUntil?: (promise: Promise<void>) => void;\n}\n\nexport interface CreateEdgeSubscribersOptions {\n /**\n * User-supplied transport invoked for every Subscribers event.\n * Implementations can call PostHog, Stripe, Zapier, Durable Objects, etc.\n */\n transport: EdgeTransport;\n /**\n * Optional service name used when no request config is active.\n * Defaults to the active instrumentation config's service name or \"edge-service\".\n */\n service?: string;\n /**\n * Default delivery behaviour for transport promises.\n * \"fire-and-forget\" (default) will not block the calling code.\n */\n delivery?: SubscriberDeliveryMode;\n /**\n * Default waitUntil handler (Cloudflare Workers, Vercel waitUntil).\n * Used when delivery === \"fire-and-forget\".\n */\n waitUntil?: (promise: Promise<void>) => void;\n /**\n * Optional error handler invoked when the transport rejects.\n */\n onError?: (error: unknown, event: EdgeEvent) => void;\n /**\n * Include OpenTelemetry trace/span identifiers in the payload. Default true.\n */\n includeTraceContext?: boolean;\n}\n\nexport interface EdgeSubscribers {\n trackEvent(\n event: string,\n attributes?: Record<string, unknown>,\n options?: EdgeDispatchOptions,\n ): OrPromise<void>;\n trackFunnelStep(\n funnel: string,\n status: FunnelStepStatus,\n attributes?: Record<string, unknown>,\n options?: EdgeDispatchOptions,\n ): OrPromise<void>;\n trackOutcome(\n operation: string,\n outcome: OutcomeStatus,\n attributes?: Record<string, unknown>,\n options?: EdgeDispatchOptions,\n ): OrPromise<void>;\n trackValue(\n metric: string,\n value: number,\n attributes?: Record<string, unknown>,\n options?: EdgeDispatchOptions,\n ): OrPromise<void>;\n dispatch(event: EdgeEvent, options?: EdgeDispatchOptions): OrPromise<void>;\n bind(options: EdgeDispatchOptions): EdgeSubscribers;\n}\n\nconst DEFAULT_SERVICE_NAME = 'edge-service';\n\n/**\n * Extract a normalized event name from any EdgeEvent.\n * Useful for subscribers that need to send events to events platforms.\n * \n * @deprecated Use `event.name` directly instead - it's now a property on all events.\n * \n * @example\n * ```typescript\n * const subscriber: EdgeSubscribersAdapter = async (event) => {\n * await sendToEvents(event.name, event.attributes) // Use event.name directly\n * }\n * ```\n */\nexport function getEventName(event: EdgeEvent): string {\n return event.name;\n}\n\nfunction isPromiseLike(value: unknown): value is Promise<unknown> {\n return typeof value === 'object' && value !== null && 'then' in value;\n}\n\nfunction createBaseEvent(\n attributes: Record<string, unknown> | undefined,\n options: CreateEdgeSubscribersOptions,\n): Omit<EdgeEventBase, 'name'> {\n const config = getActiveConfig();\n // Prioritize explicit service override, then config service name, then default\n const serviceName = options.service ?? config?.service.name ?? DEFAULT_SERVICE_NAME;\n const baseAttributes = attributes ? { ...attributes } : {};\n\n const baseEvent: Omit<EdgeEventBase, 'name'> = {\n service: serviceName,\n timestamp: Date.now(),\n attributes: baseAttributes,\n };\n\n if (options.includeTraceContext ?? true) {\n const span = trace.getActiveSpan();\n const spanContext = span?.spanContext();\n if (spanContext) {\n baseEvent.traceId = spanContext.traceId;\n baseEvent.spanId = spanContext.spanId;\n baseEvent.correlationId = spanContext.traceId.slice(0, 16);\n }\n }\n\n return baseEvent;\n}\n\nfunction handleError(\n error: unknown,\n event: EdgeEvent,\n options: CreateEdgeSubscribersOptions,\n): void {\n if (options.onError) {\n try {\n options.onError(error, event);\n return;\n } catch (handlerError) {\n console.error('[autotel-edge] Subscribers onError handler failed', handlerError);\n }\n }\n\n console.error('[autotel-edge] Subscribers transport failed', error, { event });\n}\n\nfunction deliverResult(\n result: OrPromise<void>,\n event: EdgeEvent,\n delivery: SubscriberDeliveryMode,\n waitUntil: EdgeDispatchOptions['waitUntil'],\n createOptions: CreateEdgeSubscribersOptions,\n): OrPromise<void> {\n if (!isPromiseLike(result)) {\n return delivery === 'await' ? Promise.resolve() : undefined;\n }\n\n if (delivery === 'await') {\n return Promise.resolve(result).catch((error) => {\n handleError(error, event, createOptions);\n throw error;\n });\n }\n\n const background = Promise.resolve(result).catch((error) => {\n handleError(error, event, createOptions);\n });\n\n if (waitUntil) {\n waitUntil(background);\n } else {\n void background;\n }\n\n return undefined;\n}\n\nfunction createSubscribersInstance(\n options: CreateEdgeSubscribersOptions,\n bindings: EdgeDispatchOptions = {},\n): EdgeSubscribers {\n const dispatch = (\n event: EdgeEvent,\n callOptions?: EdgeDispatchOptions,\n ): OrPromise<void> => {\n const delivery =\n callOptions?.delivery ??\n bindings.delivery ??\n options.delivery ??\n ('fire-and-forget' as SubscriberDeliveryMode);\n const waitUntil = callOptions?.waitUntil ?? bindings.waitUntil ?? options.waitUntil;\n const result = options.transport(event);\n return deliverResult(result, event, delivery, waitUntil, options);\n };\n\n const trackEvent: EdgeSubscribers['trackEvent'] = (eventName, attributes, callOptions) => {\n const baseEvent = createBaseEvent(attributes, options);\n const event: EdgeTrackEvent = {\n ...baseEvent,\n type: 'event',\n event: eventName,\n name: eventName,\n } as EdgeTrackEvent;\n return dispatch(event, callOptions);\n };\n\n const trackFunnelStep: EdgeSubscribers['trackFunnelStep'] = (\n funnel,\n status,\n attributes,\n callOptions,\n ) => {\n const baseEvent = createBaseEvent(attributes, options);\n const event: EdgeFunnelStepEvent = {\n ...baseEvent,\n type: 'funnel-step',\n funnel,\n status,\n name: `funnel-step.${status}`,\n } as EdgeFunnelStepEvent;\n return dispatch(event, callOptions);\n };\n\n const trackOutcome: EdgeSubscribers['trackOutcome'] = (\n operation,\n outcome,\n attributes,\n callOptions,\n ) => {\n const baseEvent = createBaseEvent(attributes, options);\n const event: EdgeOutcomeEvent = {\n ...baseEvent,\n type: 'outcome',\n operation,\n outcome,\n name: `outcome.${outcome}`,\n } as EdgeOutcomeEvent;\n return dispatch(event, callOptions);\n };\n\n const trackValue: EdgeSubscribers['trackValue'] = (\n metric,\n value,\n attributes,\n callOptions,\n ) => {\n const baseEvent = createBaseEvent(attributes, options);\n const event: EdgeValueEvent = {\n ...baseEvent,\n type: 'value',\n metric,\n value,\n name: `value.${metric}`,\n } as EdgeValueEvent;\n return dispatch(event, callOptions);\n };\n\n return {\n trackEvent,\n trackFunnelStep,\n trackOutcome,\n trackValue,\n dispatch,\n bind: (nextBindings: EdgeDispatchOptions) =>\n createSubscribersInstance(options, { ...bindings, ...nextBindings }),\n };\n}\n\nexport function createEdgeSubscribers(options: CreateEdgeSubscribersOptions): EdgeSubscribers {\n if (typeof options.transport !== 'function') {\n throw new TypeError('createEdgeSubscribers: options.transport is required');\n }\n\n return createSubscribersInstance(options);\n}\n\n/**\n * Get Subscribers instance from active config, bound to the current ExecutionContext.\n * Returns null if Subscribers is not configured.\n *\n * @example\n * ```typescript\n * export default {\n * async fetch(request, env, ctx) {\n * const Subscribers = getEdgeSubscribers(ctx);\n * if (Subscribers) {\n * Subscribers.trackEvent('user.signup', { plan: 'pro' });\n * }\n * return new Response('ok');\n * }\n * }\n * ```\n */\nexport function getEdgeSubscribers(\n ctx?: { waitUntil(promise: Promise<any>): void },\n): EdgeSubscribers | null {\n const config = getActiveConfig();\n if (!config) {\n return null;\n }\n\n const subscribers = config.subscribers ?? [];\n if (subscribers.length === 0) {\n return null;\n }\n\n // Combine all subscribers into a single transport function\n const combinedTransport: EdgeTransport = async (event) => {\n await Promise.all(\n subscribers.map(async (subscriber, index) => {\n try {\n await subscriber(event);\n } catch (error) {\n console.error('[autotel-edge] Subscribers subscriber failed', error, {\n subscriberIndex: index,\n eventType: event.type,\n });\n }\n }),\n );\n };\n\n return createEdgeSubscribers({\n transport: combinedTransport,\n service: config.service.name,\n waitUntil: ctx ? (promise) => ctx.waitUntil(promise) : undefined,\n });\n}\n\n\nexport {type FunnelStepStatus, type OutcomeStatus, type EdgeEvent, type EdgeTrackEvent, type EdgeFunnelStepEvent, type EdgeOutcomeEvent, type EdgeValueEvent} from '../types';"],"mappings":";;;;AAqFA,MAAM,uBAAuB;;;;;;;;;;;;;;AAe7B,SAAgB,aAAa,OAA0B;CACrD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,UAAU;EACxD,MAAM,QAAQ,IACZ,YAAY,IAAI,OAAO,YAAY,UAAU;GAC3C,IAAI;IACF,MAAM,WAAW,KAAK;GACxB,SAAS,OAAO;IACd,QAAQ,MAAM,gDAAgD,OAAO;KACnE,iBAAiB;KACjB,WAAW,MAAM;IACnB,CAAC;GACH;EACF,CAAC,CACH;CACF;CAEA,OAAO,sBAAsB;EAC3B,WAAW;EACX,SAAS,OAAO,QAAQ;EACxB,WAAW,OAAO,YAAY,IAAI,UAAU,OAAO,IAAI;CACzD,CAAC;AACH"}
1
+ {"version":3,"file":"events.js","names":[],"sources":["../src/events/index.ts"],"sourcesContent":["import { trace } from '@opentelemetry/api';\nimport { getActiveConfig } from '../core/config';\nimport type {\n OrPromise,\n EdgeEvent,\n FunnelStepStatus,\n OutcomeStatus,\n EdgeTrackEvent,\n EdgeFunnelStepEvent,\n EdgeOutcomeEvent,\n EdgeValueEvent,\n EdgeEventBase,\n} from '../types';\n\nexport type SubscriberDeliveryMode = 'fire-and-forget' | 'await';\n\n// Re-export event types for convenience\n\n\nexport type EdgeTransport = (event: EdgeEvent) => OrPromise<void>;\n\nexport interface EdgeDispatchOptions {\n delivery?: SubscriberDeliveryMode;\n waitUntil?: (promise: Promise<void>) => void;\n}\n\nexport interface CreateEdgeSubscribersOptions {\n /**\n * User-supplied transport invoked for every Subscribers event.\n * Implementations can call PostHog, Stripe, Zapier, Durable Objects, etc.\n */\n transport: EdgeTransport;\n /**\n * Optional service name used when no request config is active.\n * Defaults to the active instrumentation config's service name or \"edge-service\".\n */\n service?: string;\n /**\n * Default delivery behaviour for transport promises.\n * \"fire-and-forget\" (default) will not block the calling code.\n */\n delivery?: SubscriberDeliveryMode;\n /**\n * Default waitUntil handler (Cloudflare Workers, Vercel waitUntil).\n * Used when delivery === \"fire-and-forget\".\n */\n waitUntil?: (promise: Promise<void>) => void;\n /**\n * Optional error handler invoked when the transport rejects.\n */\n onError?: (error: unknown, event: EdgeEvent) => void;\n /**\n * Include OpenTelemetry trace/span identifiers in the payload. Default true.\n */\n includeTraceContext?: boolean;\n}\n\nexport interface EdgeSubscribers {\n trackEvent(\n event: string,\n attributes?: Record<string, unknown>,\n options?: EdgeDispatchOptions,\n ): OrPromise<void>;\n trackFunnelStep(\n funnel: string,\n status: FunnelStepStatus,\n attributes?: Record<string, unknown>,\n options?: EdgeDispatchOptions,\n ): OrPromise<void>;\n trackOutcome(\n operation: string,\n outcome: OutcomeStatus,\n attributes?: Record<string, unknown>,\n options?: EdgeDispatchOptions,\n ): OrPromise<void>;\n trackValue(\n metric: string,\n value: number,\n attributes?: Record<string, unknown>,\n options?: EdgeDispatchOptions,\n ): OrPromise<void>;\n dispatch(event: EdgeEvent, options?: EdgeDispatchOptions): OrPromise<void>;\n bind(options: EdgeDispatchOptions): EdgeSubscribers;\n}\n\nconst DEFAULT_SERVICE_NAME = 'edge-service';\n\n/**\n * Extract a normalized event name from any EdgeEvent.\n * Useful for subscribers that need to send events to events platforms.\n * \n * @deprecated Use `event.name` directly instead - it's now a property on all events.\n * \n * @example\n * ```typescript\n * const subscriber: EdgeSubscribersAdapter = async (event) => {\n * await sendToEvents(event.name, event.attributes) // Use event.name directly\n * }\n * ```\n */\nexport function getEventName(event: EdgeEvent): string {\n return event.name;\n}\n\nfunction isPromiseLike(value: unknown): value is Promise<unknown> {\n return typeof value === 'object' && value !== null && 'then' in value;\n}\n\nfunction createBaseEvent(\n attributes: Record<string, unknown> | undefined,\n options: CreateEdgeSubscribersOptions,\n): Omit<EdgeEventBase, 'name'> {\n const config = getActiveConfig();\n // Prioritize explicit service override, then config service name, then default\n const serviceName = options.service ?? config?.service.name ?? DEFAULT_SERVICE_NAME;\n const baseAttributes = attributes ? { ...attributes } : {};\n\n const baseEvent: Omit<EdgeEventBase, 'name'> = {\n service: serviceName,\n timestamp: Date.now(),\n attributes: baseAttributes,\n };\n\n if (options.includeTraceContext ?? true) {\n const span = trace.getActiveSpan();\n const spanContext = span?.spanContext();\n if (spanContext) {\n baseEvent.traceId = spanContext.traceId;\n baseEvent.spanId = spanContext.spanId;\n baseEvent.correlationId = spanContext.traceId.slice(0, 16);\n }\n }\n\n return baseEvent;\n}\n\nfunction handleError(\n error: unknown,\n event: EdgeEvent,\n options: CreateEdgeSubscribersOptions,\n): void {\n if (options.onError) {\n try {\n options.onError(error, event);\n return;\n } catch (handlerError) {\n console.error('[autotel-edge] Subscribers onError handler failed', handlerError);\n }\n }\n\n console.error('[autotel-edge] Subscribers transport failed', error, { event });\n}\n\nfunction deliverResult(\n result: OrPromise<void>,\n event: EdgeEvent,\n delivery: SubscriberDeliveryMode,\n waitUntil: EdgeDispatchOptions['waitUntil'],\n createOptions: CreateEdgeSubscribersOptions,\n): OrPromise<void> {\n if (!isPromiseLike(result)) {\n return delivery === 'await' ? Promise.resolve() : undefined;\n }\n\n if (delivery === 'await') {\n return Promise.resolve(result).catch((error) => {\n handleError(error, event, createOptions);\n throw error;\n });\n }\n\n const background = Promise.resolve(result).catch((error) => {\n handleError(error, event, createOptions);\n });\n\n if (waitUntil) {\n waitUntil(background);\n } else {\n void background;\n }\n\n return undefined;\n}\n\nfunction createSubscribersInstance(\n options: CreateEdgeSubscribersOptions,\n bindings: EdgeDispatchOptions = {},\n): EdgeSubscribers {\n const dispatch = (\n event: EdgeEvent,\n callOptions?: EdgeDispatchOptions,\n ): OrPromise<void> => {\n const delivery =\n callOptions?.delivery ??\n bindings.delivery ??\n options.delivery ??\n ('fire-and-forget' as SubscriberDeliveryMode);\n const waitUntil = callOptions?.waitUntil ?? bindings.waitUntil ?? options.waitUntil;\n const result = options.transport(event);\n return deliverResult(result, event, delivery, waitUntil, options);\n };\n\n const trackEvent: EdgeSubscribers['trackEvent'] = (eventName, attributes, callOptions) => {\n const baseEvent = createBaseEvent(attributes, options);\n const event: EdgeTrackEvent = {\n ...baseEvent,\n type: 'event',\n event: eventName,\n name: eventName,\n } as EdgeTrackEvent;\n return dispatch(event, callOptions);\n };\n\n const trackFunnelStep: EdgeSubscribers['trackFunnelStep'] = (\n funnel,\n status,\n attributes,\n callOptions,\n ) => {\n const baseEvent = createBaseEvent(attributes, options);\n const event: EdgeFunnelStepEvent = {\n ...baseEvent,\n type: 'funnel-step',\n funnel,\n status,\n name: `funnel-step.${status}`,\n } as EdgeFunnelStepEvent;\n return dispatch(event, callOptions);\n };\n\n const trackOutcome: EdgeSubscribers['trackOutcome'] = (\n operation,\n outcome,\n attributes,\n callOptions,\n ) => {\n const baseEvent = createBaseEvent(attributes, options);\n const event: EdgeOutcomeEvent = {\n ...baseEvent,\n type: 'outcome',\n operation,\n outcome,\n name: `outcome.${outcome}`,\n } as EdgeOutcomeEvent;\n return dispatch(event, callOptions);\n };\n\n const trackValue: EdgeSubscribers['trackValue'] = (\n metric,\n value,\n attributes,\n callOptions,\n ) => {\n const baseEvent = createBaseEvent(attributes, options);\n const event: EdgeValueEvent = {\n ...baseEvent,\n type: 'value',\n metric,\n value,\n name: `value.${metric}`,\n } as EdgeValueEvent;\n return dispatch(event, callOptions);\n };\n\n return {\n trackEvent,\n trackFunnelStep,\n trackOutcome,\n trackValue,\n dispatch,\n bind: (nextBindings: EdgeDispatchOptions) =>\n createSubscribersInstance(options, { ...bindings, ...nextBindings }),\n };\n}\n\nexport function createEdgeSubscribers(options: CreateEdgeSubscribersOptions): EdgeSubscribers {\n if (typeof options.transport !== 'function') {\n throw new TypeError('createEdgeSubscribers: options.transport is required');\n }\n\n return createSubscribersInstance(options);\n}\n\n/**\n * Get Subscribers instance from active config, bound to the current ExecutionContext.\n * Returns null if Subscribers is not configured.\n *\n * @example\n * ```typescript\n * export default {\n * async fetch(request, env, ctx) {\n * const Subscribers = getEdgeSubscribers(ctx);\n * if (Subscribers) {\n * Subscribers.trackEvent('user.signup', { plan: 'pro' });\n * }\n * return new Response('ok');\n * }\n * }\n * ```\n */\nexport function getEdgeSubscribers(\n ctx?: { waitUntil(promise: Promise<any>): void },\n): EdgeSubscribers | null {\n const config = getActiveConfig();\n if (!config) {\n return null;\n }\n\n const subscribers = config.subscribers ?? [];\n if (subscribers.length === 0) {\n return null;\n }\n\n // Combine all subscribers into a single transport function\n const combinedTransport: EdgeTransport = async (event) => {\n await Promise.all(\n subscribers.map(async (subscriber, index) => {\n try {\n await subscriber(event);\n } catch (error) {\n console.error('[autotel-edge] Subscribers subscriber failed', error, {\n subscriberIndex: index,\n eventType: event.type,\n });\n }\n }),\n );\n };\n\n return createEdgeSubscribers({\n transport: combinedTransport,\n service: config.service.name,\n waitUntil: ctx ? (promise) => ctx.waitUntil(promise) : undefined,\n });\n}\n\n\nexport {type FunnelStepStatus, type OutcomeStatus, type EdgeEvent, type EdgeTrackEvent, type EdgeFunnelStepEvent, type EdgeOutcomeEvent, type EdgeValueEvent} from '../types';"],"mappings":";;;;AAqFA,MAAM,uBAAuB;;;;;;;;;;;;;;AAe7B,SAAgB,aAAa,OAA0B;CACrD,OAAO,MAAM;AACf;AAEA,SAAS,cAAc,OAA2C;CAChE,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,UAAU;AAClE;AAEA,SAAS,gBACP,YACA,SAC6B;CAC7B,MAAM,SAAS,gBAAgB;CAE/B,MAAM,cAAc,QAAQ,WAAW,QAAQ,QAAQ,QAAQ;CAC/D,MAAM,iBAAiB,aAAa,EAAE,GAAG,WAAW,IAAI,CAAC;CAEzD,MAAM,YAAyC;EAC7C,SAAS;EACT,WAAW,KAAK,IAAI;EACpB,YAAY;CACd;CAEA,IAAI,QAAQ,uBAAuB,MAAM;EAEvC,MAAM,cADO,MAAM,cACI,CAAC,EAAE,YAAY;EACtC,IAAI,aAAa;GACf,UAAU,UAAU,YAAY;GAChC,UAAU,SAAS,YAAY;GAC/B,UAAU,gBAAgB,YAAY,QAAQ,MAAM,GAAG,EAAE;EAC3D;CACF;CAEA,OAAO;AACT;AAEA,SAAS,YACP,OACA,OACA,SACM;CACN,IAAI,QAAQ,SACV,IAAI;EACF,QAAQ,QAAQ,OAAO,KAAK;EAC5B;CACF,SAAS,cAAc;EACrB,QAAQ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AEA,MAAM,cACJ,QACA,OACA,YACA,gBACG;EAEH,MAAM,QAAwB;GAC5B,GAFgB,gBAAgB,YAAY,OAEjC;GACX,MAAM;GACN;GACA;GACA,MAAM,SAAS;EACjB;EACA,OAAO,SAAS,OAAO,WAAW;CACpC;CAEA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA,OAAO,iBACL,0BAA0B,SAAS;GAAE,GAAG;GAAU,GAAG;EAAa,CAAC;CACvE;AACF;AAEA,SAAgB,sBAAsB,SAAwD;CAC5F,IAAI,OAAO,QAAQ,cAAc,YAC/B,MAAM,IAAI,UAAU,sDAAsD;CAG5E,OAAO,0BAA0B,OAAO;AAC1C;;;;;;;;;;;;;;;;;;AAmBA,SAAgB,mBACd,KACwB;CACxB,MAAM,SAAS,gBAAgB;CAC/B,IAAI,CAAC,QACH,OAAO;CAGT,MAAM,cAAc,OAAO,eAAe,CAAC;CAC3C,IAAI,YAAY,WAAW,GACzB,OAAO;CAIT,MAAM,oBAAmC,OAAO,UAAU;EACxD,MAAM,QAAQ,IACZ,YAAY,IAAI,OAAO,YAAY,UAAU;GAC3C,IAAI;IACF,MAAM,WAAW,KAAK;GACxB,SAAS,OAAO;IACd,QAAQ,MAAM,gDAAgD,OAAO;KACnE,iBAAiB;KACjB,WAAW,MAAM;IACnB,CAAC;GACH;EACF,CAAC,CACH;CACF;CAEA,OAAO,sBAAsB;EAC3B,WAAW;EACX,SAAS,OAAO,QAAQ;EACxB,WAAW,OAAO,YAAY,IAAI,UAAU,OAAO,IAAI;CACzD,CAAC;AACH"}
@@ -145,7 +145,8 @@ function getExecutionLogger(ctx, options) {
145
145
  activeContext.setAttributes(flattenToAttributes(fields));
146
146
  },
147
147
  info(message, fields) {
148
- sealCheck("log.info()", fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"]);
148
+ const keys = fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"];
149
+ sealCheck("log.info()", keys);
149
150
  if (emitted) return;
150
151
  addLogEvent("info", message, fields);
151
152
  if (fields) {
@@ -154,7 +155,8 @@ function getExecutionLogger(ctx, options) {
154
155
  }
155
156
  },
156
157
  warn(message, fields) {
157
- sealCheck("log.warn()", fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"]);
158
+ const keys = fields ? ["message", ...Object.keys(fields).filter((k) => k !== "requestLogs")] : ["message"];
159
+ sealCheck("log.warn()", keys);
158
160
  if (emitted) return;
159
161
  addLogEvent("warn", message, fields);
160
162
  activeContext.setAttribute("autotel.log.level", "warn");
@@ -164,7 +166,8 @@ function getExecutionLogger(ctx, options) {
164
166
  }
165
167
  },
166
168
  error(error, fields) {
167
- sealCheck("log.error()", fields ? [...Object.keys(fields), "error"] : ["error"]);
169
+ const keys = fields ? [...Object.keys(fields), "error"] : ["error"];
170
+ sealCheck("log.error()", keys);
168
171
  if (emitted) return;
169
172
  const err = typeof error === "string" ? new Error(error) : error;
170
173
  activeContext.recordException(err);
@@ -244,4 +247,4 @@ function getExecutionLogger(ctx, options) {
244
247
 
245
248
  //#endregion
246
249
  export { createTraceContext as n, setSpanName as r, getExecutionLogger as t };
247
- //# sourceMappingURL=execution-logger-CoxSsBmU.js.map
250
+ //# sourceMappingURL=execution-logger-CSW2AyVi.js.map