@dxos/log 0.8.4-main.ae835ea → 0.8.4-main.bbf232bc24

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.
Files changed (93) hide show
  1. package/dist/lib/browser/chunk-IEP6GGEX.mjs +23 -0
  2. package/dist/lib/browser/chunk-IEP6GGEX.mjs.map +7 -0
  3. package/dist/lib/browser/chunk-V7FYKT4H.mjs +311 -0
  4. package/dist/lib/browser/chunk-V7FYKT4H.mjs.map +7 -0
  5. package/dist/lib/browser/index.mjs +346 -199
  6. package/dist/lib/browser/index.mjs.map +4 -4
  7. package/dist/lib/browser/meta.json +1 -1
  8. package/dist/lib/browser/platform/browser/index.mjs +26 -0
  9. package/dist/lib/browser/platform/browser/index.mjs.map +7 -0
  10. package/dist/lib/browser/platform/node/index.mjs +21 -0
  11. package/dist/lib/browser/platform/node/index.mjs.map +7 -0
  12. package/dist/lib/browser/processors/console-processor.mjs +102 -0
  13. package/dist/lib/browser/processors/console-processor.mjs.map +7 -0
  14. package/dist/lib/browser/processors/console-stub.mjs +9 -0
  15. package/dist/lib/browser/processors/console-stub.mjs.map +7 -0
  16. package/dist/lib/node-esm/chunk-2SZHAWBN.mjs +24 -0
  17. package/dist/lib/node-esm/chunk-2SZHAWBN.mjs.map +7 -0
  18. package/dist/lib/node-esm/chunk-5TBDXMQF.mjs +313 -0
  19. package/dist/lib/node-esm/chunk-5TBDXMQF.mjs.map +7 -0
  20. package/dist/lib/node-esm/index.mjs +348 -288
  21. package/dist/lib/node-esm/index.mjs.map +4 -4
  22. package/dist/lib/node-esm/meta.json +1 -1
  23. package/dist/lib/node-esm/platform/browser/index.mjs +27 -0
  24. package/dist/lib/node-esm/platform/browser/index.mjs.map +7 -0
  25. package/dist/lib/node-esm/platform/node/index.mjs +22 -0
  26. package/dist/lib/node-esm/platform/node/index.mjs.map +7 -0
  27. package/dist/lib/node-esm/processors/console-processor.mjs +103 -0
  28. package/dist/lib/node-esm/processors/console-processor.mjs.map +7 -0
  29. package/dist/lib/node-esm/processors/console-stub.mjs +10 -0
  30. package/dist/lib/node-esm/processors/console-stub.mjs.map +7 -0
  31. package/dist/types/src/config.d.ts.map +1 -1
  32. package/dist/types/src/context.d.ts +78 -2
  33. package/dist/types/src/context.d.ts.map +1 -1
  34. package/dist/types/src/dbg.d.ts +23 -0
  35. package/dist/types/src/dbg.d.ts.map +1 -0
  36. package/dist/types/src/decorators.d.ts +1 -1
  37. package/dist/types/src/decorators.d.ts.map +1 -1
  38. package/dist/types/src/environment.d.ts +24 -0
  39. package/dist/types/src/environment.d.ts.map +1 -0
  40. package/dist/types/src/environment.test.d.ts +2 -0
  41. package/dist/types/src/environment.test.d.ts.map +1 -0
  42. package/dist/types/src/experimental/ownership.d.ts.map +1 -1
  43. package/dist/types/src/index.d.ts +7 -3
  44. package/dist/types/src/index.d.ts.map +1 -1
  45. package/dist/types/src/jsonl.d.ts +53 -0
  46. package/dist/types/src/jsonl.d.ts.map +1 -0
  47. package/dist/types/src/jsonl.test.d.ts +2 -0
  48. package/dist/types/src/jsonl.test.d.ts.map +1 -0
  49. package/dist/types/src/log-buffer.d.ts +20 -0
  50. package/dist/types/src/log-buffer.d.ts.map +1 -0
  51. package/dist/types/src/log-buffer.test.d.ts +2 -0
  52. package/dist/types/src/log-buffer.test.d.ts.map +1 -0
  53. package/dist/types/src/log.d.ts +55 -18
  54. package/dist/types/src/log.d.ts.map +1 -1
  55. package/dist/types/src/meta.d.ts +20 -1
  56. package/dist/types/src/meta.d.ts.map +1 -1
  57. package/dist/types/src/options.d.ts +1 -6
  58. package/dist/types/src/options.d.ts.map +1 -1
  59. package/dist/types/src/platform/browser/index.d.ts.map +1 -1
  60. package/dist/types/src/platform/index.d.ts +1 -1
  61. package/dist/types/src/platform/index.d.ts.map +1 -1
  62. package/dist/types/src/platform/node/index.d.ts.map +1 -1
  63. package/dist/types/src/processors/browser-processor.d.ts.map +1 -1
  64. package/dist/types/src/processors/common.d.ts.map +1 -1
  65. package/dist/types/src/processors/console-processor.d.ts.map +1 -1
  66. package/dist/types/src/processors/file-processor.d.ts.map +1 -1
  67. package/dist/types/src/processors/index.d.ts +3 -3
  68. package/dist/types/src/processors/index.d.ts.map +1 -1
  69. package/dist/types/src/scope.d.ts.map +1 -1
  70. package/dist/types/tsconfig.tsbuildinfo +1 -1
  71. package/package.json +30 -15
  72. package/src/config.ts +1 -0
  73. package/src/context.ts +278 -7
  74. package/src/dbg.ts +34 -0
  75. package/src/decorators.ts +4 -5
  76. package/src/environment.test.ts +222 -0
  77. package/src/environment.ts +129 -0
  78. package/src/experimental/classes.test.ts +0 -1
  79. package/src/index.ts +7 -4
  80. package/src/jsonl.test.ts +121 -0
  81. package/src/jsonl.ts +104 -0
  82. package/src/log-buffer.test.ts +158 -0
  83. package/src/log-buffer.ts +89 -0
  84. package/src/log.test.ts +48 -19
  85. package/src/log.ts +146 -58
  86. package/src/meta.ts +29 -1
  87. package/src/options.ts +26 -10
  88. package/src/platform/index.ts +1 -1
  89. package/src/platform/node/index.ts +1 -2
  90. package/src/processors/browser-processor.ts +27 -28
  91. package/src/processors/console-processor.ts +5 -13
  92. package/src/processors/file-processor.ts +9 -9
  93. package/src/processors/index.ts +3 -3
