@deploze/next 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/dist/index.cjs ADDED
@@ -0,0 +1,521 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ DeplozeSpanProcessor: () => DeplozeSpanProcessor,
34
+ bracketRouteToPattern: () => bracketRouteToPattern,
35
+ createCollector: () => createCollector,
36
+ flush: () => flush,
37
+ onRequestError: () => onRequestError,
38
+ register: () => register,
39
+ registerDeploze: () => registerDeploze,
40
+ trackRequest: () => trackRequest,
41
+ withDeploze: () => withDeploze
42
+ });
43
+ module.exports = __toCommonJS(index_exports);
44
+
45
+ // src/core/normalize.ts
46
+ function normalizePathPattern(path) {
47
+ if (!path) return "/unknown";
48
+ return path.split("?")[0].split("#")[0].replace(
49
+ /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi,
50
+ ":id"
51
+ ).replace(/\/[0-9a-f]{16,}\b/gi, "/:id").replace(/\/\d{2,}\b/g, "/:id").replace(/\/$/, "") || "/";
52
+ }
53
+ function normalizeErrorSignature(message) {
54
+ return message.replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi, "{UUID}").replace(/\b[0-9a-f]{16,}\b/gi, "{ID}").replace(/\b\d{6,}\b/g, "{ID}").replace(/:\d+:\d+/g, ":{LINE}").replace(/\s+/g, " ").trim().slice(0, 200);
55
+ }
56
+
57
+ // src/core/protocol.ts
58
+ var SCHEMA_VERSION = 1;
59
+
60
+ // src/core/build-id.ts
61
+ var import_meta = {};
62
+ function getEnv(name) {
63
+ try {
64
+ return globalThis.process?.env?.[name];
65
+ } catch {
66
+ return void 0;
67
+ }
68
+ }
69
+ async function readGeneratedBuildId() {
70
+ if (process.env.NEXT_RUNTIME !== "edge") {
71
+ try {
72
+ const fs = await import("fs");
73
+ const path = await import("path");
74
+ const { fileURLToPath } = await import("url");
75
+ const dir = getModuleDir(path, fileURLToPath);
76
+ const candidates = [
77
+ path.join(dir, ".build-id.json"),
78
+ path.join(dir, "..", ".build-id.json"),
79
+ path.join(dir, "..", "..", ".build-id.json")
80
+ ];
81
+ for (const candidate of candidates) {
82
+ try {
83
+ if (!fs.existsSync(candidate)) continue;
84
+ const raw = JSON.parse(fs.readFileSync(candidate, "utf8"));
85
+ return typeof raw?.sha === "string" && raw.sha ? raw.sha : null;
86
+ } catch {
87
+ return null;
88
+ }
89
+ }
90
+ } catch {
91
+ }
92
+ }
93
+ return null;
94
+ }
95
+ function getModuleDir(path, fileURLToPath) {
96
+ try {
97
+ return path.dirname(fileURLToPath(import_meta.url));
98
+ } catch {
99
+ const dir = globalThis.__dirname;
100
+ return typeof dir !== "undefined" ? dir : process.cwd();
101
+ }
102
+ }
103
+ async function getBuildId() {
104
+ return getEnv("DEPLOZE_GIT_SHA") || getEnv("VERCEL_GIT_COMMIT_SHA") || await readGeneratedBuildId() || null;
105
+ }
106
+
107
+ // src/core/transport.ts
108
+ var SDK_VERSION = "0.1.0";
109
+ function parseRemoteConfig(body) {
110
+ if (!body || typeof body !== "object") return void 0;
111
+ const raw = body.config;
112
+ if (!raw || typeof raw !== "object") return void 0;
113
+ const cfg = raw;
114
+ const config = {};
115
+ const flush2 = Number(cfg.flush_interval_ms);
116
+ if (Number.isFinite(flush2) && flush2 >= 1e3 && flush2 <= 6e5) {
117
+ config.flush_interval_ms = Math.floor(flush2);
118
+ }
119
+ const buckets = Number(cfg.max_buckets);
120
+ if (Number.isFinite(buckets) && buckets >= 1 && buckets <= 1e4) {
121
+ config.max_buckets = Math.floor(buckets);
122
+ }
123
+ const samples = Number(cfg.max_error_samples);
124
+ if (Number.isFinite(samples) && samples >= 1 && samples <= 1e3) {
125
+ config.max_error_samples = Math.floor(samples);
126
+ }
127
+ return Object.keys(config).length > 0 ? config : void 0;
128
+ }
129
+ async function send(payload, options) {
130
+ const { endpoint, apiKey, timeoutMs = 3e3 } = options;
131
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
132
+ if (typeof fetchImpl !== "function") return { ok: false };
133
+ try {
134
+ const controller = new AbortController();
135
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
136
+ const body = {
137
+ schema_version: payload.schema_version ?? SCHEMA_VERSION,
138
+ stats: payload.stats,
139
+ errors: payload.errors
140
+ };
141
+ const buildId = await getBuildId();
142
+ const headers = {
143
+ "Content-Type": "application/json",
144
+ Authorization: `Bearer ${apiKey}`,
145
+ "User-Agent": `@deploze/next/${SDK_VERSION}`
146
+ };
147
+ if (buildId) headers["X-Deploze-Git-Sha"] = buildId;
148
+ const res = await fetchImpl(endpoint, {
149
+ method: "POST",
150
+ headers,
151
+ body: JSON.stringify(body),
152
+ keepalive: true,
153
+ signal: controller.signal
154
+ });
155
+ clearTimeout(timer);
156
+ if (!res.ok) return { ok: false };
157
+ let config;
158
+ try {
159
+ const parsed = typeof res.json === "function" ? await res.json() : typeof res.text === "function" ? JSON.parse(await res.text()) : void 0;
160
+ config = parseRemoteConfig(parsed);
161
+ } catch {
162
+ }
163
+ return { ok: true, config };
164
+ } catch {
165
+ return { ok: false };
166
+ }
167
+ }
168
+
169
+ // src/core/collector.ts
170
+ var DEFAULT_MAX_BUCKETS = 200;
171
+ var DEFAULT_MAX_ERROR_SAMPLES = 10;
172
+ var RESERVOIR_SIZE = 200;
173
+ var DEFAULT_FLUSH_INTERVAL_MS = 3e4;
174
+ var DEFAULT_ENDPOINT = "https://app.deploze.com/api/ingest";
175
+ function p95(values) {
176
+ if (values.length === 0) return void 0;
177
+ const sorted = [...values].sort((a, b) => a - b);
178
+ const idx = Math.min(sorted.length - 1, Math.ceil(sorted.length * 0.95) - 1);
179
+ return sorted[Math.max(0, idx)];
180
+ }
181
+ function createCollector(options = {}) {
182
+ const apiKey = options.apiKey ?? getEnv2("DEPLOZE_INGEST_KEY");
183
+ const endpoint = options.endpoint ?? getEnv2("DEPLOZE_INGEST_URL") ?? DEFAULT_ENDPOINT;
184
+ let flushIntervalMs = options.flushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS;
185
+ let maxBuckets = DEFAULT_MAX_BUCKETS;
186
+ let maxErrorSamples = DEFAULT_MAX_ERROR_SAMPLES;
187
+ const now = options.now ?? Date.now;
188
+ const autoFlush = options.autoFlush !== false;
189
+ const buckets = /* @__PURE__ */ new Map();
190
+ const errorSamples = /* @__PURE__ */ new Map();
191
+ let timer = null;
192
+ let flushing = false;
193
+ const isLocalDev = getEnv2("NODE_ENV") === "development" && getEnv2("DEPLOZE_ENABLE_DEV") !== "1";
194
+ const enabled = Boolean(apiKey) && !isLocalDev;
195
+ if (!enabled) {
196
+ return {
197
+ record() {
198
+ },
199
+ async flush() {
200
+ },
201
+ stop() {
202
+ },
203
+ pendingBucketCount: () => 0
204
+ };
205
+ }
206
+ const transport = {
207
+ endpoint,
208
+ apiKey,
209
+ fetchImpl: options.fetchImpl
210
+ };
211
+ function startTimer(intervalMs) {
212
+ if (!autoFlush) return;
213
+ if (timer) {
214
+ clearInterval(timer);
215
+ timer = null;
216
+ }
217
+ timer = setInterval(() => {
218
+ void flush2();
219
+ }, intervalMs);
220
+ if (typeof timer === "object" && "unref" in timer) {
221
+ timer.unref();
222
+ }
223
+ }
224
+ function applyConfig(config) {
225
+ if (!config) return;
226
+ if (typeof config.max_buckets === "number") {
227
+ maxBuckets = config.max_buckets;
228
+ }
229
+ if (typeof config.max_error_samples === "number") {
230
+ maxErrorSamples = config.max_error_samples;
231
+ }
232
+ if (typeof config.flush_interval_ms === "number" && config.flush_interval_ms !== flushIntervalMs) {
233
+ flushIntervalMs = config.flush_interval_ms;
234
+ startTimer(flushIntervalMs);
235
+ }
236
+ }
237
+ function record(input) {
238
+ try {
239
+ const status = Number(input.status);
240
+ if (!Number.isFinite(status)) return;
241
+ const path = normalizePathPattern(input.path ?? null);
242
+ const minute = new Date(Math.floor(now() / 6e4) * 6e4).toISOString();
243
+ const key = `${minute}|${path}`;
244
+ let bucket = buckets.get(key);
245
+ if (!bucket) {
246
+ if (buckets.size >= maxBuckets) return;
247
+ bucket = {
248
+ path,
249
+ minute,
250
+ count: 0,
251
+ e5xx: 0,
252
+ e4xx: 0,
253
+ latencySum: 0,
254
+ latencyCount: 0,
255
+ reservoir: [],
256
+ seen: 0
257
+ };
258
+ buckets.set(key, bucket);
259
+ }
260
+ bucket.count += 1;
261
+ if (status >= 500) bucket.e5xx += 1;
262
+ else if (status >= 400) bucket.e4xx += 1;
263
+ const duration = Number(input.durationMs);
264
+ if (Number.isFinite(duration) && duration >= 0) {
265
+ bucket.latencySum += duration;
266
+ bucket.latencyCount += 1;
267
+ bucket.seen += 1;
268
+ if (bucket.reservoir.length < RESERVOIR_SIZE) {
269
+ bucket.reservoir.push(duration);
270
+ } else {
271
+ const j = Math.floor(Math.random() * bucket.seen);
272
+ if (j < RESERVOIR_SIZE) bucket.reservoir[j] = duration;
273
+ }
274
+ }
275
+ if (status >= 500 && input.errorMessage) {
276
+ const pattern = normalizeErrorSignature(input.errorMessage);
277
+ const existing = errorSamples.get(`${path}|${pattern}`);
278
+ if (existing) {
279
+ existing.count += 1;
280
+ } else if (errorSamples.size < maxErrorSamples) {
281
+ errorSamples.set(`${path}|${pattern}`, {
282
+ path,
283
+ pattern,
284
+ sample: input.errorMessage.slice(0, 1e3),
285
+ count: 1
286
+ });
287
+ }
288
+ }
289
+ } catch {
290
+ }
291
+ }
292
+ async function flush2() {
293
+ if (flushing || buckets.size === 0 && errorSamples.size === 0) return;
294
+ flushing = true;
295
+ try {
296
+ const statRows = [...buckets.values()];
297
+ const errorRows = [...errorSamples.values()];
298
+ buckets.clear();
299
+ errorSamples.clear();
300
+ const payload = {
301
+ schema_version: SCHEMA_VERSION,
302
+ stats: statRows.map((b) => ({
303
+ path: b.path,
304
+ minute: b.minute,
305
+ total_requests: b.count,
306
+ error_count: b.e5xx,
307
+ client_error_count: b.e4xx,
308
+ avg_latency_ms: b.latencyCount > 0 ? Math.round(b.latencySum / b.latencyCount) : void 0,
309
+ p95_latency_ms: p95(b.reservoir)
310
+ })),
311
+ errors: errorRows.map((e) => ({
312
+ path: e.path,
313
+ error_pattern: e.pattern,
314
+ sample_message: e.sample,
315
+ count: e.count
316
+ }))
317
+ };
318
+ const result = await send(payload, transport);
319
+ if (result.ok) {
320
+ applyConfig(result.config);
321
+ }
322
+ } finally {
323
+ flushing = false;
324
+ }
325
+ }
326
+ function stop() {
327
+ if (timer) {
328
+ clearInterval(timer);
329
+ timer = null;
330
+ }
331
+ }
332
+ startTimer(flushIntervalMs);
333
+ return { record, flush: flush2, stop, pendingBucketCount: () => buckets.size };
334
+ }
335
+ function getEnv2(name) {
336
+ try {
337
+ return globalThis.process?.env?.[name];
338
+ } catch {
339
+ return void 0;
340
+ }
341
+ }
342
+
343
+ // src/core/singleton.ts
344
+ var collector = null;
345
+ function getCollector() {
346
+ if (!collector) {
347
+ collector = createCollector();
348
+ }
349
+ return collector;
350
+ }
351
+ function scheduleFlush() {
352
+ const specifier = "next/server";
353
+ void import(
354
+ /* @vite-ignore */
355
+ specifier
356
+ ).then((mod) => {
357
+ if (typeof mod.after === "function") {
358
+ mod.after(() => getCollector().flush());
359
+ }
360
+ }).catch(() => {
361
+ });
362
+ }
363
+
364
+ // src/core/otel.ts
365
+ var NEXT_SPAN_TYPE = "next.span_type";
366
+ var NEXT_ROUTE = "next.route";
367
+ var HTTP_ROUTE = "http.route";
368
+ var HTTP_TARGET = "http.target";
369
+ var HTTP_STATUS = "http.status_code";
370
+ var HTTP_METHOD = "http.method";
371
+ var HTTP_USER_AGENT = "http.user_agent";
372
+ var USER_AGENT_ORIGINAL = "user_agent.original";
373
+ var REQUEST_SPAN_TYPE = "BaseServer.handleRequest";
374
+ var SYNTHETIC_USER_AGENT_MARKER = "Deploze-SyntheticMonitor";
375
+ function isSyntheticUserAgent(ua) {
376
+ return typeof ua === "string" && ua.includes(SYNTHETIC_USER_AGENT_MARKER);
377
+ }
378
+ function hrToMs(start, end) {
379
+ return (end[0] - start[0]) * 1e3 + (end[1] - start[1]) / 1e6;
380
+ }
381
+ function bracketRouteToPattern(route) {
382
+ return route.replace(/\[(?:\[?\.\.\.)?([^\]]+?)\]\]?/g, (_m, name) => `:${name}`);
383
+ }
384
+ var DeplozeSpanProcessor = class {
385
+ collector;
386
+ constructor(options = {}) {
387
+ this.collector = options.collector ?? getCollector();
388
+ }
389
+ onStart() {
390
+ }
391
+ onEnd(span) {
392
+ try {
393
+ const attrs = span.attributes || {};
394
+ if (attrs[NEXT_SPAN_TYPE] !== REQUEST_SPAN_TYPE) return;
395
+ const ua = attrs[USER_AGENT_ORIGINAL] ?? attrs[HTTP_USER_AGENT];
396
+ if (isSyntheticUserAgent(typeof ua === "string" ? ua : void 0)) return;
397
+ const status = Number(attrs[HTTP_STATUS]);
398
+ if (!Number.isFinite(status)) return;
399
+ const rawRoute = attrs[NEXT_ROUTE] ?? attrs[HTTP_ROUTE] ?? attrs[HTTP_TARGET];
400
+ if (!rawRoute) return;
401
+ const path = bracketRouteToPattern(String(rawRoute));
402
+ const method = attrs[HTTP_METHOD] != null ? String(attrs[HTTP_METHOD]) : void 0;
403
+ const durationMs = hrToMs(span.startTime, span.endTime);
404
+ let errorMessage;
405
+ if (status >= 500 && Array.isArray(span.events)) {
406
+ const ex = span.events.find((e) => e.name === "exception");
407
+ const message = ex?.attributes?.["exception.message"] ?? ex?.attributes?.["exception.type"];
408
+ if (message) errorMessage = String(message);
409
+ }
410
+ this.collector.record({
411
+ path,
412
+ method,
413
+ status,
414
+ durationMs: Number.isFinite(durationMs) && durationMs >= 0 ? durationMs : void 0,
415
+ errorMessage
416
+ });
417
+ scheduleFlush();
418
+ } catch {
419
+ }
420
+ }
421
+ async forceFlush() {
422
+ await this.collector.flush();
423
+ }
424
+ async shutdown() {
425
+ await this.collector.flush();
426
+ }
427
+ };
428
+ async function registerDeploze(options = {}) {
429
+ getCollector();
430
+ try {
431
+ const mod = await import("@vercel/otel");
432
+ if (typeof mod.registerOTel !== "function") {
433
+ throw new Error("registerOTel export not found");
434
+ }
435
+ mod.registerOTel({
436
+ serviceName: options.serviceName ?? "deploze-app",
437
+ spanProcessors: [new DeplozeSpanProcessor()]
438
+ });
439
+ } catch {
440
+ console.warn(
441
+ "[deploze] Could not load @vercel/otel for automatic per-route capture. Wrap handlers with withDeploze() or call trackRequest() manually instead. Continuing in error-only mode."
442
+ );
443
+ }
444
+ }
445
+
446
+ // src/index.ts
447
+ function register() {
448
+ getCollector();
449
+ const proc = globalThis.process;
450
+ if (proc?.on) {
451
+ proc.on("beforeExit", () => {
452
+ void getCollector().flush();
453
+ });
454
+ }
455
+ }
456
+ function onRequestError(error, request) {
457
+ const message = error instanceof Error ? error.message : typeof error === "string" ? error : "Unknown error";
458
+ getCollector().record({
459
+ path: request.path,
460
+ method: request.method,
461
+ status: 500,
462
+ errorMessage: message
463
+ });
464
+ scheduleFlush();
465
+ }
466
+ function trackRequest(input) {
467
+ getCollector().record(input);
468
+ scheduleFlush();
469
+ }
470
+ function withDeploze(handler) {
471
+ return async (request, context) => {
472
+ if (isSyntheticUserAgent(request.headers.get("user-agent"))) {
473
+ return handler(request, context);
474
+ }
475
+ const start = Date.now();
476
+ const path = safePathname(request.url);
477
+ try {
478
+ const response = await handler(request, context);
479
+ getCollector().record({
480
+ path,
481
+ method: request.method,
482
+ status: response.status,
483
+ durationMs: Date.now() - start
484
+ });
485
+ scheduleFlush();
486
+ return response;
487
+ } catch (error) {
488
+ getCollector().record({
489
+ path,
490
+ method: request.method,
491
+ status: 500,
492
+ durationMs: Date.now() - start,
493
+ errorMessage: error instanceof Error ? error.message : "Unknown error"
494
+ });
495
+ scheduleFlush();
496
+ throw error;
497
+ }
498
+ };
499
+ }
500
+ function safePathname(url) {
501
+ try {
502
+ return new URL(url).pathname;
503
+ } catch {
504
+ return url || "/unknown";
505
+ }
506
+ }
507
+ async function flush() {
508
+ await getCollector().flush();
509
+ }
510
+ // Annotate the CommonJS export names for ESM import in node:
511
+ 0 && (module.exports = {
512
+ DeplozeSpanProcessor,
513
+ bracketRouteToPattern,
514
+ createCollector,
515
+ flush,
516
+ onRequestError,
517
+ register,
518
+ registerDeploze,
519
+ trackRequest,
520
+ withDeploze
521
+ });
@@ -0,0 +1,134 @@
1
+ import { C as Collector } from './collector-BHP98_1d.cjs';
2
+ export { a as CollectorOptions, R as RecordInput, c as createCollector } from './collector-BHP98_1d.cjs';
3
+
4
+ /**
5
+ * OpenTelemetry span processor — automatic per-route capture.
6
+ *
7
+ * Next.js emits a span for every request when an OTel tracer provider is
8
+ * registered (via @vercel/otel or a raw OTel SDK). The root request span
9
+ * carries the normalized route, HTTP status, method, and duration — so a
10
+ * span processor can record request counts, latency, AND error samples for
11
+ * every route with ZERO per-route code. This is the recommended automatic
12
+ * path; `withDeploze`/`trackRequest` remain manual escape hatches.
13
+ *
14
+ * Zero runtime dependencies: the OTel `SpanProcessor` interface is
15
+ * duck-typed by the tracer provider, and `ReadableSpan` is plain data — so
16
+ * we model only the fields we read as local structural types.
17
+ */
18
+
19
+ /** OTel HrTime: [seconds, nanoseconds]. */
20
+ type HrTime = [number, number];
21
+ /** The subset of OTel's ReadableSpan we consume. */
22
+ interface ReadableSpanLike {
23
+ name: string;
24
+ attributes: Record<string, unknown>;
25
+ startTime: HrTime;
26
+ endTime: HrTime;
27
+ events?: Array<{
28
+ name: string;
29
+ attributes?: Record<string, unknown>;
30
+ }>;
31
+ }
32
+ /** Structural match for OTel's SpanProcessor (methods are duck-typed). */
33
+ interface SpanProcessorLike {
34
+ onStart(span: unknown, parentContext?: unknown): void;
35
+ onEnd(span: ReadableSpanLike): void;
36
+ shutdown(): Promise<void>;
37
+ forceFlush(): Promise<void>;
38
+ }
39
+ /**
40
+ * Convert Next's dynamic route template to the SDK's `:param` form so
41
+ * buckets merge with value-based normalization:
42
+ * /users/[id] -> /users/:id
43
+ * /blog/[...slug] -> /blog/:slug
44
+ * /shop/[[...path]] -> /shop/:path
45
+ */
46
+ declare function bracketRouteToPattern(route: string): string;
47
+ interface DeplozeSpanProcessorOptions {
48
+ /** Injectable for tests; defaults to the shared singleton. */
49
+ collector?: Collector;
50
+ }
51
+ declare class DeplozeSpanProcessor implements SpanProcessorLike {
52
+ private readonly collector;
53
+ constructor(options?: DeplozeSpanProcessorOptions);
54
+ onStart(): void;
55
+ onEnd(span: ReadableSpanLike): void;
56
+ forceFlush(): Promise<void>;
57
+ shutdown(): Promise<void>;
58
+ }
59
+ /**
60
+ * One-line convenience: register OpenTelemetry (via @vercel/otel, which
61
+ * ships as a dependency of this package) with the Deploze span processor.
62
+ * Call from `instrumentation.ts`'s `register()`.
63
+ *
64
+ * Prefer the explicit form when you already configure OTel yourself:
65
+ * registerOTel({ serviceName, spanProcessors: [new DeplozeSpanProcessor()] })
66
+ *
67
+ * Falls back to error-only mode (a helpful warning) if @vercel/otel can't be
68
+ * resolved at runtime (e.g. an unusual bundler/edge setup), so it never
69
+ * throws during app startup.
70
+ */
71
+ declare function registerDeploze(options?: {
72
+ serviceName?: string;
73
+ }): Promise<void>;
74
+
75
+ /**
76
+ * @deploze/next — Deploze ingestion SDK for Next.js
77
+ *
78
+ * Recommended (automatic per-route capture — requests, latency, errors):
79
+ * npm i @deploze/next
80
+ * # set DEPLOZE_INGEST_KEY in your environment (dpi_... from repo settings)
81
+ *
82
+ * @vercel/otel ships as a dependency of this package — no separate install.
83
+ *
84
+ * // instrumentation.ts (project root or src/):
85
+ * import { registerOTel } from '@vercel/otel';
86
+ * import { DeplozeSpanProcessor } from '@deploze/next';
87
+ * export function register() {
88
+ * registerOTel({ serviceName: 'my-app', spanProcessors: [new DeplozeSpanProcessor()] });
89
+ * }
90
+ *
91
+ * No per-route edits: Next.js emits a span for every request and the
92
+ * processor records it. When using the span processor you do NOT also
93
+ * export `onRequestError` (it would double-count errors).
94
+ *
95
+ * Fallbacks when you can't run OTel:
96
+ * - error-only: `export { register, onRequestError } from '@deploze/next'`
97
+ * - manual success capture: wrap handlers with `withDeploze`, or call
98
+ * `trackRequest` from middleware / a custom server.
99
+ */
100
+ /**
101
+ * Next.js instrumentation hook. Called once per server instance start.
102
+ * Boots the collector; use this together with `onRequestError` for the
103
+ * error-only fallback path (the OTel span processor supersedes it).
104
+ */
105
+ declare function register(): void;
106
+ /**
107
+ * Next.js instrumentation error hook — captures uncaught request errors
108
+ * (server components, route handlers, middleware).
109
+ */
110
+ declare function onRequestError(error: unknown, request: {
111
+ path: string;
112
+ method: string;
113
+ }): void;
114
+ /**
115
+ * Record a completed request explicitly (for middleware or custom servers).
116
+ */
117
+ declare function trackRequest(input: {
118
+ path: string;
119
+ method?: string;
120
+ status: number;
121
+ durationMs?: number;
122
+ errorMessage?: string;
123
+ }): void;
124
+ type RouteHandler<Ctx> = (request: Request, context: Ctx) => Response | Promise<Response>;
125
+ /**
126
+ * Wrap a route handler to record status + latency for every invocation.
127
+ *
128
+ * export const GET = withDeploze(async (req) => { ... });
129
+ */
130
+ declare function withDeploze<Ctx = unknown>(handler: RouteHandler<Ctx>): RouteHandler<Ctx>;
131
+ /** Force a flush — useful in tests and short-lived scripts. */
132
+ declare function flush(): Promise<void>;
133
+
134
+ export { Collector, DeplozeSpanProcessor, type DeplozeSpanProcessorOptions, type SpanProcessorLike, bracketRouteToPattern, flush, onRequestError, register, registerDeploze, trackRequest, withDeploze };