hierarchical-approval 4.1.4 → 4.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/CHANGELOG.md CHANGED
@@ -5,6 +5,20 @@ adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
5
 
6
6
  ## [Unreleased]
7
7
 
8
+ ## [4.2.0] - 2026-11-05
9
+
10
+ ### Added
11
+
12
+ - The scheduler plugin entry point now exports `SCHEDULER_SHUTDOWN_CODE`, so callers can match the
13
+ `ApprovalError` code thrown by `scheduleAt` after `shutdown()` without copying the string.
14
+
15
+ ### Changed
16
+
17
+ - `ApprovalTestKit.fullyApprove` now rejects with an `ApprovalValidationError` instead of a plain
18
+ `Error` when `approverMap` has no entry for an open level; the message is unchanged.
19
+ - The webhook plugin's default HTTP client now throws an `ApprovalValidationError` instead of a
20
+ plain `Error` when no global `fetch` exists; the message is unchanged.
21
+
8
22
  ## [4.1.4] - 2026-11-01
9
23
 
10
24
  ### Changed
@@ -89,5 +89,6 @@ var InMemorySchedulerAdapter = class {
89
89
  };
90
90
 
91
91
  exports.InMemorySchedulerAdapter = InMemorySchedulerAdapter;
92
+ exports.SCHEDULER_SHUTDOWN_CODE = SCHEDULER_SHUTDOWN_CODE;
92
93
  //# sourceMappingURL=scheduler.cjs.map
93
94
  //# sourceMappingURL=scheduler.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors.ts","../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/plugins/scheduler/InMemorySchedulerAdapter.ts"],"names":[],"mappings":";;;AACO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD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,MAAA,YAAA,CAAa,KAAK,CAAA;AAAA,IACpB;AACA,IAAA,IAAA,CAAK,OAAO,KAAA,EAAM;AAAA,EACpB;AACF","file":"scheduler.cjs","sourcesContent":["/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","import { ApprovalError } from '../../errors.js';\nimport type { ISchedulerAdapter } from '../../adapters/ISchedulerAdapter.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\nconst SCHEDULER_SHUTDOWN_CODE = 'SCHEDULER_SHUTDOWN';\n\n/** Configuration for {@link InMemorySchedulerAdapter}. */\nexport interface InMemorySchedulerAdapterOptions {\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injectable clock — defaults to {@link systemClock}. Enables deterministic tests. */\n clock?: Clock;\n}\n\n/**\n * Reference {@link ISchedulerAdapter} implementation backed by `setTimeout`.\n *\n * This is the \"no external dependency\" default: a real BullMQ, Temporal, or\n * cron-backed adapter is a drop-in replacement for production use (surviving\n * process restarts, running across replicas), but this in-memory adapter is\n * enough to prove out {@link ISchedulerAdapter} wiring in tests or a\n * single-process deployment without pulling in a queue library.\n *\n * `scheduleAt` returns an opaque, per-call handle (not the underlying\n * `setTimeout` id) so callers never need to know the timer's native type.\n * `cancel` clears the matching timer; `shutdown` clears every timer still\n * pending, guaranteeing this adapter never keeps the event loop open past\n * teardown. Once `shutdown()` has run, further `scheduleAt` calls reject —\n * mirroring how a real queue client refuses new work after it disconnects.\n */\nexport class InMemorySchedulerAdapter implements ISchedulerAdapter {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private nextHandleSeq = 0;\n private shuttingDown = false;\n\n constructor(opts: InMemorySchedulerAdapterOptions = {}) {\n this.logger = opts.logger ?? noopLogger;\n this.clock = opts.clock ?? systemClock;\n }\n\n /** @inheritdoc */\n async scheduleAt(id: string, runAt: Date, callback: () => Promise<void>): Promise<string> {\n if (this.shuttingDown) {\n throw new ApprovalError(\n `InMemorySchedulerAdapter: cannot schedule \"${id}\" after shutdown() has been called.`,\n SCHEDULER_SHUTDOWN_CODE,\n );\n }\n\n const handle = `${id}:${++this.nextHandleSeq}`;\n const delayMs = Math.max(0, runAt.getTime() - this.clock.now().getTime());\n\n const timer = setTimeout(() => {\n this.timers.delete(handle);\n callback().catch((err: unknown) => {\n this.logger.error('InMemorySchedulerAdapter: scheduled callback threw', err, {\n id,\n handle,\n });\n });\n }, delayMs);\n\n this.timers.set(handle, timer);\n return handle;\n }\n\n /** @inheritdoc */\n async cancel(handle: string): Promise<void> {\n const timer = this.timers.get(handle);\n if (timer === undefined) return;\n clearTimeout(timer);\n this.timers.delete(handle);\n }\n\n /** @inheritdoc */\n async shutdown(): Promise<void> {\n this.shuttingDown = true;\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/errors.ts","../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/plugins/scheduler/InMemorySchedulerAdapter.ts"],"names":[],"mappings":";;;AACO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAA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MAAM,QAAA,GAA0B;AAC9B,IAAA,IAAA,CAAK,YAAA,GAAe,IAAA;AACpB,IAAA,KAAA,MAAW,KAAA,IAAS,IAAA,CAAK,MAAA,CAAO,MAAA,EAAO,EAAG;AACxC,MAAA,YAAA,CAAa,KAAK,CAAA;AAAA,IACpB;AACA,IAAA,IAAA,CAAK,OAAO,KAAA,EAAM;AAAA,EACpB;AACF","file":"scheduler.cjs","sourcesContent":["/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","import { ApprovalError } from '../../errors.js';\nimport type { ISchedulerAdapter } from '../../adapters/ISchedulerAdapter.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** {@link ApprovalError.code} raised when a job is scheduled after `shutdown()`. */\nexport const SCHEDULER_SHUTDOWN_CODE = 'SCHEDULER_SHUTDOWN';\n\n/** Configuration for {@link InMemorySchedulerAdapter}. */\nexport interface InMemorySchedulerAdapterOptions {\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injectable clock — defaults to {@link systemClock}. Enables deterministic tests. */\n clock?: Clock;\n}\n\n/**\n * Reference {@link ISchedulerAdapter} implementation backed by `setTimeout`.\n *\n * This is the \"no external dependency\" default: a real BullMQ, Temporal, or\n * cron-backed adapter is a drop-in replacement for production use (surviving\n * process restarts, running across replicas), but this in-memory adapter is\n * enough to prove out {@link ISchedulerAdapter} wiring in tests or a\n * single-process deployment without pulling in a queue library.\n *\n * `scheduleAt` returns an opaque, per-call handle (not the underlying\n * `setTimeout` id) so callers never need to know the timer's native type.\n * `cancel` clears the matching timer; `shutdown` clears every timer still\n * pending, guaranteeing this adapter never keeps the event loop open past\n * teardown. Once `shutdown()` has run, further `scheduleAt` calls reject —\n * mirroring how a real queue client refuses new work after it disconnects.\n */\nexport class InMemorySchedulerAdapter implements ISchedulerAdapter {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private nextHandleSeq = 0;\n private shuttingDown = false;\n\n constructor(opts: InMemorySchedulerAdapterOptions = {}) {\n this.logger = opts.logger ?? noopLogger;\n this.clock = opts.clock ?? systemClock;\n }\n\n /** @inheritdoc */\n async scheduleAt(id: string, runAt: Date, callback: () => Promise<void>): Promise<string> {\n if (this.shuttingDown) {\n throw new ApprovalError(\n `InMemorySchedulerAdapter: cannot schedule \"${id}\" after shutdown() has been called.`,\n SCHEDULER_SHUTDOWN_CODE,\n );\n }\n\n const handle = `${id}:${++this.nextHandleSeq}`;\n const delayMs = Math.max(0, runAt.getTime() - this.clock.now().getTime());\n\n const timer = setTimeout(() => {\n this.timers.delete(handle);\n callback().catch((err: unknown) => {\n this.logger.error('InMemorySchedulerAdapter: scheduled callback threw', err, {\n id,\n handle,\n });\n });\n }, delayMs);\n\n this.timers.set(handle, timer);\n return handle;\n }\n\n /** @inheritdoc */\n async cancel(handle: string): Promise<void> {\n const timer = this.timers.get(handle);\n if (timer === undefined) return;\n clearTimeout(timer);\n this.timers.delete(handle);\n }\n\n /** @inheritdoc */\n async shutdown(): Promise<void> {\n this.shuttingDown = true;\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n }\n}\n"]}
@@ -2,6 +2,8 @@ import { ISchedulerAdapter } from '../index.cjs';
2
2
  import { Clock } from '../index.cjs';
3
3
  import { Logger } from '../index.cjs';
4
4
 
5
+ /** {@link ApprovalError.code} raised when a job is scheduled after `shutdown()`. */
6
+ declare const SCHEDULER_SHUTDOWN_CODE = "SCHEDULER_SHUTDOWN";
5
7
  /** Configuration for {@link InMemorySchedulerAdapter}. */