@@ -1,104 +1,159 @@
1
- // src/index.ts
2
- import omit from "lodash.omit";
3
- import { pick } from "@dxos/util";
1
+ import {
2
+ LogEntry,
3
+ LogLevel,
4
+ LogProcessorType,
5
+ gatherLogInfoFromScope,
6
+ getContextFromEntry,
7
+ getRelativeFilename,
8
+ levels,
9
+ logInfo,
10
+ shortLevelName,
11
+ shouldLog
12
+ } from "./chunk-V7FYKT4H.mjs";
13
+ import {
14
+ __export,
15
+ __reExport
16
+ } from "./chunk-IEP6GGEX.mjs";
4
17
 
5
- // src/config.ts
6
- var LogLevel = /* @__PURE__ */ (function(LogLevel2) {
7
- LogLevel2[LogLevel2["TRACE"] = 5] = "TRACE";
8
- LogLevel2[LogLevel2["DEBUG"] = 10] = "DEBUG";
9
- LogLevel2[LogLevel2["VERBOSE"] = 11] = "VERBOSE";
10
- LogLevel2[LogLevel2["INFO"] = 12] = "INFO";
11
- LogLevel2[LogLevel2["WARN"] = 13] = "WARN";
12
- LogLevel2[LogLevel2["ERROR"] = 14] = "ERROR";
13
- return LogLevel2;
14
- })({});
15
- var levels = {
16
- trace: 5,
17
- debug: 10,
18
- verbose: 11,
19
- info: 12,
20
- warn: 13,
21
- error: 14
22
- };
23
- var shortLevelName = {
24
- [5]: "T",
25
- [10]: "D",
26
- [11]: "V",
27
- [12]: "I",
28
- [13]: "W",
29
- [14]: "E"
30
- };
31
- var LogProcessorType = /* @__PURE__ */ (function(LogProcessorType2) {
32
- LogProcessorType2["CONSOLE"] = "console";
33
- LogProcessorType2["BROWSER"] = "browser";
34
- LogProcessorType2["DEBUG"] = "debug";
35
- return LogProcessorType2;
36
- })({});
18
+ // src/index.ts
19
+ var index_exports = {};
20
+ __export(index_exports, {
21
+ BROWSER_PROCESSOR: () => BROWSER_PROCESSOR,
22
+ DEBUG_PROCESSOR: () => DEBUG_PROCESSOR,
23
+ FILE_PROCESSOR: () => FILE_PROCESSOR,
24
+ LOG_META_MARKER: () => LOG_META_MARKER,
25
+ LogBuffer: () => LogBuffer,
26
+ LogEntry: () => LogEntry,
27
+ LogLevel: () => LogLevel,
28
+ LogProcessorType: () => LogProcessorType,
29
+ createFileProcessor: () => createFileProcessor,
30
+ createLog: () => createLog,
31
+ dbg: () => dbg,
32
+ debug: () => debug,
33
+ gatherLogInfoFromScope: () => gatherLogInfoFromScope,
34
+ getContextFromEntry: () => getContextFromEntry,
35
+ getCurrentOwnershipScope: () => getCurrentOwnershipScope,
36
+ getRelativeFilename: () => getRelativeFilename,
37
+ inferEnvironmentName: () => inferEnvironmentName,
38
+ isLogMeta: () => isLogMeta,
39
+ levels: () => levels,
40
+ log: () => log,
41
+ logInfo: () => logInfo,
42
+ omit: () => omit,
43
+ parseFilter: () => parseFilter,
44
+ pick: () => pick,
45
+ serializeToJsonl: () => serializeToJsonl,
46
+ shortLevelName: () => shortLevelName,
47
+ shouldLog: () => shouldLog
48
+ });
49
+ import { omit, pick } from "@dxos/util";
37
50
 
