@guidelytech/node 0.15.0 → 0.17.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/README.md +149 -5
- package/dist/index.cjs +1417 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +368 -7
- package/dist/index.d.ts +368 -7
- package/dist/index.js +1404 -32
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/message.ts","../src/retry.ts","../src/client.ts"],"sourcesContent":["export { Guidely, GuidelyError, SDK_NAME, SDK_VERSION, DEFAULT_API_URL } from \"./client\";\nexport type { Environment, FetchLike, GuidelyErrorCode, GuidelyOptions } from \"./client\";\nexport type { GroupMessage, IdentifyMessage, JsonValue, MessageType, Properties, Timestamp, TrackMessage } from \"./message\";\n","import { randomBytes } from \"node:crypto\";\n\n/** Limits shared by every Guidely server SDK (sdks/conformance/track-vectors.json → limits). */\nexport const LIMITS = {\n /** Most messages in one request (the API accepts 1–100). */\n maxBatchMessages: 100,\n /** Most serialized message bytes in one request (the API accepts bodies up to 512 KB). */\n maxBatchBytes: 500_000,\n /** A message larger than this when serialized is dropped and reported. */\n maxMessageBytes: 32_768,\n maxEventLength: 120,\n maxIdLength: 256,\n} as const;\n\nexport type MessageType = \"identify\" | \"track\" | \"group\";\n\n/** JSON-compatible values for traits and properties. */\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\nexport type Properties = Record<string, unknown>;\n/** A caller-supplied time: a `Date`, epoch milliseconds or an ISO 8601 string with an offset. */\nexport type Timestamp = Date | number | string;\n\nexport interface IdentifyMessage {\n /** Your user id (1–256 characters), the one your frontend passes to `identify()`. */\n userId: string | number;\n /** Merged into the user's traits. */\n traits?: Properties | null;\n /** Links the user to this account. */\n accountId?: string | number | null;\n /** When it happened (default: now). */\n timestamp?: Timestamp;\n}\n\nexport interface TrackMessage {\n /** Your user id; `track` needs `userId` or `anonymousId`. */\n userId?: string | number | null;\n /** The browser SDK's anonymous id (`Guidely.anonymousId`) for visitors who have not signed in. */\n anonymousId?: string | number | null;\n /** The event name (1–120 characters), e.g. `\"Report Exported\"`. */\n event: string;\n properties?: Properties | null;\n /** Links the user to this account. */\n accountId?: string | number | null;\n timestamp?: Timestamp;\n}\n\nexport interface GroupMessage {\n /** The account id (1–256 characters). */\n accountId: string | number;\n /** Merged into the account's traits (`name` also becomes the account name). */\n traits?: Properties | null;\n /** Adds this user to the account. */\n userId?: string | number | null;\n timestamp?: Timestamp;\n}\n\n/** A message as it is sent. */\nexport interface WireMessage {\n type: MessageType;\n messageId: string;\n timestamp: string;\n userId?: string;\n anonymousId?: string;\n event?: string;\n accountId?: string;\n traits?: Record<string, unknown>;\n properties?: Record<string, unknown>;\n}\n\nexport class InvalidMessageError extends Error {}\n\nconst ALPHABET = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/** 24 random characters from [0-9A-Za-z] (unbiased). */\nexport function newMessageId(): string {\n let id = \"\";\n while (id.length < 24) {\n for (const b of randomBytes(32)) {\n if (b < 248) id += ALPHABET[b % 62]; // 248 = 4 × 62: reject the remainder to stay unbiased\n if (id.length === 24) break;\n }\n }\n return id;\n}\n\n/** ISO 8601 UTC with milliseconds, e.g. `2026-10-26T10:00:00.000Z`. */\nexport function formatTimestamp(value: Timestamp): string {\n let date: Date;\n if (value instanceof Date) date = value;\n else if (typeof value === \"number\") date = new Date(value);\n else if (typeof value === \"string\" && /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})$/i.test(value.trim())) date = new Date(value.trim());\n else throw new InvalidMessageError(\"timestamp must be a Date, epoch milliseconds or an ISO 8601 string with an offset\");\n if (Number.isNaN(date.getTime())) throw new InvalidMessageError(\"timestamp is not a valid date\");\n return date.toISOString();\n}\n\n/** UTF-16 code units, like JavaScript's `length` (and the server's validation). */\nconst length = (s: string) => s.length;\n\n/**\n * An id field. `required` ids must be present; optional ones treat `null`, `undefined` and `\"\"` as\n * absent. Integers become strings; anything else that is not a non-blank string ≤ 256 is invalid.\n */\nfunction id(name: string, value: unknown, required: boolean): string | undefined {\n if (value === undefined || value === null || (!required && value === \"\")) {\n if (required) throw new InvalidMessageError(`${name} is required`);\n return undefined;\n }\n let s: string;\n if (typeof value === \"string\") s = value;\n else if (typeof value === \"number\" && Number.isSafeInteger(value)) s = String(value);\n else throw new InvalidMessageError(`${name} must be a string`);\n if (s.trim() === \"\") throw new InvalidMessageError(`${name} must not be empty`);\n if (length(s) > LIMITS.maxIdLength) throw new InvalidMessageError(`${name} is longer than ${LIMITS.maxIdLength} characters`);\n return s;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction object(name: string, value: unknown): Record<string, unknown> | undefined {\n if (value === undefined || value === null) return undefined;\n if (!isPlainObject(value)) throw new InvalidMessageError(`${name} must be an object`);\n return value;\n}\n\n/**\n * Validates a call and returns the message to send (without serializing it). Throws\n * {@link InvalidMessageError} when the call must be dropped.\n */\nexport function buildMessage(type: MessageType, args: unknown, now: () => Date = () => new Date()): WireMessage {\n if (!isPlainObject(args)) throw new InvalidMessageError(`${type}() needs an object argument`);\n const timestamp = args.timestamp === undefined || args.timestamp === null ? now().toISOString() : formatTimestamp(args.timestamp as Timestamp);\n const base = { type, messageId: newMessageId(), timestamp };\n switch (type) {\n case \"identify\": {\n const userId = id(\"userId\", args.userId, true);\n const traits = object(\"traits\", args.traits);\n const accountId = id(\"accountId\", args.accountId, false);\n return { ...base, userId, ...(traits ? { traits } : {}), ...(accountId ? { accountId } : {}) };\n }\n case \"track\": {\n const userId = id(\"userId\", args.userId, false);\n const anonymousId = id(\"anonymousId\", args.anonymousId, false);\n if (!userId && !anonymousId) throw new InvalidMessageError(\"track() needs a userId or an anonymousId\");\n const event = args.event;\n if (typeof event !== \"string\" || event.trim() === \"\") throw new InvalidMessageError(\"track() needs an event name\");\n if (length(event) > LIMITS.maxEventLength) throw new InvalidMessageError(`event is longer than ${LIMITS.maxEventLength} characters`);\n const properties = object(\"properties\", args.properties);\n const accountId = id(\"accountId\", args.accountId, false);\n return {\n ...base,\n ...(userId ? { userId } : {}),\n ...(anonymousId ? { anonymousId } : {}),\n event,\n ...(properties ? { properties } : {}),\n ...(accountId ? { accountId } : {}),\n };\n }\n case \"group\": {\n const accountId = id(\"accountId\", args.accountId, true);\n const traits = object(\"traits\", args.traits);\n const userId = id(\"userId\", args.userId, false);\n return { ...base, accountId, ...(traits ? { traits } : {}), ...(userId ? { userId } : {}) };\n }\n }\n}\n","/** What to do with a batch after an answer (status 0 = no answer: network error or timeout). */\nexport type ResponseAction = \"ok\" | \"retry\" | \"drop\";\n\nexport interface BackoffOptions {\n baseMs: number;\n maxMs: number;\n retryAfterMaxMs: number;\n}\n\nexport const DEFAULT_BACKOFF: BackoffOptions = { baseMs: 1000, maxMs: 30_000, retryAfterMaxMs: 60_000 };\n\n/** 2xx → ok; no answer, 429 and 5xx → retry; anything else (other 4xx, 3xx) → drop. */\nexport function responseAction(status: number): ResponseAction {\n if (status >= 200 && status < 300) return \"ok\";\n if (status === 0 || status === 429 || (status >= 500 && status < 600)) return \"retry\";\n return \"drop\";\n}\n\n/** Retry-After in whole seconds → milliseconds; anything else (HTTP dates, garbage) → null. */\nexport function parseRetryAfter(value: string | null | undefined): number | null {\n if (value == null) return null;\n const v = value.trim();\n return /^\\d+$/.test(v) ? Number(v) * 1000 : null;\n}\n\n/**\n * The wait before retrying after failed attempt `attempt` (1 = the first send), before jitter:\n * `min(baseMs · 2^(attempt−1), maxMs)`, or Retry-After capped at `retryAfterMaxMs`.\n */\nexport function backoffDelay(attempt: number, retryAfter: string | null | undefined, o: BackoffOptions = DEFAULT_BACKOFF): number {\n const ra = parseRetryAfter(retryAfter);\n if (ra !== null) return Math.min(ra, o.retryAfterMaxMs);\n return Math.min(o.baseMs * 2 ** Math.max(0, attempt - 1), o.maxMs);\n}\n\n/** ±20 % jitter on a computed backoff (not on Retry-After). `random` is in [0, 1). */\nexport function jitter(delayMs: number, random: number): number {\n return Math.round(delayMs * (0.8 + 0.4 * random));\n}\n","import { buildMessage, InvalidMessageError, LIMITS, type GroupMessage, type IdentifyMessage, type MessageType, type TrackMessage } from \"./message\";\nimport { backoffDelay, DEFAULT_BACKOFF, jitter, parseRetryAfter, responseAction } from \"./retry\";\n\nexport const SDK_NAME = \"guidely-node\";\nexport const SDK_VERSION = \"0.15.0\";\nexport const DEFAULT_API_URL = \"https://guidelytech.com\";\nexport const BATCH_PATH = \"/api/v1/sdk/server/batch\";\n\nexport type Environment = \"development\" | \"staging\" | \"production\";\nconst ENVIRONMENTS: readonly string[] = [\"development\", \"staging\", \"production\"];\n\n/** The subset of `fetch` the SDK uses, so any implementation (undici, node-fetch, a test fake) fits. */\nexport type FetchLike = (\n url: string,\n init: { method: \"POST\"; headers: Record<string, string>; body: string; signal: AbortSignal },\n) => Promise<{ status: number; headers: { get(name: string): string | null }; text?: () => Promise<string> }>;\n\nexport type GuidelyErrorCode =\n /** A call was invalid (missing userId, empty event…) and dropped. */\n | \"invalid_message\"\n /** A message serialized to more than 32 KB and was dropped. */\n | \"message_too_large\"\n /** The queue was full (`maxQueueSize`); the oldest messages were dropped. */\n | \"queue_full\"\n /** A batch was rejected (4xx), or failed after every retry, or was cut short by a shutdown timeout. */\n | \"delivery_failed\"\n /** A call was made after `shutdown()`. */\n | \"closed\";\n\n/** Reported to `onError`; never thrown by tracking calls. */\nexport class GuidelyError extends Error {\n override readonly name = \"GuidelyError\";\n constructor(\n readonly code: GuidelyErrorCode,\n message: string,\n /** How many messages were dropped. */\n readonly count = 1,\n /** The HTTP status, for `delivery_failed` (0 when no answer was received). */\n readonly status?: number,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n }\n}\n\nexport interface GuidelyOptions {\n /** A secret API key (`gly_sk_…`) with the `events:write` scope. Never ship it to a browser. */\n secretKey: string;\n /** The environment events are written to. */\n environment: Environment;\n /** API origin (default `https://guidelytech.com`). */\n apiUrl?: string;\n /** Send a batch when this many messages are queued (default 100; batches hold at most 100). */\n flushAt?: number;\n /** Send what is queued at least this often (default 5000 ms). */\n flushIntervalMs?: number;\n /** Most messages held in memory; beyond it the oldest are dropped (default 10,000). */\n maxQueueSize?: number;\n /** Retries of a batch after network errors, 429 and 5xx (default 5, so up to 6 attempts). */\n maxRetries?: number;\n /** How long `shutdown()` (and the exit hook) waits for queued messages to go out (default 10,000 ms). */\n shutdownTimeoutMs?: number;\n /** Timeout of one HTTP request (default 10,000 ms). */\n timeoutMs?: number;\n /** Receives every problem (default: `console.warn`). Called synchronously; must not throw. */\n onError?: (error: GuidelyError) => void;\n /** `fetch` implementation (default: the global `fetch` of Node 18+). */\n fetch?: FetchLike;\n /** Flush on the process's `beforeExit` event (default true). Signals and `process.exit()` skip it: call `shutdown()`. */\n handleExit?: boolean;\n}\n\ninterface Queued {\n json: string;\n bytes: number;\n}\n\ninterface Sleep {\n timer: ReturnType<typeof setTimeout> | undefined;\n resolve: () => void;\n}\n\nconst int = (value: number | undefined, fallback: number, min: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? Math.max(min, Math.floor(value)) : fallback;\n\n/**\n * Server-side Guidely client: `identify`, `track` and `group` from your backend.\n *\n * ```ts\n * const guidely = new Guidely({ secretKey: process.env.GUIDELY_SECRET_KEY!, environment: \"production\" });\n * guidely.track({ userId: \"u_42\", event: \"Report Exported\", properties: { format: \"csv\" } });\n * await guidely.shutdown(); // before the process exits\n * ```\n *\n * Calls validate, queue and return: they never throw and never wait for the network. Messages go out\n * in batches (every `flushAt` messages, every `flushIntervalMs`, on `flush()`), one request at a time,\n * retried with backoff when Guidely is unreachable.\n */\nexport class Guidely {\n private readonly url: string;\n private readonly headers: Record<string, string>;\n private readonly flushAt: number;\n private readonly flushIntervalMs: number;\n private readonly maxQueueSize: number;\n private readonly maxRetries: number;\n private readonly shutdownTimeoutMs: number;\n private readonly timeoutMs: number;\n private readonly onError: (error: GuidelyError) => void;\n private readonly fetch: FetchLike;\n private readonly sdkJson = JSON.stringify({ name: SDK_NAME, version: SDK_VERSION });\n\n private queue: Queued[] = [];\n private droppedSinceReport = 0;\n private timer: ReturnType<typeof setTimeout> | undefined;\n private pumping: Promise<void> | null = null;\n private drainAll = false;\n /** Bumped to abandon the running pump (shutdown timeout): its request is aborted and its sleeps end. */\n private epoch = 0;\n private inflight: AbortController | null = null;\n private readonly sleeps = new Set<Sleep>();\n private closed = false;\n private shutdownPromise: Promise<void> | null = null;\n private exitDrain: Promise<void> | null = null;\n private readonly exitListener: (() => void) | null = null;\n\n constructor(options: GuidelyOptions) {\n const o = options ?? ({} as GuidelyOptions);\n const key = typeof o.secretKey === \"string\" ? o.secretKey.trim() : \"\";\n if (!key.startsWith(\"gly_sk_\")) {\n throw new TypeError(\"Guidely: secretKey must be a secret API key (gly_sk_…) with the events:write scope\");\n }\n if (!ENVIRONMENTS.includes(o.environment)) {\n throw new TypeError('Guidely: environment must be \"development\", \"staging\" or \"production\"');\n }\n const fetchImpl = o.fetch ?? (typeof globalThis.fetch === \"function\" ? (globalThis.fetch.bind(globalThis) as unknown as FetchLike) : undefined);\n if (!fetchImpl) throw new TypeError(\"Guidely: no global fetch (Node 18+ is required), pass the fetch option\");\n this.fetch = fetchImpl;\n const apiUrl = (o.apiUrl ?? DEFAULT_API_URL).trim().replace(/\\/+$/, \"\");\n this.url = `${apiUrl}${BATCH_PATH}?environment=${encodeURIComponent(o.environment)}`;\n this.headers = {\n Authorization: `Bearer ${key}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"User-Agent\": `${SDK_NAME}/${SDK_VERSION} (Node ${typeof process !== \"undefined\" ? process.version : \"unknown\"})`,\n };\n this.flushAt = int(o.flushAt, 100, 1);\n this.flushIntervalMs = int(o.flushIntervalMs, 5000, 1);\n this.maxQueueSize = int(o.maxQueueSize, 10_000, 1);\n this.maxRetries = int(o.maxRetries, 5, 0);\n this.shutdownTimeoutMs = int(o.shutdownTimeoutMs, 10_000, 0);\n this.timeoutMs = int(o.timeoutMs, 10_000, 1);\n this.onError = o.onError ?? ((e) => console.warn(`[${SDK_NAME}] ${e.message}`));\n if (o.handleExit !== false && typeof process !== \"undefined\" && typeof process.on === \"function\") {\n this.exitListener = () => this.onBeforeExit();\n process.on(\"beforeExit\", this.exitListener);\n }\n }\n\n /** Who a user is: merges `traits` into the user (creating it if needed), optionally linking an account. */\n identify(message: IdentifyMessage): void {\n this.enqueue(\"identify\", message);\n }\n\n /** What a user (or anonymous visitor) did. */\n track(message: TrackMessage): void {\n this.enqueue(\"track\", message);\n }\n\n /** Account traits, and optionally adds `userId` to the account. */\n group(message: GroupMessage): void {\n this.enqueue(\"group\", message);\n }\n\n /** Sends everything queued; resolves once it has been delivered or dropped. Never rejects. */\n flush(): Promise<void> {\n return this.startPump(true);\n }\n\n /**\n * Stops the timer and the exit hook, then flushes, waiting at most `shutdownTimeoutMs`. Later calls\n * are dropped (and reported). Call it before your process exits. Never rejects.\n */\n shutdown(): Promise<void> {\n if (this.shutdownPromise) return this.shutdownPromise;\n this.closed = true;\n this.clearTimer();\n if (this.exitListener) process.removeListener(\"beforeExit\", this.exitListener);\n this.shutdownPromise = this.drain(this.shutdownTimeoutMs);\n return this.shutdownPromise;\n }\n\n // --- queueing ------------------------------------------------------------------------------\n\n private enqueue(type: MessageType, args: unknown): void {\n try {\n if (this.closed) {\n this.report(new GuidelyError(\"closed\", `${type}() was called after shutdown(); the message was dropped`));\n return;\n }\n const message = buildMessage(type, args);\n let json: string;\n try {\n json = JSON.stringify(message);\n } catch (e) {\n throw new InvalidMessageError(`could not be serialized to JSON (${e instanceof Error ? e.message : String(e)})`);\n }\n const bytes = Buffer.byteLength(json, \"utf8\");\n if (bytes > LIMITS.maxMessageBytes) {\n this.report(new GuidelyError(\"message_too_large\", `${type}() message is ${bytes} bytes, more than the ${LIMITS.maxMessageBytes}-byte limit; it was dropped`));\n return;\n }\n if (this.queue.length >= this.maxQueueSize) {\n this.queue.shift();\n this.droppedSinceReport++;\n }\n this.queue.push({ json, bytes });\n if (this.queue.length >= this.flushAt) void this.startPump(false);\n else this.scheduleTimer();\n } catch (e) {\n if (e instanceof InvalidMessageError) this.report(new GuidelyError(\"invalid_message\", `Invalid ${type}() call dropped: ${e.message}`));\n else this.report(new GuidelyError(\"invalid_message\", `${type}() failed: ${e instanceof Error ? e.message : String(e)}`, 1, undefined, { cause: e }));\n }\n }\n\n private scheduleTimer(): void {\n if (this.timer !== undefined || this.closed) return;\n this.timer = setTimeout(() => {\n this.timer = undefined;\n void this.startPump(true);\n }, this.flushIntervalMs);\n (this.timer as { unref?: () => void }).unref?.();\n }\n\n private clearTimer(): void {\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n // --- sending -------------------------------------------------------------------------------\n\n /** Starts (or joins) the single sender. `all`: send everything, not only full batches. */\n private startPump(all: boolean): Promise<void> {\n if (all) this.drainAll = true;\n if (!this.pumping) this.pumping = this.pump();\n return this.pumping;\n }\n\n private async pump(): Promise<void> {\n await Promise.resolve(); // `this.pumping` is assigned before the loop can finish\n const epoch = this.epoch;\n try {\n const cap = Math.min(this.flushAt, LIMITS.maxBatchMessages);\n for (;;) {\n this.reportDrops();\n if (epoch !== this.epoch || this.queue.length === 0 || (!this.drainAll && this.queue.length < cap)) break;\n await this.deliver(this.takeBatch(cap), epoch);\n }\n } catch (e) {\n this.report(new GuidelyError(\"delivery_failed\", `Unexpected error while sending: ${e instanceof Error ? e.message : String(e)}`, 0, undefined, { cause: e }));\n } finally {\n this.pumping = null;\n this.drainAll = false;\n if (this.queue.length > 0) this.scheduleTimer();\n }\n }\n\n /** Up to `cap` messages from the head of the queue, at most `maxBatchBytes` of them (at least one). */\n private takeBatch(cap: number): Queued[] {\n let n = 0;\n let size = 0;\n while (n < this.queue.length && n < cap) {\n const next = this.queue[n]!;\n if (n > 0 && size + next.bytes > LIMITS.maxBatchBytes) break;\n size += next.bytes;\n n++;\n }\n return this.queue.splice(0, n);\n }\n\n private async deliver(batch: Queued[], epoch: number): Promise<void> {\n const messages = batch.map((m) => m.json).join(\",\");\n for (let attempt = 1; ; attempt++) {\n if (epoch !== this.epoch) {\n this.report(new GuidelyError(\"delivery_failed\", `${batch.length} messages were not sent before the shutdown timeout`, batch.length, 0));\n return;\n }\n const body = `{\"batch\":[${messages}],\"sentAt\":${JSON.stringify(new Date().toISOString())},\"sdk\":${this.sdkJson}}`;\n let status = 0;\n let retryAfter: string | null = null;\n let failure: unknown;\n try {\n const res = await this.send(body);\n status = res.status;\n retryAfter = res.headers.get(\"retry-after\");\n } catch (e) {\n failure = e;\n }\n const action = responseAction(status);\n if (action === \"ok\") return;\n if (epoch !== this.epoch) continue; // aborted while sending: reported at the top\n if (action === \"drop\" || attempt > this.maxRetries) {\n this.report(new GuidelyError(\"delivery_failed\", failureMessage(status, failure, batch.length, attempt), batch.length, status, { cause: failure }));\n return;\n }\n const delay = parseRetryAfter(retryAfter) !== null ? backoffDelay(attempt, retryAfter) : jitter(backoffDelay(attempt, null, DEFAULT_BACKOFF), Math.random());\n await this.sleep(delay);\n }\n }\n\n private async send(body: string) {\n const controller = new AbortController();\n this.inflight = controller;\n const timeout = setTimeout(() => controller.abort(new Error(`request timed out after ${this.timeoutMs} ms`)), this.timeoutMs);\n try {\n const res = await this.fetch(this.url, { method: \"POST\", headers: this.headers, body, signal: controller.signal });\n try {\n await res.text?.(); // release the connection\n } catch {\n // the status is what matters\n }\n return res;\n } finally {\n clearTimeout(timeout);\n if (this.inflight === controller) this.inflight = null;\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise<void>((resolve) => {\n const s: Sleep = { timer: undefined, resolve };\n s.timer = setTimeout(() => {\n this.sleeps.delete(s);\n resolve();\n }, ms);\n this.sleeps.add(s);\n });\n }\n\n /** Flushes, giving up after `timeoutMs`: the request in flight is aborted and what is left is dropped. */\n private async drain(timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = await Promise.race([\n this.startPump(true).then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), timeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (!timedOut) return;\n this.epoch++;\n this.inflight?.abort(new Error(\"shutdown timeout\"));\n for (const s of this.sleeps) {\n clearTimeout(s.timer);\n s.resolve();\n }\n this.sleeps.clear();\n const left = this.queue.length;\n this.queue = [];\n if (left > 0) this.report(new GuidelyError(\"delivery_failed\", `${left} queued messages were not sent within ${timeoutMs} ms`, left, 0));\n }\n\n private onBeforeExit(): void {\n if (this.closed || this.exitDrain || (this.queue.length === 0 && !this.pumping)) return;\n this.exitDrain = this.drain(this.shutdownTimeoutMs).finally(() => {\n this.exitDrain = null;\n });\n }\n\n // --- errors --------------------------------------------------------------------------------\n\n private reportDrops(): void {\n if (this.droppedSinceReport === 0) return;\n const n = this.droppedSinceReport;\n this.droppedSinceReport = 0;\n this.report(new GuidelyError(\"queue_full\", `The queue was full (maxQueueSize ${this.maxQueueSize}): dropped the ${n} oldest messages`, n));\n }\n\n private report(error: GuidelyError): void {\n try {\n this.onError(error);\n } catch {\n // an error handler must never break the caller\n }\n }\n}\n\nfunction failureMessage(status: number, failure: unknown, count: number, attempts: number): string {\n const what = `${count} messages were dropped`;\n if (status === 0) return `${what}: Guidely could not be reached in ${attempts} attempt${attempts === 1 ? \"\" : \"s\"} (${failure instanceof Error ? failure.message : String(failure)})`;\n if (status === 401 || status === 403) return `${what}: the key was rejected (HTTP ${status}). Check it is a gly_sk_ key with the events:write scope for this environment`;\n if (attempts > 1) return `${what}: HTTP ${status} after ${attempts} attempts`;\n return `${what}: HTTP ${status}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA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BAAoB,CAAC,CAAC;AAAA,EAC3I;AAAA,EAEQ,OAAO,OAA2B;AACxC,QAAI;AACF,WAAK,QAAQ,KAAK;AAAA,IACpB,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAEA,SAAS,eAAe,QAAgB,SAAkB,OAAe,UAA0B;AACjG,QAAM,OAAO,GAAG,KAAK;AACrB,MAAI,WAAW,EAAG,QAAO,GAAG,IAAI,qCAAqC,QAAQ,WAAW,aAAa,IAAI,KAAK,GAAG,KAAK,mBAAmB,QAAQ,QAAQ,UAAU,OAAO,OAAO,CAAC;AAClL,MAAI,WAAW,OAAO,WAAW,IAAK,QAAO,GAAG,IAAI,gCAAgC,MAAM;AAC1F,MAAI,WAAW,EAAG,QAAO,GAAG,IAAI,UAAU,MAAM,UAAU,QAAQ;AAClE,SAAO,GAAG,IAAI,UAAU,MAAM;AAChC;","names":["id"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/message.ts","../src/retry.ts","../src/errors/event.ts","../src/errors/normalize.ts","../src/errors/stack.ts","../src/errors/monitor.ts","../src/errors/breadcrumbs.ts","../src/errors/context-lines.ts","../src/errors/process-handlers.ts","../src/errors/request.ts","../src/errors/scope.ts","../src/client.ts"],"sourcesContent":["export { Guidely, GuidelyError, SDK_NAME, SDK_VERSION, DEFAULT_API_URL } from \"./client\";\nexport type { Environment, FetchLike, GuidelyErrorCode, GuidelyOptions } from \"./client\";\nexport type { GroupMessage, IdentifyMessage, JsonValue, MessageType, Properties, Timestamp, TrackMessage } from \"./message\";\nexport { Scope } from \"./errors/scope\";\nexport { parseStack } from \"./errors/stack\";\nexport type { GuidelyFrame } from \"./errors/stack\";\nexport type { FastifyLike, MiddlewareOptions } from \"./errors/monitor\";\nexport type { ProcessHandlerOptions, ProcessLike, UnhandledRejectionMode } from \"./errors/process-handlers\";\nexport type {\n Breadcrumb,\n BreadcrumbHint,\n CaptureContext,\n ConsoleLevel,\n ErrorEvent,\n ErrorOptions,\n EventHint,\n ExceptionValue,\n Mechanism,\n RequestData,\n SeverityLevel,\n StackFrame,\n User,\n} from \"./errors/types\";\n","import { randomBytes } from \"node:crypto\";\n\n/** Limits shared by every Guidely server SDK (sdks/conformance/track-vectors.json → limits). */\nexport const LIMITS = {\n /** Most messages in one request (the API accepts 1–100). */\n maxBatchMessages: 100,\n /** Most serialized message bytes in one request (the API accepts bodies up to 512 KB). */\n maxBatchBytes: 500_000,\n /** A message larger than this when serialized is dropped and reported. */\n maxMessageBytes: 32_768,\n maxEventLength: 120,\n maxIdLength: 256,\n} as const;\n\nexport type MessageType = \"identify\" | \"track\" | \"group\";\n\n/** JSON-compatible values for traits and properties. */\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\nexport type Properties = Record<string, unknown>;\n/** A caller-supplied time: a `Date`, epoch milliseconds or an ISO 8601 string with an offset. */\nexport type Timestamp = Date | number | string;\n\nexport interface IdentifyMessage {\n /** Your user id (1–256 characters), the one your frontend passes to `identify()`. */\n userId: string | number;\n /** Merged into the user's traits. */\n traits?: Properties | null;\n /** Links the user to this account. */\n accountId?: string | number | null;\n /** When it happened (default: now). */\n timestamp?: Timestamp;\n}\n\nexport interface TrackMessage {\n /** Your user id; `track` needs `userId` or `anonymousId`. */\n userId?: string | number | null;\n /** The browser SDK's anonymous id (`Guidely.anonymousId`) for visitors who have not signed in. */\n anonymousId?: string | number | null;\n /** The event name (1–120 characters), e.g. `\"Report Exported\"`. */\n event: string;\n properties?: Properties | null;\n /** Links the user to this account. */\n accountId?: string | number | null;\n timestamp?: Timestamp;\n /** Version of your app this event came from (default: the client's `appVersion` option). */\n appVersion?: string | number | null;\n}\n\nexport interface GroupMessage {\n /** The account id (1–256 characters). */\n accountId: string | number;\n /** Merged into the account's traits (`name` also becomes the account name). */\n traits?: Properties | null;\n /** Adds this user to the account. */\n userId?: string | number | null;\n timestamp?: Timestamp;\n}\n\n/** A message as it is sent. */\nexport interface WireMessage {\n type: MessageType;\n messageId: string;\n timestamp: string;\n userId?: string;\n anonymousId?: string;\n event?: string;\n accountId?: string;\n traits?: Record<string, unknown>;\n properties?: Record<string, unknown>;\n appVersion?: string;\n}\n\nexport class InvalidMessageError extends Error {}\n\nconst ALPHABET = \"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\";\n\n/** 24 random characters from [0-9A-Za-z] (unbiased). */\nexport function newMessageId(): string {\n let id = \"\";\n while (id.length < 24) {\n for (const b of randomBytes(32)) {\n if (b < 248) id += ALPHABET[b % 62]; // 248 = 4 × 62: reject the remainder to stay unbiased\n if (id.length === 24) break;\n }\n }\n return id;\n}\n\n/** ISO 8601 UTC with milliseconds, e.g. `2026-10-26T10:00:00.000Z`. */\nexport function formatTimestamp(value: Timestamp): string {\n let date: Date;\n if (value instanceof Date) date = value;\n else if (typeof value === \"number\") date = new Date(value);\n else if (typeof value === \"string\" && /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d+)?)?(Z|[+-]\\d{2}:?\\d{2})$/i.test(value.trim())) date = new Date(value.trim());\n else throw new InvalidMessageError(\"timestamp must be a Date, epoch milliseconds or an ISO 8601 string with an offset\");\n if (Number.isNaN(date.getTime())) throw new InvalidMessageError(\"timestamp is not a valid date\");\n return date.toISOString();\n}\n\n/** UTF-16 code units, like JavaScript's `length` (and the server's validation). */\nconst length = (s: string) => s.length;\n\n/**\n * An id field. `required` ids must be present; optional ones treat `null`, `undefined` and `\"\"` as\n * absent. Integers become strings; anything else that is not a non-blank string ≤ 256 is invalid.\n */\nfunction id(name: string, value: unknown, required: boolean): string | undefined {\n if (value === undefined || value === null || (!required && value === \"\")) {\n if (required) throw new InvalidMessageError(`${name} is required`);\n return undefined;\n }\n let s: string;\n if (typeof value === \"string\") s = value;\n else if (typeof value === \"number\" && Number.isSafeInteger(value)) s = String(value);\n else throw new InvalidMessageError(`${name} must be a string`);\n if (s.trim() === \"\") throw new InvalidMessageError(`${name} must not be empty`);\n if (length(s) > LIMITS.maxIdLength) throw new InvalidMessageError(`${name} is longer than ${LIMITS.maxIdLength} characters`);\n return s;\n}\n\n/** An app version: a non-blank string or number, trimmed and cut to 200 characters; anything else is left out. */\nfunction version(value: unknown): string | undefined {\n if (typeof value !== \"string\" && typeof value !== \"number\") return undefined;\n const s = String(value).trim();\n return s ? s.slice(0, 200) : undefined;\n}\n\nfunction isPlainObject(v: unknown): v is Record<string, unknown> {\n if (typeof v !== \"object\" || v === null || Array.isArray(v)) return false;\n const proto = Object.getPrototypeOf(v);\n return proto === Object.prototype || proto === null;\n}\n\nfunction object(name: string, value: unknown): Record<string, unknown> | undefined {\n if (value === undefined || value === null) return undefined;\n if (!isPlainObject(value)) throw new InvalidMessageError(`${name} must be an object`);\n return value;\n}\n\n/**\n * Validates a call and returns the message to send (without serializing it). Throws\n * {@link InvalidMessageError} when the call must be dropped.\n */\nexport function buildMessage(type: MessageType, args: unknown, now: () => Date = () => new Date()): WireMessage {\n if (!isPlainObject(args)) throw new InvalidMessageError(`${type}() needs an object argument`);\n const timestamp = args.timestamp === undefined || args.timestamp === null ? now().toISOString() : formatTimestamp(args.timestamp as Timestamp);\n const base = { type, messageId: newMessageId(), timestamp };\n switch (type) {\n case \"identify\": {\n const userId = id(\"userId\", args.userId, true);\n const traits = object(\"traits\", args.traits);\n const accountId = id(\"accountId\", args.accountId, false);\n return { ...base, userId, ...(traits ? { traits } : {}), ...(accountId ? { accountId } : {}) };\n }\n case \"track\": {\n const userId = id(\"userId\", args.userId, false);\n const anonymousId = id(\"anonymousId\", args.anonymousId, false);\n if (!userId && !anonymousId) throw new InvalidMessageError(\"track() needs a userId or an anonymousId\");\n const event = args.event;\n if (typeof event !== \"string\" || event.trim() === \"\") throw new InvalidMessageError(\"track() needs an event name\");\n if (length(event) > LIMITS.maxEventLength) throw new InvalidMessageError(`event is longer than ${LIMITS.maxEventLength} characters`);\n const properties = object(\"properties\", args.properties);\n const accountId = id(\"accountId\", args.accountId, false);\n const appVersion = version(args.appVersion);\n return {\n ...base,\n ...(userId ? { userId } : {}),\n ...(anonymousId ? { anonymousId } : {}),\n event,\n ...(properties ? { properties } : {}),\n ...(accountId ? { accountId } : {}),\n ...(appVersion ? { appVersion } : {}),\n };\n }\n case \"group\": {\n const accountId = id(\"accountId\", args.accountId, true);\n const traits = object(\"traits\", args.traits);\n const userId = id(\"userId\", args.userId, false);\n return { ...base, accountId, ...(traits ? { traits } : {}), ...(userId ? { userId } : {}) };\n }\n }\n}\n","/** What to do with a batch after an answer (status 0 = no answer: network error or timeout). */\nexport type ResponseAction = \"ok\" | \"retry\" | \"drop\";\n\nexport interface BackoffOptions {\n baseMs: number;\n maxMs: number;\n retryAfterMaxMs: number;\n}\n\nexport const DEFAULT_BACKOFF: BackoffOptions = { baseMs: 1000, maxMs: 30_000, retryAfterMaxMs: 60_000 };\n\n/** 2xx → ok; no answer, 429 and 5xx → retry; anything else (other 4xx, 3xx) → drop. */\nexport function responseAction(status: number): ResponseAction {\n if (status >= 200 && status < 300) return \"ok\";\n if (status === 0 || status === 429 || (status >= 500 && status < 600)) return \"retry\";\n return \"drop\";\n}\n\n/** Retry-After in whole seconds → milliseconds; anything else (HTTP dates, garbage) → null. */\nexport function parseRetryAfter(value: string | null | undefined): number | null {\n if (value == null) return null;\n const v = value.trim();\n return /^\\d+$/.test(v) ? Number(v) * 1000 : null;\n}\n\n/**\n * The wait before retrying after failed attempt `attempt` (1 = the first send), before jitter:\n * `min(baseMs · 2^(attempt−1), maxMs)`, or Retry-After capped at `retryAfterMaxMs`.\n */\nexport function backoffDelay(attempt: number, retryAfter: string | null | undefined, o: BackoffOptions = DEFAULT_BACKOFF): number {\n const ra = parseRetryAfter(retryAfter);\n if (ra !== null) return Math.min(ra, o.retryAfterMaxMs);\n return Math.min(o.baseMs * 2 ** Math.max(0, attempt - 1), o.maxMs);\n}\n\n/** ±20 % jitter on a computed backoff (not on Retry-After). `random` is in [0, 1). */\nexport function jitter(delayMs: number, random: number): number {\n return Math.round(delayMs * (0.8 + 0.4 * random));\n}\n","import { randomUUID } from \"node:crypto\";\nimport { readFileSync } from \"node:fs\";\nimport * as os from \"node:os\";\nimport { normalize } from \"./normalize\";\nimport { parseStack, toGuidelyFrames, type FrameOptions, type GuidelyFrame } from \"./stack\";\nimport type { ErrorEvent, ExceptionValue, Mechanism } from \"./types\";\n\n/** Limits of an `exception` message (docs/error-monitoring/sdks.md → Wire format). */\nexport const ERROR_LIMITS = {\n /** `detail` (the Sentry-shaped event) after trimming. */\n maxDetailBytes: 65_536,\n /** `properties`, inside the event's property budget. */\n maxPropertyBytes: 8_192,\n /** A whole `exception` message: properties + detail + envelope. Larger ones lose their `detail`. */\n maxMessageBytes: 81_920,\n /** Exceptions in a cause / AggregateError chain. */\n maxChain: 20,\n} as const;\n\n/** 32 lowercase hex characters, Sentry's event id form; also the message's `messageId`. */\nexport const newEventId = () => randomUUID().replace(/-/g, \"\");\n\nconst errorLike = (v: unknown): v is Error =>\n v instanceof Error || (!!v && typeof v === \"object\" && typeof (v as Error).message === \"string\" && (typeof (v as Error).stack === \"string\" || typeof (v as Error).name === \"string\"));\n\nfunction typeOf(e: Error): string {\n const name = typeof e.name === \"string\" && e.name ? e.name : undefined;\n const ctor = (e as { constructor?: { name?: unknown } }).constructor?.name;\n // A subclass that did not set `name` reports \"Error\": its class name is more useful.\n return (name === \"Error\" && typeof ctor === \"string\" && ctor && ctor !== \"Error\" ? ctor : name) ?? (typeof ctor === \"string\" && ctor ? ctor : \"Error\");\n}\n\n/** A value that is not an Error, as an exception message (Sentry: \"Non-Error exception captured…\"). */\nexport function describe(value: unknown): string {\n if (typeof value === \"string\") return value;\n if (value === undefined || value === null || typeof value !== \"object\") return String(value);\n const keys = Object.keys(value).slice(0, 10);\n return keys.length ? `Non-Error exception captured with keys: ${keys.join(\", \")}` : `Non-Error exception captured: ${Object.prototype.toString.call(value)}`;\n}\n\n/**\n * The exception chain of `error` in Sentry's order: linked errors (`cause`, an AggregateError's\n * `errors`) first, the thrown exception last. Ids number the chain depth-first from the thrown\n * exception (0); each linked error names its parent. At most 20, cycle-safe.\n */\nexport function exceptionChain(error: unknown, mechanism: { type: string; handled: boolean }, o: FrameOptions, fallbackType = \"Error\"): ExceptionValue[] {\n const out: ExceptionValue[] = [];\n const seen = new Set<unknown>();\n const visit = (value: unknown, mech: Mechanism) => {\n if (out.length >= ERROR_LIMITS.maxChain) return;\n seen.add(value);\n const id = out.length;\n const isError = errorLike(value);\n const frames = isError ? parseStack(value.stack, o) : [];\n const aggregate = isError && Array.isArray((value as { errors?: unknown }).errors);\n const ex: ExceptionValue = {\n type: (isError ? typeOf(value) : fallbackType).slice(0, 200),\n value: (isError ? String(value.message ?? \"\") : describe(value)).slice(0, 8000),\n mechanism: { ...mech, exception_id: id, ...(aggregate ? { is_exception_group: true } : {}) },\n ...(frames.length ? { stacktrace: { frames } } : {}),\n };\n out.push(ex);\n if (!isError) return;\n const link = (child: unknown, source: string) => {\n if (!errorLike(child) || seen.has(child)) return;\n visit(child, { type: \"chained\", handled: mechanism.handled, source, parent_id: id });\n };\n if (aggregate) (value as unknown as { errors: unknown[] }).errors.slice(0, ERROR_LIMITS.maxChain).forEach((child, i) => link(child, `errors[${i}]`));\n link((value as { cause?: unknown }).cause, \"cause\");\n };\n visit(error, { type: mechanism.type, handled: mechanism.handled });\n return out.reverse();\n}\n\n/** The first line of `/etc/os-release`'s NAME / VERSION_ID (Linux distributions). */\nfunction linuxRelease(): { name?: string; version?: string } {\n try {\n const text = readFileSync(\"/etc/os-release\", \"utf8\").slice(0, 10_000);\n const field = (k: string) => new RegExp(`^${k}=\"?([^\"\\\\n]*)\"?$`, \"m\").exec(text)?.[1];\n return { name: field(\"NAME\"), version: field(\"VERSION_ID\") };\n } catch {\n return {};\n }\n}\n\n/** macOS version from the Darwin kernel release (Darwin 24 = macOS 15, Darwin 25 = macOS 26). */\nfunction macosVersion(release: string): string | undefined {\n const major = Number(release.split(\".\")[0]);\n if (!Number.isFinite(major)) return undefined;\n if (major >= 25) return String(major + 1);\n if (major >= 20) return String(major - 9);\n return major >= 5 ? `10.${major - 4}` : undefined;\n}\n\nlet staticContexts: Record<string, Record<string, unknown>> | null = null;\n\n/** Runtime, OS, device, app and culture contexts. The static parts are read once per process. */\nexport function processContexts(): Record<string, Record<string, unknown>> {\n if (!staticContexts) {\n const release = safe(() => os.release(), \"\");\n const platform = process.platform;\n const linux = platform === \"linux\" ? linuxRelease() : {};\n const osName = platform === \"darwin\" ? \"macOS\" : platform === \"win32\" ? \"Windows\" : platform === \"linux\" ? (linux.name ?? \"Linux\") : safe(() => os.type(), platform);\n const osVersion = platform === \"darwin\" ? macosVersion(release) : platform === \"linux\" ? linux.version : release;\n const cpus = safe(() => os.cpus(), []);\n const intl = safe(() => Intl.DateTimeFormat().resolvedOptions(), undefined);\n staticContexts = {\n runtime: { name: \"node\", version: process.version },\n os: { name: osName, ...(osVersion ? { version: osVersion } : {}), ...(release ? { kernel_version: release } : {}) },\n device: {\n arch: process.arch,\n memory_size: safe(() => os.totalmem(), undefined),\n processor_count: cpus.length || undefined,\n cpu_description: cpus[0]?.model,\n processor_frequency: cpus[0]?.speed || undefined,\n boot_time: safe(() => new Date(Date.now() - os.uptime() * 1000).toISOString(), undefined),\n },\n app: { app_start_time: new Date(Date.now() - process.uptime() * 1000).toISOString() },\n culture: intl ? { locale: intl.locale, timezone: intl.timeZone } : {},\n };\n }\n const s = staticContexts;\n return {\n runtime: { ...s.runtime },\n os: { ...s.os },\n device: { ...s.device, free_memory: safe(() => os.freemem(), undefined) },\n app: { ...s.app, app_memory: safe(() => process.memoryUsage().rss, undefined) },\n culture: { ...s.culture },\n };\n}\n\nfunction safe<T>(fn: () => T, fallback: T): T {\n try {\n return fn();\n } catch {\n return fallback;\n }\n}\n\nconst bytes = (v: unknown) => Buffer.byteLength(JSON.stringify(v) ?? \"\", \"utf8\");\n\n/**\n * Trims `detail` to 64 KB in the documented order: breadcrumbs (oldest first), then frame source\n * context and variables, then extras and request headers, then outer frames and linked errors.\n * Returns `undefined` when even the bare exception does not fit.\n */\nexport function trimDetail(event: ErrorEvent, max: number = ERROR_LIMITS.maxDetailBytes): ErrorEvent | undefined {\n let size = bytes(event);\n if (size <= max) return event;\n const e: ErrorEvent = { ...event };\n const frames = () => (e.exception?.values ?? []).flatMap((x) => x.stacktrace?.frames ?? []);\n let crumbs = e.breadcrumbs?.values ?? [];\n while (crumbs.length > 0 && size > max) {\n crumbs = crumbs.slice(Math.ceil(crumbs.length / 2));\n e.breadcrumbs = { values: crumbs };\n size = bytes(e);\n }\n if (size <= max) return e;\n delete e.breadcrumbs;\n e.exception = e.exception ? { values: e.exception.values.map((x) => ({ ...x, ...(x.stacktrace ? { stacktrace: { frames: x.stacktrace.frames.map((f) => ({ ...f })) } } : {}) })) } : undefined;\n if (!e.exception) delete e.exception;\n for (const f of frames()) {\n delete f.pre_context;\n delete f.post_context;\n delete f.context_line;\n delete f.vars;\n }\n size = bytes(e);\n if (size <= max) return e;\n e.extra = { _trimmed: true };\n if (e.request) e.request = { ...e.request, headers: {} };\n size = bytes(e);\n if (size <= max) return e;\n // Outer frames, then linked errors (the thrown exception, last, is kept).\n for (const x of e.exception?.values ?? []) if (x.stacktrace && x.stacktrace.frames.length > 50) x.stacktrace.frames = x.stacktrace.frames.slice(-50);\n while (e.exception && e.exception.values.length > 1 && bytes(e) > max) e.exception.values.shift();\n if (bytes(e) <= max) return e;\n e.contexts = { runtime: e.contexts?.runtime ?? {} };\n delete e.extra;\n return bytes(e) <= max ? e : undefined;\n}\n\n/** The Guidely `properties` that index an occurrence, from the (possibly `beforeSend`-edited) event. */\nexport function propertiesOf(event: ErrorEvent, source: string, release: string | undefined, extra: Record<string, unknown>): Record<string, unknown> {\n const main = event.exception?.values?.[event.exception.values.length - 1];\n const os = event.contexts?.os as { name?: string; version?: string } | undefined;\n const props: Record<string, unknown> = {\n type: (main?.type ?? \"Message\").slice(0, 200),\n message: (main?.value ?? event.logentry?.formatted ?? \"\").slice(0, 1000),\n frames: toGuidelyFrames(main?.stacktrace?.frames),\n source,\n handled: main?.mechanism ? main.mechanism.handled !== false : event.level !== \"fatal\",\n level: event.level,\n platform: \"node\",\n ...(main?.mechanism?.type ? { mechanism: main.mechanism.type.slice(0, 60) } : {}),\n ...(release ? { release: release.slice(0, 200) } : {}),\n ...(Array.isArray(event.fingerprint) && event.fingerprint.length ? { fingerprintParts: event.fingerprint.slice(0, 20).map((p) => String(p).slice(0, 200)) } : {}),\n ...(event.transaction ? { transaction: String(event.transaction).slice(0, 200) } : {}),\n ...(os?.name ? { os: [os.name, os.version].filter(Boolean).join(\" \").slice(0, 60) } : {}),\n };\n const user = normalize(extra, 3) as Record<string, unknown> | undefined;\n for (const [k, v] of Object.entries(user ?? {})) if (!(k in props) && !k.startsWith(\"$\")) props[k] = v;\n return fitProperties(props);\n}\n\n/** Keeps `properties` within 8 KB: user properties go first, then outer frames. */\nfunction fitProperties(props: Record<string, unknown>): Record<string, unknown> {\n if (bytes(props) <= ERROR_LIMITS.maxPropertyBytes) return props;\n const core = new Set([\"type\", \"message\", \"frames\", \"source\", \"handled\", \"level\", \"platform\", \"mechanism\", \"release\", \"fingerprintParts\", \"transaction\", \"os\"]);\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(props)) if (core.has(k)) out[k] = v;\n const frames = (out.frames as GuidelyFrame[]).slice();\n while (frames.length > 1 && bytes(out) > ERROR_LIMITS.maxPropertyBytes) {\n frames.pop();\n out.frames = frames;\n }\n if (bytes(out) > ERROR_LIMITS.maxPropertyBytes) out.message = String(out.message).slice(0, 200);\n return out;\n}\n","/**\n * Turns whatever an app attaches to an error (extras, contexts, breadcrumb data, request headers)\n * into JSON that is safe to send: bounded in depth and size, cycle-free, and without credentials.\n * The server scrubs again, but credentials must never leave the process.\n */\n\n/** Keys whose values never leave the process (the server's sensitive-property pattern plus credentials). */\nexport const SENSITIVE_KEY = /(password|passwd|secret|token|credit|card|cvv|ssn|iban|authorization|cookie|api[-_]?key|private[-_]?key)/i;\n/** Request headers that are never sent. */\nexport const SENSITIVE_HEADER = /^(authorization|proxy-authorization|cookie|set-cookie|x-api-key|x-auth-token|x-csrf-token|x-xsrf-token|x-guidely-key|x-guidely-conversation)$|secret|token|password|passwd|api[-_]?key|signature|session/i;\n/** Query parameters whose values are replaced with {@link FILTERED}. */\nexport const SENSITIVE_PARAM = /(token|key|secret|password|passwd|pwd|auth|session|code|sig|signature|credential|ssn|card|cvv|iban)/i;\n/** Headers that carry the client's address, sent only with `sendDefaultPii`. */\nexport const IP_HEADER = /^(x-forwarded-for|x-real-ip|forwarded|cf-connecting-ip|true-client-ip|x-client-ip)$/i;\nexport const FILTERED = \"[Filtered]\";\n\nconst MAX_STRING = 2000;\nconst MAX_KEYS = 100;\nconst MAX_ITEMS = 100;\n\n/**\n * A JSON-safe copy of `value`: at most `depth` levels, 100 keys / items per level, strings cut to\n * 2,000 characters, sensitive keys removed, cycles and getters that throw replaced by markers.\n */\nexport function normalize(value: unknown, depth = 4, seen: WeakSet<object> = new WeakSet()): unknown {\n switch (typeof value) {\n case \"string\":\n return value.length > MAX_STRING ? `${value.slice(0, MAX_STRING)}…` : value;\n case \"number\":\n return Number.isFinite(value) ? value : String(value);\n case \"boolean\":\n return value;\n case \"bigint\":\n return `${value}n`;\n case \"symbol\":\n return value.toString();\n case \"function\":\n return `[Function${value.name ? `: ${value.name}` : \"\"}]`;\n case \"undefined\":\n return undefined;\n }\n if (value === null) return null;\n const obj = value as object;\n if (obj instanceof Date) return Number.isNaN(obj.getTime()) ? \"Invalid Date\" : obj.toISOString();\n if (obj instanceof Error) return `${obj.name}: ${obj.message}`.slice(0, MAX_STRING);\n if (obj instanceof RegExp) return obj.toString();\n if (ArrayBuffer.isView(obj)) return `[${obj.constructor?.name ?? \"Buffer\"} ${obj.byteLength} bytes]`;\n if (seen.has(obj)) return \"[Circular]\";\n if (depth <= 0) return Array.isArray(obj) ? \"[Array]\" : \"[Object]\";\n seen.add(obj);\n try {\n if (Array.isArray(obj) || obj instanceof Set) {\n const items = Array.isArray(obj) ? obj : [...obj];\n const out = items.slice(0, MAX_ITEMS).map((v) => normalize(v, depth - 1, seen) ?? null);\n if (items.length > MAX_ITEMS) out.push(`[${items.length - MAX_ITEMS} more]`);\n return out;\n }\n const entries: Array<[string, unknown]> = obj instanceof Map ? [...obj].map(([k, v]) => [String(k), v]) : Object.keys(obj).map((k) => [k, undefined]);\n const out: Record<string, unknown> = {};\n let n = 0;\n for (const [key, mapped] of entries) {\n if (n >= MAX_KEYS) {\n out[\"…\"] = `${entries.length - MAX_KEYS} more keys`;\n break;\n }\n if (SENSITIVE_KEY.test(key)) continue;\n let v: unknown;\n try {\n v = obj instanceof Map ? mapped : (obj as Record<string, unknown>)[key];\n } catch {\n v = \"[Getter threw]\";\n }\n const nv = normalize(v, depth - 1, seen);\n if (nv === undefined) continue;\n out[key] = nv;\n n++;\n }\n return out;\n } finally {\n seen.delete(obj);\n }\n}\n\n/** {@link normalize} for something that must be an object (extras, a context, breadcrumb data). */\nexport function normalizeObject(value: unknown, depth = 4): Record<string, unknown> | undefined {\n if (!value || typeof value !== \"object\" || Array.isArray(value)) return undefined;\n const out = normalize(value, depth);\n return out && typeof out === \"object\" && !Array.isArray(out) ? (out as Record<string, unknown>) : undefined;\n}\n\n/** A query string with the values of sensitive parameters replaced by `[Filtered]`. */\nexport function scrubQuery(query: string): string {\n return query\n .replace(/^\\?/, \"\")\n .split(\"&\")\n .filter(Boolean)\n .slice(0, 100)\n .map((pair) => {\n const i = pair.indexOf(\"=\");\n const key = i < 0 ? pair : pair.slice(0, i);\n let name = key;\n try {\n name = decodeURIComponent(key.replace(/\\+/g, \" \"));\n } catch {\n // keep the raw key\n }\n return i >= 0 && SENSITIVE_PARAM.test(name) ? `${key}=${FILTERED}` : pair;\n })\n .join(\"&\")\n .slice(0, 2000);\n}\n\n/** A URL without its query string and fragment (breadcrumbs keep only origin and path). */\nexport function stripQuery(url: string): string {\n const i = url.search(/[?#]/);\n return (i < 0 ? url : url.slice(0, i)).slice(0, 2000);\n}\n","import { posix } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { StackFrame } from \"./types\";\n\n/** A frame as Guidely indexes it (`properties.frames`, innermost first). */\nexport interface GuidelyFrame {\n fn?: string;\n file?: string;\n line?: number;\n col?: number;\n inApp?: boolean;\n}\n\nexport interface FrameOptions {\n /** Directory module names are relative to (Sentry's `getModuleFromFilename` base). */\n root?: string;\n inAppExclude?: Array<string | RegExp>;\n}\n\n/** Frames per stack sent in `detail` (the innermost ones are kept). */\nexport const MAX_DETAIL_FRAMES = 250;\n/** Frames in `properties.frames`. */\nexport const MAX_PROPERTY_FRAMES = 30;\n\n// \" at fn (/app/x.js:1:2)\", \" at async fn (file:///app/x.mjs:1:2)\", \" at /app/x.js:1:2\", \" at new Foo (node:internal/x:1:2)\"\nconst LINE = /^\\s*at (?:async )?(?:(.+?) \\((.*)\\)|(.+))$/;\nconst LOCATION = /^(.*?):(\\d+)(?::(\\d+))?$/;\n// \"eval at fn (/app/x.js:1:2), <anonymous>:3:4\": the eval call site is the useful location.\nconst EVAL_ORIGIN = /\\(([^()]*?:\\d+:\\d+)\\)/;\n\n/** Parses a V8 `Error.stack` into Sentry frames, **oldest call first** (the throwing frame last). */\nexport function parseStack(stack: unknown, o: FrameOptions = {}): StackFrame[] {\n if (typeof stack !== \"string\" || !stack) return [];\n const frames: StackFrame[] = [];\n for (const raw of stack.split(\"\\n\")) {\n if (frames.length >= MAX_DETAIL_FRAMES * 2) break;\n const m = LINE.exec(raw.length > 2000 ? raw.slice(0, 2000) : raw);\n if (!m) continue;\n const fn = m[1]?.trim();\n let location = (m[2] ?? m[3] ?? \"\").trim();\n if (location.startsWith(\"eval at \")) location = EVAL_ORIGIN.exec(location)?.[1] ?? location;\n const at = LOCATION.exec(location);\n const frame: StackFrame = {};\n if (fn) frame.function = fn.slice(0, 200);\n if (at) {\n const file = filePath(at[1]!);\n frame.filename = file.slice(0, 1000);\n frame.abs_path = file.slice(0, 1000);\n frame.lineno = Number(at[2]);\n if (at[3]) frame.colno = Number(at[3]);\n const mod = moduleOf(file, o.root);\n if (mod) frame.module = mod;\n frame.in_app = isInApp(file, o.inAppExclude);\n } else {\n // \"native\", \"<anonymous>\", \"index 0\" (Promise.all): no source location.\n if (!fn && !location) continue;\n if (location && !/^index \\d+$/.test(location)) frame.filename = location.slice(0, 200);\n frame.in_app = false;\n }\n frames.push(frame);\n }\n frames.reverse();\n return frames.length > MAX_DETAIL_FRAMES ? frames.slice(-MAX_DETAIL_FRAMES) : frames;\n}\n\n/** `file:///app/x.mjs` → `/app/x.mjs`; anything else as written. */\nfunction filePath(location: string): string {\n if (!location.startsWith(\"file://\")) return location;\n try {\n return fileURLToPath(location);\n } catch {\n return location;\n }\n}\n\n/** False for dependencies (`node_modules`), Node internals and frames without a real file. */\nexport function isInApp(file: string, exclude?: Array<string | RegExp>): boolean {\n if (!file || file.startsWith(\"node:\") || file.startsWith(\"internal/\")) return false;\n if (!file.startsWith(\"/\") && !/^[a-z]:[\\\\/]/i.test(file) && !file.startsWith(\"\\\\\\\\\")) return false; // \"events.js\" (old Node core), \"<anonymous>\"\n if (/[\\\\/]node_modules[\\\\/]/.test(file)) return false;\n for (const p of exclude ?? []) {\n if (typeof p === \"string\") {\n if (p && file.includes(p)) return false;\n } else if (p instanceof RegExp) {\n p.lastIndex = 0; // a /g pattern remembers where it stopped\n if (p.test(file)) return false;\n }\n }\n return true;\n}\n\n/**\n * Sentry's Node `module` for a path: `pkg.sub:file` inside `node_modules`, `dir.sub:file` under\n * the app's root, the file name elsewhere. Extensions are dropped (`.js`, `.mjs`, `.cjs`, `.ts`…).\n */\nexport function moduleOf(file: string, root?: string): string | undefined {\n if (!file || file.startsWith(\"node:\") || file.startsWith(\"internal/\")) return undefined;\n const normalized = file.replace(/^[a-z]:/i, \"\").replace(/\\\\/g, \"/\");\n if (!normalized.startsWith(\"/\")) return undefined;\n const parsed = posix.parse(normalized);\n let name = /^\\.[cm]?[jt]sx?$/.test(parsed.ext) ? parsed.name : parsed.base;\n try {\n name = decodeURIComponent(name);\n } catch {\n // keep it encoded\n }\n const dir = parsed.dir || \".\";\n const n = dir.lastIndexOf(\"/node_modules\");\n if (n > -1) return `${dir.slice(n + 14).replace(/\\//g, \".\")}:${name}`;\n const base = root?.replace(/^[a-z]:/i, \"\").replace(/\\\\/g, \"/\").replace(/\\/+$/, \"\");\n if (base && (dir === base || dir.startsWith(`${base}/`))) {\n const mod = dir.slice(base.length + 1).replace(/\\//g, \".\");\n return mod ? `${mod}:${name}` : name;\n }\n return name;\n}\n\n/** Sentry frames (oldest first) → Guidely frames (innermost first), at most 30. */\nexport function toGuidelyFrames(frames: StackFrame[] | undefined): GuidelyFrame[] {\n const out: GuidelyFrame[] = [];\n if (!frames) return out;\n for (let i = frames.length - 1; i >= 0 && out.length < MAX_PROPERTY_FRAMES; i--) {\n const f = frames[i]!;\n const file = f.abs_path || f.filename;\n out.push({\n ...(f.function ? { fn: f.function.slice(0, 200) } : {}),\n ...(file ? { file: file.slice(0, 500) } : {}),\n ...(typeof f.lineno === \"number\" ? { line: f.lineno } : {}),\n ...(typeof f.colno === \"number\" ? { col: f.colno } : {}),\n ...(typeof f.in_app === \"boolean\" ? { inApp: f.in_app } : {}),\n });\n }\n return out;\n}\n","import { AsyncLocalStorage, AsyncResource } from \"node:async_hooks\";\nimport * as os from \"node:os\";\nimport { dirname } from \"node:path\";\nimport { instrumentConsole, instrumentHttp } from \"./breadcrumbs\";\nimport { addContextLines, wantsContext } from \"./context-lines\";\nimport { exceptionChain, newEventId, processContexts, propertiesOf, trimDetail } from \"./event\";\nimport { normalize, normalizeObject } from \"./normalize\";\nimport { installProcessHandlers, type ProcessHandlerOptions } from \"./process-handlers\";\nimport { requestDataOf, scrubRequest, transactionOf } from \"./request\";\nimport { MAX_BREADCRUMBS, MAX_TAGS, Scope } from \"./scope\";\nimport type { FrameOptions } from \"./stack\";\nimport type { Breadcrumb, BreadcrumbHint, CaptureContext, ConsoleLevel, ErrorEvent, ErrorOptions, EventHint, ExceptionValue, SeverityLevel, User } from \"./types\";\n\n/** What the monitor needs from the client that owns the transport. */\nexport interface MonitorHost {\n environment: string;\n appVersion: string | undefined;\n apiUrl: string;\n sdk: { name: string; version: string };\n /** Queues a finished `exception` message and asks for a prompt flush. */\n push(message: Record<string, unknown>): void;\n /** False after `shutdown()`: new captures are dropped (and reported). */\n accepting(): boolean;\n report(message: string, cause?: unknown, code?: \"closed\" | \"invalid_message\"): void;\n flush(): Promise<void>;\n}\n\n/** Decides which errors a framework middleware reports (default: 5xx and errors without a status). */\nexport interface MiddlewareOptions {\n shouldHandleError?: (error: unknown) => boolean;\n}\n\n/** The parts of a Fastify instance the plugin uses. */\nexport interface FastifyLike {\n addHook(name: string, hook: (...args: any[]) => unknown): unknown;\n}\n\ntype Next = (error?: unknown) => void;\ntype Mech = { type: string; handled: boolean; level: SeverityLevel; source: string; fallbackType?: string };\n\nconst LEVELS: SeverityLevel[] = [\"fatal\", \"error\", \"warning\", \"log\", \"info\", \"debug\"];\nconst levelOf = (v: unknown): SeverityLevel | undefined => (typeof v === \"string\" && (LEVELS as string[]).includes(v) ? (v as SeverityLevel) : v === \"warn\" ? \"warning\" : undefined);\nconst KNOWN_CONTEXT_KEYS = new Set([\"userId\", \"anonymousId\", \"accountId\", \"tags\", \"extra\", \"level\", \"fingerprint\", \"contexts\", \"request\", \"user\", \"mechanism\", \"transaction\"]);\nconst idString = (v: unknown): string | undefined => (typeof v === \"string\" && v.trim() ? v.slice(0, 256) : typeof v === \"number\" && Number.isSafeInteger(v) ? String(v) : undefined);\n\n/** The HTTP status an error carries (`status`, `statusCode`, `status_code`, Boom's `output.statusCode`). */\nexport function statusOf(error: unknown): number | undefined {\n if (!error || typeof error !== \"object\") return undefined;\n const e = error as Record<string, unknown>;\n for (const v of [e.status, e.statusCode, e.status_code, (e.output as Record<string, unknown> | undefined)?.statusCode]) {\n const n = typeof v === \"string\" ? Number(v) : v;\n if (typeof n === \"number\" && Number.isInteger(n) && n >= 100 && n < 600) return n;\n }\n return undefined;\n}\n\nconst defaultShouldHandle = (error: unknown) => {\n const status = statusOf(error);\n return status === undefined || status >= 500;\n};\n\n/**\n * Error monitoring for one client: scopes (process-wide plus one per `withScope()` / request,\n * through AsyncLocalStorage), automatic breadcrumbs, capture, and the framework and process hooks.\n * Events become `exception` messages queued on the client's transport (batched, retried, bounded).\n * Nothing here throws into the app.\n */\nexport class ErrorMonitor {\n private readonly global: Scope;\n private readonly als = new AsyncLocalStorage<Scope>();\n private readonly requestScopes = new WeakMap<object, Scope>();\n /** Errors already reported by an automatic hook (an error passing through two middlewares, or a middleware and the process handler). */\n private readonly captured = new WeakSet<object>();\n private readonly bound = new WeakSet<object>();\n private readonly pending = new Set<Promise<void>>();\n private readonly cleanups: Array<() => void> = [];\n private readonly options: ErrorOptions;\n private readonly frameOptions: FrameOptions;\n private readonly sampleRate: number;\n private readonly contextLines: number;\n private readonly pii: boolean;\n private readonly release: string | undefined;\n private readonly serverName: string | undefined;\n\n constructor(\n private readonly host: MonitorHost,\n options: ErrorOptions | false | undefined,\n ) {\n const o = options && typeof options === \"object\" ? options : {};\n this.options = o;\n const max = typeof o.maxBreadcrumbs === \"number\" && o.maxBreadcrumbs >= 0 ? Math.min(MAX_BREADCRUMBS, Math.floor(o.maxBreadcrumbs)) : MAX_BREADCRUMBS;\n this.global = new Scope(max, (crumb, scope) => this.record(crumb, undefined, scope));\n const entry = typeof process !== \"undefined\" ? process.argv?.[1] : undefined;\n this.frameOptions = { root: entry ? dirname(entry) : safeCwd(), inAppExclude: Array.isArray(o.inAppExclude) ? o.inAppExclude : undefined };\n this.sampleRate = typeof o.sampleRate === \"number\" && Number.isFinite(o.sampleRate) ? Math.min(1, Math.max(0, o.sampleRate)) : 1;\n this.contextLines = typeof o.contextLines === \"number\" && Number.isFinite(o.contextLines) ? Math.max(0, Math.floor(o.contextLines)) : 5;\n this.pii = o.sendDefaultPii === true;\n this.release = (typeof o.release === \"string\" && o.release.trim() ? o.release.trim() : host.appVersion)?.slice(0, 200);\n let serverName: string | undefined;\n try {\n serverName = typeof o.serverName === \"string\" && o.serverName ? o.serverName : os.hostname();\n } catch {\n serverName = undefined;\n }\n this.serverName = serverName?.slice(0, 200);\n if (options === false) return;\n const levels: ConsoleLevel[] = o.captureConsole === false ? [] : Array.isArray(o.captureConsole) ? o.captureConsole : [\"warn\", \"error\"];\n if (levels.length) this.cleanups.push(instrumentConsole(levels, (crumb, hint) => this.record(crumb, hint, this.current())));\n if (o.captureHttp !== false) {\n const own = originOf(host.apiUrl);\n this.cleanups.push(\n instrumentHttp(\n (crumb, hint, target) => this.record(crumb, hint, target instanceof Scope ? target : this.global),\n () => this.current(),\n (url) => !!own && originOf(url) === own,\n ),\n );\n }\n }\n\n // --- scopes --------------------------------------------------------------------------------\n\n /** The scope of the running request / `withScope()` callback, else the process-wide one. */\n current(): Scope {\n return this.als.getStore() ?? this.global;\n }\n\n withScope<T>(fn: (scope: Scope) => T): T {\n const scope = this.current().clone();\n return this.als.run(scope, () => fn(scope));\n }\n\n addBreadcrumb(crumb: Breadcrumb, hint?: BreadcrumbHint): void {\n this.record(crumb, hint, this.current());\n }\n\n /** Validates a breadcrumb, runs `beforeBreadcrumb` and adds it to `scope`. */\n private record(crumb: Breadcrumb, hint: BreadcrumbHint | undefined, scope: Scope): void {\n try {\n if (!crumb || typeof crumb !== \"object\") return;\n let c: Breadcrumb = {\n timestamp: typeof crumb.timestamp === \"number\" && Number.isFinite(crumb.timestamp) ? crumb.timestamp : Date.now() / 1000,\n ...(typeof crumb.type === \"string\" && crumb.type ? { type: crumb.type.slice(0, 40) } : {}),\n ...(typeof crumb.category === \"string\" && crumb.category ? { category: crumb.category.slice(0, 100) } : {}),\n ...(levelOf(crumb.level) ? { level: levelOf(crumb.level) } : {}),\n ...(typeof crumb.message === \"string\" ? { message: crumb.message.slice(0, 1000) } : crumb.message !== undefined ? { message: String(crumb.message).slice(0, 1000) } : {}),\n };\n const data = normalizeObject(crumb.data, 3);\n if (data) c.data = data;\n const hook = this.options.beforeBreadcrumb;\n if (typeof hook === \"function\") {\n let out: Breadcrumb | null | undefined = c;\n try {\n out = hook(c, hint);\n } catch {\n out = c;\n }\n if (out === null) return;\n if (out && typeof out === \"object\" && out !== c) c = { ...out, ...(out.data ? { data: normalizeObject(out.data, 3) } : {}) };\n }\n scope.pushBreadcrumb(c);\n } catch {\n // a breadcrumb must never break the app\n }\n }\n\n // --- capture -------------------------------------------------------------------------------\n\n captureException(error: unknown, context?: CaptureContext): string {\n // Integrations (Next.js, SvelteKit) say how they caught the error: `{ type: \"nextjs.onRequestError\", handled: false }`.\n const m = context?.mechanism;\n return this.capture({ error }, context, { type: m?.type ? String(m.type).slice(0, 60) : \"generic\", handled: m?.handled ?? true, level: \"error\", source: \"manual\" });\n }\n\n captureMessage(message: string, level?: SeverityLevel | CaptureContext, context?: CaptureContext): string {\n const ctx = level && typeof level === \"object\" ? level : context;\n const lvl = typeof level === \"string\" ? levelOf(level) : undefined;\n return this.capture({ message: typeof message === \"string\" ? message : String(message) }, ctx, { type: \"generic\", handled: true, level: lvl ?? \"info\", source: \"manual\" });\n }\n\n /** An error caught by an automatic hook (process handler, middleware); skipped when already reported. */\n captureAuto(error: unknown, kind: { mechanism: string; level?: SeverityLevel; request?: unknown; fallbackType?: string }): string | undefined {\n if (error && typeof error === \"object\") {\n if (this.captured.has(error)) return undefined;\n }\n return this.capture({ error }, kind.request ? { request: kind.request } : undefined, {\n type: kind.mechanism,\n handled: false,\n level: kind.level ?? \"error\",\n source: kind.mechanism,\n fallbackType: kind.fallbackType,\n });\n }\n\n private capture(input: { error: unknown } | { message: string }, context: CaptureContext | undefined, mech: Mech): string {\n const eventId = newEventId();\n try {\n if (!this.host.accepting()) {\n this.host.report(`${\"error\" in input ? \"captureException\" : \"captureMessage\"}() was called after shutdown(); the event was dropped`, undefined, \"closed\");\n return eventId;\n }\n const ctx: CaptureContext = context && typeof context === \"object\" && !Array.isArray(context) ? context : {};\n const scope = (ctx.request && typeof ctx.request === \"object\" ? this.requestScopes.get(ctx.request) : undefined) ?? this.current();\n const data = scope.data();\n const values: ExceptionValue[] | undefined = \"error\" in input ? exceptionChain(input.error, { type: mech.type, handled: mech.handled }, this.frameOptions, mech.fallbackType) : undefined;\n const main = values?.[values.length - 1];\n if (this.ignored(main?.type, main ? main.value : (input as { message: string }).message)) return eventId;\n if (this.sampleRate < 1 && Math.random() >= this.sampleRate) return eventId;\n if (\"error\" in input && input.error && typeof input.error === \"object\") this.captured.add(input.error);\n\n const requestSource = ctx.request ?? data.request;\n const req = requestSource ? requestDataOf(requestSource, this.pii) : undefined;\n const user: User = { ...(data.user ?? {}), ...(ctx.user && typeof ctx.user === \"object\" ? ctx.user : {}) };\n if (idString(ctx.userId)) user.id = idString(ctx.userId);\n if (req?.ip && !user.ip_address) user.ip_address = req.ip;\n const tags = new Scope().setTags(data.tags).setTags(ctx.tags ?? {}).data().tags;\n const extra = { ...data.extra, ...(ctx.extra && typeof ctx.extra === \"object\" ? ctx.extra : {}) };\n const contexts: Record<string, Record<string, unknown>> = { ...processContexts(), ...data.contexts };\n for (const [k, v] of Object.entries(ctx.contexts ?? {})) {\n if (v && typeof v === \"object\") contexts[k] = v;\n else delete contexts[k];\n }\n const fingerprint = Array.isArray(ctx.fingerprint) ? ctx.fingerprint.map(String) : data.fingerprint;\n const transaction = (typeof ctx.transaction === \"string\" && ctx.transaction ? ctx.transaction.slice(0, 200) : undefined) ?? data.transaction ?? transactionOf(requestSource);\n const level = levelOf(ctx.level) ?? data.level ?? mech.level;\n const event: ErrorEvent = {\n event_id: eventId,\n timestamp: Date.now() / 1000,\n platform: \"node\",\n level,\n ...(this.release ? { release: this.release } : {}),\n environment: this.host.environment,\n ...(this.serverName ? { server_name: this.serverName } : {}),\n ...(transaction ? { transaction } : {}),\n ...(\"message\" in input ? { logentry: { formatted: input.message.slice(0, 8000) } } : {}),\n ...(values ? { exception: { values } } : {}),\n ...(data.breadcrumbs.length ? { breadcrumbs: { values: data.breadcrumbs } } : {}),\n contexts,\n ...(Object.keys(tags).length ? { tags } : {}),\n extra,\n user,\n ...(fingerprint?.length ? { fingerprint } : {}),\n ...(req ? { request: req.request } : {}),\n sdk: { ...this.host.sdk },\n };\n this.scrub(event);\n const properties: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(ctx)) if (!KNOWN_CONTEXT_KEYS.has(k)) properties[k] = v;\n const ids = { anonymousId: idString(ctx.anonymousId), accountId: idString(ctx.accountId) };\n const hint: EventHint = { originalException: \"error\" in input ? input.error : input.message, event_id: eventId };\n const finish = () => this.finish(event, hint, mech.source, properties, ids);\n const frames = values?.flatMap((v) => v.stacktrace?.frames ?? []) ?? [];\n if (this.contextLines > 0 && wantsContext(frames)) this.track(addContextLines(frames, this.contextLines).then(finish, finish));\n else {\n const done = finish();\n if (done) this.track(done);\n }\n } catch (e) {\n this.host.report(`${\"error\" in input ? \"captureException\" : \"captureMessage\"}() failed: ${e instanceof Error ? e.message : String(e)}`, e);\n }\n return eventId;\n }\n\n private ignored(type: string | undefined, message: string | undefined): boolean {\n const patterns = this.options.ignoreErrors;\n if (!Array.isArray(patterns) || patterns.length === 0) return false;\n const candidates = [type && message !== undefined ? `${type}: ${message}` : undefined, message].filter((s): s is string => typeof s === \"string\");\n return patterns.some((p) =>\n candidates.some((s) => {\n if (typeof p === \"string\") return !!p && s.includes(p);\n if (!(p instanceof RegExp)) return false;\n p.lastIndex = 0;\n return p.test(s);\n }),\n );\n }\n\n /** Makes user-supplied parts of an event JSON-safe and credential-free (again after `beforeSend`). */\n private scrub(event: ErrorEvent): void {\n event.extra = normalizeObject(event.extra, 4) ?? {};\n const contexts: Record<string, Record<string, unknown>> = {};\n for (const [k, v] of Object.entries(event.contexts ?? {}).slice(0, 50)) {\n const c = normalizeObject(v, 4);\n if (c) contexts[k] = c;\n }\n event.contexts = contexts;\n const user = normalizeObject(event.user, 3);\n if (user && !this.pii && user.ip_address === \"{{auto}}\") delete user.ip_address;\n if (user && Object.keys(user).length) event.user = user as User;\n else delete event.user;\n if (!Object.keys(event.extra).length) delete event.extra;\n if (event.tags) {\n const tags: Record<string, string> = {};\n for (const [k, v] of Object.entries(event.tags).slice(0, MAX_TAGS)) if (v !== null && v !== undefined) tags[String(k).slice(0, 32)] = String(v).slice(0, 200);\n event.tags = tags;\n }\n if (event.request) event.request = scrubRequest(event.request, this.pii);\n if (event.breadcrumbs?.values) event.breadcrumbs = { values: event.breadcrumbs.values.slice(-MAX_BREADCRUMBS).map((b) => (b.data ? { ...b, data: normalizeObject(b.data, 3) } : b)) };\n }\n\n /** `beforeSend`, then the message: properties ≤ 8 KB, detail ≤ 64 KB. May return a promise (async `beforeSend`). */\n private finish(event: ErrorEvent, hint: EventHint, source: string, properties: Record<string, unknown>, ids: { anonymousId?: string; accountId?: string }): Promise<void> | void {\n const send = (result: unknown) => {\n if (result === null) return;\n const final = result && typeof result === \"object\" ? (result as ErrorEvent) : event;\n this.scrub(final); // the hook may have added credentials\n this.send(final, source, properties, ids);\n };\n const hook = this.options.beforeSend;\n if (typeof hook !== \"function\") return this.send(event, source, properties, ids);\n let result: unknown;\n try {\n result = hook(event, hint);\n } catch {\n return send(event);\n }\n if (result && typeof (result as Promise<unknown>).then === \"function\") return (result as Promise<unknown>).then(send, () => send(event));\n return send(result);\n }\n\n private send(event: ErrorEvent, source: string, extraProperties: Record<string, unknown>, ids: { anonymousId?: string; accountId?: string }): void {\n try {\n const properties = propertiesOf(event, source, this.release, extraProperties);\n const userId = idString(event.user?.id);\n const timestamp = new Date(typeof event.timestamp === \"number\" && Number.isFinite(event.timestamp) ? event.timestamp * 1000 : Date.now()).toISOString();\n let safe: ErrorEvent;\n try {\n safe = JSON.parse(JSON.stringify(event)) as ErrorEvent;\n } catch {\n safe = normalize(event, 12) as ErrorEvent; // beforeSend added something cyclic or a BigInt\n }\n const detail = trimDetail(safe);\n const message: Record<string, unknown> = {\n type: \"exception\",\n messageId: event.event_id,\n timestamp,\n ...(userId ? { userId } : {}),\n ...(ids.anonymousId ? { anonymousId: ids.anonymousId } : {}),\n ...(ids.accountId ? { accountId: ids.accountId } : {}),\n ...(this.release ? { appVersion: this.release } : {}),\n properties,\n ...(detail ? { detail } : {}),\n };\n this.host.push(message);\n } catch (e) {\n this.host.report(`Could not build the exception event: ${e instanceof Error ? e.message : String(e)}`, e);\n }\n }\n\n private track(p: Promise<void>): void {\n const tracked: Promise<void> = p\n .catch((e) => this.host.report(`Could not build the exception event: ${e instanceof Error ? e.message : String(e)}`, e))\n .finally(() => {\n this.pending.delete(tracked);\n });\n this.pending.add(tracked);\n }\n\n /** Resolves once every event being prepared (source lines, async `beforeSend`) is queued; `null` when none is. */\n idle(): Promise<void> | null {\n if (this.pending.size === 0) return null;\n return Promise.all([...this.pending]).then(() => this.idle() ?? undefined);\n }\n\n // --- process and framework hooks ----------------------------------------------------------\n\n installProcessHandlers(options?: ProcessHandlerOptions): () => void {\n try {\n const off = installProcessHandlers(\n {\n capture: (error, kind) => void this.captureAuto(error, { mechanism: kind.mechanism, level: kind.level, fallbackType: kind.fallbackType }),\n flush: () => this.host.flush(),\n },\n options,\n );\n this.cleanups.push(off);\n return off;\n } catch (e) {\n this.host.report(`installProcessHandlers() failed: ${e instanceof Error ? e.message : String(e)}`, e);\n return () => {};\n }\n }\n\n /** Runs `fn` in a new scope for `request`, with the request's events bound to it (body parsing, `finish`). */\n private runRequest<T>(request: unknown, emitters: unknown[], fn: () => T): T {\n if (!request || typeof request !== \"object\") return fn();\n const scope = this.current().clone();\n scope.request = request;\n scope.clearBreadcrumbs();\n this.requestScopes.set(request, scope);\n return this.als.run(scope, () => {\n for (const e of emitters) this.bindEmitter(e);\n return fn();\n });\n }\n\n /**\n * Listeners of a request's / response's events (`data`, `end`, `finish`) run in the async context\n * of the server's socket, not of the middleware: bind `emit` to the request scope, as domains did.\n */\n private bindEmitter(emitter: unknown): void {\n if (!emitter || typeof emitter !== \"object\" || this.bound.has(emitter)) return;\n const e = emitter as { emit?: unknown };\n if (typeof e.emit !== \"function\") return;\n try {\n e.emit = AsyncResource.bind(e.emit as (...args: unknown[]) => boolean, \"GuidelyRequest\", emitter);\n this.bound.add(emitter);\n } catch {\n // a frozen emitter: breadcrumbs after body parsing go to the process-wide scope\n }\n }\n\n private captureRequestError(error: unknown, request: unknown, mechanism: string, options: MiddlewareOptions | undefined): void {\n try {\n const should = typeof options?.shouldHandleError === \"function\" ? options.shouldHandleError : defaultShouldHandle;\n if (should(error)) this.captureAuto(error, { mechanism, request });\n } catch {\n // never break the app's error handling\n }\n }\n\n expressRequestHandler() {\n return (req: unknown, res: unknown, next: Next): void => this.runRequest(req, [req, res], () => next());\n }\n\n expressErrorHandler(options?: MiddlewareOptions) {\n return (error: unknown, req: unknown, _res: unknown, next: Next): void => {\n this.captureRequestError(error, req, \"express\", options);\n next(error);\n };\n }\n\n fastifyErrorHook(options?: MiddlewareOptions) {\n return (request: unknown, _reply: unknown, error: unknown, done?: () => void): void => {\n this.captureRequestError(error, request, \"fastify\", options);\n done?.();\n };\n }\n\n fastifyPlugin(options?: MiddlewareOptions) {\n const plugin = (fastify: FastifyLike, _opts: unknown, done?: (error?: Error) => void): void => {\n fastify.addHook(\"onRequest\", (request: { raw?: unknown }, reply: { raw?: unknown }, next: Next) => this.runRequest(request, [request?.raw, reply?.raw], () => next()));\n // Body parsing ran outside the request's async context: re-enter it for the handler.\n fastify.addHook(\"preHandler\", (request: object, _reply: unknown, next: Next) => {\n const scope = request && typeof request === \"object\" ? this.requestScopes.get(request) : undefined;\n if (scope) this.als.run(scope, () => next());\n else next();\n });\n fastify.addHook(\"onError\", this.fastifyErrorHook(options));\n done?.();\n };\n // fastify-plugin's markers: apply the hooks to the parent instance, not an encapsulated child.\n Object.assign(plugin, { [Symbol.for(\"skip-override\")]: true, [Symbol.for(\"fastify.display-name\")]: \"@guidelytech/node\" });\n return plugin;\n }\n\n koaMiddleware(options?: MiddlewareOptions) {\n return (ctx: { req?: unknown; res?: unknown }, next: () => Promise<unknown>): Promise<unknown> =>\n this.runRequest(ctx, [ctx?.req, ctx?.res], async () => {\n try {\n return await next();\n } catch (error) {\n this.captureRequestError(error, ctx, \"koa\", options);\n throw error;\n }\n });\n }\n\n /** Stops the automatic breadcrumbs and process handlers. */\n close(): void {\n for (const off of this.cleanups.splice(0)) {\n try {\n off();\n } catch {\n // keep closing the rest\n }\n }\n }\n}\n\nfunction originOf(url: string): string | undefined {\n try {\n return new URL(url).origin;\n } catch {\n return undefined;\n }\n}\n\nfunction safeCwd(): string | undefined {\n try {\n return process.cwd();\n } catch {\n return undefined;\n }\n}\n","import * as dc from \"node:diagnostics_channel\";\nimport { format } from \"node:util\";\nimport { normalize, stripQuery } from \"./normalize\";\nimport type { Breadcrumb, BreadcrumbHint, ConsoleLevel } from \"./types\";\n\n/**\n * Automatic breadcrumbs: console calls and outgoing HTTP requests. Each console method is wrapped\n * once per process however many clients listen, and restored when the last one stops (unless\n * something else wrapped it since, in which case our wrapper stays in place, inert). HTTP requests\n * are observed through `diagnostics_channel` (`http.client.*` for `http`/`https`, `undici:request:*`\n * for `fetch` and undici), so nothing is patched.\n */\n\nexport type RecordCrumb = (crumb: Breadcrumb, hint: BreadcrumbHint) => void;\n\nconst CONSOLE_LEVEL: Record<ConsoleLevel, Breadcrumb[\"level\"]> = { debug: \"debug\", info: \"info\", log: \"log\", warn: \"warning\", error: \"error\" };\n\ninterface Wrapped {\n original: (...args: unknown[]) => void;\n wrapper: (...args: unknown[]) => void;\n listeners: Set<RecordCrumb>;\n}\n\nconst wrapped = new Map<ConsoleLevel, Wrapped>();\nlet inConsole = false;\n\n/** Records `console[level]` calls as breadcrumbs until the returned function is called. */\nexport function instrumentConsole(levels: ConsoleLevel[], record: RecordCrumb): () => void {\n const target = console as unknown as Record<string, (...args: unknown[]) => void>;\n const mine: ConsoleLevel[] = [];\n for (const level of new Set(levels)) {\n if (typeof target[level] !== \"function\") continue;\n let w = wrapped.get(level);\n if (w && w.listeners.size === 0 && target[level] !== w.wrapper) {\n wrapped.delete(level); // replaced since (a test spy, another logger): wrap what is there now\n w = undefined;\n }\n if (!w) {\n const original = target[level]!;\n const listeners = new Set<RecordCrumb>();\n const wrapper = function (this: unknown, ...args: unknown[]) {\n if (!inConsole && listeners.size > 0) {\n inConsole = true; // a listener that logs must not record itself\n try {\n const message = format(...args);\n // The SDK's own warnings (`[guidely-node] …`) are not the app's.\n if (!message.startsWith(\"[guidely-node]\")) {\n const crumb: Breadcrumb = { category: \"console\", level: CONSOLE_LEVEL[level], message: message.slice(0, 1000), data: { arguments: normalize(args, 3), logger: \"console\" } };\n for (const l of listeners) l({ ...crumb }, { input: args, level });\n }\n } catch {\n // never break logging\n } finally {\n inConsole = false;\n }\n }\n return original.apply(this, args);\n };\n w = { original, wrapper, listeners };\n wrapped.set(level, w);\n target[level] = wrapper;\n }\n w.listeners.add(record);\n mine.push(level);\n }\n return () => {\n for (const level of mine) {\n const w = wrapped.get(level);\n if (!w) continue;\n w.listeners.delete(record);\n if (w.listeners.size === 0 && target[level] === w.wrapper) {\n target[level] = w.original;\n wrapped.delete(level);\n }\n }\n };\n}\n\ntype Handler = (message: unknown, name: string | symbol) => void;\n\nfunction subscribe(name: string, handler: Handler): () => void {\n try {\n if (typeof dc.subscribe === \"function\") {\n dc.subscribe(name, handler);\n return () => dc.unsubscribe(name, handler);\n }\n const ch = dc.channel(name); // Node < 18.7\n ch.subscribe(handler);\n return () => ch.unsubscribe(handler);\n } catch {\n return () => {};\n }\n}\n\ninterface Started {\n method: string;\n url: string;\n start: number;\n /** Where the breadcrumb goes: the scope that was current when the request started. */\n target: unknown;\n}\n\nconst levelOf = (status: number | undefined): Breadcrumb[\"level\"] => (status === undefined || status >= 500 ? \"error\" : status >= 400 ? \"warning\" : \"info\");\n\n/**\n * Records outgoing requests: `{ type: \"http\", category: \"http\", data: { method, url, status_code,\n * duration_ms } }` with the query string left out. `ignore(url)` skips requests (Guidely's own\n * API). `current()` names the scope a request belongs to, read when it starts, because responses\n * arrive outside the request's async context.\n */\nexport function instrumentHttp(record: (crumb: Breadcrumb, hint: BreadcrumbHint, target: unknown) => void, current: () => unknown, ignore: (url: string) => boolean): () => void {\n const started = new WeakMap<object, Started>();\n const begin = (request: object, method: unknown, url: string) => {\n if (ignore(url)) return;\n started.set(request, { method: typeof method === \"string\" ? method.toUpperCase() : \"GET\", url: stripQuery(url), start: Date.now(), target: current() });\n };\n const end = (request: object, response: unknown, status: number | undefined, error?: unknown) => {\n const s = started.get(request);\n if (!s) return;\n started.delete(request);\n const data: Record<string, unknown> = { method: s.method, url: s.url, ...(status !== undefined ? { status_code: status } : {}), duration_ms: Date.now() - s.start };\n if (error) data.error = error instanceof Error ? error.message.slice(0, 200) : String(error).slice(0, 200);\n try {\n record({ type: \"http\", category: \"http\", level: levelOf(status), data }, { request, response }, s.target);\n } catch {\n // never break the app's request\n }\n };\n const statusOf = (response: unknown) => {\n const code = (response as { statusCode?: unknown } | undefined)?.statusCode;\n return typeof code === \"number\" ? code : undefined;\n };\n const offs = [\n // http / https\n subscribe(\"http.client.request.start\", (m) => {\n const req = (m as { request?: { method?: string; protocol?: string; host?: string; path?: string; getHeader?: (n: string) => unknown } }).request;\n if (!req || typeof req !== \"object\") return;\n const host = typeof req.getHeader === \"function\" ? req.getHeader(\"host\") : undefined;\n begin(req, req.method, `${req.protocol ?? \"http:\"}//${typeof host === \"string\" ? host : (req.host ?? \"\")}${req.path ?? \"/\"}`);\n }),\n subscribe(\"http.client.response.finish\", (m) => {\n const { request, response } = m as { request?: object; response?: unknown };\n if (request) end(request, response, statusOf(response));\n }),\n subscribe(\"http.client.request.error\", (m) => {\n const { request, error } = m as { request?: object; error?: unknown };\n if (request) end(request, undefined, undefined, error);\n }),\n // fetch / undici\n subscribe(\"undici:request:create\", (m) => {\n const req = (m as { request?: { method?: string; origin?: unknown; path?: string } }).request;\n if (!req || typeof req !== \"object\") return;\n const origin = String(req.origin ?? \"\").replace(/\\/+$/, \"\");\n begin(req, req.method, `${origin}${req.path ?? \"/\"}`);\n }),\n subscribe(\"undici:request:headers\", (m) => {\n const { request, response } = m as { request?: object; response?: unknown };\n if (request) end(request, response, statusOf(response));\n }),\n subscribe(\"undici:request:error\", (m) => {\n const { request, error } = m as { request?: object; error?: unknown };\n if (request) end(request, undefined, undefined, error);\n }),\n ];\n return () => offs.forEach((off) => off());\n}\n","import { readFile, stat } from \"node:fs/promises\";\nimport { isAbsolute } from \"node:path\";\nimport type { StackFrame } from \"./types\";\n\n/**\n * Source lines around in-app frames (Sentry's ContextLines): `pre_context`, `context_line` and\n * `post_context`, read from the files on disk. Bounded: files over 1 MB are skipped, at most 20\n * files are cached (process-wide, least recently used first out), at most 50 frames per event get\n * lines, lines are cut to 200 characters. Unreadable files are remembered as such.\n */\n\nconst MAX_FILE_BYTES = 1_000_000;\nconst MAX_CACHED_FILES = 20;\nconst MAX_FRAMES = 50;\nconst MAX_LINE = 200;\nexport const MAX_CONTEXT_LINES = 10;\n\nconst cache = new Map<string, string[] | null>();\nconst loading = new Map<string, Promise<string[] | null>>();\n\n/** Forgets cached files (tests). */\nexport function clearContextLineCache(): void {\n cache.clear();\n}\n\nfunction remember(file: string, lines: string[] | null): void {\n cache.delete(file);\n cache.set(file, lines);\n while (cache.size > MAX_CACHED_FILES) cache.delete(cache.keys().next().value as string);\n}\n\nfunction linesOf(file: string): Promise<string[] | null> {\n if (cache.has(file)) {\n const lines = cache.get(file)!;\n remember(file, lines); // most recently used\n return Promise.resolve(lines);\n }\n let p = loading.get(file);\n if (!p) {\n p = (async () => {\n try {\n const s = await stat(file);\n if (!s.isFile() || s.size > MAX_FILE_BYTES) return null;\n return (await readFile(file, \"utf8\")).split(/\\r?\\n/);\n } catch {\n return null;\n }\n })().then((lines) => {\n loading.delete(file);\n remember(file, lines);\n return lines;\n });\n loading.set(file, p);\n }\n return p;\n}\n\n/** A line cut to 200 characters, keeping the part around `colno` (Sentry's `snipLine`). */\nfunction snip(line: string, colno?: number): string {\n if (line.length <= MAX_LINE) return line;\n const at = colno ? Math.max(0, colno - 1) : 0;\n const start = Math.max(0, Math.min(at - 60, line.length - MAX_LINE));\n const end = Math.min(line.length, start + MAX_LINE);\n return `${start > 0 ? \"{snip} \" : \"\"}${line.slice(start, end)}${end < line.length ? \" {snip}\" : \"\"}`;\n}\n\n/** Whether any frame would get context lines (so capture can stay synchronous when none would). */\nexport function wantsContext(frames: StackFrame[]): boolean {\n return frames.some((f) => f.in_app && f.lineno && f.abs_path && isAbsolute(f.abs_path));\n}\n\n/** Adds up to `n` lines before and after each in-app frame's line (innermost frames first). */\nexport async function addContextLines(frames: StackFrame[], n: number): Promise<void> {\n const count = Math.min(Math.max(0, Math.floor(n)), MAX_CONTEXT_LINES);\n if (count === 0) return;\n const targets = frames.filter((f) => f.in_app && f.lineno && f.abs_path && isAbsolute(f.abs_path)).slice(-MAX_FRAMES);\n await Promise.all(\n targets.map(async (f) => {\n const lines = await linesOf(f.abs_path!);\n const i = f.lineno! - 1;\n if (!lines || i < 0 || i >= lines.length) return;\n f.pre_context = lines.slice(Math.max(0, i - count), i).map((l) => snip(l));\n f.context_line = snip(lines[i]!, f.colno);\n f.post_context = lines.slice(i + 1, i + 1 + count).map((l) => snip(l));\n }),\n );\n}\n","import { inspect } from \"node:util\";\n\n/** The parts of `process` the handlers use (tests pass a fake). */\nexport interface ProcessLike {\n on(event: string, listener: (...args: any[]) => void): unknown;\n removeListener(event: string, listener: (...args: any[]) => void): unknown;\n listeners(event: string): Array<(...args: any[]) => void>;\n exit(code?: number): void;\n exitCode?: number | string | null;\n execArgv?: string[];\n env?: Record<string, string | undefined>;\n}\n\n/** Node's `--unhandled-rejections` modes (`warn-with-error-code` warns and sets the exit code). */\nexport type UnhandledRejectionMode = \"throw\" | \"strict\" | \"warn\" | \"warn-with-error-code\" | \"none\";\n\nexport interface ProcessHandlerOptions {\n /**\n * After an uncaught exception (or a rejection Node would have crashed on): print it, flush, then\n * `exit(1)`, as Node does (default true). It never exits while the app has its own\n * `uncaughtException` listeners, since Node would not either. `false` keeps the process running,\n * like any `uncaughtException` listener does, in whatever state the error left it.\n */\n exitOnUncaught?: boolean;\n /** How unhandled rejections behave (default: Node's `--unhandled-rejections` flag, else `throw`). */\n unhandledRejection?: UnhandledRejectionMode;\n /** Most time spent sending before exiting (default 2000 ms). */\n flushTimeoutMs?: number;\n /** The process to listen on (default: `process`). */\n process?: ProcessLike;\n}\n\n/** What the handlers need from the client. */\nexport interface ProcessHandlerHost {\n capture(error: unknown, kind: { mechanism: string; level: \"fatal\" | \"error\"; fallbackType?: string }): void;\n flush(): Promise<void>;\n}\n\nconst OURS = Symbol.for(\"guidely.processHandler\");\nconst isOurs = (l: unknown) => typeof l === \"function\" && (l as unknown as Record<symbol, unknown>)[OURS] === true;\n\n/** `--unhandled-rejections=<mode>` from the command line or `NODE_OPTIONS`. */\nfunction nodeMode(proc: ProcessLike): UnhandledRejectionMode {\n const args = [...(proc.execArgv ?? []), ...(proc.env?.NODE_OPTIONS ?? \"\").split(/\\s+/)];\n for (const a of args) {\n const m = /^--unhandled-rejections=([\\w-]+)$/.exec(a);\n if (m && [\"throw\", \"strict\", \"warn\", \"warn-with-error-code\", \"none\"].includes(m[1]!)) return m[1] as UnhandledRejectionMode;\n }\n return \"throw\";\n}\n\n/**\n * Listens for `uncaughtException` (level `fatal`, mechanism `uncaughtException`) and\n * `unhandledRejection` (mechanism `unhandledRejection`; `fatal` when it ends the process, else\n * `error`). Returns a function that removes the listeners.\n *\n * Node semantics are kept: in the default `throw` mode a rejection with no other\n * `unhandledRejection` listener ends the process like an uncaught exception (print, flush,\n * `exit(1)`); `strict` does even with one; both only when the app has no `uncaughtException`\n * listener of its own. `warn` prints a warning; `none` stays silent.\n */\nexport function installProcessHandlers(host: ProcessHandlerHost, o: ProcessHandlerOptions = {}): () => void {\n const proc: ProcessLike = o.process ?? (process as unknown as ProcessLike);\n const exitOnUncaught = o.exitOnUncaught !== false;\n const mode = o.unhandledRejection ?? nodeMode(proc);\n const flushTimeoutMs = typeof o.flushTimeoutMs === \"number\" && o.flushTimeoutMs >= 0 ? o.flushTimeoutMs : 2000;\n let exiting = false;\n\n const others = (event: string) => proc.listeners(event).filter((l) => !isOurs(l)).length;\n\n const exit = (error: unknown, prefix: string) => {\n if (exiting) return;\n exiting = true;\n try {\n console.error(`${prefix}${inspect(error)}`);\n } catch {\n // stderr closed\n }\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timeout = new Promise<void>((resolve) => {\n timer = setTimeout(resolve, flushTimeoutMs);\n });\n void Promise.race([host.flush().catch(() => {}), timeout]).then(() => {\n clearTimeout(timer);\n proc.exitCode = 1;\n proc.exit(1);\n });\n };\n\n const onUncaught = (error: unknown) => {\n const crash = exitOnUncaught && others(\"uncaughtException\") === 0;\n host.capture(error, { mechanism: \"uncaughtException\", level: \"fatal\" });\n if (crash) exit(error, \"Uncaught \");\n };\n\n const onRejection = (reason: unknown) => {\n // Node raises the rejection as an uncaught exception (`strict` always, `throw` when nothing else\n // listens for rejections); it only ends the process when nothing listens for those either.\n const raised = mode === \"strict\" || (mode === \"throw\" && others(\"unhandledRejection\") === 0);\n const crash = exitOnUncaught && raised && others(\"uncaughtException\") === 0;\n host.capture(reason, { mechanism: \"unhandledRejection\", level: crash ? \"fatal\" : \"error\", fallbackType: \"UnhandledRejection\" });\n if (crash) return exit(reason, \"Unhandled promise rejection: \");\n if (mode === \"none\" || others(\"unhandledRejection\") > 0) return;\n if (mode === \"warn-with-error-code\") proc.exitCode = 1;\n try {\n console.warn(`Unhandled promise rejection: ${inspect(reason)}`);\n } catch {\n // stderr closed\n }\n };\n\n for (const l of [onUncaught, onRejection]) (l as unknown as Record<symbol, unknown>)[OURS] = true;\n proc.on(\"uncaughtException\", onUncaught);\n proc.on(\"unhandledRejection\", onRejection);\n let installed = true;\n return () => {\n if (!installed) return;\n installed = false;\n proc.removeListener(\"uncaughtException\", onUncaught);\n proc.removeListener(\"unhandledRejection\", onRejection);\n };\n}\n","import { IP_HEADER, scrubQuery, SENSITIVE_HEADER } from \"./normalize\";\nimport type { RequestData } from \"./types\";\n\n/**\n * Request data from whatever web framework is in use, typed structurally so the SDK has no framework\n * dependency: Node's `IncomingMessage`, Express `req`, Fastify `request`, Koa `ctx` (or `ctx.request`),\n * or an already Sentry-shaped `{ method, url, headers, query_string }`.\n */\nexport interface RequestLike {\n method?: string;\n url?: string;\n originalUrl?: string;\n headers?: Record<string, string | string[] | number | undefined>;\n protocol?: string;\n hostname?: string;\n host?: string;\n ip?: string;\n query_string?: unknown;\n socket?: { remoteAddress?: string; encrypted?: boolean };\n /** Express: the matched route (`/users/:id`), under `baseUrl`. */\n route?: { path?: unknown };\n baseUrl?: string;\n /** Fastify 4.10+: the route's pattern. */\n routeOptions?: { url?: string };\n /** Fastify < 4.10. */\n routerPath?: string;\n /** Koa with @koa/router. */\n _matchedRoute?: unknown;\n /** Koa `ctx.request` / `ctx.req`. */\n request?: unknown;\n req?: unknown;\n}\n\nconst str = (v: unknown, max = 2000): string | undefined => (typeof v === \"string\" && v ? v.slice(0, max) : undefined);\n\n/** Koa passes `ctx`: its request data is on `ctx` (delegated) and the Node request on `ctx.req`. */\nfunction nodeRequestOf(r: RequestLike): RequestLike {\n const req = r.req as RequestLike | undefined;\n return req && typeof req === \"object\" ? req : r;\n}\n\nfunction header(headers: RequestLike[\"headers\"], name: string): string | undefined {\n const v = headers?.[name];\n return Array.isArray(v) ? v[0] : typeof v === \"string\" ? v : typeof v === \"number\" ? String(v) : undefined;\n}\n\n/** `METHOD /route` from the matched route, when the framework exposes one. */\nexport function transactionOf(input: unknown): string | undefined {\n if (!input || typeof input !== \"object\") return undefined;\n const r = input as RequestLike;\n const method = str(r.method, 16)?.toUpperCase();\n const routePath = typeof r.route?.path === \"string\" ? r.route.path : undefined;\n const route = str(r.routeOptions?.url) ?? str(r.routerPath) ?? str(r._matchedRoute) ?? (routePath !== undefined ? `${r.baseUrl ?? \"\"}${routePath}` || \"/\" : undefined);\n return method && route ? `${method} ${route}`.slice(0, 200) : undefined;\n}\n\n/**\n * Sentry `request` data: method, origin + path (the query string apart, with sensitive values\n * `[Filtered]`), headers without cookies, credentials or (unless `sendDefaultPii`) client\n * addresses, plus the client IP when `sendDefaultPii` is on.\n */\nexport function requestDataOf(input: unknown, sendDefaultPii: boolean): { request: RequestData; ip?: string } | undefined {\n if (!input || typeof input !== \"object\") return undefined;\n const r = input as RequestLike;\n const node = nodeRequestOf(r);\n const rawHeaders = (r.headers && typeof r.headers === \"object\" ? r.headers : node.headers) ?? {};\n const headers: Record<string, string> = {};\n let n = 0;\n for (const [name, value] of Object.entries(rawHeaders)) {\n if (n >= 50) break;\n if (value === undefined || SENSITIVE_HEADER.test(name) || (!sendDefaultPii && IP_HEADER.test(name))) continue;\n headers[name.toLowerCase()] = (Array.isArray(value) ? value.join(\", \") : String(value)).slice(0, 1000);\n n++;\n }\n const raw = str(r.originalUrl) ?? str(node.originalUrl) ?? str(r.url) ?? str(node.url) ?? \"\";\n let url = raw;\n let query: string | undefined = typeof r.query_string === \"string\" ? r.query_string : undefined;\n const q = raw.indexOf(\"?\");\n if (q >= 0) {\n query = raw.slice(q + 1).replace(/#.*$/, \"\");\n url = raw.slice(0, q);\n }\n url = url.replace(/#.*$/, \"\");\n if (url && !/^[a-z][a-z0-9+.-]*:\\/\\//i.test(url)) {\n const host = header(rawHeaders, \"host\") ?? str(r.host) ?? str(r.hostname);\n const protocol = (str(r.protocol) ?? (node.socket?.encrypted ? \"https\" : \"http\")).replace(/:$/, \"\");\n if (host) url = `${protocol}://${host}${url.startsWith(\"/\") ? \"\" : \"/\"}${url}`;\n }\n const request: RequestData = {\n ...(str(r.method, 16) ? { method: str(r.method, 16)!.toUpperCase() } : {}),\n ...(url ? { url: url.slice(0, 2000) } : {}),\n ...(query ? { query_string: scrubQuery(query) } : {}),\n headers,\n };\n if (!sendDefaultPii) return { request };\n const forwarded = header(rawHeaders, \"x-forwarded-for\")?.split(\",\")[0]?.trim();\n const ip = str(r.ip, 64) ?? str(forwarded, 64) ?? str(node.socket?.remoteAddress, 64);\n if (ip) request.env = { REMOTE_ADDR: ip };\n return { request, ...(ip ? { ip } : {}) };\n}\n\n/** Re-scrubs request data a `beforeSend` hook may have edited. */\nexport function scrubRequest(request: RequestData | undefined, sendDefaultPii: boolean): RequestData | undefined {\n if (!request || typeof request !== \"object\") return undefined;\n const headers: Record<string, string> = {};\n for (const [k, v] of Object.entries(request.headers ?? {})) if (!SENSITIVE_HEADER.test(k) && (sendDefaultPii || !IP_HEADER.test(k))) headers[k] = String(v).slice(0, 1000);\n return {\n ...request,\n ...(typeof request.query_string === \"string\" ? { query_string: scrubQuery(request.query_string) } : {}),\n ...(typeof request.url === \"string\" && request.url.includes(\"?\") ? { url: `${request.url.split(\"?\")[0]}?${scrubQuery(request.url.split(\"?\").slice(1).join(\"?\"))}` } : {}),\n headers,\n };\n}\n","import type { Breadcrumb, SeverityLevel, User } from \"./types\";\n\nexport const MAX_BREADCRUMBS = 100;\nexport const MAX_TAGS = 50;\n\n/**\n * Data applied to every error captured while the scope is current: tags, extras, contexts, the user\n * and the last breadcrumbs. The client has one process-wide scope; `withScope()` (and the framework\n * middlewares, once per request) run code with a copy of it, so concurrent requests never mix.\n */\nexport class Scope {\n private tags: Record<string, string> = {};\n private extra: Record<string, unknown> = {};\n private contexts: Record<string, Record<string, unknown>> = {};\n private user: User | null = null;\n private level: SeverityLevel | undefined;\n private fingerprint: string[] | undefined;\n private transaction: string | undefined;\n private crumbs: Breadcrumb[] = [];\n /** @internal The framework request this scope was opened for (read when an error is captured). */\n request: unknown;\n\n /** @internal `max`: breadcrumbs kept; `hook`: the client's breadcrumb pipeline (`beforeBreadcrumb`). */\n constructor(\n private readonly max = MAX_BREADCRUMBS,\n private readonly hook?: (crumb: Breadcrumb, scope: Scope) => void,\n ) {}\n\n /** A tag (searchable, ≤ 50 per event; keys ≤ 32 and values ≤ 200 characters). `null` removes it. */\n setTag(key: string, value: string | number | boolean | null | undefined): this {\n if (typeof key !== \"string\" || !key) return this;\n const k = key.slice(0, 32);\n if (value === null || value === undefined) delete this.tags[k];\n else if (k in this.tags || Object.keys(this.tags).length < MAX_TAGS) this.tags[k] = String(value).slice(0, 200);\n return this;\n }\n\n setTags(tags: Record<string, string | number | boolean | null | undefined>): this {\n if (tags && typeof tags === \"object\") for (const [k, v] of Object.entries(tags)) this.setTag(k, v);\n return this;\n }\n\n /** Arbitrary data shown with the event. `undefined` removes it. */\n setExtra(key: string, value: unknown): this {\n if (typeof key !== \"string\" || !key) return this;\n if (value === undefined) delete this.extra[key];\n else this.extra[key] = value;\n return this;\n }\n\n setExtras(extras: Record<string, unknown>): this {\n if (extras && typeof extras === \"object\") for (const [k, v] of Object.entries(extras)) this.setExtra(k, v);\n return this;\n }\n\n /** A named context (`{ name: \"checkout\", cartSize: 3 }`); `null` removes it. */\n setContext(name: string, context: Record<string, unknown> | null): this {\n if (typeof name !== \"string\" || !name) return this;\n if (context === null || context === undefined || typeof context !== \"object\") delete this.contexts[name];\n else this.contexts[name] = { ...context };\n return this;\n }\n\n /** The user errors are attributed to; `user.id` becomes the event's `userId`. `null` clears it. */\n setUser(user: User | null): this {\n this.user = user && typeof user === \"object\" ? { ...user } : null;\n return this;\n }\n\n /** Overrides the level of events captured in this scope. */\n setLevel(level: SeverityLevel | undefined): this {\n this.level = level;\n return this;\n }\n\n setFingerprint(fingerprint: string[] | undefined): this {\n this.fingerprint = Array.isArray(fingerprint) ? fingerprint.map(String) : undefined;\n return this;\n }\n\n /** The transaction name (`GET /users/:id`); the request middlewares set it from the matched route. */\n setTransactionName(name: string | undefined): this {\n this.transaction = typeof name === \"string\" && name ? name.slice(0, 200) : undefined;\n return this;\n }\n\n /** Records a breadcrumb through the client's `beforeBreadcrumb`. */\n addBreadcrumb(crumb: Breadcrumb): this {\n if (this.hook) this.hook(crumb, this);\n else this.pushBreadcrumb(crumb);\n return this;\n }\n\n /** @internal Adds an already-filtered breadcrumb, dropping the oldest beyond the limit. */\n pushBreadcrumb(crumb: Breadcrumb): void {\n this.crumbs.push(crumb);\n if (this.crumbs.length > this.max) this.crumbs.splice(0, this.crumbs.length - this.max);\n }\n\n clearBreadcrumbs(): this {\n this.crumbs = [];\n return this;\n }\n\n /** Removes everything (tags, extras, contexts, user, breadcrumbs…). */\n clear(): this {\n this.tags = {};\n this.extra = {};\n this.contexts = {};\n this.user = null;\n this.level = undefined;\n this.fingerprint = undefined;\n this.transaction = undefined;\n this.crumbs = [];\n this.request = undefined;\n return this;\n }\n\n /** A copy whose changes do not affect this scope. */\n clone(): Scope {\n const s = new Scope(this.max, this.hook);\n s.tags = { ...this.tags };\n s.extra = { ...this.extra };\n s.contexts = { ...this.contexts };\n s.user = this.user ? { ...this.user } : null;\n s.level = this.level;\n s.fingerprint = this.fingerprint;\n s.transaction = this.transaction;\n s.crumbs = this.crumbs.slice();\n s.request = this.request;\n return s;\n }\n\n /** @internal The scope's data at capture time. */\n data() {\n return {\n tags: { ...this.tags },\n extra: { ...this.extra },\n contexts: { ...this.contexts },\n user: this.user ? { ...this.user } : null,\n level: this.level,\n fingerprint: this.fingerprint,\n transaction: this.transaction,\n breadcrumbs: this.crumbs.slice(),\n request: this.request,\n };\n }\n}\n","import { buildMessage, InvalidMessageError, LIMITS, type GroupMessage, type IdentifyMessage, type MessageType, type TrackMessage } from \"./message\";\nimport { backoffDelay, DEFAULT_BACKOFF, jitter, parseRetryAfter, responseAction } from \"./retry\";\nimport { ERROR_LIMITS } from \"./errors/event\";\nimport { ErrorMonitor, type FastifyLike, type MiddlewareOptions } from \"./errors/monitor\";\nimport type { ProcessHandlerOptions } from \"./errors/process-handlers\";\nimport type { Scope } from \"./errors/scope\";\nimport type { Breadcrumb, BreadcrumbHint, CaptureContext, ErrorOptions, SeverityLevel, User } from \"./errors/types\";\n\nexport const SDK_NAME = \"guidely-node\";\nexport const SDK_VERSION = \"0.17.0\";\nexport const DEFAULT_API_URL = \"https://guidelytech.com\";\nexport const BATCH_PATH = \"/api/v1/sdk/server/batch\";\n\n/** `development`, `staging`, `production` or the key of an environment you added in Settings → Environments (`qa`, `uat`…). */\nexport type Environment = \"development\" | \"staging\" | \"production\" | (string & {});\n/** Environment keys: lowercase letters, digits and dashes, starting with a letter. */\nconst ENV_KEY = /^[a-z][a-z0-9-]{0,29}$/;\n\n/** The subset of `fetch` the SDK uses, so any implementation (undici, node-fetch, a test fake) fits. */\nexport type FetchLike = (\n url: string,\n init: { method: \"POST\"; headers: Record<string, string>; body: string; signal: AbortSignal },\n) => Promise<{ status: number; headers: { get(name: string): string | null }; text?: () => Promise<string> }>;\n\nexport type GuidelyErrorCode =\n /** A call was invalid (missing userId, empty event…) and dropped. */\n | \"invalid_message\"\n /** A message serialized to more than 32 KB (80 KB for an exception) and was dropped. */\n | \"message_too_large\"\n /** The queue was full (`maxQueueSize`); the oldest messages were dropped. */\n | \"queue_full\"\n /** A batch was rejected (4xx), or failed after every retry, or was cut short by a shutdown timeout. */\n | \"delivery_failed\"\n /** A call was made after `shutdown()`. */\n | \"closed\";\n\n/** Reported to `onError`; never thrown by tracking calls. */\nexport class GuidelyError extends Error {\n override readonly name = \"GuidelyError\";\n constructor(\n readonly code: GuidelyErrorCode,\n message: string,\n /** How many messages were dropped. */\n readonly count = 1,\n /** The HTTP status, for `delivery_failed` (0 when no answer was received). */\n readonly status?: number,\n options?: { cause?: unknown },\n ) {\n super(message, options);\n }\n}\n\nexport interface GuidelyOptions {\n /** A secret API key (`gly_sk_…`) with the `events:write` scope. Never ship it to a browser. */\n secretKey: string;\n /** Key of the environment events are written to (`production`, or e.g. `qa` for one you added). */\n environment: Environment;\n /** API origin (default `https://guidelytech.com`). */\n apiUrl?: string;\n /** Send a batch when this many messages are queued (default 100; batches hold at most 100). */\n flushAt?: number;\n /** Send what is queued at least this often (default 5000 ms). */\n flushIntervalMs?: number;\n /** Most messages held in memory; beyond it the oldest are dropped (default 10,000). */\n maxQueueSize?: number;\n /** Retries of a batch after network errors, 429 and 5xx (default 5, so up to 6 attempts). */\n maxRetries?: number;\n /** How long `shutdown()` (and the exit hook) waits for queued messages to go out (default 10,000 ms). */\n shutdownTimeoutMs?: number;\n /** Timeout of one HTTP request (default 10,000 ms). */\n timeoutMs?: number;\n /** Receives every problem (default: `console.warn`). Called synchronously; must not throw. */\n onError?: (error: GuidelyError) => void;\n /** `fetch` implementation (default: the global `fetch` of Node 18+). */\n fetch?: FetchLike;\n /** Flush on the process's `beforeExit` event (default true). Signals and `process.exit()` skip it: call `shutdown()`. */\n handleExit?: boolean;\n /** Your app's version, sent with every `track` (a message's own `appVersion` wins) and as the release of errors. */\n appVersion?: string;\n /**\n * Error monitoring (`captureException`, breadcrumbs, process and framework hooks). `false` turns\n * off the automatic console / HTTP breadcrumbs; manual captures still work.\n */\n errors?: ErrorOptions | false;\n}\n\ninterface Queued {\n json: string;\n bytes: number;\n}\n\ninterface Sleep {\n timer: ReturnType<typeof setTimeout> | undefined;\n resolve: () => void;\n}\n\nconst int = (value: number | undefined, fallback: number, min: number) =>\n typeof value === \"number\" && Number.isFinite(value) ? Math.max(min, Math.floor(value)) : fallback;\n\n/**\n * Server-side Guidely client: `identify`, `track` and `group` from your backend.\n *\n * ```ts\n * const guidely = new Guidely({ secretKey: process.env.GUIDELY_SECRET_KEY!, environment: \"production\" });\n * guidely.track({ userId: \"u_42\", event: \"Report Exported\", properties: { format: \"csv\" } });\n * await guidely.shutdown(); // before the process exits\n * ```\n *\n * Calls validate, queue and return: they never throw and never wait for the network. Messages go out\n * in batches (every `flushAt` messages, every `flushIntervalMs`, on `flush()`), one request at a time,\n * retried with backoff when Guidely is unreachable.\n */\nexport class Guidely {\n private readonly url: string;\n private readonly headers: Record<string, string>;\n private readonly flushAt: number;\n private readonly flushIntervalMs: number;\n private readonly maxQueueSize: number;\n private readonly maxRetries: number;\n private readonly shutdownTimeoutMs: number;\n private readonly timeoutMs: number;\n private readonly onError: (error: GuidelyError) => void;\n private readonly fetch: FetchLike;\n private readonly appVersion: string | undefined;\n private readonly sdkJson = JSON.stringify({ name: SDK_NAME, version: SDK_VERSION });\n\n private queue: Queued[] = [];\n private droppedSinceReport = 0;\n private timer: ReturnType<typeof setTimeout> | undefined;\n private pumping: Promise<void> | null = null;\n private drainAll = false;\n /** Bumped to abandon the running pump (shutdown timeout): its request is aborted and its sleeps end. */\n private epoch = 0;\n private inflight: AbortController | null = null;\n private readonly sleeps = new Set<Sleep>();\n private closed = false;\n private shutdownPromise: Promise<void> | null = null;\n private exitDrain: Promise<void> | null = null;\n private readonly exitListener: (() => void) | null = null;\n /** Set once `shutdown()` has finished: events still being prepared then are dropped, not sent. */\n private finished = false;\n private readonly monitor: ErrorMonitor;\n\n constructor(options: GuidelyOptions) {\n const o = options ?? ({} as GuidelyOptions);\n const key = typeof o.secretKey === \"string\" ? o.secretKey.trim() : \"\";\n if (!key.startsWith(\"gly_sk_\")) {\n throw new TypeError(\"Guidely: secretKey must be a secret API key (gly_sk_…) with the events:write scope\");\n }\n if (typeof o.environment !== \"string\" || !ENV_KEY.test(o.environment)) {\n throw new TypeError('Guidely: environment must be an environment key: \"development\", \"staging\", \"production\" or one you added (e.g. \"qa\"), as shown in Settings → Environments');\n }\n const fetchImpl = o.fetch ?? (typeof globalThis.fetch === \"function\" ? (globalThis.fetch.bind(globalThis) as unknown as FetchLike) : undefined);\n if (!fetchImpl) throw new TypeError(\"Guidely: no global fetch (Node 18+ is required), pass the fetch option\");\n this.fetch = fetchImpl;\n const apiUrl = (o.apiUrl ?? DEFAULT_API_URL).trim().replace(/\\/+$/, \"\");\n this.url = `${apiUrl}${BATCH_PATH}?environment=${encodeURIComponent(o.environment)}`;\n this.headers = {\n Authorization: `Bearer ${key}`,\n \"Content-Type\": \"application/json\",\n Accept: \"application/json\",\n \"User-Agent\": `${SDK_NAME}/${SDK_VERSION} (Node ${typeof process !== \"undefined\" ? process.version : \"unknown\"})`,\n };\n this.flushAt = int(o.flushAt, 100, 1);\n this.flushIntervalMs = int(o.flushIntervalMs, 5000, 1);\n this.maxQueueSize = int(o.maxQueueSize, 10_000, 1);\n this.maxRetries = int(o.maxRetries, 5, 0);\n this.shutdownTimeoutMs = int(o.shutdownTimeoutMs, 10_000, 0);\n this.timeoutMs = int(o.timeoutMs, 10_000, 1);\n this.onError = o.onError ?? ((e) => console.warn(`[${SDK_NAME}] ${e.message}`));\n this.appVersion = typeof o.appVersion === \"string\" && o.appVersion.trim() ? o.appVersion.trim() : undefined;\n this.monitor = new ErrorMonitor(\n {\n environment: o.environment,\n appVersion: this.appVersion,\n apiUrl,\n sdk: { name: SDK_NAME, version: SDK_VERSION },\n push: (message) => this.enqueueException(message),\n accepting: () => !this.closed,\n report: (message, cause, code = \"invalid_message\") => this.report(new GuidelyError(code, message, 1, undefined, { cause })),\n flush: () => this.flush(),\n },\n o.errors,\n );\n if (o.handleExit !== false && typeof process !== \"undefined\" && typeof process.on === \"function\") {\n this.exitListener = () => this.onBeforeExit();\n process.on(\"beforeExit\", this.exitListener);\n }\n }\n\n /** Who a user is: merges `traits` into the user (creating it if needed), optionally linking an account. */\n identify(message: IdentifyMessage): void {\n this.enqueue(\"identify\", message);\n }\n\n /** What a user (or anonymous visitor) did. */\n track(message: TrackMessage): void {\n const withVersion = this.appVersion && message && typeof message === \"object\" && (message.appVersion === undefined || message.appVersion === null);\n this.enqueue(\"track\", withVersion ? { ...message, appVersion: this.appVersion } : message);\n }\n\n /** Account traits, and optionally adds `userId` to the account. */\n group(message: GroupMessage): void {\n this.enqueue(\"group\", message);\n }\n\n // --- errors ----------------------------------------------------------------------------------\n\n /**\n * Reports an error as an `exception` event (grouped into an issue), with the current scope's tags,\n * extras, contexts, user and breadcrumbs. Returns the event id. Never throws.\n *\n * ```ts\n * guidely.captureException(err, { userId: \"u_42\", tags: { area: \"billing\" }, extra: { invoiceId } });\n * ```\n */\n captureException(error: unknown, context?: CaptureContext): string {\n return this.monitor.captureException(error, context);\n }\n\n /** Reports a message (level `info` unless given), grouped by its text. Returns the event id. */\n captureMessage(message: string, level?: SeverityLevel | CaptureContext, context?: CaptureContext): string {\n return this.monitor.captureMessage(message, level, context);\n }\n\n /** A tag on every later error of the current scope (`null` removes it). */\n setTag(key: string, value: string | number | boolean | null | undefined): void {\n this.monitor.current().setTag(key, value);\n }\n\n setTags(tags: Record<string, string | number | boolean | null | undefined>): void {\n this.monitor.current().setTags(tags);\n }\n\n setExtra(key: string, value: unknown): void {\n this.monitor.current().setExtra(key, value);\n }\n\n setExtras(extras: Record<string, unknown>): void {\n this.monitor.current().setExtras(extras);\n }\n\n /** A named context on every later error of the current scope (`null` removes it). */\n setContext(name: string, context: Record<string, unknown> | null): void {\n this.monitor.current().setContext(name, context);\n }\n\n /** The user later errors of the current scope belong to (`user.id` becomes `userId`); `null` clears it. */\n setUser(user: User | null): void {\n this.monitor.current().setUser(user);\n }\n\n /** Adds a breadcrumb to the current scope (the last 100 ride along with each error). */\n addBreadcrumb(breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void {\n this.monitor.addBreadcrumb(breadcrumb, hint);\n }\n\n /**\n * Runs `fn` with a copy of the current scope: tags, user and breadcrumbs set inside (and in\n * everything it starts, through AsyncLocalStorage) stay there. Returns what `fn` returns.\n */\n withScope<T>(fn: (scope: Scope) => T): T {\n return this.monitor.withScope(fn);\n }\n\n /**\n * Reports `uncaughtException` (fatal) and `unhandledRejection`, keeping Node's behaviour: the error\n * is printed, queued events are sent (at most `flushTimeoutMs`) and the process exits with code 1.\n * Returns a function that removes the handlers (`shutdown()` removes them too).\n */\n installProcessHandlers(options?: ProcessHandlerOptions): () => void {\n return this.monitor.installProcessHandlers(options);\n }\n\n /** Express: `app.use(guidely.expressRequestHandler())` first, so each request gets its own scope. */\n expressRequestHandler(): (req: unknown, res: unknown, next: (error?: unknown) => void) => void {\n return this.monitor.expressRequestHandler();\n }\n\n /** Express: `app.use(guidely.expressErrorHandler())` after your routes, before other error handlers. */\n expressErrorHandler(options?: MiddlewareOptions): (error: unknown, req: unknown, res: unknown, next: (error?: unknown) => void) => void {\n return this.monitor.expressErrorHandler(options);\n }\n\n /** Fastify: `await app.register(guidely.fastifyPlugin())` (request scopes + the `onError` hook). */\n fastifyPlugin(options?: MiddlewareOptions): (fastify: FastifyLike, opts: unknown, done?: (error?: Error) => void) => void {\n return this.monitor.fastifyPlugin(options);\n }\n\n /** Fastify: `app.addHook(\"onError\", guidely.fastifyErrorHook())`, when you do not use the plugin. */\n fastifyErrorHook(options?: MiddlewareOptions): (request: unknown, reply: unknown, error: unknown, done?: () => void) => void {\n return this.monitor.fastifyErrorHook(options);\n }\n\n /** Koa: `app.use(guidely.koaMiddleware())` first: a scope per request; errors are reported and rethrown. */\n koaMiddleware(options?: MiddlewareOptions): (ctx: { req?: unknown; res?: unknown }, next: () => Promise<unknown>) => Promise<unknown> {\n return this.monitor.koaMiddleware(options);\n }\n\n // --- delivery ------------------------------------------------------------------------------\n\n /** Sends everything queued; resolves once it has been delivered or dropped. Never rejects. */\n flush(): Promise<void> {\n const preparing = this.monitor.idle();\n return preparing ? preparing.then(() => this.startPump(true)) : this.startPump(true);\n }\n\n /**\n * Stops the timer, the exit hook and the error hooks, then flushes, waiting at most\n * `shutdownTimeoutMs`. Later calls are dropped (and reported). Call it before your process exits.\n * Never rejects.\n */\n shutdown(): Promise<void> {\n if (this.shutdownPromise) return this.shutdownPromise;\n this.closed = true;\n this.clearTimer();\n this.monitor.close();\n if (this.exitListener) process.removeListener(\"beforeExit\", this.exitListener);\n this.shutdownPromise = this.drain(this.shutdownTimeoutMs).finally(() => {\n this.finished = true;\n });\n return this.shutdownPromise;\n }\n\n // --- queueing ------------------------------------------------------------------------------\n\n private enqueue(type: MessageType, args: unknown): void {\n try {\n if (this.closed) {\n this.report(new GuidelyError(\"closed\", `${type}() was called after shutdown(); the message was dropped`));\n return;\n }\n const message = buildMessage(type, args);\n let json: string;\n try {\n json = JSON.stringify(message);\n } catch (e) {\n throw new InvalidMessageError(`could not be serialized to JSON (${e instanceof Error ? e.message : String(e)})`);\n }\n const bytes = Buffer.byteLength(json, \"utf8\");\n if (bytes > LIMITS.maxMessageBytes) {\n this.report(new GuidelyError(\"message_too_large\", `${type}() message is ${bytes} bytes, more than the ${LIMITS.maxMessageBytes}-byte limit; it was dropped`));\n return;\n }\n this.push(json, bytes, false);\n } catch (e) {\n if (e instanceof InvalidMessageError) this.report(new GuidelyError(\"invalid_message\", `Invalid ${type}() call dropped: ${e.message}`));\n else this.report(new GuidelyError(\"invalid_message\", `${type}() failed: ${e instanceof Error ? e.message : String(e)}`, 1, undefined, { cause: e }));\n }\n }\n\n /**\n * Queues a built `exception` message (it may finish preparing after `shutdown()` began, which\n * still sends it) and starts sending right away: errors should not wait for the flush interval.\n */\n private enqueueException(message: Record<string, unknown>): void {\n if (this.finished) {\n this.report(new GuidelyError(\"closed\", \"an exception finished preparing after shutdown(); it was dropped\"));\n return;\n }\n let json = JSON.stringify(message);\n let bytes = Buffer.byteLength(json, \"utf8\");\n if (bytes > ERROR_LIMITS.maxMessageBytes && \"detail\" in message) {\n json = JSON.stringify({ ...message, detail: undefined }); // the properties alone still index the occurrence\n bytes = Buffer.byteLength(json, \"utf8\");\n }\n if (bytes > ERROR_LIMITS.maxMessageBytes) {\n this.report(new GuidelyError(\"message_too_large\", `exception message is ${bytes} bytes, more than the ${ERROR_LIMITS.maxMessageBytes}-byte limit; it was dropped`));\n return;\n }\n this.push(json, bytes, true);\n }\n\n private push(json: string, bytes: number, prompt: boolean): void {\n if (this.queue.length >= this.maxQueueSize) {\n this.queue.shift();\n this.droppedSinceReport++;\n }\n this.queue.push({ json, bytes });\n if (prompt) void this.startPump(true);\n else if (this.queue.length >= this.flushAt) void this.startPump(false);\n else this.scheduleTimer();\n }\n\n private scheduleTimer(): void {\n if (this.timer !== undefined || this.closed) return;\n this.timer = setTimeout(() => {\n this.timer = undefined;\n void this.startPump(true);\n }, this.flushIntervalMs);\n (this.timer as { unref?: () => void }).unref?.();\n }\n\n private clearTimer(): void {\n if (this.timer !== undefined) clearTimeout(this.timer);\n this.timer = undefined;\n }\n\n // --- sending -------------------------------------------------------------------------------\n\n /** Starts (or joins) the single sender. `all`: send everything, not only full batches. */\n private startPump(all: boolean): Promise<void> {\n if (all) this.drainAll = true;\n if (!this.pumping) this.pumping = this.pump();\n return this.pumping;\n }\n\n private async pump(): Promise<void> {\n await Promise.resolve(); // `this.pumping` is assigned before the loop can finish\n const epoch = this.epoch;\n try {\n const cap = Math.min(this.flushAt, LIMITS.maxBatchMessages);\n for (;;) {\n this.reportDrops();\n if (epoch !== this.epoch || this.queue.length === 0 || (!this.drainAll && this.queue.length < cap)) break;\n await this.deliver(this.takeBatch(cap), epoch);\n }\n } catch (e) {\n this.report(new GuidelyError(\"delivery_failed\", `Unexpected error while sending: ${e instanceof Error ? e.message : String(e)}`, 0, undefined, { cause: e }));\n } finally {\n this.pumping = null;\n this.drainAll = false;\n if (this.queue.length > 0) this.scheduleTimer();\n }\n }\n\n /** Up to `cap` messages from the head of the queue, at most `maxBatchBytes` of them (at least one). */\n private takeBatch(cap: number): Queued[] {\n let n = 0;\n let size = 0;\n while (n < this.queue.length && n < cap) {\n const next = this.queue[n]!;\n if (n > 0 && size + next.bytes > LIMITS.maxBatchBytes) break;\n size += next.bytes;\n n++;\n }\n return this.queue.splice(0, n);\n }\n\n private async deliver(batch: Queued[], epoch: number): Promise<void> {\n const messages = batch.map((m) => m.json).join(\",\");\n for (let attempt = 1; ; attempt++) {\n if (epoch !== this.epoch) {\n this.report(new GuidelyError(\"delivery_failed\", `${batch.length} messages were not sent before the shutdown timeout`, batch.length, 0));\n return;\n }\n const body = `{\"batch\":[${messages}],\"sentAt\":${JSON.stringify(new Date().toISOString())},\"sdk\":${this.sdkJson}}`;\n let status = 0;\n let retryAfter: string | null = null;\n let failure: unknown;\n try {\n const res = await this.send(body);\n status = res.status;\n retryAfter = res.headers.get(\"retry-after\");\n } catch (e) {\n failure = e;\n }\n const action = responseAction(status);\n if (action === \"ok\") return;\n if (epoch !== this.epoch) continue; // aborted while sending: reported at the top\n if (action === \"drop\" || attempt > this.maxRetries) {\n this.report(new GuidelyError(\"delivery_failed\", failureMessage(status, failure, batch.length, attempt), batch.length, status, { cause: failure }));\n return;\n }\n const delay = parseRetryAfter(retryAfter) !== null ? backoffDelay(attempt, retryAfter) : jitter(backoffDelay(attempt, null, DEFAULT_BACKOFF), Math.random());\n await this.sleep(delay);\n }\n }\n\n private async send(body: string) {\n const controller = new AbortController();\n this.inflight = controller;\n const timeout = setTimeout(() => controller.abort(new Error(`request timed out after ${this.timeoutMs} ms`)), this.timeoutMs);\n try {\n const res = await this.fetch(this.url, { method: \"POST\", headers: this.headers, body, signal: controller.signal });\n try {\n await res.text?.(); // release the connection\n } catch {\n // the status is what matters\n }\n return res;\n } finally {\n clearTimeout(timeout);\n if (this.inflight === controller) this.inflight = null;\n }\n }\n\n private sleep(ms: number): Promise<void> {\n return new Promise<void>((resolve) => {\n const s: Sleep = { timer: undefined, resolve };\n s.timer = setTimeout(() => {\n this.sleeps.delete(s);\n resolve();\n }, ms);\n this.sleeps.add(s);\n });\n }\n\n /** Flushes, giving up after `timeoutMs`: the request in flight is aborted and what is left is dropped. */\n private async drain(timeoutMs: number): Promise<void> {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const timedOut = await Promise.race([\n this.flush().then(() => false),\n new Promise<boolean>((resolve) => {\n timer = setTimeout(() => resolve(true), timeoutMs);\n }),\n ]);\n clearTimeout(timer);\n if (!timedOut) return;\n this.epoch++;\n this.inflight?.abort(new Error(\"shutdown timeout\"));\n for (const s of this.sleeps) {\n clearTimeout(s.timer);\n s.resolve();\n }\n this.sleeps.clear();\n const left = this.queue.length;\n this.queue = [];\n if (left > 0) this.report(new GuidelyError(\"delivery_failed\", `${left} queued messages were not sent within ${timeoutMs} ms`, left, 0));\n }\n\n private onBeforeExit(): void {\n if (this.closed || this.exitDrain || (this.queue.length === 0 && !this.pumping && !this.monitor.idle())) return;\n this.exitDrain = this.drain(this.shutdownTimeoutMs).finally(() => {\n this.exitDrain = null;\n });\n }\n\n // --- errors --------------------------------------------------------------------------------\n\n private reportDrops(): void {\n if (this.droppedSinceReport === 0) return;\n const n = this.droppedSinceReport;\n this.droppedSinceReport = 0;\n this.report(new GuidelyError(\"queue_full\", `The queue was full (maxQueueSize ${this.maxQueueSize}): dropped the ${n} oldest messages`, n));\n }\n\n private report(error: GuidelyError): void {\n try {\n this.onError(error);\n } catch {\n // an error handler must never break the caller\n }\n }\n}\n\nfunction failureMessage(status: number, failure: unknown, count: number, attempts: number): string {\n const what = `${count} messages were dropped`;\n if (status === 0) return `${what}: Guidely could not be reached in ${attempts} attempt${attempts === 1 ? \"\" : \"s\"} (${failure instanceof Error ? failure.message : String(failure)})`;\n if (status === 401 || status === 403) return `${what}: the key was rejected (HTTP ${status}). Check it is a gly_sk_ key with the events:write scope for this environment`;\n if (attempts > 1) return `${what}: HTTP ${status} after ${attempts} attempts`;\n return `${what}: HTTP ${status}`;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,yBAA4B;AAGrB,IAAM,SAAS;AAAA;AAAA,EAEpB,kBAAkB;AAAA;AAAA,EAElB,eAAe;AAAA;AAAA,EAEf,iBAAiB;AAAA,EACjB,gBAAgB;AAAA,EAChB,aAAa;AACf;AA4DO,IAAM,sBAAN,cAAkC,MAAM;AAAC;AAEhD,IAAM,WAAW;AAGV,SAAS,eAAuB;AACrC,MAAIA,MAAK;AACT,SAAOA,IAAG,SAAS,IAAI;AACrB,eAAW,SAAK,gCAAY,EAAE,GAAG;AAC/B,UAAI,IAAI,IAAK,CAAAA,OAAM,SAAS,IAAI,EAAE;AAClC,UAAIA,IAAG,WAAW,GAAI;AAAA,IACxB;AAAA,EACF;AACA,SAAOA;AACT;AAGO,SAAS,gBAAgB,OAA0B;AACxD,MAAI;AACJ,MAAI,iBAAiB,KAAM,QAAO;AAAA,WACzB,OAAO,UAAU,SAAU,QAAO,IAAI,KAAK,KAAK;AAAA,WAChD,OAAO,UAAU,YAAY,wEAAwE,KAAK,MAAM,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EAIQ,cAAoB;AAC1B,QAAI,KAAK,uBAAuB,EAAG;AACnC,UAAM,IAAI,KAAK;AACf,SAAK,qBAAqB;AAC1B,SAAK,OAAO,IAAI,aAAa,cAAc,oCAAoC,KAAK,YAAY,kBAAkB,CAAC,oBAAoB,CAAC,CAAC;AAAA,EAC3I;AAAA,EAEQ,OAAO,OAA2B;AACxC,QAAI;AACF,WAAK,QAAQ,KAAK;AAAA,IACpB,QAAQ;AAAA,IAER;AAAA,EACF;AACF;AAEA,SAAS,eAAe,QAAgB,SAAkB,OAAe,UAA0B;AACjG,QAAM,OAAO,GAAG,KAAK;AACrB,MAAI,WAAW,EAAG,QAAO,GAAG,IAAI,qCAAqC,QAAQ,WAAW,aAAa,IAAI,KAAK,GAAG,KAAK,mBAAmB,QAAQ,QAAQ,UAAU,OAAO,OAAO,CAAC;AAClL,MAAI,WAAW,OAAO,WAAW,IAAK,QAAO,GAAG,IAAI,gCAAgC,MAAM;AAC1F,MAAI,WAAW,EAAG,QAAO,GAAG,IAAI,UAAU,MAAM,UAAU,QAAQ;AAClE,SAAO,GAAG,IAAI,UAAU,MAAM;AAChC;","names":["id","type","import_node_crypto","out","id","release","cpus","os","os","import_node_path","subscribe","statusOf","import_node_path","import_node_util","levelOf","type","result","safe","type","bytes"]}
|