autotel-posthog 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,191 @@
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 ADDED
@@ -0,0 +1,158 @@
1
+ # autotel-posthog
2
+
3
+ Join autotel traces to PostHog sessions, replays and events. One session id, and a link in both directions.
4
+
5
+ PostHog knows two things a tracer cannot work out for itself: which recorded session a page view belongs to, and which person is behind it. autotel knows which trace explains a given moment. This package is the join, and it depends on no PostHog package to make it — the methods it reads are the public browser API, read structurally off whatever instance is on the page.
6
+
7
+ It is also where `PostHogSubscriber` lives, so one package covers PostHog end to end: the browser join on `autotel-posthog`, product events from the server on `autotel-posthog/subscriber`.
8
+
9
+ ## Install
10
+
11
+ The two entry points need different things, so install the half you use.
12
+
13
+ ```bash
14
+ # Browser join — needs the SDK whose session you are joining
15
+ npm install autotel-posthog posthog-js autotel-web
16
+
17
+ # Server events
18
+ npm install autotel-posthog posthog-node autotel autotel-subscribers
19
+ ```
20
+
21
+ Every peer is declared optional so the half you skip does not warn about
22
+ packages it will never import. `posthog-js` is not bundled: two copies on one
23
+ page means two session managers and two different answers to
24
+ `get_session_id()`, which would break the join this package exists to make.
25
+
26
+ ## The short version
27
+
28
+ One call wires both directions — PostHog's half itself, and the enricher for the tracer's half:
29
+
30
+ ```ts
31
+ import posthog from 'posthog-js';
32
+ import { initFull } from 'autotel-web/full';
33
+ import { joinPostHog } from 'autotel-posthog';
34
+
35
+ posthog.init('<key>');
36
+
37
+ initFull({
38
+ service: 'web',
39
+ endpoint: 'https://collector.example.com/v1/traces',
40
+ spanEnrichers: [joinPostHog(posthog)],
41
+ });
42
+ ```
43
+
44
+ `joinPostHog` appends its hook to any `before_send` chain the app already has rather than replacing it, and calling it again — strict mode, HMR, a re-render — does not stack up another copy.
45
+
46
+ Add `traceUrl` and PostHog events carry a link, not just ids to join on:
47
+
48
+ ```ts
49
+ spanEnrichers: [
50
+ joinPostHog(posthog, {
51
+ traceUrl: ({ traceId }) => `https://traces.example.com/${traceId}`,
52
+ featureFlags: ['new-checkout'],
53
+ }),
54
+ ],
55
+ ```
56
+
57
+ Everything below is what `joinPostHog` does, for anyone who wants the halves separately.
58
+
59
+ ## The halves, separately
60
+
61
+ ### Trace → PostHog
62
+
63
+ `posthogCompatibility()` is a span enricher. It stamps the PostHog session and person onto spans, and on spans that failed, a replay link deep-linked to the moment it broke.
64
+
65
+ ```ts
66
+ import { initFull } from 'autotel-web/full';
67
+ import { posthogCompatibility } from 'autotel-posthog';
68
+
69
+ initFull({
70
+ service: 'web',
71
+ endpoint: 'https://collector.example.com/v1/traces',
72
+ spanEnrichers: [posthogCompatibility()],
73
+ });
74
+ ```
75
+
76
+ | Attribute | Source | On which spans |
77
+ | -------------------- | --------------------------------------------------------- | ----------------------------- |
78
+ | `session.id` | `posthog.get_session_id()` | every span |
79
+ | `user.id` | `posthog.get_distinct_id()` | every span |
80
+ | `session.replay.url` | `posthog.get_session_replay_url({ withTimestamp: true })` | spans that recorded an error |
81
+ | `feature_flag.<key>` | `posthog.getFeatureFlag(key)` | every span, for keys you name |
82
+
83
+ Identity is read when the span **starts**, not when it ends. PostHog rotates a session after 30 minutes idle and `identify()` can land mid-request; a long span asking at the end would be filed under whoever the visitor had become by then. The replay link is the one thing decided at the end, because only the end knows whether the span failed — and it is withheld if the session rotated in between, since the link would point at a recording the span has nothing to do with.
84
+
85
+ A flag that evaluates to `false` is kept as a boolean: "not in the variant" is an answer, and comparing the two groups is the whole point. Only a flag PostHog has no opinion on is omitted.
86
+
87
+ Use `spanEnrichers`, not `spanProcessor`. The latter _replaces_ the pipeline autotel builds, so passing an enricher there switches off the export you just configured.
88
+
89
+ An error span now carries a link to the replay at the second it broke, in whatever backend the spans land in — so "a slow span" becomes "watch the person it was slow for" without leaving the trace view.
90
+
91
+ The link appears only when `posthog.sessionRecordingStarted()` is true. `get_session_replay_url()` composes a URL from the session id whether or not anything was recorded, so replay being disabled, sampled out, or simply not started yet would otherwise produce a link that lands on an empty player — and one dead link is enough to stop people trusting the ones that work. An instance too old or too stubbed to answer produces no link rather than a confident wrong one.
92
+
93
+ #### Feature flags are named, never harvested
94
+
95
+ ```ts
96
+ posthogCompatibility({ featureFlags: ['new-checkout'] });
97
+ ```
98
+
99
+ Every flag is another attribute on every span. Naming them is what keeps an analytics convenience from becoming a cardinality bill. A flag PostHog has no opinion on yet is omitted; one that evaluated to `false` is kept, because that is an answer.
100
+
101
+ ### PostHog → trace
102
+
103
+ `autotelBeforeSend()` is a PostHog `before_send` hook. It stamps `$trace_id`, `$span_id` and — when you supply `traceUrl` — `$trace_url` on every PostHog event from the span in progress, using the same property names autotel's server-side subscriber already writes.
104
+
105
+ ```ts
106
+ import posthog from 'posthog-js';
107
+ import { autotelBeforeSend } from 'autotel-posthog';
108
+
109
+ posthog.init('<key>', { before_send: [autotelBeforeSend()] });
110
+ ```
111
+
112
+ A `$exception` or a funnel drop-off in PostHog now names the trace that explains it. Events an earlier hook dropped stay dropped: `before_send` is a chain, and `null` means the page suppressed the event deliberately.
113
+
114
+ ## Product events from the server
115
+
116
+ ```ts
117
+ import { Event } from 'autotel/event';
118
+ import { PostHogSubscriber } from 'autotel-posthog/subscriber';
119
+
120
+ const events = new Event('checkout', {
121
+ subscribers: [
122
+ new PostHogSubscriber({ apiKey: process.env.POSTHOG_API_KEY! }),
123
+ ],
124
+ });
125
+ ```
126
+
127
+ Server-side `track()` events go to PostHog carrying `$trace_id` and `$span_id` — the same property names the browser hook writes, so an event points back at its trace whichever side captured it. Needs `autotel-subscribers` alongside it, for the `EventSubscriber` base it extends.
128
+
129
+ ## Without the OpenTelemetry pipeline
130
+
131
+ The minimal `autotel-web` build writes spans straight to OTLP and has no processor pipeline to hang an enricher on. Give it the session id directly:
132
+
133
+ ```ts
134
+ import { init } from 'autotel-web';
135
+ import { posthogSessionId } from 'autotel-posthog';
136
+
137
+ init({ service: 'web', session: { id: posthogSessionId } });
138
+ ```
139
+
140
+ ## Three states, one of which answers questions
141
+
142
+ A page is in one of three states, and only the last one can be asked anything:
143
+
144
+ 1. no `posthog` on the page at all,
145
+ 2. the loader snippet's array stub, which queues calls made before the real library arrives and has none of these methods,
146
+ 3. the loaded library — which still returns an empty session id until it finishes initializing.
147
+
148
+ Every call this package makes is guarded for all three. Analytics that is still starting up never throws inside a fetch handler, and never produces an attribute that means nothing.
149
+
150
+ ## Which session id wins
151
+
152
+ Where PostHog has a session id, it replaces the one `autotel-web` mints for itself. PostHog's id is what the replay, the funnels and the person profile are all keyed on, so a span carrying any other id links to nothing. Where PostHog has none yet, the locally minted id stands, because spans with no session at all are worse than spans with a session only autotel knows about.
153
+
154
+ `user.id` and the rest are filled, never overwritten — a span that set them already knows something this package does not.
155
+
156
+ ## License
157
+
158
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,267 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ let _opentelemetry_api = require("@opentelemetry/api");
3
+ //#region src/posthog-like.ts
4
+ /**
5
+ * Whether this object can actually answer questions yet.
6
+ *
7
+ * The loader snippet leaves an array on `window.posthog` that queues calls, and
8
+ * posthog-js later *replaces* it with the real instance. An integration holding
9
+ * the array from before the swap holds something that will never answer, so the
10
+ * only useful test is whether the methods are there.
11
+ */
12
+ function isUsable(posthog) {
13
+ return typeof posthog?.get_session_id === "function";
14
+ }
15
+ /**
16
+ * Call a PostHog getter without letting the page's analytics break the page's
17
+ * tracing. A stub throws `TypeError`, a partly-initialized instance returns an
18
+ * empty string, and neither is worth an attribute.
19
+ */
20
+ function readString(fn, receiver) {
21
+ if (typeof fn !== "function") return void 0;
22
+ try {
23
+ const value = fn.call(receiver);
24
+ return typeof value === "string" && value.length > 0 ? value : void 0;
25
+ } catch {
26
+ return;
27
+ }
28
+ }
29
+ function readSessionId(posthog) {
30
+ return readString(posthog.get_session_id, posthog);
31
+ }
32
+ function readDistinctId(posthog) {
33
+ return readString(posthog.get_distinct_id, posthog);
34
+ }
35
+ /**
36
+ * Whether a replay actually exists to link to.
37
+ *
38
+ * `get_session_replay_url()` composes a URL out of the session id whether or
39
+ * not anything was recorded — replay disabled, sampled out, or simply not
40
+ * started yet all still produce a link, and it lands on an empty player. Only
41
+ * an affirmative answer counts, so an instance too old or too stubbed to say
42
+ * produces no link rather than a confident wrong one.
43
+ */
44
+ function isRecording(posthog) {
45
+ try {
46
+ if (typeof posthog.sessionRecordingStarted === "function") return posthog.sessionRecordingStarted() === true;
47
+ return posthog.sessionRecording?.started === true;
48
+ } catch {
49
+ return false;
50
+ }
51
+ }
52
+ function readReplayUrl(posthog) {
53
+ if (!isRecording(posthog)) return void 0;
54
+ const fn = posthog.get_session_replay_url;
55
+ if (typeof fn !== "function") return void 0;
56
+ try {
57
+ const value = fn.call(posthog, { withTimestamp: true });
58
+ return typeof value === "string" && value.length > 0 ? value : void 0;
59
+ } catch {
60
+ return;
61
+ }
62
+ }
63
+ /**
64
+ * An evaluated flag value.
65
+ *
66
+ * `false` is an answer — "this person is not in the variant" — and is kept as a
67
+ * boolean so a query can ask for it. Only `undefined`, meaning PostHog has no
68
+ * opinion yet, is dropped: an attribute that says nothing is worse than an
69
+ * absent one.
70
+ */
71
+ function readFeatureFlag(posthog, key) {
72
+ const fn = posthog.getFeatureFlag;
73
+ if (typeof fn !== "function") return void 0;
74
+ try {
75
+ const value = fn.call(posthog, key);
76
+ if (value === void 0) return void 0;
77
+ return typeof value === "boolean" ? value : String(value);
78
+ } catch {
79
+ return;
80
+ }
81
+ }
82
+ //#endregion
83
+ //#region src/compatibility.ts
84
+ /** `SpanStatusCode.ERROR`, without importing the enum for one comparison. */
85
+ const STATUS_ERROR = 2;
86
+ function failed(span) {
87
+ return span.status?.code === STATUS_ERROR || span.attributes["exception.type"] !== void 0 || span.events?.some((event) => event.name === "exception") === true;
88
+ }
89
+ function resolvePostHog(options) {
90
+ const configured = typeof options.posthog === "function" ? options.posthog() : options.posthog;
91
+ if (isUsable(configured)) return configured;
92
+ const global = globalThis.posthog;
93
+ return isUsable(global) ? global : void 0;
94
+ }
95
+ function posthogCompatibility(options = {}) {
96
+ return {
97
+ /**
98
+ * Identity is read here, not in `onEnd`, because it is a fact about when
99
+ * the operation happened. PostHog rotates a session after 30 minutes idle,
100
+ * and `identify()` can land mid-request; a long span asking at the end
101
+ * would be filed under whoever the visitor had become by then rather than
102
+ * who started it.
103
+ */
104
+ onStart(span, _context) {
105
+ const posthog = resolvePostHog(options);
106
+ if (!posthog) return;
107
+ const sessionId = readSessionId(posthog);
108
+ if (sessionId !== void 0) span.setAttribute("session.id", sessionId);
109
+ const attributes = span.attributes;
110
+ const fill = (key, value) => {
111
+ if (value !== void 0 && attributes[key] === void 0) span.setAttribute(key, value);
112
+ };
113
+ fill("user.id", readDistinctId(posthog));
114
+ for (const key of options.featureFlags ?? []) fill(`feature_flag.${key}`, readFeatureFlag(posthog, key));
115
+ },
116
+ /**
117
+ * Only the replay link is left for the end, because only the end knows
118
+ * whether the span failed.
119
+ */
120
+ onEnd(span) {
121
+ if (!failed(span)) return;
122
+ const posthog = resolvePostHog(options);
123
+ if (!posthog) return;
124
+ const attributes = span.attributes;
125
+ if (attributes["session.replay.url"] !== void 0) return;
126
+ const current = readSessionId(posthog);
127
+ if (current === void 0 || current !== attributes["session.id"]) return;
128
+ const url = readReplayUrl(posthog);
129
+ if (url !== void 0) attributes["session.replay.url"] = url;
130
+ },
131
+ forceFlush() {
132
+ return Promise.resolve();
133
+ },
134
+ shutdown() {
135
+ return Promise.resolve();
136
+ }
137
+ };
138
+ }
139
+ //#endregion
140
+ //#region src/before-send.ts
141
+ /**
142
+ * The other half of the join: PostHog events that know which trace they
143
+ * happened inside.
144
+ *
145
+ * `posthogCompatibility()` teaches the trace about the session. This teaches
146
+ * the session about the trace, so a `$exception` or a funnel drop-off in
147
+ * PostHog carries the trace id that explains it, and the property names match
148
+ * the ones autotel's server-side subscriber already writes — one set of names
149
+ * whichever side captured the event.
150
+ *
151
+ * @example
152
+ * ```ts
153
+ * posthog.init('<key>', {
154
+ * before_send: [
155
+ * autotelBeforeSend({
156
+ * traceUrl: ({ traceId }) => `https://traces.example.com/${traceId}`,
157
+ * }),
158
+ * ],
159
+ * });
160
+ * ```
161
+ */
162
+ /**
163
+ * A PostHog `before_send` hook that adds `$trace_id` and `$span_id` from the
164
+ * span in progress.
165
+ */
166
+ function autotelBeforeSend(options = {}) {
167
+ return (event) => {
168
+ if (event === null) return null;
169
+ const spanContext = _opentelemetry_api.trace.getSpanContext(_opentelemetry_api.context.active());
170
+ if (!spanContext) return event;
171
+ const properties = event.properties;
172
+ if (properties["$trace_id"] === void 0) properties["$trace_id"] = spanContext.traceId;
173
+ if (properties["$span_id"] === void 0) properties["$span_id"] = spanContext.spanId;
174
+ if (options.traceUrl && properties["$trace_url"] === void 0) try {
175
+ const url = options.traceUrl({
176
+ traceId: spanContext.traceId,
177
+ spanId: spanContext.spanId
178
+ });
179
+ if (url !== void 0) properties["$trace_url"] = url;
180
+ } catch {}
181
+ return event;
182
+ };
183
+ }
184
+ //#endregion
185
+ //#region src/join.ts
186
+ /**
187
+ * Marks our hook so a second call recognises it. Framework code runs more than
188
+ * once — strict mode, HMR, a re-render — and a chain that grows on every render
189
+ * stamps the same properties again and again.
190
+ */
191
+ const MARKER = "__autotelBeforeSend";
192
+ function existingHooks(posthog) {
193
+ const current = posthog.config?.before_send;
194
+ if (Array.isArray(current)) return current;
195
+ return current ? [current] : [];
196
+ }
197
+ function joinPostHog(posthog, options = {}) {
198
+ const resolve = () => resolvePostHog({
199
+ ...options,
200
+ posthog
201
+ });
202
+ /**
203
+ * Returns true once the hook is in place. Kept retryable because the loader
204
+ * snippet's stub has no `set_config`: giving up at call time would leave
205
+ * every PostHog event on that page without its trace for the life of the
206
+ * page, and the real library usually arrives a moment later.
207
+ */
208
+ const wire = () => {
209
+ try {
210
+ const instance = resolve();
211
+ if (!instance) return false;
212
+ const hooks = existingHooks(instance);
213
+ if (hooks.some((hook) => hook[MARKER])) return true;
214
+ if (typeof instance.set_config !== "function") return false;
215
+ const hook = autotelBeforeSend(options);
216
+ hook[MARKER] = true;
217
+ instance.set_config({ before_send: [...hooks, hook] });
218
+ return true;
219
+ } catch {
220
+ return false;
221
+ }
222
+ };
223
+ let wired = wire();
224
+ const enricher = posthogCompatibility({
225
+ ...options,
226
+ posthog
227
+ });
228
+ return {
229
+ onStart(span, context) {
230
+ if (!wired) wired = wire();
231
+ enricher.onStart(span, context);
232
+ },
233
+ onEnd: (span) => enricher.onEnd(span),
234
+ forceFlush: () => enricher.forceFlush(),
235
+ shutdown: () => enricher.shutdown()
236
+ };
237
+ }
238
+ //#endregion
239
+ //#region src/session-id.ts
240
+ /**
241
+ * PostHog's session id, shaped for `autotel-web`'s `session.id` provider.
242
+ *
243
+ * The span enricher covers full mode, where there is an OpenTelemetry pipeline
244
+ * to hang a processor on. The minimal browser build has no such pipeline — it
245
+ * writes spans straight to OTLP — so it takes the id from a function instead,
246
+ * and this is that function:
247
+ *
248
+ * ```ts
249
+ * import { init } from 'autotel-web';
250
+ * import { posthogSessionId } from 'autotel-posthog';
251
+ *
252
+ * init({ service: 'web', session: { id: posthogSessionId } });
253
+ * ```
254
+ *
255
+ * Returns `undefined` when PostHog is absent or not yet initialized, which is
256
+ * the signal for autotel-web to fall back to minting its own id rather than
257
+ * emitting spans with no session at all.
258
+ */
259
+ function posthogSessionId(posthog) {
260
+ const instance = posthog ?? globalThis.posthog ?? void 0;
261
+ return instance ? readSessionId(instance) : void 0;
262
+ }
263
+ //#endregion
264
+ exports.autotelBeforeSend = autotelBeforeSend;
265
+ exports.joinPostHog = joinPostHog;
266
+ exports.posthogCompatibility = posthogCompatibility;
267
+ exports.posthogSessionId = posthogSessionId;