6
8
  interface InMemorySchedulerAdapterOptions {
7
9
  /** Structured logger. Defaults to {@link noopLogger}. */
@@ -40,5 +42,5 @@ declare class InMemorySchedulerAdapter implements ISchedulerAdapter {
40
42
  shutdown(): Promise<void>;
41
43
  }
42
44
 
43
- export { InMemorySchedulerAdapter };
45
+ export { InMemorySchedulerAdapter, SCHEDULER_SHUTDOWN_CODE };
44
46
  export type { InMemorySchedulerAdapterOptions };
@@ -2,6 +2,8 @@ import { ISchedulerAdapter } from '../index.js';
2
2
  import { Clock } from '../index.js';
3
3
  import { Logger } from '../index.js';
4
4
 
5
+ /** {@link ApprovalError.code} raised when a job is scheduled after `shutdown()`. */
6
+ declare const SCHEDULER_SHUTDOWN_CODE = "SCHEDULER_SHUTDOWN";
5
7
  /** Configuration for {@link InMemorySchedulerAdapter}. */
6
8
  interface InMemorySchedulerAdapterOptions {
7
9
  /** Structured logger. Defaults to {@link noopLogger}. */
@@ -40,5 +42,5 @@ declare class InMemorySchedulerAdapter implements ISchedulerAdapter {
40
42
  shutdown(): Promise<void>;
41
43
  }
42
44
 
43
- export { InMemorySchedulerAdapter };
45
+ export { InMemorySchedulerAdapter, SCHEDULER_SHUTDOWN_CODE };
44
46
  export type { InMemorySchedulerAdapterOptions };
@@ -86,6 +86,6 @@ var InMemorySchedulerAdapter = class {
86
86
  }
87
87
  };
88
88
 
89
- export { InMemorySchedulerAdapter };
89
+ export { InMemorySchedulerAdapter, SCHEDULER_SHUTDOWN_CODE };
90
90
  //# sourceMappingURL=scheduler.js.map
91
91
  //# sourceMappingURL=scheduler.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../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MAAA,CAAO,GAAA,CAAI,MAAM,CAAA;AACpC,IAAA,IAAI,UAAU,MAAA,EAAW;AACzB,IAAA,YAAA,CAAa,KAAK,CAAA;AAClB,IAAA,IAAA,CAAK,MAAA,CAAO,OAAO,MAAM,CAAA;AAAA,EAC3B;AAAA;AAAA,EAGA,MAAM,QAAA,GAA0B;AAC9B,IAAA,IAAA,CAAK,YAAA,GAAe,IAAA;AACpB,IAAA,KAAA,MAAW,KAAA,IAAS,IAAA,CAAK,MAAA,CAAO,MAAA,EAAO,EAAG;AACxC,MAAA,YAAA,CAAa,KAAK,CAAA;AAAA,IACpB;AACA,IAAA,IAAA,CAAK,OAAO,KAAA,EAAM;AAAA,EACpB;AACF","file":"scheduler.js","sourcesContent":["/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","import { ApprovalError } from '../../errors.js';\nimport type { ISchedulerAdapter } from '../../adapters/ISchedulerAdapter.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\nconst SCHEDULER_SHUTDOWN_CODE = 'SCHEDULER_SHUTDOWN';\n\n/** Configuration for {@link InMemorySchedulerAdapter}. */\nexport interface InMemorySchedulerAdapterOptions {\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injectable clock — defaults to {@link systemClock}. Enables deterministic tests. */\n clock?: Clock;\n}\n\n/**\n * Reference {@link ISchedulerAdapter} implementation backed by `setTimeout`.\n *\n * This is the \"no external dependency\" default: a real BullMQ, Temporal, or\n * cron-backed adapter is a drop-in replacement for production use (surviving\n * process restarts, running across replicas), but this in-memory adapter is\n * enough to prove out {@link ISchedulerAdapter} wiring in tests or a\n * single-process deployment without pulling in a queue library.\n *\n * `scheduleAt` returns an opaque, per-call handle (not the underlying\n * `setTimeout` id) so callers never need to know the timer's native type.\n * `cancel` clears the matching timer; `shutdown` clears every timer still\n * pending, guaranteeing this adapter never keeps the event loop open past\n * teardown. Once `shutdown()` has run, further `scheduleAt` calls reject —\n * mirroring how a real queue client refuses new work after it disconnects.\n */\nexport class InMemorySchedulerAdapter implements ISchedulerAdapter {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private nextHandleSeq = 0;\n private shuttingDown = false;\n\n constructor(opts: InMemorySchedulerAdapterOptions = {}) {\n this.logger = opts.logger ?? noopLogger;\n this.clock = opts.clock ?? systemClock;\n }\n\n /** @inheritdoc */\n async scheduleAt(id: string, runAt: Date, callback: () => Promise<void>): Promise<string> {\n if (this.shuttingDown) {\n throw new ApprovalError(\n `InMemorySchedulerAdapter: cannot schedule \"${id}\" after shutdown() has been called.`,\n SCHEDULER_SHUTDOWN_CODE,\n );\n }\n\n const handle = `${id}:${++this.nextHandleSeq}`;\n const delayMs = Math.max(0, runAt.getTime() - this.clock.now().getTime());\n\n const timer = setTimeout(() => {\n this.timers.delete(handle);\n callback().catch((err: unknown) => {\n this.logger.error('InMemorySchedulerAdapter: scheduled callback threw', err, {\n id,\n handle,\n });\n });\n }, delayMs);\n\n this.timers.set(handle, timer);\n return handle;\n }\n\n /** @inheritdoc */\n async cancel(handle: string): Promise<void> {\n const timer = this.timers.get(handle);\n if (timer === undefined) return;\n clearTimeout(timer);\n this.timers.delete(handle);\n }\n\n /** @inheritdoc */\n async shutdown(): Promise<void> {\n this.shuttingDown = true;\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/errors.ts","../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/plugins/scheduler/InMemorySchedulerAdapter.ts"],"names":[],"mappings":";AACO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,EAAS,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK;AAAA,EACnE;AAAA,EAEA,YAAA,GAAuB;AACrB,IAAA,MAAM,GAAA,GAA8B;AAAA,MAClC,SAAA,EAAW,GAAA;AAAA,MACX,QAAA,EAAU,GAAA;AAAA,MACV,SAAA,EAAW,GAAA;AAAA,MACX,UAAA,EAAY,GAAA;AAAA,MACZ,kBAAA,EAAoB;AAAA,KACtB;AACA,IAAA,OAAO,GAAA,CAAI,IAAA,CAAK,IAAI,CAAA,IAAK,GAAA;AAAA,EAC3B;AACF,CAAA;;;AClBO,IAAM,cAAqB,EAAE,GAAA,EAAK,sBAAM,IAAI,MAAK,EAAE;;;ACSnD,IAAM,UAAA,GAAqB;AAAA,EAChC,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC;AAChB,CAAA;;;ACbO,IA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AQ,KAAK,CAAA;AAC7B,IAAA,OAAO,MAAA;AAAA,EACT;AAAA;AAAA,EAGA,MAAM,OAAO,MAAA,EAA+B;AAC1C,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,MAAA,CAAO,GAAA,CAAI,MAAM,CAAA;AACpC,IAAA,IAAI,UAAU,MAAA,EAAW;AACzB,IAAA,YAAA,CAAa,KAAK,CAAA;AAClB,IAAA,IAAA,CAAK,MAAA,CAAO,OAAO,MAAM,CAAA;AAAA,EAC3B;AAAA;AAAA,EAGA,MAAM,QAAA,GAA0B;AAC9B,IAAA,IAAA,CAAK,YAAA,GAAe,IAAA;AACpB,IAAA,KAAA,MAAW,KAAA,IAAS,IAAA,CAAK,MAAA,CAAO,MAAA,EAAO,EAAG;AACxC,MAAA,YAAA,CAAa,KAAK,CAAA;AAAA,IACpB;AACA,IAAA,IAAA,CAAK,OAAO,KAAA,EAAM;AAAA,EACpB;AACF","file":"scheduler.js","sourcesContent":["/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","import { ApprovalError } from '../../errors.js';\nimport type { ISchedulerAdapter } from '../../adapters/ISchedulerAdapter.js';\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\n\n/** {@link ApprovalError.code} raised when a job is scheduled after `shutdown()`. */\nexport const SCHEDULER_SHUTDOWN_CODE = 'SCHEDULER_SHUTDOWN';\n\n/** Configuration for {@link InMemorySchedulerAdapter}. */\nexport interface InMemorySchedulerAdapterOptions {\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Injectable clock — defaults to {@link systemClock}. Enables deterministic tests. */\n clock?: Clock;\n}\n\n/**\n * Reference {@link ISchedulerAdapter} implementation backed by `setTimeout`.\n *\n * This is the \"no external dependency\" default: a real BullMQ, Temporal, or\n * cron-backed adapter is a drop-in replacement for production use (surviving\n * process restarts, running across replicas), but this in-memory adapter is\n * enough to prove out {@link ISchedulerAdapter} wiring in tests or a\n * single-process deployment without pulling in a queue library.\n *\n * `scheduleAt` returns an opaque, per-call handle (not the underlying\n * `setTimeout` id) so callers never need to know the timer's native type.\n * `cancel` clears the matching timer; `shutdown` clears every timer still\n * pending, guaranteeing this adapter never keeps the event loop open past\n * teardown. Once `shutdown()` has run, further `scheduleAt` calls reject —\n * mirroring how a real queue client refuses new work after it disconnects.\n */\nexport class InMemorySchedulerAdapter implements ISchedulerAdapter {\n private readonly logger: Logger;\n private readonly clock: Clock;\n private readonly timers = new Map<string, ReturnType<typeof setTimeout>>();\n private nextHandleSeq = 0;\n private shuttingDown = false;\n\n constructor(opts: InMemorySchedulerAdapterOptions = {}) {\n this.logger = opts.logger ?? noopLogger;\n this.clock = opts.clock ?? systemClock;\n }\n\n /** @inheritdoc */\n async scheduleAt(id: string, runAt: Date, callback: () => Promise<void>): Promise<string> {\n if (this.shuttingDown) {\n throw new ApprovalError(\n `InMemorySchedulerAdapter: cannot schedule \"${id}\" after shutdown() has been called.`,\n SCHEDULER_SHUTDOWN_CODE,\n );\n }\n\n const handle = `${id}:${++this.nextHandleSeq}`;\n const delayMs = Math.max(0, runAt.getTime() - this.clock.now().getTime());\n\n const timer = setTimeout(() => {\n this.timers.delete(handle);\n callback().catch((err: unknown) => {\n this.logger.error('InMemorySchedulerAdapter: scheduled callback threw', err, {\n id,\n handle,\n });\n });\n }, delayMs);\n\n this.timers.set(handle, timer);\n return handle;\n }\n\n /** @inheritdoc */\n async cancel(handle: string): Promise<void> {\n const timer = this.timers.get(handle);\n if (timer === undefined) return;\n clearTimeout(timer);\n this.timers.delete(handle);\n }\n\n /** @inheritdoc */\n async shutdown(): Promise<void> {\n this.shuttingDown = true;\n for (const timer of this.timers.values()) {\n clearTimeout(timer);\n }\n this.timers.clear();\n }\n}\n"]}
@@ -21,11 +21,40 @@ var noopLogger = {
21
21
  }
22
22
  };
23
23
 
24
+ // src/errors.ts
25
+ var ApprovalError = class extends Error {
26
+ constructor(message, code) {
27
+ super(message);
28
+ this.code = code;
29
+ this.name = "ApprovalError";
30
+ }
31
+ toJSON() {
32
+ return { code: this.code, message: this.message, name: this.name };
33
+ }
34
+ toHttpStatus() {
35
+ const map = {
36
+ NOT_FOUND: 404,
37
+ CONFLICT: 409,
38
+ FORBIDDEN: 403,
39
+ VALIDATION: 422,
40
+ TEMPLATE_NOT_FOUND: 404
41
+ };
42
+ return map[this.code] ?? 500;
43
+ }
44
+ };
45
+ var ApprovalValidationError = class extends ApprovalError {
46
+ constructor(message, cause) {
47
+ super(message, "VALIDATION");
48
+ this.cause = cause;
49
+ this.name = "ApprovalValidationError";
50
+ }
51
+ };
52
+
24
53
  // src/plugins/webhook/IHttpClient.ts
