autotel 4.2.4 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +191 -21
  2. package/README.md +1 -1
  3. package/dist/{functional-BCtxvYir.cjs → functional-CwsPyc4l.cjs} +17 -34
  4. package/dist/functional-CwsPyc4l.cjs.map +1 -0
  5. package/dist/{functional-CrAq8Az8.js → functional-dAYhXQPA.js} +17 -34
  6. package/dist/functional-dAYhXQPA.js.map +1 -0
  7. package/dist/functional.cjs +1 -1
  8. package/dist/functional.d.cts.map +1 -1
  9. package/dist/functional.d.ts.map +1 -1
  10. package/dist/functional.js +1 -1
  11. package/dist/index.cjs +4 -8
  12. package/dist/index.cjs.map +1 -1
  13. package/dist/index.d.cts.map +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +5 -9
  16. package/dist/index.js.map +1 -1
  17. package/dist/messaging.cjs +1 -1
  18. package/dist/messaging.js +1 -1
  19. package/dist/semantic-helpers.cjs +1 -1
  20. package/dist/semantic-helpers.js +1 -1
  21. package/dist/test-span-collector.cjs +13 -1
  22. package/dist/test-span-collector.cjs.map +1 -1
  23. package/dist/test-span-collector.d.cts +8 -0
  24. package/dist/test-span-collector.d.cts.map +1 -1
  25. package/dist/test-span-collector.d.ts +8 -0
  26. package/dist/test-span-collector.d.ts.map +1 -1
  27. package/dist/test-span-collector.js +13 -1
  28. package/dist/test-span-collector.js.map +1 -1
  29. package/dist/tracer-provider.cjs +27 -0
  30. package/dist/tracer-provider.cjs.map +1 -1
  31. package/dist/tracer-provider.d.cts +19 -1
  32. package/dist/tracer-provider.d.cts.map +1 -1
  33. package/dist/tracer-provider.d.ts +19 -1
  34. package/dist/tracer-provider.d.ts.map +1 -1
  35. package/dist/tracer-provider.js +27 -1
  36. package/dist/tracer-provider.js.map +1 -1
  37. package/dist/webhook.cjs +1 -1
  38. package/dist/webhook.js +1 -1
  39. package/dist/workflow-distributed.cjs +1 -1
  40. package/dist/workflow-distributed.js +1 -1
  41. package/dist/workflow.cjs +1 -1
  42. package/dist/workflow.js +1 -1
  43. package/package.json +2 -2
  44. package/dist/functional-BCtxvYir.cjs.map +0 -1
  45. package/dist/functional-CrAq8Az8.js.map +0 -1
