@chronos.sh/sdk 0.0.1

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../src/errors.ts","../src/internal/logger.ts","../src/internal/validate.ts","../src/client.ts","../src/worker.ts","../src/index.ts"],"sourcesContent":["/**\n * Base class for all errors thrown by the Chronos SDK. Catch this in a\n * single `catch` to handle any SDK failure generically; use the subclasses\n * to branch on cause.\n *\n * @example\n * ```ts\n * import { Chronos, ChronosError } from '@chronos.sh/sdk';\n *\n * const chronos = new Chronos({ apiKey: 'chrns_...' });\n * try {\n * await chronos.worker.start();\n * } catch (err) {\n * if (err instanceof ChronosError) {\n * console.error('Chronos failed:', err.message);\n * }\n * }\n * ```\n */\nexport class ChronosError extends Error {\n /** Original error/value that caused this SDK error, when one is available. */\n declare readonly cause?: unknown;\n\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options);\n this.name = 'ChronosError';\n\n if (options && !('cause' in this)) {\n Object.defineProperty(this, 'cause', {\n value: options.cause,\n configurable: true,\n writable: true,\n });\n }\n }\n}\n\n/**\n * Thrown when SDK options fail validation at `new Chronos({ ... })`. Covers\n * `apiKey`, `baseUrl`, `pollWaitTimeSeconds`, and `retryDelayMs`.\n *\n * @example\n * ```ts\n * import { Chronos, ChronosConfigError } from '@chronos.sh/sdk';\n *\n * try {\n * const chronos = new Chronos({ apiKey: '' });\n * } catch (err) {\n * if (err instanceof ChronosConfigError) {\n * console.error('Invalid Chronos config:', err.message);\n * }\n * }\n * ```\n */\nexport class ChronosConfigError extends ChronosError {\n constructor(message: string) {\n super(message);\n this.name = 'ChronosConfigError';\n }\n}\n\n/** Options for constructing a {@link ChronosApiError}. */\nexport type ChronosApiErrorOptions = {\n /** HTTP status code returned by the Chronos API. */\n status: number;\n /** Application-level error code from the response envelope, when present. */\n code?: string;\n /** Full parsed response payload (envelope + data, or whatever the server returned). */\n body?: unknown;\n /** Value of the `X-Request-Id` response header, when present. Pair with server logs. */\n requestId?: string;\n};\n\n/**\n * Thrown when the Chronos API responds with a non-2xx status or a\n * `success: false` envelope. Carries HTTP `status`, the application\n * `code`, parsed `body`, and the API's `X-Request-Id`.\n *\n * `instanceof ChronosApiError` means the server replied;\n * network/transport failures throw {@link ChronosNetworkError} instead.\n *\n * @example\n * ```ts\n * import { ChronosApiError } from '@chronos.sh/sdk';\n *\n * function handleSdkError(err: unknown) {\n * if (err instanceof ChronosApiError) {\n * if (err.status === 401) return refreshAuth();\n * console.error('API error', { status: err.status, requestId: err.requestId });\n * }\n * }\n * ```\n */\nexport class ChronosApiError extends ChronosError {\n /** HTTP status code returned by the Chronos API. */\n readonly status: number;\n /** Application-level error code from the response envelope, when present. */\n readonly code?: string;\n /** Full parsed response payload (envelope + data, or whatever the server returned). */\n readonly body?: unknown;\n /** Value of the `X-Request-Id` response header, when present. */\n readonly requestId?: string;\n\n constructor(message: string, options: ChronosApiErrorOptions) {\n super(message);\n this.name = 'ChronosApiError';\n this.status = options.status;\n this.code = options.code;\n this.body = options.body;\n this.requestId = options.requestId;\n }\n}\n\n/**\n * Thrown when the underlying `fetch` rejects before the server replies —\n * DNS failure, TCP reset, connection refused, etc. The original error is\n * available on `.cause`.\n *\n * Abort signals propagate unwrapped — `instanceof ChronosNetworkError`\n * always means a real transport failure, not a graceful shutdown.\n *\n * @example\n * ```ts\n * import { ChronosNetworkError } from '@chronos.sh/sdk';\n *\n * function handleSdkError(err: unknown) {\n * if (err instanceof ChronosNetworkError) {\n * console.warn('Transport blip', { cause: err.cause });\n * }\n * }\n * ```\n */\nexport class ChronosNetworkError extends ChronosError {\n /** Original error/value rejected by the underlying `fetch`. */\n declare readonly cause: unknown;\n\n constructor(message: string, options: { cause: unknown }) {\n super(message, options);\n this.name = 'ChronosNetworkError';\n }\n}\n\n/**\n * Wraps an exception thrown by a user-supplied {@link ChronosHandler}. The\n * original error is on `.cause`; `.message` is copied from the original so\n * the SDK reports it to the API as the failure reason.\n *\n * @example\n * ```ts\n * import { ChronosHandlerError } from '@chronos.sh/sdk';\n *\n * if (err instanceof ChronosHandlerError) {\n * console.error('Handler threw', err.cause);\n * }\n * ```\n */\nexport class ChronosHandlerError extends ChronosError {\n /** Original error/value thrown by the user-supplied handler. */\n declare readonly cause: unknown;\n\n constructor(message: string, options: { cause: unknown }) {\n super(message, options);\n this.name = 'ChronosHandlerError';\n }\n}\n","import type { ChronosLogger } from '../types';\n\nexport const defaultLogger: ChronosLogger = {\n debug: (message, meta) => logToConsole(console.debug, message, meta),\n info: (message, meta) => logToConsole(console.info, message, meta),\n warn: (message, meta) => logToConsole(console.warn, message, meta),\n error: (message, meta) => logToConsole(console.error, message, meta),\n};\n\nfunction logToConsole(\n method: (message?: unknown, ...optionalParams: unknown[]) => void,\n message: string,\n meta?: Record<string, unknown>,\n): void {\n if (meta) {\n method(message, meta);\n } else {\n method(message);\n }\n}\n","import { ChronosConfigError, ChronosError } from '../errors';\n\nexport const MAX_HANDLER_NAME_LENGTH = 255;\nexport const MAX_POLL_WAIT_TIME_SECONDS = 20;\n\nexport function validateApiKey(apiKey: string | undefined): string {\n const trimmed = apiKey?.trim();\n if (!trimmed) {\n throw new ChronosConfigError('Chronos apiKey is required');\n }\n return trimmed;\n}\n\nexport function validatePollWaitTime(seconds: number): void {\n if (!Number.isInteger(seconds) || seconds < 0 || seconds > MAX_POLL_WAIT_TIME_SECONDS) {\n throw new ChronosConfigError(\n `pollWaitTimeSeconds must be an integer between 0 and ${MAX_POLL_WAIT_TIME_SECONDS}`,\n );\n }\n}\n\nexport function validateRetryDelayMs(ms: number): void {\n if (!Number.isFinite(ms) || ms < 0) {\n throw new ChronosConfigError('retryDelayMs must be a non-negative number');\n }\n}\n\nexport function normalizeHandlerName(name: string): string {\n const normalized = name.trim();\n\n if (!normalized) {\n throw new ChronosError('Handler name is required');\n }\n\n if (normalized.length > MAX_HANDLER_NAME_LENGTH) {\n throw new ChronosError(`Handler name must be ${MAX_HANDLER_NAME_LENGTH} characters or fewer`);\n }\n\n return normalized;\n}\n","import { ChronosApiError, ChronosConfigError, ChronosError, ChronosNetworkError } from './errors';\nimport { defaultLogger } from './internal/logger';\nimport { validateApiKey } from './internal/validate';\nimport type { ChronosLogger, ChronosOptions, FetchLike } from './types';\n\n/** Default Chronos API base URL. */\nexport const DEFAULT_BASE_URL = 'https://api.chronos.sh';\n\ntype ApiResponse<T> = {\n success: boolean;\n message?: string;\n code?: string;\n data: T;\n};\n\nexport class BaseClient {\n readonly apiKey: string;\n readonly baseUrl: string;\n readonly fetch: FetchLike;\n readonly logger: ChronosLogger;\n private readonly headers: Record<string, string>;\n\n constructor(options: ChronosOptions) {\n this.apiKey = validateApiKey(options.apiKey);\n this.baseUrl = normalizeBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL);\n this.fetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.logger = options.logger ?? defaultLogger;\n this.headers = {\n 'content-type': 'application/json',\n authorization: `Bearer ${this.apiKey}`,\n };\n }\n\n async request<T>(path: string, body: Record<string, unknown>, signal?: AbortSignal): Promise<T> {\n let response: Response;\n try {\n response = await this.fetch(`${this.baseUrl}${path}`, {\n method: 'POST',\n headers: this.headers,\n body: JSON.stringify(body),\n signal,\n });\n } catch (err) {\n if (signal?.aborted) {\n throw err;\n }\n const message = err instanceof Error ? err.message : String(err);\n throw new ChronosNetworkError(`Chronos API request failed: ${message}`, { cause: err });\n }\n\n const payload = await parseJsonResponse<ApiResponse<T>>(response);\n const envelope = isEnvelope(payload) ? (payload as ApiResponse<T>) : undefined;\n\n if (!response.ok || (envelope && !envelope.success)) {\n throw new ChronosApiError(apiErrorMessage(response, envelope), {\n status: response.status,\n code: typeof envelope?.code === 'string' ? envelope.code : undefined,\n body: payload,\n requestId: response.headers.get('x-request-id') ?? undefined,\n });\n }\n\n if (!envelope) {\n // Plain ChronosError, not ChronosApiError — a malformed 200 body is\n // an infrastructure anomaly that should be retried, not a definitive\n // API rejection.\n throw new ChronosError('Chronos API returned an invalid response');\n }\n\n return envelope.data;\n }\n}\n\nfunction normalizeBaseUrl(baseUrl: string): string {\n const normalized = baseUrl.trim().replace(/\\/+$/, '');\n if (!normalized) {\n throw new ChronosConfigError('Chronos baseUrl is required');\n }\n return normalized;\n}\n\nasync function parseJsonResponse<T>(response: Response): Promise<T | null> {\n try {\n return (await response.json()) as T;\n } catch {\n return null;\n }\n}\n\nfunction apiErrorMessage(\n response: Response,\n envelope: Record<string, unknown> | undefined,\n): string {\n if (typeof envelope?.message === 'string' && envelope.message.trim()) {\n return envelope.message;\n }\n\n return response.ok\n ? 'Chronos API returned an invalid response'\n : `Chronos API request failed with status ${response.status}`;\n}\n\n// Malformed bodies (arrays, primitives, missing `success`) are routed to the\n// invalid-response path, not classified as API errors.\nfunction isEnvelope(value: unknown): value is Record<string, unknown> & { success: boolean } {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n return typeof (value as Record<string, unknown>).success === 'boolean';\n}\n","import type { BaseClient } from './client';\nimport { ChronosApiError, ChronosError, ChronosHandlerError, ChronosNetworkError } from './errors';\nimport {\n normalizeHandlerName,\n validatePollWaitTime,\n validateRetryDelayMs,\n} from './internal/validate';\nimport type {\n ChronosContext,\n ChronosHandler,\n ChronosHandlerResult,\n ChronosOptions,\n ChronosSchedule,\n} from './types';\n\n/** Default worker long-poll wait time in seconds. Equal to the API maximum. */\nexport const DEFAULT_POLL_WAIT_TIME_SECONDS = 20;\nconst DEFAULT_RETRY_DELAY_MS = 1_000;\nconst RESULT_REPORT_MAX_ATTEMPTS = 3;\nconst MAX_REPORTED_ERROR_LENGTH = 4_096;\nconst DEFAULT_HANDLER_ERROR = 'Chronos handler failed';\n\ntype ResultStatus = 'completed' | 'failed';\n\ntype ClaimedJob = {\n job_id: string;\n execution_id: string;\n handler: string;\n scheduled_for: string;\n attempt: number;\n timeout: number;\n payload: unknown;\n schedule: ChronosSchedule | null;\n};\n\n/**\n * Long-poll worker. Claims jobs from the Chronos API, dispatches them to\n * registered handlers, and reports results.\n *\n * Construct via `new Chronos({ apiKey }).worker` rather than directly.\n */\nexport class Worker {\n private readonly client: BaseClient;\n private readonly pollWaitTimeSeconds: number;\n private readonly retryDelayMs: number;\n private readonly handlers = new Map<string, ChronosHandler<unknown>>();\n private handlerNames: string[] = [];\n private startPromise?: Promise<void>;\n private pollController?: AbortController;\n\n constructor(client: BaseClient, options: ChronosOptions) {\n this.client = client;\n this.pollWaitTimeSeconds = options.pollWaitTimeSeconds ?? DEFAULT_POLL_WAIT_TIME_SECONDS;\n this.retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n\n validatePollWaitTime(this.pollWaitTimeSeconds);\n validateRetryDelayMs(this.retryDelayMs);\n }\n\n /**\n * Register a handler for a named job type. Invoked when the Chronos API\n * claims a job whose `handler` field matches `name`. Names are trimmed and\n * must be 1–255 characters.\n *\n * @param name - Handler name. Must match the schedule's `handler` on the API side.\n * @param handler - Async function invoked with the job context. Return a\n * plain object to record a result, or `undefined` for none.\n * @returns The Worker, for chaining.\n * @throws {ChronosError} If the name is invalid, already registered, or `handler` is not a function.\n *\n * @example\n * ```ts\n * chronos.worker\n * .handle('send-email', async (ctx) => ({ sent: true }))\n * .handle('cleanup', async () => undefined);\n * ```\n */\n handle<TPayload = unknown>(name: string, handler: ChronosHandler<TPayload>): this {\n const normalizedName = normalizeHandlerName(name);\n\n if (this.handlers.has(normalizedName)) {\n throw new ChronosError(`Handler \"${normalizedName}\" is already registered`);\n }\n\n if (typeof handler !== 'function') {\n throw new ChronosError(`Handler \"${normalizedName}\" must be a function`);\n }\n\n this.handlers.set(normalizedName, handler as ChronosHandler<unknown>);\n this.handlerNames.push(normalizedName);\n return this;\n }\n\n /**\n * Begin long-polling for jobs. The returned promise resolves when\n * {@link Worker.stop} is called and any in-flight job completes.\n *\n * @throws {ChronosError} Synchronously, if no handlers are registered or the worker is already running.\n */\n start(): Promise<void> {\n if (this.startPromise) {\n throw new ChronosError('Chronos worker is already started');\n }\n\n if (this.handlers.size === 0) {\n throw new ChronosError('Register at least one handler before starting Chronos');\n }\n\n this.pollController = new AbortController();\n this.startPromise = this.runLoop().finally(() => {\n this.startPromise = undefined;\n this.pollController = undefined;\n });\n\n return this.startPromise;\n }\n\n /**\n * Request graceful shutdown. The poll loop is aborted immediately; any\n * in-flight handler and result-report are allowed to complete to preserve\n * at-least-once delivery. Returns the same promise as the active\n * {@link Worker.start}, or a resolved promise if the worker isn't running.\n */\n stop(): Promise<void> {\n this.pollController?.abort();\n return this.startPromise ?? Promise.resolve();\n }\n\n private get isStopped(): boolean {\n return this.pollController?.signal.aborted ?? true;\n }\n\n private async runLoop(): Promise<void> {\n while (!this.isStopped) {\n try {\n const job = await this.claimJob();\n if (job) {\n await this.processJob(job);\n }\n } catch (err) {\n if (this.isStopped) {\n break;\n }\n\n this.client.logger.error('Chronos poll loop error', { err: errorToLogValue(err) });\n await sleep(this.retryDelayMs, this.pollController?.signal);\n }\n }\n }\n\n private async claimJob(): Promise<ClaimedJob | null> {\n if (this.handlerNames.length === 0) {\n throw new ChronosError('Cannot claim jobs without registered handlers');\n }\n\n return this.client.request<ClaimedJob | null>(\n '/v1/worker/jobs/claim',\n {\n wait_time_seconds: this.pollWaitTimeSeconds,\n handlers: this.handlerNames,\n },\n this.pollController?.signal,\n );\n }\n\n private async processJob(job: ClaimedJob): Promise<void> {\n const handler = this.handlers.get(job.handler);\n if (!handler) {\n return this.handleUnregisteredJob(job);\n }\n\n let handlerResult: ChronosHandlerResult;\n try {\n handlerResult = await handler(createContext(job));\n } catch (err) {\n const message = errorMessage(err);\n const handlerErr = new ChronosHandlerError(message, { cause: err });\n this.client.logger.error('Chronos handler failed', {\n ...jobLogMeta(job),\n err: errorToLogValue(handlerErr),\n });\n await this.safeReportFailed(job, message);\n return;\n }\n\n let result: Record<string, unknown> | undefined;\n try {\n result = normalizeHandlerResult(handlerResult);\n } catch (err) {\n this.client.logger.error('Chronos handler returned invalid result', {\n ...jobLogMeta(job),\n err: errorToLogValue(err),\n });\n await this.safeReportFailed(job, errorMessage(err));\n return;\n }\n\n try {\n await this.reportCompleted(job.execution_id, result);\n } catch (err) {\n this.logResultReportFailure(err, job, 'completed');\n }\n }\n\n private async handleUnregisteredJob(job: ClaimedJob): Promise<void> {\n const message = `Chronos SDK received job for unregistered handler \"${job.handler}\"`;\n this.client.logger.error(message, jobLogMeta(job));\n await this.safeReportFailed(job, message);\n }\n\n private async safeReportFailed(job: ClaimedJob, message: string): Promise<void> {\n try {\n await this.reportFailed(job.execution_id, message);\n } catch (err) {\n this.logResultReportFailure(err, job, 'failed');\n }\n }\n\n private async reportCompleted(\n executionId: string,\n result: Record<string, unknown> | undefined,\n ): Promise<void> {\n await this.reportResultWithRetry(executionId, {\n status: 'completed',\n ...(result === undefined ? {} : { result }),\n });\n }\n\n private async reportFailed(executionId: string, error: string): Promise<void> {\n await this.reportResultWithRetry(executionId, {\n status: 'failed',\n error: truncate(error, MAX_REPORTED_ERROR_LENGTH),\n });\n }\n\n private async reportResultWithRetry(\n executionId: string,\n body: Record<string, unknown>,\n ): Promise<void> {\n let lastErr: unknown;\n\n for (let attempt = 1; attempt <= RESULT_REPORT_MAX_ATTEMPTS; attempt++) {\n try {\n await this.client.request(\n `/v1/worker/executions/${encodeURIComponent(executionId)}/result`,\n body,\n );\n return;\n } catch (err) {\n const apiErr = err instanceof ChronosApiError ? err : undefined;\n\n if (apiErr?.status === 409) {\n this.client.logger.warn('Chronos result discarded; execution already terminal', {\n executionId,\n status: body.status,\n code: apiErr.code,\n });\n return;\n }\n\n if (apiErr && isTerminalReportError(apiErr.status)) {\n throw apiErr;\n }\n\n lastErr = err;\n if (attempt === RESULT_REPORT_MAX_ATTEMPTS) {\n break;\n }\n\n this.client.logger.warn('Chronos result report failed; retrying', {\n err: errorToLogValue(err),\n executionId,\n status: body.status,\n attempt,\n maxAttempts: RESULT_REPORT_MAX_ATTEMPTS,\n });\n await sleep(this.retryDelayMs);\n }\n }\n\n throw lastErr;\n }\n\n private logResultReportFailure(err: unknown, job: ClaimedJob, status: ResultStatus): void {\n const isTerminal = err instanceof ChronosApiError && isTerminalReportError(err.status);\n this.client.logger.error(\n isTerminal\n ? 'Chronos result report rejected by API'\n : 'Chronos result report failed after retries',\n { ...jobLogMeta(job), err: errorToLogValue(err), status },\n );\n }\n}\n\nfunction createContext(job: ClaimedJob): ChronosContext<unknown> {\n return {\n jobId: job.job_id,\n executionId: job.execution_id,\n handler: job.handler,\n payload: job.payload,\n scheduledFor: new Date(job.scheduled_for),\n attempt: job.attempt,\n timeout: job.timeout,\n schedule: job.schedule,\n };\n}\n\nfunction jobLogMeta(job: ClaimedJob): Record<string, unknown> {\n return {\n jobId: job.job_id,\n executionId: job.execution_id,\n handler: job.handler,\n };\n}\n\nfunction normalizeHandlerResult(result: ChronosHandlerResult): Record<string, unknown> | undefined {\n if (result === undefined) {\n return undefined;\n }\n\n if (!isPlainObject(result)) {\n throw new ChronosError('Chronos handler result must be a plain object or undefined');\n }\n\n try {\n JSON.stringify(result);\n } catch (err) {\n const reason = err instanceof Error ? err.message : 'value is not JSON-encodable';\n throw new ChronosError(`Chronos handler result is not JSON-encodable: ${reason}`);\n }\n\n return result;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) {\n return false;\n }\n\n const proto = Object.getPrototypeOf(value);\n return proto === Object.prototype || proto === null;\n}\n\nfunction errorMessage(err: unknown): string {\n const message = err instanceof Error ? err.message : String(err);\n return message.trim() || DEFAULT_HANDLER_ERROR;\n}\n\nfunction errorToLogValue(err: unknown): unknown {\n if (!(err instanceof Error)) {\n return err;\n }\n\n const base = { name: err.name, message: err.message, stack: err.stack };\n\n if (err instanceof ChronosApiError) {\n return { ...base, status: err.status, code: err.code, requestId: err.requestId };\n }\n if (err instanceof ChronosNetworkError || err instanceof ChronosHandlerError) {\n return { ...base, cause: errorToLogValue(err.cause) };\n }\n return base;\n}\n\nfunction truncate(value: string, maxLength: number): string {\n return value.length <= maxLength ? value : value.slice(0, maxLength);\n}\n\n// 409 is handled by the caller before reaching here; 408/429 are transient.\nconst NON_TERMINAL_4XX = new Set([408, 409, 429]);\n\n// 200 reaches here only via an explicit `{ success: false }` envelope from BaseClient.\nfunction isTerminalReportError(status: number): boolean {\n if (status === 200) {\n return true;\n }\n if (NON_TERMINAL_4XX.has(status)) {\n return false;\n }\n return status >= 400 && status < 500;\n}\n\nfunction sleep(ms: number, signal?: AbortSignal): Promise<void> {\n if (signal?.aborted) {\n return Promise.resolve();\n }\n\n return new Promise((resolve) => {\n const timeout: ReturnType<typeof setTimeout> = setTimeout(done, ms);\n\n function done() {\n clearTimeout(timeout);\n signal?.removeEventListener('abort', done);\n resolve();\n }\n\n signal?.addEventListener('abort', done, { once: true });\n });\n}\n","import { BaseClient, DEFAULT_BASE_URL } from './client';\nimport type { ChronosOptions } from './types';\nimport { DEFAULT_POLL_WAIT_TIME_SECONDS, Worker } from './worker';\n\n/**\n * The Chronos SDK client. Composes worker and (future) REST resource\n * subclients from a single instance.\n *\n * @example\n * ```ts\n * import { Chronos } from '@chronos.sh/sdk';\n *\n * const chronos = new Chronos({ apiKey: process.env.CHRONOS_API_KEY! });\n *\n * chronos.worker.handle<{ to: string }>('send-email', async (ctx) => {\n * await sendEmail(ctx.payload.to);\n * return { sent: true };\n * });\n *\n * await chronos.worker.start();\n * ```\n */\nexport class Chronos {\n /** Long-poll worker for executing pull-mode jobs. */\n readonly worker: Worker;\n\n /**\n * @param options - Client configuration. Only `apiKey` is required.\n * @throws {ChronosConfigError} If `apiKey` is missing or any option fails validation.\n */\n constructor(options: ChronosOptions) {\n const client = new BaseClient(options);\n this.worker = new Worker(client, options);\n }\n}\n\nexport {\n ChronosApiError,\n type ChronosApiErrorOptions,\n ChronosConfigError,\n ChronosError,\n ChronosHandlerError,\n ChronosNetworkError,\n} from './errors';\nexport type {\n ChronosContext,\n ChronosHandler,\n ChronosHandlerResult,\n Chron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AAS,sBAAsB,QAAyB;AACtD,KAAI,WAAW,IACb,QAAO;AAET,KAAI,iBAAiB,IAAI,OAAO,CAC9B,QAAO;AAET,QAAO,UAAU,OAAO,SAAS;;AAGnC,SAAS,MAAM,IAAY,QAAqC;AAC9D,KAAI,QAAQ,QACV,QAAO,QAAQ,SAAS;AAG1B,QAAO,IAAI,SAAS,YAAY;EAC9B,MAAM,UAAyC,WAAW,MAAM,GAAG;EAEnE,SAAS,OAAO;AACd,gBAAa,QAAQ;AACrB,WAAQ,oBAAoB,SAAS,KAAK;AAC1C,YAAS;;AAGX,UAAQ,iBAAiB,SAAS,MAAM,EAAE,MAAM,MAAM,CAAC;GACvD;;;;;;;;;;;;;;;;;;;;;;ACvXJ,IAAa,UAAb,MAAqB;;CAEnB;;;;;CAMA,YAAY,SAAyB;EACnC,MAAM,SAAS,IAAI,WAAW,QAAQ;AACtC,OAAK,SAAS,IAAI,OAAO,QAAQ,QAAQ"}
@@ -0,0 +1,323 @@
1
+ //#region src/types.d.ts
2
+ /**
3
+ * Result returned by a {@link ChronosHandler}. Plain objects are recorded on
4
+ * the execution; `void` / `undefined` records no result.
5
+ */
6
+ type ChronosHandlerResult = Record<string, unknown> | void;
7
+ /**
8
+ * Custom fetch implementation. Compatible with `globalThis.fetch`. Pass via
9
+ * {@link ChronosOptions.fetch} to inject middleware (logging, tracing, custom
10
+ * timeouts) or run in environments without a global `fetch`.
11
+ */
12
+ type FetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;
13
+ /**
14
+ * Logger interface. Pass via {@link ChronosOptions.logger} to integrate with
15
+ * your app's logging stack.
16
+ *
17
+ * Note: signature is `(message, meta?)` — message string first, optional
18
+ * structured metadata second. If adapting from pino-style `(obj, message)`,
19
+ * swap the argument order.
20
+ */
21
+ type ChronosLogger = {
22
+ debug(message: string, meta?: Record<string, unknown>): void;
23
+ info(message: string, meta?: Record<string, unknown>): void;
24
+ warn(message: string, meta?: Record<string, unknown>): void;
25
+ error(message: string, meta?: Record<string, unknown>): void;
26
+ };
27
+ /** Options for constructing a {@link Chronos} client. */
28
+ type ChronosOptions = {
29
+ /** API key for authentication. Sent as `Authorization: Bearer <key>`. */apiKey: string;
30
+ /**
31
+ * Override the API base URL. Defaults to `https://api.chronos.sh`. Useful
32
+ * for local development or self-hosted Chronos instances.
33
+ */
34
+ baseUrl?: string; /** Custom fetch implementation. Defaults to `globalThis.fetch`. */
35
+ fetch?: FetchLike; /** Custom logger. Defaults to a console-backed logger. */
36
+ logger?: ChronosLogger;
37
+ /**
38
+ * Worker long-poll wait time in seconds. Must be an integer between 0 and
39
+ * 20 inclusive. Defaults to 20 (the API maximum).
40
+ */
41
+ pollWaitTimeSeconds?: number;
42
+ /**
43
+ * Worker retry delay in milliseconds. Used between failed result-report
44
+ * attempts and between poll-loop iterations after a claim error. Defaults
45
+ * to 1000.
46
+ */
47
+ retryDelayMs?: number;
48
+ };
49
+ /** Schedule that produced a job. */
50
+ type ChronosSchedule = {
51
+ /** Schedule identifier. */id: string; /** Human-readable schedule name. */
52
+ name: string;
53
+ };
54
+ /**
55
+ * Context passed to a {@link ChronosHandler} when a job is claimed. Type the
56
+ * payload by supplying a generic argument.
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * type SendEmailPayload = { to: string; subject: string };
61
+ *
62
+ * chronos.worker.handle<SendEmailPayload>('send-email', async (ctx) => {
63
+ * await sendEmail(ctx.payload.to, ctx.payload.subject);
64
+ * return { sent: true };
65
+ * });
66
+ * ```
67
+ */
68
+ type ChronosContext<TPayload = unknown> = {
69
+ /** Stable identifier for the job (the schedule run). */jobId: string; /** Identifier for this specific execution attempt. Use for idempotency. */
70
+ executionId: string; /** Handler name, matching the one registered with `worker.handle()`. */
71
+ handler: string; /** Job payload, typed as `TPayload`. */
72
+ payload: TPayload; /** When the job was scheduled to run. */
73
+ scheduledFor: Date; /** Attempt number. 1 for the first attempt, increments on retries. */
74
+ attempt: number; /** Soft timeout for the handler in seconds. Informational; the SDK does not enforce. */
75
+ timeout: number; /** Schedule that produced this job, or `null` for ad-hoc jobs. */
76
+ schedule: ChronosSchedule | null;
77
+ };
78
+ /**
79
+ * Async function that processes a Chronos job. Return a plain object to
80
+ * record a result on the execution, or `undefined` for no result.
81
+ */
82
+ type ChronosHandler<TPayload = unknown> = (ctx: ChronosContext<TPayload>) => ChronosHandlerResult | Promise<ChronosHandlerResult>;
83
+ //#endregion
84
+ //#region src/client.d.ts
85
+ /** Default Chronos API base URL. */
86
+ declare const DEFAULT_BASE_URL = "https://api.chronos.sh";
87
+ declare class BaseClient {
88
+ readonly apiKey: string;
89
+ readonly baseUrl: string;
90
+ readonly fetch: FetchLike;
91
+ readonly logger: ChronosLogger;
92
+ private readonly headers;
93
+ constructor(options: ChronosOptions);
94
+ request<T>(path: string, body: Record<string, unknown>, signal?: AbortSignal): Promise<T>;
95
+ }
96
+ //#endregion
97
+ //#region src/worker.d.ts
98
+ /** Default worker long-poll wait time in seconds. Equal to the API maximum. */
99
+ declare const DEFAULT_POLL_WAIT_TIME_SECONDS = 20;
100
+ /**
101
+ * Long-poll worker. Claims jobs from the Chronos API, dispatches them to
102
+ * registered handlers, and reports results.
103
+ *
104
+ * Construct via `new Chronos({ apiKey }).worker` rather than directly.
105
+ */
106
+ declare class Worker {
107
+ private readonly client;
108
+ private readonly pollWaitTimeSeconds;
109
+ private readonly retryDelayMs;
110
+ private readonly handlers;
111
+ private handlerNames;
112
+ private startPromise?;
113
+ private pollController?;
114
+ constructor(client: BaseClient, options: ChronosOptions);
115
+ /**
116
+ * Register a handler for a named job type. Invoked when the Chronos API
117
+ * claims a job whose `handler` field matches `name`. Names are trimmed and
118
+ * must be 1–255 characters.
119
+ *
120
+ * @param name - Handler name. Must match the schedule's `handler` on the API side.
121
+ * @param handler - Async function invoked with the job context. Return a
122
+ * plain object to record a result, or `undefined` for none.
123
+ * @returns The Worker, for chaining.
124
+ * @throws {ChronosError} If the name is invalid, already registered, or `handler` is not a function.
125
+ *
126
+ * @example
127
+ * ```ts
128
+ * chronos.worker
129
+ * .handle('send-email', async (ctx) => ({ sent: true }))
130
+ * .handle('cleanup', async () => undefined);
131
+ * ```
132
+ */
133
+ handle<TPayload = unknown>(name: string, handler: ChronosHandler<TPayload>): this;
134
+ /**
135
+ * Begin long-polling for jobs. The returned promise resolves when
136
+ * {@link Worker.stop} is called and any in-flight job completes.
137
+ *
138
+ * @throws {ChronosError} Synchronously, if no handlers are registered or the worker is already running.
139
+ */
140
+ start(): Promise<void>;
141
+ /**
142
+ * Request graceful shutdown. The poll loop is aborted immediately; any
143
+ * in-flight handler and result-report are allowed to complete to preserve
144
+ * at-least-once delivery. Returns the same promise as the active
145
+ * {@link Worker.start}, or a resolved promise if the worker isn't running.
146
+ */
147
+ stop(): Promise<void>;
148
+ private get isStopped();
149
+ private runLoop;
150
+ private claimJob;
151
+ private processJob;
152
+ private handleUnregisteredJob;
153
+ private safeReportFailed;
154
+ private reportCompleted;
155
+ private reportFailed;
156
+ private reportResultWithRetry;
157
+ private logResultReportFailure;
158
+ }
159
+ //#endregion
160
+ //#region src/errors.d.ts
161
+ /**
162
+ * Base class for all errors thrown by the Chronos SDK. Catch this in a
163
+ * single `catch` to handle any SDK failure generically; use the subclasses
164
+ * to branch on cause.
165
+ *
166
+ * @example
167
+ * ```ts
168
+ * import { Chronos, ChronosError } from '@chronos.sh/sdk';
169
+ *
170
+ * const chronos = new Chronos({ apiKey: 'chrns_...' });
171
+ * try {
172
+ * await chronos.worker.start();
173
+ * } catch (err) {
174
+ * if (err instanceof ChronosError) {
175
+ * console.error('Chronos failed:', err.message);
176
+ * }
177
+ * }
178
+ * ```
179
+ */
180
+ declare class ChronosError extends Error {
181
+ /** Original error/value that caused this SDK error, when one is available. */
182
+ readonly cause?: unknown;
183
+ constructor(message: string, options?: {
184
+ cause?: unknown;
185
+ });
186
+ }
187
+ /**
188
+ * Thrown when SDK options fail validation at `new Chronos({ ... })`. Covers
189
+ * `apiKey`, `baseUrl`, `pollWaitTimeSeconds`, and `retryDelayMs`.
190
+ *
191
+ * @example
192
+ * ```ts
193
+ * import { Chronos, ChronosConfigError } from '@chronos.sh/sdk';
194
+ *
195
+ * try {
196
+ * const chronos = new Chronos({ apiKey: '' });
197
+ * } catch (err) {
198
+ * if (err instanceof ChronosConfigError) {
199
+ * console.error('Invalid Chronos config:', err.message);
200
+ * }
201
+ * }
202
+ * ```
203
+ */
204
+ declare class ChronosConfigError extends ChronosError {
205
+ constructor(message: string);
206
+ }
207
+ /** Options for constructing a {@link ChronosApiError}. */
208
+ type ChronosApiErrorOptions = {
209
+ /** HTTP status code returned by the Chronos API. */status: number; /** Application-level error code from the response envelope, when present. */
210
+ code?: string; /** Full parsed response payload (envelope + data, or whatever the server returned). */
211
+ body?: unknown; /** Value of the `X-Request-Id` response header, when present. Pair with server logs. */
212
+ requestId?: string;
213
+ };
214
+ /**
215
+ * Thrown when the Chronos API responds with a non-2xx status or a
216
+ * `success: false` envelope. Carries HTTP `status`, the application
217
+ * `code`, parsed `body`, and the API's `X-Request-Id`.
218
+ *
219
+ * `instanceof ChronosApiError` means the server replied;
220
+ * network/transport failures throw {@link ChronosNetworkError} instead.
221
+ *
222
+ * @example
223
+ * ```ts
224
+ * import { ChronosApiError } from '@chronos.sh/sdk';
225
+ *
226
+ * function handleSdkError(err: unknown) {
227
+ * if (err instanceof ChronosApiError) {
228
+ * if (err.status === 401) return refreshAuth();
229
+ * console.error('API error', { status: err.status, requestId: err.requestId });
230
+ * }
231
+ * }
232
+ * ```
233
+ */
234
+ declare class ChronosApiError extends ChronosError {
235
+ /** HTTP status code returned by the Chronos API. */
236
+ readonly status: number;
237
+ /** Application-level error code from the response envelope, when present. */
238
+ readonly code?: string;
239
+ /** Full parsed response payload (envelope + data, or whatever the server returned). */
240
+ readonly body?: unknown;
241
+ /** Value of the `X-Request-Id` response header, when present. */
242
+ readonly requestId?: string;
243
+ constructor(message: string, options: ChronosApiErrorOptions);
244
+ }
245
+ /**
246
+ * Thrown when the underlying `fetch` rejects before the server replies —
247
+ * DNS failure, TCP reset, connection refused, etc. The original error is
248
+ * available on `.cause`.
249
+ *
250
+ * Abort signals propagate unwrapped — `instanceof ChronosNetworkError`
251
+ * always means a real transport failure, not a graceful shutdown.
252
+ *
253
+ * @example
254
+ * ```ts
255
+ * import { ChronosNetworkError } from '@chronos.sh/sdk';
256
+ *
257
+ * function handleSdkError(err: unknown) {
258
+ * if (err instanceof ChronosNetworkError) {
259
+ * console.warn('Transport blip', { cause: err.cause });
260
+ * }
261
+ * }
262
+ * ```
263
+ */
264
+ declare class ChronosNetworkError extends ChronosError {
265
+ /** Original error/value rejected by the underlying `fetch`. */
266
+ readonly cause: unknown;
267
+ constructor(message: string, options: {
268
+ cause: unknown;
269
+ });
270
+ }
271
+ /**
272
+ * Wraps an exception thrown by a user-supplied {@link ChronosHandler}. The
273
+ * original error is on `.cause`; `.message` is copied from the original so
274
+ * the SDK reports it to the API as the failure reason.
275
+ *
276
+ * @example
277
+ * ```ts
278
+ * import { ChronosHandlerError } from '@chronos.sh/sdk';
279
+ *
280
+ * if (err instanceof ChronosHandlerError) {
281
+ * console.error('Handler threw', err.cause);
282
+ * }
283
+ * ```
284
+ */
285
+ declare class ChronosHandlerError extends ChronosError {
286
+ /** Original error/value thrown by the user-supplied handler. */
287
+ readonly cause: unknown;
288
+ constructor(message: string, options: {
289
+ cause: unknown;
290
+ });
291
+ }
292
+ //#endregion
293
+ //#region src/index.d.ts
294
+ /**
295
+ * The Chronos SDK client. Composes worker and (future) REST resource
296
+ * subclients from a single instance.
297
+ *
298
+ * @example
299
+ * ```ts
300
+ * import { Chronos } from '@chronos.sh/sdk';
301
+ *
302
+ * const chronos = new Chronos({ apiKey: process.env.CHRONOS_API_KEY! });
303
+ *
304
+ * chronos.worker.handle<{ to: string }>('send-email', async (ctx) => {
305
+ * await sendEmail(ctx.payload.to);
306
+ * return { sent: true };
307
+ * });
308
+ *
309
+ * await chronos.worker.start();
310
+ * ```
311
+ */
312
+ declare class Chronos {
313
+ /** Long-poll worker for executing pull-mode jobs. */
314
+ readonly worker: Worker;
315
+ /**
316
+ * @param options - Client configuration. Only `apiKey` is required.
317
+ * @throws {ChronosConfigError} If `apiKey` is missing or any option fails validation.
318
+ */
319
+ constructor(options: ChronosOptions);
320
+ }
321
+ //#endregion
322
+ export { Chronos, ChronosApiError, type ChronosApiErrorOptions, ChronosConfigError, type ChronosContext, ChronosError, type ChronosHandler, ChronosHandlerError, type ChronosHandlerResult, type ChronosLogger, ChronosNetworkError, type ChronosOptions, type ChronosSchedule, DEFAULT_BASE_URL, DEFAULT_POLL_WAIT_TIME_SECONDS, type FetchLike };
323
+ //# sourceMappingURL=index.d.cts.map