25
54
  function getDefaultHttpClient() {
26
55
  const globalFetch = globalThis.fetch;
27
56
  if (typeof globalFetch !== "function") {
28
- throw new Error(
57
+ throw new ApprovalValidationError(
29
58
  "hierarchical-approval/plugins/webhook: no global `fetch` was found. This is built into Node.js 18+ \u2014 on an older runtime, either upgrade Node.js or pass an explicit `httpClient` (any function shaped like `fetch`) via WebhookNotificationAdapterOptions."
30
59
  );
31
60
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/plugins/webhook/IHttpClient.ts","../../src/plugins/webhook/Webhook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.cjs","sourcesContent":["/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/**\n * Minimal, dependency-free HTTP port shaped after the WHATWG `fetch` function.\n *\n * The global `fetch` (built into Node.js since v18) is structurally assignable\n * to {@link HttpClient} as-is — no wrapping required, mirroring how a real\n * OpenTelemetry `Tracer` is structurally assignable to this library's\n * {@link import('../tracing/ITracer.js').Tracer} port. This library never adds\n * a dependency on axios/node-fetch/undici: bring your own fetch-shaped function\n * if you need custom behavior (a proxy, request mocking, a different runtime's\n * fetch), or use {@link getDefaultHttpClient}, which forwards to\n * `globalThis.fetch`.\n *\n * The parameter type is intentionally narrower than `fetch`'s own\n * `RequestInfo | URL` (it omits `Request`), which is what makes the global\n * `fetch` assignable here: a function accepting a *wider* input domain is\n * always assignable to a type expecting a *narrower* one.\n */\nexport type HttpClient = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Resolves the default {@link HttpClient}: `globalThis.fetch`, bound so it can\n * be invoked detached from `globalThis`.\n *\n * @throws {Error} If no global `fetch` exists (Node.js < 18). The message\n * names both ways to fix it: upgrade Node.js, or pass an explicit\n * `httpClient` (any fetch-shaped function) via\n * `WebhookNotificationAdapterOptions`.\n */\nexport function getDefaultHttpClient(): HttpClient {\n const globalFetch = globalThis.fetch;\n if (typeof globalFetch !== 'function') {\n throw new Error(\n 'hierarchical-approval/plugins/webhook: no global `fetch` was found. This is built into ' +\n 'Node.js 18+ — on an older runtime, either upgrade Node.js or pass an explicit ' +\n '`httpClient` (any function shaped like `fetch`) via WebhookNotificationAdapterOptions.',\n );\n }\n return globalFetch.bind(globalThis);\n}\n","import { createHmac } from 'node:crypto';\n\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport type {\n INotificationAdapter,\n NotificationEvent,\n} from '../../adapters/INotificationAdapter.js';\nimport type { HttpClient } from './IHttpClient.js';\nimport { getDefaultHttpClient } from './IHttpClient.js';\n\n/** Default header carrying the HMAC signature when `secret` is configured. */\nexport const DEFAULT_SIGNATURE_HEADER = 'X-Approval-Signature';\n\n/** Default per-request timeout, in milliseconds, before the request is aborted. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Default cap on delivery attempts inside a single {@link WebhookNotificationAdapter.deliver} call. */\nconst DEFAULT_MAX_ATTEMPTS = 3;\n\n/** Default base backoff delay, in milliseconds, for the first retry. */\nconst DEFAULT_BASE_DELAY_MS = 300;\n\n/** Default multiplier applied per attempt (exponential backoff). */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/** Default cap on a single computed backoff delay, in milliseconds. */\nconst DEFAULT_MAX_DELAY_MS = 10_000;\n\n/** HTTP status codes worth retrying: request timeout, rate-limited, and any server error. */\nconst RETRYABLE_STATUSES = new Set([408, 429]);\n\n/** Sleeps for `ms` milliseconds using the real timer. Overridable via `options.sleep` in tests. */\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Thrown by {@link WebhookNotificationAdapter.deliver} when delivery could not\n * be completed — either a non-retryable HTTP response (e.g. `4xx` other than\n * `408`/`429`) was received, or all retry attempts were exhausted.\n *\n * Never carries the signing secret: the message is built only from the HTTP\n * status and/or the underlying transport error's own message.\n */\nexport class WebhookDeliveryError extends Error {\n /** HTTP status of the last response received, if any (absent on a pure network/timeout failure). */\n readonly status?: number;\n /** Number of delivery attempts made before giving up. */\n readonly attempts: number;\n /**\n * The underlying network/timeout error that caused the final attempt to\n * fail, if delivery failed without ever receiving a response. Declared\n * explicitly (rather than relying on the ES2022 `Error.cause` option) since\n * this package targets ES2020.\n */\n readonly cause?: unknown;\n\n constructor(message: string, options: { status?: number; attempts: number; cause?: unknown }) {\n super(message);\n this.name = 'WebhookDeliveryError';\n this.status = options.status;\n this.attempts = options.attempts;\n this.cause = options.cause;\n }\n}\n\n/** Configuration for {@link WebhookNotificationAdapter}. */\nexport interface WebhookNotificationAdapterOptions {\n /** Destination URL every notification event is POSTed to as JSON. Required. */\n url: string;\n /** Extra static headers merged into every request (e.g. `Authorization`). */\n headers?: Record<string, string>;\n /**\n * Shared secret used to HMAC-SHA256-sign each request body. When omitted,\n * requests are sent unsigned. Never logged and never echoed in a thrown\n * error's message.\n */\n secret?: string;\n /** Header name the signature is emitted under. Defaults to {@link DEFAULT_SIGNATURE_HEADER}. */\n signatureHeader?: string;\n /** Per-request timeout in milliseconds before the request is aborted. Defaults to `10_000`. */\n timeoutMs?: number;\n /**\n * Maximum delivery attempts made by a single {@link deliver} call before\n * throwing {@link WebhookDeliveryError}. Must be >= 1. Defaults to `3`.\n *\n * This is a short, local retry budget for transient blips — it is not a\n * substitute for durable retry across process restarts. Compose with\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter}\n * for that (see the class doc).\n */\n maxAttempts?: number;\n /** Base backoff in milliseconds for the first retry. Defaults to `300`. */\n baseDelayMs?: number;\n /** Multiplier applied per attempt (exponential). Defaults to `2`. */\n backoffFactor?: number;\n /** Upper bound on a single computed backoff delay, in milliseconds. Defaults to `10_000`. */\n maxDelayMs?: number;\n /** Time source used for the signature timestamp and for resolving a `Retry-After` date. Defaults to {@link systemClock}. */\n clock?: Clock;\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Fetch-shaped HTTP port. Defaults to {@link getDefaultHttpClient}. */\n httpClient?: HttpClient;\n /** Delay function used between retries. Defaults to a real `setTimeout`-based sleep; inject a no-op/fake in tests. */\n sleep?: (ms: number) => Promise<void>;\n /**\n * Source of randomness in `[0, 1)` used for jitter. Defaults to `Math.random`.\n * Inject a deterministic function in tests to assert exact backoff delays.\n */\n random?: () => number;\n}\n\n/**\n * {@link INotificationAdapter} that delivers each approval event as a signed,\n * JSON HTTP POST to a configured webhook URL.\n *\n * **Signing.** When `secret` is configured, every request carries a\n * `{signatureHeader}: t=<unix-seconds>,v1=<hex-hmac>` header (Stripe-style),\n * where the HMAC-SHA256 digest is computed over the signing string\n * `\"<timestamp>.<body>\"`. Folding the timestamp into the signed payload lets a\n * receiver reject stale/replayed requests by checking `t` against its own\n * clock before trusting `v1`. Signing is opt-in — omit `secret` to send\n * unsigned requests.\n *\n * **Retry.** `5xx` responses, `408`, `429`, and network/timeout errors are\n * retried with exponential backoff and full jitter, up to `maxAttempts`. A\n * `429` response honors a `Retry-After` header (seconds or an HTTP date) in\n * place of the computed backoff. Any other non-2xx status (e.g. `400`, `401`,\n * `404`) is treated as permanent and is not retried.\n *\n * **Durability.** `notify()` — the {@link INotificationAdapter} method — never\n * throws, per that port's contract: on exhausting `maxAttempts` it logs and\n * drops the notification. That makes this adapter, used alone, *at-most-once*\n * and blocking (it awaits the full retry sequence inline). For at-least-once\n * delivery that survives a process restart, do not reimplement dead-lettering\n * here — instead compose with\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter},\n * passing this adapter's throwing {@link deliver} method (bound) as its\n * `transport`:\n *\n * ```ts\n * const webhook = new WebhookNotificationAdapter({ url, secret });\n * const durable = new OutboxNotificationAdapter({ transport: webhook.deliver.bind(webhook) });\n * ```\n *\n * `deliver` and `NotificationTransport` (`(event) => void | Promise<void>`)\n * are structurally compatible, so this composition type-checks with no\n * adapter shim.\n *\n * **Security.** The signing secret is never included in a log message or in a\n * {@link WebhookDeliveryError}'s message/fields — only the HTTP status and/or\n * the underlying transport error's own message are surfaced.\n */\nexport class WebhookNotificationAdapter implements INotificationAdapter {\n private readonly url: string;\n private readonly staticHeaders: Record<string, string>;\n private readonly secret?: string;\n private readonly signatureHeader: string;\n private readonly timeoutMs: number;\n private readonly maxAttempts: number;\n private readonly baseDelayMs: number;\n private readonly backoffFactor: number;\n private readonly maxDelayMs: number;\n private readonly clock: Clock;\n private readonly logger: Logger;\n private readonly httpClient: HttpClient;\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly random: () => number;\n\n constructor(options: WebhookNotificationAdapterOptions) {\n this.url = options.url;\n this.staticHeaders = options.headers ?? {};\n this.secret = options.secret;\n this.signatureHeader = options.signatureHeader ?? DEFAULT_SIGNATURE_HEADER;\n this.timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n this.maxAttempts = Math.max(1, Math.floor(options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS));\n this.baseDelayMs = Math.max(0, options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);\n this.backoffFactor = options.backoffFactor ?? DEFAULT_BACKOFF_FACTOR;\n this.maxDelayMs = Math.max(0, options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);\n this.clock = options.clock ?? systemClock;\n this.logger = options.logger ?? noopLogger;\n this.httpClient = options.httpClient ?? getDefaultHttpClient();\n this.sleep = options.sleep ?? defaultSleep;\n this.random = options.random ?? Math.random;\n }\n\n /**\n * Deliver the event, retrying transient failures. Never throws per the\n * {@link INotificationAdapter} contract: on final failure the error is\n * logged (never with the secret) and swallowed.\n */\n async notify(event: NotificationEvent): Promise<void> {\n try {\n await this.deliver(event);\n } catch (err) {\n this.logger.error(\n 'WebhookNotificationAdapter: giving up on delivery, dropping notification',\n err,\n {\n type: event.type,\n instanceId: event.instanceId,\n tenantId: event.tenantId,\n url: this.url,\n },\n );\n }\n }\n\n /**\n * POST `event` as JSON to the configured URL, retrying retryable failures\n * with exponential backoff + full jitter (honoring `Retry-After` on `429`)\n * up to `maxAttempts`.\n *\n * Unlike {@link notify}, this throws {@link WebhookDeliveryError} on final\n * failure rather than swallowing it — intentionally, so it can be composed\n * as a throwing `transport` for\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter}\n * (see the class doc).\n *\n * @throws {WebhookDeliveryError} If a non-retryable status is returned, or\n * `maxAttempts` is exhausted.\n */\n async deliver(event: NotificationEvent): Promise<void> {\n const body = JSON.stringify(event);\n const headers = this.buildHeaders(body);\n\n let attempt = 0;\n for (;;) {\n attempt++;\n let response: Response | undefined;\n let networkError: unknown;\n\n try {\n response = await this.performRequest(body, headers);\n } catch (err) {\n networkError = err;\n }\n\n if (response && this.isSuccessStatus(response.status)) {\n return;\n }\n\n const retryable = response ? this.isRetryableStatus(response.status) : true;\n const exhausted = attempt >= this.maxAttempts;\n\n if (!retryable || exhausted) {\n throw this.buildError(attempt, response, networkError);\n }\n\n const delayMs = response\n ? this.retryDelayForResponse(response, attempt)\n : this.computeBackoff(attempt);\n await this.sleep(delayMs);\n }\n }\n\n /** Issues one POST attempt with an `AbortController`-backed timeout. */\n private async performRequest(body: string, headers: Record<string, string>): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n return await this.httpClient(this.url, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** Builds request headers: content-type, static headers, then the signature (always wins). */\n private buildHeaders(body: string): Record<string, string> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n ...this.staticHeaders,\n };\n if (this.secret) {\n const timestampSeconds = Math.floor(this.clock.now().getTime() / 1000);\n const signingString = `${timestampSeconds}.${body}`;\n const signature = createHmac('sha256', this.secret).update(signingString).digest('hex');\n headers[this.signatureHeader] = `t=${timestampSeconds},v1=${signature}`;\n }\n return headers;\n }\n\n /** `2xx` is success. */\n private isSuccessStatus(status: number): boolean {\n return status >= 200 && status < 300;\n }\n\n /** `5xx`, `408` (request timeout), and `429` (rate limited) are worth retrying; other `4xx` are not. */\n private isRetryableStatus(status: number): boolean {\n return status >= 500 || RETRYABLE_STATUSES.has(status);\n }\n\n /** Delay before the next attempt for a retryable response: `Retry-After` on 429, else computed backoff. */\n private retryDelayForResponse(response: Response, attempt: number): number {\n if (response.status === 429) {\n const retryAfterMs = this.parseRetryAfterMs(response);\n if (retryAfterMs !== undefined) return retryAfterMs;\n }\n return this.computeBackoff(attempt);\n }\n\n /**\n * Parses a `Retry-After` header (delay-seconds or an HTTP date) into a\n * millisecond delay measured from the injected {@link Clock}. Returns\n * `undefined` when absent or unparseable.\n */\n private parseRetryAfterMs(response: Response): number | undefined {\n const header = response.headers.get('retry-after');\n if (!header) return undefined;\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);\n\n const dateMs = Date.parse(header);\n if (!Number.isNaN(dateMs)) return Math.max(0, dateMs - this.clock.now().getTime());\n\n return undefined;\n }\n\n /**\n * Exponential backoff for the Nth attempt (1-based) with full jitter —\n * uniformly random in `[0, cap]` — capped at `maxDelayMs`. A non-finite or\n * negative intermediate value (extreme attempt counts) collapses to the cap\n * rather than overflowing to `Infinity`/`NaN`.\n */\n private computeBackoff(attempt: number): number {\n const raw = this.baseDelayMs * Math.pow(this.backoffFactor, attempt - 1);\n const cap = !Number.isFinite(raw) || raw < 0 ? this.maxDelayMs : Math.min(raw, this.maxDelayMs);\n return Math.floor(this.random() * cap);\n }\n\n /** Builds the final {@link WebhookDeliveryError} — never includes the secret. */\n private buildError(\n attempt: number,\n response: Response | undefined,\n networkError: unknown,\n ): WebhookDeliveryError {\n if (response) {\n return new WebhookDeliveryError(\n `WebhookNotificationAdapter: delivery failed after ${attempt} attempt(s) with status ${response.status}`,\n { status: response.status, attempts: attempt },\n );\n }\n const message = networkError instanceof Error ? networkError.message : String(networkError);\n return new WebhookDeliveryError(\n `WebhookNotificationAdapter: delivery failed after ${attempt} attempt(s): ${message}`,\n {\n attempts: attempt,\n cause: networkError,\n },\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/webhook/IHttpClient.ts","../../src/plugins/webhook/WebhookNotificationAdapter.ts"],"names":["createHmac"],"mappings":";;;;;;;AAMO,IAAM,cAAqB,EAAE,GAAA,EAAK,sBAAM,IAAI,MAAK,EAAE;;;ACSnD,IAAM,UAAA,GAAqB;AAAA,EAChC,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC;AAChB,CAAA;;;ACpBO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AAAA,EAEA,MAAA,GAA0D;AACxD,IAAA,OAAO,EAAE,MAAM,IAAA,CAAK,IAAA,EAAM,SAAS,IAAA,CAAK,OAAA,EAAS,IAAA,EAAM,IAAA,CAAK,IAAA,EAAK;AAAA,EACnE;AAAA,EAEA,YAAA,GAAuB;AACrB,IAAA,MAAM,GAAA,GAA8B;AAAA,MAClC,SAAA,EAAW,GAAA;AAAA,MACX,QAAA,EAAU,GAAA;AAAA,MACV,SAAA,EAAW,GAAA;AAAA,MACX,UAAA,EAAY,GAAA;AAAA,MACZ,kBAAA,EAAoB;AAAA,KACtB;A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source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import { ApprovalValidationError } from '../../errors.js';\n\n/**\n * Minimal, dependency-free HTTP port shaped after the WHATWG `fetch` function.\n *\n * The global `fetch` (built into Node.js since v18) is structurally assignable\n * to {@link HttpClient} as-is — no wrapping required, mirroring how a real\n * OpenTelemetry `Tracer` is structurally assignable to this library's\n * {@link import('../tracing/ITracer.js').Tracer} port. This library never adds\n * a dependency on axios/node-fetch/undici: bring your own fetch-shaped function\n * if you need custom behavior (a proxy, request mocking, a different runtime's\n * fetch), or use {@link getDefaultHttpClient}, which forwards to\n * `globalThis.fetch`.\n *\n * The parameter type is intentionally narrower than `fetch`'s own\n * `RequestInfo | URL` (it omits `Request`), which is what makes the global\n * `fetch` assignable here: a function accepting a *wider* input domain is\n * always assignable to a type expecting a *narrower* one.\n */\nexport type HttpClient = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Resolves the default {@link HttpClient}: `globalThis.fetch`, bound so it can\n * be invoked detached from `globalThis`.\n *\n * @throws {ApprovalValidationError} If no global `fetch` exists (Node.js < 18). The message\n * names both ways to fix it: upgrade Node.js, or pass an explicit\n * `httpClient` (any fetch-shaped function) via\n * `WebhookNotificationAdapterOptions`.\n */\nexport function getDefaultHttpClient(): HttpClient {\n const globalFetch = globalThis.fetch;\n if (typeof globalFetch !== 'function') {\n throw new ApprovalValidationError(\n 'hierarchical-approval/plugins/webhook: no global `fetch` was found. This is built into ' +\n 'Node.js 18+ — on an older runtime, either upgrade Node.js or pass an explicit ' +\n '`httpClient` (any function shaped like `fetch`) via WebhookNotificationAdapterOptions.',\n );\n }\n return globalFetch.bind(globalThis);\n}\n","import { createHmac } from 'node:crypto';\n\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport type {\n INotificationAdapter,\n NotificationEvent,\n} from '../../adapters/INotificationAdapter.js';\nimport type { HttpClient } from './IHttpClient.js';\nimport { getDefaultHttpClient } from './IHttpClient.js';\n\n/** Default header carrying the HMAC signature when `secret` is configured. */\nexport const DEFAULT_SIGNATURE_HEADER = 'X-Approval-Signature';\n\n/** Default per-request timeout, in milliseconds, before the request is aborted. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Default cap on delivery attempts inside a single {@link WebhookNotificationAdapter.deliver} call. */\nconst DEFAULT_MAX_ATTEMPTS = 3;\n\n/** Default base backoff delay, in milliseconds, for the first retry. */\nconst DEFAULT_BASE_DELAY_MS = 300;\n\n/** Default multiplier applied per attempt (exponential backoff). */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/** Default cap on a single computed backoff delay, in milliseconds. */\nconst DEFAULT_MAX_DELAY_MS = 10_000;\n\n/** HTTP status codes worth retrying: request timeout, rate-limited, and any server error. */\nconst RETRYABLE_STATUSES = new Set([408, 429]);\n\n/** Sleeps for `ms` milliseconds using the real timer. Overridable via `options.sleep` in tests. */\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Thrown by {@link WebhookNotificationAdapter.deliver} when delivery could not\n * be completed — either a non-retryable HTTP response (e.g. `4xx` other than\n * `408`/`429`) was received, or all retry attempts were exhausted.\n *\n * Never carries the signing secret: the message is built only from the HTTP\n * status and/or the underlying transport error's own message.\n */\nexport class WebhookDeliveryError extends Error {\n /** HTTP status of the last response received, if any (absent on a pure network/timeout failure). */\n readonly status?: number;\n /** Number of delivery attempts made before giving up. */\n readonly attempts: number;\n /**\n * The underlying network/timeout error that caused the final attempt to\n * fail, if delivery failed without ever receiving a response. Declared\n * explicitly (rather than relying on the ES2022 `Error.cause` option) since\n * this package targets ES2020.\n */\n readonly cause?: unknown;\n\n constructor(message: string, options: { status?: number; attempts: number; cause?: unknown }) {\n super(message);\n this.name = 'WebhookDeliveryError';\n this.status = options.status;\n this.attempts = options.attempts;\n this.cause = options.cause;\n }\n}\n\n/** Configuration for {@link WebhookNotificationAdapter}. */\nexport interface WebhookNotificationAdapterOptions {\n /** Destination URL every notification event is POSTed to as JSON. Required. */\n url: string;\n /** Extra static headers merged into every request (e.g. `Authorization`). */\n headers?: Record<string, string>;\n /**\n * Shared secret used to HMAC-SHA256-sign each request body. When omitted,\n * requests are sent unsigned. Never logged and never echoed in a thrown\n * error's message.\n */\n secret?: string;\n /** Header name the signature is emitted under. Defaults to {@link DEFAULT_SIGNATURE_HEADER}. */\n signatureHeader?: string;\n /** Per-request timeout in milliseconds before the request is aborted. Defaults to `10_000`. */\n timeoutMs?: number;\n /**\n * Maximum delivery attempts made by a single {@link deliver} call before\n * throwing {@link WebhookDeliveryError}. Must be >= 1. Defaults to `3`.\n *\n * This is a short, local retry budget for transient blips — it is not a\n * substitute for durable retry across process restarts. Compose with\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter}\n * for that (see the class doc).\n */\n maxAttempts?: number;\n /** Base backoff in milliseconds for the first retry. Defaults to `300`. */\n baseDelayMs?: number;\n /** Multiplier applied per attempt (exponential). Defaults to `2`. */\n backoffFactor?: number;\n /** Upper bound on a single computed backoff delay, in milliseconds. Defaults to `10_000`. */\n maxDelayMs?: number;\n /** Time source used for the signature timestamp and for resolving a `Retry-After` date. Defaults to {@link systemClock}. */\n clock?: Clock;\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Fetch-shaped HTTP port. Defaults to {@link getDefaultHttpClient}. */\n httpClient?: HttpClient;\n /** Delay function used between retries. Defaults to a real `setTimeout`-based sleep; inject a no-op/fake in tests. */\n sleep?: (ms: number) => Promise<void>;\n /**\n * Source of randomness in `[0, 1)` used for jitter. Defaults to `Math.random`.\n * Inject a deterministic function in tests to assert exact backoff delays.\n */\n random?: () => number;\n}\n\n/**\n * {@link INotificationAdapter} that delivers each approval event as a signed,\n * JSON HTTP POST to a configured webhook URL.\n *\n * **Signing.** When `secret` is configured, every request carries a\n * `{signatureHeader}: t=<unix-seconds>,v1=<hex-hmac>` header (Stripe-style),\n * where the HMAC-SHA256 digest is computed over the signing string\n * `\"<timestamp>.<body>\"`. Folding the timestamp into the signed payload lets a\n * receiver reject stale/replayed requests by checking `t` against its own\n * clock before trusting `v1`. Signing is opt-in — omit `secret` to send\n * unsigned requests.\n *\n * **Retry.** `5xx` responses, `408`, `429`, and network/timeout errors are\n * retried with exponential backoff and full jitter, up to `maxAttempts`. A\n * `429` response honors a `Retry-After` header (seconds or an HTTP date) in\n * place of the computed backoff. Any other non-2xx status (e.g. `400`, `401`,\n * `404`) is treated as permanent and is not retried.\n *\n * **Durability.** `notify()` — the {@link INotificationAdapter} method — never\n * throws, per that port's contract: on exhausting `maxAttempts` it logs and\n * drops the notification. That makes this adapter, used alone, *at-most-once*\n * and blocking (it awaits the full retry sequence inline). For at-least-once\n * delivery that survives a process restart, do not reimplement dead-lettering\n * here — instead compose with\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter},\n * passing this adapter's throwing {@link deliver} method (bound) as its\n * `transport`:\n *\n * ```ts\n * const webhook = new WebhookNotificationAdapter({ url, secret });\n * const durable = new OutboxNotificationAdapter({ transport: webhook.deliver.bind(webhook) });\n * ```\n *\n * `deliver` and `NotificationTransport` (`(event) => void | Promise<void>`)\n * are structurally compatible, so this composition type-checks with no\n * adapter shim.\n *\n * **Security.** The signing secret is never included in a log message or in a\n * {@link WebhookDeliveryError}'s message/fields — only the HTTP status and/or\n * the underlying transport error's own message are surfaced.\n */\nexport class WebhookNotificationAdapter implements INotificationAdapter {\n private readonly url: string;\n private readonly staticHeaders: Record<string, string>;\n private readonly secret?: string;\n private readonly signatureHeader: string;\n private readonly timeoutMs: number;\n private readonly maxAttempts: number;\n private readonly baseDelayMs: number;\n private readonly backoffFactor: number;\n private readonly maxDelayMs: number;\n private readonly clock: Clock;\n private readonly logger: Logger;\n private readonly httpClient: HttpClient;\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly random: () => number;\n\n constructor(options: WebhookNotificationAdapterOptions) {\n this.url = options.url;\n this.staticHeaders = options.headers ?? {};\n this.secret = options.secret;\n this.signatureHeader = options.signatureHeader ?? DEFAULT_SIGNATURE_HEADER;\n this.timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n this.maxAttempts = Math.max(1, Math.floor(options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS));\n this.baseDelayMs = Math.max(0, options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);\n this.backoffFactor = options.backoffFactor ?? DEFAULT_BACKOFF_FACTOR;\n this.maxDelayMs = Math.max(0, options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);\n this.clock = options.clock ?? systemClock;\n this.logger = options.logger ?? noopLogger;\n this.httpClient = options.httpClient ?? getDefaultHttpClient();\n this.sleep = options.sleep ?? defaultSleep;\n this.random = options.random ?? Math.random;\n }\n\n /**\n * Deliver the event, retrying transient failures. Never throws per the\n * {@link INotificationAdapter} contract: on final failure the error is\n * logged (never with the secret) and swallowed.\n */\n async notify(event: NotificationEvent): Promise<void> {\n try {\n await this.deliver(event);\n } catch (err) {\n this.logger.error(\n 'WebhookNotificationAdapter: giving up on delivery, dropping notification',\n err,\n {\n type: event.type,\n instanceId: event.instanceId,\n tenantId: event.tenantId,\n url: this.url,\n },\n );\n }\n }\n\n /**\n * POST `event` as JSON to the configured URL, retrying retryable failures\n * with exponential backoff + full jitter (honoring `Retry-After` on `429`)\n * up to `maxAttempts`.\n *\n * Unlike {@link notify}, this throws {@link WebhookDeliveryError} on final\n * failure rather than swallowing it — intentionally, so it can be composed\n * as a throwing `transport` for\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter}\n * (see the class doc).\n *\n * @throws {WebhookDeliveryError} If a non-retryable status is returned, or\n * `maxAttempts` is exhausted.\n */\n async deliver(event: NotificationEvent): Promise<void> {\n const body = JSON.stringify(event);\n const headers = this.buildHeaders(body);\n\n let attempt = 0;\n for (;;) {\n attempt++;\n let response: Response | undefined;\n let networkError: unknown;\n\n try {\n response = await this.performRequest(body, headers);\n } catch (err) {\n networkError = err;\n }\n\n if (response && this.isSuccessStatus(response.status)) {\n return;\n }\n\n const retryable = response ? this.isRetryableStatus(response.status) : true;\n const exhausted = attempt >= this.maxAttempts;\n\n if (!retryable || exhausted) {\n throw this.buildError(attempt, response, networkError);\n }\n\n const delayMs = response\n ? this.retryDelayForResponse(response, attempt)\n : this.computeBackoff(attempt);\n await this.sleep(delayMs);\n }\n }\n\n /** Issues one POST attempt with an `AbortController`-backed timeout. */\n private async performRequest(body: string, headers: Record<string, string>): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n return await this.httpClient(this.url, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** Builds request headers: content-type, static headers, then the signature (always wins). */\n private buildHeaders(body: string): Record<string, string> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n ...this.staticHeaders,\n };\n if (this.secret) {\n const timestampSeconds = Math.floor(this.clock.now().getTime() / 1000);\n const signingString = `${timestampSeconds}.${body}`;\n const signature = createHmac('sha256', this.secret).update(signingString).digest('hex');\n headers[this.signatureHeader] = `t=${timestampSeconds},v1=${signature}`;\n }\n return headers;\n }\n\n /** `2xx` is success. */\n private isSuccessStatus(status: number): boolean {\n return status >= 200 && status < 300;\n }\n\n /** `5xx`, `408` (request timeout), and `429` (rate limited) are worth retrying; other `4xx` are not. */\n private isRetryableStatus(status: number): boolean {\n return status >= 500 || RETRYABLE_STATUSES.has(status);\n }\n\n /** Delay before the next attempt for a retryable response: `Retry-After` on 429, else computed backoff. */\n private retryDelayForResponse(response: Response, attempt: number): number {\n if (response.status === 429) {\n const retryAfterMs = this.parseRetryAfterMs(response);\n if (retryAfterMs !== undefined) return retryAfterMs;\n }\n return this.computeBackoff(attempt);\n }\n\n /**\n * Parses a `Retry-After` header (delay-seconds or an HTTP date) into a\n * millisecond delay measured from the injected {@link Clock}. Returns\n * `undefined` when absent or unparseable.\n */\n private parseRetryAfterMs(response: Response): number | undefined {\n const header = response.headers.get('retry-after');\n if (!header) return undefined;\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);\n\n const dateMs = Date.parse(header);\n if (!Number.isNaN(dateMs)) return Math.max(0, dateMs - this.clock.now().getTime());\n\n return undefined;\n }\n\n /**\n * Exponential backoff for the Nth attempt (1-based) with full jitter —\n * uniformly random in `[0, cap]` — capped at `maxDelayMs`. A non-finite or\n * negative intermediate value (extreme attempt counts) collapses to the cap\n * rather than overflowing to `Infinity`/`NaN`.\n */\n private computeBackoff(attempt: number): number {\n const raw = this.baseDelayMs * Math.pow(this.backoffFactor, attempt - 1);\n const cap = !Number.isFinite(raw) || raw < 0 ? this.maxDelayMs : Math.min(raw, this.maxDelayMs);\n return Math.floor(this.random() * cap);\n }\n\n /** Builds the final {@link WebhookDeliveryError} — never includes the secret. */\n private buildError(\n attempt: number,\n response: Response | undefined,\n networkError: unknown,\n ): WebhookDeliveryError {\n if (response) {\n return new WebhookDeliveryError(\n `WebhookNotificationAdapter: delivery failed after ${attempt} attempt(s) with status ${response.status}`,\n { status: response.status, attempts: attempt },\n );\n }\n const message = networkError instanceof Error ? networkError.message : String(networkError);\n return new WebhookDeliveryError(\n `WebhookNotificationAdapter: delivery failed after ${attempt} attempt(s): ${message}`,\n {\n attempts: attempt,\n cause: networkError,\n },\n );\n }\n}\n"]}
@@ -25,7 +25,7 @@ type HttpClient = (input: string | URL, init?: RequestInit) => Promise<Response>
25
25
  * Resolves the default {@link HttpClient}: `globalThis.fetch`, bound so it can