38
- // src/scope.ts
39
- var logInfoProperties = Symbol("logInfoProperties");
40
- var logInfo = (target, propertyKey, descriptor) => {
41
- (target[logInfoProperties] ??= []).push(propertyKey);
51
+ // src/environment.ts
52
+ var TAB_SUFFIX_STORAGE_KEY = "@dxos/log:env-suffix";
53
+ var SUFFIX_LENGTH = 6;
54
+ var randomSuffix = () => {
55
+ const cryptoRef = globalThis.crypto;
56
+ if (cryptoRef?.getRandomValues) {
57
+ const bytes = new Uint8Array(SUFFIX_LENGTH);
58
+ cryptoRef.getRandomValues(bytes);
59
+ let suffix = "";
60
+ for (const byte of bytes) {
61
+ suffix += (byte % 36).toString(36);
62
+ }
63
+ return suffix;
64
+ }
65
+ return Math.random().toString(36).slice(2, 2 + SUFFIX_LENGTH).padEnd(SUFFIX_LENGTH, "0");
42
66
  };
43
- var gatherLogInfoFromScope = (scope) => {
44
- if (!scope) {
45
- return {};
46
- }
47
- const res = {};
48
- const prototype = Object.getPrototypeOf(scope);
49
- const infoProps = (typeof prototype === "object" && prototype !== null ? prototype[logInfoProperties] : []) ?? [];
50
- for (const prop of infoProps) {
51
- try {
52
- res[prop] = typeof scope[prop] === "function" ? scope[prop]() : scope[prop];
53
- } catch (err) {
54
- res[prop] = err.message;
67
+ var getOrCreateTabSuffix = (session) => {
68
+ if (!session) {
69
+ return randomSuffix();
70
+ }
71
+ try {
72
+ const existing = session.getItem(TAB_SUFFIX_STORAGE_KEY);
73
+ if (existing && existing.length > 0) {
74
+ return existing;
55
75
  }
76
+ const suffix = randomSuffix();
77
+ session.setItem(TAB_SUFFIX_STORAGE_KEY, suffix);
78
+ return suffix;
79
+ } catch {
80
+ return randomSuffix();
56
81
  }
57
- return res;
58
82
  };
59
-
60
- // src/context.ts
61
- var matchFilter = (filter, level, path) => {
62
- return level >= filter.level && (!filter.pattern || path.includes(filter.pattern));
83
+ var isInstanceOf = (scope, ctorName) => {
84
+ const ctor = scope?.[ctorName];
85
+ return typeof ctor === "function" && scope instanceof ctor;
63
86
  };
64
- var shouldLog = (entry, filters) => {
65
- if (filters === void 0) {
66
- return true;
67
- } else {
68
- return filters.some((filter) => matchFilter(filter, entry.level, entry.meta?.F ?? ""));
87
+ var CF_WORKER_USER_AGENT = "Cloudflare-Workers";
88
+ var inferEnvironmentName = (options = {}) => {
89
+ const scope = options.scope ?? globalThis;
90
+ if (scope.navigator?.userAgent === CF_WORKER_USER_AGENT) {
91
+ return `cf-worker::${randomSuffix()}`;
92
+ }
93
+ if (isInstanceOf(scope, "SharedWorkerGlobalScope")) {
94
+ return `shared-worker:${scope.name ?? ""}:${randomSuffix()}`;
69
95
  }
96
+ if (isInstanceOf(scope, "ServiceWorkerGlobalScope")) {
97
+ return `service-worker::${randomSuffix()}`;
98
+ }
99
+ if (isInstanceOf(scope, "DedicatedWorkerGlobalScope")) {
100
+ return `dedicated-worker:${scope.name ?? ""}:${randomSuffix()}`;
101
+ }
102
+ if (scope.window !== void 0 && scope.window === scope) {
103
+ const origin = scope.location?.origin ?? "";
104
+ return `tab:${origin}:${getOrCreateTabSuffix(scope.sessionStorage)}`;
105
+ }
106
+ const proc = scope.process;
107
+ if (proc && typeof proc === "object" && proc.versions?.node) {
108
+ const pid = typeof proc.pid === "number" ? String(proc.pid) : "";
109
+ return `node:${pid}:${randomSuffix()}`;
110
+ }
111
+ return `unknown::${randomSuffix()}`;
70
112
  };
71
- var getContextFromEntry = (entry) => {
72
- let context;
73
- if (entry.meta) {
74
- const scopeInfo = gatherLogInfoFromScope(entry.meta.S);
75
- if (Object.keys(scopeInfo).length > 0) {
76
- context = Object.assign(context ?? {}, scopeInfo);
77
- }
113
+
114
+ // src/jsonl.ts
115
+ var serializeToJsonl = (entry, opts = {}) => {
116
+ if (entry.level <= LogLevel.TRACE) {
117
+ return void 0;
78
118
  }
79
- const entryContext = typeof entry.context === "function" ? entry.context() : entry.context;
80
- if (entryContext) {
81
- if (entryContext instanceof Error) {
82
- const c = entryContext.context;
83
- context = Object.assign(context ?? {}, {
84
- error: entryContext.stack,
85
- ...c
86
- });
87
- } else if (typeof entryContext === "object") {
88
- context = Object.assign(context ?? {}, entryContext);
119
+ const { filename, line, context: scopeName } = entry.computedMeta;
120
+ const record = {
121
+ t: new Date(entry.timestamp).toISOString(),
122
+ l: shortLevelName[entry.level] ?? "?",
123
+ m: entry.message ?? ""
124
+ };
125
+ if (filename !== void 0) {
126
+ record.f = filename;
127
+ }
128
+ if (line !== void 0) {
129
+ record.n = line;
130
+ }
131
+ if (scopeName !== void 0) {
132
+ record.o = scopeName;
133
+ }
134
+ if (entry.computedError !== void 0) {
135
+ record.e = entry.computedError;
136
+ }
137
+ if (opts.env !== void 0) {
138
+ record.i = opts.env;
139
+ }
140
+ const computedContext = entry.computedContext;
141
+ if (Object.keys(computedContext).length > 0) {
142
+ try {
143
+ record.c = JSON.stringify(computedContext);
144
+ } catch {
89
145
  }
90
146
  }
91
- if (entry.error) {
92
- context = Object.assign(context ?? {}, {
93
- error: entry.error
94
- });
147
+ try {
148
+ return JSON.stringify(record);
149
+ } catch {
150
+ return void 0;
95
151
  }
96
- return context && Object.keys(context).length > 0 ? context : void 0;
97
152
  };
98
153
 
99
154
  // src/decorators.ts
100
- import { inspect } from "@dxos/node-std/util";
101
155
  import chalk from "chalk";
156
+ import { inspect } from "@dxos/node-std/util";
102
157
  var nextPromiseId = 0;
103
158
  var createMethodLogDecorator = (log2) => (arg0, arg1, meta) => (target, propertyKey, descriptor) => {
104
159
  const method = descriptor.value;
@@ -195,60 +250,36 @@ var logAsyncResolved = (log2, methodName, resolvedValue, promiseId, startTime, c
195
250
  var logAsyncRejected = (log2, methodName, err, promiseId, startTime, combinedMeta) => {
196
251
  log2.info(`.${formatFunction(methodName)} \u21B2 \u{1F525} ${chalk.gray("reject")} ${formatPromise(promiseId)} ${formatTimeElapsed(startTime)} ${chalk.gray("=>")} ${err}`, {}, combinedMeta);
197
252
  };
198
- var greenCheck = typeof chalk.green === "function" ? chalk.green("\u2714") : "\u2714";
199
- var formatTimeElapsed = (startTime) => chalk.gray(`${(performance.now() - startTime).toFixed(0)}ms`);
200
253
  var COLOR_FUNCTION = [
201
254
  220,
202
255
  220,
203
256
  170
204
257
  ];
258
+ var greenCheck = typeof chalk.green === "function" ? chalk.green("\u2714") : "\u2714";
259
+ var formatTimeElapsed = (startTime) => chalk.gray(`${(performance.now() - startTime).toFixed(0)}ms`);
205
260
  var formatFunction = (name) => chalk.bold(chalk.rgb(...COLOR_FUNCTION)(name));
206
261
  var formatPromise = (id) => chalk.blue(`Promise#${id}`);
207
262
 
208
263
  // src/options.ts
209
264
  import defaultsDeep from "lodash.defaultsdeep";
210
265
 
211
- // src/platform/browser/index.ts
212
- var loadOptions = (filepath) => {
213
- try {
214
- let dxlog;
215
- if (typeof localStorage === "undefined") {
216
- if (globalThis.localStorage_dxlog) {
217
- dxlog = globalThis.localStorage_dxlog;
218
- }
219
- } else {
220
- dxlog = localStorage.getItem("dxlog") ?? void 0;
221
- }
222
- if (!dxlog) {
223
- return void 0;
224
- }
225
- return JSON.parse(dxlog);
226
- } catch (err) {
227
- console.info("can't parse dxlog config", err);
228
- return void 0;
229
- }
230
- };
231
-
232
- // src/processors/console-stub.ts
233
- var CONSOLE_PROCESSOR = () => {
234
- };
266
+ // src/platform/index.ts
267
+ var platform_exports = {};
268
+ __reExport(platform_exports, platform_star);
269
+ import * as platform_star from "#platform";
235
270
 
236
- // src/processors/debug-processor.ts
237
- import { inspect as inspect2 } from "@dxos/node-std/util";
238
- var DEBUG_PROCESSOR = (config, entry) => {
239
- console.log(inspect2(entry, false, null, true));
240
- };
271
+ // src/processors/index.ts
272
+ var processors_exports = {};
273
+ __export(processors_exports, {
274
+ BROWSER_PROCESSOR: () => BROWSER_PROCESSOR,
275
+ DEBUG_PROCESSOR: () => DEBUG_PROCESSOR,
276
+ FILE_PROCESSOR: () => FILE_PROCESSOR,
277
+ createFileProcessor: () => createFileProcessor,
278
+ getRelativeFilename: () => getRelativeFilename
279
+ });
241
280
 
242
281
  // src/processors/browser-processor.ts
243
- import { getDebugName, safariCheck } from "@dxos/util";
244
- var getRelativeFilename = (filename) => {
245
- const match = filename.match(/.+\/(packages\/.+\/.+)/);
246
- if (match) {
247
- const [, filePath] = match;
248
- return filePath;
249
- }
250
- return filename;
251
- };
282
+ import { safariCheck } from "@dxos/util";
252
283
  var CONFIG = {
253
284
  useTestProcessor: false,
254
285
  printFileLinks: false
@@ -259,18 +290,20 @@ var APP_BROWSER_PROCESSOR = (config, entry) => {
259
290
  }
260
291
  const LOG_BROWSER_PREFIX = config.prefix ?? "https://vscode.dev/github.com/dxos/dxos/blob/main/";
261
292
  const LOG_BROWSER_CSS = [];
293
+ const { filename, line: lineNumber, context: scopeDebugName } = entry.computedMeta;
262
294
  let link = "";
263
- if (entry.meta) {
264
- const filename = getRelativeFilename(entry.meta.F);
295
+ if (filename !== void 0 && lineNumber !== void 0) {
265
296
  const filepath = `${LOG_BROWSER_PREFIX.replace(/\/$/, "")}/${filename}`;
266
- link = `${filepath}#L${entry.meta.L}`;
297
+ link = `${filepath}#L${lineNumber}`;
267
298
  }
268
299
  let args = [];
269
- if (entry.meta?.S) {
270
- const scope = entry.meta?.S;
271
- const scopeName = scope.name || getDebugName(scope);
272
- const processPrefix = entry.meta.S?.hostSessionId ? "[worker] " : "";
273
- args.push(`%c${processPrefix}${scopeName}`, "color:#C026D3;font-weight:bold");
300
+ const scope = entry.meta?.S;
301
+ if (scope) {
302
+ const scopeName = scope.name || scopeDebugName;
303
+ if (scopeName) {
304
+ const processPrefix = scope.hostSessionId ? "[worker] " : "";
305
+ args.push(`%c${processPrefix}${scopeName}`, "color:#C026D3;font-weight:bold");
306
+ }
274
307
  }
275
308
  if (entry.message) {
276
309
  args.push(entry.message);
@@ -278,9 +311,9 @@ var APP_BROWSER_PROCESSOR = (config, entry) => {
278
311
  const context = getContextFromEntry(entry);
279
312
  if (context) {
280
313
  if (Object.keys(context).length === 1 && "error" in context) {
281
- args.push(context.error);
314
+ args.push(unwrapEffectError(context.error));
282
315
  } else if (Object.keys(context).length === 1 && "err" in context) {
283
- args.push(context.err);
316
+ args.push(unwrapEffectError(context.err));
284
317
  } else {
285
318
  args.push(context);
286
319
  }
@@ -315,10 +348,8 @@ var TEST_BROWSER_PROCESSOR = (config, entry) => {
315
348
  if (!shouldLog(entry, config.filters)) {
316
349
  return;
317
350
  }
318
- let path = "";
319
- if (entry.meta) {
320
- path = `${getRelativeFilename(entry.meta.F)}:${entry.meta.L}`;
321
- }
351
+ const { filename, line: lineNumber } = entry.computedMeta;
352
+ const path = filename !== void 0 && lineNumber !== void 0 ? `${filename}:${lineNumber}` : "";
322
353
  let args = [];
323
354
  const processPrefix = entry.meta?.S?.hostSessionId ? "[worker] " : "";
324
355
  args.push(`${processPrefix}${entry.message}`);
@@ -345,23 +376,27 @@ var TEST_BROWSER_PROCESSOR = (config, entry) => {
345
376
  }
346
377
  };
347
378
  var BROWSER_PROCESSOR = CONFIG.useTestProcessor ? TEST_BROWSER_PROCESSOR : APP_BROWSER_PROCESSOR;
379
+ var originalSymbol = /* @__PURE__ */ Symbol.for("effect/OriginalAnnotation");
380
+ var unwrapEffectError = (error) => {
381
+ if (typeof error === "object" && error !== null && originalSymbol in error) {
382
+ return error[originalSymbol];
383
+ }
384
+ return error;
385
+ };
348
386
 
349
- // src/processors/file-processor.ts
350
- import { appendFileSync, mkdirSync, openSync } from "@dxos/node-std/fs";
351
- import { dirname } from "@dxos/node-std/path";
352
- import { jsonlogify } from "@dxos/util";
387
+ // src/processors/index.ts
388
+ __reExport(processors_exports, console_processor_star);
389
+ import * as console_processor_star from "#console-processor";
353
390
 
354
- // src/processors/common.ts
355
- var getRelativeFilename2 = (filename) => {
356
- const match = filename.match(/.+\/(packages\/.+\/.+)/);
357
- if (match) {
358
- const [, filePath] = match;
359
- return filePath;
360
- }
361
- return filename;
391
+ // src/processors/debug-processor.ts
392
+ import { inspect as inspect2 } from "@dxos/node-std/util";
393
+ var DEBUG_PROCESSOR = (config, entry) => {
394
+ console.log(inspect2(entry, false, null, true));
362
395
  };
363
396
 
364
397
  // src/processors/file-processor.ts
398
+ import { appendFileSync, mkdirSync, openSync } from "@dxos/node-std/fs";
399
+ import { dirname } from "@dxos/node-std/path";
365
400
  var EAGAIN_MAX_DURATION = 1e3;
366
401
  var createFileProcessor = ({ pathOrFd, levels: levels2, filters }) => {
367
402
  let fd;
@@ -382,15 +417,12 @@ var createFileProcessor = ({ pathOrFd, levels: levels2, filters }) => {
382
417
  fd = openSync(pathOrFd, "a");
383
418
  }
384
419
  const record = {
385
- ...entry,
386
- timestamp: Date.now(),
387
- ...entry.meta ? {
388
- meta: {
389
- file: getRelativeFilename2(entry.meta.F),
390
- line: entry.meta.L
391
- }
392
- } : {},
393
- context: jsonlogify(getContextFromEntry(entry))
420
+ level: entry.level,
421
+ message: entry.message,
422
+ timestamp: entry.timestamp,
423
+ meta: entry.computedMeta,
424
+ context: entry.computedContext,
425
+ error: entry.computedError
394
426
  };
395
427
  let retryTS = 0;
396
428
  while (true) {
@@ -429,14 +461,15 @@ var FILE_PROCESSOR = createFileProcessor({
429
461
 
430
462
  // src/options.ts
431
463
  var processors = {
432
- [LogProcessorType.CONSOLE]: CONSOLE_PROCESSOR,
464
+ [LogProcessorType.CONSOLE]: processors_exports.CONSOLE_PROCESSOR,
433
465
  [LogProcessorType.BROWSER]: BROWSER_PROCESSOR,
434
466
  [LogProcessorType.DEBUG]: DEBUG_PROCESSOR
435
467
  };
436
- var IS_BROWSER = typeof window !== "undefined" || typeof navigator !== "undefined";
468
+ var browser = (typeof window !== "undefined" || typeof navigator !== "undefined") && !(typeof process !== "undefined" && process?.env?.VITEST);
437
469
  var DEFAULT_PROCESSORS = [
438
- IS_BROWSER ? BROWSER_PROCESSOR : CONSOLE_PROCESSOR
470
+ browser ? BROWSER_PROCESSOR : processors_exports.CONSOLE_PROCESSOR
439
471
  ];
472
+ var parseLogLevel = (level, defValue = LogLevel.WARN) => levels[level.toLowerCase()] ?? defValue;
440
473
  var parseFilter = (filter) => {
441
474
  if (typeof filter === "number") {
442
475
  return [
@@ -445,7 +478,6 @@ var parseFilter = (filter) => {
445
478
  }
446
479
  ];
447
480
  }
448
- const parseLogLevel = (level, defValue = LogLevel.WARN) => levels[level.toLowerCase()] ?? defValue;
449
481
  const lines = typeof filter === "string" ? filter.split(/,\s*/) : filter;
450
482
  return lines.map((filter2) => {
451
483
  const [pattern, level] = filter2.split(":");
@@ -457,66 +489,91 @@ var parseFilter = (filter) => {
457
489
  };
458
490
  });
459
491
  };
460
- var getConfig = (options) => {
461
- const nodeOptions = "process" in globalThis ? {
492
+ var createConfig = (options) => {
493
+ const envOptions = "process" in globalThis ? {
462
494
  file: process.env.LOG_CONFIG,
463
495
  filter: process.env.LOG_FILTER,
464
496
  processor: process.env.LOG_PROCESSOR
465
497
  } : void 0;
466
- const mergedOptions = defaultsDeep({}, loadOptions(nodeOptions?.file), nodeOptions, options);
498
+ const mergedOptions = defaultsDeep({}, (0, platform_exports.loadOptions)(envOptions?.file), envOptions, options);
467
499
  return {
468
500
  options: mergedOptions,
469
501
  filters: parseFilter(mergedOptions.filter ?? LogLevel.INFO),
470
502
  captureFilters: parseFilter(mergedOptions.captureFilter ?? LogLevel.WARN),
471
503
  processors: mergedOptions.processor ? [
472
504
  processors[mergedOptions.processor]
473
- ] : DEFAULT_PROCESSORS,
505
+ ] : [
506
+ ...DEFAULT_PROCESSORS
507
+ ],
474
508
  prefix: mergedOptions.prefix
475
509
  };
476
510
  };
477
511
 
478
512
  // src/log.ts
513
+ var logCount = 0;
479
514
  var createLog = () => {
480
515
  const log2 = (...params) => processLog(LogLevel.DEBUG, ...params);
481
- log2._config = getConfig();
516
+ Object.assign(log2, {
517
+ _id: `log-${++logCount}`,
518
+ _config: createConfig()
519
+ });
482
520
  Object.defineProperty(log2, "runtimeConfig", {
483
521
  get: () => log2._config
484
522
  });
485
- log2.addProcessor = (processor) => {
486
- if (DEFAULT_PROCESSORS.filter((p) => p === processor).length === 0) {
487
- DEFAULT_PROCESSORS.push(processor);
488
- }
489
- if (log2._config.processors.filter((p) => p === processor).length === 0) {
490
- log2._config.processors.push(processor);
491
- }
492
- };
493
- log2.config = (options) => {
494
- log2._config = getConfig(options);
495
- };
496
- log2.trace = (...params) => processLog(LogLevel.TRACE, ...params);
497
- log2.debug = (...params) => processLog(LogLevel.DEBUG, ...params);
498
- log2.verbose = (...params) => processLog(LogLevel.VERBOSE, ...params);
499
- log2.info = (...params) => processLog(LogLevel.INFO, ...params);
500
- log2.warn = (...params) => processLog(LogLevel.WARN, ...params);
501
- log2.error = (...params) => processLog(LogLevel.ERROR, ...params);
502
- log2.catch = (error, context, meta) => processLog(LogLevel.ERROR, void 0, context, meta, error);
503
- log2.break = () => log2.info("\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014\u2014");
504
- log2.stack = (message, context, meta) => processLog(LogLevel.INFO, `${message ?? "Stack Dump"}
505
- ${getFormattedStackTrace()}`, context, meta);
506
- log2.method = createMethodLogDecorator(log2);
507
- log2.func = createFunctionLogDecorator(log2);
508
523
  const processLog = (level, message, context = {}, meta, error) => {
509
- log2._config.processors.forEach((processor) => processor(log2._config, {
524
+ const entry = new LogEntry({
510
525
  level,
511
526
  message,
512
527
  context,
513
528
  meta,
514
529
  error
515
- }));
530
+ });
531
+ log2._config.processors.forEach((processor) => processor(log2._config, entry));
516
532
  };
533
+ Object.assign(log2, {
534
+ /**
535
+ * Update config.
536
+ * NOTE: Preserves any processors that were already added to this logger instance
537
+ * unless an explicit processor option is provided.
538
+ */
539
+ config: ({ processor, ...options } = {}) => {
540
+ const config = createConfig(options);
541
+ const processors2 = processor ? config.processors : log2._config.processors;
542
+ log2._config = {
543
+ ...config,
544
+ processors: processors2
545
+ };
546
+ return log2;
547
+ },
548
+ /**
549
+ * Adds a processor to the logger.
550
+ */
551
+ addProcessor: (processor) => {
552
+ if (log2._config.processors.filter((p) => p === processor).length === 0) {
553
+ log2._config.processors.push(processor);
554
+ }
555
+ return () => {
556
+ log2._config.processors = log2._config.processors.filter((p) => p !== processor);
557
+ };
558
+ },
559
+ trace: (...params) => processLog(LogLevel.TRACE, ...params),
560
+ debug: (...params) => processLog(LogLevel.DEBUG, ...params),
561
+ verbose: (...params) => processLog(LogLevel.VERBOSE, ...params),
562
+ info: (...params) => processLog(LogLevel.INFO, ...params),
563
+ warn: (...params) => processLog(LogLevel.WARN, ...params),
564
+ error: (...params) => processLog(LogLevel.ERROR, ...params),
565
+ catch: (error, context, meta) => processLog(LogLevel.ERROR, void 0, context, meta, error),
566
+ method: createMethodLogDecorator(log2),
567
+ function: createFunctionLogDecorator(log2),
568
+ break: () => log2.info("-".repeat(80)),
569
+ stack: (message, context, meta) => {
570
+ return processLog(LogLevel.INFO, `${message ?? "Stack Dump"}
571
+ ${getFormattedStackTrace()}`, context, meta);
572
+ }
573
+ });
517
574
  return log2;
518
575
  };
519
- var log = globalThis.dx_log ??= createLog();
576
+ var log = globalThis.DX_LOG ??= createLog();
520
577
  var start = Date.now();
521
578
  var last = start;
522
579
  var debug = (label, args) => {
@@ -533,11 +590,94 @@ var debug = (label, args) => {
533
590
  };
534
591
  var getFormattedStackTrace = () => new Error().stack.split("\n").slice(3).join("\n");
535
592
 
593
+ // src/index.ts
594
+ __reExport(index_exports, processors_exports);
595
+
596
+ // src/meta.ts
597
+ var LOG_META_MARKER = "~LogMeta";
598
+ var isLogMeta = (value) => {
599
+ return value != null && typeof value === "object" && value[LOG_META_MARKER] === LOG_META_MARKER;
600
+ };
601
+
602
+ // src/dbg.ts
603
+ var dbg = (arg, meta) => {
604
+ if (meta?.A) {
605
+ console.log(`${meta.A[0]} =`, arg);
606
+ } else {
607
+ console.log(arg);
608
+ }
609
+ return arg;
610
+ };
611
+
612
+ // src/log-buffer.ts
613
+ import { CircularBuffer } from "@dxos/util";
614
+ var DEFAULT_BUFFER_SIZE = 2e3;
615
+ var MAX_CONTEXT_LENGTH = 500;
616
+ var LogBuffer = class {
617
+ _buffer;
618
+ constructor(size = DEFAULT_BUFFER_SIZE) {
619
+ this._buffer = new CircularBuffer(size);
620
+ }
621
+ /**
622
+ * Log processor that can be registered with `log.runtimeConfig.processors`.
623
+ * Captures every level except TRACE (does not apply `shouldLog` / filter; use for full debug dumps).
624
+ */
625
+ logProcessor = (_config, entry) => {
626
+ if (entry.level <= LogLevel.TRACE) {
627
+ return;
628
+ }
629
+ const { filename, line, context: scopeName } = entry.computedMeta;
630
+ const record = {
631
+ t: new Date(entry.timestamp).toISOString(),
632
+ l: shortLevelName[entry.level] ?? "?",
633
+ m: entry.message ?? ""
634
+ };
635
+ if (filename !== void 0) {
636
+ record.f = filename;
637
+ }
638
+ if (line !== void 0) {
639
+ record.n = line;
640
+ }
641
+ if (scopeName !== void 0) {
642
+ record.o = scopeName;
643
+ }
644
+ if (entry.computedError !== void 0) {
645
+ record.e = entry.computedError;
646
+ }
647
+ const computedContext = entry.computedContext;
648
+ if (Object.keys(computedContext).length > 0) {
649
+ try {
650
+ let json = JSON.stringify(computedContext);
651
+ if (json.length > MAX_CONTEXT_LENGTH) {
652
+ json = json.slice(0, MAX_CONTEXT_LENGTH);
653
+ }
654
+ record.c = json;
655
+ } catch {
656
+ }
657
+ }
658
+ this._buffer.push(record);
659
+ };
660
+ /** Number of entries currently in the buffer. */
661
+ get size() {
662
+ return this._buffer.elementCount;
663
+ }
664
+ /** Discard all buffered entries. */
665
+ clear() {
666
+ this._buffer.clear();
667
+ }
668
+ /** Serialize buffer contents as NDJSON (newline-delimited JSON). */
669
+ serialize() {
670
+ const lines = [];
671
+ for (const record of this._buffer) {
672
+ lines.push(JSON.stringify(record));
673
+ }
674
+ return lines.join("\n");
675
+ }
676
+ };
677
+
536
678
  // src/experimental/ownership.ts
537
679
  import { inspect as inspect3 } from "@dxos/node-std/util";
538
- var kOwnershipScope = Symbol("kOwnershipScope");
539
- var kCurrentOwnershipScope = Symbol("kCurrentOwnershipScope");
540
- var kDebugInfoProperties = Symbol("kDebugInfoProperties");
680
+ var kDebugInfoProperties = /* @__PURE__ */ Symbol("kDebugInfoProperties");
541
681
  var OwnershipScope = class {
542
682
  constr;
543
683
  parent;
@@ -568,23 +708,30 @@ var OwnershipScope = class {
568
708
  var getCurrentOwnershipScope = (thisRef) => thisRef;
569
709
  export {
570
710
  BROWSER_PROCESSOR,
571
- CONSOLE_PROCESSOR,
572
711
  DEBUG_PROCESSOR,
573
712
  FILE_PROCESSOR,
713
+ LOG_META_MARKER,
714
+ LogBuffer,
715
+ LogEntry,
574
716
  LogLevel,
575
717
  LogProcessorType,
576
718
  createFileProcessor,
719
+ createLog,
720
+ dbg,
577
721
  debug,
578
722
  gatherLogInfoFromScope,
579
723
  getContextFromEntry,
580
724
  getCurrentOwnershipScope,
581
- getRelativeFilename2 as getRelativeFilename,
725
+ getRelativeFilename,
726
+ inferEnvironmentName,
727
+ isLogMeta,
582
728
  levels,
583
729
  log,
584
730
  logInfo,
585
731
  omit,
586
732
  parseFilter,
587
733
  pick,
734
+ serializeToJsonl,
588
735
  shortLevelName,
589
736
  shouldLog
590
737
  };