@timeback/caliper 0.2.2-beta.20260401223329 → 0.2.2-beta.20260409195426

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.
@@ -147,6 +147,17 @@ var TYPESCRIPT_RUNNER = {
147
147
  var patterns = null;
148
148
  var debugAll = false;
149
149
  var debugEnvSet = false;
150
+ function hasDebugOptIn() {
151
+ try {
152
+ const debugValue = process.env.DEBUG?.trim();
153
+ if (!debugValue) {
154
+ return false;
155
+ }
156
+ return debugValue.split(",").some((part) => part.trim().length > 0);
157
+ } catch {
158
+ return false;
159
+ }
160
+ }
150
161
  function patternToRegex(pattern) {
151
162
  const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
152
163
  const regexStr = escaped.replace(/\*/g, ".*");
@@ -156,7 +167,7 @@ function parseDebugEnv() {
156
167
  if (patterns !== null)
157
168
  return;
158
169
  patterns = [];
159
- if (typeof process === "undefined" || !process.env?.DEBUG) {
170
+ if (!hasDebugOptIn()) {
160
171
  debugEnvSet = false;
161
172
  return;
162
173
  }
@@ -378,6 +389,19 @@ var browserFormatter = (entry) => {
378
389
  };
379
390
  // ../../internal/logger/src/logger.ts
380
391
  var LOG_LEVELS = ["debug", "info", "warn", "error"];
392
+ var GLOBAL_LOGGING_CONFIG_KEY = Symbol.for("@timeback/internal-logger/config");
393
+ function shouldUseSilentFormatter() {
394
+ try {
395
+ return process.env["TIMEBACK_INTERNAL_LOGGER"] === "silent";
396
+ } catch {
397
+ return false;
398
+ }
399
+ }
400
+ function getGlobalLoggingConfig() {
401
+ const globalState = globalThis;
402
+ globalState[GLOBAL_LOGGING_CONFIG_KEY] ??= {};
403
+ return globalState[GLOBAL_LOGGING_CONFIG_KEY];
404
+ }
381
405
  function getFormatter(env) {
382
406
  switch (env) {
383
407
  case "terminal":
@@ -393,11 +417,14 @@ function getFormatter(env) {
393
417
  }
394
418
  }
395
419
  function getDefaultMinLevel() {
396
- if (typeof process !== "undefined" && process.env?.DEBUG) {
420
+ if (hasDebugOptIn()) {
397
421
  return "debug";
398
422
  }
399
423
  return "info";
400
424
  }
425
+ function getConfiguredFormatter(env, formatter) {
426
+ return formatter ?? getGlobalLoggingConfig().formatter ?? (shouldUseSilentFormatter() ? () => {} : getFormatter(env));
427
+ }
401
428
  function shouldLog(level, minLevel) {
402
429
  return LOG_LEVELS.indexOf(level) >= LOG_LEVELS.indexOf(minLevel);
403
430
  }
@@ -406,14 +433,14 @@ class Logger {
406
433
  scope;
407
434
  minLevel;
408
435
  environment;
409
- formatter;
436
+ explicitFormatter;
410
437
  defaultContext;
411
438
  constructor(options = {}) {
412
439
  this.scope = options.scope;
413
440
  this.minLevel = options.minLevel ?? getDefaultMinLevel();
414
441
  this.defaultContext = options.defaultContext ?? {};
415
442
  this.environment = options.environment ?? detectEnvironment();
416
- this.formatter = getFormatter(this.environment);
443
+ this.explicitFormatter = options.formatter;
417
444
  }
418
445
  child(scope) {
419
446
  const childScope = this.scope ? `${this.scope}:${scope}` : scope;
@@ -421,7 +448,8 @@ class Logger {
421
448
  scope: childScope,
422
449
  minLevel: this.minLevel,
423
450
  environment: this.environment,
424
- defaultContext: { ...this.defaultContext }
451
+ defaultContext: { ...this.defaultContext },
452
+ formatter: this.explicitFormatter
425
453
  });
426
454
  }
427
455
  withContext(context) {
@@ -429,7 +457,8 @@ class Logger {
429
457
  scope: this.scope,
430
458
  minLevel: this.minLevel,
431
459
  environment: this.environment,
432
- defaultContext: { ...this.defaultContext, ...context }
460
+ defaultContext: { ...this.defaultContext, ...context },
461
+ formatter: this.explicitFormatter
433
462
  });
434
463
  }
435
464
  debug(message, context) {
@@ -458,7 +487,7 @@ class Logger {
458
487
  context: context || Object.keys(this.defaultContext).length > 0 ? { ...this.defaultContext, ...context } : undefined,
459
488
  timestamp: new Date
460
489
  };
461
- this.formatter(entry);
490
+ getConfiguredFormatter(this.environment, this.explicitFormatter)(entry);
462
491
  }
463
492
  }
464
493
  function createLogger(options = {}) {
@@ -473,7 +502,6 @@ function isDebug() {
473
502
  return false;
474
503
  }
475
504
  }
476
- var log = createLogger({ scope: "auth", minLevel: isDebug() ? "debug" : "warn" });
477
505
 
478
506
  class TokenManager {
479
507
  config;
@@ -481,17 +509,22 @@ class TokenManager {
481
509
  tokenExpiry = 0;
482
510
  pendingRequest = null;
483
511
  fetchFn;
512
+ log;
484
513
  constructor(config) {
485
514
  this.config = config;
486
515
  this.fetchFn = config.fetch ?? globalThis.fetch.bind(globalThis);
516
+ this.log = config.logger ?? createLogger({
517
+ scope: "auth",
518
+ minLevel: isDebug() ? "debug" : "warn"
519
+ });
487
520
  }
488
521
  async getToken() {
489
522
  if (this.accessToken && Date.now() < this.tokenExpiry) {
490
- log.debug("Using cached token");
523
+ this.log.debug("Using cached token");
491
524
  return this.accessToken;
492
525
  }
493
526
  if (this.pendingRequest) {
494
- log.debug("Waiting for in-flight token request");
527
+ this.log.debug("Waiting for in-flight token request");
495
528
  return this.pendingRequest;
496
529
  }
497
530
  this.pendingRequest = this.fetchToken();
@@ -502,7 +535,7 @@ class TokenManager {
502
535
  }
503
536
  }
504
537
  async fetchToken() {
505
- log.debug("Fetching new access token...");
538
+ this.log.debug("Fetching new access token...");
506
539
  const { clientId, clientSecret } = this.config.credentials;
507
540
  const credentials = btoa(`${clientId}:${clientSecret}`);
508
541
  const start = performance.now();
@@ -516,17 +549,17 @@ class TokenManager {
516
549
  });
517
550
  const duration = Math.round(performance.now() - start);
518
551
  if (!response.ok) {
519
- log.error(`Token request failed: ${response.status} ${response.statusText}`);
552
+ this.log.error(`Token request failed: ${response.status} ${response.statusText}`);
520
553
  throw new Error(`Failed to obtain access token: ${response.status} ${response.statusText}`);
521
554
  }
522
555
  const data = await response.json();
523
556
  this.accessToken = data.access_token;
524
557
  this.tokenExpiry = Date.now() + (data.expires_in - 60) * 1000;
525
- log.debug(`Token acquired (${duration}ms, expires in ${data.expires_in}s)`);
558
+ this.log.debug(`Token acquired (${duration}ms, expires in ${data.expires_in}s)`);
526
559
  return this.accessToken;
527
560
  }
528
561
  invalidate() {
529
- log.debug("Token invalidated");
562
+ this.log.debug("Token invalidated");
530
563
  this.accessToken = null;
531
564
  this.tokenExpiry = 0;
532
565
  }
package/dist/errors.js CHANGED
@@ -5,7 +5,7 @@ import {
5
5
  NotFoundError,
6
6
  UnauthorizedError,
7
7
  ValidationError
8
- } from "./chunk-3bz9d5vy.js";
8
+ } from "./chunk-0drvsw3w.js";
9
9
  import"./chunk-6jf1natv.js";
10
10
  export {
11
11
  ValidationError,
package/dist/index.d.ts CHANGED
@@ -3,37 +3,6 @@ export { ActivityCompletedEvent, ActivityMetricType, AssessmentItemEvent, Calipe
3
3
  import { ActivityCompletedInput, QuestionAnsweredInput, QuestionGradedInput, QuestionSeenInput, TimeSpentInput, CaliperListEventsParams } from '@timeback/types/zod';
4
4
  export { ActivityCompletedInput, CaliperListEventsParams as ListEventsParams, QuestionAnsweredInput, QuestionGradedInput, QuestionSeenInput, TimeSpentInput } from '@timeback/types/zod';
5
5
 
6
- /**
7
- * Interface for obtaining OAuth2 access tokens.
8
- *
9
- * Implementations handle token caching and refresh automatically.
10
- */
11
- interface TokenProvider {
12
- /**
13
- * Get a valid access token.
14
- *
15
- * Returns a cached token if still valid, otherwise fetches a new one.
16
- *
17
- * @returns A valid access token string
18
- * @throws {Error} If token acquisition fails
19
- */
20
- getToken(): Promise<string>;
21
- /**
22
- * Invalidate the cached token.
23
- *
24
- * Forces the next getToken() call to fetch a fresh token.
25
- * Should be called when a request fails with 401 Unauthorized.
26
- *
27
- * Optional - not all implementations may support invalidation.
28
- */
29
- invalidate?(): void;
30
- }
31
-
32
- /**
33
- * All supported platforms.
34
- */
35
- declare const PLATFORMS: readonly ["BEYOND_AI", "LEARNWITH_AI"];
36
-
37
6
  /**
38
7
  * Type Definitions for `@timeback/internal-logger`
39
8
  *
@@ -69,6 +38,24 @@ type Environment$2 = 'terminal' | 'ci' | 'production' | 'browser' | 'test';
69
38
  * log.info('User created', { userId: 123, email: 'foo@bar.com' })
70
39
  */
71
40
  type LogContext = Record<string, unknown>;
41
+ /**
42
+ * A single log entry before it's formatted for output.
43
+ *
44
+ * This is the internal representation passed to formatters.
45
+ * Formatters transform this into environment-specific output.
46
+ */
47
+ interface LogEntry {
48
+ /** Severity level of this log entry */
49
+ level: LogLevel;
50
+ /** Human-readable log message */
51
+ message: string;
52
+ /** Optional namespace/category (e.g., "api", "db", "auth") */
53
+ scope?: string;
54
+ /** Optional structured data attached to this entry */
55
+ context?: LogContext;
56
+ /** When this log entry was created */
57
+ timestamp: Date;
58
+ }
72
59
  /**
73
60
  * Configuration options for creating a logger instance.
74
61
  */
@@ -94,7 +81,21 @@ interface LoggerOptions {
94
81
  * Useful for request IDs, user IDs, etc.
95
82
  */
96
83
  defaultContext?: LogContext;
84
+ /**
85
+ * Custom formatter override for this logger instance.
86
+ *
87
+ * When provided, this takes precedence over environment-based formatting.
88
+ * Useful for tests, custom sinks, or temporarily suppressing output.
89
+ */
90
+ formatter?: Formatter;
97
91
  }
92
+ /**
93
+ * Function that outputs a log entry in a specific format.
94
+ *
95
+ * Each environment has its own formatter. Formatters are responsible
96
+ * for the actual console.log/write calls.
97
+ */
98
+ type Formatter = (entry: LogEntry) => void;
98
99
 
99
100
  /**
100
101
  * Logger instance with environment-aware formatting.
@@ -109,8 +110,8 @@ declare class Logger {
109
110
  private minLevel;
110
111
  /** The detected or configured environment */
111
112
  private environment;
112
- /** Function that formats and outputs log entries */
113
- private formatter;
113
+ /** Optional explicit formatter override for this logger instance */
114
+ private explicitFormatter?;
114
115
  /** Context added to every log entry from this logger */
115
116
  private defaultContext;
116
117
  /**
@@ -200,6 +201,37 @@ declare class Logger {
200
201
  private log;
201
202
  }
202
203
 
204
+ /**
205
+ * Interface for obtaining OAuth2 access tokens.
206
+ *
207
+ * Implementations handle token caching and refresh automatically.
208
+ */
209
+ interface TokenProvider {
210
+ /**
211
+ * Get a valid access token.
212
+ *
213
+ * Returns a cached token if still valid, otherwise fetches a new one.
214
+ *
215
+ * @returns A valid access token string
216
+ * @throws {Error} If token acquisition fails
217
+ */
218
+ getToken(): Promise<string>;
219
+ /**
220
+ * Invalidate the cached token.
221
+ *
222
+ * Forces the next getToken() call to fetch a fresh token.
223
+ * Should be called when a request fails with 401 Unauthorized.
224
+ *
225
+ * Optional - not all implementations may support invalidation.
226
+ */
227
+ invalidate?(): void;
228
+ }
229
+
230
+ /**
231
+ * All supported platforms.
232
+ */
233
+ declare const PLATFORMS: readonly ["BEYOND_AI", "LEARNWITH_AI"];
234
+
203
235
  /**
204
236
  * Where Clause Types
205
237
  *
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import {
9
9
  validateNonEmptyString,
10
10
  validateOffsetListParams,
11
11
  validateWithSchema
12
- } from "./chunk-3bz9d5vy.js";
12
+ } from "./chunk-0drvsw3w.js";
13
13
  import {
14
14
  CALIPER_DATA_VERSION,
15
15
  CALIPER_ENV_VARS,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@timeback/caliper",
3
- "version": "0.2.2-beta.20260401223329",
3
+ "version": "0.2.2-beta.20260409195426",
4
4
  "description": "Caliper Analytics client SDK for Timeback",
5
5
  "type": "module",
6
6
  "exports": {
@@ -42,6 +42,6 @@
42
42
  "esbuild": "^0.27.3"
43
43
  },
44
44
  "peerDependencies": {
45
- "typescript": "^5"
45
+ "typescript": "^5 || ^6"
46
46
  }
47
47
  }