26
26
  * be invoked detached from `globalThis`.
27
27
  *
28
- * @throws {Error} If no global `fetch` exists (Node.js < 18). The message
28
+ * @throws {ApprovalValidationError} If no global `fetch` exists (Node.js < 18). The message
29
29
  * names both ways to fix it: upgrade Node.js, or pass an explicit
30
30
  * `httpClient` (any fetch-shaped function) via
31
31
  * `WebhookNotificationAdapterOptions`.
@@ -25,7 +25,7 @@ type HttpClient = (input: string | URL, init?: RequestInit) => Promise<Response>
25
25
  * Resolves the default {@link HttpClient}: `globalThis.fetch`, bound so it can
26
26
  * be invoked detached from `globalThis`.
27
27
  *
28
- * @throws {Error} If no global `fetch` exists (Node.js < 18). The message
28
+ * @throws {ApprovalValidationError} If no global `fetch` exists (Node.js < 18). The message
29
29
  * names both ways to fix it: upgrade Node.js, or pass an explicit
30
30
  * `httpClient` (any fetch-shaped function) via
31
31
  * `WebhookNotificationAdapterOptions`.
@@ -19,11 +19,40 @@ var noopLogger = {
19
19
  }
20
20
  };
21
21
 
22
+ // src/errors.ts
23
+ var ApprovalError = class extends Error {
24
+ constructor(message, code) {
25
+ super(message);
26
+ this.code = code;
27
+ this.name = "ApprovalError";
28
+ }
29
+ toJSON() {
30
+ return { code: this.code, message: this.message, name: this.name };
31
+ }
32
+ toHttpStatus() {
33
+ const map = {
34
+ NOT_FOUND: 404,
35
+ CONFLICT: 409,
36
+ FORBIDDEN: 403,
37
+ VALIDATION: 422,
38
+ TEMPLATE_NOT_FOUND: 404
39
+ };
40
+ return map[this.code] ?? 500;
41
+ }
42
+ };
43
+ var ApprovalValidationError = class extends ApprovalError {
44
+ constructor(message, cause) {
45
+ super(message, "VALIDATION");
46
+ this.cause = cause;
47
+ this.name = "ApprovalValidationError";
48
+ }
49
+ };
50
+
22
51
  // src/plugins/webhook/IHttpClient.ts
