@zharp/cloudflare 0.0.0-stage → 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 +21 -0
- package/README.md +88 -3
- package/dist/index.d.mts +163 -0
- package/dist/index.d.ts +163 -0
- package/dist/index.js +9 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +9 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +70 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Zharp
|
|
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.
|
package/README.md
CHANGED
|
@@ -1,3 +1,88 @@
|
|
|
1
|
-
#
|
|
2
|
-
|
|
3
|
-
|
|
1
|
+
# @zharp/cloudflare
|
|
2
|
+
|
|
3
|
+
Zharp Application Monitoring for **Cloudflare Workers**, **Durable Objects** and **Pages Functions**:
|
|
4
|
+
errors with readable stacks (each counted once), a trace per request continued from the caller's
|
|
5
|
+
`traceparent` and carried on to the services it calls, failed D1 queries with their SQL, spans for
|
|
6
|
+
D1, KV, R2, Queues, service bindings and Durable Objects, and logs when you ask for them.
|
|
7
|
+
|
|
8
|
+
Small (about 40 KB minified with `@opentelemetry/api`), sent with `ctx.waitUntil` so responses are
|
|
9
|
+
never held up. Needs the `nodejs_compat` flag (AsyncLocalStorage).
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm init zharp@latest # finds wrangler.toml / wrangler.jsonc and does all of the below
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## Workers
|
|
16
|
+
|
|
17
|
+
```ts
|
|
18
|
+
import { withZharp } from '@zharp/cloudflare';
|
|
19
|
+
|
|
20
|
+
export default withZharp({
|
|
21
|
+
async fetch(request, env, ctx) { … },
|
|
22
|
+
async scheduled(controller, env, ctx) { … },
|
|
23
|
+
async queue(batch, env, ctx) { … },
|
|
24
|
+
});
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
```sh
|
|
28
|
+
npx wrangler secret put ZHARP_KEY # the app key from the Zharp dashboard
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Hono works the same — `export default withZharp(app)` — and spans are named after Hono's matched
|
|
32
|
+
route. Settings can also be passed in code: `withZharp((env) => ({ key: env.ZHARP_KEY }), handler)`.
|
|
33
|
+
|
|
34
|
+
## Durable Objects
|
|
35
|
+
|
|
36
|
+
```ts
|
|
37
|
+
import { instrumentDurableObject } from '@zharp/cloudflare';
|
|
38
|
+
|
|
39
|
+
class CartObject extends DurableObject { … }
|
|
40
|
+
export const Cart = instrumentDurableObject(CartObject);
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Each `fetch`, RPC method, `alarm` and WebSocket message is a span; what they throw is reported.
|
|
44
|
+
|
|
45
|
+
## Pages Functions
|
|
46
|
+
|
|
47
|
+
```ts
|
|
48
|
+
// functions/_middleware.ts
|
|
49
|
+
import { zharpPagesPlugin } from '@zharp/cloudflare';
|
|
50
|
+
|
|
51
|
+
export const onRequest = zharpPagesPlugin();
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Settings (vars and secrets)
|
|
55
|
+
|
|
56
|
+
| Variable | |
|
|
57
|
+
|---|---|
|
|
58
|
+
| `ZHARP_KEY` | The app key (a secret). Without it nothing is sent. |
|
|
59
|
+
| `ZHARP_SERVICE` | `service.name`; default `worker` (Pages: `pages`). |
|
|
60
|
+
| `ZHARP_ENVIRONMENT` | `deployment.environment.name`. |
|
|
61
|
+
| `ZHARP_RELEASE` | The release source maps are matched by; default the deployed version's ID (`version_metadata` binding `CF_VERSION_METADATA`). |
|
|
62
|
+
| `ZHARP_LOGS` | `true` sends `console.*` lines with their trace. Off by default: Workers Logs keeps them. |
|
|
63
|
+
| `ZHARP_TRACING` | `false`: errors and logs only. |
|
|
64
|
+
| `ZHARP_SAMPLE_RATE` | 0–1, default 1. |
|
|
65
|
+
| `ZHARP_CAPTURE_HEADERS` | `false` turns request/response headers off (secrets are always `[Filtered]`). |
|
|
66
|
+
| `ZHARP_DISABLED` | `true`: send nothing. |
|
|
67
|
+
|
|
68
|
+
## Readable stacks
|
|
69
|
+
|
|
70
|
+
Wrangler bundles and minifies; Zharp maps stacks back with the build's source maps, matched by
|
|
71
|
+
release:
|
|
72
|
+
|
|
73
|
+
```sh
|
|
74
|
+
wrangler deploy --outdir .wrangler/zharp-dist --var ZHARP_RELEASE:$SHA
|
|
75
|
+
ZHARP_AUTH_TOKEN=… npx zharp sourcemaps upload .wrangler/zharp-dist --release $SHA --app <id>
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
(with `upload_source_maps = true` in the Wrangler config, so the build has its maps). Projects built
|
|
79
|
+
with Cloudflare's Vite plugin can use `@zharp/vite-plugin` instead.
|
|
80
|
+
|
|
81
|
+
## API
|
|
82
|
+
|
|
83
|
+
`Zharp.captureError(error, attributes?)`, `Zharp.setUser({ id, email, name })`,
|
|
84
|
+
`Zharp.setTag(key, value)`, `Zharp.log.info(message, attributes?)` (and the other levels),
|
|
85
|
+
`Zharp.startSpan(name, fn)`, `Zharp.flush()`. Inside a request, the user and tags belong to that
|
|
86
|
+
request only.
|
|
87
|
+
|
|
88
|
+
Docs: https://zharp.io/docs/sdks/cloudflare
|
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { CaptureHeaders } from '@zharp/internal/headers';
|
|
2
|
+
|
|
3
|
+
type Attributes = Record<string, unknown>;
|
|
4
|
+
interface ZharpUser {
|
|
5
|
+
/** Sent as `enduser.id`. An ID or an email — whatever identifies the person in your app. */
|
|
6
|
+
id: string | number;
|
|
7
|
+
/** Sent as `enduser.email`. */
|
|
8
|
+
email?: string;
|
|
9
|
+
/** Sent as `enduser.name`. */
|
|
10
|
+
name?: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Settings for `withZharp`, `instrumentDurableObject` and `zharpPagesPlugin`. Every one of them
|
|
14
|
+
* can also come from the Worker's environment (vars and secrets), which is where they usually
|
|
15
|
+
* live: the options passed in code win.
|
|
16
|
+
*/
|
|
17
|
+
interface ZharpCloudflareOptions {
|
|
18
|
+
/**
|
|
19
|
+
* The app's key from the Zharp dashboard (`zpk_…`). Falls back to the `ZHARP_KEY` secret
|
|
20
|
+
* (`wrangler secret put ZHARP_KEY`). Without one nothing is sent, and the Worker runs as before.
|
|
21
|
+
*/
|
|
22
|
+
key?: string;
|
|
23
|
+
/** `service.name`. Falls back to `ZHARP_SERVICE`, then `worker` (Pages: `pages`). */
|
|
24
|
+
service?: string;
|
|
25
|
+
/** `deployment.environment.name`. Falls back to `ZHARP_ENVIRONMENT`. */
|
|
26
|
+
environment?: string;
|
|
27
|
+
/**
|
|
28
|
+
* `service.version`: what uploaded source maps are matched by. Falls back to `ZHARP_RELEASE`
|
|
29
|
+
* (`wrangler deploy --var ZHARP_RELEASE:$SHA`), then the deployed version's ID from the
|
|
30
|
+
* `CF_VERSION_METADATA` binding.
|
|
31
|
+
*/
|
|
32
|
+
release?: string;
|
|
33
|
+
/** Default `https://api.zharp.io/api/v1/otlp`. Falls back to `ZHARP_ENDPOINT`. */
|
|
34
|
+
endpoint?: string;
|
|
35
|
+
/**
|
|
36
|
+
* Fraction of traces to keep, 0 to 1. Default 1. A request that arrives with a `traceparent`
|
|
37
|
+
* keeps its caller's decision. Errors are always sent. Falls back to `ZHARP_SAMPLE_RATE`.
|
|
38
|
+
*/
|
|
39
|
+
sampleRate?: number;
|
|
40
|
+
/** Traces. Default true; `false` (or `ZHARP_TRACING=false`) sends errors and logs only. */
|
|
41
|
+
tracing?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Send `console.*` output as logs, each with its request's trace. Default **false**: Cloudflare's
|
|
44
|
+
* Workers Logs keeps it already. Falls back to `ZHARP_LOGS` (`true` turns it on). Errors and
|
|
45
|
+
* `Zharp.log` are sent either way.
|
|
46
|
+
*/
|
|
47
|
+
logs?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Request and response headers on HTTP spans. Default on; secrets (`authorization`, `cookie`,
|
|
50
|
+
* API keys, tokens…) are recorded as `[Filtered]`. `false` (or `ZHARP_CAPTURE_HEADERS=false`)
|
|
51
|
+
* turns it off; `{ redact: [...] }` filters more names.
|
|
52
|
+
*/
|
|
53
|
+
captureHeaders?: CaptureHeaders;
|
|
54
|
+
/**
|
|
55
|
+
* Failed D1 queries reported as errors with the line of your code that ran them and the SQL.
|
|
56
|
+
* Default true.
|
|
57
|
+
*/
|
|
58
|
+
captureQueryErrors?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Outgoing requests that get no span and no `traceparent` (a bare host, a URL prefix, or a
|
|
61
|
+
* RegExp tested against the full URL).
|
|
62
|
+
*/
|
|
63
|
+
ignoreUrls?: Array<string | RegExp>;
|
|
64
|
+
}
|
|
65
|
+
/** Options, or a function that reads them from the Worker's `env`. */
|
|
66
|
+
type ZharpConfig<E = any> = ZharpCloudflareOptions | ((env: E) => ZharpCloudflareOptions);
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The SDK in one isolate: settings read from the first `env` it sees, the queues of spans and
|
|
70
|
+
* logs, and how errors are reported. And the state of each request (or alarm, queue batch,
|
|
71
|
+
* cron run) it handles: its tags, its user, and what it still has to send when it ends.
|
|
72
|
+
*
|
|
73
|
+
* An isolate lives across many requests, so nothing about a request is kept outside its state;
|
|
74
|
+
* and there is no timer to send things later — each request flushes with `ctx.waitUntil`, so the
|
|
75
|
+
* response is not held up and the work still finishes.
|
|
76
|
+
*/
|
|
77
|
+
|
|
78
|
+
declare const SEVERITY: {
|
|
79
|
+
readonly trace: 1;
|
|
80
|
+
readonly debug: 5;
|
|
81
|
+
readonly info: 9;
|
|
82
|
+
readonly warn: 13;
|
|
83
|
+
readonly error: 17;
|
|
84
|
+
readonly fatal: 21;
|
|
85
|
+
};
|
|
86
|
+
type Level = keyof typeof SEVERITY;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* A Worker's default export, traced:
|
|
90
|
+
*
|
|
91
|
+
* export default withZharp((env) => ({ key: env.ZHARP_KEY }), {
|
|
92
|
+
* async fetch(request, env, ctx) { … },
|
|
93
|
+
* async scheduled(controller, env, ctx) { … },
|
|
94
|
+
* });
|
|
95
|
+
*
|
|
96
|
+
* The handler can be an object (`{ fetch, scheduled, queue }`), a Hono app, or a
|
|
97
|
+
* `WorkerEntrypoint` class. With no config, settings come from `env` (`ZHARP_KEY`, …).
|
|
98
|
+
*/
|
|
99
|
+
declare function withZharp<H>(handler: H): H;
|
|
100
|
+
declare function withZharp<H, E = any>(config: ZharpConfig<E> | undefined, handler: H): H;
|
|
101
|
+
/**
|
|
102
|
+
* A Durable Object class, traced: each `fetch`, RPC method, `alarm` and WebSocket message is a
|
|
103
|
+
* span, and errors are reported.
|
|
104
|
+
*
|
|
105
|
+
* export const Cart = instrumentDurableObject(CartObject);
|
|
106
|
+
*
|
|
107
|
+
* Settings come from `config`, else from the config given to `withZharp`, else from `env`.
|
|
108
|
+
*/
|
|
109
|
+
declare function instrumentDurableObject<C extends new (...args: any[]) => any>(cls: C, config?: ZharpConfig): C;
|
|
110
|
+
interface PagesContext {
|
|
111
|
+
request: Request;
|
|
112
|
+
env: Record<string, unknown>;
|
|
113
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
114
|
+
next(input?: Request | string, init?: RequestInit): Promise<Response>;
|
|
115
|
+
functionPath?: string;
|
|
116
|
+
[key: string]: unknown;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Pages Functions: in `functions/_middleware.ts`,
|
|
120
|
+
*
|
|
121
|
+
* export const onRequest = zharpPagesPlugin((context) => ({ key: context.env.ZHARP_KEY }));
|
|
122
|
+
*
|
|
123
|
+
* Every request through the project's Functions is a span, errors they throw are reported, and
|
|
124
|
+
* D1, KV, R2 and the rest of `context.env` are traced for the functions after it.
|
|
125
|
+
*/
|
|
126
|
+
declare function zharpPagesPlugin<E = any>(config?: ZharpConfig<E> | ((context: PagesContext) => ReturnType<Extract<ZharpConfig<E>, Function>>)): (context: PagesContext) => Promise<Response>;
|
|
127
|
+
|
|
128
|
+
/** Sent as telemetry.sdk.version. Kept in step with package.json. */
|
|
129
|
+
declare const VERSION = "0.1.0";
|
|
130
|
+
|
|
131
|
+
type LogFn = (message: unknown, attributes?: Attributes) => void;
|
|
132
|
+
/** A span made with `Zharp.startSpan`. */
|
|
133
|
+
interface ZharpSpanHandle {
|
|
134
|
+
readonly traceId: string;
|
|
135
|
+
readonly spanId: string;
|
|
136
|
+
setAttribute(key: string, value: unknown): ZharpSpanHandle;
|
|
137
|
+
setAttributes(attributes: Attributes): ZharpSpanHandle;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The API, as in the other Zharp JavaScript SDKs. Inside a request, tags and the user belong to
|
|
141
|
+
* that request only; outside one (at module scope) they apply to everything this isolate sends.
|
|
142
|
+
*/
|
|
143
|
+
declare const Zharp: {
|
|
144
|
+
/** Report an error you caught. Sent as handled, grouped with its other occurrences. */
|
|
145
|
+
captureError(error: unknown, attributes?: Attributes): void;
|
|
146
|
+
/** Who the request is for: `enduser.id` (and email, name) on its spans, logs and errors. */
|
|
147
|
+
setUser(user: ZharpUser | null): void;
|
|
148
|
+
/** An attribute on the request's spans, logs and errors. `null` removes it. */
|
|
149
|
+
setTag(key: string, value: string | number | boolean | null | undefined): void;
|
|
150
|
+
/** Logs, sent whatever `ZHARP_LOGS` says, with the active request's trace. */
|
|
151
|
+
log: Record<Level, LogFn>;
|
|
152
|
+
/**
|
|
153
|
+
* Run `fn` in a span named `name`. Fetches, queries and logs inside it belong to it; a promise
|
|
154
|
+
* it returns ends the span when it settles. Errors pass through unchanged.
|
|
155
|
+
*/
|
|
156
|
+
startSpan<T>(name: string, fn: (span: ZharpSpanHandle) => T, attributes?: Attributes): T;
|
|
157
|
+
/** The active span's trace ID, e.g. to show on an error page. */
|
|
158
|
+
readonly traceId: string | undefined;
|
|
159
|
+
/** Send everything queued now. The wrappers already do this at the end of each request. */
|
|
160
|
+
flush(): Promise<void>;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
export { type Attributes, VERSION, Zharp, type ZharpCloudflareOptions, type ZharpConfig, type ZharpSpanHandle, type ZharpUser, Zharp as default, instrumentDurableObject, withZharp, zharpPagesPlugin };
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { CaptureHeaders } from '@zharp/internal/headers';
|
|
2
|
+
|
|
3
|
+
type Attributes = Record<string, unknown>;
|
|
4
|
+
interface ZharpUser {
|
|
5
|
+
/** Sent as `enduser.id`. An ID or an email — whatever identifies the person in your app. */
|
|
6
|
+
id: string | number;
|
|
7
|
+
/** Sent as `enduser.email`. */
|
|
8
|
+
email?: string;
|
|
9
|
+
/** Sent as `enduser.name`. */
|
|
10
|
+
name?: string;
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* Settings for `withZharp`, `instrumentDurableObject` and `zharpPagesPlugin`. Every one of them
|
|
14
|
+
* can also come from the Worker's environment (vars and secrets), which is where they usually
|
|
15
|
+
* live: the options passed in code win.
|
|
16
|
+
*/
|
|
17
|
+
interface ZharpCloudflareOptions {
|
|
18
|
+
/**
|
|
19
|
+
* The app's key from the Zharp dashboard (`zpk_…`). Falls back to the `ZHARP_KEY` secret
|
|
20
|
+
* (`wrangler secret put ZHARP_KEY`). Without one nothing is sent, and the Worker runs as before.
|
|
21
|
+
*/
|
|
22
|
+
key?: string;
|
|
23
|
+
/** `service.name`. Falls back to `ZHARP_SERVICE`, then `worker` (Pages: `pages`). */
|
|
24
|
+
service?: string;
|
|
25
|
+
/** `deployment.environment.name`. Falls back to `ZHARP_ENVIRONMENT`. */
|
|
26
|
+
environment?: string;
|
|
27
|
+
/**
|
|
28
|
+
* `service.version`: what uploaded source maps are matched by. Falls back to `ZHARP_RELEASE`
|
|
29
|
+
* (`wrangler deploy --var ZHARP_RELEASE:$SHA`), then the deployed version's ID from the
|
|
30
|
+
* `CF_VERSION_METADATA` binding.
|
|
31
|
+
*/
|
|
32
|
+
release?: string;
|
|
33
|
+
/** Default `https://api.zharp.io/api/v1/otlp`. Falls back to `ZHARP_ENDPOINT`. */
|
|
34
|
+
endpoint?: string;
|
|
35
|
+
/**
|
|
36
|
+
* Fraction of traces to keep, 0 to 1. Default 1. A request that arrives with a `traceparent`
|
|
37
|
+
* keeps its caller's decision. Errors are always sent. Falls back to `ZHARP_SAMPLE_RATE`.
|
|
38
|
+
*/
|
|
39
|
+
sampleRate?: number;
|
|
40
|
+
/** Traces. Default true; `false` (or `ZHARP_TRACING=false`) sends errors and logs only. */
|
|
41
|
+
tracing?: boolean;
|
|
42
|
+
/**
|
|
43
|
+
* Send `console.*` output as logs, each with its request's trace. Default **false**: Cloudflare's
|
|
44
|
+
* Workers Logs keeps it already. Falls back to `ZHARP_LOGS` (`true` turns it on). Errors and
|
|
45
|
+
* `Zharp.log` are sent either way.
|
|
46
|
+
*/
|
|
47
|
+
logs?: boolean;
|
|
48
|
+
/**
|
|
49
|
+
* Request and response headers on HTTP spans. Default on; secrets (`authorization`, `cookie`,
|
|
50
|
+
* API keys, tokens…) are recorded as `[Filtered]`. `false` (or `ZHARP_CAPTURE_HEADERS=false`)
|
|
51
|
+
* turns it off; `{ redact: [...] }` filters more names.
|
|
52
|
+
*/
|
|
53
|
+
captureHeaders?: CaptureHeaders;
|
|
54
|
+
/**
|
|
55
|
+
* Failed D1 queries reported as errors with the line of your code that ran them and the SQL.
|
|
56
|
+
* Default true.
|
|
57
|
+
*/
|
|
58
|
+
captureQueryErrors?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* Outgoing requests that get no span and no `traceparent` (a bare host, a URL prefix, or a
|
|
61
|
+
* RegExp tested against the full URL).
|
|
62
|
+
*/
|
|
63
|
+
ignoreUrls?: Array<string | RegExp>;
|
|
64
|
+
}
|
|
65
|
+
/** Options, or a function that reads them from the Worker's `env`. */
|
|
66
|
+
type ZharpConfig<E = any> = ZharpCloudflareOptions | ((env: E) => ZharpCloudflareOptions);
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The SDK in one isolate: settings read from the first `env` it sees, the queues of spans and
|
|
70
|
+
* logs, and how errors are reported. And the state of each request (or alarm, queue batch,
|
|
71
|
+
* cron run) it handles: its tags, its user, and what it still has to send when it ends.
|
|
72
|
+
*
|
|
73
|
+
* An isolate lives across many requests, so nothing about a request is kept outside its state;
|
|
74
|
+
* and there is no timer to send things later — each request flushes with `ctx.waitUntil`, so the
|
|
75
|
+
* response is not held up and the work still finishes.
|
|
76
|
+
*/
|
|
77
|
+
|
|
78
|
+
declare const SEVERITY: {
|
|
79
|
+
readonly trace: 1;
|
|
80
|
+
readonly debug: 5;
|
|
81
|
+
readonly info: 9;
|
|
82
|
+
readonly warn: 13;
|
|
83
|
+
readonly error: 17;
|
|
84
|
+
readonly fatal: 21;
|
|
85
|
+
};
|
|
86
|
+
type Level = keyof typeof SEVERITY;
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* A Worker's default export, traced:
|
|
90
|
+
*
|
|
91
|
+
* export default withZharp((env) => ({ key: env.ZHARP_KEY }), {
|
|
92
|
+
* async fetch(request, env, ctx) { … },
|
|
93
|
+
* async scheduled(controller, env, ctx) { … },
|
|
94
|
+
* });
|
|
95
|
+
*
|
|
96
|
+
* The handler can be an object (`{ fetch, scheduled, queue }`), a Hono app, or a
|
|
97
|
+
* `WorkerEntrypoint` class. With no config, settings come from `env` (`ZHARP_KEY`, …).
|
|
98
|
+
*/
|
|
99
|
+
declare function withZharp<H>(handler: H): H;
|
|
100
|
+
declare function withZharp<H, E = any>(config: ZharpConfig<E> | undefined, handler: H): H;
|
|
101
|
+
/**
|
|
102
|
+
* A Durable Object class, traced: each `fetch`, RPC method, `alarm` and WebSocket message is a
|
|
103
|
+
* span, and errors are reported.
|
|
104
|
+
*
|
|
105
|
+
* export const Cart = instrumentDurableObject(CartObject);
|
|
106
|
+
*
|
|
107
|
+
* Settings come from `config`, else from the config given to `withZharp`, else from `env`.
|
|
108
|
+
*/
|
|
109
|
+
declare function instrumentDurableObject<C extends new (...args: any[]) => any>(cls: C, config?: ZharpConfig): C;
|
|
110
|
+
interface PagesContext {
|
|
111
|
+
request: Request;
|
|
112
|
+
env: Record<string, unknown>;
|
|
113
|
+
waitUntil(promise: Promise<unknown>): void;
|
|
114
|
+
next(input?: Request | string, init?: RequestInit): Promise<Response>;
|
|
115
|
+
functionPath?: string;
|
|
116
|
+
[key: string]: unknown;
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* Pages Functions: in `functions/_middleware.ts`,
|
|
120
|
+
*
|
|
121
|
+
* export const onRequest = zharpPagesPlugin((context) => ({ key: context.env.ZHARP_KEY }));
|
|
122
|
+
*
|
|
123
|
+
* Every request through the project's Functions is a span, errors they throw are reported, and
|
|
124
|
+
* D1, KV, R2 and the rest of `context.env` are traced for the functions after it.
|
|
125
|
+
*/
|
|
126
|
+
declare function zharpPagesPlugin<E = any>(config?: ZharpConfig<E> | ((context: PagesContext) => ReturnType<Extract<ZharpConfig<E>, Function>>)): (context: PagesContext) => Promise<Response>;
|
|
127
|
+
|
|
128
|
+
/** Sent as telemetry.sdk.version. Kept in step with package.json. */
|
|
129
|
+
declare const VERSION = "0.1.0";
|
|
130
|
+
|
|
131
|
+
type LogFn = (message: unknown, attributes?: Attributes) => void;
|
|
132
|
+
/** A span made with `Zharp.startSpan`. */
|
|
133
|
+
interface ZharpSpanHandle {
|
|
134
|
+
readonly traceId: string;
|
|
135
|
+
readonly spanId: string;
|
|
136
|
+
setAttribute(key: string, value: unknown): ZharpSpanHandle;
|
|
137
|
+
setAttributes(attributes: Attributes): ZharpSpanHandle;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* The API, as in the other Zharp JavaScript SDKs. Inside a request, tags and the user belong to
|
|
141
|
+
* that request only; outside one (at module scope) they apply to everything this isolate sends.
|
|
142
|
+
*/
|
|
143
|
+
declare const Zharp: {
|
|
144
|
+
/** Report an error you caught. Sent as handled, grouped with its other occurrences. */
|
|
145
|
+
captureError(error: unknown, attributes?: Attributes): void;
|
|
146
|
+
/** Who the request is for: `enduser.id` (and email, name) on its spans, logs and errors. */
|
|
147
|
+
setUser(user: ZharpUser | null): void;
|
|
148
|
+
/** An attribute on the request's spans, logs and errors. `null` removes it. */
|
|
149
|
+
setTag(key: string, value: string | number | boolean | null | undefined): void;
|
|
150
|
+
/** Logs, sent whatever `ZHARP_LOGS` says, with the active request's trace. */
|
|
151
|
+
log: Record<Level, LogFn>;
|
|
152
|
+
/**
|
|
153
|
+
* Run `fn` in a span named `name`. Fetches, queries and logs inside it belong to it; a promise
|
|
154
|
+
* it returns ends the span when it settles. Errors pass through unchanged.
|
|
155
|
+
*/
|
|
156
|
+
startSpan<T>(name: string, fn: (span: ZharpSpanHandle) => T, attributes?: Attributes): T;
|
|
157
|
+
/** The active span's trace ID, e.g. to show on an error page. */
|
|
158
|
+
readonly traceId: string | undefined;
|
|
159
|
+
/** Send everything queued now. The wrappers already do this at the end of each request. */
|
|
160
|
+
flush(): Promise<void>;
|
|
161
|
+
};
|
|
162
|
+
|
|
163
|
+
export { type Attributes, VERSION, Zharp, type ZharpCloudflareOptions, type ZharpConfig, type ZharpSpanHandle, type ZharpUser, Zharp as default, instrumentDurableObject, withZharp, zharpPagesPlugin };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var api=require('@opentelemetry/api'),node_async_hooks=require('node:async_hooks');var Et="zharp.debug_ids",J=new Map,Pe=new Set;function At(){let e=typeof globalThis<"u"?globalThis:void 0,t=e&&e.__zharpDebugIds;return t&&typeof t=="object"?t:void 0}function $e(e){let t=e.trim();if(!t)return;let n=/^at (?:async )?(?:.*? \()?(.+?):\d+:\d+\)?$/.exec(t);if(n)return Le(n[1]);if(!t.startsWith("at "))return n=/^(?:[^@]*@)?(.+?):\d+:\d+$/.exec(t),n?Le(n[1]):void 0}function Le(e){let t=e.replace(/^address at /,"");if(!(!t||t.includes("eval at ")||t==="<anonymous>"||t==="native"))return t}function Tt(e){let t=[];for(let n of e.split(`
|
|
2
|
+
`)){let r=$e(n);r&&!t.includes(r)&&t.push(r);}return t}function Ct(){let e=At();if(e)for(let t in e){if(Pe.has(t))continue;Pe.add(t);let n=e[t];if(typeof n=="string")for(let r of t.split(`
|
|
3
|
+
`)){let o=$e(r);if(o){J.set(o,n);break}}}}function qt(e){if(e)try{if(Ct(),J.size===0)return;let t;for(let n of Tt(e)){let r=J.get(n);r&&((t??={})[n]=r);}return t}catch{return}}function V(e){let t=qt(e);return t?{[Et]:JSON.stringify(t)}:{}}function ee(e){let t=new Uint8Array(e),n=typeof crypto<"u"?crypto:void 0;if(n&&n.getRandomValues)n.getRandomValues(t);else for(let o=0;o<e;o++)t[o]=Math.random()*256|0;let r="";for(let o=0;o<e;o++)r+=(t[o]<16?"0":"")+t[o].toString(16);return /^0+$/.test(r)?ee(e):r}var je=()=>ee(16),He=()=>ee(8);function q(){let e=typeof performance<"u"?performance:void 0;return e&&e.timeOrigin?e.timeOrigin+e.now():Date.now()}function P(e){let t=Math.floor(e),n=Math.round((e-t)*1e6);return n>=1e6?`${t+1}000000`:`${t}${String(n).padStart(6,"0")}`}function Ue(e,t=0){return typeof e=="string"?{stringValue:e}:typeof e=="boolean"?{boolValue:e}:typeof e=="number"?Number.isInteger(e)?{intValue:e}:{doubleValue:e}:e instanceof Error?{stringValue:`${e.name}: ${e.message}`}:e==null?{stringValue:""}:t<4&&Array.isArray(e)?{arrayValue:{values:e.map(n=>Ue(n,t+1))}}:t<4&&typeof e=="object"?{kvlistValue:{values:O(e,t+1)}}:{stringValue:L(e)}}function O(e,t=0){let n=[];for(let r in e){let o=e[r];o!==void 0&&n.push({key:r,value:Ue(o,t)});}return n}function L(e){if(typeof e=="string")return e;if(e instanceof Error)return `${e.name}: ${e.message}`;try{let t=JSON.stringify(e);return t===void 0?String(e):t}catch{return String(e)}}function l(e){try{return e()}catch{return}}function K(e){return typeof TextEncoder<"u"?new TextEncoder().encode(e).length:e.length*2}function W(e){if(e instanceof Error)return e;if(e&&typeof e=="object"&&typeof e.message=="string"){let t=new Error(e.message);return t.name=typeof e.name=="string"?e.name:"Error",typeof e.stack=="string"&&(t.stack=e.stack),t}return new Error(typeof e=="string"?e:`Non-Error thrown: ${L(e)}`)}function te(e,t){let n=(e.name&&e.name!=="Error"?e.name:e.constructor?.name)||"Error",r=e.message||"",o=`${n}: ${r}`,s=typeof e.stack=="string"?e.stack:"";return s.startsWith(e.name||n)||(s=s?`${o}
|
|
4
|
+
${s}`:o),{"exception.type":n,"exception.message":r,"exception.stacktrace":s,"zharp.handled":t?"true":"false",...V(s)}}var Ot={debug:"debug",log:"info",info:"info",warn:"warn",error:"error"};function Fe(e,t){let n={},r=false;for(let o of e){let s=console[o];if(typeof s!="function"||s.__zharp)continue;n[o]=s;let i=function(...a){s.apply(this??console,a),!r&&(r=true,l(()=>{let u=a.map(c=>c instanceof Error?c.stack||String(c):L(c)).join(" ");u.startsWith("[Zharp]")||t(Ot[o],u);}),r=false);};i.__zharp=true,console[o]=i;}return ()=>Object.assign(console,n)}var re="[Filtered]";var _t=["password","passwd","passphrase","secret","token","apikey","accesskey","privatekey","authorization","cookie","creditcard","cardnumber","cvv","cvc","ssn","iban","sessionid","signature","credential"],It=["auth","pin","pwd","otp","card","pan","jwt","sid","codeverifier"],Pt=["key","sig","code","state","session"],ne=e=>e.toLowerCase().replace(/[^a-z0-9]/g,"");function se(e,t=[]){let n=ne(e);return n?It.includes(n)||_t.some(r=>n.includes(r))?true:t.some(r=>r instanceof RegExp?r.test(e):ne(r)===n):false}function F(e,t=[]){if(!e)return e;let n=e.replace(/^([a-z][a-z0-9+.-]*:\/\/)[^/?#@]*@/i,"$1"),r=n.indexOf("?");if(r<0)return n;let o=n.indexOf("#",r),s=n.slice(r+1,o<0?void 0:o),i=Lt(s,t);return i!==s&&(n=n.slice(0,r+1)+i+(o<0?"":n.slice(o))),n}function Lt(e,t=[]){return e&&e.split("&").map(n=>{let r=n.indexOf("=");if(r<0)return n;let o=n.slice(0,r);try{o=decodeURIComponent(o.replace(/\+/g," "));}catch{}return (se(o,t)||Pt.includes(ne(o)))&&r<n.length-1?`${n.slice(0,r)}=${re}`:n}).join("&")}var $t=new Set(["authorization","proxy-authorization","cookie","set-cookie","x-api-key","x-auth-token","x-csrf-token","x-xsrf-token"]),jt=40,ve=512;function Ne(e,t){return e===false||t==="false"||t==="0"?null:{redact:typeof e=="object"&&e?.redact?e.redact:[]}}function Ht(e,t,n){if(t==null)return null;if($t.has(e)||se(e,n.redact))return re;let r=Array.isArray(t)?t.join(", "):String(t);return r.length>ve?`${r.slice(0,ve)}\u2026`:r}function _(e,t,n){let r={};if(!t)return r;let o=typeof t[Symbol.iterator]=="function"?[...t]:Object.entries(t),s=0;for(let[i,a]of o){if(s>=jt)break;let u=i.toLowerCase(),c=Ht(u,a,n);c!==null&&(r[`http.${e}.header.${u}`]=c,s++);}return r}var Ut=100,oe=5e3,ie=1e3,Ft=5*6e4,vt=1e6,Me=6e4,ae=false;async function ce(e,t,n,r=false){if(ae)return 401;let o={"Content-Type":"application/json",Authorization:`Bearer ${e.key}`},s=n;if(!r&&e.compress!==false&&n.length>2048&&typeof CompressionStream<"u")try{s=await new Response(new Blob([n]).stream().pipeThrough(new CompressionStream("gzip"))).arrayBuffer(),o["Content-Encoding"]="gzip";}catch{s=n;}try{let i=await e.fetch.call(globalThis,`${e.url}/v1/${t}`,{method:"POST",headers:o,body:s,keepalive:r,credentials:"omit"});return (i.status===401||i.status===403)&&(ae||(ae=!0,console.warn(`[Zharp] The key was rejected (HTTP ${i.status}); ${e.rejectedHint??"nothing more will be sent from this page. Check Zharp.init({ key }) and the app's allowed origins."}`))),i.status}catch{return 0}}var ue=0;function Nt(e,t,n){let r=K(n);ue+r<=Me?(ue+=r,ce(e,t,n,true).finally(()=>{ue-=r;})):ce(e,t,n);}var Bt=e=>e===0||e===429||e>=500;function Be(e,t,n){let r=K(JSON.stringify(n([]))),o=[],s=[],i=r;for(let a of e){let u=K(JSON.stringify(a))+1;s.length&&i+u>t&&(o.push({body:JSON.stringify(n(s)),items:s}),s=[],i=r),s.push(a),i+=u;}return s.length&&o.push({body:JSON.stringify(n(s)),items:s}),o}var v=class{constructor(t,n,r,o=true){this.endpoint=t;this.signal=n;this.wrap=r;this.timers=o;}endpoint;signal;wrap;timers;queue=[];timer=null;sending=null;failures=0;add(t){this.queue.push(t),this.queue.length>ie&&this.queue.splice(0,this.queue.length-ie),this.queue.length>=Ut&&!this.failures?this.flush():this.schedule(oe);}async flush(){for(;this.sending;)await this.sending;if(this.queue.length)return this.sending=this.send().finally(()=>this.sending=null),this.sending}flushOnHide(){if(!this.queue.length)return;let t=this.queue;this.queue=[];for(let{body:n}of Be(t,Me,this.wrap))Nt(this.endpoint,this.signal,n);}schedule(t){this.timer||!this.timers||(this.timer=setTimeout(()=>{this.timer=null,this.flush();},t));}async send(){this.timer&&(clearTimeout(this.timer),this.timer=null);let t=this.queue;this.queue=[];let n=Be(t,vt,this.wrap);for(let r=0;r<n.length;r++){let o=await ce(this.endpoint,this.signal,n[r].body);if(Bt(o)){let s=n.slice(r).flatMap(i=>i.items);this.queue=s.concat(this.queue).slice(-ie),this.failures++,this.schedule(Math.min(oe*2**this.failures,Ft));return}this.failures=0;}this.queue.length&&this.schedule(oe);}};var N="0.1.0";var Ze="https://api.zharp.io/api/v1/otlp",m=e=>typeof e=="string"&&e.trim()?e.trim():void 0,Q=e=>{if(typeof e=="boolean")return e;let t=m(e)?.toLowerCase();if(t){if(/^(true|1|yes|on)$/.test(t))return true;if(/^(false|0|no|off)$/.test(t))return false}};function Mt(e){let t=e.CF_VERSION_METADATA;return t&&typeof t=="object"?{id:m(t.id),tag:m(t.tag)}:{}}function De(e,t,n){let r=e&&typeof e=="object"?e:{},o=(typeof t=="function"?t(r):t)??{};if(Q(r.ZHARP_DISABLED))return null;let s=m(o.key)??m(r.ZHARP_KEY)??m(r.ZHARP_API_KEY);if(!s)return null;let i=Mt(r),a=m(o.release)??m(r.ZHARP_RELEASE)??i.id,u=typeof o.sampleRate=="number"?o.sampleRate:Number(m(r.ZHARP_SAMPLE_RATE)??1),c=Q(r.ZHARP_CAPTURE_HEADERS);return {key:s,endpoint:(m(o.endpoint)??m(r.ZHARP_ENDPOINT)??Ze).replace(/\/+$/,""),sampleRate:Number.isFinite(u)?Math.min(1,Math.max(0,u)):1,tracing:o.tracing??Q(r.ZHARP_TRACING)??true,logs:o.logs??Q(r.ZHARP_LOGS)??false,captureHeaders:o.captureHeaders??(c===false?false:void 0),captureQueryErrors:o.captureQueryErrors??true,ignoreUrls:o.ignoreUrls??[],resource:{"service.name":m(o.service)??m(r.ZHARP_SERVICE)??n.service,"service.version":a,"deployment.environment.name":m(o.environment)??m(r.ZHARP_ENVIRONMENT)??m(r.ZHARP_ENV),"telemetry.sdk.name":"zharp","telemetry.sdk.language":"webjs","telemetry.sdk.version":N,"cloud.provider":"cloudflare","cloud.platform":n.platform,"faas.version":i.id,"cloudflare.version.tag":i.tag}}}var fe=class{als=new node_async_hooks.AsyncLocalStorage;active(){return this.als.getStore()??api.ROOT_CONTEXT}with(t,n,r,...o){return this.als.run(t,()=>n.apply(r,o))}bind(t,n){if(typeof n!="function")return n;let r=this;return function(...o){return r.with(t,()=>n.apply(this,o))}}enable(){return this}disable(){return this}},j=new fe,Ve=api.createContextKey("zharp.cloudflare.request"),b=()=>j.active(),R=(e=b())=>e.getValue(Ve),Ke=(e,t)=>e.setValue(Ve,t),I=()=>{let e=api.trace.getSpan(b());return e instanceof $?e:void 0},le=null,We=e=>{le=e;},Wt=e=>e+1,Qt=64,$=class{constructor(t,n,r,o,s,i,a){this.name=t;this.kind=n;let u=r&&api.trace.isSpanContextValid(r);this.traceId=u?r.traceId:je(),this.parentSpanId=u?r.spanId:void 0,this.sampled=u?(r.traceFlags&api.TraceFlags.SAMPLED)===api.TraceFlags.SAMPLED:Math.random()<(le?.sampleRate??1),this.startTime=i!==void 0?de(i):q(),this.request=o,s&&Object.assign(this.attributes,s),a&&this.links.push(...a);}name;kind;traceId;spanId=He();parentSpanId;sampled;attributes={};startTime;request;events=[];links=[];status={code:api.SpanStatusCode.UNSET};endTime=0;get ended(){return this.endTime!==0}spanContext(){return {traceId:this.traceId,spanId:this.spanId,traceFlags:this.sampled?api.TraceFlags.SAMPLED:api.TraceFlags.NONE}}setAttribute(t,n){return !this.endTime&&n!==void 0&&(this.attributes[t]=n),this}setAttributes(t){for(let n in t)this.setAttribute(n,t[n]);return this}addEvent(t,n,r){if(this.endTime||this.events.length>=Qt)return this;if(t==="exception")return this;let o=typeof n=="number"||n instanceof Date||Array.isArray(n);return this.events.push({name:t,time:de(o?n:r??q()),attributes:o?void 0:n}),this}addLink(t){return this.links.push(t),this}addLinks(t){return this.links.push(...t),this}setStatus(t){return this.endTime||(this.status=t),this}updateName(t){return this.endTime||(this.name=t),this}isRecording(){return !this.endTime}recordException(t){Qe?.(t,this);}end(t){this.endTime||(this.endTime=Math.max(t!==void 0?de(t):q(),this.startTime),this.sampled&&le?.export(this));}toOtlp(t){return {traceId:this.traceId,spanId:this.spanId,parentSpanId:this.parentSpanId,name:this.name,kind:Wt(this.kind),startTimeUnixNano:P(this.startTime),endTimeUnixNano:P(this.endTime),attributes:O({...t,...this.attributes}),events:this.events.length?this.events.map(n=>({name:n.name,timeUnixNano:P(n.time),attributes:O(n.attributes??{})})):void 0,links:this.links.length?this.links.map(n=>({traceId:n.context.traceId,spanId:n.context.spanId,attributes:O(n.attributes??{})})):void 0,status:this.status.message?{code:this.status.code,message:this.status.message}:{code:this.status.code}}}},Qe=null,Xe=e=>{Qe=e;};function de(e){return typeof e=="number"?e<1e12?typeof performance<"u"&&performance.timeOrigin?performance.timeOrigin+e:Date.now():e:e instanceof Date?e.getTime():Array.isArray(e)?e[0]*1e3+e[1]/1e6:q()}function k(e,t={},n=b()){let r=t.root?void 0:api.trace.getSpanContext(n);return new $(e,t.kind??api.SpanKind.INTERNAL,r,R(n),t.attributes,t.startTime,t.links)}function X(e,t,n=b()){return j.with(api.trace.setSpan(n,e),t)}var pe=class{startSpan(t,n,r){return k(t,n,r??b())}startActiveSpan(t,...n){let r=n[n.length-1],o=n.length>1?n[0]:void 0,i=(n.length>2?n[1]:void 0)??b(),a=k(t,o,i);return j.with(api.trace.setSpan(i,a),()=>r(a))}},Xt=new pe,Yt={getTracer:()=>Xt},Gt=/^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;function ge(e){let t=e?Gt.exec(e.trim().toLowerCase()):null;if(!(!t||/^0+$/.test(t[1])||/^0+$/.test(t[2])))return {traceId:t[1],spanId:t[2],traceFlags:parseInt(t[3],16)&1,isRemote:true}}function he(e){return `00-${e.traceId}-${e.spanId}-${e.traceFlags&api.TraceFlags.SAMPLED?"01":"00"}`}var Jt={inject(e,t,n){let r=api.trace.getSpanContext(e);r&&api.trace.isSpanContextValid(r)&&n.set(t,"traceparent",he(r));},extract(e,t,n){let r=n.get(t,"traceparent"),o=ge(Array.isArray(r)?r[0]:r);return o?api.trace.setSpanContext(e,o):e},fields:()=>["traceparent"]},ze=false;function Ye(){if(!ze){ze=true;try{api.context.setGlobalContextManager(j),api.trace.setGlobalTracerProvider(Yt),api.propagation.setGlobalPropagator(Jt);}catch{}}}var me=new WeakMap;function Ge(e){let t=e&&typeof e=="object"?me.get(e):void 0;return t&&(t.claimed=true),t}function Je(e){return e.queryFailures.filter(t=>!t.claimed)}function ye(e){let t={},n=Error.stackTraceLimit;try{Error.stackTraceLimit=40,Error.captureStackTrace?.(t,e);}finally{Error.stackTraceLimit=n;}return (t.stack??"").split(`
|
|
5
|
+
`).slice(1).filter(r=>/^\s+at /.test(r))}function et(e){return /\b(SQLITE_[A-Z_]+)\b/.exec(e)?.[1]}var tt=e=>/^\s*(\w+)/.exec(e)?.[1]?.toUpperCase()??"QUERY",be=4e3;function en(e,t,n,r,o){let s=e?.message??String(e),i=et(s),a="D1Error",u={"zharp.mechanism":"db","db.system":"sqlite","db.statement":n.slice(0,be),"db.name":r,...i?{"db.error.code":i}:{}};return {error:e,span:t,claimed:false,attributes:u,exception(c){let f=[`${a}: ${s}`,...o].join(`
|
|
6
|
+
`);return {"exception.type":a,"exception.message":s,"exception.stacktrace":f,"zharp.handled":c?"true":"false",...V(f)}}}}async function we(e,t){let n=b(),r=R(n);if(!r)return t();let o=k(`${e.operation} ${e.database}`,{kind:api.SpanKind.CLIENT,attributes:{"db.system":"sqlite","db.system.name":"sqlite","db.namespace":e.database,"db.operation.name":e.operation,"db.statement":e.sql.slice(0,be),"db.query.text":e.sql.slice(0,be),"cloudflare.binding.type":"d1"}},n);try{let s=await t();return l(()=>{let i=s?.meta??(Array.isArray(s)?s[0]?.meta:void 0);i&&o.setAttributes({"cloudflare.d1.rows_read":i.rows_read,"cloudflare.d1.rows_written":i.rows_written,"cloudflare.d1.served_by":i.served_by});let a=s?.results;Array.isArray(a)&&o.setAttribute("db.response.returned_rows",a.length);}),s}catch(s){let i=s?.message??String(s);o.setStatus({code:api.SpanStatusCode.ERROR,message:i});let a=et(i);if(a&&o.setAttribute("db.response.status_code",a),e.captureErrors&&s&&typeof s=="object"&&!me.has(s)){let u=en(s,o,e.sql,e.database,e.frames);me.set(s,u),r.queryFailures.push(u);}throw s}finally{o.end();}}var nt=new WeakMap,rt=new WeakMap,tn=new Set(["first","all","run","raw"]);function st(e,t,n,r){let o=new Proxy(e,{get(s,i){let a=Reflect.get(s,i,s);if(typeof a!="function")return a;if(i==="bind")return (...u)=>st(a.apply(s,u),t,n,r);if(typeof i=="string"&&tn.has(i)){let u=function(...c){let f=ye(u);return we({database:n,sql:t,operation:tt(t),frames:f,captureErrors:r},()=>a.apply(s,c))};return u}return a.bind(s)}});return nt.set(o,e),rt.set(o,t),o}function Re(e,t,n){return new Proxy(e,{get(r,o){let s=Reflect.get(r,o,r);if(typeof s!="function")return s;if(o==="prepare")return i=>st(s.call(r,i),String(i??""),t,n);if(o==="batch"){let i=function(a){let u=ye(i),c=Array.isArray(a)?a:[],f=c.map(d=>(d&&typeof d=="object"?rt.get(d):void 0)??"?").join(`;
|
|
7
|
+
`),p=c.map(d=>d&&typeof d=="object"?nt.get(d)??d:d);return we({database:t,sql:f,operation:"BATCH",frames:u,captureErrors:n},()=>s.call(r,p))};return i}if(o==="exec"){let i=function(a){let u=ye(i);return we({database:t,sql:String(a??""),operation:tt(String(a??"")),frames:u,captureErrors:n},()=>s.call(r,a))};return i}return o==="withSession"?(...i)=>Re(s.apply(r,i),t,n):s.bind(r)}})}var nn=()=>typeof location<"u"?location.href:"http://localhost/";function ot(e,t){let n=l(()=>new URL(e,nn()));return n?t.some(r=>r instanceof RegExp?r.test(n.href):r?r.includes("://")?n.href.startsWith(r):n.host===r||n.hostname===r:false):false}var it=false;function at(e){if(it||typeof globalThis.fetch!="function")return;it=true;let t=globalThis.fetch,n=function(o,s){return Se(e,t,globalThis,o,s,void 0)};n.__zharp=true,globalThis.fetch=n;}function Se(e,t,n,r,o,s){let i=b();if(!R(i)||!e.settings.tracing)return t.call(n,r,o);let a;try{a=new Request(r,o);}catch{return t.call(n,r,o)}let u=l(()=>new URL(a.url));if(!s&&(!u||a.url.startsWith(e.settings.endpoint)||ot(a.url,e.settings.ignoreUrls)))return t.call(n,a);let c=a.method.toUpperCase(),f=k(s?`${c} ${s.name}`:`${c} ${u?.host??""}`.trim(),{kind:api.SpanKind.CLIENT,attributes:{"http.request.method":c,"url.full":F(a.url),"server.address":s?void 0:u?.hostname,"server.port":s||!u?.port?void 0:Number(u.port),...s?{"cloudflare.binding.name":s.name,"cloudflare.binding.type":s.type}:{}}},i);return a.headers.has("traceparent")||l(()=>a.headers.set("traceparent",he(f.spanContext()))),e.headers&&f.setAttributes(_("request",a.headers,e.headers)),X(f,()=>t.call(n,a),i).then(p=>(l(()=>{f.setAttribute("http.response.status_code",p.status),e.headers&&f.setAttributes(_("response",p.headers,e.headers)),p.status>=400&&f.setStatus({code:api.SpanStatusCode.ERROR,message:`HTTP ${p.status}`}),f.end();}),p),p=>{throw l(()=>{f.setStatus({code:api.SpanStatusCode.ERROR,message:p?.message??String(p)}),f.setAttribute("error.type",p?.name||"Error"),f.end();}),p})}var rn={trace:1,debug:5,info:9,warn:13,error:17,fatal:21},ft={},lt=null,xe=class{constructor(t){this.settings=t;let n=globalThis.fetch;this.endpoint={url:t.endpoint,key:t.key,fetch:n,rejectedHint:"nothing more will be sent from this isolate. Check the ZHARP_KEY secret (the app key from the Zharp dashboard)."},this.headers=Ne(t.captureHeaders);let r=O(t.resource),o={name:"@zharp/cloudflare",version:N};this.spans=new v(this.endpoint,"traces",s=>({resourceSpans:[{resource:{attributes:r},scopeSpans:[{scope:o,spans:s}]}]}),false),this.logs=new v(this.endpoint,"logs",s=>({resourceLogs:[{resource:{attributes:r},scopeLogs:[{scope:o,logRecords:s}]}]}),false),We({sampleRate:t.sampleRate,export:s=>{t.tracing&&this.spans.add(s.toOtlp(ut(s.request)));}}),Xe((s,i)=>this.report(s,true,{"zharp.mechanism":"opentelemetry"},i)),Ye(),t.tracing&&at(this),t.logs&&Fe(["debug","log","info","warn","error"],(s,i)=>this.emit(s,i,{"log.source":"console"}));}settings;endpoint;spans;logs;headers;reported=new WeakSet;newRequest(){return {runtime:this,tags:{},user:null,queryFailures:[],pending:[]}}report(t,n,r={},o=I()){l(()=>{if(t&&typeof t=="object"){if(this.reported.has(t))return;this.reported.add(t);}let s=Ge(t),i=s?s.exception(n):te(W(t),n);this.emit("error",`${i["exception.type"]}: ${i["exception.message"]}`,{...s?.attributes??{},...r},i,o);});}wasReported(t){return !!t&&typeof t=="object"&&this.reported.has(t)}emit(t,n,r,o,s=I()){l(()=>{let i=P(q()),a=s?.request??R(),u={...ut(a)};for(let c in r){let f=r[c];f instanceof Error&&!o&&(t==="error"||t==="fatal")?(o=te(f,!0),this.reported.add(f)):u[c]=f;}this.logs.add({timeUnixNano:i,observedTimeUnixNano:i,severityNumber:rn[t],severityText:t.toUpperCase(),body:{stringValue:typeof n=="string"?n:n instanceof Error?n.message:L(n)},attributes:O({...u,...o}),traceId:s?.traceId,spanId:s?.spanId});});}async finish(t){try{for(let n=0;n<t.pending.length;){let r=t.pending.slice(n);n=t.pending.length,await Promise.allSettled(r);}for(let n of Je(t))this.report(n.error,!0,{},n.span);}catch{}await this.flush();}async flush(){await Promise.all([this.spans.flush(),this.logs.flush()]).catch(()=>{});}};function ut(e){let t=e?.user??lt;return {...ft,...e?.tags,"enduser.id":t?String(t.id):void 0,"enduser.email":t?.email,"enduser.name":t?.name}}function pt(e,t){let n=R()?.tags??ft;t==null?delete n[e]:n[e]=t;}function gt(e){let t=e&&e.id!==void 0&&e.id!==null&&e.id!==""?{id:e.id,email:e.email,name:e.name}:null,n=R();n?n.user=t:lt=t;}var M=null,ct=false,dt;function Y(e,t,n){if(M)return M;t!==void 0&&(dt=t);let r=l(()=>De(e,t??dt,n));if(!r){let o=/^(true|1|yes|on)$/i.test(String(e?.ZHARP_DISABLED??""));return !ct&&!o&&(ct=true,console.warn("[Zharp] No key: set the ZHARP_KEY secret (wrangler secret put ZHARP_KEY) to the app key from the Zharp dashboard. Nothing will be sent.")),null}return M=new xe(r),M}var Z=()=>M;var ht={D1Database:"d1",D1DatabaseSession:"d1",KvNamespace:"kv",R2Bucket:"r2",WorkerQueue:"queue",Fetcher:"service",DurableObjectNamespace:"durable-object"},D=(e,...t)=>t.every(n=>typeof l(()=>e[n])=="function");function sn(e){if(!e||typeof e!="object")return;let t=l(()=>Object.getPrototypeOf(e)?.constructor?.name);if(t&&ht[t])return ht[t];if(!(t&&t!=="Object")){if(D(e,"prepare","batch","exec"))return "d1";if(D(e,"head","get","put","list","delete","createMultipartUpload"))return "r2";if(D(e,"get","put","list","delete","getWithMetadata"))return "kv";if(D(e,"send","sendBatch"))return "queue";if(D(e,"idFromName","get"))return "durable-object"}}var G=Symbol.for("zharp.cloudflare.wrapped"),mt=new WeakMap;function Ee(e,t){return !e||typeof e!="object"||e[G]?e:new Proxy(e,{get(n,r,o){if(r===G)return true;let s=Reflect.get(n,r,o);return typeof r!="string"?s:Ae(s,r,t)??s}})}function Ae(e,t,n){if(!e||typeof e!="object"||e[G])return;let r=sn(e);if(!r)return;let o=mt.get(e);o||mt.set(e,o=new Map);let s=o.get(t);if(s)return s;let i=an(on(r,e,t,n));return o.set(t,i),i}function on(e,t,n,r){switch(e){case "d1":return Re(t,n,r.settings.captureQueryErrors);case "kv":return ke(t,["get","getWithMetadata","put","list","delete"],(o,s)=>({name:`KV ${o} ${n}`,kind:api.SpanKind.CLIENT,attributes:{"db.system":"cloudflare_kv","db.namespace":n,"db.operation.name":o,"cloudflare.binding.type":"kv","cloudflare.kv.key":typeof s[0]=="string"?s[0]:void 0,"cloudflare.kv.keys":Array.isArray(s[0])?s[0].length:void 0},result:o.startsWith("get")?i=>({"cloudflare.kv.hit":o==="get"?i!==null:i?.value!==null}):void 0}));case "r2":return ke(t,["head","get","put","list","delete","createMultipartUpload","resumeMultipartUpload"],(o,s)=>({name:`R2 ${o} ${n}`,kind:api.SpanKind.CLIENT,attributes:{"cloudflare.binding.type":"r2","cloudflare.r2.bucket":n,"cloudflare.r2.operation":o,"cloudflare.r2.key":typeof s[0]=="string"?s[0]:void 0},result:o==="get"||o==="head"?i=>({"cloudflare.r2.hit":i!==null}):void 0}));case "queue":return ke(t,["send","sendBatch"],(o,s)=>({name:`${n} send`,kind:api.SpanKind.PRODUCER,attributes:{"messaging.system":"cloudflare_queues","messaging.operation.type":"send","messaging.destination.name":n,"messaging.batch.message_count":o==="sendBatch"&&Array.isArray(s[0])?s[0].length:void 0}}));case "service":return yt(t,{name:n,type:"service"},r);case "durable-object":return new Proxy(t,{get(o,s){let i=Reflect.get(o,s,o);return typeof i!="function"?i:s==="get"||s==="getByName"?(...a)=>yt(i.apply(o,a),{name:n,type:"durable-object"},r):i.bind(o)}})}}function an(e){return new Proxy(e,{get(t,n,r){return n===G?true:Reflect.get(t,n,r)}})}function yt(e,t,n){return !e||typeof e!="object"?e:new Proxy(e,{get(r,o){let s=Reflect.get(r,o,r);return o!=="fetch"||typeof s!="function"?s:(i,a)=>Se(n,s,r,i,a,t)}})}function ke(e,t,n){let r=new Set(t);return new Proxy(e,{get(o,s){let i=Reflect.get(o,s,o);return typeof i!="function"?i:typeof s!="string"||!r.has(s)?i.bind(o):(...a)=>{let u=b();if(!R(u))return i.apply(o,a);let c=n(s,a),f=k(c.name,{kind:c.kind,attributes:c.attributes},u),p;try{p=i.apply(o,a);}catch(d){throw f.setStatus({code:api.SpanStatusCode.ERROR,message:d?.message}),f.end(),d}return Promise.resolve(p).then(d=>(c.result&&l(()=>f.setAttributes(c.result(d))),f.end(),d),d=>{throw f.setStatus({code:api.SpanStatusCode.ERROR,message:d?.message??String(d)}),f.end(),d})}}})}function Te(e){return !!e&&typeof e=="object"&&typeof e.fetch=="function"&&typeof e.router?.match=="function"&&Array.isArray(e.routes)}function wt(e,t){return l(()=>{let n=typeof e.getPath=="function"?e.getPath(t):new URL(t.url).pathname,r=t.method==="HEAD"?"GET":t.method,[o]=e.router.match(r,n)??[];if(!Array.isArray(o)||!o.length)return;let s=o.map(u=>u?.[0]?.[1]).filter(u=>u&&typeof u.path=="string"),a=([...s].reverse().find(u=>u.method!=="ALL")??s[s.length-1])?.path;return a&&a!=="/*"&&a!=="*"?a:void 0})}var bt=Symbol.for("zharp.cloudflare.honoErrorHandler");function Rt(e,t){l(()=>{let n=e.errorHandler;if(typeof n!="function"||n[bt])return;let r=function(o,s){let i=o?.status;return typeof o?.getResponse=="function"&&typeof i=="number"&&i<500||t.report(o,!1,{"zharp.mechanism":"hono"},I()),n.call(this,o,s)};r[bt]=!0,e.errorHandler=r;});}var Ce={service:"worker",platform:"cloudflare.workers"},dn={service:"pages",platform:"cloudflare.pages"},fn=/^(\d+|[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|[0-9a-f]{16,}|[A-Za-z0-9_-]{24,})$/i,ln=e=>e.split("/").map(t=>fn.test(t)?":id":t).join("/")||"/";async function H(e,t,n,r,o){let s=e.newRequest(),i=ge(t.traceparent),a=new $(t.name,t.kind,i,s,t.attributes),u=api.trace.setSpan(Ke(api.ROOT_CONTEXT,s),a);try{let c=await j.with(u,()=>r(s,a));return o&&l(()=>o(c,a)),c}catch(c){throw e.report(c,false,{"zharp.mechanism":t.mechanism},a),a.setStatus({code:api.SpanStatusCode.ERROR,message:c?.message??String(c)}),t.attributes["http.request.method"]&&!a.attributes["http.response.status_code"]&&a.setAttribute("http.response.status_code",500),c}finally{a.end();let c=e.finish(s);n&&l(()=>n.waitUntil(c));}}function z(e,t,n){return !e||typeof e.waitUntil!="function"?e:new Proxy(e,{get(r,o){let s=Reflect.get(r,o,r);return o==="waitUntil"&&typeof s=="function"?i=>{let a=Promise.resolve(i).catch(u=>{throw n.report(u,false,{"zharp.mechanism":"waitUntil"}),u});return t.pending.push(a),s.call(r,a)}:typeof s=="function"?s.bind(r):s}})}function qe(e,t,n,r={}){let o=l(()=>new URL(e.url)),s=e.method.toUpperCase(),i=e.cf,a=e.headers;return {name:`${s} ${ln(o?.pathname??"/")}`,kind:api.SpanKind.SERVER,traceparent:a.get("traceparent"),mechanism:n,attributes:{"faas.trigger":"http","http.request.method":s,"url.full":F(e.url),"url.path":o?.pathname,"url.scheme":o?.protocol.replace(":",""),"server.address":o?.hostname,"user_agent.original":a.get("user-agent")??void 0,"client.address":a.get("cf-connecting-ip")??void 0,"cloudflare.ray_id":a.get("cf-ray")??void 0,"cloudflare.colo":typeof i?.colo=="string"?i.colo:void 0,"geo.country.iso_code":typeof i?.country=="string"?i.country:void 0,...t.headers?_("request",a,t.headers):{},...r}}}function Oe(e){return (t,n)=>{t instanceof Response&&(n.setAttribute("http.response.status_code",t.status),e.headers&&n.setAttributes(_("response",t.headers,e.headers)),t.status>=500&&n.setStatus({code:api.SpanStatusCode.ERROR,message:`HTTP ${t.status}`}));}}function pn(e,t,n,r,o){return function(...s){let i=n??this,a=e==="fetch"||e==="scheduled"||e==="queue"||e==="email"||e==="tail"||e==="trace"?s[1]:void 0,u=s[2],c=a!==void 0?Y(a,r,Ce):null;if(!c)return t.apply(i,s);let f=Ee(a,c);if(e==="fetch"){let d=s[0];Te(o)&&Rt(o,c);let C=qe(d,c,"cloudflare.fetch");return H(c,C,u,E=>t.call(i,d,f,z(u,E,c),...s.slice(3)),(E,h)=>{Oe(c)(E,h);let y=Te(o)?wt(o,d):void 0;y&&(h.setAttribute("http.route",y),h.updateName(`${d.method.toUpperCase()} ${y}`));})}if(e==="scheduled"){let d=s[0]??{},C={name:`cron ${d.cron??""}`.trim(),kind:api.SpanKind.SERVER,mechanism:"cloudflare.scheduled",attributes:{"faas.trigger":"timer","faas.cron":d.cron,"faas.time":typeof d.scheduledTime=="number"?new Date(d.scheduledTime).toISOString():void 0}};return H(c,C,u,E=>t.call(i,d,f,z(u,E,c)))}if(e==="queue"){let d=s[0]??{},C={name:`${d.queue??"queue"} process`,kind:api.SpanKind.CONSUMER,mechanism:"cloudflare.queue",attributes:{"faas.trigger":"pubsub","messaging.system":"cloudflare_queues","messaging.operation.type":"process","messaging.destination.name":d.queue,"messaging.batch.message_count":Array.isArray(d.messages)?d.messages.length:void 0}};return H(c,C,u,E=>t.call(i,d,f,z(u,E,c)))}let p={name:e,kind:api.SpanKind.SERVER,mechanism:`cloudflare.${e}`,attributes:{"faas.trigger":"other"}};return H(c,p,u,d=>t.call(i,s[0],f,z(u,d,c),...s.slice(3)))}}var gn=new Set(["fetch","scheduled","queue","email","tail","trace","test"]);function hn(e,t){let[n,r]=t===void 0?[void 0,e]:[e,t];if(typeof r=="function")return xt(r,n,Ce,"worker");if(!r||typeof r!="object")return r;let o=new Map;return new Proxy(r,{get(s,i,a){let u=Reflect.get(s,i,a);if(typeof i!="string"||!gn.has(i)||typeof u!="function")return u;let c=o.get(i);return c||o.set(i,c=pn(i,u,s,n,s)),c}})}var St={webSocketMessage:"websocket message",webSocketClose:"websocket close",webSocketError:"websocket error"},mn=new Set(["constructor","then","toJSON","dup","ctx","env","state","storage"]);function yn(e,t){return xt(e,t,Ce,"durable-object")}function xt(e,t,n,r){return new Proxy(e,{construct(o,s,i){let[a,u]=s,c=Y(u,t,n);if(!c)return Reflect.construct(o,s,i);let f=Reflect.construct(o,[a,Ee(u,c),...s.slice(2)],i),p=o.name||(r==="durable-object"?"DurableObject":"Worker"),d=l(()=>a?.id?.toString?.()),C=new Map,E=(h,y)=>function(...A){let S={"cloudflare.durable_object.class":r==="durable-object"?p:void 0,"cloudflare.durable_object.id":r==="durable-object"?d:void 0},x,Ie;h==="fetch"&&A[0]instanceof Request?(x=qe(A[0],c,r==="durable-object"?"cloudflare.durable_object":"cloudflare.fetch",S),Ie=Oe(c)):h==="alarm"?x={name:`${p} alarm`,kind:api.SpanKind.SERVER,mechanism:"cloudflare.alarm",attributes:{"faas.trigger":"timer",...S}}:St[h]?x={name:`${p} ${St[h]}`,kind:api.SpanKind.SERVER,mechanism:"cloudflare.websocket",attributes:{"faas.trigger":"other",...S}}:h==="scheduled"||h==="queue"?x={name:h==="scheduled"?`cron ${A[0]?.cron??""}`.trim():`${A[0]?.queue??"queue"} process`,kind:h==="queue"?api.SpanKind.CONSUMER:api.SpanKind.SERVER,mechanism:`cloudflare.${h}`,attributes:{"faas.trigger":h==="queue"?"pubsub":"timer","faas.cron":A[0]?.cron,"messaging.destination.name":A[0]?.queue}}:x={name:`${p}.${h}`,kind:api.SpanKind.SERVER,mechanism:"cloudflare.rpc",attributes:{"rpc.system":"cloudflare_rpc","rpc.service":p,"rpc.method":h,...S}};let kt=typeof a?.waitUntil=="function"?a:void 0;return H(c,x,kt,()=>y.apply(f,A),Ie)};return new Proxy(f,{get(h,y,A){let S=Reflect.get(h,y,A);if(typeof y!="string"||typeof S!="function"||mn.has(y)||y.startsWith("_")||S===Object.prototype[y])return S;let x=C.get(y);return x||C.set(y,x=E(y,S)),x}})}})}function bn(e){return async t=>{let n=typeof e=="function"?s=>e({...t,env:s}):e,r=Y(t.env,n,dn);if(!r)return t.next();l(()=>{for(let s of Object.keys(t.env)){let i=Ae(t.env[s],s,r);i&&(t.env[s]=i);}});let o=qe(t.request,r,"cloudflare.pages");return H(r,o,t,s=>{let i=z({waitUntil:t.waitUntil.bind(t)},s,r);return l(()=>{t.waitUntil=i.waitUntil;}),t.next()},Oe(r))}}var U=e=>(t,n)=>Z()?.emit(e,t,n),_e={traceId:"",spanId:"",setAttribute:()=>_e,setAttributes:()=>_e},Rn={captureError(e,t){Z()?.report(e,true,t);},setUser(e){l(()=>gt(e));},setTag(e,t){l(()=>pt(e,t));},log:{trace:U("trace"),debug:U("debug"),info:U("info"),warn:U("warn"),error:U("error"),fatal:U("fatal")},startSpan(e,t,n){if(!Z())return t(_e);let r=k(e,{attributes:n}),o=s=>{r.setStatus({code:api.SpanStatusCode.ERROR,message:W(s).message}),r.end();};try{let s=X(r,()=>t(r));return s&&typeof s.then=="function"?s.then(i=>(r.end(),i),i=>{throw o(i),i}):(r.end(),s)}catch(s){throw o(s),s}},get traceId(){return I()?.traceId},async flush(){await Z()?.flush();}},Ur=Rn;
|
|
8
|
+
exports.VERSION=N;exports.Zharp=Rn;exports.default=Ur;exports.instrumentDurableObject=yn;exports.withZharp=hn;exports.zharpPagesPlugin=bn;//# sourceMappingURL=index.js.map
|
|
9
|
+
//# sourceMappingURL=index.js.map
|