logquill 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,7 +1,8 @@
1
+ import { gzipSync } from 'zlib';
1
2
  import { mkdirSync, openSync, writeSync, fstatSync, closeSync, existsSync, unlinkSync, renameSync } from 'fs';
2
3
  import { dirname } from 'path';
3
4
 
4
- // src/levels.ts
5
+ // src/core/levels.ts
5
6
  var Level = /* @__PURE__ */ ((Level2) => {
6
7
  Level2[Level2["TRACE"] = 5] = "TRACE";
7
8
  Level2[Level2["DEBUG"] = 10] = "DEBUG";
@@ -36,7 +37,7 @@ function parseLevel(level) {
36
37
  return level;
37
38
  }
38
39
 
39
- // src/records.ts
40
+ // src/core/records.ts
40
41
  function utcTimestamp() {
41
42
  return (/* @__PURE__ */ new Date()).toISOString();
42
43
  }
@@ -50,14 +51,14 @@ function createRecord(params) {
50
51
  };
51
52
  }
52
53
 
53
- // src/formatter.ts
54
+ // src/core/formatter.ts
54
55
  var JSONFormatter = class {
55
56
  format(record) {
56
57
  return JSON.stringify(record);
57
58
  }
58
59
  };
59
60
 
60
- // src/context-plugin.ts
61
+ // src/plugins/context-plugin.ts
61
62
  var ContextPlugin = class {
62
63
  context;
63
64
  constructor(context) {
@@ -68,7 +69,7 @@ var ContextPlugin = class {
68
69
  }
69
70
  };
70
71
 
71
- // src/redact-plugin.ts
72
+ // src/plugins/redact-plugin.ts
72
73
  var DEFAULT_REDACTED_KEYS = ["password", "token", "secret", "api_key", "authorization"];
73
74
  var RedactPlugin = class {
74
75
  keys;
@@ -86,7 +87,7 @@ var RedactPlugin = class {
86
87
  }
87
88
  };
88
89
 
89
- // src/sampling-plugin.ts
90
+ // src/plugins/sampling-plugin.ts
90
91
  var SamplingPlugin = class {
91
92
  rate;
92
93
  rng;
@@ -102,7 +103,7 @@ var SamplingPlugin = class {
102
103
  }
103
104
  };
104
105
 
105
- // src/transport.ts
106
+ // src/transports/transport.ts
106
107
  var Transport = class {
107
108
  formatter;
108
109
  constructor(formatter = new JSONFormatter()) {
@@ -128,7 +129,1050 @@ var CollectingTransport = class extends Transport {
128
129
  }
129
130
  };
130
131
 
131
- // src/console-transport.ts
132
+ // src/transports/batching-transport.ts
133
+ var BatchingTransport = class extends Transport {
134
+ maxRecords;
135
+ maxBytes;
136
+ buffer = [];
137
+ bufferBytes = 0;
138
+ constructor(options = {}) {
139
+ super(options.formatter);
140
+ this.maxRecords = options.maxRecords ?? 100;
141
+ this.maxBytes = options.maxBytes ?? 1e6;
142
+ }
143
+ /** Converts a written record into the buffered item type. Defaults to the record itself. */
144
+ toItem(formatted, record) {
145
+ return record;
146
+ }
147
+ /** Estimated byte size of one buffered item, used for the `maxBytes` bound. */
148
+ sizeOf(item) {
149
+ return JSON.stringify(item).length;
150
+ }
151
+ write(formatted, record) {
152
+ const item = this.toItem(formatted, record);
153
+ this.buffer.push(item);
154
+ this.bufferBytes += this.sizeOf(item);
155
+ if (this.buffer.length >= this.maxRecords || this.bufferBytes >= this.maxBytes) {
156
+ this.flush();
157
+ }
158
+ }
159
+ /** Send the current batch now, even if it hasn't reached a bound. */
160
+ flush() {
161
+ if (this.buffer.length === 0) {
162
+ return;
163
+ }
164
+ const batch = this.buffer;
165
+ this.buffer = [];
166
+ this.bufferBytes = 0;
167
+ const result = this.sendBatch(batch);
168
+ if (result) {
169
+ result.catch((error) => {
170
+ console.error(`${this.constructor.name}: failed to send log batch`, error);
171
+ });
172
+ }
173
+ }
174
+ close() {
175
+ this.flush();
176
+ }
177
+ };
178
+
179
+ // src/transports/sql/base-sql-transport.ts
180
+ function metaString(meta, key) {
181
+ const value = meta[key];
182
+ return typeof value === "string" ? value : null;
183
+ }
184
+ var BaseSQLTransport = class extends BatchingTransport {
185
+ tableName;
186
+ ensureSchema;
187
+ schemaEnsured = false;
188
+ constructor(options = {}) {
189
+ super(options);
190
+ this.tableName = options.tableName ?? "logs";
191
+ this.ensureSchema = options.ensureSchema ?? false;
192
+ }
193
+ toItem(_formatted, record) {
194
+ return {
195
+ timestamp: record.timestamp,
196
+ level: record.level,
197
+ logger: record.logger,
198
+ message: record.message,
199
+ meta: JSON.stringify(record.meta),
200
+ runId: metaString(record.meta, "runId"),
201
+ spanId: metaString(record.meta, "spanId"),
202
+ parentSpanId: metaString(record.meta, "parentSpanId"),
203
+ traceId: metaString(record.meta, "traceId")
204
+ };
205
+ }
206
+ sizeOf(row) {
207
+ return row.message.length + row.meta.length + 96;
208
+ }
209
+ /**
210
+ * Minimal, dialect-generic `CREATE TABLE IF NOT EXISTS` for dev/test use via
211
+ * `ensureSchema: true`. Production deployments should manage this table with
212
+ * a real migration instead — override in a subclass for dialect-correct
213
+ * column types (e.g. `JSONB` on Postgres).
214
+ */
215
+ createTableSQL() {
216
+ return `CREATE TABLE IF NOT EXISTS ${this.tableName} (
217
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
218
+ timestamp TEXT NOT NULL,
219
+ level TEXT NOT NULL,
220
+ logger TEXT NOT NULL,
221
+ message TEXT NOT NULL,
222
+ meta TEXT NOT NULL,
223
+ runId TEXT,
224
+ spanId TEXT,
225
+ parentSpanId TEXT,
226
+ traceId TEXT
227
+ )`;
228
+ }
229
+ async sendBatch(rows) {
230
+ if (this.ensureSchema && !this.schemaEnsured) {
231
+ this.schemaEnsured = true;
232
+ await this.ensureTable();
233
+ }
234
+ await this.insertRows(rows);
235
+ }
236
+ };
237
+
238
+ // src/transports/sql/sqlite-transport.ts
239
+ var SQLiteTransport = class extends BaseSQLTransport {
240
+ injectedClient;
241
+ filename;
242
+ client;
243
+ constructor(options = {}) {
244
+ super(options);
245
+ this.injectedClient = options.client;
246
+ this.filename = options.filename ?? ":memory:";
247
+ }
248
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
249
+ resolvedClient() {
250
+ return this.injectedClient ?? this.client;
251
+ }
252
+ async importClient() {
253
+ let DatabaseCtor;
254
+ try {
255
+ const moduleName = "better-sqlite3";
256
+ const mod = await import(moduleName);
257
+ DatabaseCtor = mod.default;
258
+ } catch {
259
+ throw new Error(
260
+ "SQLiteTransport: install `better-sqlite3` to use this transport without providing a client \u2014 `npm install better-sqlite3`"
261
+ );
262
+ }
263
+ this.client = new DatabaseCtor(this.filename);
264
+ return this.client;
265
+ }
266
+ async ensureTable() {
267
+ const client = this.resolvedClient() ?? await this.importClient();
268
+ client.exec(this.createTableSQL());
269
+ }
270
+ async insertRows(rows) {
271
+ const client = this.resolvedClient() ?? await this.importClient();
272
+ const stmt = client.prepare(
273
+ `INSERT INTO ${this.tableName} (timestamp, level, logger, message, meta, runId, spanId, parentSpanId, traceId) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`
274
+ );
275
+ const insertMany = client.transaction((batch) => {
276
+ for (const row of batch) {
277
+ stmt.run(
278
+ row.timestamp,
279
+ row.level,
280
+ row.logger,
281
+ row.message,
282
+ row.meta,
283
+ row.runId,
284
+ row.spanId,
285
+ row.parentSpanId,
286
+ row.traceId
287
+ );
288
+ }
289
+ });
290
+ insertMany(rows);
291
+ }
292
+ };
293
+
294
+ // src/transports/sql/postgres-transport.ts
295
+ var PostgresTransport = class extends BaseSQLTransport {
296
+ injectedClient;
297
+ connectionString;
298
+ connectionConfig;
299
+ client;
300
+ constructor(options = {}) {
301
+ super(options);
302
+ this.injectedClient = options.client;
303
+ this.connectionString = options.connectionString;
304
+ this.connectionConfig = options.connectionConfig;
305
+ }
306
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
307
+ resolvedClient() {
308
+ return this.injectedClient ?? this.client;
309
+ }
310
+ async importClient() {
311
+ let PoolCtor;
312
+ try {
313
+ const moduleName = "pg";
314
+ const mod = await import(moduleName);
315
+ const resolved = mod.default?.Pool ?? mod.Pool;
316
+ if (!resolved) {
317
+ throw new Error("no Pool export found");
318
+ }
319
+ PoolCtor = resolved;
320
+ } catch {
321
+ throw new Error(
322
+ "PostgresTransport: install `pg` to use this transport without providing a client \u2014 `npm install pg`"
323
+ );
324
+ }
325
+ const config = this.connectionString ? { connectionString: this.connectionString } : this.connectionConfig ?? {};
326
+ this.client = new PoolCtor(config);
327
+ return this.client;
328
+ }
329
+ /** Postgres-correct `CREATE TABLE IF NOT EXISTS`: `SERIAL` primary key, `JSONB` for `meta`. */
330
+ createTableSQL() {
331
+ return `CREATE TABLE IF NOT EXISTS ${this.tableName} (
332
+ id SERIAL PRIMARY KEY,
333
+ timestamp TEXT NOT NULL,
334
+ level TEXT NOT NULL,
335
+ logger TEXT NOT NULL,
336
+ message TEXT NOT NULL,
337
+ meta JSONB NOT NULL,
338
+ "runId" TEXT,
339
+ "spanId" TEXT,
340
+ "parentSpanId" TEXT,
341
+ "traceId" TEXT
342
+ )`;
343
+ }
344
+ async ensureTable() {
345
+ const client = this.resolvedClient() ?? await this.importClient();
346
+ await client.query(this.createTableSQL(), []);
347
+ }
348
+ async insertRows(rows) {
349
+ const client = this.resolvedClient() ?? await this.importClient();
350
+ const columns = 9;
351
+ const values = [];
352
+ const placeholders = [];
353
+ rows.forEach((row, rowIndex) => {
354
+ const base = rowIndex * columns;
355
+ placeholders.push(
356
+ `(${Array.from({ length: columns }, (_, col) => `$${String(base + col + 1)}`).join(", ")})`
357
+ );
358
+ values.push(
359
+ row.timestamp,
360
+ row.level,
361
+ row.logger,
362
+ row.message,
363
+ row.meta,
364
+ row.runId,
365
+ row.spanId,
366
+ row.parentSpanId,
367
+ row.traceId
368
+ );
369
+ });
370
+ const sql = `INSERT INTO ${this.tableName} (timestamp, level, logger, message, meta, "runId", "spanId", "parentSpanId", "traceId") VALUES ${placeholders.join(", ")}`;
371
+ await client.query(sql, values);
372
+ }
373
+ };
374
+
375
+ // src/transports/sql/mysql-transport.ts
376
+ var MySQLTransport = class extends BaseSQLTransport {
377
+ injectedClient;
378
+ connectionString;
379
+ connectionConfig;
380
+ client;
381
+ constructor(options = {}) {
382
+ super(options);
383
+ this.injectedClient = options.client;
384
+ this.connectionString = options.connectionString;
385
+ this.connectionConfig = options.connectionConfig;
386
+ }
387
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
388
+ resolvedClient() {
389
+ return this.injectedClient ?? this.client;
390
+ }
391
+ async importClient() {
392
+ let createPool;
393
+ try {
394
+ const moduleName = "mysql2/promise";
395
+ const mod = await import(moduleName);
396
+ const resolved = mod.default?.createPool ?? mod.createPool;
397
+ if (!resolved) {
398
+ throw new Error("no createPool export found");
399
+ }
400
+ createPool = resolved;
401
+ } catch {
402
+ throw new Error(
403
+ "MySQLTransport: install `mysql2` to use this transport without providing a client \u2014 `npm install mysql2`"
404
+ );
405
+ }
406
+ const target = this.connectionString ?? this.connectionConfig ?? {};
407
+ this.client = createPool(target);
408
+ return this.client;
409
+ }
410
+ /** MySQL-correct `CREATE TABLE IF NOT EXISTS`: `AUTO_INCREMENT` primary key, `JSON` column type for `meta`. */
411
+ createTableSQL() {
412
+ return `CREATE TABLE IF NOT EXISTS ${this.tableName} (
413
+ id INT AUTO_INCREMENT PRIMARY KEY,
414
+ timestamp VARCHAR(64) NOT NULL,
415
+ level VARCHAR(16) NOT NULL,
416
+ logger VARCHAR(255) NOT NULL,
417
+ message TEXT NOT NULL,
418
+ meta JSON NOT NULL,
419
+ runId VARCHAR(255),
420
+ spanId VARCHAR(255),
421
+ parentSpanId VARCHAR(255),
422
+ traceId VARCHAR(255)
423
+ )`;
424
+ }
425
+ async ensureTable() {
426
+ const client = this.resolvedClient() ?? await this.importClient();
427
+ await client.execute(this.createTableSQL(), []);
428
+ }
429
+ async insertRows(rows) {
430
+ const client = this.resolvedClient() ?? await this.importClient();
431
+ const columns = 9;
432
+ const values = [];
433
+ const placeholders = [];
434
+ for (const row of rows) {
435
+ placeholders.push(`(${Array.from({ length: columns }, () => "?").join(", ")})`);
436
+ values.push(
437
+ row.timestamp,
438
+ row.level,
439
+ row.logger,
440
+ row.message,
441
+ row.meta,
442
+ row.runId,
443
+ row.spanId,
444
+ row.parentSpanId,
445
+ row.traceId
446
+ );
447
+ }
448
+ const sql = `INSERT INTO ${this.tableName} (timestamp, level, logger, message, meta, runId, spanId, parentSpanId, traceId) VALUES ${placeholders.join(", ")}`;
449
+ await client.execute(sql, values);
450
+ }
451
+ };
452
+
453
+ // src/transports/nosql/mongodb-transport.ts
454
+ var MongoDBTransport = class extends BatchingTransport {
455
+ injectedCollection;
456
+ connectionString;
457
+ database;
458
+ collectionName;
459
+ collection;
460
+ constructor(options = {}) {
461
+ super(options);
462
+ this.injectedCollection = options.collection;
463
+ this.connectionString = options.connectionString;
464
+ this.database = options.database ?? "logquill";
465
+ this.collectionName = options.collectionName ?? "logs";
466
+ }
467
+ /** Synchronously available collection, if one was injected or already connected — avoids an unnecessary microtask hop on the hot path. */
468
+ resolvedCollection() {
469
+ return this.injectedCollection ?? this.collection;
470
+ }
471
+ async importCollection() {
472
+ if (!this.connectionString) {
473
+ throw new Error(
474
+ "MongoDBTransport: provide either a `collection` or a `connectionString` to connect with \u2014 neither was given"
475
+ );
476
+ }
477
+ let MongoClientCtor;
478
+ try {
479
+ const moduleName = "mongodb";
480
+ const mod = await import(moduleName);
481
+ MongoClientCtor = mod.MongoClient;
482
+ } catch {
483
+ throw new Error(
484
+ "MongoDBTransport: install `mongodb` to use this transport without providing a client \u2014 `npm install mongodb`"
485
+ );
486
+ }
487
+ const client = new MongoClientCtor(this.connectionString);
488
+ await client.connect();
489
+ this.collection = client.db(this.database).collection(this.collectionName);
490
+ return this.collection;
491
+ }
492
+ async sendBatch(batch) {
493
+ const collection = this.resolvedCollection() ?? await this.importCollection();
494
+ await collection.insertMany(batch.map((record) => ({ ...record })));
495
+ }
496
+ };
497
+
498
+ // src/transports/nosql/dynamodb-transport.ts
499
+ var DYNAMO_BATCH_LIMIT = 25;
500
+ function toAttributeValue(value) {
501
+ if (value === null || value === void 0) {
502
+ return { NULL: true };
503
+ }
504
+ if (typeof value === "string") {
505
+ return { S: value };
506
+ }
507
+ if (typeof value === "number") {
508
+ return { N: String(value) };
509
+ }
510
+ if (typeof value === "boolean") {
511
+ return { BOOL: value };
512
+ }
513
+ if (typeof value === "bigint") {
514
+ return { N: value.toString() };
515
+ }
516
+ if (Array.isArray(value)) {
517
+ return { L: value.map((entry) => toAttributeValue(entry)) };
518
+ }
519
+ if (typeof value === "object") {
520
+ const m = {};
521
+ for (const [key, entryValue] of Object.entries(value)) {
522
+ m[key] = toAttributeValue(entryValue);
523
+ }
524
+ return { M: m };
525
+ }
526
+ return { NULL: true };
527
+ }
528
+ function marshallItem(item) {
529
+ return toAttributeValue({ ...item }).M;
530
+ }
531
+ var DynamoDBTransport = class extends BatchingTransport {
532
+ injectedClient;
533
+ tableName;
534
+ region;
535
+ client;
536
+ constructor(options = {}) {
537
+ super(options);
538
+ this.injectedClient = options.client;
539
+ this.tableName = options.tableName ?? "logs";
540
+ this.region = options.region;
541
+ }
542
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
543
+ resolvedClient() {
544
+ return this.injectedClient ?? this.client;
545
+ }
546
+ async importClient() {
547
+ let DynamoDBClientCtor;
548
+ let BatchWriteItemCommandCtor;
549
+ try {
550
+ const moduleName = "@aws-sdk/client-dynamodb";
551
+ const mod = await import(moduleName);
552
+ DynamoDBClientCtor = mod.DynamoDBClient;
553
+ BatchWriteItemCommandCtor = mod.BatchWriteItemCommand;
554
+ } catch {
555
+ throw new Error(
556
+ "DynamoDBTransport: install `@aws-sdk/client-dynamodb` to use this transport without providing a client \u2014 `npm install @aws-sdk/client-dynamodb`"
557
+ );
558
+ }
559
+ const sdkClient = new DynamoDBClientCtor(this.region ? { region: this.region } : {});
560
+ this.client = {
561
+ async batchWriteItems(tableName, items) {
562
+ const requestItems = {
563
+ [tableName]: items.map((item) => ({ PutRequest: { Item: marshallItem(item) } }))
564
+ };
565
+ return sdkClient.send(new BatchWriteItemCommandCtor({ RequestItems: requestItems }));
566
+ }
567
+ };
568
+ return this.client;
569
+ }
570
+ /** `meta.runId`, else `meta.traceId`, else the logger name — see the class doc for why. */
571
+ partitionKey(record) {
572
+ const runId = record.meta.runId;
573
+ if (typeof runId === "string" && runId.length > 0) {
574
+ return runId;
575
+ }
576
+ const traceId = record.meta.traceId;
577
+ if (typeof traceId === "string" && traceId.length > 0) {
578
+ return traceId;
579
+ }
580
+ return record.logger;
581
+ }
582
+ toDynamoItem(record) {
583
+ const spanId = record.meta.spanId;
584
+ const parentSpanId = record.meta.parentSpanId;
585
+ const traceId = record.meta.traceId;
586
+ return {
587
+ runId: this.partitionKey(record),
588
+ timestamp: record.timestamp,
589
+ level: record.level,
590
+ logger: record.logger,
591
+ message: record.message,
592
+ meta: record.meta,
593
+ ...typeof spanId === "string" ? { spanId } : {},
594
+ ...typeof parentSpanId === "string" ? { parentSpanId } : {},
595
+ ...typeof traceId === "string" ? { traceId } : {}
596
+ };
597
+ }
598
+ async sendBatch(batch) {
599
+ const client = this.resolvedClient() ?? await this.importClient();
600
+ const items = batch.map((record) => this.toDynamoItem(record));
601
+ const chunks = [];
602
+ for (let offset = 0; offset < items.length; offset += DYNAMO_BATCH_LIMIT) {
603
+ chunks.push(items.slice(offset, offset + DYNAMO_BATCH_LIMIT));
604
+ }
605
+ await Promise.all(chunks.map((chunk) => client.batchWriteItems(this.tableName, chunk)));
606
+ }
607
+ };
608
+
609
+ // src/transports/nosql/redis-transport.ts
610
+ var RedisTransport = class extends BatchingTransport {
611
+ injectedClient;
612
+ url;
613
+ stream;
614
+ client;
615
+ constructor(options = {}) {
616
+ super(options);
617
+ this.injectedClient = options.client;
618
+ this.url = options.url ?? "redis://localhost:6379";
619
+ this.stream = options.stream ?? "logquill:logs";
620
+ }
621
+ /** Synchronously available client, if one was injected or already connected — avoids an unnecessary microtask hop on the hot path. */
622
+ resolvedClient() {
623
+ return this.injectedClient ?? this.client;
624
+ }
625
+ async importClient() {
626
+ let createClient;
627
+ try {
628
+ const moduleName = "redis";
629
+ const mod = await import(moduleName);
630
+ createClient = mod.createClient;
631
+ } catch {
632
+ throw new Error(
633
+ "RedisTransport: install `redis` to use this transport without providing a client \u2014 `npm install redis`"
634
+ );
635
+ }
636
+ const client = createClient({ url: this.url });
637
+ await client.connect();
638
+ this.client = client;
639
+ return client;
640
+ }
641
+ toFields(record) {
642
+ return {
643
+ timestamp: record.timestamp,
644
+ level: record.level,
645
+ logger: record.logger,
646
+ message: record.message,
647
+ meta: JSON.stringify(record.meta)
648
+ };
649
+ }
650
+ async sendBatch(batch) {
651
+ const client = this.resolvedClient() ?? await this.importClient();
652
+ await Promise.all(batch.map((record) => client.xAdd(this.stream, "*", this.toFields(record))));
653
+ }
654
+ };
655
+
656
+ // src/transports/queue/base-queue-transport.ts
657
+ var BaseQueueTransport = class extends BatchingTransport {
658
+ topic;
659
+ constructor(options) {
660
+ super(options);
661
+ this.topic = options.topic;
662
+ }
663
+ sendBatch(batch) {
664
+ return this.publishBatch(batch);
665
+ }
666
+ };
667
+
668
+ // src/transports/queue/kafka-transport.ts
669
+ function metaKey(meta, key) {
670
+ const value = meta[key];
671
+ return typeof value === "string" ? value : void 0;
672
+ }
673
+ var KafkaTransport = class extends BaseQueueTransport {
674
+ injectedClient;
675
+ brokers;
676
+ client;
677
+ constructor(options) {
678
+ super(options);
679
+ this.injectedClient = options.client;
680
+ this.brokers = options.brokers ?? ["localhost:9092"];
681
+ }
682
+ /** Synchronously available producer, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
683
+ resolvedClient() {
684
+ return this.injectedClient ?? this.client;
685
+ }
686
+ /**
687
+ * Builds the real `kafkajs` producer and connects it. Connection happens
688
+ * here, once, as part of acquiring the driver — not on every
689
+ * `publishBatch()` call — so an injected `client` (tests, or a caller's
690
+ * own already-connected producer) is trusted to already be ready and is
691
+ * never re-connected.
692
+ */
693
+ async importClient() {
694
+ let producer;
695
+ try {
696
+ const moduleName = "kafkajs";
697
+ const mod = await import(moduleName);
698
+ producer = new mod.Kafka({ brokers: this.brokers }).producer();
699
+ await producer.connect?.();
700
+ } catch {
701
+ throw new Error(
702
+ "KafkaTransport: install `kafkajs` to use this transport without providing a client \u2014 `npm install kafkajs`"
703
+ );
704
+ }
705
+ this.client = producer;
706
+ return producer;
707
+ }
708
+ async publishBatch(records) {
709
+ const client = this.resolvedClient() ?? await this.importClient();
710
+ await client.send({
711
+ topic: this.topic,
712
+ messages: records.map((record) => ({
713
+ key: metaKey(record.meta, "runId") ?? metaKey(record.meta, "traceId") ?? null,
714
+ value: JSON.stringify(record)
715
+ }))
716
+ });
717
+ }
718
+ };
719
+
720
+ // src/transports/queue/rabbitmq-transport.ts
721
+ var RabbitMQTransport = class extends BaseQueueTransport {
722
+ injectedClient;
723
+ url;
724
+ client;
725
+ constructor(options) {
726
+ super(options);
727
+ this.injectedClient = options.client;
728
+ this.url = options.url ?? "amqp://localhost";
729
+ }
730
+ /** Synchronously available channel, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
731
+ resolvedClient() {
732
+ return this.injectedClient ?? this.client;
733
+ }
734
+ /**
735
+ * Opens the real `amqplib` connection/channel and asserts the queue
736
+ * exists. Both happen here, once, as part of acquiring the driver — not on
737
+ * every `publishBatch()` call — so an injected `client` (tests, or a
738
+ * caller's own already-open channel) is trusted to already have its queue
739
+ * set up and is never re-asserted.
740
+ */
741
+ async importClient() {
742
+ let channel;
743
+ try {
744
+ const moduleName = "amqplib";
745
+ const mod = await import(moduleName);
746
+ const connection = await mod.connect(this.url);
747
+ channel = await connection.createChannel();
748
+ await channel.assertQueue?.(this.topic);
749
+ } catch {
750
+ throw new Error(
751
+ "RabbitMQTransport: install `amqplib` to use this transport without providing a client \u2014 `npm install amqplib`"
752
+ );
753
+ }
754
+ this.client = channel;
755
+ return channel;
756
+ }
757
+ async publishBatch(records) {
758
+ const client = this.resolvedClient() ?? await this.importClient();
759
+ for (const record of records) {
760
+ client.sendToQueue(this.topic, Buffer.from(JSON.stringify(record)));
761
+ }
762
+ }
763
+ };
764
+
765
+ // src/transports/queue/sqs-transport.ts
766
+ var SQS_BATCH_LIMIT = 10;
767
+ var SQSTransport = class extends BaseQueueTransport {
768
+ injectedClient;
769
+ region;
770
+ client;
771
+ constructor(options) {
772
+ super(options);
773
+ this.injectedClient = options.client;
774
+ this.region = options.region;
775
+ }
776
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
777
+ resolvedClient() {
778
+ return this.injectedClient ?? this.client;
779
+ }
780
+ async importClient() {
781
+ let client;
782
+ try {
783
+ const moduleName = "@aws-sdk/client-sqs";
784
+ const mod = await import(moduleName);
785
+ const sdkClient = new mod.SQSClient({ region: this.region });
786
+ const CommandCtor = mod.SendMessageBatchCommand;
787
+ client = {
788
+ sendMessageBatch: (queueUrl, entries) => sdkClient.send(
789
+ new CommandCtor({
790
+ QueueUrl: queueUrl,
791
+ Entries: entries.map((entry) => ({ Id: entry.id, MessageBody: entry.body }))
792
+ })
793
+ )
794
+ };
795
+ } catch {
796
+ throw new Error(
797
+ "SQSTransport: install `@aws-sdk/client-sqs` to use this transport without providing a client \u2014 `npm install @aws-sdk/client-sqs`"
798
+ );
799
+ }
800
+ this.client = client;
801
+ return client;
802
+ }
803
+ async publishBatch(records) {
804
+ const client = this.resolvedClient() ?? await this.importClient();
805
+ const chunks = [];
806
+ for (let start = 0; start < records.length; start += SQS_BATCH_LIMIT) {
807
+ chunks.push(records.slice(start, start + SQS_BATCH_LIMIT));
808
+ }
809
+ await Promise.all(
810
+ chunks.map(
811
+ (chunk) => client.sendMessageBatch(
812
+ this.topic,
813
+ chunk.map((record, index) => ({ id: String(index), body: JSON.stringify(record) }))
814
+ )
815
+ )
816
+ );
817
+ }
818
+ };
819
+
820
+ // src/transports/queue/pubsub-transport.ts
821
+ var PubSubTransport = class extends BaseQueueTransport {
822
+ injectedClient;
823
+ projectId;
824
+ client;
825
+ constructor(options) {
826
+ super(options);
827
+ this.injectedClient = options.client;
828
+ this.projectId = options.projectId;
829
+ }
830
+ /** Synchronously available topic reference, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
831
+ resolvedClient() {
832
+ return this.injectedClient ?? this.client;
833
+ }
834
+ async importClient() {
835
+ let topic;
836
+ try {
837
+ const moduleName = "@google-cloud/pubsub";
838
+ const mod = await import(moduleName);
839
+ topic = new mod.PubSub({ projectId: this.projectId }).topic(this.topic);
840
+ } catch {
841
+ throw new Error(
842
+ "PubSubTransport: install `@google-cloud/pubsub` to use this transport without providing a client \u2014 `npm install @google-cloud/pubsub`"
843
+ );
844
+ }
845
+ this.client = topic;
846
+ return topic;
847
+ }
848
+ async publishBatch(records) {
849
+ const client = this.resolvedClient() ?? await this.importClient();
850
+ await Promise.all(records.map((record) => client.publishMessage({ data: Buffer.from(JSON.stringify(record)) })));
851
+ }
852
+ };
853
+
854
+ // src/transports/cloud/cloudwatch-transport.ts
855
+ var CloudWatchTransport = class extends BatchingTransport {
856
+ logGroupName;
857
+ logStreamName;
858
+ region;
859
+ injectedClient;
860
+ client;
861
+ constructor(options) {
862
+ super(options);
863
+ this.logGroupName = options.logGroupName;
864
+ this.logStreamName = options.logStreamName;
865
+ this.region = options.region;
866
+ this.injectedClient = options.client;
867
+ }
868
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
869
+ resolvedClient() {
870
+ return this.injectedClient ?? this.client;
871
+ }
872
+ async importClient() {
873
+ let ClientCtor;
874
+ let PutLogEventsCommandCtor;
875
+ try {
876
+ const moduleName = "@aws-sdk/client-cloudwatch-logs";
877
+ const mod = await import(moduleName);
878
+ ClientCtor = mod.CloudWatchLogsClient;
879
+ PutLogEventsCommandCtor = mod.PutLogEventsCommand;
880
+ } catch {
881
+ throw new Error(
882
+ "CloudWatchTransport: install `@aws-sdk/client-cloudwatch-logs` to use this transport without providing a client \u2014 `npm install @aws-sdk/client-cloudwatch-logs`"
883
+ );
884
+ }
885
+ const sdkClient = new ClientCtor({ region: this.region });
886
+ this.client = {
887
+ putLogEvents: (logGroupName, logStreamName, events) => sdkClient.send(
888
+ new PutLogEventsCommandCtor({
889
+ logGroupName,
890
+ logStreamName,
891
+ logEvents: events
892
+ })
893
+ )
894
+ };
895
+ return this.client;
896
+ }
897
+ async sendBatch(batch) {
898
+ const client = this.resolvedClient() ?? await this.importClient();
899
+ const events = batch.map((record) => ({
900
+ timestamp: Date.parse(record.timestamp),
901
+ message: this.format(record)
902
+ })).sort((a, b) => a.timestamp - b.timestamp);
903
+ await client.putLogEvents(this.logGroupName, this.logStreamName, events);
904
+ }
905
+ };
906
+
907
+ // src/transports/cloud/cloud-logging-transport.ts
908
+ function gcpSeverity(levelValue) {
909
+ const level = parseLevel(levelValue);
910
+ switch (level) {
911
+ case 5 /* TRACE */:
912
+ case 10 /* DEBUG */:
913
+ return "DEBUG";
914
+ case 20 /* INFO */:
915
+ return "INFO";
916
+ case 30 /* WARN */:
917
+ return "WARNING";
918
+ case 40 /* ERROR */:
919
+ return "ERROR";
920
+ case 50 /* FATAL */:
921
+ return "CRITICAL";
922
+ }
923
+ }
924
+ var CloudLoggingTransport = class extends BatchingTransport {
925
+ logName;
926
+ projectId;
927
+ injectedClient;
928
+ client;
929
+ constructor(options = {}) {
930
+ super(options);
931
+ this.logName = options.logName ?? "logquill";
932
+ this.projectId = options.projectId;
933
+ this.injectedClient = options.client;
934
+ }
935
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
936
+ resolvedClient() {
937
+ return this.injectedClient ?? this.client;
938
+ }
939
+ async importClient() {
940
+ let LoggingCtor;
941
+ try {
942
+ const moduleName = "@google-cloud/logging";
943
+ const mod = await import(moduleName);
944
+ LoggingCtor = mod.Logging;
945
+ } catch {
946
+ throw new Error(
947
+ "CloudLoggingTransport: install `@google-cloud/logging` to use this transport without providing a client \u2014 `npm install @google-cloud/logging`"
948
+ );
949
+ }
950
+ const logging = new LoggingCtor({ projectId: this.projectId });
951
+ const log = logging.log(this.logName);
952
+ this.client = {
953
+ writeLogEntries: (entries) => log.write(entries)
954
+ };
955
+ return this.client;
956
+ }
957
+ async sendBatch(batch) {
958
+ const client = this.resolvedClient() ?? await this.importClient();
959
+ const entries = batch.map((record) => ({
960
+ severity: gcpSeverity(record.level),
961
+ timestamp: record.timestamp,
962
+ jsonPayload: JSON.parse(this.format(record))
963
+ }));
964
+ await client.writeLogEntries(entries);
965
+ }
966
+ };
967
+
968
+ // src/transports/cloud/app-insights-transport.ts
969
+ function appInsightsSeverity(levelValue) {
970
+ const level = parseLevel(levelValue);
971
+ switch (level) {
972
+ case 5 /* TRACE */:
973
+ case 10 /* DEBUG */:
974
+ return 0;
975
+ // Verbose
976
+ case 20 /* INFO */:
977
+ return 1;
978
+ // Information
979
+ case 30 /* WARN */:
980
+ return 2;
981
+ // Warning
982
+ case 40 /* ERROR */:
983
+ return 3;
984
+ // Error
985
+ case 50 /* FATAL */:
986
+ return 4;
987
+ }
988
+ }
989
+ var AppInsightsTransport = class extends BatchingTransport {
990
+ connectionString;
991
+ injectedClient;
992
+ client;
993
+ constructor(options = {}) {
994
+ super(options);
995
+ this.connectionString = options.connectionString;
996
+ this.injectedClient = options.client;
997
+ }
998
+ /** Synchronously available client, if one was injected or already imported — avoids an unnecessary microtask hop on the hot path. */
999
+ resolvedClient() {
1000
+ return this.injectedClient ?? this.client;
1001
+ }
1002
+ async importClient() {
1003
+ let TelemetryClientCtor;
1004
+ try {
1005
+ const moduleName = "applicationinsights";
1006
+ const mod = await import(moduleName);
1007
+ TelemetryClientCtor = mod.TelemetryClient;
1008
+ } catch {
1009
+ throw new Error(
1010
+ "AppInsightsTransport: install `applicationinsights` to use this transport without providing a client \u2014 `npm install applicationinsights`"
1011
+ );
1012
+ }
1013
+ const telemetryClient = new TelemetryClientCtor(this.connectionString);
1014
+ this.client = {
1015
+ trackTraceBatch: (traces) => {
1016
+ for (const trace of traces) {
1017
+ telemetryClient.trackTrace(trace);
1018
+ }
1019
+ telemetryClient.flush();
1020
+ return Promise.resolve();
1021
+ }
1022
+ };
1023
+ return this.client;
1024
+ }
1025
+ async sendBatch(batch) {
1026
+ const client = this.resolvedClient() ?? await this.importClient();
1027
+ const traces = batch.map((record) => ({
1028
+ message: this.format(record),
1029
+ severity: appInsightsSeverity(record.level)
1030
+ }));
1031
+ await client.trackTraceBatch(traces);
1032
+ }
1033
+ };
1034
+
1035
+ // src/transports/cloud/datadog-transport.ts
1036
+ async function fetchDatadogSender(url, apiKey, batch) {
1037
+ const response = await fetch(url, {
1038
+ method: "POST",
1039
+ headers: { "Content-Type": "application/json", "DD-API-KEY": apiKey },
1040
+ body: `[${batch.join(",")}]`
1041
+ });
1042
+ if (!response.ok) {
1043
+ throw new Error(
1044
+ `DatadogTransport: request to ${url} failed with status ${String(response.status)} \u2014 check the API key and site region`
1045
+ );
1046
+ }
1047
+ }
1048
+ var DatadogTransport = class extends BatchingTransport {
1049
+ url;
1050
+ apiKey;
1051
+ site;
1052
+ sender;
1053
+ constructor(options) {
1054
+ super(options);
1055
+ this.apiKey = options.apiKey;
1056
+ this.site = options.site ?? "datadoghq.com";
1057
+ this.url = `https://http-intake.logs.${this.site}/api/v2/logs`;
1058
+ this.sender = options.sender ?? fetchDatadogSender;
1059
+ }
1060
+ sendBatch(batch) {
1061
+ const formatted = batch.map((record) => this.format(record));
1062
+ return this.sender(this.url, this.apiKey, formatted);
1063
+ }
1064
+ };
1065
+
1066
+ // src/transports/cloud/elasticsearch-transport.ts
1067
+ async function fetchElasticsearchSender(url, headers, body) {
1068
+ const response = await fetch(url, {
1069
+ method: "POST",
1070
+ headers: { ...headers, "Content-Type": "application/x-ndjson" },
1071
+ body
1072
+ });
1073
+ if (!response.ok) {
1074
+ throw new Error(`ElasticsearchTransport: request to ${url} failed with status ${String(response.status)}`);
1075
+ }
1076
+ }
1077
+ var ElasticsearchTransport = class extends BatchingTransport {
1078
+ url;
1079
+ index;
1080
+ apiKey;
1081
+ sender;
1082
+ constructor(options) {
1083
+ super(options);
1084
+ this.index = options.index ?? "logs";
1085
+ this.url = `${options.node.replace(/\/+$/, "")}/_bulk`;
1086
+ this.apiKey = options.apiKey;
1087
+ this.sender = options.sender ?? fetchElasticsearchSender;
1088
+ }
1089
+ sendBatch(batch) {
1090
+ const lines = [];
1091
+ for (const record of batch) {
1092
+ lines.push(JSON.stringify({ index: { _index: this.index } }));
1093
+ lines.push(this.format(record));
1094
+ }
1095
+ const body = `${lines.join("\n")}
1096
+ `;
1097
+ const headers = {};
1098
+ if (this.apiKey !== void 0) {
1099
+ headers.Authorization = `ApiKey ${this.apiKey}`;
1100
+ }
1101
+ return this.sender(this.url, headers, body);
1102
+ }
1103
+ };
1104
+ async function fetchNewRelicSender(url, headers, body) {
1105
+ const response = await fetch(url, { method: "POST", headers, body });
1106
+ return {
1107
+ ok: response.ok,
1108
+ status: response.status,
1109
+ retryAfter: response.headers.get("retry-after")
1110
+ };
1111
+ }
1112
+ function withoutEventType(record) {
1113
+ const meta = { ...record.meta };
1114
+ delete meta.eventType;
1115
+ return { ...record, meta };
1116
+ }
1117
+ function resumeTimestamp(retryAfter, now) {
1118
+ if (retryAfter === null) {
1119
+ return now + 6e4;
1120
+ }
1121
+ const seconds = Number(retryAfter);
1122
+ if (Number.isFinite(seconds)) {
1123
+ return now + seconds * 1e3;
1124
+ }
1125
+ const dateMs = Date.parse(retryAfter);
1126
+ return Number.isNaN(dateMs) ? now + 6e4 : dateMs;
1127
+ }
1128
+ var NewRelicTransport = class extends BatchingTransport {
1129
+ url;
1130
+ region;
1131
+ licenseKey;
1132
+ sender;
1133
+ clock;
1134
+ pausedUntil = null;
1135
+ constructor(options) {
1136
+ super(options);
1137
+ this.licenseKey = options.licenseKey;
1138
+ this.region = options.region ?? "US";
1139
+ this.url = this.region === "EU" ? "https://log-api.eu.newrelic.com/log/v1" : "https://log-api.newrelic.com/log/v1";
1140
+ this.sender = options.sender ?? fetchNewRelicSender;
1141
+ this.clock = options.clock ?? Date.now;
1142
+ }
1143
+ async sendBatch(batch) {
1144
+ const now = this.clock();
1145
+ if (this.pausedUntil !== null && now < this.pausedUntil) {
1146
+ console.error(
1147
+ `NewRelicTransport: sends paused until ${new Date(this.pausedUntil).toISOString()} after a 429 rate-limit response \u2014 skipping this batch rather than making a doomed request`
1148
+ );
1149
+ return;
1150
+ }
1151
+ this.pausedUntil = null;
1152
+ const records = batch.map((record) => withoutEventType(record));
1153
+ const body = gzipSync(Buffer.from(JSON.stringify(records)));
1154
+ const headers = {
1155
+ "Content-Type": "application/json",
1156
+ "Content-Encoding": "gzip",
1157
+ "Api-Key": this.licenseKey
1158
+ };
1159
+ const result = await this.sender(this.url, headers, body);
1160
+ if (result.status === 429) {
1161
+ this.pausedUntil = resumeTimestamp(result.retryAfter, now);
1162
+ console.error(
1163
+ `NewRelicTransport: received 429 from New Relic \u2014 pausing sends until ${new Date(this.pausedUntil).toISOString()}. Reduce log volume or increase batching to stay under the rate limit.`
1164
+ );
1165
+ return;
1166
+ }
1167
+ if (!result.ok) {
1168
+ throw new Error(
1169
+ `NewRelicTransport: request to ${this.url} failed with status ${String(result.status)} \u2014 check the license key and region`
1170
+ );
1171
+ }
1172
+ }
1173
+ };
1174
+
1175
+ // src/transports/console-transport.ts
132
1176
  var COLORS = {
133
1177
  [5 /* TRACE */]: "\x1B[90m",
134
1178
  // gray
@@ -216,7 +1260,7 @@ var FileTransport = class extends Transport {
216
1260
  }
217
1261
  };
218
1262
 
219
- // src/http-transport.ts
1263
+ // src/transports/http-transport.ts
220
1264
  async function fetchSender(url, batch) {
221
1265
  const response = await fetch(url, {
222
1266
  method: "POST",
@@ -263,7 +1307,7 @@ var HTTPTransport = class extends Transport {
263
1307
  }
264
1308
  };
265
1309
 
266
- // src/logger.ts
1310
+ // src/core/logger.ts
267
1311
  var Logger = class _Logger {
268
1312
  name;
269
1313
  transports;
@@ -365,8 +1409,8 @@ var Logger = class _Logger {
365
1409
  };
366
1410
 
367
1411
  // src/index.ts
368
- var VERSION = "0.1.2";
1412
+ var VERSION = "0.2.0";
369
1413
 
370
- export { CollectingTransport, ConsoleTransport, ContextPlugin, DEFAULT_REDACTED_KEYS, FileTransport, HTTPTransport, JSONFormatter, Level, Logger, RedactPlugin, SamplingPlugin, Transport, VERSION, createRecord, levelName, parseLevel, utcTimestamp };
1414
+ export { AppInsightsTransport, BaseQueueTransport, BaseSQLTransport, BatchingTransport, CloudLoggingTransport, CloudWatchTransport, CollectingTransport, ConsoleTransport, ContextPlugin, DEFAULT_REDACTED_KEYS, DatadogTransport, DynamoDBTransport, ElasticsearchTransport, FileTransport, HTTPTransport, JSONFormatter, KafkaTransport, Level, Logger, MongoDBTransport, MySQLTransport, NewRelicTransport, PostgresTransport, PubSubTransport, RabbitMQTransport, RedactPlugin, RedisTransport, SQLiteTransport, SQSTransport, SamplingPlugin, Transport, VERSION, createRecord, levelName, parseLevel, utcTimestamp };
371
1415
  //# sourceMappingURL=index.mjs.map
372
1416
  //# sourceMappingURL=index.mjs.map