23
52
  function getDefaultHttpClient() {
24
53
  const globalFetch = globalThis.fetch;
25
54
  if (typeof globalFetch !== "function") {
26
- throw new Error(
55
+ throw new ApprovalValidationError(
27
56
  "hierarchical-approval/plugins/webhook: no global `fetch` was found. This is built into Node.js 18+ \u2014 on an older runtime, either upgrade Node.js or pass an explicit `httpClient` (any function shaped like `fetch`) via WebhookNotificationAdapterOptions."
28
57
  );
29
58
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/plugins/webhook/IHttpClient.ts","../../src/plugins/webhook/WebhookNotificationAdapter.ts"],"names":[],"mappings":";;;;;AAMO,IAAM,cAAqB,EAAE,GAAA,EAAK,sBAAM,IAAI,MAAK,EAAE;;;ACSnD,IAAM,UAAA,GAAqB;AAAA,EAChC,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC;AAChB,CAAA;;;ACOO,SAAS,oBAAA,GAAmC;AACjD,EAAA,MAAM,cAAc,UAAA,CAAW,KAAA;AAC/B,EAAA,IAAI,OAAO,gBAAgB,UAAA,EAAY;AACrC,IAAA,MAAM,IAAI,KAAA;AAAA,MACR;AAAA,KAGF;AAAA,EACF;AACA,EAAA,OAAO,WAAA,CAAY,KAAK,UAAU,CAAA;AACpC;;;ACxBO,IAAM,wBAAA,GAA2B;AAGxC,IAAM,kBAAA,GAAqB,GAAA;AAG3B,IAAM,oBAAA,GAAuB,CAAA;AAG7B,IAAM,qBAAA,GAAwB,GAAA;AAG9B,IAAM,sBAAA,GAAyB,CAAA;AAG/B,IAAM,oBAAA,GAAuB,GAAA;AAG7B,IAAM,qCAAqB,IAAI,GA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AA,CAAS,MAAM,CAAA,CAAA;AAAA,QACtG,EAAE,MAAA,EAAQ,QAAA,CAAS,MAAA,EAAQ,UAAU,OAAA;AAAQ,OAC/C;AAAA,IACF;AACA,IAAA,MAAM,UAAU,YAAA,YAAwB,KAAA,GAAQ,YAAA,CAAa,OAAA,GAAU,OAAO,YAAY,CAAA;AAC1F,IAAA,OAAO,IAAI,oBAAA;AAAA,MACT,CAAA,kDAAA,EAAqD,OAAO,CAAA,aAAA,EAAgB,OAAO,CAAA,CAAA;AAAA,MACnF;AAAA,QACE,QAAA,EAAU,OAAA;AAAA,QACV,KAAA,EAAO;AAAA;AACT,KACF;AAAA,EACF;AACF","file":"webhook.js","sourcesContent":["/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/**\n * Minimal, dependency-free HTTP port shaped after the WHATWG `fetch` function.\n *\n * The global `fetch` (built into Node.js since v18) is structurally assignable\n * to {@link HttpClient} as-is — no wrapping required, mirroring how a real\n * OpenTelemetry `Tracer` is structurally assignable to this library's\n * {@link import('../tracing/ITracer.js').Tracer} port. This library never adds\n * a dependency on axios/node-fetch/undici: bring your own fetch-shaped function\n * if you need custom behavior (a proxy, request mocking, a different runtime's\n * fetch), or use {@link getDefaultHttpClient}, which forwards to\n * `globalThis.fetch`.\n *\n * The parameter type is intentionally narrower than `fetch`'s own\n * `RequestInfo | URL` (it omits `Request`), which is what makes the global\n * `fetch` assignable here: a function accepting a *wider* input domain is\n * always assignable to a type expecting a *narrower* one.\n */\nexport type HttpClient = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Resolves the default {@link HttpClient}: `globalThis.fetch`, bound so it can\n * be invoked detached from `globalThis`.\n *\n * @throws {Error} If no global `fetch` exists (Node.js < 18). The message\n * names both ways to fix it: upgrade Node.js, or pass an explicit\n * `httpClient` (any fetch-shaped function) via\n * `WebhookNotificationAdapterOptions`.\n */\nexport function getDefaultHttpClient(): HttpClient {\n const globalFetch = globalThis.fetch;\n if (typeof globalFetch !== 'function') {\n throw new Error(\n 'hierarchical-approval/plugins/webhook: no global `fetch` was found. This is built into ' +\n 'Node.js 18+ — on an older runtime, either upgrade Node.js or pass an explicit ' +\n '`httpClient` (any function shaped like `fetch`) via WebhookNotificationAdapterOptions.',\n );\n }\n return globalFetch.bind(globalThis);\n}\n","import { createHmac } from 'node:crypto';\n\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport type {\n INotificationAdapter,\n NotificationEvent,\n} from '../../adapters/INotificationAdapter.js';\nimport type { HttpClient } from './IHttpClient.js';\nimport { getDefaultHttpClient } from './IHttpClient.js';\n\n/** Default header carrying the HMAC signature when `secret` is configured. */\nexport const DEFAULT_SIGNATURE_HEADER = 'X-Approval-Signature';\n\n/** Default per-request timeout, in milliseconds, before the request is aborted. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Default cap on delivery attempts inside a single {@link WebhookNotificationAdapter.deliver} call. */\nconst DEFAULT_MAX_ATTEMPTS = 3;\n\n/** Default base backoff delay, in milliseconds, for the first retry. */\nconst DEFAULT_BASE_DELAY_MS = 300;\n\n/** Default multiplier applied per attempt (exponential backoff). */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/** Default cap on a single computed backoff delay, in milliseconds. */\nconst DEFAULT_MAX_DELAY_MS = 10_000;\n\n/** HTTP status codes worth retrying: request timeout, rate-limited, and any server error. */\nconst RETRYABLE_STATUSES = new Set([408, 429]);\n\n/** Sleeps for `ms` milliseconds using the real timer. Overridable via `options.sleep` in tests. */\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Thrown by {@link WebhookNotificationAdapter.deliver} when delivery could not\n * be completed — either a non-retryable HTTP response (e.g. `4xx` other than\n * `408`/`429`) was received, or all retry attempts were exhausted.\n *\n * Never carries the signing secret: the message is built only from the HTTP\n * status and/or the underlying transport error's own message.\n */\nexport class WebhookDeliveryError extends Error {\n /** HTTP status of the last response received, if any (absent on a pure network/timeout failure). */\n readonly status?: number;\n /** Number of delivery attempts made before giving up. */\n readonly attempts: number;\n /**\n * The underlying network/timeout error that caused the final attempt to\n * fail, if delivery failed without ever receiving a response. Declared\n * explicitly (rather than relying on the ES2022 `Error.cause` option) since\n * this package targets ES2020.\n */\n readonly cause?: unknown;\n\n constructor(message: string, options: { status?: number; attempts: number; cause?: unknown }) {\n super(message);\n this.name = 'WebhookDeliveryError';\n this.status = options.status;\n this.attempts = options.attempts;\n this.cause = options.cause;\n }\n}\n\n/** Configuration for {@link WebhookNotificationAdapter}. */\nexport interface WebhookNotificationAdapterOptions {\n /** Destination URL every notification event is POSTed to as JSON. Required. */\n url: string;\n /** Extra static headers merged into every request (e.g. `Authorization`). */\n headers?: Record<string, string>;\n /**\n * Shared secret used to HMAC-SHA256-sign each request body. When omitted,\n * requests are sent unsigned. Never logged and never echoed in a thrown\n * error's message.\n */\n secret?: string;\n /** Header name the signature is emitted under. Defaults to {@link DEFAULT_SIGNATURE_HEADER}. */\n signatureHeader?: string;\n /** Per-request timeout in milliseconds before the request is aborted. Defaults to `10_000`. */\n timeoutMs?: number;\n /**\n * Maximum delivery attempts made by a single {@link deliver} call before\n * throwing {@link WebhookDeliveryError}. Must be >= 1. Defaults to `3`.\n *\n * This is a short, local retry budget for transient blips — it is not a\n * substitute for durable retry across process restarts. Compose with\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter}\n * for that (see the class doc).\n */\n maxAttempts?: number;\n /** Base backoff in milliseconds for the first retry. Defaults to `300`. */\n baseDelayMs?: number;\n /** Multiplier applied per attempt (exponential). Defaults to `2`. */\n backoffFactor?: number;\n /** Upper bound on a single computed backoff delay, in milliseconds. Defaults to `10_000`. */\n maxDelayMs?: number;\n /** Time source used for the signature timestamp and for resolving a `Retry-After` date. Defaults to {@link systemClock}. */\n clock?: Clock;\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Fetch-shaped HTTP port. Defaults to {@link getDefaultHttpClient}. */\n httpClient?: HttpClient;\n /** Delay function used between retries. Defaults to a real `setTimeout`-based sleep; inject a no-op/fake in tests. */\n sleep?: (ms: number) => Promise<void>;\n /**\n * Source of randomness in `[0, 1)` used for jitter. Defaults to `Math.random`.\n * Inject a deterministic function in tests to assert exact backoff delays.\n */\n random?: () => number;\n}\n\n/**\n * {@link INotificationAdapter} that delivers each approval event as a signed,\n * JSON HTTP POST to a configured webhook URL.\n *\n * **Signing.** When `secret` is configured, every request carries a\n * `{signatureHeader}: t=<unix-seconds>,v1=<hex-hmac>` header (Stripe-style),\n * where the HMAC-SHA256 digest is computed over the signing string\n * `\"<timestamp>.<body>\"`. Folding the timestamp into the signed payload lets a\n * receiver reject stale/replayed requests by checking `t` against its own\n * clock before trusting `v1`. Signing is opt-in — omit `secret` to send\n * unsigned requests.\n *\n * **Retry.** `5xx` responses, `408`, `429`, and network/timeout errors are\n * retried with exponential backoff and full jitter, up to `maxAttempts`. A\n * `429` response honors a `Retry-After` header (seconds or an HTTP date) in\n * place of the computed backoff. Any other non-2xx status (e.g. `400`, `401`,\n * `404`) is treated as permanent and is not retried.\n *\n * **Durability.** `notify()` — the {@link INotificationAdapter} method — never\n * throws, per that port's contract: on exhausting `maxAttempts` it logs and\n * drops the notification. That makes this adapter, used alone, *at-most-once*\n * and blocking (it awaits the full retry sequence inline). For at-least-once\n * delivery that survives a process restart, do not reimplement dead-lettering\n * here — instead compose with\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter},\n * passing this adapter's throwing {@link deliver} method (bound) as its\n * `transport`:\n *\n * ```ts\n * const webhook = new WebhookNotificationAdapter({ url, secret });\n * const durable = new OutboxNotificationAdapter({ transport: webhook.deliver.bind(webhook) });\n * ```\n *\n * `deliver` and `NotificationTransport` (`(event) => void | Promise<void>`)\n * are structurally compatible, so this composition type-checks with no\n * adapter shim.\n *\n * **Security.** The signing secret is never included in a log message or in a\n * {@link WebhookDeliveryError}'s message/fields — only the HTTP status and/or\n * the underlying transport error's own message are surfaced.\n */\nexport class WebhookNotificationAdapter implements INotificationAdapter {\n private readonly url: string;\n private readonly staticHeaders: Record<string, string>;\n private readonly secret?: string;\n private readonly signatureHeader: string;\n private readonly timeoutMs: number;\n private readonly maxAttempts: number;\n private readonly baseDelayMs: number;\n private readonly backoffFactor: number;\n private readonly maxDelayMs: number;\n private readonly clock: Clock;\n private readonly logger: Logger;\n private readonly httpClient: HttpClient;\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly random: () => number;\n\n constructor(options: WebhookNotificationAdapterOptions) {\n this.url = options.url;\n this.staticHeaders = options.headers ?? {};\n this.secret = options.secret;\n this.signatureHeader = options.signatureHeader ?? DEFAULT_SIGNATURE_HEADER;\n this.timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n this.maxAttempts = Math.max(1, Math.floor(options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS));\n this.baseDelayMs = Math.max(0, options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);\n this.backoffFactor = options.backoffFactor ?? DEFAULT_BACKOFF_FACTOR;\n this.maxDelayMs = Math.max(0, options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);\n this.clock = options.clock ?? systemClock;\n this.logger = options.logger ?? noopLogger;\n this.httpClient = options.httpClient ?? getDefaultHttpClient();\n this.sleep = options.sleep ?? defaultSleep;\n this.random = options.random ?? Math.random;\n }\n\n /**\n * Deliver the event, retrying transient failures. Never throws per the\n * {@link INotificationAdapter} contract: on final failure the error is\n * logged (never with the secret) and swallowed.\n */\n async notify(event: NotificationEvent): Promise<void> {\n try {\n await this.deliver(event);\n } catch (err) {\n this.logger.error(\n 'WebhookNotificationAdapter: giving up on delivery, dropping notification',\n err,\n {\n type: event.type,\n instanceId: event.instanceId,\n tenantId: event.tenantId,\n url: this.url,\n },\n );\n }\n }\n\n /**\n * POST `event` as JSON to the configured URL, retrying retryable failures\n * with exponential backoff + full jitter (honoring `Retry-After` on `429`)\n * up to `maxAttempts`.\n *\n * Unlike {@link notify}, this throws {@link WebhookDeliveryError} on final\n * failure rather than swallowing it — intentionally, so it can be composed\n * as a throwing `transport` for\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter}\n * (see the class doc).\n *\n * @throws {WebhookDeliveryError} If a non-retryable status is returned, or\n * `maxAttempts` is exhausted.\n */\n async deliver(event: NotificationEvent): Promise<void> {\n const body = JSON.stringify(event);\n const headers = this.buildHeaders(body);\n\n let attempt = 0;\n for (;;) {\n attempt++;\n let response: Response | undefined;\n let networkError: unknown;\n\n try {\n response = await this.performRequest(body, headers);\n } catch (err) {\n networkError = err;\n }\n\n if (response && this.isSuccessStatus(response.status)) {\n return;\n }\n\n const retryable = response ? this.isRetryableStatus(response.status) : true;\n const exhausted = attempt >= this.maxAttempts;\n\n if (!retryable || exhausted) {\n throw this.buildError(attempt, response, networkError);\n }\n\n const delayMs = response\n ? this.retryDelayForResponse(response, attempt)\n : this.computeBackoff(attempt);\n await this.sleep(delayMs);\n }\n }\n\n /** Issues one POST attempt with an `AbortController`-backed timeout. */\n private async performRequest(body: string, headers: Record<string, string>): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n return await this.httpClient(this.url, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** Builds request headers: content-type, static headers, then the signature (always wins). */\n private buildHeaders(body: string): Record<string, string> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n ...this.staticHeaders,\n };\n if (this.secret) {\n const timestampSeconds = Math.floor(this.clock.now().getTime() / 1000);\n const signingString = `${timestampSeconds}.${body}`;\n const signature = createHmac('sha256', this.secret).update(signingString).digest('hex');\n headers[this.signatureHeader] = `t=${timestampSeconds},v1=${signature}`;\n }\n return headers;\n }\n\n /** `2xx` is success. */\n private isSuccessStatus(status: number): boolean {\n return status >= 200 && status < 300;\n }\n\n /** `5xx`, `408` (request timeout), and `429` (rate limited) are worth retrying; other `4xx` are not. */\n private isRetryableStatus(status: number): boolean {\n return status >= 500 || RETRYABLE_STATUSES.has(status);\n }\n\n /** Delay before the next attempt for a retryable response: `Retry-After` on 429, else computed backoff. */\n private retryDelayForResponse(response: Response, attempt: number): number {\n if (response.status === 429) {\n const retryAfterMs = this.parseRetryAfterMs(response);\n if (retryAfterMs !== undefined) return retryAfterMs;\n }\n return this.computeBackoff(attempt);\n }\n\n /**\n * Parses a `Retry-After` header (delay-seconds or an HTTP date) into a\n * millisecond delay measured from the injected {@link Clock}. Returns\n * `undefined` when absent or unparseable.\n */\n private parseRetryAfterMs(response: Response): number | undefined {\n const header = response.headers.get('retry-after');\n if (!header) return undefined;\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);\n\n const dateMs = Date.parse(header);\n if (!Number.isNaN(dateMs)) return Math.max(0, dateMs - this.clock.now().getTime());\n\n return undefined;\n }\n\n /**\n * Exponential backoff for the Nth attempt (1-based) with full jitter —\n * uniformly random in `[0, cap]` — capped at `maxDelayMs`. A non-finite or\n * negative intermediate value (extreme attempt counts) collapses to the cap\n * rather than overflowing to `Infinity`/`NaN`.\n */\n private computeBackoff(attempt: number): number {\n const raw = this.baseDelayMs * Math.pow(this.backoffFactor, attempt - 1);\n const cap = !Number.isFinite(raw) || raw < 0 ? this.maxDelayMs : Math.min(raw, this.maxDelayMs);\n return Math.floor(this.random() * cap);\n }\n\n /** Builds the final {@link WebhookDeliveryError} — never includes the secret. */\n private buildError(\n attempt: number,\n response: Response | undefined,\n networkError: unknown,\n ): WebhookDeliveryError {\n if (response) {\n return new WebhookDeliveryError(\n `WebhookNotificationAdapter: delivery failed after ${attempt} attempt(s) with status ${response.status}`,\n { status: response.status, attempts: attempt },\n );\n }\n const message = networkError instanceof Error ? networkError.message : String(networkError);\n return new WebhookDeliveryError(\n `WebhookNotificationAdapter: delivery failed after ${attempt} attempt(s): ${message}`,\n {\n attempts: attempt,\n cause: networkError,\n },\n );\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/utils/Clock.ts","../../src/utils/Logger.ts","../../src/errors.ts","../../src/plugins/webhook/IHttpClient.ts","../../src/plugins/webhook/WebhookNotificationAdapter.ts"],"names":[],"mappings":";;;;;AAMO,IAAM,cAAqB,EAAE,GAAA,EAAK,sBAAM,IAAI,MAAK,EAAE;;;ACSnD,IAAM,UAAA,GAAqB;AAAA,EAChC,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,MAAM,MAAM;AAAA,EAAC,CAAA;AAAA,EACb,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC,CAAA;AAAA,EACd,OAAO,MAAM;AAAA,EAAC;AAChB,CAAA;;;ACpBO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,WAAA,CACE,SACgB,IAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAFG,IAAA,IAAA,CAAA,IAAA,GAAA,IAAA;AAGhB,IAAA,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QACtG,EAAE,MAAA,EAAQ,QAAA,CAAS,MAAA,EAAQ,UAAU,OAAA;AAAQ,OAC/C;AAAA,IACF;AACA,IAAA,MAAM,UAAU,YAAA,YAAwB,KAAA,GAAQ,YAAA,CAAa,OAAA,GAAU,OAAO,YAAY,CAAA;AAC1F,IAAA,OAAO,IAAI,oBAAA;AAAA,MACT,CAAA,kDAAA,EAAqD,OAAO,CAAA,aAAA,EAAgB,OAAO,CAAA,CAAA;AAAA,MACnF;AAAA,QACE,QAAA,EAAU,OAAA;AAAA,QACV,KAAA,EAAO;AAAA;AACT,KACF;AAAA,EACF;AACF","file":"webhook.js","sourcesContent":["/** Time source injected into engine and plugin components, so tests can control the clock. */\nexport interface Clock {\n now(): Date;\n}\n\n/** {@link Clock} backed by the real wall clock — the default when no clock is configured. */\nexport const systemClock: Clock = { now: () => new Date() };\n","/** Structured logger injected into engine and plugin components. */\nexport interface Logger {\n /** Routine, expected activity. */\n info(msg: string, context?: Record<string, unknown>): void;\n /** Unexpected but recoverable condition. */\n warn(msg: string, context?: Record<string, unknown>): void;\n /** A caught error that did not stop the calling operation. */\n error(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** A caught error severe enough that the calling operation could not continue. */\n fatal(msg: string, err?: unknown, context?: Record<string, unknown>): void;\n /** Verbose, developer-facing detail. */\n debug(msg: string, context?: Record<string, unknown>): void;\n}\n\n/** {@link Logger} that discards every call — the default when no logger is configured. */\nexport const noopLogger: Logger = {\n info: () => {},\n warn: () => {},\n error: () => {},\n fatal: () => {},\n debug: () => {},\n};\n","/** Base class for all errors thrown by this library; carries a stable machine-readable `code`. */\nexport class ApprovalError extends Error {\n constructor(\n message: string,\n public readonly code: string,\n ) {\n super(message);\n this.name = 'ApprovalError';\n }\n\n toJSON(): { code: string; message: string; name: string } {\n return { code: this.code, message: this.message, name: this.name };\n }\n\n toHttpStatus(): number {\n const map: Record<string, number> = {\n NOT_FOUND: 404,\n CONFLICT: 409,\n FORBIDDEN: 403,\n VALIDATION: 422,\n TEMPLATE_NOT_FOUND: 404,\n };\n return map[this.code] ?? 500;\n }\n}\n\n/** Thrown when a requested resource (instance, template, etc.) does not exist. */\nexport class ApprovalNotFoundError extends ApprovalError {\n constructor(resource: string, id: string) {\n super(`${resource} \"${id}\" not found.`, 'NOT_FOUND');\n this.name = 'ApprovalNotFoundError';\n }\n}\n\n/** Thrown when an instance was modified by another process since it was last read. */\nexport class ApprovalConflictError extends ApprovalError {\n constructor(instanceId: string) {\n super(\n `Concurrent modification detected on instance \"${instanceId}\". The record was updated by another process. Please retry.`,\n 'CONFLICT',\n );\n this.name = 'ApprovalConflictError';\n }\n}\n\n/** Thrown when the caller is not authorized to perform the requested action. */\nexport class ApprovalForbiddenError extends ApprovalError {\n constructor(message: string) {\n super(message, 'FORBIDDEN');\n this.name = 'ApprovalForbiddenError';\n }\n}\n\n/** Thrown when input or configuration fails validation; `cause` may hold the originating error. */\nexport class ApprovalValidationError extends ApprovalError {\n constructor(\n message: string,\n public readonly cause?: unknown,\n ) {\n super(message, 'VALIDATION');\n this.name = 'ApprovalValidationError';\n }\n}\n\n/** Thrown when a template lookup by name finds no registered template. */\nexport class ApprovalTemplateNotFoundError extends ApprovalError {\n constructor(name: string) {\n super(`Template \"${name}\" not found.`, 'TEMPLATE_NOT_FOUND');\n this.name = 'ApprovalTemplateNotFoundError';\n }\n}\n","import { ApprovalValidationError } from '../../errors.js';\n\n/**\n * Minimal, dependency-free HTTP port shaped after the WHATWG `fetch` function.\n *\n * The global `fetch` (built into Node.js since v18) is structurally assignable\n * to {@link HttpClient} as-is — no wrapping required, mirroring how a real\n * OpenTelemetry `Tracer` is structurally assignable to this library's\n * {@link import('../tracing/ITracer.js').Tracer} port. This library never adds\n * a dependency on axios/node-fetch/undici: bring your own fetch-shaped function\n * if you need custom behavior (a proxy, request mocking, a different runtime's\n * fetch), or use {@link getDefaultHttpClient}, which forwards to\n * `globalThis.fetch`.\n *\n * The parameter type is intentionally narrower than `fetch`'s own\n * `RequestInfo | URL` (it omits `Request`), which is what makes the global\n * `fetch` assignable here: a function accepting a *wider* input domain is\n * always assignable to a type expecting a *narrower* one.\n */\nexport type HttpClient = (input: string | URL, init?: RequestInit) => Promise<Response>;\n\n/**\n * Resolves the default {@link HttpClient}: `globalThis.fetch`, bound so it can\n * be invoked detached from `globalThis`.\n *\n * @throws {ApprovalValidationError} If no global `fetch` exists (Node.js < 18). The message\n * names both ways to fix it: upgrade Node.js, or pass an explicit\n * `httpClient` (any fetch-shaped function) via\n * `WebhookNotificationAdapterOptions`.\n */\nexport function getDefaultHttpClient(): HttpClient {\n const globalFetch = globalThis.fetch;\n if (typeof globalFetch !== 'function') {\n throw new ApprovalValidationError(\n 'hierarchical-approval/plugins/webhook: no global `fetch` was found. This is built into ' +\n 'Node.js 18+ — on an older runtime, either upgrade Node.js or pass an explicit ' +\n '`httpClient` (any function shaped like `fetch`) via WebhookNotificationAdapterOptions.',\n );\n }\n return globalFetch.bind(globalThis);\n}\n","import { createHmac } from 'node:crypto';\n\nimport type { Clock } from '../../utils/Clock.js';\nimport { systemClock } from '../../utils/Clock.js';\nimport type { Logger } from '../../utils/Logger.js';\nimport { noopLogger } from '../../utils/Logger.js';\nimport type {\n INotificationAdapter,\n NotificationEvent,\n} from '../../adapters/INotificationAdapter.js';\nimport type { HttpClient } from './IHttpClient.js';\nimport { getDefaultHttpClient } from './IHttpClient.js';\n\n/** Default header carrying the HMAC signature when `secret` is configured. */\nexport const DEFAULT_SIGNATURE_HEADER = 'X-Approval-Signature';\n\n/** Default per-request timeout, in milliseconds, before the request is aborted. */\nconst DEFAULT_TIMEOUT_MS = 10_000;\n\n/** Default cap on delivery attempts inside a single {@link WebhookNotificationAdapter.deliver} call. */\nconst DEFAULT_MAX_ATTEMPTS = 3;\n\n/** Default base backoff delay, in milliseconds, for the first retry. */\nconst DEFAULT_BASE_DELAY_MS = 300;\n\n/** Default multiplier applied per attempt (exponential backoff). */\nconst DEFAULT_BACKOFF_FACTOR = 2;\n\n/** Default cap on a single computed backoff delay, in milliseconds. */\nconst DEFAULT_MAX_DELAY_MS = 10_000;\n\n/** HTTP status codes worth retrying: request timeout, rate-limited, and any server error. */\nconst RETRYABLE_STATUSES = new Set([408, 429]);\n\n/** Sleeps for `ms` milliseconds using the real timer. Overridable via `options.sleep` in tests. */\nfunction defaultSleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/**\n * Thrown by {@link WebhookNotificationAdapter.deliver} when delivery could not\n * be completed — either a non-retryable HTTP response (e.g. `4xx` other than\n * `408`/`429`) was received, or all retry attempts were exhausted.\n *\n * Never carries the signing secret: the message is built only from the HTTP\n * status and/or the underlying transport error's own message.\n */\nexport class WebhookDeliveryError extends Error {\n /** HTTP status of the last response received, if any (absent on a pure network/timeout failure). */\n readonly status?: number;\n /** Number of delivery attempts made before giving up. */\n readonly attempts: number;\n /**\n * The underlying network/timeout error that caused the final attempt to\n * fail, if delivery failed without ever receiving a response. Declared\n * explicitly (rather than relying on the ES2022 `Error.cause` option) since\n * this package targets ES2020.\n */\n readonly cause?: unknown;\n\n constructor(message: string, options: { status?: number; attempts: number; cause?: unknown }) {\n super(message);\n this.name = 'WebhookDeliveryError';\n this.status = options.status;\n this.attempts = options.attempts;\n this.cause = options.cause;\n }\n}\n\n/** Configuration for {@link WebhookNotificationAdapter}. */\nexport interface WebhookNotificationAdapterOptions {\n /** Destination URL every notification event is POSTed to as JSON. Required. */\n url: string;\n /** Extra static headers merged into every request (e.g. `Authorization`). */\n headers?: Record<string, string>;\n /**\n * Shared secret used to HMAC-SHA256-sign each request body. When omitted,\n * requests are sent unsigned. Never logged and never echoed in a thrown\n * error's message.\n */\n secret?: string;\n /** Header name the signature is emitted under. Defaults to {@link DEFAULT_SIGNATURE_HEADER}. */\n signatureHeader?: string;\n /** Per-request timeout in milliseconds before the request is aborted. Defaults to `10_000`. */\n timeoutMs?: number;\n /**\n * Maximum delivery attempts made by a single {@link deliver} call before\n * throwing {@link WebhookDeliveryError}. Must be >= 1. Defaults to `3`.\n *\n * This is a short, local retry budget for transient blips — it is not a\n * substitute for durable retry across process restarts. Compose with\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter}\n * for that (see the class doc).\n */\n maxAttempts?: number;\n /** Base backoff in milliseconds for the first retry. Defaults to `300`. */\n baseDelayMs?: number;\n /** Multiplier applied per attempt (exponential). Defaults to `2`. */\n backoffFactor?: number;\n /** Upper bound on a single computed backoff delay, in milliseconds. Defaults to `10_000`. */\n maxDelayMs?: number;\n /** Time source used for the signature timestamp and for resolving a `Retry-After` date. Defaults to {@link systemClock}. */\n clock?: Clock;\n /** Structured logger. Defaults to {@link noopLogger}. */\n logger?: Logger;\n /** Fetch-shaped HTTP port. Defaults to {@link getDefaultHttpClient}. */\n httpClient?: HttpClient;\n /** Delay function used between retries. Defaults to a real `setTimeout`-based sleep; inject a no-op/fake in tests. */\n sleep?: (ms: number) => Promise<void>;\n /**\n * Source of randomness in `[0, 1)` used for jitter. Defaults to `Math.random`.\n * Inject a deterministic function in tests to assert exact backoff delays.\n */\n random?: () => number;\n}\n\n/**\n * {@link INotificationAdapter} that delivers each approval event as a signed,\n * JSON HTTP POST to a configured webhook URL.\n *\n * **Signing.** When `secret` is configured, every request carries a\n * `{signatureHeader}: t=<unix-seconds>,v1=<hex-hmac>` header (Stripe-style),\n * where the HMAC-SHA256 digest is computed over the signing string\n * `\"<timestamp>.<body>\"`. Folding the timestamp into the signed payload lets a\n * receiver reject stale/replayed requests by checking `t` against its own\n * clock before trusting `v1`. Signing is opt-in — omit `secret` to send\n * unsigned requests.\n *\n * **Retry.** `5xx` responses, `408`, `429`, and network/timeout errors are\n * retried with exponential backoff and full jitter, up to `maxAttempts`. A\n * `429` response honors a `Retry-After` header (seconds or an HTTP date) in\n * place of the computed backoff. Any other non-2xx status (e.g. `400`, `401`,\n * `404`) is treated as permanent and is not retried.\n *\n * **Durability.** `notify()` — the {@link INotificationAdapter} method — never\n * throws, per that port's contract: on exhausting `maxAttempts` it logs and\n * drops the notification. That makes this adapter, used alone, *at-most-once*\n * and blocking (it awaits the full retry sequence inline). For at-least-once\n * delivery that survives a process restart, do not reimplement dead-lettering\n * here — instead compose with\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter},\n * passing this adapter's throwing {@link deliver} method (bound) as its\n * `transport`:\n *\n * ```ts\n * const webhook = new WebhookNotificationAdapter({ url, secret });\n * const durable = new OutboxNotificationAdapter({ transport: webhook.deliver.bind(webhook) });\n * ```\n *\n * `deliver` and `NotificationTransport` (`(event) => void | Promise<void>`)\n * are structurally compatible, so this composition type-checks with no\n * adapter shim.\n *\n * **Security.** The signing secret is never included in a log message or in a\n * {@link WebhookDeliveryError}'s message/fields — only the HTTP status and/or\n * the underlying transport error's own message are surfaced.\n */\nexport class WebhookNotificationAdapter implements INotificationAdapter {\n private readonly url: string;\n private readonly staticHeaders: Record<string, string>;\n private readonly secret?: string;\n private readonly signatureHeader: string;\n private readonly timeoutMs: number;\n private readonly maxAttempts: number;\n private readonly baseDelayMs: number;\n private readonly backoffFactor: number;\n private readonly maxDelayMs: number;\n private readonly clock: Clock;\n private readonly logger: Logger;\n private readonly httpClient: HttpClient;\n private readonly sleep: (ms: number) => Promise<void>;\n private readonly random: () => number;\n\n constructor(options: WebhookNotificationAdapterOptions) {\n this.url = options.url;\n this.staticHeaders = options.headers ?? {};\n this.secret = options.secret;\n this.signatureHeader = options.signatureHeader ?? DEFAULT_SIGNATURE_HEADER;\n this.timeoutMs = Math.max(1, options.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n this.maxAttempts = Math.max(1, Math.floor(options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS));\n this.baseDelayMs = Math.max(0, options.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);\n this.backoffFactor = options.backoffFactor ?? DEFAULT_BACKOFF_FACTOR;\n this.maxDelayMs = Math.max(0, options.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);\n this.clock = options.clock ?? systemClock;\n this.logger = options.logger ?? noopLogger;\n this.httpClient = options.httpClient ?? getDefaultHttpClient();\n this.sleep = options.sleep ?? defaultSleep;\n this.random = options.random ?? Math.random;\n }\n\n /**\n * Deliver the event, retrying transient failures. Never throws per the\n * {@link INotificationAdapter} contract: on final failure the error is\n * logged (never with the secret) and swallowed.\n */\n async notify(event: NotificationEvent): Promise<void> {\n try {\n await this.deliver(event);\n } catch (err) {\n this.logger.error(\n 'WebhookNotificationAdapter: giving up on delivery, dropping notification',\n err,\n {\n type: event.type,\n instanceId: event.instanceId,\n tenantId: event.tenantId,\n url: this.url,\n },\n );\n }\n }\n\n /**\n * POST `event` as JSON to the configured URL, retrying retryable failures\n * with exponential backoff + full jitter (honoring `Retry-After` on `429`)\n * up to `maxAttempts`.\n *\n * Unlike {@link notify}, this throws {@link WebhookDeliveryError} on final\n * failure rather than swallowing it — intentionally, so it can be composed\n * as a throwing `transport` for\n * {@link import('../notify/OutboxNotificationAdapter.js').OutboxNotificationAdapter}\n * (see the class doc).\n *\n * @throws {WebhookDeliveryError} If a non-retryable status is returned, or\n * `maxAttempts` is exhausted.\n */\n async deliver(event: NotificationEvent): Promise<void> {\n const body = JSON.stringify(event);\n const headers = this.buildHeaders(body);\n\n let attempt = 0;\n for (;;) {\n attempt++;\n let response: Response | undefined;\n let networkError: unknown;\n\n try {\n response = await this.performRequest(body, headers);\n } catch (err) {\n networkError = err;\n }\n\n if (response && this.isSuccessStatus(response.status)) {\n return;\n }\n\n const retryable = response ? this.isRetryableStatus(response.status) : true;\n const exhausted = attempt >= this.maxAttempts;\n\n if (!retryable || exhausted) {\n throw this.buildError(attempt, response, networkError);\n }\n\n const delayMs = response\n ? this.retryDelayForResponse(response, attempt)\n : this.computeBackoff(attempt);\n await this.sleep(delayMs);\n }\n }\n\n /** Issues one POST attempt with an `AbortController`-backed timeout. */\n private async performRequest(body: string, headers: Record<string, string>): Promise<Response> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), this.timeoutMs);\n try {\n return await this.httpClient(this.url, {\n method: 'POST',\n headers,\n body,\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n }\n }\n\n /** Builds request headers: content-type, static headers, then the signature (always wins). */\n private buildHeaders(body: string): Record<string, string> {\n const headers: Record<string, string> = {\n 'content-type': 'application/json',\n ...this.staticHeaders,\n };\n if (this.secret) {\n const timestampSeconds = Math.floor(this.clock.now().getTime() / 1000);\n const signingString = `${timestampSeconds}.${body}`;\n const signature = createHmac('sha256', this.secret).update(signingString).digest('hex');\n headers[this.signatureHeader] = `t=${timestampSeconds},v1=${signature}`;\n }\n return headers;\n }\n\n /** `2xx` is success. */\n private isSuccessStatus(status: number): boolean {\n return status >= 200 && status < 300;\n }\n\n /** `5xx`, `408` (request timeout), and `429` (rate limited) are worth retrying; other `4xx` are not. */\n private isRetryableStatus(status: number): boolean {\n return status >= 500 || RETRYABLE_STATUSES.has(status);\n }\n\n /** Delay before the next attempt for a retryable response: `Retry-After` on 429, else computed backoff. */\n private retryDelayForResponse(response: Response, attempt: number): number {\n if (response.status === 429) {\n const retryAfterMs = this.parseRetryAfterMs(response);\n if (retryAfterMs !== undefined) return retryAfterMs;\n }\n return this.computeBackoff(attempt);\n }\n\n /**\n * Parses a `Retry-After` header (delay-seconds or an HTTP date) into a\n * millisecond delay measured from the injected {@link Clock}. Returns\n * `undefined` when absent or unparseable.\n */\n private parseRetryAfterMs(response: Response): number | undefined {\n const header = response.headers.get('retry-after');\n if (!header) return undefined;\n\n const seconds = Number(header);\n if (Number.isFinite(seconds)) return Math.max(0, seconds * 1000);\n\n const dateMs = Date.parse(header);\n if (!Number.isNaN(dateMs)) return Math.max(0, dateMs - this.clock.now().getTime());\n\n return undefined;\n }\n\n /**\n * Exponential backoff for the Nth attempt (1-based) with full jitter —\n * uniformly random in `[0, cap]` — capped at `maxDelayMs`. A non-finite or\n * negative intermediate value (extreme attempt counts) collapses to the cap\n * rather than overflowing to `Infinity`/`NaN`.\n */\n private computeBackoff(attempt: number): number {\n const raw = this.baseDelayMs * Math.pow(this.backoffFactor, attempt - 1);\n const cap = !Number.isFinite(raw) || raw < 0 ? this.maxDelayMs : Math.min(raw, this.maxDelayMs);\n return Math.floor(this.random() * cap);\n }\n\n /** Builds the final {@link WebhookDeliveryError} — never includes the secret. */\n private buildError(\n attempt: number,\n response: Response | undefined,\n networkError: unknown,\n ): WebhookDeliveryError {\n if (response) {\n return new WebhookDeliveryError(\n `WebhookNotificationAdapter: delivery failed after ${attempt} attempt(s) with status ${response.status}`,\n { status: response.status, attempts: attempt },\n );\n }\n const message = networkError instanceof Error ? networkError.message : String(networkError);\n return new WebhookDeliveryError(\n `WebhookNotificationAdapter: delivery failed after ${attempt} attempt(s): ${message}`,\n {\n attempts: attempt,\n cause: networkError,\n },\n );\n }\n}\n"]}
package/dist/testing.cjs CHANGED
@@ -5275,7 +5275,7 @@ var ApprovalTestKit = class {
5275
5275
  for (const level of open) {
5276
5276
  const approverId = approverMap[level.level];
5277
5277
  if (!approverId) {
5278
- throw new Error(
5278
+ throw new ApprovalValidationError(
5279
5279
  `No approver provided for level ${level.level}. Pass all levels in approverMap.`
5280
5280
  );
5281
5281
  }