package/LICENSE CHANGED
@@ -1,21 +1,191 @@
1
- MIT License
2
-
3
- Copyright (c) 2025 Jag Reehal
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
@@ -2,7 +2,7 @@
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/autotel.svg?label=autotel)](https://www.npmjs.com/package/autotel)
4
4
  [![npm subscribers](https://img.shields.io/npm/v/autotel-subscribers.svg?label=subscribers)](https://www.npmjs.com/package/autotel-subscribers)
5
- [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
5
+ [![License: Apache 2.0](https://img.shields.io/badge/license-Apache_2.0-blue.svg)](LICENSE)
6
6
 
7
7
  **Write once, observe everywhere.** Instrument your Node.js code a single time, keep the DX you love, and stream traces, metrics, logs, and product events to **any** observability stack without vendor lock-in.
8
8
 
@@ -1,4 +1,5 @@
1
1
  const require_rolldown_runtime = require('./rolldown-runtime-C_NdSu1c.cjs');
2
+ const require_tracer_provider = require('./tracer-provider.cjs');
2
3
  const require_config = require('./config.cjs');
3
4
  const require_sampling = require('./sampling.cjs');
4
5
  const require_init = require('./init-BxJEJ9Tn.cjs');
@@ -508,16 +509,10 @@ function wrapWithTracing(fnFactory, options, variableName) {
508
509
  try {
509
510
  const queue = require_track.getEventQueue();
510
511
  if (queue && queue.size() > 0) await queue.flush();
511
- if (shouldAutoFlushSpans) {
512
- const sdk = require_init.getSdk();
513
- if (sdk) try {
514
- const sdkAny = sdk;
515
- if (typeof sdkAny.getTracerProvider === "function") {
516
- const tracerProvider = sdkAny.getTracerProvider();
517
- if (tracerProvider && typeof tracerProvider.forceFlush === "function") await tracerProvider.forceFlush();
518
- }
519
- } catch {}
520
- }
512
+ if (shouldAutoFlushSpans) try {
513
+ const tracerProvider = require_tracer_provider.getForceFlushableProvider(require_init.getSdk());
514
+ if (tracerProvider) await tracerProvider.forceFlush();
515
+ } catch {}
521
516
  } catch (error) {
522
517
  const logger = require_init.getConfig()?.logger;
523
518
  if (logger?.error) logger.error({ err: error instanceof Error ? error : void 0 }, `[autotel] Auto-flush failed${error instanceof Error ? "" : `: ${String(error)}`}`);
@@ -675,19 +670,13 @@ function wrapWithTracingSync(fnFactory, options, variableName) {
675
670
  const logger = require_init.getConfig()?.logger;
676
671
  if (logger?.error) logger.error({ err: error instanceof Error ? error : void 0 }, `[autotel] Auto-flush failed${error instanceof Error ? "" : `: ${String(error)}`}`);
677
672
  });
678
- if (shouldAutoFlushSpans) {
679
- const sdk = require_init.getSdk();
680
- if (sdk) try {
681
- const sdkAny = sdk;
682
- if (typeof sdkAny.getTracerProvider === "function") {
683
- const tracerProvider = sdkAny.getTracerProvider();
684
- if (tracerProvider && typeof tracerProvider.forceFlush === "function") tracerProvider.forceFlush().catch((error) => {
685
- const logger = require_init.getConfig()?.logger;
686
- if (logger?.error) logger.error({ err: error instanceof Error ? error : void 0 }, `[autotel] Span flush failed${error instanceof Error ? "" : `: ${String(error)}`}`);
687
- });
688
- }
689
- } catch {}
690
- }
673
+ if (shouldAutoFlushSpans) try {
674
+ const tracerProvider = require_tracer_provider.getForceFlushableProvider(require_init.getSdk());
675
+ if (tracerProvider) tracerProvider.forceFlush().catch((error) => {
676
+ const logger = require_init.getConfig()?.logger;
677
+ if (logger?.error) logger.error({ err: error instanceof Error ? error : void 0 }, `[autotel] Span flush failed${error instanceof Error ? "" : `: ${String(error)}`}`);
678
+ });
679
+ } catch {}
691
680
  };
692
681
  const spanOptions = {};
693
682
  if (options.startNewRoot) spanOptions.root = true;
@@ -828,16 +817,10 @@ function executeImmediately(fn, options) {
828
817
  try {
829
818
  const queue = require_track.getEventQueue();
830
819
  if (queue && queue.size() > 0) await queue.flush();
831
- if (shouldAutoFlushSpans) {
832
- const sdk = require_init.getSdk();
833
- if (sdk) try {
834
- const sdkAny = sdk;
835
- if (typeof sdkAny.getTracerProvider === "function") {
836
- const tracerProvider = sdkAny.getTracerProvider();
837
- if (tracerProvider && typeof tracerProvider.forceFlush === "function") await tracerProvider.forceFlush();
838
- }
839
- } catch {}
840
- }
820
+ if (shouldAutoFlushSpans) try {
821
+ const tracerProvider = require_tracer_provider.getForceFlushableProvider(require_init.getSdk());
822
+ if (tracerProvider) await tracerProvider.forceFlush();
823
+ } catch {}
841
824
  } catch (error) {
842
825
  const logger = require_init.getConfig()?.logger;
843
826
  if (logger?.error) logger.error({ err: error instanceof Error ? error : void 0 }, `[autotel] Auto-flush failed${error instanceof Error ? "" : `: ${String(error)}`}`);
@@ -1312,4 +1295,4 @@ Object.defineProperty(exports, 'withTracing', {
1312
1295
  return withTracing;
1313
1296
  }
1314
1297
  });
1315
- //# sourceMappingURL=functional-BCtxvYir.cjs.map
1298
+ //# sourceMappingURL=functional-CwsPyc4l.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"functional-CwsPyc4l.cjs","names":["nodeUrl","nodeFs","otelTrace","createTraceContext","getConfig","AlwaysSampler","getInitConfig","getEventQueue","getForceFlushableProvider","getSdk","getActiveContextWithBaggage","runInOperationContext","context","getContextStorage","AUTOTEL_SAMPLING_TAIL_KEEP","AUTOTEL_SAMPLING_TAIL_EVALUATED","SpanStatusCode","propagation"],"sources":["../src/variable-name-inference.ts","../src/functional.ts"],"sourcesContent":["/**\n * Variable Name Inference Utility\n *\n * Attempts to infer variable names from const/export const assignments\n * by analyzing the call stack and parsing source code.\n *\n * This is a best-effort approach with graceful degradation - if inference\n * fails for any reason, it returns undefined without breaking the application.\n */\n\n// namespace imports for browser-bundler compat — see node-require.ts\nimport * as nodeFs from 'node:fs';\nimport * as nodeUrl from 'node:url';\n\ninterface CallLocation {\n file: string;\n line: number;\n column: number;\n}\n\n/**\n * LRU Cache for inferred variable names\n * Key: \"file:line\" (e.g., \"/path/to/file.ts:42\")\n * Value: inferred variable name or undefined\n */\nconst inferenceCache = new Map<string, string | undefined>();\nconst MAX_CACHE_SIZE = 50;\n\n/**\n * Captures the current call stack\n */\nfunction captureStackTrace(): string {\n const originalStackTraceLimit = Error.stackTraceLimit;\n Error.stackTraceLimit = 10; // Only need first few frames\n\n const err = new Error('Stack trace capture');\n const stack = err.stack || '';\n\n Error.stackTraceLimit = originalStackTraceLimit;\n return stack;\n}\n\n/**\n * Parses the stack trace to find where trace() was called\n *\n * Stack trace format (Node.js):\n * at functionName (file:line:column)\n * at file:line:column\n *\n * We skip frames until we find one that's NOT in functional.ts or this file.\n * We also need to skip one additional frame (the trace/span/instrument function itself)\n * to get to the actual user code.\n */\nfunction parseCallLocation(stack: string): CallLocation | undefined {\n const lines = stack.split('\\n');\n let skippedExternalFrame = false;\n\n for (const line of lines) {\n // Skip if line contains this file or functional.ts (internal frames)\n // Be specific about the filename to avoid matching test files\n if (\n line.includes('variable-name-inference.ts') ||\n line.includes('variable-name-inference.js') ||\n line.includes('functional.ts') ||\n line.includes('functional.js')\n ) {\n continue;\n }\n\n // Match various stack trace formats\n // Format 1: at functionName (file:line:column)\n // Format 2: at file:line:column\n const match =\n line.match(/at\\s+(?:.*\\s+)?\\(?([^:]+):(\\d+):(\\d+)\\)?/) ||\n line.match(/^.*?([^:]+):(\\d+):(\\d+)/);\n\n if (match) {\n let filePath = match[1]!.trim();\n\n // Handle file:// URLs (convert to paths)\n if (filePath.startsWith('file://')) {\n try {\n filePath = nodeUrl.fileURLToPath(filePath);\n } catch {\n continue;\n }\n }\n\n // Skip the first external frame (the trace/span function itself)\n // We want the frame where the user CALLS trace(), not inside trace()\n if (!skippedExternalFrame) {\n skippedExternalFrame = true;\n continue;\n }\n\n return {\n file: filePath,\n line: Number.parseInt(match[2]!, 10),\n column: Number.parseInt(match[3]!, 10),\n };\n }\n }\n\n return undefined;\n}\n\n/**\n * Reads a specific line from a source file\n */\nfunction readSourceLine(\n filePath: string,\n lineNumber: number,\n): string | undefined {\n try {\n // Check if we can access the file system (not available in edge runtimes)\n if (typeof nodeFs.readFileSync !== 'function') {\n return undefined;\n }\n\n const content = nodeFs.readFileSync(filePath, 'utf8');\n const lines = content.split('\\n');\n\n // Line numbers are 1-based\n return lines[lineNumber - 1];\n } catch {\n // File doesn't exist, permission denied, or other error\n return undefined;\n }\n}\n\n/**\n * Extracts variable name from source code line using regex patterns\n *\n * Supported patterns:\n * - const varName = anyFunction(\n * - export const varName = anyFunction(\n * - let varName = anyFunction(\n * - var varName = anyFunction(\n *\n * Note: This won't work with destructuring assignments or complex patterns\n */\nfunction extractVariableName(sourceLine: string): string | undefined {\n // Remove leading/trailing whitespace\n const trimmed = sourceLine.trim();\n\n // Pattern: (export)? (const|let|var) varName = anyFunctionCall(\n // We match any function call, not just trace(), to support wrapper functions\n const patterns = [\n // export const varName = anyFunction(\n /export\\s+const\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // const varName = anyFunction(\n /const\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // export let varName = anyFunction(\n /export\\s+let\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // let varName = anyFunction(\n /let\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // export var varName = anyFunction(\n /export\\s+var\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n // var varName = anyFunction(\n /var\\s+([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*=\\s*[a-zA-Z_$][a-zA-Z0-9_$]*\\s*\\(/,\n ];\n\n for (const pattern of patterns) {\n const match = trimmed.match(pattern);\n if (match && match[1]) {\n return match[1];\n }\n }\n\n return undefined;\n}\n\n/**\n * Adds an entry to the cache with LRU eviction\n */\nfunction cacheInference(key: string, value: string | undefined): void {\n // If cache is full, remove oldest entry (first entry in Map)\n if (inferenceCache.size >= MAX_CACHE_SIZE) {\n const firstKey = inferenceCache.keys().next().value;\n if (firstKey) {\n inferenceCache.delete(firstKey);\n }\n }\n\n inferenceCache.set(key, value);\n}\n\n/**\n * Main entry point: Attempts to infer the variable name from the call stack\n *\n * This function:\n * 1. Captures the call stack\n * 2. Parses it to find where trace() was called (file + line)\n * 3. Reads that line from the source file\n * 4. Extracts the variable name using regex\n *\n * Returns undefined if inference fails at any step (graceful degradation).\n * Results are cached to avoid repeated file I/O.\n *\n * @returns The inferred variable name, or undefined if inference failed\n */\nexport function inferVariableNameFromCallStack(): string | undefined {\n try {\n // Capture stack trace\n const stack = captureStackTrace();\n\n // Parse stack to find trace() call location\n const callLocation = parseCallLocation(stack);\n if (!callLocation) {\n return undefined;\n }\n\n // Check cache\n const cacheKey = `${callLocation.file}:${callLocation.line}`;\n if (inferenceCache.has(cacheKey)) {\n return inferenceCache.get(cacheKey);\n }\n\n // Read source line\n const sourceLine = readSourceLine(callLocation.file, callLocation.line);\n if (!sourceLine) {\n return undefined;\n }\n\n // Extract variable name\n const variableName = extractVariableName(sourceLine);\n\n // Cache result (even if undefined, to avoid repeated failed attempts)\n cacheInference(cacheKey, variableName);\n\n return variableName;\n } catch {\n // Graceful degradation - don't break the app if inference fails\n return undefined;\n }\n}\n\n/**\n * Clears the inference cache (useful for testing)\n */\nexport function clearInferenceCache(): void {\n inferenceCache.clear();\n}\n","/**\n * Functional API for non-class code\n *\n * Three approaches for different use cases:\n * 1. trace() - Zero-ceremony HOF for single functions\n * 2. withTracing() - Middleware-style composable wrapper\n * 3. instrument() - Batch auto-instrumentation for modules\n *\n * @example trace() - Single function\n * ```typescript\n * export const createUser = trace(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example withTracing() - Composable middleware\n * ```typescript\n * export const createUser = withTracing({\n * name: 'user.create'\n * })(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example instrument() - Batch instrumentation\n * ```typescript\n * export default instrument({\n * createUser: async (data) => { },\n * updateUser: async (id, data) => { }\n * }, { serviceName: 'user' })\n * ```\n */\n\nimport {\n SpanStatusCode,\n trace as otelTrace,\n context,\n propagation,\n type Span,\n} from '@opentelemetry/api';\nimport { getConfig } from './config';\nimport { getConfig as getInitConfig, getSdk } from './init';\nimport { getForceFlushableProvider } from './tracer-provider';\nimport {\n type Sampler,\n type SamplingContext,\n AlwaysSampler,\n AUTOTEL_SAMPLING_TAIL_KEEP,\n AUTOTEL_SAMPLING_TAIL_EVALUATED,\n} from './sampling';\nimport { getEventQueue } from './track';\nimport type { TraceContext } from './trace-context';\nimport {\n createTraceContext,\n enterOrRun,\n getActiveContextWithBaggage,\n getContextStorage,\n} from './trace-context';\nimport { setSpanName } from './trace-helpers';\nimport { runInOperationContext } from './operation-context';\nimport { inferVariableNameFromCallStack } from './variable-name-inference';\n\n/**\n * Complete trace context containing trace identifiers and span methods\n *\n * The ctx parameter in trace() functions provides:\n * - traceId, spanId, correlationId from the active span\n * - Span manipulation methods (setAttribute, setAttributes, setStatus, recordException)\n *\n * For custom context, access it directly in your functions (standard OpenTelemetry pattern).\n *\n * @example\n * ```typescript\n * import { trace } from 'autotel'\n *\n * export const createUser = trace(ctx => async (data: CreateUserData) => {\n * // Get custom context directly (standard OTel approach)\n * const userId = getCurrentUserId()\n * const tenantId = getCurrentTenant()\n *\n * // Use ctx for span operations and trace IDs\n * ctx.setAttribute('user.id', data.id)\n * ctx.setAttribute('user.tenant', tenantId)\n * console.log(ctx.traceId) // Trace IDs available\n * })\n * ```\n */\nexport type { TraceContext } from './trace-context';\n\n/**\n * Helper type to extract function signature from factory pattern\n * This helps TypeScript infer types correctly for factory functions\n */\ntype ExtractFunctionSignature<T> = T extends (ctx: TraceContext) => infer F\n ? F extends (...args: infer Args) => infer Return\n ? (...args: Args) => Return\n : never\n : never;\n\n/**\n * Helper type to exclude functions that return functions from immediate execution overloads\n */\ntype ExcludeFactoryReturn<T> = T extends (ctx: TraceContext) => infer F\n ? // eslint-disable-next-line @typescript-eslint/no-explicit-any\n F extends (...args: any[]) => any\n ? never\n : T\n : T;\n\ntype GenericFunction = (...args: unknown[]) => unknown;\n\nconst FACTORY_NAME_HINTS = new Set([\n 'ctx',\n '_ctx',\n 'context',\n 'tracecontext',\n 'tracectx',\n]);\nconst TRACE_FACTORY_SET = new WeakSet<object>();\n\nconst SINGLE_LINE_COMMENT_REGEX = /\\/\\/.*$/gm;\nconst MULTI_LINE_COMMENT_REGEX = /\\/\\*[\\s\\S]*?\\*\\//gm;\nconst PARAM_TOKEN_SANITIZE_REGEX = new RegExp(String.raw`[{}\\[\\]\\s]`, 'g');\n\nfunction markAsTraceFactory(fn: object): void {\n TRACE_FACTORY_SET.add(fn);\n}\n\nfunction hasFactoryMark(fn: object): boolean {\n return TRACE_FACTORY_SET.has(fn);\n}\n\nfunction sanitizeParameterToken(token: string): string {\n const [firstToken] = token.split('=');\n return (firstToken ?? '').replaceAll(PARAM_TOKEN_SANITIZE_REGEX, '').trim();\n}\n\nfunction getFirstParameterToken(fn: GenericFunction): string | null {\n let source = Function.prototype.toString.call(fn);\n source = source\n .replaceAll(MULTI_LINE_COMMENT_REGEX, '')\n .replaceAll(SINGLE_LINE_COMMENT_REGEX, '')\n .trim();\n\n // Arrow functions\n const arrowMatch = source.match(\n /^(?:async\\s*)?(?:\\(([^)]*)\\)|([^=()]+))\\s*=>/,\n );\n if (arrowMatch) {\n const params = (arrowMatch[1] ?? arrowMatch[2] ?? '').split(',');\n const first = params[0]?.trim();\n if (first) {\n return sanitizeParameterToken(first);\n }\n return null;\n }\n\n // Function declarations/expressions\n const functionMatch = source.match(/^[^(]*\\(([^)]*)\\)/);\n if (functionMatch) {\n const params = functionMatch[1]?.split(',');\n const first = params?.[0]?.trim();\n if (first) {\n return sanitizeParameterToken(first);\n }\n }\n\n return null;\n}\n\n/**\n * Symbol that explicitly marks a function as immediate-execution-with-ctx\n * (`(ctx) => result`), bypassing parameter-name introspection. Library\n * authors who wrap user handlers — like `autotel-aws/lambda`'s `wrapHandler`\n * — should mark their inner trace function with this so dispatch survives\n * downstream bundlers that minify parameter names.\n */\nconst IMMEDIATE_EXECUTION_SYMBOL = Symbol.for('autotel.immediate-execution');\n\ntype ImmediateExecutionFlag = {\n [IMMEDIATE_EXECUTION_SYMBOL]?: true;\n};\n\nfunction hasImmediateExecutionMark(fn: unknown): boolean {\n return (\n typeof fn === 'function' &&\n (fn as ImmediateExecutionFlag)[IMMEDIATE_EXECUTION_SYMBOL] === true\n );\n}\n\n/**\n * Mark a function as immediate-execution-with-ctx so `trace(name, fn)`\n * dispatch doesn't depend on the first parameter being named `ctx`.\n *\n * Necessary when the function will be bundled by a minifier (esbuild,\n * terser, etc.) that renames identifiers. The name-allowlist heuristic in\n * `looksLikeTraceFactory` cannot recover from that; the marker can.\n *\n * @example\n * ```ts\n * import { markAsImmediate, trace } from 'autotel';\n *\n * const inner = markAsImmediate(async (ctx) => {\n * ctx.setAttribute('user.id', '123');\n * return { ok: true };\n * });\n * const result = await trace('user.read', inner);\n * ```\n */\nexport function markAsImmediate<F>(fn: F): F {\n if (typeof fn === 'function') {\n (fn as unknown as ImmediateExecutionFlag)[IMMEDIATE_EXECUTION_SYMBOL] =\n true;\n }\n return fn;\n}\n\nfunction looksLikeTraceFactory(fn: GenericFunction): boolean {\n if (hasFactoryMark(fn)) {\n return true;\n }\n if (hasImmediateExecutionMark(fn)) {\n return true;\n }\n\n if (fn.length === 0) {\n if (!isAsyncFunction(fn)) {\n try {\n const result = fn();\n return typeof result === 'function';\n } catch {\n return false;\n }\n }\n return false;\n }\n\n const firstParam = getFirstParameterToken(fn);\n if (!firstParam) {\n return false;\n }\n\n const normalized = firstParam.toLowerCase();\n if (\n FACTORY_NAME_HINTS.has(normalized) ||\n normalized.startsWith('ctx') ||\n normalized.startsWith('_ctx') ||\n normalized.startsWith('trace') ||\n normalized.endsWith('ctx') || // Match baseCtx, spanCtx, etc.\n normalized.includes('context') // Match traceContext, spanContext, etc.\n ) {\n return true;\n }\n\n return false;\n}\n\n/**\n * Check if a function that takes ctx returns another function (factory pattern)\n * vs returning a value directly (immediate execution pattern)\n *\n * IMPORTANT: For async functions, we skip probing entirely and assume immediate execution.\n * This is because:\n * - Factory pattern: `(ctx) => async (...args) => result` - outer function is SYNC\n * - Immediate execution: `async (ctx) => result` - function itself is ASYNC\n *\n * Probing async functions by executing them causes side effects (like creating orphan spans)\n * because the async function starts executing synchronously until the first await.\n */\nfunction isFactoryReturningFunction(\n fnWithCtx: (ctx: TraceContext) => unknown,\n): boolean {\n // Async functions with ctx parameter are always immediate execution\n // because factory patterns have a sync outer function that returns the async inner\n if (isAsyncFunction(fnWithCtx)) {\n return false;\n }\n\n try {\n const result = fnWithCtx(createDummyCtx());\n return typeof result === 'function';\n } catch {\n // If the function throws when called with dummy ctx, assume it's immediate execution\n // since factory functions typically just return a function and don't execute logic\n return false;\n }\n}\n\nfunction isTraceFactoryFunction<TArgs extends unknown[], TReturn>(\n fn:\n | ((...args: TArgs) => TReturn)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn),\n): fn is (ctx: TraceContext) => (...args: TArgs) => TReturn {\n if (typeof fn !== 'function') {\n return false;\n }\n\n if (hasFactoryMark(fn)) {\n return true;\n }\n\n if (looksLikeTraceFactory(fn as GenericFunction)) {\n markAsTraceFactory(fn);\n return true;\n }\n\n return false;\n}\n\nfunction ensureTraceFactory<TArgs extends unknown[], TReturn>(\n fnOrFactory:\n | ((...args: TArgs) => TReturn | Promise<TReturn>)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn | Promise<TReturn>),\n): (ctx: TraceContext) => (...args: TArgs) => TReturn | Promise<TReturn> {\n if (isTraceFactoryFunction(fnOrFactory)) {\n return fnOrFactory;\n }\n\n const plainFn = fnOrFactory as (...args: TArgs) => TReturn | Promise<TReturn>;\n const factory = (ctx: TraceContext) => {\n void ctx;\n return plainFn;\n };\n markAsTraceFactory(factory);\n return factory;\n}\n\ntype WrappedFunction<TArgs extends unknown[], TReturn> = (\n ...args: TArgs\n) => TReturn | Promise<TReturn>;\n\nfunction wrapFactoryWithTracing<TArgs extends unknown[], TReturn>(\n fnOrFactory:\n | ((...args: TArgs) => TReturn | Promise<TReturn>)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn | Promise<TReturn>),\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): WrappedFunction<TArgs, TReturn> {\n const factory = ensureTraceFactory(fnOrFactory);\n\n // Get the inner function (the actual function being traced)\n const sampleFn = factory(createDummyCtx());\n\n // Infer function name with priority:\n // 1. Explicit variable name (from instrument() or explicit name parameter)\n // 2. Inner function name (named function expressions - e.g., \"async function createUser\")\n // 3. Variable name from call stack (inferred from const assignment, for arrow functions)\n // 4. Factory function name (for cases where factory itself is named)\n const innerFunctionName = inferFunctionName(\n sampleFn as InstrumentableFunction,\n );\n const callStackVariableName = innerFunctionName\n ? undefined\n : inferVariableNameFromCallStack(); // Only infer from call stack if no inner function name\n const factoryName = inferFunctionName(factory as InstrumentableFunction);\n const effectiveVariableName =\n variableName || innerFunctionName || callStackVariableName || factoryName;\n\n const useAsyncWrapper = isAsyncFunction(sampleFn);\n\n if (useAsyncWrapper) {\n return wrapWithTracing(\n factory as (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n options,\n effectiveVariableName,\n ) as WrappedFunction<TArgs, TReturn>;\n }\n\n return wrapWithTracingSync(\n factory as (ctx: TraceContext) => (...args: TArgs) => TReturn,\n options,\n effectiveVariableName,\n ) as WrappedFunction<TArgs, TReturn>;\n}\n\n/**\n * Common options for functional tracing\n */\nexport interface TracingOptions<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n> {\n /**\n * Span name (highest priority)\n * If provided, this is used as the span name\n */\n name?: string;\n\n /**\n * Service name (used to compose final span name)\n * If name not provided, span name becomes: ${serviceName}.${functionName}\n */\n serviceName?: string;\n\n /**\n * Sampling strategy\n * @default AlwaysSampler\n */\n sampler?: Sampler;\n\n /**\n * Enable metrics collection (counter, histogram)\n * @default false\n */\n withMetrics?: boolean;\n\n /**\n * Extract attributes from function arguments\n */\n attributesFromArgs?: (args: TArgs) => Record<string, unknown>;\n\n /**\n * Extract attributes from function result\n */\n attributesFromResult?: (result: TReturn) => Record<string, unknown>;\n\n /**\n * Capture the function arguments onto the span as `autotel.input`\n * (JSON, truncated). One arg is captured directly; multiple are captured as\n * an array. Off by default — opt in per call. Tools (visualizers, devtools)\n * read this alongside `ai.toolCall.args` to show function I/O uniformly.\n * Avoid on args with secrets/PII, or pair with a redacting processor.\n */\n captureInput?: boolean;\n\n /**\n * Capture the function return value onto the span as `autotel.output`\n * (JSON, truncated). Off by default. Same caveats as {@link captureInput}.\n */\n captureOutput?: boolean;\n\n /**\n * Start a new root span instead of creating a child\n * Useful for serverless entry points\n * @default false\n */\n startNewRoot?: boolean;\n\n /**\n * Flush events queue when span ends\n * Only flushes on root spans (to avoid excessive flushing)\n * @default true\n */\n flushOnRootSpanEnd?: boolean;\n\n /**\n * Span kind for semantic convention compliance\n * Used for messaging (PRODUCER/CONSUMER), HTTP (CLIENT/SERVER), etc.\n * @default SpanKind.INTERNAL\n */\n spanKind?: import('@opentelemetry/api').SpanKind;\n}\n\n/**\n * Options for instrument() batch instrumentation\n */\nexport interface InstrumentOptions<\n T extends Record<string, InstrumentableFunction> = Record<\n string,\n InstrumentableFunction\n >,\n> extends TracingOptions {\n /** Functions to instrument */\n functions: T;\n /**\n * Per-function configuration overrides\n */\n overrides?: Record<string, Partial<TracingOptions>>;\n\n /**\n * Functions to skip (won't be instrumented)\n * Supports:\n * - String keys: 'functionName'\n * - RegExp: /^_internal/\n * - Predicate: (key, fn) => boolean\n *\n * By default, functions starting with _ are skipped\n */\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n skip?: (string | RegExp | ((key: string, fn: Function) => boolean))[];\n}\n\n// Maximum error message length to prevent span bloat\nconst MAX_ERROR_MESSAGE_LENGTH = 500;\n\nfunction createDummyCtx<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> {\n // `recordException` / `addEvent` are no-op shims kept for the same\n // compatibility window as `createTraceContext` (see trace-context.ts).\n return {\n traceId: '',\n spanId: '',\n correlationId: '',\n setAttribute: () => {},\n setAttributes: () => {},\n setStatus: () => {},\n recordException: () => {},\n addEvent: () => {},\n addLink: () => {},\n addLinks: () => {},\n updateName: () => {},\n isRecording: () => false,\n getBaggage: () => {},\n setBaggage: () => '',\n deleteBaggage: () => {},\n getAllBaggage: () => new Map(),\n } as unknown as TraceContext<TBaggage>;\n}\n\n/** Attribute keys for opt-in function I/O capture (see TracingOptions). */\nconst AUTOTEL_INPUT_ATTR = 'autotel.input';\nconst AUTOTEL_OUTPUT_ATTR = 'autotel.output';\nconst CAPTURE_MAX_CHARS = 4096;\n\n/** JSON-serialize a captured value, defensively (truncate, swallow cycles). */\nfunction serializeCapture(value: unknown): string | undefined {\n if (value === undefined) return undefined;\n try {\n const json = typeof value === 'string' ? value : JSON.stringify(value);\n if (json === undefined) return undefined;\n return json.length > CAPTURE_MAX_CHARS\n ? `${json.slice(0, CAPTURE_MAX_CHARS)}…[truncated]`\n : json;\n } catch {\n return undefined;\n }\n}\n\n/** `autotel.input` from args (single arg captured directly, else the array). */\nfunction captureInputAttrs(\n args: unknown[],\n enabled?: boolean,\n): Record<string, unknown> {\n if (!enabled) return {};\n const s = serializeCapture(args.length === 1 ? args[0] : args);\n return s === undefined ? {} : { [AUTOTEL_INPUT_ATTR]: s };\n}\n\n/** `autotel.output` from the return value. */\nfunction captureOutputAttrs(\n result: unknown,\n enabled?: boolean,\n): Record<string, unknown> {\n if (!enabled) return {};\n const s = serializeCapture(result);\n return s === undefined ? {} : { [AUTOTEL_OUTPUT_ATTR]: s };\n}\n\nfunction isAsyncFunction(fn: unknown): boolean {\n return typeof fn === 'function' && fn.constructor?.name === 'AsyncFunction';\n}\n\n// Symbol to prevent double-instrumentation (idempotency flag)\nconst INSTRUMENTED_SYMBOL = Symbol.for('autotel.functional.instrumented');\n\ntype InstrumentedFlag = {\n [INSTRUMENTED_SYMBOL]?: true;\n};\n\nfunction hasInstrumentationFlag(value: unknown): value is InstrumentedFlag {\n return (\n (typeof value === 'function' || typeof value === 'object') &&\n value !== null &&\n Boolean((value as InstrumentedFlag)[INSTRUMENTED_SYMBOL])\n );\n}\n\n/**\n * Truncate error message to prevent span bloat\n */\nfunction truncateErrorMessage(message: string): string {\n if (message.length <= MAX_ERROR_MESSAGE_LENGTH) {\n return message;\n }\n return `${message.slice(0, MAX_ERROR_MESSAGE_LENGTH)}... (truncated)`;\n}\n\ntype InstrumentableFunction<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n> = ((...args: TArgs) => TReturn | Promise<TReturn>) & {\n displayName?: string;\n name?: string;\n};\n\n/**\n * Try to infer function name from function properties\n * Checks for displayName, name, or other metadata that might be set\n */\nfunction inferFunctionName<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n>(fn: InstrumentableFunction<TArgs, TReturn>): string | undefined {\n // Check for displayName property (sometimes set by bundlers)\n const displayName = (fn as { displayName?: string }).displayName;\n if (displayName) {\n return displayName;\n }\n\n // Check function.name (works for named functions and modern arrow function assignment)\n // Note: Empty string is falsy, so this handles both undefined and ''\n if (fn.name && fn.name !== 'anonymous' && fn.name !== '') {\n return fn.name;\n }\n\n // Try to extract name from function source (for function declarations)\n const source = Function.prototype.toString.call(fn);\n const match = source.match(/function\\s+([^(\\s]+)/);\n if (match && match[1] && match[1] !== 'anonymous') {\n return match[1];\n }\n\n return undefined;\n}\n\n/**\n * Determine span name using priority:\n * 1. Explicit name option\n * 2. serviceName + functionName\n * 3. Inferred from function/variable name (including stack trace fallback)\n * 4. Fallback to 'unknown'\n */\nfunction getSpanName<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fn: InstrumentableFunction<TArgs, TReturn>,\n variableName?: string,\n): string {\n // 1. Explicit name\n if (options.name) {\n return options.name;\n }\n\n // 2. Try variable name, function name, or function properties\n let fnName = variableName || inferFunctionName(fn);\n\n // Default to 'anonymous' if still no name\n fnName = fnName || 'anonymous';\n\n // 2. serviceName + functionName\n if (options.serviceName) {\n return `${options.serviceName}.${fnName}`;\n }\n\n // 3. Inferred from function name\n if (fnName && fnName !== 'anonymous') {\n return fnName;\n }\n\n // 4. Fallback\n return 'unknown';\n}\n\n/**\n * Check if function should be skipped\n */\nfunction shouldSkip(\n key: string,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n fn: Function,\n // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type\n skip?: (string | RegExp | ((key: string, fn: Function) => boolean))[],\n): boolean {\n // Default: skip functions starting with _\n if (key.startsWith('_')) {\n return true;\n }\n\n if (!skip || skip.length === 0) {\n return false;\n }\n\n for (const rule of skip) {\n if (typeof rule === 'string' && key === rule) {\n return true;\n } else if (rule instanceof RegExp && rule.test(key)) {\n return true;\n } else if (typeof rule === 'function' && rule(key, fn)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Get current trace context value (internal helper)\n *\n * Returns base context (trace IDs) + span methods from the active span.\n */\nfunction getCtxValue<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(): TraceContext<TBaggage> | null {\n const activeSpan = otelTrace.getActiveSpan();\n if (!activeSpan) return null;\n\n // Use shared utility to create trace context\n return createTraceContext<TBaggage>(activeSpan);\n}\n\n/**\n * Context object that lazily evaluates the active span on property access\n *\n * Access trace context directly without function call syntax.\n *\n * @example\n * ```typescript\n * import { trace, ctx } from 'autotel'\n *\n * export const createUser = trace(async (data) => {\n * // Direct property access - no function call!\n * if (ctx.traceId) {\n * ctx.setAttribute('user.id', data.id)\n * console.log('Trace:', ctx.traceId)\n * }\n * })\n * ```\n */\nexport const ctx = new Proxy(\n {},\n {\n get(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return;\n }\n return ctxValue[prop as keyof typeof ctxValue];\n },\n\n has(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return false;\n }\n return prop in ctxValue;\n },\n\n ownKeys() {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return [];\n }\n return Object.keys(ctxValue);\n },\n\n getOwnPropertyDescriptor(_target, prop) {\n const ctxValue = getCtxValue();\n if (!ctxValue) {\n return;\n }\n return Object.getOwnPropertyDescriptor(ctxValue, prop);\n },\n },\n);\n\n/**\n * Core tracing wrapper for async functions (internal implementation)\n */\nfunction wrapWithTracing<TArgs extends unknown[], TReturn>(\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): (...args: TArgs) => Promise<TReturn> {\n // Idempotency check: if already instrumented, return as-is\n if (hasInstrumentationFlag(fnFactory)) {\n // Already instrumented - proceed\n }\n\n const config = getConfig();\n const tracer = config.tracer;\n const meter = config.meter;\n const sampler = options.sampler || new AlwaysSampler();\n\n const tempFn = fnFactory(createDummyCtx());\n const spanName = getSpanName(options, tempFn, variableName);\n\n const callCounter = options.withMetrics\n ? meter.createCounter(`${spanName}.calls`, {\n description: `Call count for ${spanName}`,\n unit: '1',\n })\n : undefined;\n\n const durationHistogram = options.withMetrics\n ? meter.createHistogram(`${spanName}.duration`, {\n description: `Duration for ${spanName}`,\n unit: 'ms',\n })\n : undefined;\n\n const wrappedFunction = async function wrappedFunction(\n this: unknown,\n ...args: TArgs\n ): Promise<TReturn> {\n const samplingContext: SamplingContext = {\n operationName: spanName,\n args,\n metadata: {},\n };\n\n const shouldSample = sampler.shouldSample(samplingContext);\n const needsTailSampling =\n 'needsTailSampling' in sampler &&\n typeof sampler.needsTailSampling === 'function'\n ? sampler.needsTailSampling()\n : false;\n\n if (!shouldSample && !needsTailSampling) {\n const fn = fnFactory(createDummyCtx());\n return await fn.call(this, ...args);\n }\n\n const startTime = performance.now();\n const isRootSpan =\n options.startNewRoot || otelTrace.getActiveSpan() === undefined;\n const shouldAutoFlush =\n options.flushOnRootSpanEnd ?? getInitConfig()?.flushOnRootSpanEnd ?? true;\n const shouldAutoFlushSpans = getInitConfig()?.forceFlushOnShutdown ?? false;\n\n const flushIfNeeded = async () => {\n if (!shouldAutoFlush || !isRootSpan) return;\n\n try {\n // Flush events queue\n const queue = getEventQueue();\n if (queue && queue.size() > 0) {\n await queue.flush();\n }\n\n // Flush OpenTelemetry spans if enabled\n if (shouldAutoFlushSpans) {\n try {\n const tracerProvider = getForceFlushableProvider(getSdk());\n if (tracerProvider) {\n await tracerProvider.forceFlush();\n }\n } catch {\n // Ignore errors when accessing tracer provider (may not be available in test mocks)\n }\n }\n } catch (error) {\n const initConfig = getInitConfig();\n const logger = initConfig?.logger;\n if (logger?.error) {\n logger.error(\n {\n err: error instanceof Error ? error : undefined,\n },\n `[autotel] Auto-flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n }\n };\n\n // Build span options including root and kind\n const spanOptions: import('@opentelemetry/api').SpanOptions = {};\n if (options.startNewRoot) {\n spanOptions.root = true;\n }\n if (options.spanKind !== undefined) {\n spanOptions.kind = options.spanKind;\n }\n\n const parentContext = getActiveContextWithBaggage();\n return tracer.startActiveSpan(\n spanName,\n spanOptions,\n parentContext,\n async (span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(spanName, async () => {\n let shouldKeepSpan = true;\n\n setSpanName(span, spanName);\n\n // Initialize context storage with the active context BEFORE creating trace context\n const initialContext = context.active();\n const contextStorage = getContextStorage();\n if (!contextStorage.getStore()) {\n enterOrRun(contextStorage, initialContext);\n }\n\n const ctxValue = createTraceContext(span);\n const fn = fnFactory(ctxValue);\n const argsAttributes = {\n ...captureInputAttrs(args, options.captureInput),\n ...(options.attributesFromArgs\n ? options.attributesFromArgs(args)\n : {}),\n };\n\n const handleTailSampling = (\n success: boolean,\n duration: number,\n error?: unknown,\n ) => {\n if (\n needsTailSampling &&\n 'shouldKeepTrace' in sampler &&\n typeof sampler.shouldKeepTrace === 'function'\n ) {\n shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {\n success,\n duration,\n error,\n });\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_KEEP, shouldKeepSpan);\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_EVALUATED, true);\n }\n };\n\n const onSuccess = async (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n const resultAttributes = {\n ...captureOutputAttrs(result, options.captureOutput),\n ...(options.attributesFromResult\n ? options.attributesFromResult(result)\n : {}),\n };\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n ...argsAttributes,\n ...resultAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n await flushIfNeeded();\n return result;\n };\n\n const onError = async (error: unknown): Promise<never> => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'error',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'error',\n });\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n const truncatedMessage = truncateErrorMessage(errorMessage);\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncatedMessage,\n });\n\n span.setAttributes({\n ...argsAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': false,\n error: true,\n 'exception.type':\n error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n\n if (error instanceof Error && error.stack) {\n span.setAttribute(\n 'exception.stack',\n error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH),\n );\n }\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n\n handleTailSampling(false, duration, error);\n\n span.end();\n await flushIfNeeded();\n throw error;\n };\n\n try {\n callCounter?.add(1, {\n operation: spanName,\n status: 'started',\n });\n\n // Execute the user's function with the updated context\n // This ensures ctx.setBaggage() changes are visible to OpenTelemetry operations\n // (like BaggageSpanProcessor, child spans, etc.)\n // We use getActiveContextWithBaggage() which checks the stored context,\n // so if baggage is set during execution, it will be picked up\n const executeWithContext = async () => {\n // Get the current context (may have been updated by ctx.setBaggage())\n const currentContext = getActiveContextWithBaggage();\n // Establish the context in OpenTelemetry's context manager\n return context.with(currentContext, async () => {\n return fn.call(this, ...args);\n });\n };\n const result = await executeWithContext();\n\n return await onSuccess(result);\n } catch (error) {\n await onError(error);\n throw error;\n }\n });\n },\n );\n };\n\n // Mark as instrumented to prevent double-wrapping\n (wrappedFunction as InstrumentedFlag)[INSTRUMENTED_SYMBOL] = true;\n\n Object.defineProperty(wrappedFunction, 'name', {\n value: tempFn.name || 'trace',\n configurable: true,\n });\n\n return wrappedFunction;\n}\n\n/**\n * Core tracing wrapper for sync functions (internal implementation)\n */\nfunction wrapWithTracingSync<TArgs extends unknown[], TReturn>(\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n options: TracingOptions<TArgs, TReturn>,\n variableName?: string,\n): (...args: TArgs) => TReturn {\n // Idempotency check: if already instrumented, return as-is\n if (hasInstrumentationFlag(fnFactory)) {\n // If already instrumented, we need to extract the original factory\n // For now, we'll just proceed - this edge case is handled by the wrapped function check\n }\n\n const config = getConfig();\n const tracer = config.tracer;\n const meter = config.meter;\n const sampler = options.sampler || new AlwaysSampler();\n\n // We need to get a reference function name for span naming\n // Create a minimal dummy context just for extracting the function name\n // This won't affect actual tracing - we use the real context inside the span\n const tempFn = fnFactory(createDummyCtx());\n const spanName = getSpanName(options, tempFn, variableName);\n\n // Metrics setup (if enabled)\n const callCounter = options.withMetrics\n ? meter.createCounter(`${spanName}.calls`, {\n description: `Call count for ${spanName}`,\n unit: '1',\n })\n : undefined;\n\n const durationHistogram = options.withMetrics\n ? meter.createHistogram(`${spanName}.duration`, {\n description: `Duration for ${spanName}`,\n unit: 'ms',\n })\n : undefined;\n\n // Return wrapped function\n function wrappedFunction(\n this: unknown,\n ...args: TArgs\n ): TReturn | Promise<TReturn> {\n const samplingContext: SamplingContext = {\n operationName: spanName,\n args,\n metadata: {},\n };\n\n const shouldSample = sampler.shouldSample(samplingContext);\n const needsTailSampling =\n 'needsTailSampling' in sampler &&\n typeof sampler.needsTailSampling === 'function'\n ? sampler.needsTailSampling()\n : false;\n\n // If not sampling and no tail sampling, execute without tracing\n if (!shouldSample && !needsTailSampling) {\n const fn = fnFactory(createDummyCtx());\n return fn.call(this, ...args);\n }\n\n const startTime = performance.now();\n\n // Track if this is a root span for auto-flush\n const isRootSpan =\n options.startNewRoot || otelTrace.getActiveSpan() === undefined;\n const shouldAutoFlush =\n options.flushOnRootSpanEnd ?? getInitConfig()?.flushOnRootSpanEnd ?? true;\n const shouldAutoFlushSpans = getInitConfig()?.forceFlushOnShutdown ?? false;\n\n // Note: This is intentionally fire-and-forget (void) for synchronous functions.\n // Synchronous functions cannot await flush completion without blocking execution.\n // The forceFlushOnShutdown guarantee only applies to async functions.\n const flushIfNeeded = () => {\n if (!shouldAutoFlush || !isRootSpan) return;\n\n // Flush events queue\n const queue = getEventQueue();\n if (queue && queue.size() > 0) {\n void queue.flush().catch((error) => {\n const initConfig = getInitConfig();\n const logger = initConfig?.logger;\n if (logger?.error) {\n logger.error(\n {\n err: error instanceof Error ? error : undefined,\n },\n `[autotel] Auto-flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n });\n }\n\n // Flush OpenTelemetry spans if enabled\n if (shouldAutoFlushSpans) {\n try {\n const tracerProvider = getForceFlushableProvider(getSdk());\n if (tracerProvider) {\n void tracerProvider.forceFlush().catch((error: unknown) => {\n const initConfig = getInitConfig();\n const logger = initConfig?.logger;\n if (logger?.error) {\n logger.error(\n {\n err: error instanceof Error ? error : undefined,\n },\n `[autotel] Span flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n });\n }\n } catch {\n // Ignore errors when accessing tracer provider (may not be available in test mocks)\n }\n }\n };\n\n // Build span options including root and kind\n const spanOptions: import('@opentelemetry/api').SpanOptions = {};\n if (options.startNewRoot) {\n spanOptions.root = true;\n }\n if (options.spanKind !== undefined) {\n spanOptions.kind = options.spanKind;\n }\n\n const parentContext = getActiveContextWithBaggage();\n return tracer.startActiveSpan(\n spanName,\n spanOptions,\n parentContext,\n (span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(spanName, () => {\n let shouldKeepSpan = true;\n\n // Store span name for trace context helpers\n setSpanName(span, spanName);\n\n // Create trace context for this span using shared utility\n const ctxValue = createTraceContext(span);\n\n // Get the actual function from the factory\n const fn = fnFactory(ctxValue);\n\n // Extract attributes only when actually tracing\n // This avoids expensive preprocessing when sampling rejects the trace\n const argsAttributes = {\n ...captureInputAttrs(args, options.captureInput),\n ...(options.attributesFromArgs\n ? options.attributesFromArgs(args)\n : {}),\n };\n\n const handleTailSampling = (\n success: boolean,\n duration: number,\n error?: unknown,\n ) => {\n if (\n needsTailSampling &&\n 'shouldKeepTrace' in sampler &&\n typeof sampler.shouldKeepTrace === 'function'\n ) {\n shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {\n success,\n duration,\n error,\n });\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_KEEP, shouldKeepSpan);\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_EVALUATED, true);\n }\n };\n\n const onSuccess = (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n const resultAttributes = {\n ...captureOutputAttrs(result, options.captureOutput),\n ...(options.attributesFromResult\n ? options.attributesFromResult(result)\n : {}),\n };\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n ...argsAttributes,\n ...resultAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n void flushIfNeeded();\n return result;\n };\n\n const onError = (error: unknown): never => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'error',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'error',\n });\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n const truncatedMessage = truncateErrorMessage(errorMessage);\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncatedMessage,\n });\n\n span.setAttributes({\n ...argsAttributes,\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': false,\n error: true,\n 'exception.type':\n error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n\n handleTailSampling(false, duration, error);\n\n span.end();\n void flushIfNeeded();\n throw error;\n };\n\n try {\n callCounter?.add(1, {\n operation: spanName,\n status: 'started',\n });\n\n const result = fn.call(this, ...args);\n\n if (result instanceof Promise) {\n return result.then(onSuccess, onError);\n }\n\n return onSuccess(result);\n } catch (error) {\n return onError(error);\n }\n });\n },\n );\n }\n\n // Mark as instrumented to prevent double-wrapping\n (wrappedFunction as InstrumentedFlag)[INSTRUMENTED_SYMBOL] = true;\n\n // Preserve function name for better debugging\n // Use the same tempFn we created earlier for span naming\n Object.defineProperty(wrappedFunction, 'name', {\n value: tempFn.name || 'trace',\n configurable: true,\n });\n\n return wrappedFunction as unknown as (...args: TArgs) => TReturn;\n}\n\n/**\n * Execute a function immediately within a trace span\n * Used for the immediate execution pattern: trace((ctx) => result)\n */\nfunction executeImmediately<TReturn = unknown>(\n fn: (ctx: TraceContext) => TReturn | Promise<TReturn>,\n options: TracingOptions<unknown[], unknown>,\n): TReturn | Promise<TReturn> {\n const config = getConfig();\n const tracer = config.tracer;\n const meter = config.meter;\n const sampler = options.sampler || new AlwaysSampler();\n\n // Get span name from options or use 'anonymous'\n const spanName = options.name || 'anonymous';\n\n const samplingContext: SamplingContext = {\n operationName: spanName,\n args: [],\n metadata: {},\n };\n\n const shouldSample = sampler.shouldSample(samplingContext);\n const needsTailSampling =\n 'needsTailSampling' in sampler &&\n typeof sampler.needsTailSampling === 'function'\n ? sampler.needsTailSampling()\n : false;\n\n if (!shouldSample && !needsTailSampling) {\n return fn(createDummyCtx());\n }\n\n const startTime = performance.now();\n const isRootSpan =\n options.startNewRoot || otelTrace.getActiveSpan() === undefined;\n const shouldAutoFlush =\n options.flushOnRootSpanEnd ?? getInitConfig()?.flushOnRootSpanEnd ?? true;\n const shouldAutoFlushSpans = getInitConfig()?.forceFlushOnShutdown ?? false;\n\n const callCounter = options.withMetrics\n ? meter.createCounter(`${spanName}.calls`, {\n description: `Call count for ${spanName}`,\n unit: '1',\n })\n : undefined;\n\n const durationHistogram = options.withMetrics\n ? meter.createHistogram(`${spanName}.duration`, {\n description: `Duration for ${spanName}`,\n unit: 'ms',\n })\n : undefined;\n\n const flushIfNeeded = async () => {\n if (!shouldAutoFlush || !isRootSpan) return;\n\n try {\n // Flush events queue\n const queue = getEventQueue();\n if (queue && queue.size() > 0) {\n await queue.flush();\n }\n\n // Flush OpenTelemetry spans if enabled\n if (shouldAutoFlushSpans) {\n try {\n const tracerProvider = getForceFlushableProvider(getSdk());\n if (tracerProvider) {\n await tracerProvider.forceFlush();\n }\n } catch {\n // Ignore errors when accessing tracer provider (may not be available in test mocks)\n }\n }\n } catch (error) {\n const initConfig = getInitConfig();\n const logger = initConfig?.logger;\n if (logger?.error) {\n logger.error(\n {\n err: error instanceof Error ? error : undefined,\n },\n `[autotel] Auto-flush failed${error instanceof Error ? '' : `: ${String(error)}`}`,\n );\n }\n }\n };\n\n // Build span options including root and kind\n const spanOptions: import('@opentelemetry/api').SpanOptions = {};\n if (options.startNewRoot) {\n spanOptions.root = true;\n }\n if (options.spanKind !== undefined) {\n spanOptions.kind = options.spanKind;\n }\n\n const parentContext = getActiveContextWithBaggage();\n return tracer.startActiveSpan(\n spanName,\n spanOptions,\n parentContext,\n (span) => {\n return runInOperationContext(spanName, () => {\n let shouldKeepSpan = true;\n\n setSpanName(span, spanName);\n const ctxValue = createTraceContext(span);\n\n const handleTailSampling = (\n success: boolean,\n duration: number,\n error?: unknown,\n ) => {\n if (\n needsTailSampling &&\n 'shouldKeepTrace' in sampler &&\n typeof sampler.shouldKeepTrace === 'function'\n ) {\n shouldKeepSpan = sampler.shouldKeepTrace(samplingContext, {\n success,\n duration,\n error,\n });\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_KEEP, shouldKeepSpan);\n span.setAttribute(AUTOTEL_SAMPLING_TAIL_EVALUATED, true);\n }\n };\n\n // Sync handlers for synchronous results (can't await)\n // NOTE: forceFlushOnShutdown will NOT block for synchronous trace() calls\n // Flush is fire-and-forget, so spans may be dropped if process exits immediately\n const onSuccessSync = (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n void flushIfNeeded();\n return result;\n };\n\n const onErrorSync = (error: unknown): never => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'error',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'error',\n });\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n const truncatedMessage = truncateErrorMessage(errorMessage);\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncatedMessage,\n });\n\n span.setAttributes({\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': false,\n error: true,\n 'exception.type':\n error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n\n if (error instanceof Error && error.stack) {\n span.setAttribute(\n 'exception.stack',\n error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH),\n );\n }\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n\n handleTailSampling(false, duration, error);\n\n span.end();\n void flushIfNeeded();\n throw error;\n };\n\n // Async handlers for Promise results (await flush)\n const onSuccessAsync = async (result: TReturn) => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'success',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'success',\n });\n\n span.setStatus({ code: SpanStatusCode.OK });\n span.setAttributes({\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': true,\n });\n\n handleTailSampling(true, duration);\n\n span.end();\n await flushIfNeeded();\n return result;\n };\n\n const onErrorAsync = async (error: unknown): Promise<never> => {\n const duration = performance.now() - startTime;\n\n callCounter?.add(1, {\n operation: spanName,\n status: 'error',\n });\n\n durationHistogram?.record(duration, {\n operation: spanName,\n status: 'error',\n });\n\n const errorMessage =\n error instanceof Error ? error.message : 'Unknown error';\n const truncatedMessage = truncateErrorMessage(errorMessage);\n\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: truncatedMessage,\n });\n\n span.setAttributes({\n 'operation.name': spanName,\n 'code.function': spanName,\n 'operation.duration': duration,\n 'operation.success': false,\n error: true,\n 'exception.type':\n error instanceof Error ? error.constructor.name : 'Error',\n 'exception.message': truncatedMessage,\n });\n\n if (error instanceof Error && error.stack) {\n span.setAttribute(\n 'exception.stack',\n error.stack.slice(0, MAX_ERROR_MESSAGE_LENGTH),\n );\n }\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n\n handleTailSampling(false, duration, error);\n\n span.end();\n await flushIfNeeded();\n throw error;\n };\n\n try {\n callCounter?.add(1, {\n operation: spanName,\n status: 'started',\n });\n\n const result = fn(ctxValue);\n\n // Check if result is a Promise - use async handlers to await flush\n if (result instanceof Promise) {\n return result.then(onSuccessAsync, onErrorAsync);\n }\n\n // Synchronous result - use sync handlers\n return onSuccessSync(result);\n } catch (error) {\n return onErrorSync(error);\n }\n });\n },\n );\n}\n\n/**\n * Approach 1: trace() - Zero-ceremony HOF\n *\n * Wrap a single function with automatic tracing.\n * The function receives a context object as the first parameter.\n *\n * Supports two patterns:\n * 1. **Factory pattern** - Returns a traced function: `trace(ctx => (...args) => result)`\n * 2. **Immediate execution** - Executes immediately with tracing: `trace(ctx => result)`\n *\n * @example Auto-inferred name - Plain function\n * ```typescript\n * export const createUser = trace(async (data) => {\n * return await db.users.create(data)\n * })\n * // → Traced as \"createUser\"\n * ```\n *\n * @example Auto-inferred name - Factory pattern (with ctx access)\n * ```typescript\n * export const createUser = trace(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * // → Traced as \"createUser\", returns wrapped function\n * ```\n *\n * @example Immediate execution - Execute once with tracing\n * ```typescript\n * // Wraps an existing function and executes immediately\n * function timed<T>(fn: () => Promise<T>): Promise<T> {\n * return trace(async (ctx) => {\n * ctx.setAttribute('operation', 'timed')\n * return await fn()\n * })\n * }\n * // → Executes immediately, returns result directly\n * ```\n *\n * @example Custom name - Plain function\n * ```typescript\n * export const createUser = trace('user.create', async (data) => {\n * return await db.users.create(data)\n * })\n * // → Traced as \"user.create\"\n * ```\n *\n * @example Custom name - Factory pattern\n * ```typescript\n * export const createUser = trace('user.create', ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * // → Traced as \"user.create\"\n * ```\n *\n * @example Custom name - Immediate execution\n * ```typescript\n * const result = trace('fetch.user', async (ctx) => {\n * ctx.setAttribute('userId', '123')\n * return await fetchUser('123')\n * })\n * // → Executes immediately with span name \"fetch.user\"\n * ```\n *\n * @example Full options - Plain function\n * ```typescript\n * export const createUser = trace({\n * name: 'user.create',\n * sampler: new AdaptiveSampler(),\n * withMetrics: true\n * }, async (data) => {\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Full options - Factory pattern\n * ```typescript\n * export const createUser = trace({\n * name: 'user.create',\n * sampler: new AdaptiveSampler(),\n * withMetrics: true\n * }, ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n */\n// Sync overloads - Ordered from most specific to most generic for better type inference\n\n// Single argument - Specific overloads with TraceContext first\n// Overload 1a: Immediate execution - sync function with context\nexport function trace<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n TReturn = unknown,\n>(fn: (ctx: TraceContext<TBaggage>) => TReturn): TReturn;\n// Overload 1b: Factory sync function with no args - non-generic for type inference\nexport function trace<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n>(fnFactory: (ctx: TraceContext<TBaggage>) => () => unknown): () => unknown;\n// Overload 1c: Factory sync function - non-generic for type inference\nexport function trace<\n TBaggage extends Record<string, unknown> | undefined = undefined,\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n>(\n fnFactory: (ctx: TraceContext<TBaggage>) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// Overload 1d: Factory sync function with no args returning explicit type (typed generic)\nexport function trace<TReturn = unknown>(\n fnFactory: (ctx: TraceContext) => () => TReturn,\n): () => TReturn;\n// Overload 1e: Factory sync function - use conditional type to extract signature\n// This overload is more specific and helps TypeScript infer types from factory functions\nexport function trace<\n TFactory extends (ctx: TraceContext) => (...args: unknown[]) => unknown,\n>(fnFactory: TFactory): ExtractFunctionSignature<TFactory>;\n// Overload 1f: Generic factory sync function (fallback)\nexport function trace<TArgs extends unknown[], TReturn = unknown>(\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Single argument - Plain function overloads (no ctx parameter)\n// Overload 1g: Plain sync function with no args\nexport function trace<TReturn = unknown>(fn: () => TReturn): () => TReturn;\n// Overload 1h: Plain sync function (generic fallback)\nexport function trace<TArgs extends unknown[], TReturn = unknown>(\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Two arguments - name + function - Specific overloads with TraceContext first\n// Overload 2a: Name + immediate execution sync with context\n// This overload only matches functions that DON'T return functions (factories)\nexport function trace<TReturn = unknown>(\n name: string,\n fn: ExcludeFactoryReturn<(ctx: TraceContext) => TReturn>,\n): TReturn;\n// Overload 2b: Name + factory sync function with no args\nexport function trace<TReturn = unknown>(\n name: string,\n fnFactory: (ctx: TraceContext) => () => TReturn,\n): () => TReturn;\n// Overload 2c: Name + factory sync function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n name: string,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// Overload 2d: Name + factory sync function - use conditional type to extract signature\n// This overload allows TypeScript to infer types from the factory function parameter\nexport function trace<\n TFactory extends (ctx: TraceContext) => (...args: unknown[]) => unknown,\n>(name: string, fnFactory: TFactory): ExtractFunctionSignature<TFactory>;\n// Overload 2e: Name + factory sync function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n name: string,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Two arguments - name + function - Plain function overloads\n// Overload 2f: Name + plain sync function\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n name: string,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Two arguments - options + function - Specific overloads with TraceContext first\n// Overload 3a: Options + immediate execution sync with context\nexport function trace<TReturn = unknown>(\n options: TracingOptions<[], TReturn>,\n fn: (ctx: TraceContext) => TReturn,\n): TReturn;\n// Overload 3b: Options + factory sync function with no args\nexport function trace<TReturn = unknown>(\n options: TracingOptions<[], TReturn>,\n fnFactory: (ctx: TraceContext) => () => TReturn,\n): () => TReturn;\n// Overload 3c: Options + factory sync function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n// Overload 3d: Options + factory sync function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n options: TracingOptions<TArgs, TReturn>,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Two arguments - options + function - Plain function overloads\n// Overload 3e: Options + plain sync function\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n options: TracingOptions<TArgs, TReturn>,\n fn: (...args: TArgs) => TReturn,\n): (...args: TArgs) => TReturn;\n\n// Async overloads - Ordered from most specific to most generic\n\n// Single argument - Specific async overloads with TraceContext first\n// Overload 4a: Immediate execution - async function with context\nexport function trace<TReturn = unknown>(\n fn: (ctx: TraceContext) => Promise<TReturn>,\n): Promise<TReturn>;\n// Overload 4b: Factory async function with no args - non-generic for type inference\nexport function trace(\n fnFactory: (ctx: TraceContext) => () => Promise<unknown>,\n): () => Promise<unknown>;\n// Overload 4c: Factory async function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n// Overload 4d: Factory async function with no args (typed generic)\nexport function trace<TReturn = unknown>(\n fnFactory: (ctx: TraceContext) => () => Promise<TReturn>,\n): () => Promise<TReturn>;\n// Overload 4e: Factory async function - use conditional type to extract signature\nexport function trace<\n TFactory extends (\n ctx: TraceContext,\n ) => (...args: unknown[]) => Promise<unknown>,\n>(fnFactory: TFactory): ExtractFunctionSignature<TFactory>;\n// Overload 4f: Generic factory async function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Single argument - Plain async function overloads (no ctx parameter)\n// Overload 4g: Plain async function with no args\nexport function trace<TReturn = unknown>(\n fn: () => Promise<TReturn>,\n): () => Promise<TReturn>;\n// Overload 4h: Plain async function (generic fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n fn: (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Two arguments - name + async function - Specific overloads with TraceContext first\n// Overload 5a: Name + immediate execution async with context\n// This overload only matches functions that DON'T return functions (factories)\nexport function trace<TReturn = unknown>(\n name: string,\n fn: ExcludeFactoryReturn<(ctx: TraceContext) => Promise<TReturn>>,\n): Promise<TReturn>;\n// Overload 5b: Name + factory async function with no args\nexport function trace<TReturn = unknown>(\n name: string,\n fnFactory: (ctx: TraceContext) => () => Promise<TReturn>,\n): () => Promise<TReturn>;\n// Overload 5c: Name + factory async function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n name: string,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n// Overload 5d: Name + factory async function - use conditional type to extract signature\n// This overload allows TypeScript to infer types from the factory function parameter\nexport function trace<\n TFactory extends (\n ctx: TraceContext,\n ) => (...args: unknown[]) => Promise<unknown>,\n>(name: string, fnFactory: TFactory): ExtractFunctionSignature<TFactory>;\n// Overload 5e: Name + factory async function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n name: string,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Two arguments - name + async function - Plain function overloads\n// Overload 5f: Name + plain async function\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n name: string,\n fn: (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Two arguments - options + async function - Specific overloads with TraceContext first\n// Overload 6a: Options + immediate execution async with context\nexport function trace<TReturn = unknown>(\n options: TracingOptions<[], TReturn>,\n fn: (ctx: TraceContext) => Promise<TReturn>,\n): Promise<TReturn>;\n// Overload 6b: Options + factory async function with no args\nexport function trace<TReturn = unknown>(\n options: TracingOptions<[], TReturn>,\n fnFactory: (ctx: TraceContext) => () => Promise<TReturn>,\n): () => Promise<TReturn>;\n// Overload 6c: Options + factory async function - non-generic for type inference\nexport function trace<TArgs extends unknown[], TReturn>(\n options: TracingOptions<TArgs, TReturn>,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n// Overload 6d: Options + factory async function (fallback)\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n options: TracingOptions<TArgs, TReturn>,\n fnFactory: (ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Two arguments - options + async function - Plain function overloads\n// Overload 6e: Options + plain async function\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n options: TracingOptions<TArgs, TReturn>,\n fn: (...args: TArgs) => Promise<TReturn>,\n): (...args: TArgs) => Promise<TReturn>;\n\n// Implementation\nexport function trace<TArgs extends unknown[] = unknown[], TReturn = unknown>(\n fnOrNameOrOptions:\n | ((...args: TArgs) => TReturn)\n | ((...args: TArgs) => Promise<TReturn>)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn)\n | ((ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>)\n | ((ctx: TraceContext) => TReturn)\n | ((ctx: TraceContext) => Promise<TReturn>)\n | string\n | TracingOptions<TArgs, TReturn>,\n maybeFn?:\n | ((...args: TArgs) => TReturn)\n | ((...args: TArgs) => Promise<TReturn>)\n | ((ctx: TraceContext) => (...args: TArgs) => TReturn)\n | ((ctx: TraceContext) => (...args: TArgs) => Promise<TReturn>)\n | ((ctx: TraceContext) => TReturn)\n | ((ctx: TraceContext) => Promise<TReturn>),\n): WrappedFunction<TArgs, TReturn> | TReturn | Promise<TReturn> {\n // Handle: trace(fn) - single argument\n if (typeof fnOrNameOrOptions === 'function') {\n // Check if it's immediate execution pattern: (ctx) => result\n if (\n looksLikeTraceFactory(fnOrNameOrOptions as GenericFunction) &&\n !isFactoryReturningFunction(\n fnOrNameOrOptions as (ctx: TraceContext) => unknown,\n )\n ) {\n // Immediate execution pattern\n return executeImmediately(\n fnOrNameOrOptions as (ctx: TraceContext) => TReturn | Promise<TReturn>,\n {},\n ) as WrappedFunction<TArgs, TReturn> | TReturn | Promise<TReturn>;\n }\n // Factory pattern or plain function\n return wrapFactoryWithTracing(\n fnOrNameOrOptions as (...args: TArgs) => TReturn,\n {} as TracingOptions<TArgs, TReturn>,\n );\n }\n\n // Handle: trace(name, fn) or trace(options, fn) - two arguments\n if (typeof fnOrNameOrOptions === 'string') {\n if (!maybeFn) {\n throw new Error('trace(name, fn): fn is required');\n }\n // Check if it's immediate execution pattern\n if (\n looksLikeTraceFactory(maybeFn as GenericFunction) &&\n !isFactoryReturningFunction(maybeFn as (ctx: TraceContext) => unknown)\n ) {\n // Immediate execution pattern with name\n return executeImmediately(\n maybeFn as (ctx: TraceContext) => TReturn | Promise<TReturn>,\n { name: fnOrNameOrOptions },\n ) as WrappedFunction<TArgs, TReturn> | TReturn | Promise<TReturn>;\n }\n return wrapFactoryWithTracing(\n maybeFn as (...args: TArgs) => TReturn,\n { name: fnOrNameOrOptions } as TracingOptions<TArgs, TReturn>,\n );\n }\n\n // Handle: trace(options, fn)\n if (!maybeFn) {\n throw new Error('trace(options, fn): fn is required');\n }\n\n // Check if it's immediate execution pattern\n if (\n looksLikeTraceFactory(maybeFn as GenericFunction) &&\n !isFactoryReturningFunction(maybeFn as (ctx: TraceContext) => unknown)\n ) {\n // Immediate execution pattern with options\n return executeImmediately(\n maybeFn as (ctx: TraceContext) => TReturn | Promise<TReturn>,\n fnOrNameOrOptions as TracingOptions<unknown[], unknown>,\n ) as WrappedFunction<TArgs, TReturn> | TReturn | Promise<TReturn>;\n }\n\n return wrapFactoryWithTracing(\n maybeFn as (...args: TArgs) => TReturn,\n fnOrNameOrOptions as TracingOptions<TArgs, TReturn>,\n );\n}\n\n/**\n * Approach 2: withTracing() - Middleware-style composable wrapper\n *\n * Returns a HOF that wraps functions with tracing.\n * Perfect for composition and reusable configuration.\n *\n * @example Standard usage\n * ```typescript\n * export const createUser = withTracing({\n * name: 'user.create'\n * })(ctx => async (data) => {\n * ctx.setAttribute('user.id', data.id)\n * return await db.users.create(data)\n * })\n * ```\n *\n * @example Composable\n * ```typescript\n * const trace = withTracing({ serviceName: 'user' })\n *\n * export const createUser = trace(ctx => async (data) => { })\n * export const updateUser = trace(ctx => async (id, data) => { })\n * ```\n *\n * @example With other middleware\n * ```typescript\n * export const createUser = compose(\n * withAuth({ role: 'admin' }),\n * withTracing({ name: 'user.create' }),\n * withRateLimit({ max: 100 })\n * )(ctx => async (data) => { })\n * ```\n */\nexport function withTracing<\n TArgs extends unknown[] = unknown[],\n TReturn = unknown,\n>(\n options: TracingOptions<TArgs, TReturn> = {},\n): (\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n) => (...args: TArgs) => TReturn | Promise<TReturn> {\n return (\n fnFactory: (\n ctx: TraceContext,\n ) => (...args: TArgs) => TReturn | Promise<TReturn>,\n ): WrappedFunction<TArgs, TReturn> =>\n wrapFactoryWithTracing<TArgs, TReturn>(fnFactory, options);\n}\n\n/**\n * Approach 3: instrument() - Batch auto-instrumentation\n *\n * Instrument an entire module/object at once.\n * Closest to @Instrumented decorator pattern.\n *\n * @example Basic usage\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * updateUser: async (id, data) => { },\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * sampler: new AdaptiveSampler()\n * })\n * // → Traced as \"user.createUser\", \"user.updateUser\", \"user.deleteUser\"\n * ```\n *\n * @example Per-function overrides\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * overrides: {\n * deleteUser: {\n * sampler: new AlwaysSampler(),\n * withMetrics: true\n * }\n * }\n * })\n * ```\n *\n * @example Skip functions\n * ```typescript\n * export default instrument({\n * functions: {\n * createUser: async (data) => { },\n * _internal: async () => { }, // Auto-skipped (_-prefix)\n * deleteUser: async (id) => { }\n * },\n * serviceName: 'user',\n * skip: [/^test/, (key) => key.includes('debug')]\n * })\n * ```\n */\nexport function instrument<T extends Record<string, InstrumentableFunction>>(\n options: InstrumentOptions<T>,\n): T {\n const { functions, ...tracingOptions } = options;\n const instrumented: Partial<T> = {};\n\n for (const key of Object.keys(functions)) {\n const typedKey = key as keyof T;\n const fn = functions[typedKey];\n\n // Skip if not a function or undefined - just pass through the value\n if (!fn || typeof fn !== 'function') {\n instrumented[typedKey] = fn as T[typeof typedKey];\n continue;\n }\n\n // Only instrument own enumerable async functions\n // Check if should skip\n if (shouldSkip(key, fn, tracingOptions.skip)) {\n instrumented[typedKey] = fn as T[typeof typedKey];\n continue;\n }\n\n // Merge base options with per-function overrides\n const fnOptions: TracingOptions = {\n ...tracingOptions,\n ...tracingOptions.overrides?.[key],\n // If no explicit name, use key as function name\n name: tracingOptions.overrides?.[key]?.name,\n };\n\n // Bind function to original object to preserve 'this' context\n // This ensures methods can access state on the original object\n const boundFn = fn.bind(functions);\n\n // Convert plain function to factory pattern for trace()\n // For instrument(), we create a factory that ignores ctx and returns the original function\n const fnFactory = (ctx: TraceContext) => {\n void ctx;\n return boundFn;\n };\n\n // Wrap with tracing (sync or async based on implementation)\n instrumented[typedKey] = wrapFactoryWithTracing(\n fnFactory,\n fnOptions,\n key,\n ) as T[typeof typedKey];\n }\n\n return instrumented as T;\n}\n\n/**\n * Options for span() function\n */\nexport interface SpanOptions {\n /** Span name */\n name: string;\n /** Attributes to set on the span */\n attributes?: Record<string, string | number | boolean>;\n}\n\n/**\n * Execute a function within a named span\n *\n * Useful for adding tracing to specific code blocks without wrapping\n * the entire function. Supports both synchronous and asynchronous functions.\n *\n * Mirrors `trace()`: pass a span name as the first argument for the common\n * case, or full `SpanOptions` when you need to attach attributes.\n *\n * @example\n * ```typescript\n * // Name shorthand\n * await span('payment.charge', async (span) => {\n * await chargeCustomer(order);\n * })\n *\n * // Full options when attributes are needed\n * await span(\n * { name: 'payment.charge', attributes: { amount: order.total } },\n * async (span) => {\n * await chargeCustomer(order);\n * },\n * )\n *\n * // Sync\n * const total = span('calculateTotal', (span) => {\n * return items.reduce((sum, item) => sum + item.price, 0);\n * })\n * ```\n */\n// Overloads — sync first (more specific match), then async.\n// Each shape is offered with a string name OR a full SpanOptions object so\n// span() aligns with trace()'s argument flexibility.\nexport function span<T = unknown>(name: string, fn: (span: Span) => T): T;\nexport function span<T = unknown>(\n name: string,\n fn: (span: Span) => Promise<T>,\n): Promise<T>;\nexport function span<T = unknown>(\n options: SpanOptions,\n fn: (span: Span) => T,\n): T;\nexport function span<T = unknown>(\n options: SpanOptions,\n fn: (span: Span) => Promise<T>,\n): Promise<T>;\n// Implementation\nexport function span<T = unknown>(\n nameOrOptions: string | SpanOptions,\n fn: (span: Span) => T | Promise<T>,\n): T | Promise<T> {\n const options: SpanOptions =\n typeof nameOrOptions === 'string' ? { name: nameOrOptions } : nameOrOptions;\n const config = getConfig();\n const tracer = config.tracer;\n const { name, attributes } = options;\n\n const executeSpan = (span: Span) => {\n // Run within operation context so events can auto-capture operation.name\n return runInOperationContext(name, () => {\n try {\n // Set attributes\n if (attributes) {\n for (const [key, value] of Object.entries(attributes)) {\n span.setAttribute(key, value);\n }\n }\n\n const result = fn(span);\n\n // Check if result is a Promise\n if (result instanceof Promise) {\n return result\n .then((resolved) => {\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return resolved;\n })\n .catch((error) => {\n const errorMessage =\n error instanceof Error\n ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH)\n : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);\n\n span.setAttribute('error.message', errorMessage);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.end();\n throw error;\n });\n } else {\n // Synchronous function\n span.setStatus({ code: SpanStatusCode.OK });\n span.end();\n return result;\n }\n } catch (error) {\n // Synchronous error handling\n const errorMessage =\n error instanceof Error\n ? error.message.slice(0, MAX_ERROR_MESSAGE_LENGTH)\n : String(error).slice(0, MAX_ERROR_MESSAGE_LENGTH);\n\n span.setAttribute('error.message', errorMessage);\n span.setStatus({\n code: SpanStatusCode.ERROR,\n message: errorMessage,\n });\n\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.end();\n throw error;\n }\n });\n };\n\n const parentContext = getActiveContextWithBaggage();\n const result = tracer.startActiveSpan(name, {}, parentContext, executeSpan);\n\n // tracer.startActiveSpan might return a Promise even for sync callbacks\n // Check if it's a Promise and handle accordingly\n if (result instanceof Promise) {\n return result;\n }\n\n return result as T;\n}\n\n/**\n * Options for withNewContext() function\n */\nexport interface WithNewContextOptions<T = unknown> {\n /** Function to execute in new root context */\n fn: () => Promise<T>;\n}\n\n/**\n * Execute a function in a new root context (prevents span propagation)\n *\n * Useful when you want to start a completely new trace without\n * parent-child relationships.\n *\n * @example\n * ```typescript\n * async function handleWebhook(payload: WebhookPayload) {\n * // This creates a new root trace, not connected to the HTTP request trace\n * await withNewContext({\n * fn: async () => {\n * await trace(ctx => async () => {\n * await processWebhookPayload(payload)\n * })()\n * }\n * })\n * }\n * ```\n */\nexport async function withNewContext<T = unknown>(\n options: WithNewContextOptions<T>,\n): Promise<T> {\n const { fn } = options;\n const config = getConfig();\n const tracer = config.tracer;\n\n // Start a new root span (breaks trace propagation)\n return tracer.startActiveSpan('root', { root: true }, async (span) => {\n try {\n const result = await fn();\n span.setStatus({ code: SpanStatusCode.OK });\n return result;\n } catch (error) {\n span.recordException(\n error instanceof Error ? error : new Error(String(error)),\n );\n span.setStatus({ code: SpanStatusCode.ERROR });\n throw error;\n } finally {\n span.end();\n }\n });\n}\n\n/**\n * Options for withBaggage() function\n */\nexport interface WithBaggageOptions<T = unknown> {\n /** Baggage entries to set (key-value pairs) */\n baggage: Record<string, string>;\n /** Function to execute with the updated baggage */\n fn: () => T | Promise<T>;\n}\n\n/**\n * Execute a function with updated baggage entries\n *\n * Baggage is immutable in OpenTelemetry, so this helper creates a new context\n * with the specified baggage entries and runs the function within that context.\n * All child spans created within the function will inherit the baggage.\n *\n * @example Setting baggage for downstream services\n * ```typescript\n * import { trace, withBaggage } from 'autotel';\n *\n * export const createOrder = trace((ctx) => async (order: Order) => {\n * // Set baggage that will be propagated to downstream HTTP calls\n * return await withBaggage({\n * baggage: {\n * 'tenant.id': order.tenantId,\n * 'user.id': order.userId,\n * },\n * fn: async () => {\n * // This HTTP call will include the baggage in headers\n * await fetch('/api/charge', {\n * method: 'POST',\n * body: JSON.stringify(order),\n * });\n * },\n * });\n * });\n * ```\n *\n * @example Using with existing baggage\n * ```typescript\n * export const processOrder = trace((ctx) => async (order: Order) => {\n * // Read existing baggage\n * const tenantId = ctx.getBaggage('tenant.id');\n *\n * // Add additional baggage entries\n * return await withBaggage({\n * baggage: {\n * 'order.id': order.id,\n * 'order.amount': String(order.amount),\n * },\n * fn: async () => {\n * await charge(order);\n * },\n * });\n * });\n * ```\n */\nexport function withBaggage<T = unknown>(\n options: WithBaggageOptions<T>,\n): T | Promise<T> {\n const { baggage: baggageEntries, fn } = options;\n const currentContext = context.active();\n\n // Get existing baggage or create new\n let updatedBaggage =\n propagation.getBaggage(currentContext) ?? propagation.createBaggage();\n\n // Set all baggage entries\n for (const [key, value] of Object.entries(baggageEntries)) {\n updatedBaggage = updatedBaggage.setEntry(key, { value });\n }\n\n // Create new context with updated baggage\n const newContext = propagation.setBaggage(currentContext, updatedBaggage);\n\n // Sync contextStorage so nested traces (via getActiveContextWithBaggage) see the baggage.\n // Use run() instead of enterWith() to properly scope the context changes.\n const ctxStorage = getContextStorage();\n const previousStored = ctxStorage.getStore();\n const baggageEnrichedStored = previousStored\n ? { value: propagation.setBaggage(previousStored.value, updatedBaggage) }\n : { value: newContext };\n\n // Run the function within the new context, scoped properly\n const result = previousStored\n ? ctxStorage.run(baggageEnrichedStored, () => context.with(newContext, fn))\n : context.with(newContext, fn);\n\n if (result instanceof Promise) {\n // For async operations, ensure context is restored after the promise settles\n return result.then(\n (value) => {\n // Restore original context before resolving\n if (previousStored) {\n return ctxStorage.run(previousStored, () => value);\n }\n return value;\n },\n (error) => {\n // Restore original context before rejecting\n if (previousStored) {\n return ctxStorage.run(previousStored, () => {\n throw error;\n });\n }\n throw error;\n },\n );\n }\n\n // Sync function - context automatically restored when scope exits\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,MAAM,iCAAiB,IAAI,IAAgC;AAC3D,MAAM,iBAAiB;;;;AAK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