@zerolith/otel 0.0.0-canary.20261102.g8292c77

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,201 @@
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,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising 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
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,31 @@
1
+ # @zerolith/otel
2
+
3
+ Spans for zerolith applications through `@opentelemetry/api`, the one dependency this package has beyond zerolith. It adds nothing unless installed, and with the API's no-op tracer it costs nothing until an SDK is configured.
4
+
5
+ ```ts
6
+ import { trace } from "@opentelemetry/api";
7
+ import { navigationObserver, tracedHydrate, tracedTransport } from "@zerolith/otel";
8
+
9
+ const tracer = trace.getTracer("my-app");
10
+ const router = createRouter(appRoutes, { observe: navigationObserver(tracer) });
11
+ const api = createClient<Api>(apiRoutes, { transport: tracedTransport(undefined, tracer) });
12
+ tracedHydrate(App(router), "#app", tracer);
13
+ ```
14
+
15
+ - `navigationObserver` opens a span when a navigation starts and ends it on commit, failure, or cancel, with the route name, the path, and the mode as attributes, and `zerolith.navigation.canceled` on a canceled one.
16
+ - `tracedHydrate` wraps `hydrate` in a span and records the number of mismatches.
17
+ - `tracedTransport` wraps a client transport in a client span per request, with the method, URL, and status, and injects a `traceparent` header from the active span so the server's trace continues the browser's.
18
+
19
+ The guide is on the [docs site](https://zerolith.dev/guide/observability/).
20
+
21
+ Status: alpha. Install with `npm install @zerolith/otel@alpha`; the API may change before 1.0.
22
+
23
+ ## Documentation
24
+
25
+ - The [observability guide](https://zerolith.dev/guide/observability/) explains it with examples that run as tests.
26
+ - The [reference](https://zerolith.dev/reference/zerolith-otel/) lists every export, generated from the source.
27
+ - New to zerolith? The [tutorial](https://zerolith.dev/learn/) builds an app step by step, and the [playground](https://zerolith.dev/playground/) runs code in the browser.
28
+
29
+ ## License
30
+
31
+ Apache-2.0. See `LICENSE`.
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @zerolith/otel: spans through `@opentelemetry/api` for the three things
3
+ * worth tracing in a zerolith application: a navigation, a hydration, and
4
+ * a request of the typed client. The application supplies the tracer, so
5
+ * the SDK and the exporter stay its choice, and the API's no-op tracer
6
+ * makes every call free until one is configured.
7
+ */
8
+ import { type Context, type Tracer } from "@opentelemetry/api";
9
+ import { type HydrateResult, type MountTarget } from "zerolith";
10
+ import type { Transport } from "@zerolith/client";
11
+ import type { NavigationEvent } from "@zerolith/router";
12
+ /**
13
+ * The `observe` function for `createRouter`: a span named `navigate`
14
+ * opens when a navigation starts and ends when it commits, fails, or is
15
+ * canceled by a newer navigation, with `zerolith.route`, `url.path`,
16
+ * `url.query` when the URL has a query, and `zerolith.navigation.mode` as
17
+ * attributes, the loader's error recorded on failure, and
18
+ * `zerolith.navigation.canceled` set on a canceled one, whose status stays
19
+ * unset. The values of the query keys the URL conventions redact, such as
20
+ * `sig`, are recorded as `REDACTED`.
21
+ */
22
+ export declare function navigationObserver(tracer?: Tracer): (event: NavigationEvent) => void;
23
+ /** `hydrate` inside a span named `hydrate`, with the number of mismatches as `zerolith.hydration.mismatches`. */
24
+ export declare function tracedHydrate(view: unknown, container: MountTarget, tracer?: Tracer): HydrateResult;
25
+ /** The W3C `traceparent` header for a context, or undefined when no span is active in it. */
26
+ export declare function traceparent(active?: Context): string | undefined;
27
+ /**
28
+ * Wraps a transport, or `fetch` when none is given, so every request runs
29
+ * in a client span named by its method, as `GET`, with
30
+ * `http.request.method`, `url.full`, and `http.response.status_code`,
31
+ * carries a `traceparent` header from that span, and records a failed
32
+ * request as an error. The span is not named by the request's path, which
33
+ * would give every note its own span name; the HTTP conventions name a
34
+ * client span by its method when no route template is known. `url.full`
35
+ * records the values of the query keys the conventions redact, such as
36
+ * `sig`, as `REDACTED`.
37
+ */
38
+ export declare function tracedTransport(transport: Transport | undefined, tracer?: Tracer): Transport;
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAAE,KAAK,OAAO,EAAuC,KAAK,MAAM,EAAkB,MAAM,oBAAoB,CAAC;AACpH,OAAO,EAAE,KAAK,aAAa,EAAE,KAAK,WAAW,EAAW,MAAM,UAAU,CAAC;AACzE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAClD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,kBAAkB,CAAC;AAqBxD;;;;;;;;;GASG;AACH,wBAAgB,kBAAkB,CAAC,MAAM,GAAE,MAAwB,GAAG,CAAC,KAAK,EAAE,eAAe,KAAK,IAAI,CAsCrG;AAED,iHAAiH;AACjH,wBAAgB,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,MAAM,GAAE,MAAwB,GAAG,aAAa,CAsBpH;AAED,6FAA6F;AAC7F,wBAAgB,WAAW,CAAC,MAAM,GAAE,OAA0B,GAAG,MAAM,GAAG,SAAS,CAQlF;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,eAAe,CAAC,SAAS,EAAE,SAAS,GAAG,SAAS,EAAE,MAAM,GAAE,MAAwB,GAAG,SAAS,CA8B7G"}
package/dist/index.js ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * @zerolith/otel: spans through `@opentelemetry/api` for the three things
3
+ * worth tracing in a zerolith application: a navigation, a hydration, and
4
+ * a request of the typed client. The application supplies the tracer, so
5
+ * the SDK and the exporter stay its choice, and the API's no-op tracer
6
+ * makes every call free until one is configured.
7
+ */
8
+ import { SpanKind, SpanStatusCode, context, trace } from "@opentelemetry/api";
9
+ import { hydrate } from "zerolith";
10
+ /** The tracer used when none is given: the API's tracer for this package, a no-op until an SDK registers a provider. */
11
+ function defaultTracer() {
12
+ return trace.getTracer("@zerolith/otel");
13
+ }
14
+ /** The query keys whose values the URL conventions redact by default, such as a signed URL's signature. */
15
+ const SENSITIVE_QUERY = new Set(["X-Amz-Signature", "X-Amz-Credential", "X-Amz-Security-Token", "sig", "X-Goog-Signature"]);
16
+ /** A URL's query component without its `?`, with the value of each key the conventions redact replaced by `REDACTED`. */
17
+ function redactedQuery(search) {
18
+ return search.replace(/^\?/, "").split("&").map((pair) => {
19
+ const key = pair.split("=", 1)[0] ?? "";
20
+ return SENSITIVE_QUERY.has(key) ? `${key}=REDACTED` : pair;
21
+ }).join("&");
22
+ }
23
+ /**
24
+ * The `observe` function for `createRouter`: a span named `navigate`
25
+ * opens when a navigation starts and ends when it commits, fails, or is
26
+ * canceled by a newer navigation, with `zerolith.route`, `url.path`,
27
+ * `url.query` when the URL has a query, and `zerolith.navigation.mode` as
28
+ * attributes, the loader's error recorded on failure, and
29
+ * `zerolith.navigation.canceled` set on a canceled one, whose status stays
30
+ * unset. The values of the query keys the URL conventions redact, such as
31
+ * `sig`, are recorded as `REDACTED`.
32
+ */
33
+ export function navigationObserver(tracer = defaultTracer()) {
34
+ const open = new Map();
35
+ return (event) => {
36
+ if (event.type === "start") {
37
+ const query = redactedQuery(event.url.search);
38
+ const span = tracer.startSpan("navigate", {
39
+ kind: SpanKind.INTERNAL,
40
+ attributes: { "url.path": event.url.pathname, ...(query === "" ? {} : { "url.query": query }), "zerolith.navigation.mode": event.mode }
41
+ });
42
+ open.set(event.id, span);
43
+ return;
44
+ }
45
+ const span = open.get(event.id);
46
+ if (span === undefined) {
47
+ return;
48
+ }
49
+ open.delete(event.id);
50
+ if (event.type === "commit") {
51
+ span.setAttribute("zerolith.route", event.name ?? "");
52
+ span.setStatus({ code: SpanStatusCode.OK });
53
+ }
54
+ else if (event.type === "cancel") {
55
+ span.setAttribute("zerolith.navigation.canceled", true);
56
+ }
57
+ else {
58
+ const error = event.error;
59
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
60
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
61
+ }
62
+ span.end();
63
+ };
64
+ }
65
+ /** `hydrate` inside a span named `hydrate`, with the number of mismatches as `zerolith.hydration.mismatches`. */
66
+ export function tracedHydrate(view, container, tracer = defaultTracer()) {
67
+ return tracer.startActiveSpan("hydrate", (span) => {
68
+ try {
69
+ const result = hydrate(view, container);
70
+ span.setAttribute("zerolith.hydration.mismatches", result.mismatches.length);
71
+ span.setStatus({ code: SpanStatusCode.OK });
72
+ return result;
73
+ }
74
+ catch (error) {
75
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
76
+ span.setStatus({ code: SpanStatusCode.ERROR });
77
+ throw error;
78
+ }
79
+ finally {
80
+ span.end();
81
+ }
82
+ });
83
+ }
84
+ /** The W3C `traceparent` header for a context, or undefined when no span is active in it. */
85
+ export function traceparent(active = context.active()) {
86
+ const span = trace.getSpanContext(active);
87
+ if (span === undefined || !trace.isSpanContextValid(span)) {
88
+ return undefined;
89
+ }
90
+ return `00-${span.traceId}-${span.spanId}-${span.traceFlags.toString(16).padStart(2, "0")}`;
91
+ }
92
+ /**
93
+ * Wraps a transport, or `fetch` when none is given, so every request runs
94
+ * in a client span named by its method, as `GET`, with
95
+ * `http.request.method`, `url.full`, and `http.response.status_code`,
96
+ * carries a `traceparent` header from that span, and records a failed
97
+ * request as an error. The span is not named by the request's path, which
98
+ * would give every note its own span name; the HTTP conventions name a
99
+ * client span by its method when no route template is known. `url.full`
100
+ * records the values of the query keys the conventions redact, such as
101
+ * `sig`, as `REDACTED`.
102
+ */
103
+ export function tracedTransport(transport, tracer = defaultTracer()) {
104
+ const send = transport ?? ((request) => fetch(request));
105
+ return (request) => {
106
+ const full = new URL(request.url);
107
+ full.search = redactedQuery(full.search);
108
+ return tracer.startActiveSpan(request.method, { kind: SpanKind.CLIENT, attributes: { "http.request.method": request.method, "url.full": full.href } }, async (span) => {
109
+ try {
110
+ const header = traceparent();
111
+ const traced = header === undefined ? request : new Request(request, { headers: withHeader(request.headers, "traceparent", header) });
112
+ const response = await send(traced);
113
+ span.setAttribute("http.response.status_code", response.status);
114
+ span.setStatus(response.ok ? { code: SpanStatusCode.OK } : { code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` });
115
+ return response;
116
+ }
117
+ catch (error) {
118
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
119
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
120
+ throw error;
121
+ }
122
+ finally {
123
+ span.end();
124
+ }
125
+ });
126
+ };
127
+ }
128
+ function withHeader(headers, name, value) {
129
+ const copy = new Headers(headers);
130
+ copy.set(name, value);
131
+ return copy;
132
+ }
133
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,EAA2B,QAAQ,EAAE,cAAc,EAAe,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAC;AACpH,OAAO,EAAwC,OAAO,EAAE,MAAM,UAAU,CAAC;AAIzE,wHAAwH;AACxH,SAAS,aAAa;IAElB,OAAO,KAAK,CAAC,SAAS,CAAC,gBAAgB,CAAC,CAAC;AAC7C,CAAC;AAED,2GAA2G;AAC3G,MAAM,eAAe,GAAG,IAAI,GAAG,CAAC,CAAC,iBAAiB,EAAE,kBAAkB,EAAE,sBAAsB,EAAE,KAAK,EAAE,kBAAkB,CAAC,CAAC,CAAC;AAE5H,yHAAyH;AACzH,SAAS,aAAa,CAAC,MAAc;IAEjC,OAAO,MAAM,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE;QAErD,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;QACxC,OAAO,eAAe,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,WAAW,CAAC,CAAC,CAAC,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E,CAAC;YACf,CAAC;QACL,CAAC,CAAC,CAAC;IACP,CAAC,CAAC;AACN,CAAC;AAED,SAAS,UAAU,CAAC,OAAgB,EAAE,IAAY,EAAE,KAAa;IAE7D,MAAM,IAAI,GAAG,IAAI,OAAO,CAAC,OAAO,CAAC,CAAC;IAClC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;IACtB,OAAO,IAAI,CAAC;AAChB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,57 @@
1
+ {
2
+ "name": "@zerolith/otel",
3
+ "version": "0.0.0-canary.20261102.g8292c77",
4
+ "description": "OpenTelemetry spans for zerolith applications through @opentelemetry/api: a span per navigation, per hydration, and per request of the typed client with traceparent propagation",
5
+ "license": "Apache-2.0",
6
+ "author": "molexxxx",
7
+ "homepage": "https://zerolith.dev/",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/molexxxx/zerolith.git",
11
+ "directory": "packages/otel"
12
+ },
13
+ "bugs": {
14
+ "url": "https://github.com/molexxxx/zerolith/issues"
15
+ },
16
+ "keywords": [
17
+ "zerolith",
18
+ "opentelemetry",
19
+ "tracing"
20
+ ],
21
+ "type": "module",
22
+ "sideEffects": false,
23
+ "engines": {
24
+ "node": ">=24.0.0"
25
+ },
26
+ "exports": {
27
+ ".": {
28
+ "types": "./dist/index.d.ts",
29
+ "default": "./dist/index.js"
30
+ },
31
+ "./package.json": "./package.json"
32
+ },
33
+ "files": [
34
+ "dist",
35
+ "src",
36
+ "LICENSE",
37
+ "README.md"
38
+ ],
39
+ "scripts": {
40
+ "build": "tsc -p tsconfig.build.json"
41
+ },
42
+ "peerDependencies": {
43
+ "@opentelemetry/api": ">=1.9.0 <2.0.0",
44
+ "@zerolith/client": "^0.0.0-canary.20261102.g8292c77",
45
+ "@zerolith/router": "^0.0.0-canary.20261102.g8292c77",
46
+ "zerolith": "^0.0.0-canary.20261102.g8292c77"
47
+ },
48
+ "peerDependenciesMeta": {
49
+ "@zerolith/client": { "optional": true },
50
+ "@zerolith/router": { "optional": true }
51
+ },
52
+ "devDependencies": {
53
+ "@zerolith/client": "^0.0.0-canary.20261102.g8292c77",
54
+ "@zerolith/router": "^0.0.0-canary.20261102.g8292c77",
55
+ "zerolith": "^0.0.0-canary.20261102.g8292c77"
56
+ }
57
+ }
package/src/index.ts ADDED
@@ -0,0 +1,166 @@
1
+ /**
2
+ * @zerolith/otel: spans through `@opentelemetry/api` for the three things
3
+ * worth tracing in a zerolith application: a navigation, a hydration, and
4
+ * a request of the typed client. The application supplies the tracer, so
5
+ * the SDK and the exporter stay its choice, and the API's no-op tracer
6
+ * makes every call free until one is configured.
7
+ */
8
+ import { type Context, type Span, SpanKind, SpanStatusCode, type Tracer, context, trace } from "@opentelemetry/api";
9
+ import { type HydrateResult, type MountTarget, hydrate } from "zerolith";
10
+ import type { Transport } from "@zerolith/client";
11
+ import type { NavigationEvent } from "@zerolith/router";
12
+
13
+ /** The tracer used when none is given: the API's tracer for this package, a no-op until an SDK registers a provider. */
14
+ function defaultTracer(): Tracer
15
+ {
16
+ return trace.getTracer("@zerolith/otel");
17
+ }
18
+
19
+ /** The query keys whose values the URL conventions redact by default, such as a signed URL's signature. */
20
+ const SENSITIVE_QUERY = new Set(["X-Amz-Signature", "X-Amz-Credential", "X-Amz-Security-Token", "sig", "X-Goog-Signature"]);
21
+
22
+ /** A URL's query component without its `?`, with the value of each key the conventions redact replaced by `REDACTED`. */
23
+ function redactedQuery(search: string): string
24
+ {
25
+ return search.replace(/^\?/, "").split("&").map((pair) =>
26
+ {
27
+ const key = pair.split("=", 1)[0] ?? "";
28
+ return SENSITIVE_QUERY.has(key) ? `${key}=REDACTED` : pair;
29
+ }).join("&");
30
+ }
31
+
32
+ /**
33
+ * The `observe` function for `createRouter`: a span named `navigate`
34
+ * opens when a navigation starts and ends when it commits, fails, or is
35
+ * canceled by a newer navigation, with `zerolith.route`, `url.path`,
36
+ * `url.query` when the URL has a query, and `zerolith.navigation.mode` as
37
+ * attributes, the loader's error recorded on failure, and
38
+ * `zerolith.navigation.canceled` set on a canceled one, whose status stays
39
+ * unset. The values of the query keys the URL conventions redact, such as
40
+ * `sig`, are recorded as `REDACTED`.
41
+ */
42
+ export function navigationObserver(tracer: Tracer = defaultTracer()): (event: NavigationEvent) => void
43
+ {
44
+ const open = new Map<number, Span>();
45
+ return (event) =>
46
+ {
47
+ if (event.type === "start")
48
+ {
49
+ const query = redactedQuery(event.url.search);
50
+ const span = tracer.startSpan("navigate", {
51
+ kind: SpanKind.INTERNAL,
52
+ attributes: { "url.path": event.url.pathname, ...(query === "" ? {} : { "url.query": query }), "zerolith.navigation.mode": event.mode }
53
+ });
54
+ open.set(event.id, span);
55
+ return;
56
+ }
57
+ const span = open.get(event.id);
58
+ if (span === undefined)
59
+ {
60
+ return;
61
+ }
62
+ open.delete(event.id);
63
+ if (event.type === "commit")
64
+ {
65
+ span.setAttribute("zerolith.route", event.name ?? "");
66
+ span.setStatus({ code: SpanStatusCode.OK });
67
+ }
68
+ else if (event.type === "cancel")
69
+ {
70
+ span.setAttribute("zerolith.navigation.canceled", true);
71
+ }
72
+ else
73
+ {
74
+ const error = event.error;
75
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
76
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
77
+ }
78
+ span.end();
79
+ };
80
+ }
81
+
82
+ /** `hydrate` inside a span named `hydrate`, with the number of mismatches as `zerolith.hydration.mismatches`. */
83
+ export function tracedHydrate(view: unknown, container: MountTarget, tracer: Tracer = defaultTracer()): HydrateResult
84
+ {
85
+ return tracer.startActiveSpan("hydrate", (span) =>
86
+ {
87
+ try
88
+ {
89
+ const result = hydrate(view, container);
90
+ span.setAttribute("zerolith.hydration.mismatches", result.mismatches.length);
91
+ span.setStatus({ code: SpanStatusCode.OK });
92
+ return result;
93
+ }
94
+ catch (error)
95
+ {
96
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
97
+ span.setStatus({ code: SpanStatusCode.ERROR });
98
+ throw error;
99
+ }
100
+ finally
101
+ {
102
+ span.end();
103
+ }
104
+ });
105
+ }
106
+
107
+ /** The W3C `traceparent` header for a context, or undefined when no span is active in it. */
108
+ export function traceparent(active: Context = context.active()): string | undefined
109
+ {
110
+ const span = trace.getSpanContext(active);
111
+ if (span === undefined || !trace.isSpanContextValid(span))
112
+ {
113
+ return undefined;
114
+ }
115
+ return `00-${span.traceId}-${span.spanId}-${span.traceFlags.toString(16).padStart(2, "0")}`;
116
+ }
117
+
118
+ /**
119
+ * Wraps a transport, or `fetch` when none is given, so every request runs
120
+ * in a client span named by its method, as `GET`, with
121
+ * `http.request.method`, `url.full`, and `http.response.status_code`,
122
+ * carries a `traceparent` header from that span, and records a failed
123
+ * request as an error. The span is not named by the request's path, which
124
+ * would give every note its own span name; the HTTP conventions name a
125
+ * client span by its method when no route template is known. `url.full`
126
+ * records the values of the query keys the conventions redact, such as
127
+ * `sig`, as `REDACTED`.
128
+ */
129
+ export function tracedTransport(transport: Transport | undefined, tracer: Tracer = defaultTracer()): Transport
130
+ {
131
+ const send: Transport = transport ?? ((request) => fetch(request));
132
+ return (request) =>
133
+ {
134
+ const full = new URL(request.url);
135
+ full.search = redactedQuery(full.search);
136
+ return tracer.startActiveSpan(request.method, { kind: SpanKind.CLIENT, attributes: { "http.request.method": request.method, "url.full": full.href } }, async (span) =>
137
+ {
138
+ try
139
+ {
140
+ const header = traceparent();
141
+ const traced = header === undefined ? request : new Request(request, { headers: withHeader(request.headers, "traceparent", header) });
142
+ const response = await send(traced);
143
+ span.setAttribute("http.response.status_code", response.status);
144
+ span.setStatus(response.ok ? { code: SpanStatusCode.OK } : { code: SpanStatusCode.ERROR, message: `HTTP ${response.status}` });
145
+ return response;
146
+ }
147
+ catch (error)
148
+ {
149
+ span.recordException(error instanceof Error ? error : new Error(String(error)));
150
+ span.setStatus({ code: SpanStatusCode.ERROR, message: error instanceof Error ? error.message : String(error) });
151
+ throw error;
152
+ }
153
+ finally
154
+ {
155
+ span.end();
156
+ }
157
+ });
158
+ };
159
+ }
160
+
161
+ function withHeader(headers: Headers, name: string, value: string): Headers
162
+ {
163
+ const copy = new Headers(headers);
164
+ copy.set(name, value);
165
+ return copy;
166
+ }