@grow-codes/grafana-loki 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.js ADDED
@@ -0,0 +1,3621 @@
1
+ import { ConfigError, LokiError, ErrorCode, sleep, CancelledError, TimeoutError, errorForStatus, UnavailableError, logRecordByteSize, toAttributes, severityText, normalizeHexId, parseSeverity, ValidationError, BaseLogQueryClient, UnsupportedError } from './chunk-KTHP35QG.js';
2
+ export { AuthenticationError, BaseLogQueryClient, CancelledError, ConfigError, ConflictError, ErrorCode, LokiError, NotFoundError, PermissionDeniedError, RateLimitError, Severity, TimeoutError, UnavailableError, UnsupportedError, UnsupportedLogQueryClient, ValidationError, canonicalSeverity, codeForStatus, errorForCode, errorForStatus, isLokiError, logRecordByteSize, logRecordFromJson, logRecordToJson, parseLogRecord, parseSeverity, pollTail, pollUntil, reasonForCode, serializeLogRecord, severityText, sleep, throwIfAborted, toAttrValue, toAttributes, waitForLog } from './chunk-KTHP35QG.js';
3
+ import { readFileSync } from 'fs';
4
+ import { ProxyAgent, Agent, fetch } from 'undici';
5
+ import { gzipSync } from 'zlib';
6
+ import { trace, context, isSpanContextValid } from '@opentelemetry/api';
7
+ import { Writable } from 'stream';
8
+ import { compress } from 'snappyjs';
9
+ import WebSocket from 'ws';
10
+
11
+ // src/core/redaction.ts
12
+ var REDACTED = "[REDACTED]";
13
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
14
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
15
+ "authorization",
16
+ "proxy-authorization",
17
+ "cookie",
18
+ "set-cookie"
19
+ ]);
20
+ var SENSITIVE_HEADER_PARTS = [
21
+ "token",
22
+ "secret",
23
+ "password",
24
+ "api-key",
25
+ "apikey",
26
+ "key",
27
+ "auth",
28
+ "session",
29
+ "signature",
30
+ "credential"
31
+ ];
32
+ var SENSITIVE_FIELD_PARTS = [
33
+ "password",
34
+ "passwd",
35
+ "secret",
36
+ "token",
37
+ "authorization",
38
+ "cookie",
39
+ "api_key",
40
+ "apikey",
41
+ "api-key",
42
+ "access_key",
43
+ "private_key",
44
+ "client_secret",
45
+ "credential",
46
+ "session",
47
+ "signature"
48
+ ];
49
+ var MIN_SECRET_LENGTH = 4;
50
+ function isSensitiveHeader(name) {
51
+ const n = name.toLowerCase();
52
+ return SENSITIVE_HEADERS.has(n) || SENSITIVE_HEADER_PARTS.some((p) => n.includes(p));
53
+ }
54
+ var PATH_NAME = /path$/;
55
+ function isSensitiveField(name, extraKeys = []) {
56
+ const n = name.toLowerCase();
57
+ return !PATH_NAME.test(n) && SENSITIVE_FIELD_PARTS.some((p) => n.includes(p)) || extraKeys.some((k) => k !== "" && n.includes(k.toLowerCase()));
58
+ }
59
+ function headerEntries(headers) {
60
+ if (Symbol.iterator in headers) {
61
+ return Array.from(headers, ([k, v]) => [k, v]);
62
+ }
63
+ const out = [];
64
+ for (const [k, v] of Object.entries(headers)) {
65
+ if (v === void 0) continue;
66
+ out.push([k, typeof v === "string" ? v : v.join(", ")]);
67
+ }
68
+ return out;
69
+ }
70
+ function redactHeaders(headers) {
71
+ const out = {};
72
+ for (const [k, v] of headerEntries(headers)) {
73
+ out[k] = isSensitiveHeader(k) ? REDACTED : v;
74
+ }
75
+ return out;
76
+ }
77
+ function redactUrl(url) {
78
+ let parsed;
79
+ try {
80
+ parsed = new URL(url.toString());
81
+ } catch {
82
+ return redactQueryString(url.toString());
83
+ }
84
+ if (parsed.password !== "") parsed.password = REDACTED;
85
+ if (parsed.password === "" && parsed.username !== "" && parsed.username !== REDACTED) {
86
+ parsed.username = REDACTED;
87
+ }
88
+ const params = parsed.searchParams;
89
+ let changed = false;
90
+ const next = new URLSearchParams();
91
+ for (const [k, v] of params) {
92
+ if (isSensitiveField(k)) {
93
+ next.append(k, REDACTED);
94
+ changed = true;
95
+ } else {
96
+ next.append(k, v);
97
+ }
98
+ }
99
+ if (changed) parsed.search = next.toString();
100
+ return parsed.toString().replaceAll(encodeURIComponent(REDACTED), REDACTED);
101
+ }
102
+ function redactQueryString(text) {
103
+ return text.replace(
104
+ /([?&])([^=&#\s]+)=([^&#\s]*)/g,
105
+ (m, sep, k) => isSensitiveField(k) ? `${sep}${k}=${REDACTED}` : m
106
+ );
107
+ }
108
+ function redactFields(value, extraKeys = []) {
109
+ return redactValue(value, extraKeys, /* @__PURE__ */ new WeakMap());
110
+ }
111
+ function redactValue(value, extraKeys, seen) {
112
+ if (value === null || typeof value !== "object") return value;
113
+ if (value instanceof Date || value instanceof Uint8Array) return value;
114
+ const cached = seen.get(value);
115
+ if (cached !== void 0) return cached;
116
+ if (Array.isArray(value)) {
117
+ const arr = [];
118
+ seen.set(value, arr);
119
+ for (const item of value) arr.push(redactValue(item, extraKeys, seen));
120
+ return arr;
121
+ }
122
+ if (value instanceof Map) {
123
+ const map = /* @__PURE__ */ new Map();
124
+ seen.set(value, map);
125
+ for (const [k, v] of value) {
126
+ map.set(
127
+ k,
128
+ typeof k === "string" && isSensitiveField(k, extraKeys) ? REDACTED : redactValue(v, extraKeys, seen)
129
+ );
130
+ }
131
+ return map;
132
+ }
133
+ const out = {};
134
+ seen.set(value, out);
135
+ for (const [k, v] of Object.entries(value)) {
136
+ out[k] = isSensitiveField(k, extraKeys) ? REDACTED : redactValue(v, extraKeys, seen);
137
+ }
138
+ return out;
139
+ }
140
+ function redactText(text, knownSecrets = []) {
141
+ const values = /* @__PURE__ */ new Set();
142
+ for (const s of knownSecrets) {
143
+ const v = s instanceof Secret ? s.reveal() : s;
144
+ if (typeof v === "string" && v.length >= MIN_SECRET_LENGTH) values.add(v);
145
+ }
146
+ let out = text;
147
+ for (const v of [...values].sort((a, b) => b.length - a.length)) {
148
+ out = out.split(v).join(REDACTED);
149
+ }
150
+ return out;
151
+ }
152
+ var Secret = class _Secret {
153
+ #value;
154
+ constructor(value) {
155
+ this.#value = value;
156
+ }
157
+ /** Wraps a string (returns `undefined` for `undefined`/empty, keeps an existing Secret). */
158
+ static from(value) {
159
+ if (value === void 0 || value === null) return void 0;
160
+ if (value instanceof _Secret) return value;
161
+ return value === "" ? void 0 : new _Secret(value);
162
+ }
163
+ /** The wrapped value. */
164
+ reveal() {
165
+ return this.#value;
166
+ }
167
+ /** Constant-time-ish comparison with another value. */
168
+ equals(other) {
169
+ const a = this.#value;
170
+ const b = other instanceof _Secret ? other.reveal() : other;
171
+ if (a.length !== b.length) return false;
172
+ let diff = 0;
173
+ for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
174
+ return diff === 0;
175
+ }
176
+ toString() {
177
+ return REDACTED;
178
+ }
179
+ toJSON() {
180
+ return REDACTED;
181
+ }
182
+ [INSPECT]() {
183
+ return REDACTED;
184
+ }
185
+ };
186
+ function redactError(err, knownSecrets = []) {
187
+ const secrets = [...knownSecrets];
188
+ if (err instanceof Error) {
189
+ const copy = new Error(redactText(redactQueryString(err.message), secrets));
190
+ copy.name = err.name;
191
+ const code = err.code;
192
+ if (typeof code === "string") copy.code = code;
193
+ if (err.cause !== void 0) copy.cause = redactError(err.cause, secrets);
194
+ return copy;
195
+ }
196
+ return new Error(redactText(String(err), secrets));
197
+ }
198
+
199
+ // src/core/env.ts
200
+ var UNIT_MS = {
201
+ ns: 1e-6,
202
+ us: 1e-3,
203
+ \u00B5s: 1e-3,
204
+ ms: 1,
205
+ s: 1e3,
206
+ m: 6e4,
207
+ h: 36e5
208
+ };
209
+ var DURATION_PART = /(\d+(?:\.\d+)?|\.\d+)(ns|us|µs|ms|s|m|h)/gy;
210
+ function parseDuration(raw) {
211
+ const text = raw.trim();
212
+ if (/^\d+$/.test(text)) return Number(text);
213
+ if (text === "") return void 0;
214
+ DURATION_PART.lastIndex = 0;
215
+ let total = 0;
216
+ let pos = 0;
217
+ let match;
218
+ while ((match = DURATION_PART.exec(text)) !== null) {
219
+ total += Number(match[1]) * UNIT_MS[match[2]];
220
+ pos = DURATION_PART.lastIndex;
221
+ }
222
+ return pos === text.length && pos > 0 ? Math.round(total) : void 0;
223
+ }
224
+ var TRUE_WORDS = /* @__PURE__ */ new Set(["true", "1", "yes", "on"]);
225
+ var FALSE_WORDS = /* @__PURE__ */ new Set(["false", "0", "no", "off"]);
226
+ function parseBool(raw) {
227
+ const text = raw.trim().toLowerCase();
228
+ if (TRUE_WORDS.has(text)) return true;
229
+ if (FALSE_WORDS.has(text)) return false;
230
+ return void 0;
231
+ }
232
+ function parseInteger(raw) {
233
+ const text = raw.trim();
234
+ if (!/^[+-]?\d+$/.test(text)) return void 0;
235
+ const n = Number(text);
236
+ return Number.isSafeInteger(n) ? n : void 0;
237
+ }
238
+ var EnvReader = class {
239
+ prefix;
240
+ #env;
241
+ /**
242
+ * @param prefix e.g. `"GROW_GRAFANA_LOKI_"`.
243
+ * @param env environment map, defaults to `process.env`.
244
+ */
245
+ constructor(prefix, env = process.env) {
246
+ this.prefix = prefix;
247
+ this.#env = env;
248
+ }
249
+ /** Finds the first present variable: `<prefix><name>`, then each vendor name. */
250
+ lookup(name, vendorNames = []) {
251
+ for (const candidate of [this.prefix + name, ...vendorNames]) {
252
+ const value = this.#env[candidate];
253
+ if (value !== void 0 && value !== "") return { name: candidate, value };
254
+ }
255
+ return void 0;
256
+ }
257
+ /** String value. */
258
+ string(name, vendorNames = []) {
259
+ return this.lookup(name, vendorNames)?.value;
260
+ }
261
+ /** Credential value wrapped in a {@link Secret}. */
262
+ secret(name, vendorNames = []) {
263
+ return Secret.from(this.string(name, vendorNames));
264
+ }
265
+ /** Duration in milliseconds (see {@link parseDuration}). */
266
+ duration(name, vendorNames = []) {
267
+ return this.#parse(name, vendorNames, parseDuration, "a duration such as 1500, 500ms or 10s");
268
+ }
269
+ /** Boolean (see {@link parseBool}). */
270
+ bool(name, vendorNames = []) {
271
+ return this.#parse(name, vendorNames, parseBool, "a boolean (true/false/1/0/yes/no/on/off)");
272
+ }
273
+ /** Integer. */
274
+ int(name, vendorNames = []) {
275
+ return this.#parse(name, vendorNames, parseInteger, "an integer");
276
+ }
277
+ #parse(name, vendorNames, parse, expected) {
278
+ const hit = this.lookup(name, vendorNames);
279
+ if (hit === void 0) return void 0;
280
+ const value = parse(hit.value);
281
+ if (value === void 0) {
282
+ throw new ConfigError(
283
+ `invalid value in environment variable ${hit.name}: expected ${expected}`
284
+ );
285
+ }
286
+ return value;
287
+ }
288
+ };
289
+
290
+ // src/core/health.ts
291
+ var HEALTHY_WORDS = /* @__PURE__ */ new Set([
292
+ "ok",
293
+ "up",
294
+ "healthy",
295
+ "pass",
296
+ "passing",
297
+ "green",
298
+ "ready",
299
+ "available",
300
+ "running",
301
+ "serving"
302
+ ]);
303
+ function isHealthyWord(status) {
304
+ return HEALTHY_WORDS.has(status.trim().toLowerCase());
305
+ }
306
+ function healthStatus(status, details = {}, healthy = isHealthyWord(status)) {
307
+ const flat = {};
308
+ for (const [k, v] of Object.entries(details)) {
309
+ if (v === void 0 || v === null) continue;
310
+ if (typeof v === "string") flat[k] = v;
311
+ else if (typeof v === "number" || typeof v === "boolean" || typeof v === "bigint")
312
+ flat[k] = String(v);
313
+ else if (typeof v === "object") flat[k] = JSON.stringify(v);
314
+ }
315
+ return { healthy, status, details: flat };
316
+ }
317
+ async function probeHealth(probe) {
318
+ try {
319
+ return await probe();
320
+ } catch (err) {
321
+ if (err instanceof LokiError) {
322
+ if (err.code === ErrorCode.Cancelled || err.code === ErrorCode.Config) throw err;
323
+ if (err.httpStatus !== void 0) {
324
+ return healthStatus("unhealthy", { httpStatus: err.httpStatus, error: err.code }, false);
325
+ }
326
+ return healthStatus("unreachable", { error: err.code }, false);
327
+ }
328
+ return healthStatus("unreachable", { error: ErrorCode.Unavailable }, false);
329
+ }
330
+ }
331
+
332
+ // src/core/hooks.ts
333
+ var silentLogger = Object.freeze({
334
+ debug: () => void 0,
335
+ info: () => void 0,
336
+ warn: () => void 0,
337
+ error: () => void 0
338
+ });
339
+ function safeCall(fn, ...args) {
340
+ if (fn === void 0) return;
341
+ try {
342
+ const result = fn(...args);
343
+ if (result instanceof Promise) result.catch(() => void 0);
344
+ } catch {
345
+ }
346
+ }
347
+ function safeLogger(logger) {
348
+ if (logger === void 0) return silentLogger;
349
+ return {
350
+ debug: (m, f) => {
351
+ safeCall(
352
+ (a, b) => {
353
+ logger.debug(a, b);
354
+ },
355
+ m,
356
+ f
357
+ );
358
+ },
359
+ info: (m, f) => {
360
+ safeCall(
361
+ (a, b) => {
362
+ logger.info(a, b);
363
+ },
364
+ m,
365
+ f
366
+ );
367
+ },
368
+ warn: (m, f) => {
369
+ safeCall(
370
+ (a, b) => {
371
+ logger.warn(a, b);
372
+ },
373
+ m,
374
+ f
375
+ );
376
+ },
377
+ error: (m, f) => {
378
+ safeCall(
379
+ (a, b) => {
380
+ logger.error(a, b);
381
+ },
382
+ m,
383
+ f
384
+ );
385
+ }
386
+ };
387
+ }
388
+
389
+ // src/core/retry.ts
390
+ var RetryPolicy = class _RetryPolicy {
391
+ static DEFAULTS = Object.freeze({
392
+ maxRetries: 3,
393
+ initialBackoffMs: 100,
394
+ maxBackoffMs: 1e4,
395
+ multiplier: 2,
396
+ maxRetryAfterMs: 6e4
397
+ });
398
+ maxRetries;
399
+ initialBackoffMs;
400
+ maxBackoffMs;
401
+ multiplier;
402
+ maxRetryAfterMs;
403
+ random;
404
+ constructor(options = {}) {
405
+ const d = _RetryPolicy.DEFAULTS;
406
+ this.maxRetries = options.maxRetries ?? d.maxRetries;
407
+ this.initialBackoffMs = options.initialBackoffMs ?? d.initialBackoffMs;
408
+ this.maxBackoffMs = options.maxBackoffMs ?? d.maxBackoffMs;
409
+ this.multiplier = options.multiplier ?? d.multiplier;
410
+ this.maxRetryAfterMs = options.maxRetryAfterMs ?? d.maxRetryAfterMs;
411
+ this.random = options.random ?? Math.random;
412
+ Object.freeze(this);
413
+ }
414
+ /** Returns a policy from options, keeping an existing instance as is. */
415
+ static from(value) {
416
+ return value instanceof _RetryPolicy ? value : new _RetryPolicy(value);
417
+ }
418
+ /** Upper bound of the backoff before retry `n` (0-based): `min(max, initial * multiplier^n)`. */
419
+ backoffCapMs(retry) {
420
+ return Math.min(this.maxBackoffMs, this.initialBackoffMs * this.multiplier ** retry);
421
+ }
422
+ /** Full-jitter backoff before retry `n` (0-based): `random(0, backoffCapMs(n))`. */
423
+ backoffMs(retry) {
424
+ return this.random() * this.backoffCapMs(retry);
425
+ }
426
+ /** Validation problems (empty when valid). */
427
+ problems() {
428
+ const out = [];
429
+ if (!Number.isInteger(this.maxRetries) || this.maxRetries < 0)
430
+ out.push("retry.maxRetries must be an integer >= 0");
431
+ if (!(this.initialBackoffMs >= 0)) out.push("retry.initialBackoffMs must be >= 0");
432
+ if (!(this.maxBackoffMs >= 0)) out.push("retry.maxBackoffMs must be >= 0");
433
+ if (!(this.multiplier >= 1)) out.push("retry.multiplier must be >= 1");
434
+ if (!(this.maxRetryAfterMs >= 0)) out.push("retry.maxRetryAfterMs must be >= 0");
435
+ return out;
436
+ }
437
+ toJSON() {
438
+ return {
439
+ maxRetries: this.maxRetries,
440
+ initialBackoffMs: this.initialBackoffMs,
441
+ maxBackoffMs: this.maxBackoffMs,
442
+ multiplier: this.multiplier,
443
+ maxRetryAfterMs: this.maxRetryAfterMs
444
+ };
445
+ }
446
+ };
447
+ function parseRetryAfter(value, now = Date.now()) {
448
+ if (value === null || value === void 0) return void 0;
449
+ const text = value.trim();
450
+ if (text === "") return void 0;
451
+ if (/^\d+(\.\d+)?$/.test(text)) return Math.round(Number(text) * 1e3);
452
+ if (!/[a-z]/i.test(text)) return void 0;
453
+ const at = Date.parse(text);
454
+ if (Number.isNaN(at)) return void 0;
455
+ return Math.max(0, at - now);
456
+ }
457
+ var IDEMPOTENT_METHODS = /* @__PURE__ */ new Set([
458
+ "GET",
459
+ "HEAD",
460
+ "OPTIONS",
461
+ "PUT",
462
+ "DELETE"
463
+ ]);
464
+ function isIdempotentMethod(method) {
465
+ return IDEMPOTENT_METHODS.has(method.toUpperCase());
466
+ }
467
+ function isRetryableStatus(status, idempotent) {
468
+ if (status === 429) return true;
469
+ if (!idempotent) return false;
470
+ return status === 408 || status === 500 || status === 502 || status === 503 || status === 504;
471
+ }
472
+
473
+ // src/core/options.ts
474
+ var DEFAULT_TIMEOUTS = Object.freeze({
475
+ connectTimeoutMs: 1e4,
476
+ requestTimeoutMs: 3e4,
477
+ totalTimeoutMs: 12e4
478
+ });
479
+ function resolveCommonConfig(options, defaultUrl) {
480
+ const out = {
481
+ url: options.url ?? defaultUrl,
482
+ connectTimeoutMs: options.connectTimeoutMs ?? DEFAULT_TIMEOUTS.connectTimeoutMs,
483
+ requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_TIMEOUTS.requestTimeoutMs,
484
+ totalTimeoutMs: options.totalTimeoutMs ?? DEFAULT_TIMEOUTS.totalTimeoutMs,
485
+ retry: RetryPolicy.from(options.retry),
486
+ tls: Object.freeze({ ...options.tls }),
487
+ headers: Object.freeze({ ...options.headers })
488
+ };
489
+ if (options.proxy !== void 0) out.proxy = options.proxy;
490
+ if (options.userAgentSuffix !== void 0) out.userAgentSuffix = options.userAgentSuffix;
491
+ if (options.hooks !== void 0) out.hooks = options.hooks;
492
+ if (options.logger !== void 0) out.logger = options.logger;
493
+ return out;
494
+ }
495
+ function isHttpUrl(value) {
496
+ try {
497
+ const u = new URL(value);
498
+ return u.protocol === "http:" || u.protocol === "https:";
499
+ } catch {
500
+ return false;
501
+ }
502
+ }
503
+ function validateCommonConfig(config) {
504
+ const problems = [];
505
+ if (!isHttpUrl(config.url)) problems.push("url must be an http or https URL");
506
+ for (const key of ["connectTimeoutMs", "requestTimeoutMs", "totalTimeoutMs"]) {
507
+ const v = config[key];
508
+ if (!Number.isFinite(v) || v <= 0) problems.push(`${key} must be a positive number`);
509
+ }
510
+ problems.push(...config.retry.problems());
511
+ const tls = config.tls;
512
+ if (tls.clientCertPath === void 0 !== (tls.clientKeyPath === void 0)) {
513
+ problems.push("tls.clientCertPath and tls.clientKeyPath must be given together");
514
+ }
515
+ if (config.proxy !== void 0 && !isHttpUrl(config.proxy)) {
516
+ problems.push("proxy must be an http or https URL");
517
+ }
518
+ if (problems.length > 0) throw new ConfigError(`invalid configuration: ${problems.join("; ")}`);
519
+ }
520
+ function readCommonEnv(reader, vendor = {}) {
521
+ const out = {};
522
+ const url = reader.string("URL", vendor.url);
523
+ if (url !== void 0) out.url = url;
524
+ const connect = reader.duration("CONNECT_TIMEOUT");
525
+ if (connect !== void 0) out.connectTimeoutMs = connect;
526
+ const request = reader.duration("REQUEST_TIMEOUT");
527
+ if (request !== void 0) out.requestTimeoutMs = request;
528
+ const total = reader.duration("TOTAL_TIMEOUT");
529
+ if (total !== void 0) out.totalTimeoutMs = total;
530
+ const maxRetries = reader.int("MAX_RETRIES");
531
+ if (maxRetries !== void 0) out.retry = { maxRetries };
532
+ const tls = {};
533
+ const ca = reader.string("CA_CERT", vendor.caCert);
534
+ if (ca !== void 0) tls.caCertPath = ca;
535
+ const cert = reader.string("CLIENT_CERT", vendor.clientCert);
536
+ if (cert !== void 0) tls.clientCertPath = cert;
537
+ const key = reader.string("CLIENT_KEY", vendor.clientKey);
538
+ if (key !== void 0) tls.clientKeyPath = key;
539
+ const insecure = reader.bool("INSECURE_SKIP_VERIFY", vendor.insecureSkipVerify);
540
+ if (insecure !== void 0) tls.insecureSkipVerify = insecure;
541
+ if (Object.keys(tls).length > 0) out.tls = tls;
542
+ const proxy = reader.string("PROXY", vendor.proxy);
543
+ if (proxy !== void 0) out.proxy = proxy;
544
+ return out;
545
+ }
546
+ function definedOnly(value) {
547
+ const out = {};
548
+ for (const [k, v] of Object.entries(value)) {
549
+ if (v !== void 0) out[k] = v;
550
+ }
551
+ return out;
552
+ }
553
+ function mergeOptions(...layers) {
554
+ const out = {};
555
+ for (const layer of layers) {
556
+ if (layer === void 0) continue;
557
+ for (const [k, v] of Object.entries(definedOnly(layer))) {
558
+ const prev = out[k];
559
+ if ((k === "tls" || k === "headers" || k === "retry" && !(v instanceof RetryPolicy)) && typeof prev === "object" && prev !== null) {
560
+ const base = prev instanceof RetryPolicy ? prev.toJSON() : prev;
561
+ out[k] = { ...base, ...definedOnly(v) };
562
+ } else {
563
+ out[k] = v;
564
+ }
565
+ }
566
+ }
567
+ return out;
568
+ }
569
+ function describeCommonConfig(config) {
570
+ const headers = {};
571
+ for (const k of Object.keys(config.headers)) headers[k] = REDACTED;
572
+ const out = {
573
+ url: redactUrl(config.url),
574
+ connectTimeoutMs: config.connectTimeoutMs,
575
+ requestTimeoutMs: config.requestTimeoutMs,
576
+ totalTimeoutMs: config.totalTimeoutMs,
577
+ retry: config.retry.toJSON(),
578
+ tls: {
579
+ ...config.tls,
580
+ ...config.tls.caCertPem === void 0 ? {} : { caCertPem: REDACTED }
581
+ },
582
+ headers
583
+ };
584
+ if (config.proxy !== void 0) out.proxy = redactUrl(config.proxy);
585
+ if (config.userAgentSuffix !== void 0) out.userAgentSuffix = config.userAgentSuffix;
586
+ return out;
587
+ }
588
+ function secretValues(...values) {
589
+ return values.filter((v) => v instanceof Secret).map((s) => s.reveal());
590
+ }
591
+
592
+ // src/core/version.ts
593
+ var SDK_VERSION = "0.1.0";
594
+ var PACKAGE_KEY = "grafana-loki";
595
+ var LANGUAGE = "typescript";
596
+ var SDK_KIT_VERSION = "0.2.0";
597
+
598
+ // src/core/transport.ts
599
+ var DEFAULT_REQUEST_ID_HEADERS = [
600
+ "x-request-id",
601
+ "x-amzn-requestid",
602
+ "x-amz-request-id",
603
+ "x-datadog-request-id",
604
+ "request-id",
605
+ "x-correlation-id"
606
+ ];
607
+ var MAX_VENDOR_TEXT = 300;
608
+ var PRE_SEND_CODES = /* @__PURE__ */ new Set([
609
+ "ECONNREFUSED",
610
+ "ENOTFOUND",
611
+ "EAI_AGAIN",
612
+ "EHOSTUNREACH",
613
+ "ENETUNREACH",
614
+ "EADDRNOTAVAIL",
615
+ "UND_ERR_CONNECT_TIMEOUT"
616
+ ]);
617
+ var TLS_CODE = /CERT|SELF_SIGNED|UNABLE_TO_|ERR_TLS|ERR_SSL|DEPTH_ZERO/;
618
+ var CANCEL = /* @__PURE__ */ Symbol("cancel");
619
+ var ATTEMPT_TIMEOUT = /* @__PURE__ */ Symbol("attempt-timeout");
620
+ var insecureWarned = false;
621
+ var AbortedAttempt = class extends Error {
622
+ kind;
623
+ constructor(kind) {
624
+ super("aborted");
625
+ this.kind = kind;
626
+ }
627
+ };
628
+ function errorCode(err) {
629
+ let current = err;
630
+ for (let depth = 0; depth < 5 && current !== void 0 && current !== null; depth++) {
631
+ const code = current.code;
632
+ if (typeof code === "string") return code;
633
+ current = current.cause;
634
+ }
635
+ return void 0;
636
+ }
637
+ function readPem(path) {
638
+ return path === void 0 ? void 0 : readFileSync(path, "utf8");
639
+ }
640
+ function createDispatcher(config, logger = safeLogger(config.logger)) {
641
+ const tls = config.tls;
642
+ if (tls.insecureSkipVerify === true && !insecureWarned) {
643
+ insecureWarned = true;
644
+ logger.warn("TLS certificate verification is disabled (insecureSkipVerify); use only in tests");
645
+ }
646
+ const caParts = [tls.caCertPem, readPem(tls.caCertPath)].filter(
647
+ (v) => v !== void 0
648
+ );
649
+ const tlsOptions2 = {
650
+ timeout: config.connectTimeoutMs,
651
+ rejectUnauthorized: tls.insecureSkipVerify !== true,
652
+ ...caParts.length > 0 ? { ca: caParts } : {},
653
+ ...tls.clientCertPath === void 0 ? {} : { cert: readPem(tls.clientCertPath) },
654
+ ...tls.clientKeyPath === void 0 ? {} : { key: readPem(tls.clientKeyPath) }
655
+ };
656
+ if (config.proxy !== void 0) {
657
+ return new ProxyAgent({
658
+ uri: config.proxy,
659
+ connect: { timeout: config.connectTimeoutMs },
660
+ requestTls: tlsOptions2
661
+ });
662
+ }
663
+ return new Agent({ connect: tlsOptions2 });
664
+ }
665
+ var HttpTransport = class {
666
+ /** `grow-codes-<key>/<version> (typescript)[ <suffix>]`. */
667
+ userAgent;
668
+ retry;
669
+ #config;
670
+ #options;
671
+ #logger;
672
+ #hooks;
673
+ #fetch;
674
+ #sleep;
675
+ #now;
676
+ #requestIdHeaders;
677
+ #dispatcher;
678
+ #closed = false;
679
+ constructor(options) {
680
+ this.#options = options;
681
+ this.#config = options.config;
682
+ this.retry = options.config.retry;
683
+ this.#logger = safeLogger(options.config.logger);
684
+ this.#hooks = options.config.hooks ?? {};
685
+ this.#fetch = fetch;
686
+ this.#sleep = options.sleep ?? sleep;
687
+ this.#now = options.now ?? Date.now;
688
+ this.#requestIdHeaders = options.requestIdHeaders ?? DEFAULT_REQUEST_ID_HEADERS;
689
+ this.#dispatcher = options.dispatcher;
690
+ const suffix = options.config.userAgentSuffix;
691
+ this.userAgent = `grow-codes-${PACKAGE_KEY}/${SDK_VERSION} (${LANGUAGE})` + (suffix !== void 0 && suffix !== "" ? ` ${suffix}` : "");
692
+ }
693
+ /** Whether {@link close} was called. */
694
+ get closed() {
695
+ return this.#closed;
696
+ }
697
+ /** Builds the absolute URL for a path and query. */
698
+ buildUrl(path, query) {
699
+ let url;
700
+ if (/^https?:\/\//i.test(path)) {
701
+ url = new URL(path);
702
+ } else {
703
+ const base = this.#config.url.endsWith("/") ? this.#config.url : this.#config.url + "/";
704
+ url = new URL(path.replace(/^\/+/, ""), base);
705
+ }
706
+ for (const [k, v] of Object.entries(query ?? {})) {
707
+ if (v === void 0 || v === null) continue;
708
+ if (Array.isArray(v)) {
709
+ for (const item of v)
710
+ url.searchParams.append(k, String(item));
711
+ } else {
712
+ url.searchParams.append(k, String(v));
713
+ }
714
+ }
715
+ return url;
716
+ }
717
+ /** Redacts known secrets from a text (error messages, vendor text). */
718
+ redact(text) {
719
+ return redactText(text, this.#knownSecrets());
720
+ }
721
+ #knownSecrets() {
722
+ return [...this.#options.knownSecrets?.() ?? []];
723
+ }
724
+ #getDispatcher() {
725
+ this.#dispatcher ??= createDispatcher(this.#config, this.#logger);
726
+ return this.#dispatcher;
727
+ }
728
+ /** `GET` shortcut. */
729
+ get(path, options = {}) {
730
+ return this.request({ ...options, method: "GET", path });
731
+ }
732
+ /** `POST` shortcut. */
733
+ post(path, options = {}) {
734
+ return this.request({ ...options, method: "POST", path });
735
+ }
736
+ /** `PUT` shortcut. */
737
+ put(path, options = {}) {
738
+ return this.request({ ...options, method: "PUT", path });
739
+ }
740
+ /** `DELETE` shortcut. */
741
+ delete(path, options = {}) {
742
+ return this.request({ ...options, method: "DELETE", path });
743
+ }
744
+ /**
745
+ * Sends a request with retries; throws an SDK error on failure. Every error message passes
746
+ * through {@link redact} with the known secrets.
747
+ */
748
+ async request(options) {
749
+ try {
750
+ return await this.#request(options);
751
+ } catch (err) {
752
+ if (err instanceof LokiError) err.message = this.redact(err.message);
753
+ throw err;
754
+ }
755
+ }
756
+ async #request(options) {
757
+ const method = (options.method ?? "GET").toUpperCase();
758
+ const operation = options.operation ?? `${method} ${options.path.split("?")[0] ?? ""}`;
759
+ if (this.#closed) throw new CancelledError(`${operation}: client is closed`);
760
+ const signal = options.signal;
761
+ if (signal?.aborted === true) throw new CancelledError(`${operation}: cancelled`);
762
+ const url = this.buildUrl(options.path, options.query);
763
+ const safeUrl = redactUrl(url);
764
+ const headers = this.#buildHeaders(options);
765
+ const body = options.json !== void 0 ? JSON.stringify(options.json) : options.body;
766
+ const idempotent = options.idempotent ?? isIdempotentMethod(method);
767
+ const requestTimeout = options.requestTimeoutMs ?? this.#config.requestTimeoutMs;
768
+ const totalTimeout = options.totalTimeoutMs ?? this.#config.totalTimeoutMs;
769
+ const start = this.#now();
770
+ const deadline = start + totalTimeout;
771
+ const policy = this.retry;
772
+ for (let attempt = 1; ; attempt++) {
773
+ const remaining = deadline - this.#now();
774
+ if (remaining <= 0) {
775
+ throw new TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`);
776
+ }
777
+ const attemptTimeout = Math.min(requestTimeout, remaining);
778
+ const isTotal = attemptTimeout < requestTimeout;
779
+ safeCall(this.#hooks.onRequest, {
780
+ method,
781
+ url: safeUrl,
782
+ headers: redactHeaders(headers),
783
+ attempt
784
+ });
785
+ this.#logger.debug("http request", { method, url: safeUrl, attempt });
786
+ const attemptStart = this.#now();
787
+ let failure;
788
+ let willRetry = false;
789
+ let waitMs = 0;
790
+ try {
791
+ const res = await this.#attempt(
792
+ url,
793
+ method,
794
+ headers,
795
+ body,
796
+ attemptTimeout,
797
+ signal,
798
+ options.responseType ?? "json",
799
+ options.allowStatus ?? []
800
+ );
801
+ const durationMs = this.#now() - attemptStart;
802
+ const requestId = this.#requestId(res.headers);
803
+ safeCall(this.#hooks.onResponse, {
804
+ method,
805
+ url: safeUrl,
806
+ status: res.status,
807
+ durationMs,
808
+ attempt,
809
+ ...requestId === void 0 ? {} : { requestId }
810
+ });
811
+ this.#logger.debug("http response", {
812
+ method,
813
+ url: safeUrl,
814
+ status: res.status,
815
+ durationMs,
816
+ attempt
817
+ });
818
+ if (res.status < 400 || options.allowStatus?.includes(res.status) === true) {
819
+ return {
820
+ status: res.status,
821
+ headers: res.headers,
822
+ data: res.data,
823
+ ...requestId === void 0 ? {} : { requestId },
824
+ durationMs: this.#now() - start,
825
+ attempts: attempt,
826
+ ...res.status >= 400 ? { text: res.text } : {}
827
+ };
828
+ }
829
+ const retryAfter = res.status === 429 || res.status === 503 ? parseRetryAfter(res.headers.get("retry-after"), this.#now()) : void 0;
830
+ const reason = this.vendorText(res.text);
831
+ const defaultError = errorForStatus(operation, res.status, {
832
+ ...reason === void 0 ? {} : { reason },
833
+ ...requestId === void 0 ? {} : { requestId },
834
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter }
835
+ });
836
+ const classified = this.#classifyResponse(options.classifyError, {
837
+ operation,
838
+ method,
839
+ status: res.status,
840
+ headers: res.headers,
841
+ body: res.text,
842
+ ...reason === void 0 ? {} : { reason },
843
+ ...requestId === void 0 ? {} : { requestId },
844
+ ...retryAfter === void 0 ? {} : { retryAfterMs: retryAfter },
845
+ attempt,
846
+ defaultError
847
+ });
848
+ failure = classified ?? defaultError;
849
+ if (isRetryableStatus(res.status, idempotent) && (classified === void 0 || classified.retryable) && attempt <= policy.maxRetries) {
850
+ const backoff = policy.backoffMs(attempt - 1);
851
+ if (retryAfter !== void 0) {
852
+ if (retryAfter > policy.maxRetryAfterMs || retryAfter >= deadline - this.#now()) {
853
+ willRetry = false;
854
+ } else {
855
+ willRetry = true;
856
+ waitMs = Math.max(retryAfter, backoff);
857
+ }
858
+ } else {
859
+ willRetry = true;
860
+ waitMs = backoff;
861
+ }
862
+ }
863
+ } catch (err) {
864
+ failure = this.#classify(err, operation, attemptTimeout, isTotal, totalTimeout);
865
+ const preSend = PRE_SEND_CODES.has(errorCode(err) ?? "");
866
+ willRetry = failure.retryable && !(failure.code === "TIMEOUT" && isTotal) && (idempotent || preSend) && attempt <= policy.maxRetries;
867
+ waitMs = willRetry ? policy.backoffMs(attempt - 1) : 0;
868
+ }
869
+ if (willRetry && waitMs >= deadline - this.#now()) {
870
+ safeCall(this.#hooks.onError, {
871
+ method,
872
+ url: safeUrl,
873
+ error: failure,
874
+ attempt,
875
+ willRetry: false
876
+ });
877
+ throw new TimeoutError(
878
+ `${operation}: total timeout of ${totalTimeout} ms exceeded after ${attempt} attempts`,
879
+ {
880
+ cause: failure,
881
+ ...failure.httpStatus === void 0 ? {} : { httpStatus: failure.httpStatus },
882
+ ...failure.requestId === void 0 ? {} : { requestId: failure.requestId }
883
+ }
884
+ );
885
+ }
886
+ safeCall(this.#hooks.onError, { method, url: safeUrl, error: failure, attempt, willRetry });
887
+ if (!willRetry) {
888
+ this.#logger.debug("http call failed", {
889
+ method,
890
+ url: safeUrl,
891
+ attempt,
892
+ code: failure.code
893
+ });
894
+ throw failure;
895
+ }
896
+ this.#logger.warn("http call failed, retrying", {
897
+ method,
898
+ url: safeUrl,
899
+ attempt,
900
+ code: failure.code,
901
+ waitMs: Math.round(waitMs)
902
+ });
903
+ await this.#sleep(waitMs, signal).catch((err) => {
904
+ throw err instanceof LokiError ? err : new CancelledError(`${operation}: cancelled`);
905
+ });
906
+ }
907
+ }
908
+ #buildHeaders(options) {
909
+ const headers = {
910
+ accept: "application/json",
911
+ "user-agent": this.userAgent
912
+ };
913
+ const layers = [
914
+ this.#config.headers,
915
+ this.#options.defaultHeaders?.() ?? {},
916
+ options.headers ?? {}
917
+ ];
918
+ for (const layer of layers) {
919
+ for (const [k, v] of Object.entries(layer)) headers[k.toLowerCase()] = v;
920
+ }
921
+ if (options.json !== void 0 && headers["content-type"] === void 0) {
922
+ headers["content-type"] = "application/json";
923
+ }
924
+ return headers;
925
+ }
926
+ async #attempt(url, method, headers, body, timeoutMs, signal, responseType, allowStatus) {
927
+ const controller = new AbortController();
928
+ const timer = setTimeout(() => {
929
+ controller.abort(ATTEMPT_TIMEOUT);
930
+ }, timeoutMs);
931
+ timer.unref();
932
+ const onAbort = () => {
933
+ controller.abort(CANCEL);
934
+ };
935
+ signal?.addEventListener("abort", onAbort, { once: true });
936
+ try {
937
+ const init = {
938
+ method,
939
+ headers,
940
+ signal: controller.signal,
941
+ dispatcher: this.#getDispatcher(),
942
+ redirect: "follow"
943
+ };
944
+ if (body !== void 0) init.body = body;
945
+ const res = await this.#fetch(url, init);
946
+ const bytes = new Uint8Array(await res.arrayBuffer());
947
+ const isError = res.status >= 400;
948
+ const allowed = isError && allowStatus.includes(res.status);
949
+ const text = isError || responseType === "json" || responseType === "text" ? new TextDecoder().decode(bytes) : "";
950
+ let data;
951
+ if (isError && !allowed || responseType === "none") {
952
+ data = void 0;
953
+ } else if (responseType === "bytes") {
954
+ data = bytes;
955
+ } else if (responseType === "text") {
956
+ data = text;
957
+ } else if (allowed) {
958
+ data = parseJsonOrUndefined(text);
959
+ } else {
960
+ data = this.#parseJson(text, res.status);
961
+ }
962
+ return { status: res.status, headers: res.headers, data, text };
963
+ } catch (err) {
964
+ const reason = controller.signal.reason;
965
+ if (controller.signal.aborted && (reason === CANCEL || reason === ATTEMPT_TIMEOUT)) {
966
+ throw new AbortedAttempt(reason);
967
+ }
968
+ throw err;
969
+ } finally {
970
+ clearTimeout(timer);
971
+ signal?.removeEventListener("abort", onAbort);
972
+ }
973
+ }
974
+ #parseJson(text, status) {
975
+ if (text.trim() === "") return void 0;
976
+ try {
977
+ return JSON.parse(text);
978
+ } catch {
979
+ throw new UnavailableError(`invalid JSON in response (HTTP ${status})`, {
980
+ retryable: false,
981
+ httpStatus: status
982
+ });
983
+ }
984
+ }
985
+ #classify(err, operation, timeoutMs, isTotal, totalTimeout) {
986
+ if (err instanceof LokiError) return err;
987
+ if (err instanceof AbortedAttempt) {
988
+ if (err.kind === CANCEL) return new CancelledError(`${operation}: cancelled`);
989
+ return isTotal ? new TimeoutError(`${operation}: total timeout of ${totalTimeout} ms exceeded`) : new TimeoutError(`${operation}: request timed out after ${timeoutMs} ms`);
990
+ }
991
+ const cause = redactError(err, this.#knownSecrets());
992
+ const code = errorCode(err);
993
+ if (code === "UND_ERR_CONNECT_TIMEOUT") {
994
+ return new TimeoutError(
995
+ `${operation}: connect timeout after ${this.#config.connectTimeoutMs} ms`,
996
+ { cause }
997
+ );
998
+ }
999
+ if (code !== void 0 && TLS_CODE.test(code)) {
1000
+ return new UnavailableError(`${operation}: TLS error (${code})`, { cause, retryable: false });
1001
+ }
1002
+ return new UnavailableError(
1003
+ `${operation}: network error${code === void 0 ? "" : ` (${code})`}`,
1004
+ { cause }
1005
+ );
1006
+ }
1007
+ #classifyResponse(perRequest, response) {
1008
+ for (const classify of [perRequest, this.#options.classifyError]) {
1009
+ if (classify === void 0) continue;
1010
+ let mapped;
1011
+ try {
1012
+ mapped = classify(response);
1013
+ } catch (err) {
1014
+ mapped = err instanceof LokiError ? err : void 0;
1015
+ }
1016
+ if (mapped instanceof LokiError) return mapped;
1017
+ }
1018
+ return void 0;
1019
+ }
1020
+ /**
1021
+ * Extracts the vendor error message from a response body (JSON `message`, `error`, … or plain
1022
+ * text; HTML is ignored), collapses whitespace, trims, redacts secrets and truncates it to
1023
+ * {@link MAX_VENDOR_TEXT} characters. Returns `undefined` when there is nothing useful.
1024
+ */
1025
+ vendorText(text) {
1026
+ const trimmed = text.trim();
1027
+ if (trimmed === "") return void 0;
1028
+ let extracted;
1029
+ try {
1030
+ extracted = extractMessage(JSON.parse(trimmed));
1031
+ } catch {
1032
+ extracted = /^\s*</.test(trimmed) ? void 0 : trimmed;
1033
+ }
1034
+ const collapsed = extracted?.replace(/\s+/g, " ").trim();
1035
+ if (collapsed === void 0 || collapsed === "") return void 0;
1036
+ const redacted = redactSecretsInText(this.redact(collapsed));
1037
+ return redacted.length > MAX_VENDOR_TEXT ? redacted.slice(0, MAX_VENDOR_TEXT - 1).trimEnd() + "\u2026" : redacted;
1038
+ }
1039
+ #requestId(headers) {
1040
+ for (const name of this.#requestIdHeaders) {
1041
+ const v = headers.get(name);
1042
+ if (v !== null && v !== "") return v;
1043
+ }
1044
+ return void 0;
1045
+ }
1046
+ /** Releases connections. Idempotent. */
1047
+ async close() {
1048
+ if (this.#closed) return;
1049
+ this.#closed = true;
1050
+ const dispatcher = this.#dispatcher;
1051
+ this.#dispatcher = void 0;
1052
+ if (dispatcher !== void 0 && this.#options.dispatcher === void 0) {
1053
+ await dispatcher.close().catch(() => void 0);
1054
+ }
1055
+ }
1056
+ };
1057
+ function parseJsonOrUndefined(text) {
1058
+ if (text.trim() === "") return void 0;
1059
+ try {
1060
+ return JSON.parse(text);
1061
+ } catch {
1062
+ return void 0;
1063
+ }
1064
+ }
1065
+ function extractMessage(body) {
1066
+ if (typeof body === "string") return body;
1067
+ if (body === null || typeof body !== "object") return void 0;
1068
+ if (Array.isArray(body)) return body.length > 0 ? extractMessage(body[0]) : void 0;
1069
+ const obj = body;
1070
+ for (const key of [
1071
+ "message",
1072
+ "error_description",
1073
+ "error",
1074
+ "errors",
1075
+ "detail",
1076
+ "msg",
1077
+ "title",
1078
+ "reason"
1079
+ ]) {
1080
+ const found = extractMessage(obj[key]);
1081
+ if (found !== void 0 && found !== "") return found;
1082
+ }
1083
+ return void 0;
1084
+ }
1085
+ var SECRET_ASSIGNMENT = /((?:password|passwd|secret|token|authorization|api[_-]?key|access[_-]?key|private[_-]?key|credential|session|signature)["']?\s*[:=]\s*["']?)([^"'\s,;&}]+)/gi;
1086
+ var BEARER = /\b(bearer|basic)\s+[A-Za-z0-9._~+/=-]+/gi;
1087
+ function redactSecretsInText(text) {
1088
+ return text.replace(BEARER, "$1 [REDACTED]").replace(SECRET_ASSIGNMENT, "$1[REDACTED]");
1089
+ }
1090
+
1091
+ // src/config.ts
1092
+ var INSPECT2 = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
1093
+ var CATALOG_PORT = "3100";
1094
+ var MAX_TENANT_ID_LENGTH = 150;
1095
+ var TENANT_CHARS = /^[A-Za-z0-9!\-_.*'()]+$/;
1096
+ var LABEL_NAME = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
1097
+ function tenantIdProblem(id, multiTenantQueries = false) {
1098
+ if (id.includes("|")) {
1099
+ if (!multiTenantQueries) {
1100
+ return "tenant id must not contain '|' (multi-tenant queries are not enabled)";
1101
+ }
1102
+ for (const part of id.split("|")) {
1103
+ const problem = tenantIdProblem(part, false);
1104
+ if (problem !== void 0) return problem;
1105
+ }
1106
+ return void 0;
1107
+ }
1108
+ if (id === "") return "tenant id must not be empty";
1109
+ if (new TextEncoder().encode(id).length > MAX_TENANT_ID_LENGTH) {
1110
+ return `tenant id is too long (max ${MAX_TENANT_ID_LENGTH} bytes)`;
1111
+ }
1112
+ if (id === "." || id === "..") return "tenant id must not be '.' or '..'";
1113
+ if (!TENANT_CHARS.test(id)) {
1114
+ return "tenant id may only contain letters, digits and !-_.*'()";
1115
+ }
1116
+ return void 0;
1117
+ }
1118
+ var VENDOR_ENV = {
1119
+ url: ["LOKI_URL"],
1120
+ tenantId: ["LOKI_TENANT_ID"],
1121
+ username: ["LOKI_USERNAME", "LOKI_BASIC_AUTH_USER"],
1122
+ password: ["LOKI_PASSWORD", "LOKI_BASIC_AUTH_PASSWORD"],
1123
+ bearerToken: ["LOKI_BEARER_TOKEN"]
1124
+ };
1125
+ var LokiConfig = class _LokiConfig {
1126
+ /** Default endpoint. */
1127
+ static DEFAULT_URL = `http://127.0.0.1:${/\d+/.exec(CATALOG_PORT)?.[0] ?? "8080"}`;
1128
+ /** Prefix of every environment variable. */
1129
+ static ENV_PREFIX = "GROW_GRAFANA_LOKI_";
1130
+ url;
1131
+ connectTimeoutMs;
1132
+ requestTimeoutMs;
1133
+ totalTimeoutMs;
1134
+ retry;
1135
+ tls;
1136
+ proxy;
1137
+ headers;
1138
+ userAgentSuffix;
1139
+ hooks;
1140
+ logger;
1141
+ /** Tenant (`X-Scope-OrgID`); not sent when unset. */
1142
+ tenantId;
1143
+ /** Basic-auth user. */
1144
+ username;
1145
+ /** Basic-auth password. */
1146
+ password;
1147
+ /** Bearer token. */
1148
+ bearerToken;
1149
+ /** Whether tenant ids joined with `|` are allowed. */
1150
+ multiTenantQueries;
1151
+ /** Configured cardinality guard allowlist (`undefined` = `DEFAULT_ALLOWED_LABELS`). */
1152
+ allowedLabels;
1153
+ /** Whether `push` skips the cardinality guard. */
1154
+ disableLabelGuard;
1155
+ /** Applies defaults, validates (throws {@link ConfigError}) and freezes. */
1156
+ constructor(options = {}) {
1157
+ const common = resolveCommonConfig(options, _LokiConfig.DEFAULT_URL);
1158
+ this.url = common.url;
1159
+ this.connectTimeoutMs = common.connectTimeoutMs;
1160
+ this.requestTimeoutMs = common.requestTimeoutMs;
1161
+ this.totalTimeoutMs = common.totalTimeoutMs;
1162
+ this.retry = common.retry;
1163
+ this.tls = common.tls;
1164
+ this.headers = common.headers;
1165
+ if (common.proxy !== void 0) this.proxy = common.proxy;
1166
+ if (common.userAgentSuffix !== void 0) this.userAgentSuffix = common.userAgentSuffix;
1167
+ if (common.hooks !== void 0) this.hooks = common.hooks;
1168
+ if (common.logger !== void 0) this.logger = common.logger;
1169
+ if (options.tenantId !== void 0 && options.tenantId !== "") this.tenantId = options.tenantId;
1170
+ if (options.username !== void 0 && options.username !== "") this.username = options.username;
1171
+ const password = Secret.from(options.password);
1172
+ if (password !== void 0) this.password = password;
1173
+ const bearer = Secret.from(options.bearerToken);
1174
+ if (bearer !== void 0) this.bearerToken = bearer;
1175
+ this.multiTenantQueries = options.multiTenantQueries ?? false;
1176
+ if (options.allowedLabels !== void 0) {
1177
+ this.allowedLabels = Object.freeze([...options.allowedLabels]);
1178
+ }
1179
+ this.disableLabelGuard = options.disableLabelGuard ?? false;
1180
+ this.validate();
1181
+ Object.freeze(this);
1182
+ }
1183
+ /** Returns `options` when it already is a config, otherwise builds one. */
1184
+ static from(options = {}) {
1185
+ if (options instanceof _LokiConfig) return options;
1186
+ return new _LokiConfig(options);
1187
+ }
1188
+ /**
1189
+ * Builds a config from the environment. Precedence: explicit `overrides` >
1190
+ * `GROW_GRAFANA_LOKI_<NAME>` > vendor variables ({@link VENDOR_ENV}) > defaults.
1191
+ */
1192
+ static fromEnv(overrides = {}, env = process.env) {
1193
+ const reader = new EnvReader(_LokiConfig.ENV_PREFIX, env);
1194
+ const fromEnv = readCommonEnv(reader, VENDOR_ENV);
1195
+ const tenantId = reader.string("TENANT_ID", VENDOR_ENV.tenantId);
1196
+ if (tenantId !== void 0) fromEnv.tenantId = tenantId;
1197
+ const username = reader.string("USERNAME", VENDOR_ENV.username);
1198
+ if (username !== void 0) fromEnv.username = username;
1199
+ const password = reader.secret("PASSWORD", VENDOR_ENV.password);
1200
+ if (password !== void 0) fromEnv.password = password;
1201
+ const bearer = reader.secret("BEARER_TOKEN", VENDOR_ENV.bearerToken);
1202
+ if (bearer !== void 0) fromEnv.bearerToken = bearer;
1203
+ const merged = mergeOptions(fromEnv, overrides);
1204
+ return new _LokiConfig(merged);
1205
+ }
1206
+ /** A copy of this config with some fields replaced (validated again). */
1207
+ with(overrides) {
1208
+ const current = {
1209
+ url: this.url,
1210
+ connectTimeoutMs: this.connectTimeoutMs,
1211
+ requestTimeoutMs: this.requestTimeoutMs,
1212
+ totalTimeoutMs: this.totalTimeoutMs,
1213
+ retry: this.retry,
1214
+ tls: { ...this.tls },
1215
+ headers: { ...this.headers },
1216
+ ...this.proxy === void 0 ? {} : { proxy: this.proxy },
1217
+ ...this.userAgentSuffix === void 0 ? {} : { userAgentSuffix: this.userAgentSuffix },
1218
+ ...this.hooks === void 0 ? {} : { hooks: this.hooks },
1219
+ ...this.logger === void 0 ? {} : { logger: this.logger },
1220
+ ...this.tenantId === void 0 ? {} : { tenantId: this.tenantId },
1221
+ ...this.username === void 0 ? {} : { username: this.username },
1222
+ ...this.password === void 0 ? {} : { password: this.password },
1223
+ ...this.bearerToken === void 0 ? {} : { bearerToken: this.bearerToken },
1224
+ multiTenantQueries: this.multiTenantQueries,
1225
+ ...this.allowedLabels === void 0 ? {} : { allowedLabels: this.allowedLabels },
1226
+ disableLabelGuard: this.disableLabelGuard
1227
+ };
1228
+ return new _LokiConfig({ ...current, ...overrides });
1229
+ }
1230
+ /** Throws {@link ConfigError} when a setting is invalid. */
1231
+ validate() {
1232
+ validateCommonConfig(this);
1233
+ const problems = [];
1234
+ if (this.tenantId !== void 0) {
1235
+ const problem = tenantIdProblem(this.tenantId, this.multiTenantQueries);
1236
+ if (problem !== void 0) problems.push(problem);
1237
+ }
1238
+ for (const name of this.allowedLabels ?? []) {
1239
+ if (!LABEL_NAME.test(name) || name.startsWith("__")) {
1240
+ problems.push(`allowedLabels contains an invalid label name ${JSON.stringify(name)}`);
1241
+ }
1242
+ }
1243
+ if (this.username === void 0 !== (this.password === void 0)) {
1244
+ problems.push("username and password must be given together");
1245
+ }
1246
+ if (this.password !== void 0 && this.bearerToken !== void 0) {
1247
+ problems.push("basic auth (username/password) and bearerToken are mutually exclusive");
1248
+ }
1249
+ if (this.bearerToken?.reveal().trim() === "") problems.push("bearerToken must not be blank");
1250
+ if (problems.length > 0) {
1251
+ throw new ConfigError(`invalid configuration: ${problems.join("; ")}`);
1252
+ }
1253
+ }
1254
+ /** The `Authorization` header value, when credentials are configured. */
1255
+ authorizationHeader() {
1256
+ if (this.bearerToken !== void 0) return `Bearer ${this.bearerToken.reveal()}`;
1257
+ if (this.username !== void 0 && this.password !== void 0) {
1258
+ return `Basic ${basicCredentials(this.username, this.password.reveal())}`;
1259
+ }
1260
+ return void 0;
1261
+ }
1262
+ /** Credential values to redact from error messages and logs. */
1263
+ knownSecrets() {
1264
+ const out = secretValues(this.password, this.bearerToken);
1265
+ if (this.username !== void 0 && this.password !== void 0) {
1266
+ out.push(basicCredentials(this.username, this.password.reveal()));
1267
+ }
1268
+ return out;
1269
+ }
1270
+ /** Debug form with every credential redacted. */
1271
+ toJSON() {
1272
+ return {
1273
+ ...describeCommonConfig(this),
1274
+ tenantId: this.tenantId ?? null,
1275
+ username: this.username ?? null,
1276
+ password: this.password === void 0 ? null : REDACTED,
1277
+ bearerToken: this.bearerToken === void 0 ? null : REDACTED,
1278
+ multiTenantQueries: this.multiTenantQueries,
1279
+ allowedLabels: this.allowedLabels ?? null,
1280
+ disableLabelGuard: this.disableLabelGuard
1281
+ };
1282
+ }
1283
+ toString() {
1284
+ return `LokiConfig(${JSON.stringify(this.toJSON())})`;
1285
+ }
1286
+ [INSPECT2]() {
1287
+ return this.toString();
1288
+ }
1289
+ };
1290
+ function basicCredentials(username, password) {
1291
+ return Buffer.from(`${username}:${password}`, "utf8").toString("base64");
1292
+ }
1293
+
1294
+ // src/logging/redaction.ts
1295
+ var DEFAULT_REDACT_KEYS = Object.freeze([
1296
+ "password",
1297
+ "passwd",
1298
+ "token",
1299
+ "authorization",
1300
+ "secret",
1301
+ "cookie",
1302
+ "api_key",
1303
+ "apikey",
1304
+ "access_key",
1305
+ "private_key"
1306
+ ]);
1307
+ var RedactionProcessor = class {
1308
+ #keys;
1309
+ #patterns;
1310
+ #replacement;
1311
+ constructor(options = {}) {
1312
+ this.#keys = (options.keys ?? DEFAULT_REDACT_KEYS).map((k) => k.toLowerCase()).filter((k) => k !== "");
1313
+ this.#patterns = (options.patterns ?? []).map(
1314
+ (p) => p.flags.includes("g") ? new RegExp(p.source, p.flags) : new RegExp(p.source, `${p.flags}g`)
1315
+ );
1316
+ this.#replacement = options.replacement ?? "[REDACTED]";
1317
+ }
1318
+ /** Returns a redacted copy of `record`; the input is not modified. */
1319
+ process(record) {
1320
+ return {
1321
+ ...record,
1322
+ body: this.redactText(record.body),
1323
+ attributes: this.redactAttributes(record.attributes)
1324
+ };
1325
+ }
1326
+ /** Whether an attribute name is sensitive. */
1327
+ isSensitiveKey(key) {
1328
+ const lower = key.toLowerCase();
1329
+ return this.#keys.some((k) => lower.includes(k));
1330
+ }
1331
+ /** Applies the patterns to `text`. */
1332
+ redactText(text) {
1333
+ let out = text;
1334
+ for (const pattern of this.#patterns) {
1335
+ pattern.lastIndex = 0;
1336
+ out = out.replace(pattern, this.#replacement);
1337
+ }
1338
+ return out;
1339
+ }
1340
+ /** Redacts an attribute map recursively. */
1341
+ redactAttributes(attributes) {
1342
+ const out = {};
1343
+ for (const [key, value] of Object.entries(attributes)) {
1344
+ out[key] = this.isSensitiveKey(key) ? this.#replacement : this.#redactValue(value);
1345
+ }
1346
+ return out;
1347
+ }
1348
+ #redactValue(value) {
1349
+ if (typeof value === "string") return this.redactText(value);
1350
+ if (Array.isArray(value)) return value.map((v) => this.#redactValue(v));
1351
+ if (typeof value === "object") return this.redactAttributes(value);
1352
+ return value;
1353
+ }
1354
+ };
1355
+
1356
+ // src/logging/batch.ts
1357
+ var DEFAULT_BATCH_OPTIONS = Object.freeze({
1358
+ maxQueueSize: 2048,
1359
+ maxBatchSize: 512,
1360
+ maxBatchBytes: 1048576,
1361
+ flushIntervalMs: 1e3,
1362
+ exportTimeoutMs: 3e4,
1363
+ dropPolicy: "drop_newest",
1364
+ gzip: true,
1365
+ maxExportRetries: 2,
1366
+ retryBackoffMs: 200
1367
+ });
1368
+ var POSITIVE = [
1369
+ "maxQueueSize",
1370
+ "maxBatchSize",
1371
+ "maxBatchBytes",
1372
+ "flushIntervalMs",
1373
+ "exportTimeoutMs"
1374
+ ];
1375
+ var NON_NEGATIVE = ["maxExportRetries", "retryBackoffMs"];
1376
+ function resolveBatchOptions(options = {}) {
1377
+ const defined = Object.fromEntries(Object.entries(options).filter(([, v]) => v !== void 0));
1378
+ const resolved = { ...DEFAULT_BATCH_OPTIONS, ...defined };
1379
+ for (const key of POSITIVE) {
1380
+ const v = resolved[key];
1381
+ if (!Number.isFinite(v) || v <= 0)
1382
+ throw new ConfigError(`logging.batch: ${key} must be a positive number`);
1383
+ }
1384
+ for (const key of NON_NEGATIVE) {
1385
+ const v = resolved[key];
1386
+ if (!Number.isFinite(v) || v < 0) throw new ConfigError(`logging.batch: ${key} must be >= 0`);
1387
+ }
1388
+ if (!["drop_newest", "drop_oldest", "block"].includes(resolved.dropPolicy)) {
1389
+ throw new ConfigError("logging.batch: dropPolicy must be drop_newest, drop_oldest or block");
1390
+ }
1391
+ return resolved;
1392
+ }
1393
+ function isRetryable(error) {
1394
+ return typeof error === "object" && error !== null && error.retryable === true;
1395
+ }
1396
+ var BatchProcessor = class {
1397
+ #exporter;
1398
+ #opts;
1399
+ #queue = [];
1400
+ #stop = new AbortController();
1401
+ #queuedBytes = 0;
1402
+ #inflight = 0;
1403
+ #enqueued = 0;
1404
+ #dequeued = 0;
1405
+ #forceUntil = 0;
1406
+ #sent = 0;
1407
+ #dropped = 0;
1408
+ #failed = 0;
1409
+ #retries = 0;
1410
+ #closed = false;
1411
+ #kickScheduled = false;
1412
+ #draining = null;
1413
+ #shutdown = null;
1414
+ #capacityWaiters = [];
1415
+ #timer;
1416
+ constructor(exporter, options = {}) {
1417
+ this.#exporter = exporter;
1418
+ this.#opts = resolveBatchOptions(options);
1419
+ this.#timer = setInterval(() => {
1420
+ this.#onTick();
1421
+ }, this.#opts.flushIntervalMs);
1422
+ this.#timer.unref();
1423
+ }
1424
+ /** The resolved options. */
1425
+ get options() {
1426
+ return this.#opts;
1427
+ }
1428
+ /** Enqueues a record. Returns false when it was dropped. Never blocks (see `dropPolicy`). */
1429
+ add(record) {
1430
+ if (this.#closed) {
1431
+ this.#drop([record], "shutdown");
1432
+ return false;
1433
+ }
1434
+ if (this.#queue.length >= this.#opts.maxQueueSize) {
1435
+ if (this.#opts.dropPolicy === "drop_newest") {
1436
+ this.#drop([record], "queue_full");
1437
+ return false;
1438
+ }
1439
+ if (this.#opts.dropPolicy === "drop_oldest") {
1440
+ const oldest = this.#queue.shift();
1441
+ this.#queuedBytes -= oldest.bytes;
1442
+ this.#dequeued += 1;
1443
+ this.#drop([oldest.record], "queue_full");
1444
+ } else {
1445
+ this.#forceUntil = Math.max(this.#forceUntil, this.#enqueued + 1);
1446
+ }
1447
+ }
1448
+ const bytes = logRecordByteSize(record);
1449
+ this.#queue.push({ record, bytes });
1450
+ this.#queuedBytes += bytes;
1451
+ this.#enqueued += 1;
1452
+ if (this.#queue.length >= this.#opts.maxBatchSize || this.#queuedBytes >= this.#opts.maxBatchBytes || this.#forceUntil > this.#dequeued) {
1453
+ this.#scheduleKick();
1454
+ }
1455
+ return true;
1456
+ }
1457
+ /**
1458
+ * Like {@link add}, but with `dropPolicy: "block"` waits until the queue has room first.
1459
+ * Resolves false when the record was dropped (for example because the processor shut down).
1460
+ */
1461
+ async addAsync(record) {
1462
+ while (this.#opts.dropPolicy === "block" && !this.#closed && this.#queue.length >= this.#opts.maxQueueSize) {
1463
+ this.#forceUntil = Math.max(this.#forceUntil, this.#enqueued);
1464
+ this.#scheduleKick();
1465
+ await new Promise((resolve) => this.#capacityWaiters.push(resolve));
1466
+ }
1467
+ return this.add(record);
1468
+ }
1469
+ /** Exports everything queued at the time of the call. Rejects with `TimeoutError` after `timeoutMs`. */
1470
+ async flush(timeoutMs = this.#opts.exportTimeoutMs) {
1471
+ if (this.#shutdown !== null) return this.#shutdown;
1472
+ await this.#withTimeout(this.#drainTo(this.#enqueued), timeoutMs, "logging.flush");
1473
+ }
1474
+ /**
1475
+ * Drains the queue (bounded by `timeoutMs`), drops what is left with reason `shutdown`, then shuts
1476
+ * the exporter down. Idempotent; later {@link add} calls drop with reason `shutdown`.
1477
+ */
1478
+ shutdown(timeoutMs = this.#opts.exportTimeoutMs) {
1479
+ this.#shutdown ??= this.#doShutdown(timeoutMs);
1480
+ return this.#shutdown;
1481
+ }
1482
+ /** Current counters. */
1483
+ stats() {
1484
+ return {
1485
+ queued: this.#queue.length + this.#inflight,
1486
+ sent: this.#sent,
1487
+ dropped: this.#dropped,
1488
+ failed: this.#failed,
1489
+ retries: this.#retries
1490
+ };
1491
+ }
1492
+ async #doShutdown(timeoutMs) {
1493
+ this.#closed = true;
1494
+ clearInterval(this.#timer);
1495
+ this.#releaseWaiters();
1496
+ try {
1497
+ await this.#withTimeout(this.#drainTo(this.#enqueued), timeoutMs, "logging.shutdown");
1498
+ } catch {
1499
+ this.#stop.abort();
1500
+ }
1501
+ if (this.#queue.length > 0) {
1502
+ const rest = this.#queue.splice(0, this.#queue.length).map((e) => e.record);
1503
+ this.#dequeued += rest.length;
1504
+ this.#queuedBytes = 0;
1505
+ this.#drop(rest, "shutdown");
1506
+ }
1507
+ try {
1508
+ await this.#exporter.shutdown();
1509
+ } catch (error) {
1510
+ this.#notifyError(error, []);
1511
+ }
1512
+ }
1513
+ #onTick() {
1514
+ if (this.#queue.length === 0) return;
1515
+ this.#forceUntil = Math.max(this.#forceUntil, this.#enqueued);
1516
+ void this.#kick();
1517
+ }
1518
+ #scheduleKick() {
1519
+ if (this.#kickScheduled) return;
1520
+ this.#kickScheduled = true;
1521
+ queueMicrotask(() => {
1522
+ this.#kickScheduled = false;
1523
+ void this.#kick();
1524
+ });
1525
+ }
1526
+ async #drainTo(target) {
1527
+ this.#forceUntil = Math.max(this.#forceUntil, target);
1528
+ while (!this.#stop.signal.aborted && (this.#dequeued < target && this.#queue.length > 0 || this.#inflight > 0)) {
1529
+ await this.#kick();
1530
+ }
1531
+ }
1532
+ #kick() {
1533
+ this.#draining ??= this.#drainLoop().finally(() => {
1534
+ this.#draining = null;
1535
+ });
1536
+ return this.#draining;
1537
+ }
1538
+ async #drainLoop() {
1539
+ while (this.#queue.length > 0 && !this.#stop.signal.aborted) {
1540
+ const full = this.#queue.length >= this.#opts.maxBatchSize || this.#queuedBytes >= this.#opts.maxBatchBytes;
1541
+ if (!full && this.#forceUntil <= this.#dequeued) break;
1542
+ await this.#exportBatch(this.#takeBatch());
1543
+ }
1544
+ }
1545
+ #takeBatch() {
1546
+ let count = 0;
1547
+ let bytes = 2;
1548
+ for (const entry of this.#queue) {
1549
+ if (count >= this.#opts.maxBatchSize) break;
1550
+ const next = bytes + entry.bytes + (count > 0 ? 1 : 0);
1551
+ if (count > 0 && next > this.#opts.maxBatchBytes) break;
1552
+ bytes = next;
1553
+ count += 1;
1554
+ }
1555
+ const taken = this.#queue.splice(0, count);
1556
+ for (const e of taken) this.#queuedBytes -= e.bytes;
1557
+ this.#dequeued += count;
1558
+ this.#inflight += count;
1559
+ this.#releaseWaiters();
1560
+ return taken.map((e) => e.record);
1561
+ }
1562
+ async #exportBatch(records) {
1563
+ try {
1564
+ for (let attempt = 0; ; attempt += 1) {
1565
+ let result;
1566
+ try {
1567
+ result = await this.#exportOnce(records);
1568
+ } catch (error) {
1569
+ if (await this.#shouldRetry(error, attempt)) continue;
1570
+ this.#fail(records, error);
1571
+ return;
1572
+ }
1573
+ const accepted = Math.min(records.length, Math.max(0, Math.trunc(result.accepted)));
1574
+ if (accepted === 0 && result.error !== void 0 && await this.#shouldRetry(result.error, attempt)) {
1575
+ continue;
1576
+ }
1577
+ this.#sent += accepted;
1578
+ const failed = records.length - accepted;
1579
+ if (accepted === 0) {
1580
+ this.#fail(
1581
+ records,
1582
+ result.error ?? new Error("logging.export: the service accepted no records")
1583
+ );
1584
+ } else if (failed > 0) {
1585
+ this.#failed += failed;
1586
+ this.#notifyError(
1587
+ result.error ?? new Error(`logging.export: ${failed} records rejected`),
1588
+ records
1589
+ );
1590
+ }
1591
+ return;
1592
+ }
1593
+ } finally {
1594
+ this.#inflight -= records.length;
1595
+ }
1596
+ }
1597
+ async #shouldRetry(error, attempt) {
1598
+ if (!isRetryable(error) || attempt >= this.#opts.maxExportRetries || this.#stop.signal.aborted)
1599
+ return false;
1600
+ this.#retries += 1;
1601
+ await this.#sleep(this.#opts.retryBackoffMs * 2 ** attempt);
1602
+ return !this.#stop.signal.aborted;
1603
+ }
1604
+ #exportOnce(records) {
1605
+ const timeoutMs = this.#opts.exportTimeoutMs;
1606
+ const controller = new AbortController();
1607
+ const onStop = () => {
1608
+ controller.abort(this.#stop.signal.reason);
1609
+ };
1610
+ this.#stop.signal.addEventListener("abort", onStop, { once: true });
1611
+ let timer;
1612
+ const timeout = new Promise((_, reject) => {
1613
+ timer = setTimeout(() => {
1614
+ const error = new TimeoutError(`logging.export: timed out after ${timeoutMs} ms`);
1615
+ controller.abort(error);
1616
+ reject(error);
1617
+ }, timeoutMs);
1618
+ timer.unref();
1619
+ });
1620
+ const run = Promise.resolve().then(
1621
+ () => this.#exporter.export(records, { signal: controller.signal, gzip: this.#opts.gzip })
1622
+ );
1623
+ return Promise.race([run, timeout]).finally(() => {
1624
+ clearTimeout(timer);
1625
+ this.#stop.signal.removeEventListener("abort", onStop);
1626
+ });
1627
+ }
1628
+ #sleep(ms) {
1629
+ return new Promise((resolve) => {
1630
+ const done = () => {
1631
+ clearTimeout(timer);
1632
+ this.#stop.signal.removeEventListener("abort", done);
1633
+ resolve();
1634
+ };
1635
+ const timer = setTimeout(done, ms);
1636
+ timer.unref();
1637
+ this.#stop.signal.addEventListener("abort", done, { once: true });
1638
+ });
1639
+ }
1640
+ async #withTimeout(work, timeoutMs, operation) {
1641
+ let timer;
1642
+ const timeout = new Promise((_, reject) => {
1643
+ timer = setTimeout(() => {
1644
+ reject(new TimeoutError(`${operation}: timed out after ${timeoutMs} ms`));
1645
+ }, timeoutMs);
1646
+ timer.unref();
1647
+ });
1648
+ try {
1649
+ await Promise.race([work, timeout]);
1650
+ } finally {
1651
+ clearTimeout(timer);
1652
+ }
1653
+ }
1654
+ #releaseWaiters() {
1655
+ if (this.#capacityWaiters.length === 0) return;
1656
+ if (!this.#closed && this.#queue.length >= this.#opts.maxQueueSize) return;
1657
+ const waiters = this.#capacityWaiters;
1658
+ this.#capacityWaiters = [];
1659
+ for (const resolve of waiters) resolve();
1660
+ }
1661
+ #fail(records, error) {
1662
+ this.#failed += records.length;
1663
+ this.#notifyError(error, records);
1664
+ this.#notifyDrop(records, "export_failed");
1665
+ }
1666
+ #drop(records, reason) {
1667
+ this.#dropped += records.length;
1668
+ this.#notifyDrop(records, reason);
1669
+ }
1670
+ #notifyDrop(records, reason) {
1671
+ try {
1672
+ this.#opts.onDrop?.(records, reason);
1673
+ } catch {
1674
+ }
1675
+ }
1676
+ #notifyError(error, records) {
1677
+ try {
1678
+ this.#opts.onError?.(error, records);
1679
+ } catch {
1680
+ }
1681
+ }
1682
+ };
1683
+ var Logger = class _Logger {
1684
+ #sink;
1685
+ #attributes;
1686
+ #minSeverity;
1687
+ #name;
1688
+ constructor(sink, options = {}) {
1689
+ this.#sink = sink;
1690
+ this.#name = options.name;
1691
+ this.#minSeverity = options.minSeverity ?? 9 /* Info */;
1692
+ this.#attributes = {
1693
+ ...options.name !== void 0 ? { "logger.name": options.name } : {},
1694
+ ...options.attributes
1695
+ };
1696
+ }
1697
+ /** The logger name, when set. */
1698
+ get name() {
1699
+ return this.#name;
1700
+ }
1701
+ /** The minimum severity this logger sends. */
1702
+ get minSeverity() {
1703
+ return this.#minSeverity;
1704
+ }
1705
+ /** Whether a record of `severity` would be sent. */
1706
+ isEnabled(severity) {
1707
+ return severity >= this.#minSeverity;
1708
+ }
1709
+ trace(message, attributes) {
1710
+ this.log(1 /* Trace */, message, attributes);
1711
+ }
1712
+ debug(message, attributes) {
1713
+ this.log(5 /* Debug */, message, attributes);
1714
+ }
1715
+ info(message, attributes) {
1716
+ this.log(9 /* Info */, message, attributes);
1717
+ }
1718
+ warn(message, attributes) {
1719
+ this.log(13 /* Warn */, message, attributes);
1720
+ }
1721
+ error(message, attributes) {
1722
+ this.log(17 /* Error */, message, attributes);
1723
+ }
1724
+ fatal(message, attributes) {
1725
+ this.log(21 /* Fatal */, message, attributes);
1726
+ }
1727
+ /** Sends one record at `severity` (if enabled). */
1728
+ log(severity, message, attributes) {
1729
+ if (!this.isEnabled(severity)) return;
1730
+ const input = {
1731
+ message,
1732
+ severity,
1733
+ attributes: { ...this.#attributes, ...attributes }
1734
+ };
1735
+ const span = trace.getSpan(context.active());
1736
+ if (span !== void 0) {
1737
+ const ctx = span.spanContext();
1738
+ if (isSpanContextValid(ctx)) {
1739
+ input.traceId = ctx.traceId;
1740
+ input.spanId = ctx.spanId;
1741
+ input.traceFlags = ctx.traceFlags;
1742
+ }
1743
+ }
1744
+ this.#sink.send(input);
1745
+ }
1746
+ /** A logger with extra attributes (same sink, name and minimum severity). */
1747
+ child(attributes) {
1748
+ const options = {
1749
+ minSeverity: this.#minSeverity,
1750
+ attributes: { ...this.#attributes, ...attributes }
1751
+ };
1752
+ if (this.#name !== void 0) options.name = this.#name;
1753
+ return new _Logger(this.#sink, options);
1754
+ }
1755
+ };
1756
+
1757
+ // src/logging/client.ts
1758
+ function isLogRecord(input) {
1759
+ return "body" in input && typeof input.body === "string";
1760
+ }
1761
+ var BatchingLogClient = class {
1762
+ #processor;
1763
+ #resource;
1764
+ #redaction;
1765
+ #minSeverity;
1766
+ #now;
1767
+ #closing = null;
1768
+ constructor(exporter, options = {}) {
1769
+ this.#processor = new BatchProcessor(exporter, options.batch);
1770
+ this.#resource = toAttributes(options.resource ?? {});
1771
+ const redaction = options.redaction ?? {};
1772
+ this.#redaction = redaction === false ? null : redaction instanceof RedactionProcessor ? redaction : new RedactionProcessor(redaction);
1773
+ this.#minSeverity = options.minSeverity ?? 9 /* Info */;
1774
+ this.#now = options.now ?? (() => /* @__PURE__ */ new Date());
1775
+ }
1776
+ /** The underlying processor. */
1777
+ get processor() {
1778
+ return this.#processor;
1779
+ }
1780
+ /** The resource attributes added to every record. */
1781
+ get resource() {
1782
+ return this.#resource;
1783
+ }
1784
+ send(record) {
1785
+ try {
1786
+ this.#processor.add(this.#prepare(record));
1787
+ } catch {
1788
+ }
1789
+ }
1790
+ sendBatch(records) {
1791
+ for (const record of records) this.send(record);
1792
+ }
1793
+ flush(timeoutMs) {
1794
+ return this.#processor.flush(timeoutMs);
1795
+ }
1796
+ close() {
1797
+ this.#closing ??= this.#processor.shutdown();
1798
+ return this.#closing;
1799
+ }
1800
+ stats() {
1801
+ return this.#processor.stats();
1802
+ }
1803
+ logger(name, attributes) {
1804
+ const options = { minSeverity: this.#minSeverity };
1805
+ if (name !== void 0) options.name = name;
1806
+ if (attributes !== void 0) options.attributes = attributes;
1807
+ return new Logger(this, options);
1808
+ }
1809
+ /** Applies defaults, resource, id normalization and redaction. */
1810
+ #prepare(input) {
1811
+ const now = this.#now();
1812
+ let record;
1813
+ if (isLogRecord(input)) {
1814
+ record = {
1815
+ ...input,
1816
+ attributes: toAttributes(input.attributes),
1817
+ resource: { ...this.#resource, ...toAttributes(input.resource) }
1818
+ };
1819
+ record.observedTimestamp ??= now;
1820
+ } else {
1821
+ const severity = input.severity ?? 9 /* Info */;
1822
+ record = {
1823
+ timestamp: input.timestamp ?? now,
1824
+ observedTimestamp: now,
1825
+ severity,
1826
+ severityText: severityText(severity),
1827
+ body: input.message,
1828
+ attributes: toAttributes(input.attributes ?? {}),
1829
+ resource: { ...this.#resource }
1830
+ };
1831
+ if (input.traceId !== void 0) record.traceId = input.traceId;
1832
+ if (input.spanId !== void 0) record.spanId = input.spanId;
1833
+ if (input.traceFlags !== void 0) record.traceFlags = input.traceFlags;
1834
+ }
1835
+ const traceId = normalizeHexId(record.traceId, 32);
1836
+ const spanId = traceId === void 0 ? void 0 : normalizeHexId(record.spanId, 16);
1837
+ delete record.traceId;
1838
+ delete record.spanId;
1839
+ if (traceId === void 0) delete record.traceFlags;
1840
+ else record.traceId = traceId;
1841
+ if (spanId !== void 0) record.spanId = spanId;
1842
+ return this.#redaction === null ? record : this.#redaction.process(record);
1843
+ }
1844
+ };
1845
+ function pinoLevelToSeverity(level) {
1846
+ if (typeof level === "number") {
1847
+ if (level < 20) return 1 /* Trace */;
1848
+ if (level < 30) return 5 /* Debug */;
1849
+ if (level < 40) return 9 /* Info */;
1850
+ if (level < 50) return 13 /* Warn */;
1851
+ if (level < 60) return 17 /* Error */;
1852
+ return 21 /* Fatal */;
1853
+ }
1854
+ return typeof level === "string" ? parseSeverity(level) ?? 9 /* Info */ : 9 /* Info */;
1855
+ }
1856
+ function pinoLineToRecord(line, opts = {}) {
1857
+ const consumed = /* @__PURE__ */ new Set();
1858
+ const pick = (...keys) => {
1859
+ for (const key of keys) {
1860
+ if (key in line) {
1861
+ consumed.add(key);
1862
+ return line[key];
1863
+ }
1864
+ }
1865
+ return void 0;
1866
+ };
1867
+ const level = pick("level");
1868
+ const time = pick("time");
1869
+ const message = pick(opts.messageKey ?? "msg");
1870
+ const hostname = pick("hostname");
1871
+ const pid = pick("pid");
1872
+ const traceId = pick("trace_id", "traceId");
1873
+ const spanId = pick("span_id", "spanId");
1874
+ const traceFlags = pick("trace_flags", "traceFlags");
1875
+ const rest = Object.fromEntries(Object.entries(line).filter(([k]) => !consumed.has(k)));
1876
+ const severity = pinoLevelToSeverity(level);
1877
+ const timestamp = typeof time === "number" || typeof time === "string" ? new Date(time) : /* @__PURE__ */ new Date();
1878
+ const resource = {};
1879
+ if (typeof hostname === "string") resource["host.name"] = hostname;
1880
+ if (typeof pid === "number") resource["process.pid"] = pid;
1881
+ const record = {
1882
+ timestamp: Number.isNaN(timestamp.getTime()) ? /* @__PURE__ */ new Date() : timestamp,
1883
+ severity,
1884
+ severityText: typeof level === "string" ? level.toUpperCase() : severityText(severity),
1885
+ body: typeof message === "string" ? message : message === void 0 ? "" : JSON.stringify(message),
1886
+ attributes: { ...opts.attributes, ...toAttributes(rest) },
1887
+ resource
1888
+ };
1889
+ if (typeof traceId === "string") record.traceId = traceId;
1890
+ if (typeof spanId === "string") record.spanId = spanId;
1891
+ if (typeof traceFlags === "number") record.traceFlags = traceFlags;
1892
+ else if (typeof traceFlags === "string" && /^[0-9a-f]{1,2}$/i.test(traceFlags)) {
1893
+ record.traceFlags = parseInt(traceFlags, 16);
1894
+ }
1895
+ return record;
1896
+ }
1897
+ function createPinoTransport(client, opts = {}) {
1898
+ let pending = "";
1899
+ const handleLine = (line) => {
1900
+ if (line.trim() === "") return;
1901
+ let parsed;
1902
+ try {
1903
+ parsed = JSON.parse(line);
1904
+ } catch {
1905
+ parsed = void 0;
1906
+ }
1907
+ if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
1908
+ client.send(pinoLineToRecord(parsed, opts));
1909
+ } else {
1910
+ client.send({ message: line, severity: 9 /* Info */, attributes: { ...opts.attributes } });
1911
+ }
1912
+ };
1913
+ return new Writable({
1914
+ decodeStrings: false,
1915
+ write(chunk, _encoding, callback) {
1916
+ pending += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
1917
+ let index = pending.indexOf("\n");
1918
+ while (index >= 0) {
1919
+ handleLine(pending.slice(0, index));
1920
+ pending = pending.slice(index + 1);
1921
+ index = pending.indexOf("\n");
1922
+ }
1923
+ callback();
1924
+ },
1925
+ final(callback) {
1926
+ handleLine(pending);
1927
+ pending = "";
1928
+ if (opts.flushOnEnd === false) {
1929
+ callback();
1930
+ return;
1931
+ }
1932
+ client.flush().then(
1933
+ () => {
1934
+ callback();
1935
+ },
1936
+ () => {
1937
+ callback();
1938
+ }
1939
+ );
1940
+ }
1941
+ });
1942
+ }
1943
+ var LEVEL = /* @__PURE__ */ Symbol.for("level");
1944
+ var WINSTON_LEVELS = {
1945
+ silly: 1 /* Trace */,
1946
+ verbose: 5 /* Debug */,
1947
+ http: 9 /* Info */,
1948
+ emerg: 21 /* Fatal */,
1949
+ alert: 21 /* Fatal */,
1950
+ crit: 21 /* Fatal */
1951
+ };
1952
+ function winstonLevelToSeverity(level) {
1953
+ const lower = level.toLowerCase();
1954
+ return WINSTON_LEVELS[lower] ?? parseSeverity(lower) ?? 9 /* Info */;
1955
+ }
1956
+ var WinstonTransport = class extends Writable {
1957
+ #client;
1958
+ #attributes;
1959
+ /** Level filter (same meaning as winston-transport's `level`). */
1960
+ level;
1961
+ /** Level table, set by winston when the logger pipes into this transport. */
1962
+ levels;
1963
+ constructor(client, opts = {}) {
1964
+ super({ objectMode: true });
1965
+ this.#client = client;
1966
+ this.#attributes = opts.attributes ?? {};
1967
+ this.level = opts.level;
1968
+ this.on("pipe", (source) => {
1969
+ this.levels ??= source.levels;
1970
+ });
1971
+ }
1972
+ /** Converts a winston info object into a {@link LogRecord}. */
1973
+ toRecord(info) {
1974
+ const rawLevel = typeof info[LEVEL] === "string" ? info[LEVEL] : info.level;
1975
+ const severity = winstonLevelToSeverity(rawLevel);
1976
+ const { level: _level, message, timestamp, ...rest } = info;
1977
+ const time = typeof timestamp === "string" || typeof timestamp === "number" ? new Date(timestamp) : /* @__PURE__ */ new Date();
1978
+ return {
1979
+ timestamp: Number.isNaN(time.getTime()) ? /* @__PURE__ */ new Date() : time,
1980
+ severity,
1981
+ severityText: rawLevel.toUpperCase(),
1982
+ body: typeof message === "string" ? message : message === void 0 ? "" : JSON.stringify(message),
1983
+ attributes: { ...this.#attributes, ...toAttributes(rest) },
1984
+ resource: {}
1985
+ };
1986
+ }
1987
+ /** Winston-compatible entry point. */
1988
+ log(info, callback) {
1989
+ if (this.#accepts(info)) this.#client.send(this.toRecord(info));
1990
+ callback?.();
1991
+ }
1992
+ _write(info, _encoding, callback) {
1993
+ this.log(info, () => {
1994
+ callback();
1995
+ });
1996
+ }
1997
+ _final(callback) {
1998
+ this.#client.flush().then(
1999
+ () => {
2000
+ callback();
2001
+ },
2002
+ () => {
2003
+ callback();
2004
+ }
2005
+ );
2006
+ }
2007
+ /** Called by winston when the transport is removed or the logger closes. */
2008
+ close() {
2009
+ void this.#client.flush().catch(() => void 0);
2010
+ }
2011
+ #accepts(info) {
2012
+ if (this.level === void 0 || this.levels === void 0) return true;
2013
+ const max = this.levels[this.level];
2014
+ const current = this.levels[info.level];
2015
+ return max === void 0 || current === void 0 || current <= max;
2016
+ }
2017
+ };
2018
+
2019
+ // src/time.ts
2020
+ var NS_PER_MS = 1000000n;
2021
+ var DIGITS = /^\d+$/;
2022
+ function dateToNanos(date) {
2023
+ const ms = date.getTime();
2024
+ if (!Number.isFinite(ms)) throw new ValidationError("invalid date");
2025
+ return (BigInt(ms) * NS_PER_MS).toString();
2026
+ }
2027
+ function nanosToDate(ns) {
2028
+ const value = typeof ns === "bigint" ? ns : BigInt(ns);
2029
+ return new Date(Number(value / NS_PER_MS));
2030
+ }
2031
+ function toNanos(value, field = "time") {
2032
+ if (value instanceof Date) {
2033
+ if (Number.isNaN(value.getTime())) throw new ValidationError(`${field}: invalid date`);
2034
+ return dateToNanos(value);
2035
+ }
2036
+ if (typeof value === "bigint") {
2037
+ if (value < 0n) throw new ValidationError(`${field}: must not be negative`);
2038
+ return value.toString();
2039
+ }
2040
+ const text = value.trim();
2041
+ if (DIGITS.test(text)) return text;
2042
+ const parsed = Date.parse(text);
2043
+ if (text === "" || Number.isNaN(parsed)) {
2044
+ throw new ValidationError(`${field}: expected a Date, bigint nanoseconds or RFC 3339 text`);
2045
+ }
2046
+ return dateToNanos(new Date(parsed));
2047
+ }
2048
+ function optionalNanos(value, field) {
2049
+ return value === void 0 ? void 0 : toNanos(value, field);
2050
+ }
2051
+ function secondsToDate(seconds) {
2052
+ return new Date(Math.round(seconds * 1e3));
2053
+ }
2054
+ function msToDuration(ms, field) {
2055
+ if (!Number.isFinite(ms) || ms <= 0) {
2056
+ throw new ValidationError(`${field}: must be a positive number of milliseconds`);
2057
+ }
2058
+ return `${Math.round(ms)}ms`;
2059
+ }
2060
+
2061
+ // src/labels.ts
2062
+ var LABEL_NAME_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
2063
+ var DEFAULT_ALLOWED_LABELS = Object.freeze([
2064
+ "service_name",
2065
+ "service_namespace",
2066
+ "deployment_environment",
2067
+ "host_name",
2068
+ "level",
2069
+ "job",
2070
+ "instance",
2071
+ "namespace",
2072
+ "pod",
2073
+ "container"
2074
+ ]);
2075
+ var RESERVED_METADATA_KEYS = Object.freeze([
2076
+ "severity_text",
2077
+ "severity_number",
2078
+ "trace_id",
2079
+ "span_id",
2080
+ "trace_flags"
2081
+ ]);
2082
+ function isValidLabelName(name) {
2083
+ return LABEL_NAME_PATTERN.test(name) && !name.startsWith("__");
2084
+ }
2085
+ function validateLabelName(name, what = "label name") {
2086
+ if (!LABEL_NAME_PATTERN.test(name)) {
2087
+ throw new ValidationError(
2088
+ `invalid ${what} ${JSON.stringify(name)}: must match [a-zA-Z_][a-zA-Z0-9_]*`
2089
+ );
2090
+ }
2091
+ if (name.startsWith("__")) {
2092
+ throw new ValidationError(`invalid ${what} ${JSON.stringify(name)}: "__" names are reserved`);
2093
+ }
2094
+ }
2095
+ function validateLabels(labels) {
2096
+ for (const [name, value] of Object.entries(labels)) {
2097
+ validateLabelName(name);
2098
+ if (typeof value !== "string" || value === "") {
2099
+ throw new ValidationError(`label ${name}: value must be a non-empty string`);
2100
+ }
2101
+ }
2102
+ }
2103
+ function normalizeLabelName(key) {
2104
+ const replaced = key.replace(/[^a-zA-Z0-9_]/g, "_");
2105
+ if (replaced === "") return "_";
2106
+ return /^[0-9]/.test(replaced) ? `_${replaced}` : replaced;
2107
+ }
2108
+ function formatLabelSet(labels) {
2109
+ const parts = Object.keys(labels).sort().map((k) => `${k}=${JSON.stringify(labels[k])}`);
2110
+ return `{${parts.join(", ")}}`;
2111
+ }
2112
+ function attrToString(value) {
2113
+ if (typeof value === "string") return value;
2114
+ if (typeof value === "number" || typeof value === "boolean") return String(value);
2115
+ return JSON.stringify(value);
2116
+ }
2117
+ var CardinalityGuard = class {
2118
+ #allowed;
2119
+ /** A guard for `allowed` (default {@link DEFAULT_ALLOWED_LABELS}). */
2120
+ constructor(allowed = DEFAULT_ALLOWED_LABELS) {
2121
+ this.#allowed = new Set(allowed);
2122
+ }
2123
+ /** The allowlist, sorted. */
2124
+ get allowed() {
2125
+ return [...this.#allowed].sort();
2126
+ }
2127
+ /** Whether `name` may be an index label. */
2128
+ isAllowed(name) {
2129
+ return this.#allowed.has(name);
2130
+ }
2131
+ /** A copy of `stream` whose labels outside the allowlist are moved to every entry's metadata. */
2132
+ apply(stream) {
2133
+ const labels = {};
2134
+ const moved = {};
2135
+ for (const [k, v] of Object.entries(stream.labels)) {
2136
+ if (this.#allowed.has(k)) labels[k] = v;
2137
+ else moved[k] = v;
2138
+ }
2139
+ if (Object.keys(moved).length === 0) return { labels, entries: stream.entries };
2140
+ return {
2141
+ labels,
2142
+ entries: stream.entries.map((e) => ({
2143
+ ...e,
2144
+ structuredMetadata: { ...moved, ...e.structuredMetadata ?? {} }
2145
+ }))
2146
+ };
2147
+ }
2148
+ };
2149
+ function isScalar(value) {
2150
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
2151
+ }
2152
+ function recordsToStreams(records, options = {}) {
2153
+ const allowed = new Set(options.allowedLabels ?? DEFAULT_ALLOWED_LABELS);
2154
+ const streams = /* @__PURE__ */ new Map();
2155
+ for (const record of records) {
2156
+ const labels = {};
2157
+ const metadata = {};
2158
+ const place = (key2, value) => {
2159
+ const name = normalizeLabelName(key2);
2160
+ if (allowed.has(name) && isValidLabelName(name) && isScalar(value) && String(value) !== "") {
2161
+ labels[name] = String(value);
2162
+ } else {
2163
+ metadata[name] = attrToString(value);
2164
+ }
2165
+ };
2166
+ for (const [k, v] of Object.entries(record.resource)) place(k, v);
2167
+ for (const [k, v] of Object.entries(record.attributes)) place(k, v);
2168
+ const text = record.severityText !== "" ? record.severityText : severityText(record.severity);
2169
+ if (allowed.has("level") && labels.level === void 0) labels.level = text.toLowerCase();
2170
+ metadata.severity_text = text;
2171
+ metadata.severity_number = String(record.severity);
2172
+ if (record.traceId !== void 0) {
2173
+ metadata.trace_id = record.traceId;
2174
+ if (record.spanId !== void 0) metadata.span_id = record.spanId;
2175
+ if (record.traceFlags !== void 0) metadata.trace_flags = String(record.traceFlags);
2176
+ }
2177
+ const key = formatLabelSet(labels);
2178
+ let stream = streams.get(key);
2179
+ if (stream === void 0) {
2180
+ stream = { labels, entries: [] };
2181
+ streams.set(key, stream);
2182
+ }
2183
+ stream.entries.push({
2184
+ timestamp: dateToNanos(record.timestamp),
2185
+ line: record.body,
2186
+ structuredMetadata: metadata
2187
+ });
2188
+ }
2189
+ return [...streams.values()];
2190
+ }
2191
+
2192
+ // src/exporter.ts
2193
+ var SKIP_LABEL_GUARD = /* @__PURE__ */ Symbol("grow.loki.skipLabelGuard");
2194
+ async function exportWith(records, send) {
2195
+ if (records.length === 0) return { accepted: 0, rejected: 0 };
2196
+ try {
2197
+ await send();
2198
+ return { accepted: records.length, rejected: 0 };
2199
+ } catch (error) {
2200
+ if (error instanceof LokiError) return { accepted: 0, rejected: records.length, error };
2201
+ throw error;
2202
+ }
2203
+ }
2204
+ var LokiLogExporter = class {
2205
+ #pusher;
2206
+ #options;
2207
+ constructor(pusher, options = {}) {
2208
+ this.#pusher = pusher;
2209
+ this.#options = options;
2210
+ }
2211
+ export(records, opts) {
2212
+ return exportWith(
2213
+ records,
2214
+ () => this.#pusher.push(recordsToStreams(records, this.#options), {
2215
+ format: this.#options.format ?? "json",
2216
+ gzip: opts.gzip,
2217
+ [SKIP_LABEL_GUARD]: true,
2218
+ ...opts.signal === void 0 ? {} : { signal: opts.signal }
2219
+ })
2220
+ );
2221
+ }
2222
+ shutdown() {
2223
+ return Promise.resolve();
2224
+ }
2225
+ };
2226
+ var LokiOtlpExporter = class {
2227
+ #pusher;
2228
+ constructor(pusher) {
2229
+ this.#pusher = pusher;
2230
+ }
2231
+ export(records, opts) {
2232
+ return exportWith(
2233
+ records,
2234
+ () => this.#pusher.pushOtlp(records, {
2235
+ gzip: opts.gzip,
2236
+ ...opts.signal === void 0 ? {} : { signal: opts.signal }
2237
+ })
2238
+ );
2239
+ }
2240
+ shutdown() {
2241
+ return Promise.resolve();
2242
+ }
2243
+ };
2244
+ var OTLP_SCOPE_NAME = "grow-codes-grafana-loki";
2245
+ function toOtlpValue(value) {
2246
+ if (typeof value === "string") return { stringValue: value };
2247
+ if (typeof value === "boolean") return { boolValue: value };
2248
+ if (typeof value === "number") {
2249
+ return Number.isSafeInteger(value) ? { intValue: String(value) } : { doubleValue: value };
2250
+ }
2251
+ if (Array.isArray(value)) return { arrayValue: { values: value.map(toOtlpValue) } };
2252
+ return { kvlistValue: { values: toOtlpAttributes(value) } };
2253
+ }
2254
+ function toOtlpAttributes(attrs) {
2255
+ return Object.entries(attrs).map(([key, value]) => ({ key, value: toOtlpValue(value) }));
2256
+ }
2257
+ function recordsToOtlpJson(records) {
2258
+ const byResource = /* @__PURE__ */ new Map();
2259
+ for (const r of records) {
2260
+ const key = JSON.stringify(r.resource);
2261
+ let group = byResource.get(key);
2262
+ if (group === void 0) {
2263
+ group = { resource: r.resource, logRecords: [] };
2264
+ byResource.set(key, group);
2265
+ }
2266
+ const lr = {
2267
+ timeUnixNano: dateToNanos(r.timestamp),
2268
+ observedTimeUnixNano: dateToNanos(r.observedTimestamp ?? r.timestamp),
2269
+ severityNumber: r.severity,
2270
+ severityText: r.severityText,
2271
+ body: { stringValue: r.body },
2272
+ attributes: toOtlpAttributes(r.attributes)
2273
+ };
2274
+ if (r.traceId !== void 0) lr.traceId = r.traceId;
2275
+ if (r.spanId !== void 0) lr.spanId = r.spanId;
2276
+ if (r.traceFlags !== void 0) lr.flags = r.traceFlags;
2277
+ group.logRecords.push(lr);
2278
+ }
2279
+ return {
2280
+ resourceLogs: [...byResource.values()].map((g) => ({
2281
+ resource: { attributes: toOtlpAttributes(g.resource) },
2282
+ scopeLogs: [{ scope: { name: OTLP_SCOPE_NAME }, logRecords: g.logRecords }]
2283
+ }))
2284
+ };
2285
+ }
2286
+ var encoder = new TextEncoder();
2287
+ var Writer = class {
2288
+ #chunks = [];
2289
+ #length = 0;
2290
+ get length() {
2291
+ return this.#length;
2292
+ }
2293
+ bytes(b) {
2294
+ this.#chunks.push(b);
2295
+ this.#length += b.length;
2296
+ }
2297
+ varint(value) {
2298
+ const out = [];
2299
+ let v = value;
2300
+ while (v > 0x7fn) {
2301
+ out.push(Number(v & 0x7fn) | 128);
2302
+ v >>= 7n;
2303
+ }
2304
+ out.push(Number(v));
2305
+ this.bytes(Uint8Array.from(out));
2306
+ }
2307
+ tag(field, wireType) {
2308
+ this.varint(BigInt(field << 3 | wireType));
2309
+ }
2310
+ /** Length-delimited field (wire type 2). */
2311
+ lengthDelimited(field, payload) {
2312
+ this.tag(field, 2);
2313
+ this.varint(BigInt(payload.length));
2314
+ this.bytes(payload);
2315
+ }
2316
+ string(field, value) {
2317
+ this.lengthDelimited(field, encoder.encode(value));
2318
+ }
2319
+ /** Varint field (wire type 0); zero values are omitted (proto3 default). */
2320
+ uint(field, value) {
2321
+ if (value === 0n) return;
2322
+ this.tag(field, 0);
2323
+ this.varint(value);
2324
+ }
2325
+ finish() {
2326
+ const out = new Uint8Array(this.#length);
2327
+ let offset = 0;
2328
+ for (const c of this.#chunks) {
2329
+ out.set(c, offset);
2330
+ offset += c.length;
2331
+ }
2332
+ return out;
2333
+ }
2334
+ };
2335
+ function encodeTimestamp(ns) {
2336
+ const w = new Writer();
2337
+ w.uint(1, ns / 1000000000n);
2338
+ w.uint(2, ns % 1000000000n);
2339
+ return w.finish();
2340
+ }
2341
+ function encodePushRequest(streams) {
2342
+ const req = new Writer();
2343
+ for (const stream of streams) {
2344
+ const s = new Writer();
2345
+ s.string(1, formatLabelSet(stream.labels));
2346
+ for (const entry of stream.entries) {
2347
+ const e = new Writer();
2348
+ e.lengthDelimited(
2349
+ 1,
2350
+ encodeTimestamp(BigInt(toNanos(entry.timestamp ?? /* @__PURE__ */ new Date(), "timestamp")))
2351
+ );
2352
+ e.string(2, entry.line);
2353
+ for (const [name, value] of Object.entries(entry.structuredMetadata ?? {})) {
2354
+ const pair = new Writer();
2355
+ pair.string(1, name);
2356
+ pair.string(2, value);
2357
+ e.lengthDelimited(3, pair.finish());
2358
+ }
2359
+ s.lengthDelimited(2, e.finish());
2360
+ }
2361
+ req.lengthDelimited(1, s.finish());
2362
+ }
2363
+ return req.finish();
2364
+ }
2365
+ function snappyCompress(data) {
2366
+ return compress(data);
2367
+ }
2368
+ function decodeRpcStatusMessage(bytes) {
2369
+ let pos = 0;
2370
+ const readVarint = () => {
2371
+ let result = 0;
2372
+ let shift = 0;
2373
+ while (pos < bytes.length && shift < 35) {
2374
+ const b = bytes[pos++];
2375
+ result += (b & 127) * 2 ** shift;
2376
+ if ((b & 128) === 0) return result;
2377
+ shift += 7;
2378
+ }
2379
+ return void 0;
2380
+ };
2381
+ let message;
2382
+ while (pos < bytes.length) {
2383
+ const tag = readVarint();
2384
+ if (tag === void 0) return void 0;
2385
+ const field = tag >> 3;
2386
+ const wire = tag & 7;
2387
+ if (wire === 0) {
2388
+ if (readVarint() === void 0) return void 0;
2389
+ } else if (wire === 2) {
2390
+ const len = readVarint();
2391
+ if (len === void 0 || pos + len > bytes.length) return void 0;
2392
+ if (field === 2) message = new TextDecoder().decode(bytes.subarray(pos, pos + len));
2393
+ pos += len;
2394
+ } else {
2395
+ return void 0;
2396
+ }
2397
+ }
2398
+ return message;
2399
+ }
2400
+
2401
+ // src/logql.ts
2402
+ var MATCH_OPS = /* @__PURE__ */ new Set(["=", "!=", "=~", "!~"]);
2403
+ var NUMERIC_OPS = /* @__PURE__ */ new Set(["==", "!=", ">", ">=", "<", "<="]);
2404
+ function quoteLogQL(value) {
2405
+ return JSON.stringify(value);
2406
+ }
2407
+ function checkName(name, what) {
2408
+ if (!LABEL_NAME_PATTERN.test(name)) {
2409
+ throw new ValidationError(
2410
+ `LogQL: invalid ${what} ${JSON.stringify(name)}: must match [a-zA-Z_][a-zA-Z0-9_]*`
2411
+ );
2412
+ }
2413
+ }
2414
+ function formatNumber(value) {
2415
+ if (!Number.isFinite(value)) throw new ValidationError("LogQL: numbers must be finite");
2416
+ return value.toLocaleString("en-US", { useGrouping: false, maximumFractionDigits: 20 });
2417
+ }
2418
+ function matchesEmpty(m) {
2419
+ switch (m.op) {
2420
+ case "=":
2421
+ return m.value === "";
2422
+ case "!=":
2423
+ return m.value !== "";
2424
+ default: {
2425
+ let re;
2426
+ try {
2427
+ re = new RegExp(`^(?:${m.value})$`);
2428
+ } catch {
2429
+ return false;
2430
+ }
2431
+ return m.op === "=~" ? re.test("") : !re.test("");
2432
+ }
2433
+ }
2434
+ }
2435
+ var LogQL = class _LogQL {
2436
+ #matchers;
2437
+ #stages;
2438
+ constructor(matchers, stages) {
2439
+ this.#matchers = matchers;
2440
+ this.#stages = stages;
2441
+ }
2442
+ /** Starts a query from equality matchers (`{app="x", env="prod"}`). */
2443
+ static selector(labels = {}) {
2444
+ let q = new _LogQL([], []);
2445
+ for (const [name, value] of Object.entries(labels)) q = q.label(name, "=", value);
2446
+ return q;
2447
+ }
2448
+ /** Quotes a string literal (see {@link quoteLogQL}). */
2449
+ static quote(value) {
2450
+ return quoteLogQL(value);
2451
+ }
2452
+ /** Adds a stream-selector matcher (`=`, `!=`, `=~`, `!~`). */
2453
+ label(name, op, value) {
2454
+ checkName(name, "label name");
2455
+ if (!MATCH_OPS.has(op)) throw new ValidationError(`LogQL: invalid matcher operator ${op}`);
2456
+ return new _LogQL([...this.#matchers, { name, op, value }], this.#stages);
2457
+ }
2458
+ #stage(text) {
2459
+ return new _LogQL(this.#matchers, [...this.#stages, text]);
2460
+ }
2461
+ /** Line filter `|= "text"` (case-sensitive substring). */
2462
+ lineContains(text) {
2463
+ return this.#stage(`|= ${quoteLogQL(text)}`);
2464
+ }
2465
+ /** Line filter `!= "text"`. */
2466
+ lineNotContains(text) {
2467
+ return this.#stage(`!= ${quoteLogQL(text)}`);
2468
+ }
2469
+ /** Line filter `|~ "regex"` (RE2; prefix `(?i)` for case-insensitive). */
2470
+ lineMatches(regex) {
2471
+ return this.#stage(`|~ ${quoteLogQL(regex)}`);
2472
+ }
2473
+ /** Line filter `!~ "regex"`. */
2474
+ lineNotMatches(regex) {
2475
+ return this.#stage(`!~ ${quoteLogQL(regex)}`);
2476
+ }
2477
+ /** Parser stage `| json`. */
2478
+ json() {
2479
+ return this.#stage("| json");
2480
+ }
2481
+ /** Parser stage `| logfmt`. */
2482
+ logfmt() {
2483
+ return this.#stage("| logfmt");
2484
+ }
2485
+ /** Parser stage `| unpack` (lines packed by Promtail's `pack` stage). */
2486
+ unpack() {
2487
+ return this.#stage("| unpack");
2488
+ }
2489
+ /** Parser stage `| regexp "<re>"` with named capture groups. */
2490
+ regexp(pattern) {
2491
+ return this.#stage(`| regexp ${quoteLogQL(pattern)}`);
2492
+ }
2493
+ /** Parser stage `| pattern "<pattern>"`. */
2494
+ pattern(pattern) {
2495
+ return this.#stage(`| pattern ${quoteLogQL(pattern)}`);
2496
+ }
2497
+ /** Formatting stage `| line_format "<template>"`. */
2498
+ lineFormat(template) {
2499
+ return this.#stage(`| line_format ${quoteLogQL(template)}`);
2500
+ }
2501
+ /**
2502
+ * Label filter on an extracted label or structured-metadata key. Numbers use the numeric
2503
+ * operators (`==`, `!=`, `>`, `>=`, `<`, `<=`); strings use `=`, `!=`, `=~`, `!~`.
2504
+ */
2505
+ where(field, op, value) {
2506
+ checkName(field, "field name");
2507
+ if (typeof value === "number") {
2508
+ if (!NUMERIC_OPS.has(op)) {
2509
+ throw new ValidationError(`LogQL: operator ${op} cannot compare numbers`);
2510
+ }
2511
+ return this.#stage(`| ${field} ${op} ${formatNumber(value)}`);
2512
+ }
2513
+ if (!MATCH_OPS.has(op)) {
2514
+ throw new ValidationError(`LogQL: operator ${op} cannot compare strings`);
2515
+ }
2516
+ return this.#stage(`| ${field} ${op} ${quoteLogQL(value)}`);
2517
+ }
2518
+ /** Appends a raw pipeline stage (`| <stage>`, e.g. `drop level`); the text is not escaped. */
2519
+ pipe(stage) {
2520
+ return this.#stage(`| ${stage.trim()}`);
2521
+ }
2522
+ /**
2523
+ * Renders the query. Throws `ValidationError` when the selector is empty or every matcher
2524
+ * also matches the empty string (Loki rejects such selectors).
2525
+ */
2526
+ toString() {
2527
+ if (this.#matchers.length === 0) {
2528
+ throw new ValidationError("LogQL: a stream selector needs at least one matcher");
2529
+ }
2530
+ if (this.#matchers.every(matchesEmpty)) {
2531
+ throw new ValidationError(
2532
+ "LogQL: the selector needs at least one matcher that does not match the empty value"
2533
+ );
2534
+ }
2535
+ const selector = `{${this.#matchers.map((m) => `${m.name}${m.op}${quoteLogQL(m.value)}`).join(", ")}}`;
2536
+ return [selector, ...this.#stages].join(" ");
2537
+ }
2538
+ /** Same as {@link toString}. */
2539
+ build() {
2540
+ return this.toString();
2541
+ }
2542
+ };
2543
+
2544
+ // src/query-client.ts
2545
+ var MAX_QUERY_LIMIT = 5e3;
2546
+ var ALL_STREAMS_SELECTOR = '{service_name=~".+"}';
2547
+ var RESOURCE_KEYS = {
2548
+ service_name: "service.name",
2549
+ service_namespace: "service.namespace",
2550
+ service_version: "service.version",
2551
+ service_instance_id: "service.instance.id",
2552
+ deployment_environment: "deployment.environment",
2553
+ host_name: "host.name"
2554
+ };
2555
+ function toSearchLogQL(query) {
2556
+ const trimmed = query.trim();
2557
+ if (trimmed.startsWith("{")) return trimmed;
2558
+ if (trimmed === "") return ALL_STREAMS_SELECTOR;
2559
+ return `${ALL_STREAMS_SELECTOR} |= ${quoteLogQL(trimmed)}`;
2560
+ }
2561
+ function encodeCursor(ns, skip) {
2562
+ return Buffer.from(`${ns}:${skip}`, "utf8").toString("base64url");
2563
+ }
2564
+ function decodeCursor(cursor) {
2565
+ const text = Buffer.from(cursor, "base64url").toString("utf8");
2566
+ const match = /^(\d+):(\d+)$/.exec(text);
2567
+ if (match === null) throw new ValidationError("logging.search: invalid cursor");
2568
+ return { ns: match[1], skip: Number(match[2]) };
2569
+ }
2570
+ var CONSUMED_METADATA = /* @__PURE__ */ new Set([
2571
+ "severity_text",
2572
+ "severity_number",
2573
+ "trace_id",
2574
+ "span_id",
2575
+ "trace_flags",
2576
+ "observed_timestamp"
2577
+ ]);
2578
+ function severityFrom(md, labels) {
2579
+ const fromNumber = md.severity_number === void 0 ? null : parseSeverity(md.severity_number);
2580
+ const fromText = md.severity_text === void 0 ? null : parseSeverity(md.severity_text);
2581
+ const severity = fromNumber ?? fromText ?? (md.detected_level === void 0 ? null : parseSeverity(md.detected_level)) ?? (labels.level === void 0 ? null : parseSeverity(labels.level)) ?? 9 /* Info */;
2582
+ return { severity, text: md.severity_text ?? severityText(severity) };
2583
+ }
2584
+ function entryToLogRecord(labels, entry) {
2585
+ const md = entry.structuredMetadata;
2586
+ const attributes = {};
2587
+ for (const [k, v] of Object.entries(md)) if (!CONSUMED_METADATA.has(k)) attributes[k] = v;
2588
+ for (const [k, v] of Object.entries(entry.parsed)) attributes[k] = v;
2589
+ const resource = {};
2590
+ for (const [k, v] of Object.entries(labels)) resource[RESOURCE_KEYS[k] ?? k] = v;
2591
+ const { severity, text } = severityFrom(md, labels);
2592
+ const record = {
2593
+ timestamp: entry.timestamp,
2594
+ severity,
2595
+ severityText: text,
2596
+ body: entry.line,
2597
+ attributes,
2598
+ resource
2599
+ };
2600
+ if (md.observed_timestamp !== void 0 && /^\d+$/.test(md.observed_timestamp)) {
2601
+ record.observedTimestamp = nanosToDate(md.observed_timestamp);
2602
+ }
2603
+ const traceId = md.trace_id?.toLowerCase();
2604
+ if (traceId !== void 0 && /^[0-9a-f]{32}$/.test(traceId)) {
2605
+ record.traceId = traceId;
2606
+ const spanId = md.span_id?.toLowerCase();
2607
+ if (spanId !== void 0 && /^[0-9a-f]{16}$/.test(spanId)) record.spanId = spanId;
2608
+ const flagsText = md.trace_flags ?? md.flags;
2609
+ if (flagsText !== void 0 && /^\d+$/.test(flagsText)) {
2610
+ record.traceFlags = Number(flagsText);
2611
+ if (md.trace_flags === void 0) delete attributes.flags;
2612
+ }
2613
+ }
2614
+ return record;
2615
+ }
2616
+ function compareNs(a, b) {
2617
+ if (a.length !== b.length) return a.length - b.length;
2618
+ return a < b ? -1 : a > b ? 1 : 0;
2619
+ }
2620
+ function mergeStreams(streams, order) {
2621
+ const flat = [];
2622
+ for (const s of streams) {
2623
+ const labelKey = formatLabelSet(s.labels);
2624
+ for (const entry of s.entries) flat.push({ labels: s.labels, labelKey, entry });
2625
+ }
2626
+ const dir = order === "asc" ? 1 : -1;
2627
+ flat.sort((a, b) => {
2628
+ const t = compareNs(a.entry.timestampNs, b.entry.timestampNs);
2629
+ if (t !== 0) return t * dir;
2630
+ if (a.labelKey !== b.labelKey) return a.labelKey < b.labelKey ? -1 : 1;
2631
+ return a.entry.line < b.entry.line ? -1 : a.entry.line > b.entry.line ? 1 : 0;
2632
+ });
2633
+ return flat;
2634
+ }
2635
+ var LokiLogQueryClient = class extends BaseLogQueryClient {
2636
+ #source;
2637
+ constructor(source) {
2638
+ super();
2639
+ this.#source = source;
2640
+ }
2641
+ /**
2642
+ * Searches with `query_range`. `query` is LogQL (starting with `{`) or free text. `order`
2643
+ * `desc` (default) is newest first. Pass `nextCursor` back as `cursor` for the next page
2644
+ * (the cursor is `<timestamp>:<entries at that timestamp already returned>`, so pages never
2645
+ * skip or repeat entries sharing a nanosecond). `total` is not available from Loki.
2646
+ */
2647
+ async search(query, opts = {}) {
2648
+ const limit = opts.limit ?? 100;
2649
+ if (!Number.isInteger(limit) || limit < 1 || limit > MAX_QUERY_LIMIT) {
2650
+ throw new ValidationError(`logging.search: limit must be an integer 1..${MAX_QUERY_LIMIT}`);
2651
+ }
2652
+ const order = opts.order ?? "desc";
2653
+ let start = opts.start;
2654
+ let end = opts.end;
2655
+ let cursor;
2656
+ if (opts.cursor !== void 0) {
2657
+ cursor = decodeCursor(opts.cursor);
2658
+ if (order === "desc") end = BigInt(cursor.ns) + 1n;
2659
+ else start = BigInt(cursor.ns);
2660
+ }
2661
+ const fetch = Math.min(limit + (cursor?.skip ?? 0), MAX_QUERY_LIMIT);
2662
+ const logql = toSearchLogQL(query);
2663
+ const direction = order === "asc" ? "forward" : "backward";
2664
+ const signal = opts.signal === void 0 ? {} : { signal: opts.signal };
2665
+ const result = await this.#source.queryRange(logql, {
2666
+ ...start === void 0 ? {} : { start },
2667
+ ...end === void 0 ? {} : { end },
2668
+ limit: fetch,
2669
+ direction,
2670
+ ...signal
2671
+ });
2672
+ let merged = mergeStreams(result.streams, order);
2673
+ const truncated = merged.length >= fetch;
2674
+ const boundary = merged[merged.length - 1]?.entry.timestampNs;
2675
+ if (truncated && boundary !== void 0) {
2676
+ const exact = await this.#source.queryRange(logql, {
2677
+ start: BigInt(boundary),
2678
+ end: BigInt(boundary) + 1n,
2679
+ limit: MAX_QUERY_LIMIT,
2680
+ direction,
2681
+ ...signal
2682
+ });
2683
+ merged = mergeStreams(
2684
+ [
2685
+ ...result.streams.map((s) => ({
2686
+ labels: s.labels,
2687
+ entries: s.entries.filter((e) => e.timestampNs !== boundary)
2688
+ })),
2689
+ ...exact.streams
2690
+ ],
2691
+ order
2692
+ );
2693
+ }
2694
+ let offset = 0;
2695
+ if (cursor !== void 0) {
2696
+ while (offset < cursor.skip && offset < merged.length && merged[offset]?.entry.timestampNs === cursor.ns) {
2697
+ offset++;
2698
+ }
2699
+ }
2700
+ const remaining = merged.slice(offset);
2701
+ const page = remaining.slice(0, limit);
2702
+ const out = {
2703
+ records: page.map((f) => entryToLogRecord(f.labels, f.entry))
2704
+ };
2705
+ const more = truncated || remaining.length > limit;
2706
+ const last = page[page.length - 1];
2707
+ if (more && last !== void 0) {
2708
+ const lastNs = last.entry.timestampNs;
2709
+ let atLast = page.filter((f) => f.entry.timestampNs === lastNs).length;
2710
+ if (cursor !== void 0 && cursor.ns === lastNs) atLast += cursor.skip;
2711
+ out.nextCursor = encodeCursor(lastNs, atLast);
2712
+ }
2713
+ return out;
2714
+ }
2715
+ /**
2716
+ * Live tail over the WebSocket API (`start` defaults to now, so only new records arrive).
2717
+ * Connection errors and abnormal closes go to `opts.onError`.
2718
+ */
2719
+ tail(query, onRecord, opts = {}) {
2720
+ let stopped = false;
2721
+ let tail;
2722
+ const report = (error) => {
2723
+ if (!stopped) opts.onError?.(error);
2724
+ };
2725
+ this.#source.tail(
2726
+ toSearchLogQL(query),
2727
+ (streams) => {
2728
+ for (const f of mergeStreams(streams, "asc")) {
2729
+ if (stopped) return;
2730
+ onRecord(entryToLogRecord(f.labels, f.entry));
2731
+ }
2732
+ },
2733
+ { start: opts.start ?? /* @__PURE__ */ new Date(), onError: report }
2734
+ ).then((t) => {
2735
+ tail = t;
2736
+ if (stopped) t.stop();
2737
+ }, report);
2738
+ return {
2739
+ stop() {
2740
+ stopped = true;
2741
+ tail?.stop();
2742
+ }
2743
+ };
2744
+ }
2745
+ /** Every stream of the default window as a label-set string (`{a="b", c="d"}`), sorted. */
2746
+ async listStreams() {
2747
+ const series = await this.#source.series([ALL_STREAMS_SELECTOR]);
2748
+ return [...new Set(series.map(formatLabelSet))].sort();
2749
+ }
2750
+ /** Label names of the default window. */
2751
+ listLabels() {
2752
+ return this.#source.labels();
2753
+ }
2754
+ };
2755
+
2756
+ // src/results.ts
2757
+ function isObject(v) {
2758
+ return typeof v === "object" && v !== null && !Array.isArray(v);
2759
+ }
2760
+ function bad(what) {
2761
+ throw new UnavailableError(`unexpected response from Loki: ${what}`, { retryable: false });
2762
+ }
2763
+ function stringMap(v) {
2764
+ const out = {};
2765
+ if (!isObject(v)) return out;
2766
+ for (const [k, val] of Object.entries(v)) {
2767
+ if (val === null || val === void 0) continue;
2768
+ out[k] = typeof val === "string" ? val : JSON.stringify(val);
2769
+ }
2770
+ return out;
2771
+ }
2772
+ function parseValue(v) {
2773
+ if (typeof v === "number") return v;
2774
+ if (typeof v !== "string") return Number.NaN;
2775
+ if (v === "+Inf" || v === "Inf") return Number.POSITIVE_INFINITY;
2776
+ if (v === "-Inf") return Number.NEGATIVE_INFINITY;
2777
+ return Number(v);
2778
+ }
2779
+ function decodeSample(v) {
2780
+ if (!Array.isArray(v) || v.length < 2 || typeof v[0] !== "number") bad("malformed sample");
2781
+ return { timestamp: secondsToDate(v[0]), value: parseValue(v[1]) };
2782
+ }
2783
+ function decodeEntry(v) {
2784
+ if (!Array.isArray(v) || typeof v[0] !== "string" || typeof v[1] !== "string") {
2785
+ bad("malformed stream value");
2786
+ }
2787
+ const ns = v[0];
2788
+ if (!/^\d+$/.test(ns)) bad("malformed timestamp");
2789
+ const extra = v[2];
2790
+ return {
2791
+ timestampNs: ns,
2792
+ timestamp: nanosToDate(ns),
2793
+ line: v[1],
2794
+ structuredMetadata: isObject(extra) ? stringMap(extra.structuredMetadata) : {},
2795
+ parsed: isObject(extra) ? stringMap(extra.parsed) : {}
2796
+ };
2797
+ }
2798
+ function decodeStreams(v) {
2799
+ if (v === void 0 || v === null) return [];
2800
+ if (!Array.isArray(v)) bad("streams is not a list");
2801
+ return v.map((s) => {
2802
+ if (!isObject(s)) bad("malformed stream");
2803
+ const values = Array.isArray(s.values) ? s.values : [];
2804
+ return { labels: stringMap(s.stream), entries: values.map(decodeEntry) };
2805
+ });
2806
+ }
2807
+ function decodeQueryResult(body) {
2808
+ if (!isObject(body) || !isObject(body.data)) bad("missing data");
2809
+ const data = body.data;
2810
+ const resultType = data.resultType;
2811
+ const out = {
2812
+ resultType: "streams",
2813
+ streams: [],
2814
+ vector: [],
2815
+ matrix: [],
2816
+ stats: isObject(data.stats) ? data.stats : {}
2817
+ };
2818
+ const result = data.result;
2819
+ switch (resultType) {
2820
+ case "streams":
2821
+ out.streams = decodeStreams(result);
2822
+ break;
2823
+ case "vector":
2824
+ out.resultType = "vector";
2825
+ out.vector = (Array.isArray(result) ? result : []).map((r) => {
2826
+ if (!isObject(r)) bad("malformed vector sample");
2827
+ return { metric: stringMap(r.metric), ...decodeSample(r.value) };
2828
+ });
2829
+ break;
2830
+ case "matrix":
2831
+ out.resultType = "matrix";
2832
+ out.matrix = (Array.isArray(result) ? result : []).map((r) => {
2833
+ if (!isObject(r)) bad("malformed matrix series");
2834
+ const values = Array.isArray(r.values) ? r.values : [];
2835
+ return { metric: stringMap(r.metric), samples: values.map(decodeSample) };
2836
+ });
2837
+ break;
2838
+ case "scalar":
2839
+ out.resultType = "scalar";
2840
+ out.scalar = decodeSample(result);
2841
+ break;
2842
+ default:
2843
+ bad(`unknown resultType ${String(resultType)}`);
2844
+ }
2845
+ return out;
2846
+ }
2847
+ function decodeStringList(body) {
2848
+ if (!isObject(body)) bad("missing body");
2849
+ const data = body.data;
2850
+ if (data === void 0 || data === null) return [];
2851
+ if (!Array.isArray(data)) bad("data is not a list");
2852
+ return data.filter((x) => typeof x === "string");
2853
+ }
2854
+ function decodeSeries(body) {
2855
+ if (!isObject(body)) bad("missing body");
2856
+ const data = body.data;
2857
+ if (data === void 0 || data === null) return [];
2858
+ if (!Array.isArray(data)) bad("data is not a list");
2859
+ return data.map(stringMap);
2860
+ }
2861
+ function decodeIndexStats(body) {
2862
+ if (!isObject(body)) bad("missing body");
2863
+ const num = (k) => typeof body[k] === "number" ? body[k] : 0;
2864
+ return {
2865
+ streams: num("streams"),
2866
+ chunks: num("chunks"),
2867
+ bytes: num("bytes"),
2868
+ entries: num("entries")
2869
+ };
2870
+ }
2871
+ function decodeBuildInfo(body) {
2872
+ if (!isObject(body)) bad("missing body");
2873
+ const str = (k) => typeof body[k] === "string" ? body[k] : "";
2874
+ return {
2875
+ version: str("version"),
2876
+ revision: str("revision"),
2877
+ branch: str("branch"),
2878
+ buildUser: str("buildUser"),
2879
+ buildDate: str("buildDate"),
2880
+ goVersion: str("goVersion")
2881
+ };
2882
+ }
2883
+ function decodeTailFrame(body) {
2884
+ if (!isObject(body)) bad("malformed tail frame");
2885
+ const dropped = Array.isArray(body.dropped_entries) ? body.dropped_entries : [];
2886
+ return {
2887
+ streams: decodeStreams(body.streams),
2888
+ droppedEntries: dropped.filter(isObject).map((d) => ({
2889
+ labels: stringMap(d.labels),
2890
+ timestampNs: typeof d.timestamp === "string" ? d.timestamp : String(d.timestamp)
2891
+ }))
2892
+ };
2893
+ }
2894
+ function vendorText(text, redact) {
2895
+ const trimmed = text.trim().replace(/\s+/g, " ");
2896
+ if (trimmed === "") return void 0;
2897
+ const red = redact(trimmed);
2898
+ return red.length > MAX_VENDOR_TEXT ? red.slice(0, MAX_VENDOR_TEXT - 1) + "\u2026" : red;
2899
+ }
2900
+ function tlsOptions(tls) {
2901
+ const ca = [
2902
+ tls.caCertPem,
2903
+ tls.caCertPath === void 0 ? void 0 : readFileSync(tls.caCertPath, "utf8")
2904
+ ].filter((v) => v !== void 0);
2905
+ return {
2906
+ rejectUnauthorized: tls.insecureSkipVerify !== true,
2907
+ ...ca.length > 0 ? { ca } : {},
2908
+ ...tls.clientCertPath === void 0 ? {} : { cert: readFileSync(tls.clientCertPath, "utf8") },
2909
+ ...tls.clientKeyPath === void 0 ? {} : { key: readFileSync(tls.clientKeyPath, "utf8") }
2910
+ };
2911
+ }
2912
+ function openTail(params, onFrame, callbacks = {}) {
2913
+ const op = "tail";
2914
+ return new Promise((resolve, reject) => {
2915
+ if (params.signal?.aborted === true) {
2916
+ reject(new CancelledError(`${op}: cancelled`));
2917
+ return;
2918
+ }
2919
+ let settled = false;
2920
+ let opened = false;
2921
+ let stopped = false;
2922
+ let resolveClosed;
2923
+ const closed = new Promise((r) => {
2924
+ resolveClosed = r;
2925
+ });
2926
+ const ws = new WebSocket(params.url, {
2927
+ headers: params.headers,
2928
+ handshakeTimeout: params.connectTimeoutMs,
2929
+ followRedirects: false,
2930
+ perMessageDeflate: false,
2931
+ ...tlsOptions(params.tls)
2932
+ });
2933
+ const fail = (error) => {
2934
+ if (settled) return;
2935
+ settled = true;
2936
+ params.signal?.removeEventListener("abort", onAbort);
2937
+ reject(error);
2938
+ };
2939
+ const report = (error) => {
2940
+ try {
2941
+ callbacks.onError?.(error);
2942
+ } catch {
2943
+ }
2944
+ };
2945
+ const handle = {
2946
+ stop() {
2947
+ if (stopped) return;
2948
+ stopped = true;
2949
+ params.signal?.removeEventListener("abort", onAbort);
2950
+ if (ws.readyState === WebSocket.OPEN) ws.close(1e3);
2951
+ else ws.terminate();
2952
+ },
2953
+ closed
2954
+ };
2955
+ function onAbort() {
2956
+ if (!settled) {
2957
+ fail(new CancelledError(`${op}: cancelled`));
2958
+ ws.terminate();
2959
+ } else {
2960
+ handle.stop();
2961
+ }
2962
+ }
2963
+ params.signal?.addEventListener("abort", onAbort, { once: true });
2964
+ ws.on("unexpected-response", (req, res) => {
2965
+ const socket = res.socket;
2966
+ const chunks = [];
2967
+ res.on("data", (c) => chunks.push(c));
2968
+ res.on("end", () => {
2969
+ const status = res.statusCode ?? 0;
2970
+ const reason = vendorText(Buffer.concat(chunks).toString("utf8"), params.redact);
2971
+ fail(errorForStatus(op, status, reason === void 0 ? {} : { reason }));
2972
+ socket.destroy();
2973
+ req.destroy();
2974
+ resolveClosed();
2975
+ });
2976
+ });
2977
+ ws.on("open", () => {
2978
+ if (settled) return;
2979
+ settled = true;
2980
+ opened = true;
2981
+ resolve(handle);
2982
+ });
2983
+ ws.on("message", (data) => {
2984
+ let frame;
2985
+ try {
2986
+ frame = decodeTailFrame(
2987
+ JSON.parse(Buffer.from(data).toString("utf8"))
2988
+ );
2989
+ } catch (err) {
2990
+ report(
2991
+ err instanceof UnavailableError ? err : new UnavailableError(`${op}: malformed frame`, { retryable: false })
2992
+ );
2993
+ return;
2994
+ }
2995
+ if (frame.droppedEntries.length > 0) {
2996
+ try {
2997
+ callbacks.onDropped?.(frame.droppedEntries);
2998
+ } catch {
2999
+ }
3000
+ }
3001
+ if (frame.streams.length > 0) onFrame(frame);
3002
+ });
3003
+ ws.on("error", (err) => {
3004
+ if (!settled) {
3005
+ fail(
3006
+ /timed out/i.test(err.message) ? new TimeoutError(`${op}: connect timeout after ${params.connectTimeoutMs} ms`) : new UnavailableError(`${op}: ${params.redact(err.message)}`)
3007
+ );
3008
+ } else if (opened && !stopped) {
3009
+ report(new UnavailableError(`${op}: ${params.redact(err.message)}`));
3010
+ }
3011
+ });
3012
+ ws.on("close", (code, reasonBuf) => {
3013
+ params.signal?.removeEventListener("abort", onAbort);
3014
+ const reason = vendorText(reasonBuf.toString("utf8"), params.redact);
3015
+ if (!settled) {
3016
+ fail(new UnavailableError(`${op}: connection closed before the upgrade (code ${code})`));
3017
+ } else if (opened && !stopped && code !== 1e3) {
3018
+ report(
3019
+ new UnavailableError(
3020
+ `${op}: connection closed (code ${code})${reason === void 0 ? "" : `: ${reason}`}`,
3021
+ { retryable: code === 1001 || code === 1006 }
3022
+ )
3023
+ );
3024
+ }
3025
+ stopped = true;
3026
+ resolveClosed();
3027
+ });
3028
+ });
3029
+ }
3030
+
3031
+ // src/client.ts
3032
+ var ENCODING_FLAGS_HEADER = "x-loki-response-encoding-flags";
3033
+ var TENANT_HEADER = "x-scope-orgid";
3034
+ var SHUTTING_DOWN = /ingester is shutting down/i;
3035
+ function mapLokiError(err) {
3036
+ if (!(err instanceof LokiError) || !SHUTTING_DOWN.test(err.message)) return err;
3037
+ const message = err.message.includes("WAL") ? err.message : `${err.message} (the Loki ingester is stopping or its WAL disk is at least 90 % full)`;
3038
+ return new UnavailableError(message, {
3039
+ ...err.httpStatus === void 0 ? {} : { httpStatus: err.httpStatus },
3040
+ ...err.requestId === void 0 ? {} : { requestId: err.requestId },
3041
+ ...err.retryAfterMs === void 0 ? {} : { retryAfterMs: err.retryAfterMs },
3042
+ ...err.cause === void 0 ? {} : { cause: err.cause },
3043
+ retryable: true
3044
+ });
3045
+ }
3046
+ function vectorToMatrix(result) {
3047
+ if (result.resultType !== "vector") return result;
3048
+ return {
3049
+ ...result,
3050
+ resultType: "matrix",
3051
+ matrix: result.vector.map(({ metric, timestamp, value }) => ({
3052
+ metric,
3053
+ samples: [{ timestamp, value }]
3054
+ })),
3055
+ vector: []
3056
+ };
3057
+ }
3058
+ function cleanRpcStatus(err) {
3059
+ if (!(err instanceof LokiError)) return err;
3060
+ const match = /^(.*?: )([\s\S]*)( \(HTTP \d+\))$/.exec(err.message);
3061
+ if (match === null) return err;
3062
+ const raw = match[2];
3063
+ const decoded = decodeRpcStatusMessage(new TextEncoder().encode(raw)) ?? raw;
3064
+ const text = decoded.replace(/[\u0000-\u001f\u007f]/g, "").trim();
3065
+ err.message = `${match[1]}${text}${match[3]}`;
3066
+ return err;
3067
+ }
3068
+ function checkLimit(limit, op, max = Number.MAX_SAFE_INTEGER) {
3069
+ if (limit !== void 0 && (!Number.isInteger(limit) || limit < 1 || limit > max)) {
3070
+ throw new ValidationError(`${op}: limit must be an integer 1..${max}`);
3071
+ }
3072
+ }
3073
+ function checkQuery(logql, op) {
3074
+ if (typeof logql !== "string" || logql.trim() === "") {
3075
+ throw new ValidationError(`${op}: query must not be empty`);
3076
+ }
3077
+ }
3078
+ var LokiClient = class _LokiClient {
3079
+ /** The immutable configuration. */
3080
+ config;
3081
+ #transport;
3082
+ #ownsTransport;
3083
+ #tails = /* @__PURE__ */ new Set();
3084
+ #logClients = /* @__PURE__ */ new Set();
3085
+ #guard;
3086
+ #closed = false;
3087
+ #closing;
3088
+ /** Accepts a {@link LokiConfig} or plain options. */
3089
+ constructor(config = {}, internals = {}, shared) {
3090
+ const cfg = LokiConfig.from(config);
3091
+ this.config = cfg;
3092
+ this.#guard = new CardinalityGuard(cfg.allowedLabels);
3093
+ if (shared !== void 0) {
3094
+ this.#transport = shared.transport;
3095
+ this.#ownsTransport = false;
3096
+ } else {
3097
+ this.#transport = new HttpTransport({
3098
+ ...internals,
3099
+ config: cfg,
3100
+ defaultHeaders: () => {
3101
+ const auth = cfg.authorizationHeader();
3102
+ return auth === void 0 ? {} : { authorization: auth };
3103
+ },
3104
+ knownSecrets: () => cfg.knownSecrets()
3105
+ });
3106
+ this.#ownsTransport = true;
3107
+ }
3108
+ }
3109
+ /** Builds a client from `GROW_GRAFANA_LOKI_*` (and `LOKI_*`) environment variables. */
3110
+ static fromEnv(overrides = {}) {
3111
+ return new _LokiClient(LokiConfig.fromEnv(overrides));
3112
+ }
3113
+ /** The shared HTTP transport (for service modules). @internal */
3114
+ get transport() {
3115
+ return this.#transport;
3116
+ }
3117
+ /** The tenant this client sends as `X-Scope-OrgID`, if any. */
3118
+ get tenantId() {
3119
+ return this.config.tenantId;
3120
+ }
3121
+ /**
3122
+ * A client for another tenant: shares this client's connections, sends `X-Scope-OrgID: id`
3123
+ * on every request and on the tail handshake. This client is unchanged. Closing the child
3124
+ * does not close the shared connections. Throws `ValidationError` for an invalid id.
3125
+ */
3126
+ withTenant(id) {
3127
+ const problem = tenantIdProblem(id, this.config.multiTenantQueries);
3128
+ if (problem !== void 0) throw new ValidationError(`withTenant: ${problem}`);
3129
+ return new _LokiClient(this.config.with({ tenantId: id }), {}, { transport: this.#transport });
3130
+ }
3131
+ #tenantHeaders() {
3132
+ return this.config.tenantId === void 0 ? {} : { [TENANT_HEADER]: this.config.tenantId };
3133
+ }
3134
+ async #request(options) {
3135
+ if (this.#closed) {
3136
+ throw new CancelledError(`${options.operation ?? options.path}: client is closed`);
3137
+ }
3138
+ try {
3139
+ return await this.#transport.request({
3140
+ ...options,
3141
+ headers: { ...this.#tenantHeaders(), ...options.headers }
3142
+ });
3143
+ } catch (err) {
3144
+ throw mapLokiError(err);
3145
+ }
3146
+ }
3147
+ async #getJson(path, operation, query, options, categorize = false) {
3148
+ const res = await this.#request({
3149
+ method: "GET",
3150
+ path,
3151
+ operation,
3152
+ query,
3153
+ ...categorize ? { headers: { [ENCODING_FLAGS_HEADER]: "categorize-labels" } } : {},
3154
+ ...options.signal === void 0 ? {} : { signal: options.signal }
3155
+ });
3156
+ return res.data;
3157
+ }
3158
+ // ---------------------------------------------------------------- status
3159
+ /**
3160
+ * Readiness: `GET /ready`. `200 ready` → healthy `ok`; `503` → unhealthy with Loki's text
3161
+ * (e.g. `Ingester not ready: waiting for 15s after being ready`); network errors →
3162
+ * `unreachable`. Never throws except for `CANCELLED` and `CONFIG`.
3163
+ */
3164
+ health(options = {}) {
3165
+ return probeHealth(async () => {
3166
+ try {
3167
+ await this.#request({
3168
+ method: "GET",
3169
+ path: "/ready",
3170
+ operation: "health",
3171
+ responseType: "text",
3172
+ idempotent: false,
3173
+ // report 503 at once instead of retrying it
3174
+ ...options
3175
+ });
3176
+ return healthStatus("ok", {});
3177
+ } catch (err) {
3178
+ if (err instanceof LokiError && err.httpStatus === 503) {
3179
+ const text = /^health: (.*) \(HTTP 503\)$/.exec(err.message)?.[1] ?? "unhealthy";
3180
+ return healthStatus(text, { httpStatus: 503 }, false);
3181
+ }
3182
+ throw err;
3183
+ }
3184
+ });
3185
+ }
3186
+ /** `true` when `GET /ready` answers 200 (same probe as {@link health}). */
3187
+ async ready(options = {}) {
3188
+ return (await this.health(options)).healthy;
3189
+ }
3190
+ /**
3191
+ * Authenticated round trip: `GET /loki/api/v1/labels?since=5m` with auth and tenant headers.
3192
+ * Returns the latency in milliseconds; `AuthenticationError` without a tenant (multi-tenant
3193
+ * Loki) or with wrong gateway credentials.
3194
+ */
3195
+ async ping(options = {}) {
3196
+ const start = performance.now();
3197
+ await this.#request({
3198
+ method: "GET",
3199
+ path: "/loki/api/v1/labels",
3200
+ query: { since: "5m" },
3201
+ operation: "ping",
3202
+ responseType: "none",
3203
+ ...options
3204
+ });
3205
+ return performance.now() - start;
3206
+ }
3207
+ /** Build information: `GET /loki/api/v1/status/buildinfo`. */
3208
+ async buildInfo(options = {}) {
3209
+ return decodeBuildInfo(
3210
+ await this.#getJson("/loki/api/v1/status/buildinfo", "buildInfo", void 0, options)
3211
+ );
3212
+ }
3213
+ /** Server version (`buildInfo().version`, e.g. `"3.7.10"`). */
3214
+ async serverVersion(options = {}) {
3215
+ const info = await this.buildInfo(options);
3216
+ if (info.version === "") {
3217
+ throw new UnsupportedError("serverVersion: the service does not report a version");
3218
+ }
3219
+ return info.version;
3220
+ }
3221
+ // ------------------------------------------------------------------ push
3222
+ /**
3223
+ * Pushes streams with `POST /loki/api/v1/push`. JSON by default (optionally gzip);
3224
+ * `format: "protobuf"` sends a Snappy-compressed `PushRequest`. The cardinality guard moves
3225
+ * labels outside `config.allowedLabels` to every entry's structured metadata (unless
3226
+ * `config.disableLabelGuard`), then labels are validated client side. Entries without a
3227
+ * timestamp get "now". Retrying is safe: Loki drops entries identical to stored ones (same labels,
3228
+ * timestamp and line), so the push is marked idempotent and retried on 5xx and network
3229
+ * errors. Status 260 (ingestion blocked by the operator) throws a non-retryable error.
3230
+ */
3231
+ async push(streams, options = {}) {
3232
+ const op = "push";
3233
+ const live = streams.filter((s) => s.entries.length > 0);
3234
+ if (live.length === 0) return;
3235
+ const now = /* @__PURE__ */ new Date();
3236
+ const guard = this.config.disableLabelGuard || options[SKIP_LABEL_GUARD] === true ? void 0 : this.#guard;
3237
+ const normalized = live.map((input) => {
3238
+ const s = guard === void 0 ? input : guard.apply(input);
3239
+ validateLabels(s.labels);
3240
+ return {
3241
+ labels: s.labels,
3242
+ entries: s.entries.map((e) => {
3243
+ if (typeof e.line !== "string") throw new ValidationError(`${op}: line must be a string`);
3244
+ for (const [k, v] of Object.entries(e.structuredMetadata ?? {})) {
3245
+ if (k === "") {
3246
+ throw new ValidationError(`${op}: structured metadata name must not be empty`);
3247
+ }
3248
+ if (typeof v !== "string") {
3249
+ throw new ValidationError(`${op}: structured metadata ${k} must be a string`);
3250
+ }
3251
+ }
3252
+ return { ...e, timestamp: toNanos(e.timestamp ?? now, "timestamp") };
3253
+ })
3254
+ };
3255
+ });
3256
+ const format = options.format ?? "json";
3257
+ if (format !== "json" && format !== "protobuf") {
3258
+ throw new ValidationError(`${op}: unknown format ${format}`);
3259
+ }
3260
+ let body;
3261
+ const headers = {};
3262
+ if (format === "protobuf") {
3263
+ body = snappyCompress(encodePushRequest(normalized));
3264
+ headers["content-type"] = "application/x-protobuf";
3265
+ } else {
3266
+ body = JSON.stringify({
3267
+ streams: normalized.map((s) => ({
3268
+ stream: s.labels,
3269
+ values: s.entries.map(
3270
+ (e) => e.structuredMetadata !== void 0 && Object.keys(e.structuredMetadata).length > 0 ? [e.timestamp, e.line, e.structuredMetadata] : [e.timestamp, e.line]
3271
+ )
3272
+ }))
3273
+ });
3274
+ headers["content-type"] = "application/json";
3275
+ if (options.gzip === true) {
3276
+ body = gzipSync(body);
3277
+ headers["content-encoding"] = "gzip";
3278
+ }
3279
+ }
3280
+ const res = await this.#request({
3281
+ method: "POST",
3282
+ path: "/loki/api/v1/push",
3283
+ operation: op,
3284
+ body,
3285
+ headers,
3286
+ idempotent: true,
3287
+ responseType: "none",
3288
+ ...options.signal === void 0 ? {} : { signal: options.signal }
3289
+ });
3290
+ if (res.status === 260) {
3291
+ throw new UnavailableError(
3292
+ `${op}: ingestion is blocked by the Loki administrator (HTTP 260)`,
3293
+ {
3294
+ httpStatus: 260,
3295
+ retryable: false
3296
+ }
3297
+ );
3298
+ }
3299
+ }
3300
+ /**
3301
+ * Pushes records as OTLP/JSON to `POST /otlp/v1/logs` (Loki's OTLP endpoint). Loki promotes
3302
+ * its default resource attributes (`service.name`, `deployment.environment`, …) to labels and
3303
+ * stores everything else as structured metadata.
3304
+ */
3305
+ async pushOtlp(records, options = {}) {
3306
+ if (records.length === 0) return;
3307
+ let body = JSON.stringify(recordsToOtlpJson(records));
3308
+ const headers = { "content-type": "application/json" };
3309
+ if (options.gzip === true) {
3310
+ body = gzipSync(body);
3311
+ headers["content-encoding"] = "gzip";
3312
+ }
3313
+ try {
3314
+ await this.#request({
3315
+ method: "POST",
3316
+ path: "/otlp/v1/logs",
3317
+ operation: "pushOtlp",
3318
+ body,
3319
+ headers,
3320
+ idempotent: true,
3321
+ responseType: "none",
3322
+ ...options.signal === void 0 ? {} : { signal: options.signal }
3323
+ });
3324
+ } catch (err) {
3325
+ throw cleanRpcStatus(err);
3326
+ }
3327
+ }
3328
+ // ----------------------------------------------------------------- query
3329
+ /**
3330
+ * Instant metric query: `GET /loki/api/v1/query`. A plain log selector (`{...}` with or
3331
+ * without a pipeline) is rejected with `ValidationError`, as Loki does not run log queries
3332
+ * as instant queries; use {@link queryRange} instead.
3333
+ */
3334
+ async query(logql, options = {}) {
3335
+ checkQuery(logql, "query");
3336
+ if (logql.trim().startsWith("{")) {
3337
+ throw new ValidationError(
3338
+ "query: log queries cannot run as instant queries; use queryRange or search"
3339
+ );
3340
+ }
3341
+ checkLimit(options.limit, "query");
3342
+ return decodeQueryResult(
3343
+ await this.#getJson(
3344
+ "/loki/api/v1/query",
3345
+ "query",
3346
+ {
3347
+ query: logql,
3348
+ time: optionalNanos(options.time, "time"),
3349
+ limit: options.limit,
3350
+ direction: options.direction
3351
+ },
3352
+ options,
3353
+ true
3354
+ )
3355
+ );
3356
+ }
3357
+ /** Range query (logs or metrics): `GET /loki/api/v1/query_range`. */
3358
+ async queryRange(logql, options = {}) {
3359
+ checkQuery(logql, "queryRange");
3360
+ checkLimit(options.limit, "queryRange", MAX_QUERY_LIMIT);
3361
+ return decodeQueryResult(
3362
+ await this.#getJson(
3363
+ "/loki/api/v1/query_range",
3364
+ "queryRange",
3365
+ {
3366
+ query: logql,
3367
+ start: optionalNanos(options.start, "start"),
3368
+ end: optionalNanos(options.end, "end"),
3369
+ since: options.sinceMs === void 0 ? void 0 : msToDuration(options.sinceMs, "sinceMs"),
3370
+ step: options.stepMs === void 0 ? void 0 : msToDuration(options.stepMs, "stepMs"),
3371
+ interval: options.intervalMs === void 0 ? void 0 : msToDuration(options.intervalMs, "intervalMs"),
3372
+ limit: options.limit,
3373
+ direction: options.direction
3374
+ },
3375
+ options,
3376
+ true
3377
+ )
3378
+ );
3379
+ }
3380
+ /** Label names: `GET /loki/api/v1/labels` (an empty result is `[]`). */
3381
+ async labels(options = {}) {
3382
+ return decodeStringList(
3383
+ await this.#getJson(
3384
+ "/loki/api/v1/labels",
3385
+ "labels",
3386
+ {
3387
+ start: optionalNanos(options.start, "start"),
3388
+ end: optionalNanos(options.end, "end"),
3389
+ since: options.sinceMs === void 0 ? void 0 : msToDuration(options.sinceMs, "sinceMs"),
3390
+ query: options.query
3391
+ },
3392
+ options
3393
+ )
3394
+ );
3395
+ }
3396
+ /**
3397
+ * Values of one label: `GET /loki/api/v1/label/{name}/values`. The name is validated client
3398
+ * side (Loki answers unknown and invalid names with an empty result).
3399
+ */
3400
+ async labelValues(name, options = {}) {
3401
+ validateLabelName(name);
3402
+ return decodeStringList(
3403
+ await this.#getJson(
3404
+ `/loki/api/v1/label/${encodeURIComponent(name)}/values`,
3405
+ "labelValues",
3406
+ {
3407
+ start: optionalNanos(options.start, "start"),
3408
+ end: optionalNanos(options.end, "end"),
3409
+ since: options.sinceMs === void 0 ? void 0 : msToDuration(options.sinceMs, "sinceMs"),
3410
+ query: options.query
3411
+ },
3412
+ options
3413
+ )
3414
+ );
3415
+ }
3416
+ /** Series matching any of the selectors: `GET /loki/api/v1/series` (at least one matcher). */
3417
+ async series(matchers, options = {}) {
3418
+ const list = typeof matchers === "string" ? [matchers] : [...matchers];
3419
+ if (list.length === 0 || list.some((m) => m.trim() === "")) {
3420
+ throw new ValidationError("series: at least one non-empty matcher is required");
3421
+ }
3422
+ return decodeSeries(
3423
+ await this.#getJson(
3424
+ "/loki/api/v1/series",
3425
+ "series",
3426
+ {
3427
+ "match[]": list,
3428
+ start: optionalNanos(options.start, "start"),
3429
+ end: optionalNanos(options.end, "end"),
3430
+ since: options.sinceMs === void 0 ? void 0 : msToDuration(options.sinceMs, "sinceMs")
3431
+ },
3432
+ options
3433
+ )
3434
+ );
3435
+ }
3436
+ /**
3437
+ * Approximate index statistics: `GET /loki/api/v1/index/stats`. Reads the TSDB index only,
3438
+ * so data still in the ingester counts after the next chunk flush.
3439
+ */
3440
+ async indexStats(query, options = {}) {
3441
+ checkQuery(query, "indexStats");
3442
+ return decodeIndexStats(
3443
+ await this.#getJson(
3444
+ "/loki/api/v1/index/stats",
3445
+ "indexStats",
3446
+ {
3447
+ query,
3448
+ start: optionalNanos(options.start, "start"),
3449
+ end: optionalNanos(options.end, "end")
3450
+ },
3451
+ options
3452
+ )
3453
+ );
3454
+ }
3455
+ #volumeQuery(query, options) {
3456
+ checkLimit(options.limit, "volume");
3457
+ return {
3458
+ query,
3459
+ start: optionalNanos(options.start, "start"),
3460
+ end: optionalNanos(options.end, "end"),
3461
+ limit: options.limit,
3462
+ targetLabels: options.targetLabels === void 0 || options.targetLabels.length === 0 ? void 0 : options.targetLabels.join(","),
3463
+ aggregateBy: options.aggregateBy
3464
+ };
3465
+ }
3466
+ /**
3467
+ * Ingested bytes per series or label: `GET /loki/api/v1/index/volume` (vector result).
3468
+ * Needs `limits_config.volume_enabled: true`; otherwise Loki returns an empty vector.
3469
+ */
3470
+ async volume(query, options = {}) {
3471
+ checkQuery(query, "volume");
3472
+ return decodeQueryResult(
3473
+ await this.#getJson(
3474
+ "/loki/api/v1/index/volume",
3475
+ "volume",
3476
+ this.#volumeQuery(query, options),
3477
+ options
3478
+ )
3479
+ );
3480
+ }
3481
+ /**
3482
+ * Volume over time: `GET /loki/api/v1/index/volume_range`. Always a matrix: Loki answers
3483
+ * with a `vector` when every series has a single point, which is converted to one-sample
3484
+ * matrix series.
3485
+ */
3486
+ async volumeRange(query, options = {}) {
3487
+ checkQuery(query, "volumeRange");
3488
+ return vectorToMatrix(
3489
+ decodeQueryResult(
3490
+ await this.#getJson(
3491
+ "/loki/api/v1/index/volume_range",
3492
+ "volumeRange",
3493
+ {
3494
+ ...this.#volumeQuery(query, options),
3495
+ step: options.stepMs === void 0 ? void 0 : msToDuration(options.stepMs, "stepMs")
3496
+ },
3497
+ options
3498
+ )
3499
+ )
3500
+ );
3501
+ }
3502
+ /** Normalizes a LogQL query on the server (`GET /loki/api/v1/format_query`). */
3503
+ async formatQuery(logql, options = {}) {
3504
+ checkQuery(logql, "formatQuery");
3505
+ const body = await this.#getJson(
3506
+ "/loki/api/v1/format_query",
3507
+ "formatQuery",
3508
+ { query: logql },
3509
+ options
3510
+ );
3511
+ const data = body?.data;
3512
+ if (typeof data !== "string") {
3513
+ throw new UnavailableError("formatQuery: unexpected response", { retryable: false });
3514
+ }
3515
+ return data;
3516
+ }
3517
+ /**
3518
+ * Live tail over WebSocket (`/loki/api/v1/tail`). Resolves once connected; handshake errors
3519
+ * reject (`AuthenticationError`, `ValidationError`, …). `onEntries` receives the streams of
3520
+ * every frame; dropped entries go to `onDropped`, later errors to `onError`. Only log queries
3521
+ * (starting with `{`) are allowed. Stop with `handle.stop()` or `close()`.
3522
+ * Proxies are not used for the WebSocket.
3523
+ */
3524
+ async tail(logql, onEntries, options = {}) {
3525
+ const op = "tail";
3526
+ checkQuery(logql, op);
3527
+ if (!logql.trim().startsWith("{")) {
3528
+ throw new ValidationError(`${op}: only log queries (starting with a selector) can be tailed`);
3529
+ }
3530
+ checkLimit(options.limit, op);
3531
+ let delayFor;
3532
+ if (options.delayForMs !== void 0) {
3533
+ delayFor = Math.round(options.delayForMs / 1e3);
3534
+ if (!Number.isFinite(delayFor) || delayFor < 0 || delayFor > 5) {
3535
+ throw new ValidationError(`${op}: delayForMs must be between 0 and 5000`);
3536
+ }
3537
+ }
3538
+ if (this.#closed || this.#transport.closed) {
3539
+ throw new CancelledError(`${op}: client is closed`);
3540
+ }
3541
+ const url = this.#transport.buildUrl("/loki/api/v1/tail", {
3542
+ query: logql,
3543
+ start: optionalNanos(options.start ?? /* @__PURE__ */ new Date(), "start"),
3544
+ limit: options.limit,
3545
+ delay_for: delayFor
3546
+ });
3547
+ url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
3548
+ const headers = {};
3549
+ const auth = this.config.authorizationHeader();
3550
+ for (const [k, v] of Object.entries({
3551
+ ...this.config.headers,
3552
+ ...auth === void 0 ? {} : { authorization: auth },
3553
+ ...this.#tenantHeaders(),
3554
+ [ENCODING_FLAGS_HEADER]: "categorize-labels",
3555
+ "user-agent": this.#transport.userAgent
3556
+ })) {
3557
+ headers[k.toLowerCase()] = v;
3558
+ }
3559
+ const handle = await openTail(
3560
+ {
3561
+ url,
3562
+ headers,
3563
+ tls: this.config.tls,
3564
+ connectTimeoutMs: this.config.connectTimeoutMs,
3565
+ ...options.signal === void 0 ? {} : { signal: options.signal },
3566
+ redact: (t) => this.#transport.redact(t)
3567
+ },
3568
+ (frame) => {
3569
+ onEntries(frame.streams, frame);
3570
+ },
3571
+ {
3572
+ ...options.onDropped === void 0 ? {} : { onDropped: options.onDropped },
3573
+ ...options.onError === void 0 ? {} : { onError: options.onError }
3574
+ }
3575
+ );
3576
+ this.#tails.add(handle);
3577
+ void handle.closed.then(() => this.#tails.delete(handle));
3578
+ return handle;
3579
+ }
3580
+ // --------------------------------------------------------------- logging
3581
+ /**
3582
+ * A batching {@link LogClient} that writes to this Loki (and tenant). Records go through
3583
+ * redaction and the cardinality guard; `protocol: "otlp"` uses `/otlp/v1/logs` instead.
3584
+ * {@link close} flushes and closes every log client created here.
3585
+ */
3586
+ logClient(options = {}) {
3587
+ const { protocol, allowedLabels, ...batching } = options;
3588
+ const exporter = protocol === "otlp" ? new LokiOtlpExporter(this) : new LokiLogExporter(this, {
3589
+ format: protocol ?? "json",
3590
+ allowedLabels: allowedLabels ?? this.#guard.allowed
3591
+ });
3592
+ const client = new BatchingLogClient(exporter, batching);
3593
+ this.#logClients.add(client);
3594
+ return client;
3595
+ }
3596
+ /** A {@link LogQueryClient} (search, tail, listStreams, listLabels, waitForLog) on this Loki. */
3597
+ logQueryClient() {
3598
+ return new LokiLogQueryClient(this);
3599
+ }
3600
+ /**
3601
+ * Flushes and closes log clients created by {@link logClient}, stops open tails and releases
3602
+ * connections (children from {@link withTenant} leave the shared connections open).
3603
+ * Idempotent.
3604
+ */
3605
+ close() {
3606
+ this.#closing ??= this.#shutdown();
3607
+ return this.#closing;
3608
+ }
3609
+ async #shutdown() {
3610
+ await Promise.allSettled([...this.#logClients].map((c) => c.close()));
3611
+ this.#logClients.clear();
3612
+ this.#closed = true;
3613
+ for (const t of this.#tails) t.stop();
3614
+ this.#tails.clear();
3615
+ if (this.#ownsTransport) await this.#transport.close();
3616
+ }
3617
+ };
3618
+
3619
+ export { ALL_STREAMS_SELECTOR, BatchProcessor, BatchingLogClient, CardinalityGuard, DEFAULT_ALLOWED_LABELS, DEFAULT_BATCH_OPTIONS, DEFAULT_REDACT_KEYS, DEFAULT_REQUEST_ID_HEADERS, DEFAULT_TIMEOUTS, ENCODING_FLAGS_HEADER, EnvReader, HttpTransport, LABEL_NAME_PATTERN, LANGUAGE, LogQL, Logger, LokiClient, LokiConfig, LokiLogExporter, LokiLogQueryClient, LokiOtlpExporter, MAX_QUERY_LIMIT, MAX_TENANT_ID_LENGTH, MAX_VENDOR_TEXT, MIN_SECRET_LENGTH, OTLP_SCOPE_NAME, PACKAGE_KEY, REDACTED, RESERVED_METADATA_KEYS, RedactionProcessor, RetryPolicy, SDK_KIT_VERSION, SDK_VERSION, SENSITIVE_FIELD_PARTS, Secret, TENANT_HEADER, VENDOR_ENV, WinstonTransport, attrToString, createDispatcher, createPinoTransport, dateToNanos, decodeBuildInfo, decodeCursor, decodeEntry, decodeIndexStats, decodeQueryResult, decodeRpcStatusMessage, decodeSeries, decodeStreams, decodeStringList, decodeTailFrame, definedOnly, describeCommonConfig, encodeCursor, encodePushRequest, entryToLogRecord, formatLabelSet, healthStatus, isHealthyWord, isIdempotentMethod, isRetryableStatus, isSensitiveField, isSensitiveHeader, isValidLabelName, mergeOptions, mergeStreams, msToDuration, nanosToDate, normalizeLabelName, optionalNanos, parseBool, parseDuration, parseInteger, parseRetryAfter, pinoLevelToSeverity, pinoLineToRecord, probeHealth, quoteLogQL, readCommonEnv, recordsToOtlpJson, recordsToStreams, redactError, redactFields, redactHeaders, redactSecretsInText, redactText, redactUrl, resolveBatchOptions, resolveCommonConfig, safeCall, safeLogger, secondsToDate, secretValues, silentLogger, snappyCompress, stringMap, tenantIdProblem, toNanos, toOtlpValue, toSearchLogQL, validateCommonConfig, validateLabelName, validateLabels, winstonLevelToSeverity };
3620
+ //# sourceMappingURL=index.js.map
3621
+ //# sourceMappingURL=index.js.map