abxbus 2.5.4 → 2.5.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/BaseEvent.d.ts +53 -28
- package/dist/cjs/BaseEvent.js +148 -28
- package/dist/cjs/BaseEvent.js.map +2 -2
- package/dist/cjs/LockManager.js +1 -1
- package/dist/cjs/LockManager.js.map +2 -2
- package/dist/cjs/events_suck.d.ts +8 -15
- package/dist/cjs/events_suck.js +1 -1
- package/dist/cjs/events_suck.js.map +2 -2
- package/dist/cjs/jsonschema.d.ts +6 -0
- package/dist/cjs/jsonschema.js +155 -0
- package/dist/cjs/jsonschema.js.map +7 -0
- package/dist/cjs/retry.d.ts +2 -0
- package/dist/cjs/retry.js +110 -35
- package/dist/cjs/retry.js.map +3 -3
- package/dist/cjs/types.d.ts +6 -10
- package/dist/cjs/types.js +9 -16
- package/dist/cjs/types.js.map +2 -2
- package/dist/esm/BaseEvent.js +148 -28
- package/dist/esm/BaseEvent.js.map +2 -2
- package/dist/esm/LockManager.js +1 -1
- package/dist/esm/LockManager.js.map +2 -2
- package/dist/esm/events_suck.js +1 -1
- package/dist/esm/events_suck.js.map +2 -2
- package/dist/esm/jsonschema.js +135 -0
- package/dist/esm/jsonschema.js.map +7 -0
- package/dist/esm/retry.js +110 -35
- package/dist/esm/retry.js.map +3 -3
- package/dist/esm/types.js +8 -15
- package/dist/esm/types.js.map +2 -2
- package/dist/types/BaseEvent.d.ts +53 -28
- package/dist/types/events_suck.d.ts +8 -15
- package/dist/types/jsonschema.d.ts +6 -0
- package/dist/types/retry.d.ts +2 -0
- package/dist/types/types.d.ts +6 -10
- package/package.json +1 -1
- package/src/BaseEvent.ts +321 -80
- package/src/LockManager.ts +1 -1
- package/src/events_suck.ts +20 -22
- package/src/jsonschema.ts +146 -0
- package/src/retry.ts +132 -38
- package/src/types.ts +10 -19
package/dist/esm/retry.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/retry.ts"],
|
|
4
|
-
"sourcesContent": ["import { createAsyncLocalStorage, type AsyncLocalStorageLike } from './async_context.js'\nimport { isNodeRuntime } from './optional_deps.js'\n\ntype SemaphoreScope = 'multiprocess' | 'global' | 'class' | 'instance'\n\ntype MultiprocessLockHandle = {\n release: () => Promise<void>\n}\n\ntype SyncMultiprocessLockHandle = {\n release: () => void\n}\n\ntype AnyFunction = (this: any, ...args: any[]) => any\ntype LegacyMethodDescriptor = TypedPropertyDescriptor<AnyFunction>\ntype RetryDecorator = {\n <T extends AnyFunction>(target: T): T\n <T extends AnyFunction>(target: T, context: ClassMethodDecoratorContext): T\n (target: object, property_key: string | symbol, descriptor: LegacyMethodDescriptor): LegacyMethodDescriptor\n}\n\nconst MULTIPROCESS_SEMAPHORE_DIRNAME = 'browser_use_semaphores'\nconst MULTIPROCESS_STALE_LOCK_MS = 5 * 60 * 1000\n\nlet multiprocess_fallback_reason_logged: string | null = null\n\n// \u2500\u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface RetryOptions {\n /** Total number of attempts including the initial call (1 = no retry, 3 = up to 2 retries). Default: 1 */\n max_attempts?: number\n\n /** Seconds to wait between retries. Default: 0 */\n retry_after?: number\n\n /** Multiplier applied to retry_after after each attempt for exponential backoff. Default: 1.0 (constant delay) */\n retry_backoff_factor?: number\n\n /** Only retry when the thrown error matches one of these matchers. Accepts error class constructors,\n * string error names (matched against error.name), or RegExp patterns (tested against String(error)).\n * Default: undefined (retry on any error) */\n retry_on_errors?: Array<(new (...args: any[]) => Error) | string | RegExp>\n\n /** Per-attempt timeout in seconds. Default: undefined (no per-attempt timeout) */\n timeout?: number | null\n\n /** Maximum concurrent executions sharing this semaphore. Default: undefined (no concurrency limit) */\n semaphore_limit?: number | null\n\n /** Semaphore identifier. Functions with the same name share the same concurrency slot pool. Default: function name.\n * If a function is provided, it receives the same arguments as the wrapped function. */\n semaphore_name?: string | ((...args: any[]) => string) | null\n\n /** If true, proceed without concurrency limit when semaphore acquisition times out. Default: true */\n semaphore_lax?: boolean\n\n /** Semaphore scoping strategy. Default: 'global'\n * - 'multiprocess': all processes on the machine share one semaphore (Node.js only)\n * - 'global': all calls share one semaphore (keyed by semaphore_name)\n * - 'class': all instances of the same class share one semaphore (keyed by className.semaphore_name)\n * - 'instance': each object instance gets its own semaphore (keyed by instanceId.semaphore_name)\n * 'class' and 'instance' require `this` to be an object; they fall back to 'global' for standalone calls. */\n semaphore_scope?: SemaphoreScope\n\n /** Maximum seconds to wait for semaphore acquisition. Default: undefined \u2192 timeout * max(1, limit - 1) */\n semaphore_timeout?: number | null\n}\n\n// \u2500\u2500\u2500 Errors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Thrown when a single attempt exceeds the per-attempt timeout. */\nexport class RetryTimeoutError extends Error {\n timeout_seconds: number\n attempt: number\n\n constructor(message: string, params: { timeout_seconds: number; attempt: number }) {\n super(message)\n this.name = 'RetryTimeoutError'\n this.timeout_seconds = params.timeout_seconds\n this.attempt = params.attempt\n }\n}\n\n/** Thrown (when semaphore_lax=false) if the semaphore cannot be acquired within the timeout. */\nexport class SemaphoreTimeoutError extends Error {\n semaphore_name: string\n semaphore_limit: number\n timeout_seconds: number\n\n constructor(message: string, params: { semaphore_name: string; semaphore_limit: number; timeout_seconds: number }) {\n super(message)\n this.name = 'SemaphoreTimeoutError'\n this.semaphore_name = params.semaphore_name\n this.semaphore_limit = params.semaphore_limit\n this.timeout_seconds = params.timeout_seconds\n }\n}\n\n// \u2500\u2500\u2500 Re-entrancy tracking via AsyncLocalStorage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Prevents deadlocks when a retry()-wrapped function calls another retry()-wrapped\n// function that shares the same semaphore (or calls itself recursively).\n//\n// Each async call stack tracks which semaphore names it currently holds. When a\n// nested call encounters a semaphore it already holds, it skips acquisition and\n// runs directly within the parent's slot.\n//\n// Uses the same AsyncLocalStorage polyfill as the rest of abxbus (see async_context.ts)\n// so it works in Node.js and gracefully degrades to a no-op in browsers.\n\ntype ReentrantStore = Set<string>\n\n// Separate AsyncLocalStorage instance for retry re-entrancy tracking.\n// Created via the shared factory in async_context.ts (returns null in browsers).\nconst retry_context_storage: AsyncLocalStorageLike | null = createAsyncLocalStorage()\n\nfunction getHeldSemaphores(): ReentrantStore {\n return (retry_context_storage?.getStore() as ReentrantStore | undefined) ?? new Set()\n}\n\nfunction runWithHeldSemaphores<T>(held: ReentrantStore, fn: () => T): T {\n if (!retry_context_storage) return fn()\n return retry_context_storage.run(held, fn)\n}\n\n// \u2500\u2500\u2500 Semaphore scope helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nlet _next_instance_id = 1\nconst _instance_ids = new WeakMap<object, number>()\n\nfunction scopedSemaphoreKey(base_name: string, scope: SemaphoreScope, context: unknown): string {\n if (scope === 'class' && context && typeof context === 'object') {\n return `${(context as object).constructor?.name ?? 'Object'}.${base_name}`\n }\n if (scope === 'instance' && context && typeof context === 'object') {\n let id = _instance_ids.get(context as object)\n if (id === undefined) {\n id = _next_instance_id++\n _instance_ids.set(context as object, id)\n }\n return `${id}.${base_name}`\n }\n return base_name\n}\n\n// \u2500\u2500\u2500 Global semaphore registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass RetrySemaphore {\n readonly size: number\n private inUse: number\n private waiters: Array<() => void>\n\n constructor(size: number) {\n this.size = size\n this.inUse = 0\n this.waiters = []\n }\n\n tryAcquire(): boolean {\n if (this.size === Infinity) {\n return true\n }\n if (this.inUse < this.size) {\n this.inUse += 1\n return true\n }\n return false\n }\n\n async acquire(): Promise<void> {\n if (this.tryAcquire()) {\n return\n }\n await new Promise<void>((resolve) => {\n this.waiters.push(resolve)\n })\n }\n\n release(): void {\n if (this.size === Infinity) {\n return\n }\n const next = this.waiters.shift()\n if (next) {\n // Handoff: keep the permit accounted for and transfer it directly to the waiter.\n next()\n return\n }\n this.inUse = Math.max(0, this.inUse - 1)\n }\n}\n\nconst SEMAPHORE_REGISTRY = new Map<string, RetrySemaphore>()\n\nfunction getOrCreateSemaphore(name: string, limit: number): RetrySemaphore {\n const existing = SEMAPHORE_REGISTRY.get(name)\n if (existing && existing.size === limit) return existing\n const sem = new RetrySemaphore(limit)\n SEMAPHORE_REGISTRY.set(name, sem)\n return sem\n}\n\n/** Reset the global semaphore registry. Useful in tests. */\nexport function clearSemaphoreRegistry(): void {\n SEMAPHORE_REGISTRY.clear()\n multiprocess_fallback_reason_logged = null\n}\n\n// \u2500\u2500\u2500 retry() decorator / higher-order wrapper \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Usage as a higher-order function (works on async and sync functions):\n//\n// const fetchWithRetry = retry({ max_attempts: 3, retry_after: 1 })(async (url: string) => {\n// return await fetch(url)\n// })\n//\n// const readWithRetry = retry({ max_attempts: 3, retry_after: 1 })((path: string) => {\n// return readFileSync(path, 'utf8')\n// })\n//\n// Usage as a TC39 Stage 3 or legacy experimental decorator on class methods:\n//\n// class ApiClient {\n// @retry({ max_attempts: 3, retry_after: 1 })\n// async fetchData(): Promise<Data> { ... }\n// }\n//\n// Usage on event bus handlers:\n//\n// bus.on(MyEvent, retry({ max_attempts: 3 })(async (event) => {\n// await riskyOperation(event.data)\n// }))\n\nexport function retry(options: RetryOptions = {}): RetryDecorator {\n const {\n max_attempts = 1,\n retry_after = 0,\n retry_backoff_factor = 1.0,\n retry_on_errors,\n timeout,\n semaphore_limit,\n semaphore_name: semaphore_name_option,\n semaphore_lax = true,\n semaphore_scope = 'global',\n semaphore_timeout,\n } = options\n\n const decorateFunction = <T extends AnyFunction>(target: T, _context?: ClassMethodDecoratorContext): T => {\n const fn_name = target.name || (_context?.name as string) || 'anonymous'\n const effective_max_attempts = Math.max(1, max_attempts)\n const effective_retry_after = Math.max(0, retry_after)\n\n const shouldRetry = (error: unknown): boolean => {\n if (!retry_on_errors || retry_on_errors.length === 0) return true\n return retry_on_errors.some((matcher) =>\n typeof matcher === 'string'\n ? (error as Error)?.name === matcher\n : matcher instanceof RegExp\n ? matcher.test(String(error))\n : error instanceof matcher\n )\n }\n\n const asyncRetryDelay = async (attempt: number): Promise<void> => {\n const delay_seconds = effective_retry_after * Math.pow(retry_backoff_factor, attempt - 1)\n if (delay_seconds > 0) {\n await sleep(delay_seconds * 1000)\n }\n }\n\n const syncRetryDelay = (attempt: number): void => {\n const delay_seconds = effective_retry_after * Math.pow(retry_backoff_factor, attempt - 1)\n if (delay_seconds > 0) {\n sleepSync(delay_seconds * 1000)\n }\n }\n\n const runRetryLoopFromThenable = async (\n this_arg: any,\n args: any[],\n first_thenable: PromiseLike<any>,\n first_attempt: number\n ): Promise<any> => {\n let current_result: any = first_thenable\n for (let attempt = first_attempt; attempt <= effective_max_attempts; attempt++) {\n try {\n if (attempt !== first_attempt) {\n current_result = target.apply(this_arg, args)\n }\n if (isThenable(current_result)) {\n if (timeout != null && timeout > 0) {\n return await _runWithTimeout(() => Promise.resolve(current_result), timeout * 1000, attempt)\n }\n return await current_result\n }\n return current_result\n } catch (error) {\n if (!shouldRetry(error)) throw error\n if (attempt >= effective_max_attempts) throw error\n await asyncRetryDelay(attempt)\n }\n }\n throw new Error(`retry(${fn_name}): unexpected end of retry loop`)\n }\n\n async function asyncRetryWrapper(this: any, ...args: any[]): Promise<any> {\n const base_name = typeof semaphore_name_option === 'function' ? semaphore_name_option(...args) : (semaphore_name_option ?? fn_name)\n const sem_name = typeof base_name === 'string' ? base_name : String(base_name)\n // \u2500\u2500 Resolve scoped semaphore key at call time (uses `this` for class/instance scopes) \u2500\u2500\n const scoped_key = scopedSemaphoreKey(sem_name, semaphore_scope, this)\n\n // \u2500\u2500 Check re-entrancy: skip semaphore if we already hold it in this async context \u2500\u2500\n const held = getHeldSemaphores()\n const needs_semaphore = semaphore_limit != null && semaphore_limit > 0\n const is_reentrant = needs_semaphore && held.has(scoped_key)\n\n // \u2500\u2500 Semaphore acquisition (held across all retry attempts, skipped if re-entrant) \u2500\u2500\n let semaphore: RetrySemaphore | null = null\n let multiprocess_lock: MultiprocessLockHandle | null = null\n let semaphore_acquired = false\n\n if (needs_semaphore && !is_reentrant) {\n const effective_sem_timeout =\n semaphore_timeout != null ? semaphore_timeout : timeout != null ? timeout * Math.max(1, semaphore_limit! - 1) : null\n\n if (semaphore_scope === 'multiprocess') {\n if (isNodeRuntime()) {\n multiprocess_lock = await acquireMultiprocessSemaphore(scoped_key, semaphore_limit!, effective_sem_timeout, semaphore_lax)\n semaphore_acquired = multiprocess_lock !== null\n } else {\n logMultiprocessFallbackOnce('multiprocess semaphores require a Node.js runtime; falling back to in-process global scope')\n semaphore = getOrCreateSemaphore(scoped_key, semaphore_limit!)\n if (effective_sem_timeout != null && effective_sem_timeout > 0) {\n semaphore_acquired = await acquireWithTimeout(semaphore, effective_sem_timeout * 1000)\n if (!semaphore_acquired) {\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(\n `Failed to acquire semaphore \"${scoped_key}\" within ${effective_sem_timeout}s (limit=${semaphore_limit})`,\n { semaphore_name: scoped_key, semaphore_limit: semaphore_limit!, timeout_seconds: effective_sem_timeout }\n )\n }\n }\n } else {\n await semaphore.acquire()\n semaphore_acquired = true\n }\n }\n } else {\n semaphore = getOrCreateSemaphore(scoped_key, semaphore_limit!)\n\n if (effective_sem_timeout != null && effective_sem_timeout > 0) {\n semaphore_acquired = await acquireWithTimeout(semaphore, effective_sem_timeout * 1000)\n if (!semaphore_acquired) {\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(\n `Failed to acquire semaphore \"${scoped_key}\" within ${effective_sem_timeout}s (limit=${semaphore_limit})`,\n { semaphore_name: scoped_key, semaphore_limit: semaphore_limit!, timeout_seconds: effective_sem_timeout }\n )\n }\n }\n } else {\n await semaphore.acquire()\n semaphore_acquired = true\n }\n }\n }\n\n // \u2500\u2500 Build the set of held semaphores for nested calls \u2500\u2500\n const new_held = new Set(held)\n if (semaphore_acquired) {\n new_held.add(scoped_key)\n }\n\n // \u2500\u2500 Retry loop (runs inside the semaphore and re-entrancy context) \u2500\u2500\n const runRetryLoop = async (): Promise<any> => {\n for (let attempt = 1; attempt <= effective_max_attempts; attempt++) {\n try {\n if (timeout != null && timeout > 0) {\n return await _runWithTimeout(() => Promise.resolve(target.apply(this, args)), timeout * 1000, attempt)\n } else {\n return await Promise.resolve(target.apply(this, args))\n }\n } catch (error) {\n if (!shouldRetry(error)) throw error\n\n // Last attempt: rethrow\n if (attempt >= effective_max_attempts) throw error\n\n // Wait before next attempt with exponential backoff\n await asyncRetryDelay(attempt)\n }\n }\n\n // Unreachable, but satisfies the type checker\n throw new Error(`retry(${fn_name}): unexpected end of retry loop`)\n }\n\n try {\n return await runWithHeldSemaphores(new_held, runRetryLoop)\n } finally {\n if (semaphore_acquired && multiprocess_lock) {\n await multiprocess_lock.release()\n } else if (semaphore_acquired && semaphore) {\n semaphore.release()\n }\n }\n }\n\n function syncRetryWrapper(this: any, ...args: any[]): any {\n const base_name = typeof semaphore_name_option === 'function' ? semaphore_name_option(...args) : (semaphore_name_option ?? fn_name)\n const sem_name = typeof base_name === 'string' ? base_name : String(base_name)\n const scoped_key = scopedSemaphoreKey(sem_name, semaphore_scope, this)\n\n const held = getHeldSemaphores()\n const needs_semaphore = semaphore_limit != null && semaphore_limit > 0\n const is_reentrant = needs_semaphore && held.has(scoped_key)\n\n let semaphore: RetrySemaphore | null = null\n let multiprocess_lock: SyncMultiprocessLockHandle | null = null\n let semaphore_acquired = false\n\n if (needs_semaphore && !is_reentrant) {\n const effective_sem_timeout =\n semaphore_timeout != null ? semaphore_timeout : timeout != null ? timeout * Math.max(1, semaphore_limit! - 1) : null\n\n if (semaphore_scope === 'multiprocess') {\n if (isNodeRuntime()) {\n multiprocess_lock = acquireMultiprocessSemaphoreSync(scoped_key, semaphore_limit!, effective_sem_timeout, semaphore_lax)\n semaphore_acquired = multiprocess_lock !== null\n } else {\n logMultiprocessFallbackOnce('multiprocess semaphores require a Node.js runtime; falling back to in-process global scope')\n semaphore = getOrCreateSemaphore(scoped_key, semaphore_limit!)\n semaphore_acquired = acquireSemaphoreSyncOrThrow(semaphore, scoped_key, semaphore_limit!, effective_sem_timeout, semaphore_lax)\n }\n } else {\n semaphore = getOrCreateSemaphore(scoped_key, semaphore_limit!)\n semaphore_acquired = acquireSemaphoreSyncOrThrow(semaphore, scoped_key, semaphore_limit!, effective_sem_timeout, semaphore_lax)\n }\n }\n\n const new_held = new Set(held)\n if (semaphore_acquired) {\n new_held.add(scoped_key)\n }\n\n const release = (): void => {\n if (semaphore_acquired && multiprocess_lock) {\n multiprocess_lock.release()\n } else if (semaphore_acquired && semaphore) {\n semaphore.release()\n }\n }\n\n const runRetryLoop = (): any => {\n for (let attempt = 1; attempt <= effective_max_attempts; attempt++) {\n const attempt_started_at = Date.now()\n try {\n const result = target.apply(this, args)\n if (isThenable(result)) {\n return runRetryLoopFromThenable(this, args, result, attempt)\n }\n if (timeout != null && timeout > 0 && Date.now() - attempt_started_at > timeout * 1000) {\n throw new RetryTimeoutError(`Timed out after ${timeout}s (attempt ${attempt})`, {\n timeout_seconds: timeout,\n attempt,\n })\n }\n return result\n } catch (error) {\n if (!shouldRetry(error)) throw error\n if (attempt >= effective_max_attempts) throw error\n syncRetryDelay(attempt)\n }\n }\n throw new Error(`retry(${fn_name}): unexpected end of retry loop`)\n }\n\n try {\n const result = runWithHeldSemaphores(new_held, runRetryLoop)\n if (isThenable(result)) {\n return Promise.resolve(result).finally(release)\n }\n release()\n return result\n } catch (error) {\n release()\n throw error\n }\n }\n\n const retryWrapper = isAsyncFunction(target) ? asyncRetryWrapper : syncRetryWrapper\n Object.defineProperty(retryWrapper, 'name', { value: fn_name, configurable: true })\n if (_context?.kind === 'method' && typeof _context.addInitializer === 'function') {\n _context.addInitializer(function (this: unknown) {\n const owner_name = findDecoratedMethodOwnerName(this, _context, retryWrapper)\n if (owner_name) {\n Object.defineProperty(retryWrapper, 'name', { value: `${owner_name}.${fn_name}`, configurable: true })\n }\n })\n }\n return retryWrapper as unknown as T\n }\n\n function decorator<T extends AnyFunction>(\n target: T | object,\n context_or_property_key?: ClassMethodDecoratorContext | string | symbol,\n descriptor?: LegacyMethodDescriptor\n ): T | LegacyMethodDescriptor {\n if (descriptor?.value && typeof descriptor.value === 'function') {\n descriptor.value = decorateFunction(descriptor.value)\n return descriptor\n }\n if (typeof target === 'function') {\n return decorateFunction(target as T, typeof context_or_property_key === 'object' ? context_or_property_key : undefined)\n }\n throw new TypeError('retry() can only decorate functions and class methods')\n }\n return decorator as RetryDecorator\n}\n\n// \u2500\u2500\u2500 Internal helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction findDecoratedMethodOwnerName(\n context_this: unknown,\n context: ClassMethodDecoratorContext,\n replacement: (...args: any[]) => any\n): string | null {\n const method_name = context.name\n if (typeof method_name !== 'string') {\n return null\n }\n\n if (context.static) {\n let ctor = typeof context_this === 'function' ? context_this : null\n while (ctor && ctor !== Function.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(ctor, method_name)\n if (descriptor?.value === replacement) {\n return ctor.name || null\n }\n const parent = Object.getPrototypeOf(ctor)\n ctor = typeof parent === 'function' ? parent : null\n }\n return null\n }\n\n if ((typeof context_this !== 'object' && typeof context_this !== 'function') || context_this === null) {\n return null\n }\n\n let prototype = Object.getPrototypeOf(context_this)\n while (prototype && prototype !== Object.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, method_name)\n if (descriptor?.value === replacement) {\n const ctor_name = (prototype as { constructor?: { name?: string } }).constructor?.name\n return ctor_name || null\n }\n prototype = Object.getPrototypeOf(prototype)\n }\n return null\n}\n\nfunction isAsyncFunction(fn: AnyFunction): boolean {\n return Object.prototype.toString.call(fn) === '[object AsyncFunction]'\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') && value !== null && typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\n/**\n * Try to acquire a semaphore within a timeout. Returns true if acquired, false if timed out.\n * If the semaphore is acquired after the timeout (due to the waiter remaining queued),\n * it is immediately released to avoid leaking slots.\n */\nasync function acquireWithTimeout(semaphore: RetrySemaphore, timeout_ms: number): Promise<boolean> {\n return new Promise<boolean>((resolve) => {\n let settled = false\n\n const timer = setTimeout(() => {\n if (!settled) {\n settled = true\n resolve(false)\n }\n }, timeout_ms)\n\n semaphore.acquire().then(() => {\n if (!settled) {\n settled = true\n clearTimeout(timer)\n resolve(true)\n } else {\n // Acquired after timeout fired \u2014 release immediately to avoid slot leak\n semaphore.release()\n }\n })\n })\n}\n\nfunction acquireSemaphoreSyncOrThrow(\n semaphore: RetrySemaphore,\n scoped_key: string,\n semaphore_limit: number,\n timeout_seconds: number | null,\n semaphore_lax: boolean\n): boolean {\n const acquired = acquireSemaphoreSync(semaphore, timeout_seconds == null ? null : timeout_seconds * 1000)\n if (acquired) return true\n\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(`Failed to acquire semaphore \"${scoped_key}\" within ${timeout_seconds}s (limit=${semaphore_limit})`, {\n semaphore_name: scoped_key,\n semaphore_limit,\n timeout_seconds: timeout_seconds ?? 0,\n })\n }\n return false\n}\n\nfunction acquireSemaphoreSync(semaphore: RetrySemaphore, timeout_ms: number | null): boolean {\n if (semaphore.tryAcquire()) return true\n\n const start = Date.now()\n while (true) {\n if (timeout_ms != null && timeout_ms > 0 && Date.now() - start >= timeout_ms) {\n return false\n }\n sleepSync(10)\n if (semaphore.tryAcquire()) return true\n }\n}\n\nfunction logMultiprocessFallbackOnce(reason: string): void {\n if (multiprocess_fallback_reason_logged === reason) return\n multiprocess_fallback_reason_logged = reason\n console.warn(`[abxbus.retry] ${reason}`)\n}\n\nfunction importNodeModuleSync(specifier: string): any {\n const maybe_process = (\n globalThis as {\n process?: { getBuiltinModule?: (name: string) => any }\n }\n ).process\n const get_builtin_module = maybe_process?.getBuiltinModule\n const bare_specifier = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier\n\n if (typeof get_builtin_module === 'function') {\n const builtin = get_builtin_module(bare_specifier) ?? get_builtin_module(specifier)\n if (builtin) return builtin\n }\n\n let require_fn: ((name: string) => any) | undefined\n try {\n require_fn = Function('return typeof require === \"function\" ? require : undefined')() as ((name: string) => any) | undefined\n } catch {\n require_fn = undefined\n }\n if (require_fn) return require_fn(specifier)\n\n throw new Error('[abxbus.retry] synchronous Node.js module loading is unavailable; cannot use sync multiprocess semaphores')\n}\n\nasync function importNodeModule(specifier: string): Promise<any> {\n const dynamic_import = Function('module_name', 'return import(module_name)') as (module_name: string) => Promise<unknown>\n return dynamic_import(specifier) as Promise<any>\n}\n\nasync function acquireMultiprocessSemaphore(\n scoped_key: string,\n semaphore_limit: number,\n semaphore_timeout_seconds: number | null,\n semaphore_lax: boolean\n): Promise<MultiprocessLockHandle | null> {\n const [crypto, fs, os, path] = await Promise.all([\n importNodeModule('node:crypto'),\n importNodeModule('node:fs'),\n importNodeModule('node:os'),\n importNodeModule('node:path'),\n ])\n const semaphore_directory = path.join(os.tmpdir(), MULTIPROCESS_SEMAPHORE_DIRNAME)\n const lock_prefix = crypto.createHash('sha256').update(scoped_key).digest('hex').slice(0, 40)\n fs.mkdirSync(semaphore_directory, { recursive: true })\n\n const start = Date.now()\n let retry_delay_ms = 100\n\n while (true) {\n const elapsed_ms = Date.now() - start\n const remaining_ms =\n semaphore_timeout_seconds != null && semaphore_timeout_seconds > 0 ? semaphore_timeout_seconds * 1000 - elapsed_ms : null\n\n if (remaining_ms != null && remaining_ms <= 0) {\n break\n }\n\n for (let slot = 0; slot < semaphore_limit; slot++) {\n const slot_file = path.join(semaphore_directory, `${lock_prefix}.${String(slot).padStart(2, '0')}.lock`)\n const token = `${process.pid}:${Date.now()}:${Math.random().toString(16).slice(2)}`\n\n try {\n const fd = fs.openSync(slot_file, 'wx', 0o600)\n try {\n fs.writeFileSync(\n fd,\n JSON.stringify({\n token,\n pid: process.pid,\n semaphore_name: scoped_key,\n created_at_ms: Date.now(),\n }),\n 'utf8'\n )\n } finally {\n fs.closeSync(fd)\n }\n return {\n release: async () => {\n try {\n const raw = String(fs.readFileSync(slot_file, 'utf8') || '').trim()\n const current_owner = raw ? (JSON.parse(raw) as { token?: unknown }) : null\n if (current_owner?.token === token) {\n fs.unlinkSync(slot_file)\n }\n } catch {}\n },\n }\n } catch (error) {\n if (!(error instanceof Error) || (error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error\n }\n\n try {\n const raw = String(fs.readFileSync(slot_file, 'utf8') || '').trim()\n const current_owner = raw ? (JSON.parse(raw) as { pid?: unknown }) : null\n const current_pid = typeof current_owner?.pid === 'number' ? current_owner.pid : null\n if (current_pid != null) {\n try {\n process.kill(current_pid, 0)\n continue\n } catch {}\n }\n\n const slot_age_ms = Date.now() - fs.statSync(slot_file).mtimeMs\n if (current_pid != null || slot_age_ms >= MULTIPROCESS_STALE_LOCK_MS) {\n fs.unlinkSync(slot_file)\n }\n } catch {}\n }\n }\n\n const sleep_ms = Math.min(retry_delay_ms, remaining_ms ?? retry_delay_ms)\n if (sleep_ms > 0) {\n await sleep(sleep_ms)\n }\n retry_delay_ms = Math.min(retry_delay_ms * 2, 1000)\n }\n\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(\n `Failed to acquire semaphore \"${scoped_key}\" within ${semaphore_timeout_seconds}s (limit=${semaphore_limit})`,\n { semaphore_name: scoped_key, semaphore_limit, timeout_seconds: semaphore_timeout_seconds ?? 0 }\n )\n }\n\n return null\n}\n\nfunction acquireMultiprocessSemaphoreSync(\n scoped_key: string,\n semaphore_limit: number,\n semaphore_timeout_seconds: number | null,\n semaphore_lax: boolean\n): SyncMultiprocessLockHandle | null {\n const crypto = importNodeModuleSync('node:crypto')\n const fs = importNodeModuleSync('node:fs')\n const os = importNodeModuleSync('node:os')\n const path = importNodeModuleSync('node:path')\n const semaphore_directory = path.join(os.tmpdir(), MULTIPROCESS_SEMAPHORE_DIRNAME)\n const lock_prefix = crypto.createHash('sha256').update(scoped_key).digest('hex').slice(0, 40)\n fs.mkdirSync(semaphore_directory, { recursive: true })\n\n const start = Date.now()\n let retry_delay_ms = 100\n\n while (true) {\n const elapsed_ms = Date.now() - start\n const remaining_ms =\n semaphore_timeout_seconds != null && semaphore_timeout_seconds > 0 ? semaphore_timeout_seconds * 1000 - elapsed_ms : null\n\n if (remaining_ms != null && remaining_ms <= 0) {\n break\n }\n\n for (let slot = 0; slot < semaphore_limit; slot++) {\n const slot_file = path.join(semaphore_directory, `${lock_prefix}.${String(slot).padStart(2, '0')}.lock`)\n const token = `${process.pid}:${Date.now()}:${Math.random().toString(16).slice(2)}`\n\n try {\n const fd = fs.openSync(slot_file, 'wx', 0o600)\n try {\n fs.writeFileSync(\n fd,\n JSON.stringify({\n token,\n pid: process.pid,\n semaphore_name: scoped_key,\n created_at_ms: Date.now(),\n }),\n 'utf8'\n )\n } finally {\n fs.closeSync(fd)\n }\n return {\n release: () => {\n try {\n const raw = String(fs.readFileSync(slot_file, 'utf8') || '').trim()\n const current_owner = raw ? (JSON.parse(raw) as { token?: unknown }) : null\n if (current_owner?.token === token) {\n fs.unlinkSync(slot_file)\n }\n } catch {}\n },\n }\n } catch (error) {\n if (!(error instanceof Error) || (error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error\n }\n\n try {\n const raw = String(fs.readFileSync(slot_file, 'utf8') || '').trim()\n const current_owner = raw ? (JSON.parse(raw) as { pid?: unknown }) : null\n const current_pid = typeof current_owner?.pid === 'number' ? current_owner.pid : null\n if (current_pid != null) {\n try {\n process.kill(current_pid, 0)\n continue\n } catch {}\n }\n\n const slot_age_ms = Date.now() - fs.statSync(slot_file).mtimeMs\n if (current_pid != null || slot_age_ms >= MULTIPROCESS_STALE_LOCK_MS) {\n fs.unlinkSync(slot_file)\n }\n } catch {}\n }\n }\n\n const sleep_ms = Math.min(retry_delay_ms, remaining_ms ?? retry_delay_ms)\n if (sleep_ms > 0) {\n sleepSync(sleep_ms)\n }\n retry_delay_ms = Math.min(retry_delay_ms * 2, 1000)\n }\n\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(\n `Failed to acquire semaphore \"${scoped_key}\" within ${semaphore_timeout_seconds}s (limit=${semaphore_limit})`,\n { semaphore_name: scoped_key, semaphore_limit, timeout_seconds: semaphore_timeout_seconds ?? 0 }\n )\n }\n\n return null\n}\n\n/** Run fn() with a timeout. Rejects with RetryTimeoutError if the timeout fires first. */\nasync function _runWithTimeout<T>(fn: () => Promise<T>, timeout_ms: number, attempt: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let settled = false\n\n const timer = setTimeout(() => {\n if (!settled) {\n settled = true\n reject(\n new RetryTimeoutError(`Timed out after ${timeout_ms / 1000}s (attempt ${attempt})`, {\n timeout_seconds: timeout_ms / 1000,\n attempt,\n })\n )\n }\n }, timeout_ms)\n\n fn().then(\n (value) => {\n if (!settled) {\n settled = true\n clearTimeout(timer)\n resolve(value)\n }\n },\n (error) => {\n if (!settled) {\n settled = true\n clearTimeout(timer)\n reject(error)\n }\n }\n )\n })\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction sleepSync(ms: number): void {\n if (ms <= 0) return\n\n const shared_array_buffer = (globalThis as { SharedArrayBuffer?: typeof SharedArrayBuffer }).SharedArrayBuffer\n const atomics = (globalThis as { Atomics?: typeof Atomics }).Atomics\n if (typeof shared_array_buffer === 'function' && typeof atomics?.wait === 'function') {\n try {\n const buffer = new shared_array_buffer(4)\n const view = new Int32Array(buffer)\n atomics.wait(view, 0, 0, ms)\n return\n } catch {}\n }\n\n const deadline = Date.now() + ms\n while (Date.now() < deadline) {}\n}\n"],
|
|
5
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;AAClB,iBAAO,KAAK;AAAA,QACd;AAAA,MACF;AAAA,IACF;AAAA,EACF,CAAC;AACH;AAEA,SAAS,MAAM,IAA2B;AACxC,SAAO,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,EAAE,CAAC;AACzD;AAEA,SAAS,UAAU,IAAkB;AACnC,MAAI,MAAM,EAAG;AAEb,QAAM,sBAAuB,WAAgE;AAC7F,QAAM,UAAW,WAA4C;AAC7D,MAAI,OAAO,wBAAwB,cAAc,OAAO,SAAS,SAAS,YAAY;AACpF,QAAI;AACF,YAAM,SAAS,IAAI,oBAAoB,CAAC;AACxC,YAAM,OAAO,IAAI,WAAW,MAAM;AAClC,cAAQ,KAAK,MAAM,GAAG,GAAG,EAAE;AAC3B;AAAA,IACF,QAAQ;AAAA,IAAC;AAAA,EACX;AAEA,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,SAAO,KAAK,IAAI,IAAI,UAAU;AAAA,EAAC;AACjC;",
|
|
6
|
-
"names": []
|
|
4
|
+
"sourcesContent": ["import { createAsyncLocalStorage, type AsyncLocalStorageLike } from './async_context.js'\nimport { isNodeRuntime } from './optional_deps.js'\n\ntype SemaphoreScope = 'multiprocess' | 'global' | 'class' | 'instance'\n\ntype MultiprocessLockHandle = {\n release: () => Promise<void>\n}\n\ntype SyncMultiprocessLockHandle = {\n release: () => void\n}\n\ntype AnyFunction = (this: any, ...args: any[]) => any\ntype LegacyMethodDescriptor = TypedPropertyDescriptor<AnyFunction>\ntype RetryDecorator = {\n <T extends AnyFunction>(target: T): T\n <T extends AnyFunction>(target: T, context: ClassMethodDecoratorContext): T\n (target: object, property_key: string | symbol, descriptor: LegacyMethodDescriptor): LegacyMethodDescriptor\n}\n\nconst MULTIPROCESS_SEMAPHORE_DIRNAME = 'browser_use_semaphores'\nconst MULTIPROCESS_STALE_LOCK_MS = 5 * 60 * 1000\nconst RETRY_SLOW_WARNING_THROTTLE_MS = 2000\nconst RETRY_SLOW_WARNING_ARGS_MAX_LENGTH = 80\n\nlet multiprocess_fallback_reason_logged: string | null = null\n\n// \u2500\u2500\u2500 Types \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nexport interface RetryOptions {\n /** Total number of attempts including the initial call (1 = no retry, 3 = up to 2 retries). Default: 1 */\n max_attempts?: number\n\n /** Seconds to wait between retries. Default: 0 */\n retry_after?: number\n\n /** Multiplier applied to retry_after after each attempt for exponential backoff. Default: 1.0 (constant delay) */\n retry_backoff_factor?: number\n\n /** Only retry when the thrown error matches one of these matchers. Accepts error class constructors,\n * string error names (matched against error.name), or RegExp patterns (tested against String(error)).\n * Default: undefined (retry on any error) */\n retry_on_errors?: Array<(new (...args: any[]) => Error) | string | RegExp>\n\n /** Per-attempt timeout in seconds. Default: undefined (no per-attempt timeout) */\n timeout?: number | null\n\n /** Emit a warning when a decorated call exceeds this many seconds. Default: undefined (disabled) */\n slow_timeout?: number | null\n\n /** Maximum concurrent executions sharing this semaphore. Default: undefined (no concurrency limit) */\n semaphore_limit?: number | null\n\n /** Semaphore identifier. Functions with the same name share the same concurrency slot pool. Default: function name.\n * If a function is provided, it receives the same arguments as the wrapped function. */\n semaphore_name?: string | ((...args: any[]) => string) | null\n\n /** If true, proceed without concurrency limit when semaphore acquisition times out. Default: true */\n semaphore_lax?: boolean\n\n /** Semaphore scoping strategy. Default: 'global'\n * - 'multiprocess': all processes on the machine share one semaphore (Node.js only)\n * - 'global': all calls share one semaphore (keyed by semaphore_name)\n * - 'class': all instances of the same class share one semaphore (keyed by className.semaphore_name)\n * - 'instance': each object instance gets its own semaphore (keyed by instanceId.semaphore_name)\n * 'class' and 'instance' require `this` to be an object; they fall back to 'global' for standalone calls. */\n semaphore_scope?: SemaphoreScope\n\n /** Maximum seconds to wait for semaphore acquisition. Default: undefined \u2192 timeout * max(1, limit - 1) */\n semaphore_timeout?: number | null\n}\n\n// \u2500\u2500\u2500 Errors \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\n/** Thrown when a single attempt exceeds the per-attempt timeout. */\nexport class RetryTimeoutError extends Error {\n timeout_seconds: number\n attempt: number\n\n constructor(message: string, params: { timeout_seconds: number; attempt: number }) {\n super(message)\n this.name = 'RetryTimeoutError'\n this.timeout_seconds = params.timeout_seconds\n this.attempt = params.attempt\n }\n}\n\n/** Thrown (when semaphore_lax=false) if the semaphore cannot be acquired within the timeout. */\nexport class SemaphoreTimeoutError extends Error {\n semaphore_name: string\n semaphore_limit: number\n timeout_seconds: number\n\n constructor(message: string, params: { semaphore_name: string; semaphore_limit: number; timeout_seconds: number }) {\n super(message)\n this.name = 'SemaphoreTimeoutError'\n this.semaphore_name = params.semaphore_name\n this.semaphore_limit = params.semaphore_limit\n this.timeout_seconds = params.timeout_seconds\n }\n}\n\n// \u2500\u2500\u2500 Re-entrancy tracking via AsyncLocalStorage \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Prevents deadlocks when a retry()-wrapped function calls another retry()-wrapped\n// function that shares the same semaphore (or calls itself recursively).\n//\n// Each async call stack tracks which semaphore names it currently holds. When a\n// nested call encounters a semaphore it already holds, it skips acquisition and\n// runs directly within the parent's slot.\n//\n// Uses the same AsyncLocalStorage polyfill as the rest of abxbus (see async_context.ts)\n// so it works in Node.js and gracefully degrades to a no-op in browsers.\n\ntype ReentrantStore = Set<string>\n\n// Separate AsyncLocalStorage instance for retry re-entrancy tracking.\n// Created via the shared factory in async_context.ts (returns null in browsers).\nconst retry_context_storage: AsyncLocalStorageLike | null = createAsyncLocalStorage()\n\nfunction getHeldSemaphores(): ReentrantStore {\n return (retry_context_storage?.getStore() as ReentrantStore | undefined) ?? new Set()\n}\n\nfunction runWithHeldSemaphores<T>(held: ReentrantStore, fn: () => T): T {\n if (!retry_context_storage) return fn()\n return retry_context_storage.run(held, fn)\n}\n\n// \u2500\u2500\u2500 Semaphore scope helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nlet _next_instance_id = 1\nconst _instance_ids = new WeakMap<object, number>()\n\nfunction scopedSemaphoreKey(base_name: string, scope: SemaphoreScope, context: unknown): string {\n if (scope === 'class' && context && typeof context === 'object') {\n return `${(context as object).constructor?.name ?? 'Object'}.${base_name}`\n }\n if (scope === 'instance' && context && typeof context === 'object') {\n let id = _instance_ids.get(context as object)\n if (id === undefined) {\n id = _next_instance_id++\n _instance_ids.set(context as object, id)\n }\n return `${id}.${base_name}`\n }\n return base_name\n}\n\n// \u2500\u2500\u2500 Global semaphore registry \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nclass RetrySemaphore {\n readonly size: number\n private inUse: number\n private waiters: Array<() => void>\n\n constructor(size: number) {\n this.size = size\n this.inUse = 0\n this.waiters = []\n }\n\n tryAcquire(): boolean {\n if (this.size === Infinity) {\n return true\n }\n if (this.inUse < this.size) {\n this.inUse += 1\n return true\n }\n return false\n }\n\n async acquire(): Promise<void> {\n if (this.tryAcquire()) {\n return\n }\n await new Promise<void>((resolve) => {\n this.waiters.push(resolve)\n })\n }\n\n release(): void {\n if (this.size === Infinity) {\n return\n }\n const next = this.waiters.shift()\n if (next) {\n // Handoff: keep the permit accounted for and transfer it directly to the waiter.\n next()\n return\n }\n this.inUse = Math.max(0, this.inUse - 1)\n }\n}\n\nconst SEMAPHORE_REGISTRY = new Map<string, RetrySemaphore>()\n\nfunction getOrCreateSemaphore(name: string, limit: number): RetrySemaphore {\n const existing = SEMAPHORE_REGISTRY.get(name)\n if (existing && existing.size === limit) return existing\n const sem = new RetrySemaphore(limit)\n SEMAPHORE_REGISTRY.set(name, sem)\n return sem\n}\n\n/** Reset the global semaphore registry. Useful in tests. */\nexport function clearSemaphoreRegistry(): void {\n SEMAPHORE_REGISTRY.clear()\n multiprocess_fallback_reason_logged = null\n}\n\n// \u2500\u2500\u2500 retry() decorator / higher-order wrapper \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n//\n// Usage as a higher-order function (works on async and sync functions):\n//\n// const fetchWithRetry = retry({ max_attempts: 3, retry_after: 1 })(async (url: string) => {\n// return await fetch(url)\n// })\n//\n// const readWithRetry = retry({ max_attempts: 3, retry_after: 1 })((path: string) => {\n// return readFileSync(path, 'utf8')\n// })\n//\n// Usage as a TC39 Stage 3 or legacy experimental decorator on class methods:\n//\n// class ApiClient {\n// @retry({ max_attempts: 3, retry_after: 1 })\n// async fetchData(): Promise<Data> { ... }\n// }\n//\n// Usage on event bus handlers:\n//\n// bus.on(MyEvent, retry({ max_attempts: 3 })(async (event) => {\n// await riskyOperation(event.data)\n// }))\n\nexport function retry(options: RetryOptions = {}): RetryDecorator {\n const {\n max_attempts = 1,\n retry_after = 0,\n retry_backoff_factor = 1.0,\n retry_on_errors,\n timeout,\n slow_timeout,\n semaphore_limit,\n semaphore_name: semaphore_name_option,\n semaphore_lax = true,\n semaphore_scope = 'global',\n semaphore_timeout,\n } = options\n\n const decorateFunction = <T extends AnyFunction>(target: T, _context?: ClassMethodDecoratorContext, owner_name?: string | null): T => {\n const base_fn_name = target.name || (_context?.name as string) || 'anonymous'\n let fn_name = owner_name ? `${owner_name}.${base_fn_name}` : base_fn_name\n const effective_max_attempts = Math.max(1, max_attempts)\n const effective_retry_after = Math.max(0, retry_after)\n const effective_slow_timeout_ms = slow_timeout != null && slow_timeout > 0 ? slow_timeout * 1000 : null\n let last_slow_warning_at = 0\n\n const shouldRetry = (error: unknown): boolean => {\n if (!retry_on_errors || retry_on_errors.length === 0) return true\n return retry_on_errors.some((matcher) =>\n typeof matcher === 'string'\n ? (error as Error)?.name === matcher\n : matcher instanceof RegExp\n ? matcher.test(String(error))\n : error instanceof matcher\n )\n }\n\n const asyncRetryDelay = async (attempt: number): Promise<void> => {\n const delay_seconds = effective_retry_after * Math.pow(retry_backoff_factor, attempt - 1)\n if (delay_seconds > 0) {\n await sleep(delay_seconds * 1000)\n }\n }\n\n const syncRetryDelay = (attempt: number): void => {\n const delay_seconds = effective_retry_after * Math.pow(retry_backoff_factor, attempt - 1)\n if (delay_seconds > 0) {\n sleepSync(delay_seconds * 1000)\n }\n }\n\n const emitSlowWarningIfDue = (args: any[], start_time: number): void => {\n if (effective_slow_timeout_ms == null) return\n const now = Date.now()\n if (now - last_slow_warning_at < RETRY_SLOW_WARNING_THROTTLE_MS) return\n last_slow_warning_at = now\n console.warn(`Warning: ${fn_name}(${formatRetrySlowWarningArgs(args)}) slow (${((now - start_time) / 1000).toFixed(1)}s)`)\n }\n\n const runRetryLoopFromThenable = async (\n this_arg: any,\n args: any[],\n first_thenable: PromiseLike<any>,\n first_attempt: number\n ): Promise<any> => {\n let current_result: any = first_thenable\n for (let attempt = first_attempt; attempt <= effective_max_attempts; attempt++) {\n try {\n if (attempt !== first_attempt) {\n current_result = target.apply(this_arg, args)\n }\n if (isThenable(current_result)) {\n if (timeout != null && timeout > 0) {\n return await _runWithTimeout(() => Promise.resolve(current_result), timeout * 1000, attempt)\n }\n return await current_result\n }\n return current_result\n } catch (error) {\n if (!shouldRetry(error)) throw error\n if (attempt >= effective_max_attempts) throw error\n await asyncRetryDelay(attempt)\n }\n }\n throw new Error(`retry(${fn_name}): unexpected end of retry loop`)\n }\n\n async function asyncRetryWrapper(this: any, ...args: any[]): Promise<any> {\n const base_name = typeof semaphore_name_option === 'function' ? semaphore_name_option(...args) : (semaphore_name_option ?? fn_name)\n const sem_name = typeof base_name === 'string' ? base_name : String(base_name)\n // \u2500\u2500 Resolve scoped semaphore key at call time (uses `this` for class/instance scopes) \u2500\u2500\n const scoped_key = scopedSemaphoreKey(sem_name, semaphore_scope, this)\n\n // \u2500\u2500 Check re-entrancy: skip semaphore if we already hold it in this async context \u2500\u2500\n const held = getHeldSemaphores()\n const needs_semaphore = semaphore_limit != null && semaphore_limit > 0\n const is_reentrant = needs_semaphore && held.has(scoped_key)\n\n // \u2500\u2500 Semaphore acquisition (held across all retry attempts, skipped if re-entrant) \u2500\u2500\n let semaphore: RetrySemaphore | null = null\n let multiprocess_lock: MultiprocessLockHandle | null = null\n let semaphore_acquired = false\n\n if (needs_semaphore && !is_reentrant) {\n const effective_sem_timeout =\n semaphore_timeout != null ? semaphore_timeout : timeout != null ? timeout * Math.max(1, semaphore_limit! - 1) : null\n\n if (semaphore_scope === 'multiprocess') {\n if (isNodeRuntime()) {\n multiprocess_lock = await acquireMultiprocessSemaphore(scoped_key, semaphore_limit!, effective_sem_timeout, semaphore_lax)\n semaphore_acquired = multiprocess_lock !== null\n } else {\n logMultiprocessFallbackOnce('multiprocess semaphores require a Node.js runtime; falling back to in-process global scope')\n semaphore = getOrCreateSemaphore(scoped_key, semaphore_limit!)\n if (effective_sem_timeout != null && effective_sem_timeout > 0) {\n semaphore_acquired = await acquireWithTimeout(semaphore, effective_sem_timeout * 1000)\n if (!semaphore_acquired) {\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(\n `Failed to acquire semaphore \"${scoped_key}\" within ${effective_sem_timeout}s (limit=${semaphore_limit})`,\n { semaphore_name: scoped_key, semaphore_limit: semaphore_limit!, timeout_seconds: effective_sem_timeout }\n )\n }\n }\n } else {\n await semaphore.acquire()\n semaphore_acquired = true\n }\n }\n } else {\n semaphore = getOrCreateSemaphore(scoped_key, semaphore_limit!)\n\n if (effective_sem_timeout != null && effective_sem_timeout > 0) {\n semaphore_acquired = await acquireWithTimeout(semaphore, effective_sem_timeout * 1000)\n if (!semaphore_acquired) {\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(\n `Failed to acquire semaphore \"${scoped_key}\" within ${effective_sem_timeout}s (limit=${semaphore_limit})`,\n { semaphore_name: scoped_key, semaphore_limit: semaphore_limit!, timeout_seconds: effective_sem_timeout }\n )\n }\n }\n } else {\n await semaphore.acquire()\n semaphore_acquired = true\n }\n }\n }\n\n // \u2500\u2500 Build the set of held semaphores for nested calls \u2500\u2500\n const new_held = new Set(held)\n if (semaphore_acquired) {\n new_held.add(scoped_key)\n }\n\n // \u2500\u2500 Retry loop (runs inside the semaphore and re-entrancy context) \u2500\u2500\n const runRetryLoop = async (): Promise<any> => {\n const call_started_at = Date.now()\n const warning_args = [...args]\n const slow_warning_timer =\n effective_slow_timeout_ms == null\n ? null\n : setTimeout(() => emitSlowWarningIfDue(warning_args, call_started_at), effective_slow_timeout_ms)\n const finishSlowWarning = (): void => {\n if (slow_warning_timer !== null) {\n clearTimeout(slow_warning_timer)\n }\n if (effective_slow_timeout_ms != null && Date.now() - call_started_at >= effective_slow_timeout_ms) {\n emitSlowWarningIfDue(warning_args, call_started_at)\n }\n }\n\n try {\n for (let attempt = 1; attempt <= effective_max_attempts; attempt++) {\n try {\n if (timeout != null && timeout > 0) {\n return await _runWithTimeout(() => Promise.resolve(target.apply(this, args)), timeout * 1000, attempt)\n } else {\n return await Promise.resolve(target.apply(this, args))\n }\n } catch (error) {\n if (!shouldRetry(error)) throw error\n\n // Last attempt: rethrow\n if (attempt >= effective_max_attempts) throw error\n\n // Wait before next attempt with exponential backoff\n await asyncRetryDelay(attempt)\n }\n }\n\n // Unreachable, but satisfies the type checker\n throw new Error(`retry(${fn_name}): unexpected end of retry loop`)\n } finally {\n finishSlowWarning()\n }\n }\n\n try {\n return await runWithHeldSemaphores(new_held, runRetryLoop)\n } finally {\n if (semaphore_acquired && multiprocess_lock) {\n await multiprocess_lock.release()\n } else if (semaphore_acquired && semaphore) {\n semaphore.release()\n }\n }\n }\n\n function syncRetryWrapper(this: any, ...args: any[]): any {\n const base_name = typeof semaphore_name_option === 'function' ? semaphore_name_option(...args) : (semaphore_name_option ?? fn_name)\n const sem_name = typeof base_name === 'string' ? base_name : String(base_name)\n const scoped_key = scopedSemaphoreKey(sem_name, semaphore_scope, this)\n\n const held = getHeldSemaphores()\n const needs_semaphore = semaphore_limit != null && semaphore_limit > 0\n const is_reentrant = needs_semaphore && held.has(scoped_key)\n\n let semaphore: RetrySemaphore | null = null\n let multiprocess_lock: SyncMultiprocessLockHandle | null = null\n let semaphore_acquired = false\n\n if (needs_semaphore && !is_reentrant) {\n const effective_sem_timeout =\n semaphore_timeout != null ? semaphore_timeout : timeout != null ? timeout * Math.max(1, semaphore_limit! - 1) : null\n\n if (semaphore_scope === 'multiprocess') {\n if (isNodeRuntime()) {\n multiprocess_lock = acquireMultiprocessSemaphoreSync(scoped_key, semaphore_limit!, effective_sem_timeout, semaphore_lax)\n semaphore_acquired = multiprocess_lock !== null\n } else {\n logMultiprocessFallbackOnce('multiprocess semaphores require a Node.js runtime; falling back to in-process global scope')\n semaphore = getOrCreateSemaphore(scoped_key, semaphore_limit!)\n semaphore_acquired = acquireSemaphoreSyncOrThrow(semaphore, scoped_key, semaphore_limit!, effective_sem_timeout, semaphore_lax)\n }\n } else {\n semaphore = getOrCreateSemaphore(scoped_key, semaphore_limit!)\n semaphore_acquired = acquireSemaphoreSyncOrThrow(semaphore, scoped_key, semaphore_limit!, effective_sem_timeout, semaphore_lax)\n }\n }\n\n const new_held = new Set(held)\n if (semaphore_acquired) {\n new_held.add(scoped_key)\n }\n\n const release = (): void => {\n if (semaphore_acquired && multiprocess_lock) {\n multiprocess_lock.release()\n } else if (semaphore_acquired && semaphore) {\n semaphore.release()\n }\n }\n\n const runRetryLoop = (): any => {\n const call_started_at = Date.now()\n const warning_args = [...args]\n const slow_warning_timer =\n effective_slow_timeout_ms == null\n ? null\n : setTimeout(() => emitSlowWarningIfDue(warning_args, call_started_at), effective_slow_timeout_ms)\n const finishSlowWarning = (): void => {\n if (slow_warning_timer !== null) {\n clearTimeout(slow_warning_timer)\n }\n if (effective_slow_timeout_ms != null && Date.now() - call_started_at >= effective_slow_timeout_ms) {\n emitSlowWarningIfDue(warning_args, call_started_at)\n }\n }\n\n let finish_on_return = true\n try {\n for (let attempt = 1; attempt <= effective_max_attempts; attempt++) {\n const attempt_started_at = Date.now()\n try {\n const result = target.apply(this, args)\n if (isThenable(result)) {\n finish_on_return = false\n return runRetryLoopFromThenable(this, args, result, attempt).finally(finishSlowWarning)\n }\n if (timeout != null && timeout > 0 && Date.now() - attempt_started_at > timeout * 1000) {\n throw new RetryTimeoutError(`Timed out after ${timeout}s (attempt ${attempt})`, {\n timeout_seconds: timeout,\n attempt,\n })\n }\n return result\n } catch (error) {\n if (!shouldRetry(error)) throw error\n if (attempt >= effective_max_attempts) {\n throw error\n }\n syncRetryDelay(attempt)\n }\n }\n throw new Error(`retry(${fn_name}): unexpected end of retry loop`)\n } finally {\n if (finish_on_return) {\n finishSlowWarning()\n }\n }\n }\n\n try {\n const result = runWithHeldSemaphores(new_held, runRetryLoop)\n if (isThenable(result)) {\n return Promise.resolve(result).finally(release)\n }\n release()\n return result\n } catch (error) {\n release()\n throw error\n }\n }\n\n const retryWrapper = isAsyncFunction(target) ? asyncRetryWrapper : syncRetryWrapper\n Object.defineProperty(retryWrapper, 'name', { value: fn_name, configurable: true })\n if (_context?.kind === 'method' && typeof _context.addInitializer === 'function') {\n _context.addInitializer(function (this: unknown) {\n const owner_name = findDecoratedMethodOwnerName(this, _context, retryWrapper)\n if (owner_name) {\n fn_name = `${owner_name}.${target.name || (_context.name as string) || 'anonymous'}`\n Object.defineProperty(retryWrapper, 'name', { value: fn_name, configurable: true })\n }\n })\n }\n return retryWrapper as unknown as T\n }\n\n function decorator<T extends AnyFunction>(\n target: T | object,\n context_or_property_key?: ClassMethodDecoratorContext | string | symbol,\n descriptor?: LegacyMethodDescriptor\n ): T | LegacyMethodDescriptor {\n if (descriptor?.value && typeof descriptor.value === 'function') {\n const owner_name =\n target && (typeof target === 'object' || typeof target === 'function')\n ? typeof target === 'function'\n ? target.name\n : (target as { constructor?: { name?: string } }).constructor?.name\n : null\n descriptor.value = decorateFunction(descriptor.value, undefined, owner_name)\n return descriptor\n }\n if (typeof target === 'function') {\n return decorateFunction(target as T, typeof context_or_property_key === 'object' ? context_or_property_key : undefined)\n }\n throw new TypeError('retry() can only decorate functions and class methods')\n }\n return decorator as RetryDecorator\n}\n\n// \u2500\u2500\u2500 Internal helpers \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\n\nfunction findDecoratedMethodOwnerName(\n context_this: unknown,\n context: ClassMethodDecoratorContext,\n replacement: (...args: any[]) => any\n): string | null {\n const method_name = context.name\n if (typeof method_name !== 'string') {\n return null\n }\n\n if (context.static) {\n let ctor = typeof context_this === 'function' ? context_this : null\n while (ctor && ctor !== Function.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(ctor, method_name)\n if (descriptor?.value === replacement) {\n return ctor.name || null\n }\n const parent = Object.getPrototypeOf(ctor)\n ctor = typeof parent === 'function' ? parent : null\n }\n return null\n }\n\n if ((typeof context_this !== 'object' && typeof context_this !== 'function') || context_this === null) {\n return null\n }\n\n let prototype = Object.getPrototypeOf(context_this)\n while (prototype && prototype !== Object.prototype) {\n const descriptor = Object.getOwnPropertyDescriptor(prototype, method_name)\n if (descriptor?.value === replacement) {\n const ctor_name = (prototype as { constructor?: { name?: string } }).constructor?.name\n return ctor_name || null\n }\n prototype = Object.getPrototypeOf(prototype)\n }\n return null\n}\n\nfunction isAsyncFunction(fn: AnyFunction): boolean {\n return Object.prototype.toString.call(fn) === '[object AsyncFunction]'\n}\n\nfunction isThenable(value: unknown): value is PromiseLike<unknown> {\n return (\n (typeof value === 'object' || typeof value === 'function') && value !== null && typeof (value as { then?: unknown }).then === 'function'\n )\n}\n\nfunction formatRetrySlowWarningArgs(args: any[]): string {\n const preview = args.map(formatRetrySlowWarningValue).join(', ')\n if (preview.length > RETRY_SLOW_WARNING_ARGS_MAX_LENGTH) {\n return `${preview.slice(0, RETRY_SLOW_WARNING_ARGS_MAX_LENGTH - 3).replace(/,?\\s*$/, '')}...`\n }\n return preview\n}\n\nfunction formatRetrySlowWarningValue(value: unknown): string {\n let text: string\n if (typeof value === 'string') {\n text = value\n } else if (value === null || value === undefined) {\n text = String(value)\n } else if (typeof value === 'object') {\n try {\n text = JSON.stringify(value)\n } catch {\n text = String(value)\n }\n } else {\n text = String(value)\n }\n return text.replace(/['\"]/g, '').slice(0, 3)\n}\n\n/**\n * Try to acquire a semaphore within a timeout. Returns true if acquired, false if timed out.\n * If the semaphore is acquired after the timeout (due to the waiter remaining queued),\n * it is immediately released to avoid leaking slots.\n */\nasync function acquireWithTimeout(semaphore: RetrySemaphore, timeout_ms: number): Promise<boolean> {\n return new Promise<boolean>((resolve) => {\n let settled = false\n\n const timer = setTimeout(() => {\n if (!settled) {\n settled = true\n resolve(false)\n }\n }, timeout_ms)\n\n semaphore.acquire().then(() => {\n if (!settled) {\n settled = true\n clearTimeout(timer)\n resolve(true)\n } else {\n // Acquired after timeout fired \u2014 release immediately to avoid slot leak\n semaphore.release()\n }\n })\n })\n}\n\nfunction acquireSemaphoreSyncOrThrow(\n semaphore: RetrySemaphore,\n scoped_key: string,\n semaphore_limit: number,\n timeout_seconds: number | null,\n semaphore_lax: boolean\n): boolean {\n const acquired = acquireSemaphoreSync(semaphore, timeout_seconds == null ? null : timeout_seconds * 1000)\n if (acquired) return true\n\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(`Failed to acquire semaphore \"${scoped_key}\" within ${timeout_seconds}s (limit=${semaphore_limit})`, {\n semaphore_name: scoped_key,\n semaphore_limit,\n timeout_seconds: timeout_seconds ?? 0,\n })\n }\n return false\n}\n\nfunction acquireSemaphoreSync(semaphore: RetrySemaphore, timeout_ms: number | null): boolean {\n if (semaphore.tryAcquire()) return true\n\n const start = Date.now()\n while (true) {\n if (timeout_ms != null && timeout_ms > 0 && Date.now() - start >= timeout_ms) {\n return false\n }\n sleepSync(10)\n if (semaphore.tryAcquire()) return true\n }\n}\n\nfunction logMultiprocessFallbackOnce(reason: string): void {\n if (multiprocess_fallback_reason_logged === reason) return\n multiprocess_fallback_reason_logged = reason\n console.warn(`[abxbus.retry] ${reason}`)\n}\n\nfunction importNodeModuleSync(specifier: string): any {\n const maybe_process = (\n globalThis as {\n process?: { getBuiltinModule?: (name: string) => any }\n }\n ).process\n const get_builtin_module = maybe_process?.getBuiltinModule\n const bare_specifier = specifier.startsWith('node:') ? specifier.slice('node:'.length) : specifier\n\n if (typeof get_builtin_module === 'function') {\n const builtin = get_builtin_module(bare_specifier) ?? get_builtin_module(specifier)\n if (builtin) return builtin\n }\n\n let require_fn: ((name: string) => any) | undefined\n try {\n require_fn = Function('return typeof require === \"function\" ? require : undefined')() as ((name: string) => any) | undefined\n } catch {\n require_fn = undefined\n }\n if (require_fn) return require_fn(specifier)\n\n throw new Error('[abxbus.retry] synchronous Node.js module loading is unavailable; cannot use sync multiprocess semaphores')\n}\n\nasync function importNodeModule(specifier: string): Promise<any> {\n const dynamic_import = Function('module_name', 'return import(module_name)') as (module_name: string) => Promise<unknown>\n return dynamic_import(specifier) as Promise<any>\n}\n\nasync function acquireMultiprocessSemaphore(\n scoped_key: string,\n semaphore_limit: number,\n semaphore_timeout_seconds: number | null,\n semaphore_lax: boolean\n): Promise<MultiprocessLockHandle | null> {\n const [crypto, fs, os, path] = await Promise.all([\n importNodeModule('node:crypto'),\n importNodeModule('node:fs'),\n importNodeModule('node:os'),\n importNodeModule('node:path'),\n ])\n const semaphore_directory = path.join(os.tmpdir(), MULTIPROCESS_SEMAPHORE_DIRNAME)\n const lock_prefix = crypto.createHash('sha256').update(scoped_key).digest('hex').slice(0, 40)\n fs.mkdirSync(semaphore_directory, { recursive: true })\n\n const start = Date.now()\n let retry_delay_ms = 100\n\n while (true) {\n const elapsed_ms = Date.now() - start\n const remaining_ms =\n semaphore_timeout_seconds != null && semaphore_timeout_seconds > 0 ? semaphore_timeout_seconds * 1000 - elapsed_ms : null\n\n if (remaining_ms != null && remaining_ms <= 0) {\n break\n }\n\n for (let slot = 0; slot < semaphore_limit; slot++) {\n const slot_file = path.join(semaphore_directory, `${lock_prefix}.${String(slot).padStart(2, '0')}.lock`)\n const token = `${process.pid}:${Date.now()}:${Math.random().toString(16).slice(2)}`\n\n try {\n const fd = fs.openSync(slot_file, 'wx', 0o600)\n try {\n fs.writeFileSync(\n fd,\n JSON.stringify({\n token,\n pid: process.pid,\n semaphore_name: scoped_key,\n created_at_ms: Date.now(),\n }),\n 'utf8'\n )\n } finally {\n fs.closeSync(fd)\n }\n return {\n release: async () => {\n try {\n const raw = String(fs.readFileSync(slot_file, 'utf8') || '').trim()\n const current_owner = raw ? (JSON.parse(raw) as { token?: unknown }) : null\n if (current_owner?.token === token) {\n fs.unlinkSync(slot_file)\n }\n } catch {}\n },\n }\n } catch (error) {\n if (!(error instanceof Error) || (error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error\n }\n\n try {\n const raw = String(fs.readFileSync(slot_file, 'utf8') || '').trim()\n const current_owner = raw ? (JSON.parse(raw) as { pid?: unknown }) : null\n const current_pid = typeof current_owner?.pid === 'number' ? current_owner.pid : null\n if (current_pid != null) {\n try {\n process.kill(current_pid, 0)\n continue\n } catch {}\n }\n\n const slot_age_ms = Date.now() - fs.statSync(slot_file).mtimeMs\n if (current_pid != null || slot_age_ms >= MULTIPROCESS_STALE_LOCK_MS) {\n fs.unlinkSync(slot_file)\n }\n } catch {}\n }\n }\n\n const sleep_ms = Math.min(retry_delay_ms, remaining_ms ?? retry_delay_ms)\n if (sleep_ms > 0) {\n await sleep(sleep_ms)\n }\n retry_delay_ms = Math.min(retry_delay_ms * 2, 1000)\n }\n\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(\n `Failed to acquire semaphore \"${scoped_key}\" within ${semaphore_timeout_seconds}s (limit=${semaphore_limit})`,\n { semaphore_name: scoped_key, semaphore_limit, timeout_seconds: semaphore_timeout_seconds ?? 0 }\n )\n }\n\n return null\n}\n\nfunction acquireMultiprocessSemaphoreSync(\n scoped_key: string,\n semaphore_limit: number,\n semaphore_timeout_seconds: number | null,\n semaphore_lax: boolean\n): SyncMultiprocessLockHandle | null {\n const crypto = importNodeModuleSync('node:crypto')\n const fs = importNodeModuleSync('node:fs')\n const os = importNodeModuleSync('node:os')\n const path = importNodeModuleSync('node:path')\n const semaphore_directory = path.join(os.tmpdir(), MULTIPROCESS_SEMAPHORE_DIRNAME)\n const lock_prefix = crypto.createHash('sha256').update(scoped_key).digest('hex').slice(0, 40)\n fs.mkdirSync(semaphore_directory, { recursive: true })\n\n const start = Date.now()\n let retry_delay_ms = 100\n\n while (true) {\n const elapsed_ms = Date.now() - start\n const remaining_ms =\n semaphore_timeout_seconds != null && semaphore_timeout_seconds > 0 ? semaphore_timeout_seconds * 1000 - elapsed_ms : null\n\n if (remaining_ms != null && remaining_ms <= 0) {\n break\n }\n\n for (let slot = 0; slot < semaphore_limit; slot++) {\n const slot_file = path.join(semaphore_directory, `${lock_prefix}.${String(slot).padStart(2, '0')}.lock`)\n const token = `${process.pid}:${Date.now()}:${Math.random().toString(16).slice(2)}`\n\n try {\n const fd = fs.openSync(slot_file, 'wx', 0o600)\n try {\n fs.writeFileSync(\n fd,\n JSON.stringify({\n token,\n pid: process.pid,\n semaphore_name: scoped_key,\n created_at_ms: Date.now(),\n }),\n 'utf8'\n )\n } finally {\n fs.closeSync(fd)\n }\n return {\n release: () => {\n try {\n const raw = String(fs.readFileSync(slot_file, 'utf8') || '').trim()\n const current_owner = raw ? (JSON.parse(raw) as { token?: unknown }) : null\n if (current_owner?.token === token) {\n fs.unlinkSync(slot_file)\n }\n } catch {}\n },\n }\n } catch (error) {\n if (!(error instanceof Error) || (error as NodeJS.ErrnoException).code !== 'EEXIST') {\n throw error\n }\n\n try {\n const raw = String(fs.readFileSync(slot_file, 'utf8') || '').trim()\n const current_owner = raw ? (JSON.parse(raw) as { pid?: unknown }) : null\n const current_pid = typeof current_owner?.pid === 'number' ? current_owner.pid : null\n if (current_pid != null) {\n try {\n process.kill(current_pid, 0)\n continue\n } catch {}\n }\n\n const slot_age_ms = Date.now() - fs.statSync(slot_file).mtimeMs\n if (current_pid != null || slot_age_ms >= MULTIPROCESS_STALE_LOCK_MS) {\n fs.unlinkSync(slot_file)\n }\n } catch {}\n }\n }\n\n const sleep_ms = Math.min(retry_delay_ms, remaining_ms ?? retry_delay_ms)\n if (sleep_ms > 0) {\n sleepSync(sleep_ms)\n }\n retry_delay_ms = Math.min(retry_delay_ms * 2, 1000)\n }\n\n if (!semaphore_lax) {\n throw new SemaphoreTimeoutError(\n `Failed to acquire semaphore \"${scoped_key}\" within ${semaphore_timeout_seconds}s (limit=${semaphore_limit})`,\n { semaphore_name: scoped_key, semaphore_limit, timeout_seconds: semaphore_timeout_seconds ?? 0 }\n )\n }\n\n return null\n}\n\n/** Run fn() with a timeout. Rejects with RetryTimeoutError if the timeout fires first. */\nasync function _runWithTimeout<T>(fn: () => Promise<T>, timeout_ms: number, attempt: number): Promise<T> {\n return new Promise<T>((resolve, reject) => {\n let settled = false\n\n const timer = setTimeout(() => {\n if (!settled) {\n settled = true\n reject(\n new RetryTimeoutError(`Timed out after ${timeout_ms / 1000}s (attempt ${attempt})`, {\n timeout_seconds: timeout_ms / 1000,\n attempt,\n })\n )\n }\n }, timeout_ms)\n\n fn().then(\n (value) => {\n if (!settled) {\n settled = true\n clearTimeout(timer)\n resolve(value)\n }\n },\n (error) => {\n if (!settled) {\n settled = true\n clearTimeout(timer)\n reject(error)\n }\n }\n )\n })\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nfunction sleepSync(ms: number): void {\n if (ms <= 0) return\n\n const shared_array_buffer = (globalThis as { SharedArrayBuffer?: typeof SharedArrayBuffer }).SharedArrayBuffer\n const atomics = (globalThis as { Atomics?: typeof Atomics }).Atomics\n if (typeof shared_array_buffer === 'function' && typeof atomics?.wait === 'function') {\n try {\n const buffer = new shared_array_buffer(4)\n const view = new Int32Array(buffer)\n atomics.wait(view, 0, 0, ms)\n return\n } catch {}\n }\n\n const deadline = Date.now() + ms\n while (Date.now() < deadline) {}\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,+BAA2D;AACpE,SAAS,qBAAqB;AAoB9B,MAAM,iCAAiC;AACvC,MAAM,6BAA6B,IAAI,KAAK;AAC5C,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I,WAAW,MAAM;AAClC,cAAQ,KAAK,MAAM,GAAG,GAAG,EAAE;AAC3B;AAAA,IACF,QAAQ;AAAA,IAAC;AAAA,EACX;AAEA,QAAM,WAAW,KAAK,IAAI,IAAI;AAC9B,SAAO,KAAK,IAAI,IAAI,UAAU;AAAA,EAAC;AACjC;",
|
|
6
|
+
"names": ["owner_name"]
|
|
7
7
|
}
|
package/dist/esm/types.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
+
import { fromJsonSchema, isJsonSchema } from "./jsonschema.js";
|
|
2
3
|
const normalizeEventPattern = (event_pattern) => {
|
|
3
4
|
if (event_pattern === "*") {
|
|
4
5
|
return "*";
|
|
@@ -21,7 +22,7 @@ const normalizeEventPattern = (event_pattern) => {
|
|
|
21
22
|
} catch {
|
|
22
23
|
preview = String(event_pattern).slice(0, 30);
|
|
23
24
|
}
|
|
24
|
-
throw new Error('bus.on(match_pattern, ...) must be a string event type, "*", or a BaseEvent class, got: ' + preview);
|
|
25
|
+
throw new Error('bus.on(match_pattern, ...) must be a string event type, "*", or a BaseEvent.extend() event class, got: ' + preview);
|
|
25
26
|
};
|
|
26
27
|
const isZodSchema = (value) => !!value && typeof value.safeParse === "function";
|
|
27
28
|
const eventResultTypeFromConstructor = (value) => {
|
|
@@ -50,16 +51,7 @@ const extractZodShape = (raw) => {
|
|
|
50
51
|
}
|
|
51
52
|
return shape;
|
|
52
53
|
};
|
|
53
|
-
|
|
54
|
-
if (!schema || !isZodSchema(schema)) return schema;
|
|
55
|
-
const zod_any = z;
|
|
56
|
-
return zod_any.toJSONSchema(schema);
|
|
57
|
-
};
|
|
58
|
-
const fromJsonSchema = (schema) => {
|
|
59
|
-
const zod_any = z;
|
|
60
|
-
return zod_any.fromJSONSchema(schema);
|
|
61
|
-
};
|
|
62
|
-
const normalizeEventResultType = (value) => {
|
|
54
|
+
function normalizeEventResultType(value) {
|
|
63
55
|
if (value === void 0 || value === null) {
|
|
64
56
|
return void 0;
|
|
65
57
|
}
|
|
@@ -70,15 +62,16 @@ const normalizeEventResultType = (value) => {
|
|
|
70
62
|
if (constructor_schema) {
|
|
71
63
|
return constructor_schema;
|
|
72
64
|
}
|
|
65
|
+
if (!isJsonSchema(value)) {
|
|
66
|
+
throw new Error(`event_result_type must be a Zod schema, constructor shorthand, or JSON Schema value, got: ${typeof value}`);
|
|
67
|
+
}
|
|
73
68
|
return fromJsonSchema(value);
|
|
74
|
-
}
|
|
69
|
+
}
|
|
75
70
|
export {
|
|
76
71
|
eventResultTypeFromConstructor,
|
|
77
72
|
extractZodShape,
|
|
78
|
-
fromJsonSchema,
|
|
79
73
|
isZodSchema,
|
|
80
74
|
normalizeEventPattern,
|
|
81
|
-
normalizeEventResultType
|
|
82
|
-
toJsonSchema
|
|
75
|
+
normalizeEventResultType
|
|
83
76
|
};
|
|
84
77
|
//# sourceMappingURL=types.js.map
|
package/dist/esm/types.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/types.ts"],
|
|
4
|
-
"sourcesContent": ["import { z } from 'zod'\nimport type { BaseEvent } from './BaseEvent.js'\n\nexport type EventStatus = 'pending' | 'started' | 'completed'\
|
|
5
|
-
"mappings": "AAAA,SAAS,SAAS;
|
|
4
|
+
"sourcesContent": ["import { z } from 'zod'\nimport type { BaseEvent, EventClass as BaseEventClass } from './BaseEvent.js'\nimport { fromJsonSchema, isJsonSchema, type JsonSchema } from './jsonschema.js'\n\nexport type EventStatus = 'pending' | 'started' | 'completed'\nexport type { EventClass } from './BaseEvent.js'\n\nexport type EventPattern<T extends BaseEvent = BaseEvent> = string | BaseEventClass<T>\n\nexport type EventWithResultSchema<TResult> = BaseEvent & { __event_result_type__?: TResult }\n\nexport type EventResultType<TEvent extends BaseEvent> = TEvent extends { __event_result_type__?: infer TResult } ? TResult : unknown\n\nexport type EventResultTypeConstructor = StringConstructor | NumberConstructor | BooleanConstructor | ArrayConstructor | ObjectConstructor\n\nexport type EventResultTypeInput = z.ZodTypeAny | EventResultTypeConstructor | JsonSchema\n\nexport type EventHandlerReturn<T extends BaseEvent = BaseEvent> = EventResultType<T> | BaseEvent | null | void\n\nexport type EventHandlerCallable<T extends BaseEvent = BaseEvent> = (event: T) => EventHandlerReturn<T> | Promise<EventHandlerReturn<T>>\n\n// For string and wildcard subscriptions we cannot reliably infer which event\n// type will arrive, so return type checking intentionally degrades to unknown.\nexport type UntypedEventHandlerFunction<T extends BaseEvent = BaseEvent> = (\n event: T\n) => EventHandlerReturn<T> | unknown | Promise<EventHandlerReturn<T> | unknown>\n\nexport type FindWindow = boolean | number\n\ntype FindReservedOptionKeys = 'past' | 'future' | 'child_of'\n\ntype EventFilterFields<T extends BaseEvent> = {\n [K in keyof T as string extends K\n ? never\n : number extends K\n ? never\n : symbol extends K\n ? never\n : K extends FindReservedOptionKeys\n ? never\n : T[K] extends (...args: any[]) => any\n ? never\n : K]?: T[K]\n}\n\nexport type FindOptions<T extends BaseEvent = BaseEvent> = {\n past?: FindWindow\n future?: FindWindow\n child_of?: BaseEvent | null\n} & EventFilterFields<T> &\n Record<string, unknown>\n\nexport type FilterOptions<T extends BaseEvent = BaseEvent> = FindOptions<T> & { limit?: number | null }\n\nexport const normalizeEventPattern = (event_pattern: EventPattern | '*'): string | '*' => {\n if (event_pattern === '*') {\n return '*'\n }\n if (typeof event_pattern === 'string') {\n return event_pattern\n }\n const event_type = (event_pattern as { event_type?: unknown }).event_type\n if (typeof event_type === 'string' && event_type.length > 0 && event_type !== 'BaseEvent') {\n return event_type\n }\n const class_name = (event_pattern as { name?: unknown }).name\n if (typeof class_name === 'string' && class_name.length > 0 && class_name !== 'BaseEvent') {\n return class_name\n }\n let preview: string\n try {\n const encoded = JSON.stringify(event_pattern)\n preview = typeof encoded === 'string' ? encoded.slice(0, 30) : String(event_pattern).slice(0, 30)\n } catch {\n preview = String(event_pattern).slice(0, 30)\n }\n throw new Error('bus.on(match_pattern, ...) must be a string event type, \"*\", or a BaseEvent.extend() event class, got: ' + preview)\n}\n\nexport const isZodSchema = (value: unknown): value is z.ZodTypeAny => !!value && typeof (value as z.ZodTypeAny).safeParse === 'function'\n\nexport const eventResultTypeFromConstructor = (value: unknown): z.ZodTypeAny | undefined => {\n if (value === String) {\n return z.string()\n }\n if (value === Number) {\n return z.number()\n }\n if (value === Boolean) {\n return z.boolean()\n }\n if (value === Array) {\n return z.array(z.unknown())\n }\n if (value === Object) {\n return z.record(z.string(), z.unknown())\n }\n return undefined\n}\n\nexport const extractZodShape = (raw: Record<string, unknown>): z.ZodRawShape => {\n const shape: Record<string, z.ZodTypeAny> = {}\n for (const [key, value] of Object.entries(raw)) {\n if (key === 'event_result_type') continue\n if (isZodSchema(value)) shape[key] = value\n }\n return shape as z.ZodRawShape\n}\n\nexport function normalizeEventResultType(value: unknown): z.ZodTypeAny | undefined {\n if (value === undefined || value === null) {\n return undefined\n }\n if (isZodSchema(value)) {\n return value\n }\n const constructor_schema = eventResultTypeFromConstructor(value)\n if (constructor_schema) {\n return constructor_schema\n }\n if (!isJsonSchema(value)) {\n throw new Error(`event_result_type must be a Zod schema, constructor shorthand, or JSON Schema value, got: ${typeof value}`)\n }\n return fromJsonSchema(value)\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,SAAS;AAElB,SAAS,gBAAgB,oBAAqC;AAoDvD,MAAM,wBAAwB,CAAC,kBAAoD;AACxF,MAAI,kBAAkB,KAAK;AACzB,WAAO;AAAA,EACT;AACA,MAAI,OAAO,kBAAkB,UAAU;AACrC,WAAO;AAAA,EACT;AACA,QAAM,aAAc,cAA2C;AAC/D,MAAI,OAAO,eAAe,YAAY,WAAW,SAAS,KAAK,eAAe,aAAa;AACzF,WAAO;AAAA,EACT;AACA,QAAM,aAAc,cAAqC;AACzD,MAAI,OAAO,eAAe,YAAY,WAAW,SAAS,KAAK,eAAe,aAAa;AACzF,WAAO;AAAA,EACT;AACA,MAAI;AACJ,MA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AAI,MAAM,6FAA6F,OAAO,KAAK,EAAE;AAAA,EAC7H;AACA,SAAO,eAAe,KAAK;AAC7B;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,6 +4,7 @@ import { EventResult } from './EventResult.js';
|
|
|
4
4
|
import { EventHandler } from './EventHandler.js';
|
|
5
5
|
import type { EventConcurrencyMode, EventHandlerConcurrencyMode, EventHandlerCompletionMode, Deferred } from './LockManager.js';
|
|
6
6
|
import { AsyncLock } from './LockManager.js';
|
|
7
|
+
import { type JsonSchema } from './jsonschema.js';
|
|
7
8
|
import type { EventHandlerCallable, EventResultType } from './types.js';
|
|
8
9
|
export declare const BaseEventSchema: z.ZodObject<{
|
|
9
10
|
event_id: z.ZodString;
|
|
@@ -42,7 +43,7 @@ export declare const BaseEventSchema: z.ZodObject<{
|
|
|
42
43
|
first: "first";
|
|
43
44
|
}>>>;
|
|
44
45
|
}, z.core.$loose>;
|
|
45
|
-
type AnyEventSchema = z.
|
|
46
|
+
type AnyEventSchema = z.ZodObject<z.ZodRawShape>;
|
|
46
47
|
export type BaseEventData = z.infer<typeof BaseEventSchema>;
|
|
47
48
|
export type BaseEventJSON = BaseEventData & Record<string, unknown>;
|
|
48
49
|
type BaseEventFieldName = 'event_id' | 'event_created_at' | 'event_type' | 'event_version' | 'event_timeout' | 'event_slow_timeout' | 'event_handler_timeout' | 'event_handler_slow_timeout' | 'event_blocks_parent_completion' | 'event_parent_id' | 'event_path' | 'event_result_type' | 'event_emitted_by_handler_id' | 'event_pending_bus_count' | 'event_status' | 'event_started_at' | 'event_completed_at' | 'event_results' | 'event_concurrency' | 'event_handler_concurrency' | 'event_handler_completion';
|
|
@@ -52,20 +53,54 @@ type BaseEventFields = {
|
|
|
52
53
|
export type BaseEventInit<TFields extends Record<string, unknown>> = TFields & Partial<BaseEventFields>;
|
|
53
54
|
type BaseEventSchemaShape = typeof BaseEventSchema.shape;
|
|
54
55
|
export type EventSchema<TShape extends z.ZodRawShape> = z.ZodObject<BaseEventSchemaShape & TShape>;
|
|
55
|
-
type
|
|
56
|
+
type EventPayloadShape<TShape extends z.ZodRawShape> = {
|
|
57
|
+
[K in keyof TShape as K extends BaseEventFieldName ? never : K]: TShape[K];
|
|
58
|
+
};
|
|
59
|
+
type EventPayload<TShape extends z.ZodRawShape> = EventPayloadShape<TShape> extends Record<string, never> ? {} : z.infer<z.ZodObject<EventPayloadShape<TShape>>>;
|
|
60
|
+
type EventClassMetadataFieldName = 'fromJSON' | 'prototype' | 'event_schema' | 'model_fields' | 'event_type' | 'event_version' | 'event_result_type';
|
|
61
|
+
type StaticDefaultSchema = z.ZodDefault<z.ZodTypeAny> | z.ZodPrefault<z.ZodTypeAny> | z.ZodCatch<z.ZodTypeAny>;
|
|
62
|
+
type EventModelFields<TShape extends z.ZodRawShape> = {
|
|
63
|
+
readonly [K in keyof TShape]: TShape[K];
|
|
64
|
+
};
|
|
65
|
+
type StaticEventDefaultValues<TShape extends z.ZodRawShape> = {
|
|
66
|
+
readonly [K in keyof TShape as K extends EventClassMetadataFieldName ? never : TShape[K] extends StaticDefaultSchema ? K : never]: z.output<TShape[K]>;
|
|
67
|
+
};
|
|
68
|
+
type StaticEventDefaultValuesFromSchema<TSchema extends AnyEventSchema> = TSchema extends z.ZodObject<infer TShape> ? StaticEventDefaultValues<TShape> : {};
|
|
69
|
+
type EventModelFieldsFromSchema<TSchema extends AnyEventSchema> = TSchema extends z.ZodObject<infer TShape> ? TSchema['shape'] & EventModelFields<TShape> : {};
|
|
70
|
+
type OptionalFactoryArgs<TData> = {} extends TData ? [data?: TData] : [data: TData];
|
|
56
71
|
type EventInput<TShape extends z.ZodRawShape> = z.input<EventSchema<TShape>>;
|
|
57
72
|
export type EventInit<TShape extends z.ZodRawShape> = Omit<EventInput<TShape>, keyof BaseEventFields> & Partial<BaseEventFields>;
|
|
58
|
-
type EventPayloadFromSchema<TSchema extends AnyEventSchema> = z.output<TSchema> extends Record<string, unknown> ? z.output<TSchema> : {};
|
|
73
|
+
type EventPayloadFromSchema<TSchema extends AnyEventSchema> = z.output<TSchema> extends Record<string, unknown> ? Omit<z.output<TSchema>, keyof BaseEventFields> : {};
|
|
59
74
|
type EventInputFromSchema<TSchema extends AnyEventSchema> = z.input<TSchema> extends Record<string, unknown> ? z.input<TSchema> : never;
|
|
60
75
|
export type EventInitFromSchema<TSchema extends AnyEventSchema> = Omit<EventInputFromSchema<TSchema>, keyof BaseEventFields> & Partial<BaseEventFields>;
|
|
61
76
|
type EventWithResultSchema<TResult> = BaseEvent & {
|
|
62
77
|
__event_result_type__?: TResult;
|
|
63
78
|
};
|
|
64
|
-
type
|
|
79
|
+
type NormalizedEventResultSchema<TInput> = TInput extends z.ZodTypeAny ? TInput : TInput extends z.core.$ZodType ? z.ZodType<z.output<TInput>> : TInput extends StringConstructor ? z.ZodString : TInput extends NumberConstructor ? z.ZodNumber : TInput extends BooleanConstructor ? z.ZodBoolean : TInput extends ArrayConstructor ? z.ZodArray<z.ZodUnknown> : TInput extends ObjectConstructor ? z.ZodRecord<z.ZodString, z.ZodUnknown> : TInput extends JsonSchema ? z.ZodTypeAny : z.ZodTypeAny;
|
|
80
|
+
type ResultTypeSchemaFromShape<TShape> = TShape extends {
|
|
81
|
+
event_result_type: infer S;
|
|
82
|
+
} ? NormalizedEventResultSchema<S> : z.ZodTypeAny | undefined;
|
|
83
|
+
type ResultTypeSchemaFromEventSchema<TSchema> = TSchema extends z.ZodObject<infer TShape> ? ResultTypeSchemaFromShape<TShape> : z.ZodTypeAny | undefined;
|
|
84
|
+
type ResultTypeFromEventResultTypeInput<TInput> = TInput extends z.ZodTypeAny ? z.infer<TInput> : TInput extends z.core.$ZodType ? z.output<TInput> : TInput extends StringConstructor ? string : TInput extends NumberConstructor ? number : TInput extends BooleanConstructor ? boolean : TInput extends ArrayConstructor ? unknown[] : TInput extends ObjectConstructor ? Record<string, unknown> : TInput extends JsonSchema ? unknown : unknown;
|
|
65
85
|
type ResultSchemaFromShape<TShape> = TShape extends {
|
|
66
86
|
event_result_type: infer S;
|
|
67
87
|
} ? ResultTypeFromEventResultTypeInput<S> : unknown;
|
|
68
88
|
type ResultSchemaFromEventSchema<TSchema> = TSchema extends z.ZodObject<infer TShape> ? ResultSchemaFromShape<TShape> : unknown;
|
|
89
|
+
type ZodLiteralValue = string | number | bigint | boolean | null | undefined;
|
|
90
|
+
type ShortcutDefaultModelField<K, TValue> = K extends keyof BaseEventSchemaShape ? z.ZodDefault<BaseEventSchemaShape[K]> : z.ZodDefault<TValue extends ZodLiteralValue ? z.ZodLiteral<TValue> : z.ZodType<TValue>>;
|
|
91
|
+
type ShortcutModelFields<TShape> = {
|
|
92
|
+
[K in keyof TShape as K extends 'event_result_type' ? never : K]: TShape[K] extends z.ZodTypeAny ? TShape[K] : ShortcutDefaultModelField<K, TShape[K]>;
|
|
93
|
+
} & (TShape extends {
|
|
94
|
+
event_result_type: infer TResultType;
|
|
95
|
+
} ? {
|
|
96
|
+
event_result_type: NormalizedEventResultSchema<TResultType>;
|
|
97
|
+
} : {});
|
|
98
|
+
type ShortcutZodModelFields<TShape> = {
|
|
99
|
+
[K in keyof ShortcutModelFields<TShape>]: ShortcutModelFields<TShape>[K] extends z.ZodTypeAny ? ShortcutModelFields<TShape>[K] : never;
|
|
100
|
+
};
|
|
101
|
+
type ShortcutStaticDefaultValues<TShape, TModelFields extends z.ZodRawShape> = StaticEventDefaultValues<TModelFields> & {
|
|
102
|
+
readonly [K in keyof TShape as K extends EventClassMetadataFieldName ? never : TShape[K] extends z.ZodTypeAny ? never : K]: TShape[K];
|
|
103
|
+
};
|
|
69
104
|
export type EventResultInclude<TEvent extends BaseEvent> = (result: EventResult<TEvent>['result'], event_result: EventResult<TEvent>) => boolean;
|
|
70
105
|
export type EventResultOptions<TEvent extends BaseEvent> = {
|
|
71
106
|
include?: EventResultInclude<TEvent>;
|
|
@@ -86,28 +121,15 @@ type EventResultUpdateOptions<TEvent extends BaseEvent> = {
|
|
|
86
121
|
result?: EventResultType<TEvent> | BaseEvent | undefined;
|
|
87
122
|
error?: unknown;
|
|
88
123
|
};
|
|
89
|
-
export type
|
|
90
|
-
(
|
|
91
|
-
new (
|
|
92
|
-
event_schema: EventSchema<TShape>;
|
|
93
|
-
class?: new (data: EventInit<TShape>) => EventWithResultSchema<TResult> & EventPayload<TShape>;
|
|
94
|
-
event_type?: string;
|
|
95
|
-
event_version?: string;
|
|
96
|
-
event_result_type?: z.ZodTypeAny;
|
|
97
|
-
fromJSON?: (data: unknown) => EventWithResultSchema<TResult> & EventPayload<TShape>;
|
|
98
|
-
};
|
|
99
|
-
export type SchemaEventFactory<TSchema extends AnyEventSchema, TResult = unknown> = {
|
|
100
|
-
(data: EventInitFromSchema<TSchema>): EventWithResultSchema<TResult> & EventPayloadFromSchema<TSchema>;
|
|
101
|
-
new (data: EventInitFromSchema<TSchema>): EventWithResultSchema<TResult> & EventPayloadFromSchema<TSchema>;
|
|
124
|
+
export type EventClass<TEvent extends BaseEvent = BaseEvent, TInit = never, TSchema extends z.ZodTypeAny = AnyEventSchema, TModelFields extends z.ZodRawShape = z.ZodRawShape, TResultSchema extends z.ZodTypeAny | undefined = z.ZodTypeAny | undefined, TStaticFields = {}> = TStaticFields & {
|
|
125
|
+
(...args: OptionalFactoryArgs<TInit>): TEvent;
|
|
126
|
+
new (...args: OptionalFactoryArgs<TInit>): TEvent;
|
|
102
127
|
event_schema: TSchema;
|
|
103
|
-
|
|
104
|
-
event_type
|
|
105
|
-
event_version
|
|
106
|
-
event_result_type
|
|
107
|
-
fromJSON
|
|
108
|
-
};
|
|
109
|
-
type ZodShapeFrom<TShape extends Record<string, unknown>> = {
|
|
110
|
-
[K in keyof TShape as K extends 'event_result_type' ? never : TShape[K] extends z.ZodTypeAny ? K : never]: Extract<TShape[K], z.ZodTypeAny>;
|
|
128
|
+
model_fields: TModelFields;
|
|
129
|
+
event_type: string;
|
|
130
|
+
event_version: string;
|
|
131
|
+
event_result_type: TResultSchema;
|
|
132
|
+
fromJSON: (data: unknown) => TEvent;
|
|
111
133
|
};
|
|
112
134
|
export declare class BaseEvent {
|
|
113
135
|
event_id: string;
|
|
@@ -132,10 +154,13 @@ export declare class BaseEvent {
|
|
|
132
154
|
event_handler_concurrency?: EventHandlerConcurrencyMode | null;
|
|
133
155
|
event_handler_completion?: EventHandlerCompletionMode | null;
|
|
134
156
|
event_schema?: z.ZodTypeAny;
|
|
157
|
+
_event_parse_schema?: z.ZodTypeAny;
|
|
135
158
|
static event_type?: string;
|
|
136
159
|
static event_version: string;
|
|
137
160
|
static event_result_type?: z.ZodTypeAny;
|
|
138
161
|
static event_schema: AnyEventSchema;
|
|
162
|
+
static model_fields: z.ZodRawShape;
|
|
163
|
+
static _event_parse_schema: AnyEventSchema;
|
|
139
164
|
event_bus?: EventBus;
|
|
140
165
|
_event_original?: BaseEvent;
|
|
141
166
|
_event_dispatch_context?: unknown | null;
|
|
@@ -144,9 +169,9 @@ export declare class BaseEvent {
|
|
|
144
169
|
_lock_for_event_handler: AsyncLock | null;
|
|
145
170
|
constructor(data?: BaseEventInit<Record<string, unknown>>);
|
|
146
171
|
toString(): string;
|
|
147
|
-
static extend<TSchema extends z.ZodObject<z.ZodRawShape>>(event_type: string, event_schema: TSchema):
|
|
148
|
-
static extend<TShape extends
|
|
149
|
-
static extend<TShape extends
|
|
172
|
+
static extend<TSchema extends z.ZodObject<z.ZodRawShape>>(event_type: string, event_schema: TSchema): EventClass<EventWithResultSchema<ResultSchemaFromEventSchema<TSchema>> & EventPayloadFromSchema<TSchema>, EventInitFromSchema<TSchema>, TSchema, EventModelFieldsFromSchema<TSchema>, ResultTypeSchemaFromEventSchema<TSchema>, StaticEventDefaultValuesFromSchema<TSchema>>;
|
|
173
|
+
static extend<const TShape extends Record<string, unknown>>(event_type: string, shape?: TShape): EventClass<EventWithResultSchema<ResultSchemaFromShape<ShortcutZodModelFields<TShape>>> & EventPayload<ShortcutZodModelFields<TShape>>, EventInit<ShortcutZodModelFields<TShape>>, EventSchema<ShortcutZodModelFields<TShape>>, EventModelFields<ShortcutZodModelFields<TShape>>, ResultTypeSchemaFromShape<ShortcutZodModelFields<TShape>>, ShortcutStaticDefaultValues<TShape, ShortcutZodModelFields<TShape>>>;
|
|
174
|
+
static extend<TShape extends z.ZodRawShape>(event_type: string, shape?: TShape): EventClass<EventWithResultSchema<ResultSchemaFromShape<TShape>> & EventPayload<TShape>, EventInit<TShape>, EventSchema<TShape>, EventModelFields<TShape>, ResultTypeSchemaFromShape<TShape>, StaticEventDefaultValues<TShape>>;
|
|
150
175
|
static fromJSON<T extends typeof BaseEvent>(this: T, data: unknown): InstanceType<T>;
|
|
151
176
|
static toJSONArray(events: Iterable<BaseEvent>): BaseEventJSON[];
|
|
152
177
|
static fromJSONArray(data: unknown): BaseEvent[];
|
|
@@ -1,28 +1,21 @@
|
|
|
1
1
|
import { EventBus } from './EventBus.js';
|
|
2
2
|
import { BaseEvent } from './BaseEvent.js';
|
|
3
3
|
import type { EventClass, EventResultType } from './types.js';
|
|
4
|
-
type EventMap = Record<string, EventClass<BaseEvent>>;
|
|
5
|
-
type
|
|
6
|
-
type FunctionMap = Record<string, AnyFn>;
|
|
4
|
+
type EventMap = Record<string, EventClass<BaseEvent, never>>;
|
|
5
|
+
type FunctionMap = Record<string, (...args: never[]) => unknown>;
|
|
7
6
|
type ExtraDict = Record<string, unknown>;
|
|
8
|
-
type EventFieldsFromFn<TFunc extends
|
|
9
|
-
type
|
|
10
|
-
|
|
11
|
-
__event_result_type__?: Awaited<ReturnType<TFunc>>;
|
|
12
|
-
};
|
|
13
|
-
new (data: EventFieldsFromFn<TFunc> & ExtraDict): BaseEvent & EventFieldsFromFn<TFunc> & {
|
|
14
|
-
__event_result_type__?: Awaited<ReturnType<TFunc>>;
|
|
15
|
-
};
|
|
16
|
-
event_type?: string;
|
|
7
|
+
type EventFieldsFromFn<TFunc extends FunctionMap[string]> = Parameters<TFunc> extends [infer TArg, ...unknown[]] ? (TArg extends Record<string, unknown> ? TArg : ExtraDict) : ExtraDict;
|
|
8
|
+
type EventFromFn<TFunc extends FunctionMap[string]> = BaseEvent & EventFieldsFromFn<TFunc> & {
|
|
9
|
+
__event_result_type__?: Awaited<ReturnType<TFunc>>;
|
|
17
10
|
};
|
|
18
11
|
export type GeneratedEvents<TEvents extends FunctionMap> = {
|
|
19
12
|
by_name: {
|
|
20
|
-
[K in keyof TEvents]:
|
|
13
|
+
[K in keyof TEvents]: EventClass<EventFromFn<TEvents[K]>, EventFieldsFromFn<TEvents[K]> & ExtraDict>;
|
|
21
14
|
};
|
|
22
15
|
} & {
|
|
23
|
-
[K in keyof TEvents]:
|
|
16
|
+
[K in keyof TEvents]: EventClass<EventFromFn<TEvents[K]>, EventFieldsFromFn<TEvents[K]> & ExtraDict>;
|
|
24
17
|
};
|
|
25
|
-
type EventInit<TEventClass extends EventClass<BaseEvent>> = ConstructorParameters<TEventClass> extends [
|
|
18
|
+
type EventInit<TEventClass extends EventClass<BaseEvent>> = [ConstructorParameters<TEventClass>[0]] extends [undefined] ? {} : NonNullable<ConstructorParameters<TEventClass>[0]>;
|
|
26
19
|
type EventMethodArgs<TEventClass extends EventClass<BaseEvent>> = {} extends EventInit<TEventClass> ? [init?: EventInit<TEventClass>, extra?: Record<string, unknown>] : [init: EventInit<TEventClass>, extra?: Record<string, unknown>];
|
|
27
20
|
type EventMethodResult<TEventClass extends EventClass<BaseEvent>> = EventResultType<InstanceType<TEventClass>> | undefined;
|
|
28
21
|
export type EventsSuckClient<TEvents extends EventMap> = {
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export type JsonSchema = boolean | z.core.JSONSchema.JSONSchema;
|
|
3
|
+
export declare const isJsonSchema: (value: unknown) => value is JsonSchema;
|
|
4
|
+
export declare const normalizeJsonSchema: (schema: JsonSchema) => JsonSchema;
|
|
5
|
+
export declare const toJsonSchema: (schema: z.core.$ZodType) => JsonSchema;
|
|
6
|
+
export declare const fromJsonSchema: (schema: JsonSchema) => z.ZodTypeAny;
|
package/dist/types/retry.d.ts
CHANGED
|
@@ -19,6 +19,8 @@ export interface RetryOptions {
|
|
|
19
19
|
retry_on_errors?: Array<(new (...args: any[]) => Error) | string | RegExp>;
|
|
20
20
|
/** Per-attempt timeout in seconds. Default: undefined (no per-attempt timeout) */
|
|
21
21
|
timeout?: number | null;
|
|
22
|
+
/** Emit a warning when a decorated call exceeds this many seconds. Default: undefined (disabled) */
|
|
23
|
+
slow_timeout?: number | null;
|
|
22
24
|
/** Maximum concurrent executions sharing this semaphore. Default: undefined (no concurrency limit) */
|
|
23
25
|
semaphore_limit?: number | null;
|
|
24
26
|
/** Semaphore identifier. Functions with the same name share the same concurrency slot pool. Default: function name.
|
package/dist/types/types.d.ts
CHANGED
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
|
-
import type { BaseEvent } from './BaseEvent.js';
|
|
2
|
+
import type { BaseEvent, EventClass as BaseEventClass } from './BaseEvent.js';
|
|
3
|
+
import { type JsonSchema } from './jsonschema.js';
|
|
3
4
|
export type EventStatus = 'pending' | 'started' | 'completed';
|
|
4
|
-
export type EventClass
|
|
5
|
-
|
|
6
|
-
} & (new (...args: any[]) => T);
|
|
7
|
-
export type EventPattern<T extends BaseEvent = BaseEvent> = string | EventClass<T>;
|
|
5
|
+
export type { EventClass } from './BaseEvent.js';
|
|
6
|
+
export type EventPattern<T extends BaseEvent = BaseEvent> = string | BaseEventClass<T>;
|
|
8
7
|
export type EventWithResultSchema<TResult> = BaseEvent & {
|
|
9
8
|
__event_result_type__?: TResult;
|
|
10
9
|
};
|
|
@@ -12,7 +11,7 @@ export type EventResultType<TEvent extends BaseEvent> = TEvent extends {
|
|
|
12
11
|
__event_result_type__?: infer TResult;
|
|
13
12
|
} ? TResult : unknown;
|
|
14
13
|
export type EventResultTypeConstructor = StringConstructor | NumberConstructor | BooleanConstructor | ArrayConstructor | ObjectConstructor;
|
|
15
|
-
export type EventResultTypeInput = z.ZodTypeAny | EventResultTypeConstructor |
|
|
14
|
+
export type EventResultTypeInput = z.ZodTypeAny | EventResultTypeConstructor | JsonSchema;
|
|
16
15
|
export type EventHandlerReturn<T extends BaseEvent = BaseEvent> = EventResultType<T> | BaseEvent | null | void;
|
|
17
16
|
export type EventHandlerCallable<T extends BaseEvent = BaseEvent> = (event: T) => EventHandlerReturn<T> | Promise<EventHandlerReturn<T>>;
|
|
18
17
|
export type UntypedEventHandlerFunction<T extends BaseEvent = BaseEvent> = (event: T) => EventHandlerReturn<T> | unknown | Promise<EventHandlerReturn<T> | unknown>;
|
|
@@ -33,7 +32,4 @@ export declare const normalizeEventPattern: (event_pattern: EventPattern | "*")
|
|
|
33
32
|
export declare const isZodSchema: (value: unknown) => value is z.ZodTypeAny;
|
|
34
33
|
export declare const eventResultTypeFromConstructor: (value: unknown) => z.ZodTypeAny | undefined;
|
|
35
34
|
export declare const extractZodShape: (raw: Record<string, unknown>) => z.ZodRawShape;
|
|
36
|
-
export declare
|
|
37
|
-
export declare const fromJsonSchema: (schema: unknown) => z.ZodTypeAny;
|
|
38
|
-
export declare const normalizeEventResultType: (value: EventResultTypeInput) => z.ZodTypeAny | undefined;
|
|
39
|
-
export {};
|
|
35
|
+
export declare function normalizeEventResultType(value: unknown): z.ZodTypeAny | undefined;
|