@maroonedsoftware/jobbroker 1.8.1 → 1.8.2

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.
@@ -1 +1 @@
1
- {"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAyB,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAclD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAqB1C,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAvBzB;;;;;;;;OAQG;IACH,yBAAyB,SAAK;IAE9B;;;;;;;OAOG;gBAEgB,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;IAKjC;;;;;;;;;;;;;;OAcG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAyC5B;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,oBAAoB;IAuB5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
1
+ {"version":3,"file":"pgboss.job.runner.d.ts","sourceRoot":"","sources":["../../src/pgboss/pgboss.job.runner.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAE,MAAM,SAAS,CAAC;AAC/C,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAC;AAElD,OAAO,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAC7C,OAAO,EAAyB,oBAAoB,EAAE,MAAM,8BAA8B,CAAC;AAC3F,OAAO,EAAE,MAAM,EAAE,MAAM,0BAA0B,CAAC;AAclD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA8BG;AACH,qBACa,eAAgB,SAAQ,SAAS;IAqB1C,OAAO,CAAC,QAAQ,CAAC,SAAS;IAC1B,OAAO,CAAC,QAAQ,CAAC,aAAa;IAC9B,OAAO,CAAC,QAAQ,CAAC,MAAM;IACvB,OAAO,CAAC,QAAQ,CAAC,MAAM;IAvBzB;;;;;;;;OAQG;IACH,yBAAyB,SAAK;IAE9B;;;;;;;OAOG;gBAEgB,SAAS,EAAE,SAAS,EACpB,aAAa,EAAE,oBAAoB,EACnC,MAAM,EAAE,MAAM,EACd,MAAM,EAAE,MAAM;IAKjC;;;;;;;;;;;;;;OAcG;IACG,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAwD5B;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,oBAAoB;IAuB5B;;;;;;;;;OASG;IACG,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;CAG5B"}
package/dist/pgboss.js CHANGED
@@ -355,7 +355,7 @@ var PgBossJobRunner = class extends JobRunner {
355
355
  identifier = registration;
356
356
  }
357
357
  await this.pgboss.work(name, async (jobs) => {
358
- await Promise.allSettled(jobs.map(async (job) => {
358
+ const results = await Promise.allSettled(jobs.map(async (job) => {
359
359
  const jobRunner = this.container.get(identifier);
360
360
  const controller = new AbortController();
361
361
  const pgSignal = job.signal;
@@ -370,10 +370,18 @@ var PgBossJobRunner = class extends JobRunner {
370
370
  await jobRunner.run(job.data, signal);
371
371
  } catch (error) {
372
372
  this.logger.error(error);
373
+ throw error;
373
374
  } finally {
374
375
  stopWatching();
375
376
  }
376
377
  }));
378
+ const failures = results.filter((result) => result.status === "rejected").map((result) => result.reason);
379
+ if (failures.length === 1) {
380
+ throw failures[0];
381
+ }
382
+ if (failures.length > 1) {
383
+ throw new AggregateError(failures, `${failures.length} of ${jobs.length} jobs in queue "${name}" failed`);
384
+ }
377
385
  });
378
386
  }
379
387
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.runner.ts"],"sourcesContent":["import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { DateTime, Duration } from 'luxon';\nimport { JobBroker } from '../job.broker.js';\nimport { JobInfo } from '../job.info.js';\nimport { JobSendOptions } from '../job.send.options.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * PgBoss implementation of the {@link JobBroker} interface.\n *\n * This broker uses PostgreSQL (via pg-boss) as the backing queue for job\n * processing. It provides reliable, transactional job queuing with support\n * for scheduled jobs using cron expressions.\n *\n * Each enqueue and schedule call sources its pg-boss `db` executor from the\n * injected {@link PgBossConnectionProvider}. The default provider returns\n * `undefined` (pg-boss uses its own pool), but a request-scoped override can\n * supply a transaction-bound executor so jobs are enqueued atomically with the\n * surrounding database transaction.\n *\n * @example\n * ```typescript\n * // Setup with dependency injection\n * const pgboss = new PgBoss('postgres://...');\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n *\n * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());\n *\n * // Send a job\n * await broker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Hello!'\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobBroker extends JobBroker {\n /**\n * Creates a new PgBossJobBroker instance.\n *\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * enqueue/schedule; the default returns `undefined` (pg-boss's own\n * pool), while a request-scoped override enables transactional enqueue.\n */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue.\n *\n * The job-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the job is enqueued atomically with that transaction.\n *\n * When `options.startAfter` is supplied the job is deferred via pg-boss's\n * native `startAfter`, which imposes no upper bound on the delay: a\n * {@link Duration} is converted to a relative number of seconds and a\n * {@link DateTime} to an absolute `Date`.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss does not return a job id (e.g. the job was\n * deduplicated away by a singleton policy).\n */\n async send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const id = await this.pgboss.send(name, payload, {\n db: this.connectionProvider.executor(),\n ...this.toStartAfter(options?.startAfter),\n });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\n }\n\n /**\n * Maps a backend-agnostic `startAfter` intent onto pg-boss's native\n * `startAfter` option.\n *\n * A {@link Duration} becomes a relative number of seconds; a {@link DateTime}\n * becomes an absolute `Date`. Returns an empty object when no deferral was\n * requested so the field is simply omitted from the send options.\n */\n private toStartAfter(startAfter: JobSendOptions['startAfter']): { startAfter?: number | Date } {\n if (Duration.isDuration(startAfter)) {\n return { startAfter: startAfter.as('seconds') };\n }\n if (DateTime.isDateTime(startAfter)) {\n return { startAfter: startAfter.toJSDate() };\n }\n return {};\n }\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued by pg-boss according to the\n * specified cron schedule. If a schedule already exists for this job,\n * it will be updated with the new cron expression and payload.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own\n * pool, which is the expected behavior for bootstrap-time scheduling.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws Error if the job name is not found in the registry.\n */\n async schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.schedule(name, cron, payload, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n\n /**\n * Cancels one or more jobs in the PgBoss queue.\n *\n * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a\n * job is still queued or already running: a queued job is never picked up,\n * while a running job is observed as cancelled by the {@link PgBossJobRunner}\n * (which polls for the state change and aborts the handler's `AbortSignal`).\n * Interrupting a running handler is cooperative — see {@link Job.run}.\n *\n * @param name - The name of the registered job to cancel.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws Error if the job name is not found in the registry.\n */\n async cancel(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.cancel(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs currently in the `cancelled` state are affected.\n *\n * @param name - The name of the registered job to resume.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws Error if the job name is not found in the registry.\n */\n async resume(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.resume(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Permanently deletes one or more jobs from the PgBoss queue.\n *\n * @param name - The name of the registered job to delete.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws Error if the job name is not found in the registry.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to look up.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws Error if the job name is not found in the registry.\n */\n async getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const [job] = await this.pgboss.findJobs<Payload>(name, { id, db: this.connectionProvider.executor() });\n if (!job) {\n return null;\n }\n\n return { id: job.id, name: job.name, state: job.state, data: job.data };\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\n\n/**\n * Configuration for a scheduled job registration.\n *\n * Use this type when you need to register a job that runs on a schedule\n * rather than being triggered manually.\n *\n * @example\n * ```typescript\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *' // Every day at 9 AM\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** A cron expression defining when the job should run. */\n cron: string;\n};\n\n/**\n * Registry map for PgBoss job registrations.\n *\n * This map holds all job registrations, mapping job names to either:\n * - A job class identifier (for on-demand jobs)\n * - A {@link PgBossJobRegistration} object (for scheduled jobs)\n *\n * The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}\n * to validate job names and resolve job handlers.\n *\n * @example\n * ```typescript\n * const registry = new PgBossJobRegistryMap();\n *\n * // Register an on-demand job\n * registry.set('send-email', SendEmailJob);\n *\n * // Register a scheduled job\n * registry.set('daily-cleanup', {\n * job: CleanupJob,\n * cron: '0 0 * * *'\n * });\n *\n * // Use with dependency injection\n * container.bind(PgBossJobRegistryMap).toValue(registry);\n * ```\n */\n@Injectable()\nexport class PgBossJobRegistryMap extends Map<string, Identifier<Job> | PgBossJobRegistration> {}\n","import { Injectable } from 'injectkit';\nimport { Db } from 'pg-boss';\n\n/**\n * Supplies the pg-boss database executor used when enqueuing or scheduling jobs.\n *\n * pg-boss accepts an optional `db` ({@link Db}) on its send/schedule options. When\n * provided, the job-insert SQL runs on that executor's connection instead of\n * pg-boss's own pool — letting an enqueue participate in an in-flight database\n * transaction so the job row and the surrounding business writes commit or roll\n * back together.\n *\n * The default implementation returns `undefined`, which makes pg-boss fall back\n * to its internal pool (i.e. the standard, non-transactional behavior). To enqueue\n * jobs transactionally, register an override on a request-scoped DI container whose\n * {@link executor} returns a transaction-bound executor — for example pg-boss's\n * `fromKysely(trx)` adapter wrapping the active Kysely transaction.\n *\n * @example\n * ```typescript\n * import { fromKysely } from 'pg-boss';\n * import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker';\n *\n * // In request scope, bind a provider backed by the active transaction.\n * class TransactionalConnectionProvider extends PgBossConnectionProvider {\n * constructor(private readonly trx: Transaction<DB>) {\n * super();\n * }\n *\n * override executor() {\n * return fromKysely(this.trx);\n * }\n * }\n * ```\n */\n@Injectable()\nexport class PgBossConnectionProvider {\n /**\n * Returns the pg-boss executor to run job-insert SQL against, or `undefined`\n * to use pg-boss's internal connection pool.\n *\n * @returns A transaction-bound {@link Db} executor, or `undefined` for the\n * default pooled (non-transactional) behavior.\n */\n executor(): Db | undefined {\n return undefined;\n }\n}\n","import { Job as PgJob, PgBoss } from 'pg-boss';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobRunner } from '../job.runner.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * Type guard to check if a registration is a scheduled job configuration.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} with cron schedule.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isPgBossJobRegistration = (registration: any): registration is PgBossJobRegistration => {\n return registration && 'job' in registration && 'cron' in registration;\n};\n\n/**\n * PgBoss implementation of the {@link JobRunner} interface.\n *\n * This runner processes jobs from PostgreSQL queues using pg-boss. It\n * automatically creates queues for registered jobs, sets up scheduled\n * jobs, and handles job execution with error logging.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * How often, in seconds, a running job polls pg-boss to detect that it has\n * been cancelled. When a poll observes the job is no longer present or its\n * state is `cancelled`, the `AbortSignal` passed to the job's handler is\n * aborted so cooperative handlers can stop. Set to `0` to disable polling\n * (running jobs will then only be interruptible on shutdown/timeout).\n *\n * @default 5\n */\n cancelPollIntervalSeconds = 5;\n\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The DI container for resolving job instances.\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param logger - The logger for recording job execution errors.\n */\n constructor(\n private readonly container: Container,\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly logger: Logger,\n ) {\n super();\n }\n\n /**\n * Starts the job runner and begins processing registered jobs.\n *\n * For each registered job, this method:\n * 1. Creates the queue if it doesn't exist\n * 2. Sets up the cron schedule (for scheduled jobs)\n * 3. Starts a worker to process jobs from the queue\n *\n * Each item in a batch resolves its `Job` instance from the DI container\n * individually and execution is awaited via `Promise.allSettled`, so pg-boss\n * does not acknowledge a batch until every job has actually finished and\n * one job's failure cannot suppress its sibling's logs.\n *\n * @returns A promise that resolves when all workers are registered with pg-boss.\n */\n async start(): Promise<void> {\n await this.pgboss.start();\n\n for (const [name, registration] of this.registrations.entries()) {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n await this.pgboss.createQueue(name);\n }\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n await this.pgboss.schedule(name, registration.cron);\n } else {\n identifier = registration;\n }\n\n await this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n await Promise.allSettled(\n jobs.map(async job => {\n const jobRunner = this.container.get<Job>(identifier);\n const controller = new AbortController();\n // pg-boss aborts `job.signal` on timeout/shutdown; combine it with our\n // own controller, which the cancellation poll aborts. (`signal` is typed\n // as always present, but may be absent when jobs are faked in tests.)\n const pgSignal = (job as { signal?: AbortSignal }).signal;\n const signal = AbortSignal.any(pgSignal ? [controller.signal, pgSignal] : [controller.signal]);\n const stopWatching = this.watchForCancellation(name, job.id, controller);\n try {\n await jobRunner.run(job.data, signal);\n } catch (error) {\n this.logger.error(error);\n } finally {\n stopWatching();\n }\n }),\n );\n });\n }\n }\n\n /**\n * Polls pg-boss for a running job and aborts the given controller when the job\n * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).\n *\n * This is what turns {@link PgBossJobBroker.cancel} into a signal the running\n * handler can observe, even when `cancel` is called from a different process:\n * the cancellation is a state change on the shared PostgreSQL row, and every\n * runner polls that row for the jobs it is currently executing.\n *\n * @param name - The queue/job name.\n * @param id - The id of the running job to watch.\n * @param controller - The controller to abort once cancellation is detected.\n * @returns A function that stops the poll; always call it when the job finishes.\n * @internal\n */\n private watchForCancellation(name: string, id: string, controller: AbortController): () => void {\n if (this.cancelPollIntervalSeconds <= 0) {\n return () => {};\n }\n\n const timer = setInterval(async () => {\n try {\n const [job] = await this.pgboss.findJobs(name, { id });\n if (!job || job.state === 'cancelled') {\n controller.abort();\n clearInterval(timer);\n }\n } catch (error) {\n this.logger.error(error);\n }\n }, this.cancelPollIntervalSeconds * 1000);\n\n // Don't let the poll timer keep the process alive on its own.\n timer.unref?.();\n\n return () => clearInterval(timer);\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n"],"mappings":";;;;;;;AAAA,SAASA,cAAc;AACvB,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAoDhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACpDhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFRO,IAAMC,kBAAN,cAA8BC,UAAAA;SAAAA;;;;;;;;;;;;;;;EAUnC,YACmBC,eACAC,QACAC,oBACjB;AACA,UAAK,GAAA,KAJYF,gBAAAA,eAAAA,KACAC,SAAAA,QAAAA,KACAC,qBAAAA;EAGnB;;;;;;;;;;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AASQ,OAAO;AACd,iBAAK7B,OAAO6B,MAAMA,KAAAA;UACpB,UAAA;AACEL,yBAAAA;UACF;QACF,CAAA,CAAA;MAEJ,CAAA;IACF;EACF;;;;;;;;;;;;;;;;EAiBQC,qBAAqBvB,MAAcwB,IAAYR,YAAyC;AAC9F,QAAI,KAAKtB,6BAA6B,GAAG;AACvC,aAAO,MAAA;MAAO;IAChB;AAEA,UAAMkC,QAAQC,YAAY,YAAA;AACxB,UAAI;AACF,cAAM,CAACvB,GAAAA,IAAO,MAAM,KAAKT,OAAOiC,SAAS9B,MAAM;UAAEwB;QAAG,CAAA;AACpD,YAAI,CAAClB,OAAOA,IAAIyB,UAAU,aAAa;AACrCf,qBAAWgB,MAAK;AAChBC,wBAAcL,KAAAA;QAChB;MACF,SAASD,OAAO;AACd,aAAK7B,OAAO6B,MAAMA,KAAAA;MACpB;IACF,GAAG,KAAKjC,4BAA4B,GAAA;AAGpCkC,UAAMM,QAAK;AAEX,WAAO,MAAMD,cAAcL,KAAAA;EAC7B;;;;;;;;;;;EAYA,MAAMO,OAAsB;AAC1B,UAAM,KAAKtC,OAAOsC,KAAI;EACxB;AACF;;;;;;;;;;;","names":["PgBoss","Injectable","DateTime","Duration","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","options","has","Error","id","db","executor","toStartAfter","startAfter","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","cron","unschedule","cancel","resume","deleteJob","getJob","job","findJobs","state","data","PgBoss","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","cancelPollIntervalSeconds","container","registrations","pgboss","logger","start","name","entries","queue","getQueue","createQueue","identifier","job","schedule","cron","work","jobs","Promise","allSettled","map","jobRunner","get","controller","AbortController","pgSignal","signal","AbortSignal","any","stopWatching","watchForCancellation","id","run","data","error","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop"]}
1
+ {"version":3,"sources":["../src/pgboss/pgboss.job.broker.ts","../src/pgboss/pgboss.job.registration.ts","../src/pgboss/pgboss.connection.provider.ts","../src/pgboss/pgboss.job.runner.ts"],"sourcesContent":["import { PgBoss } from 'pg-boss';\nimport { Injectable } from 'injectkit';\nimport { DateTime, Duration } from 'luxon';\nimport { JobBroker } from '../job.broker.js';\nimport { JobInfo } from '../job.info.js';\nimport { JobSendOptions } from '../job.send.options.js';\nimport { PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { PgBossConnectionProvider } from './pgboss.connection.provider.js';\n\n/**\n * PgBoss implementation of the {@link JobBroker} interface.\n *\n * This broker uses PostgreSQL (via pg-boss) as the backing queue for job\n * processing. It provides reliable, transactional job queuing with support\n * for scheduled jobs using cron expressions.\n *\n * Each enqueue and schedule call sources its pg-boss `db` executor from the\n * injected {@link PgBossConnectionProvider}. The default provider returns\n * `undefined` (pg-boss uses its own pool), but a request-scoped override can\n * supply a transaction-bound executor so jobs are enqueued atomically with the\n * surrounding database transaction.\n *\n * @example\n * ```typescript\n * // Setup with dependency injection\n * const pgboss = new PgBoss('postgres://...');\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n *\n * const broker = new PgBossJobBroker(registry, pgboss, new PgBossConnectionProvider());\n *\n * // Send a job\n * await broker.send('send-email', {\n * to: 'user@example.com',\n * subject: 'Hello!'\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobBroker extends JobBroker {\n /**\n * Creates a new PgBossJobBroker instance.\n *\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param connectionProvider - Supplies the pg-boss `db` executor for each\n * enqueue/schedule; the default returns `undefined` (pg-boss's own\n * pool), while a request-scoped override enables transactional enqueue.\n */\n constructor(\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly connectionProvider: PgBossConnectionProvider,\n ) {\n super();\n }\n\n /**\n * Sends a job to the PgBoss queue.\n *\n * The job-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; when that executor is bound to an active\n * transaction, the job is enqueued atomically with that transaction.\n *\n * When `options.startAfter` is supplied the job is deferred via pg-boss's\n * native `startAfter`, which imposes no upper bound on the delay: a\n * {@link Duration} is converted to a relative number of seconds and a\n * {@link DateTime} to an absolute `Date`.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to execute.\n * @param payload - The data to pass to the job handler.\n * @param options - Optional enqueue options, e.g. `startAfter` to defer the job.\n * @returns A promise that resolves with the id of the queued job.\n * @throws Error if the job name is not found in the registry.\n * @throws Error if pg-boss does not return a job id (e.g. the job was\n * deduplicated away by a singleton policy).\n */\n async send<Payload extends object>(name: string, payload: Payload, options?: JobSendOptions): Promise<string> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const id = await this.pgboss.send(name, payload, {\n db: this.connectionProvider.executor(),\n ...this.toStartAfter(options?.startAfter),\n });\n if (!id) {\n throw new Error(`Failed to enqueue job ${name}`);\n }\n\n return id;\n }\n\n /**\n * Maps a backend-agnostic `startAfter` intent onto pg-boss's native\n * `startAfter` option.\n *\n * A {@link Duration} becomes a relative number of seconds; a {@link DateTime}\n * becomes an absolute `Date`. Returns an empty object when no deferral was\n * requested so the field is simply omitted from the send options.\n */\n private toStartAfter(startAfter: JobSendOptions['startAfter']): { startAfter?: number | Date } {\n if (Duration.isDuration(startAfter)) {\n return { startAfter: startAfter.as('seconds') };\n }\n if (DateTime.isDateTime(startAfter)) {\n return { startAfter: startAfter.toJSDate() };\n }\n return {};\n }\n\n /**\n * Schedules a recurring job using a cron expression.\n *\n * The job will be automatically enqueued by pg-boss according to the\n * specified cron schedule. If a schedule already exists for this job,\n * it will be updated with the new cron expression and payload.\n *\n * The schedule-insert SQL runs against the executor returned by the injected\n * {@link PgBossConnectionProvider}; the default executor uses pg-boss's own\n * pool, which is the expected behavior for bootstrap-time scheduling.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to schedule.\n * @param cron - A cron expression (e.g., '0 9 * * *' for daily at 9am).\n * @param payload - Optional data to pass to the job on each execution.\n * @returns A promise that resolves when the schedule has been created.\n * @throws Error if the job name is not found in the registry.\n */\n async schedule<Payload extends object>(name: string, cron: string, payload?: Payload): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.schedule(name, cron, payload, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Removes a scheduled job from pg-boss.\n *\n * This stops future executions of the scheduled job. Jobs that are\n * already queued will still be processed.\n *\n * @param name - The name of the scheduled job to remove.\n * @returns A promise that resolves when the schedule has been removed.\n * @throws Error if the job name is not found in the registry.\n */\n async unschedule(name: string): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.unschedule(name);\n }\n\n /**\n * Cancels one or more jobs in the PgBoss queue.\n *\n * pg-boss marks the job(s) as `cancelled` in PostgreSQL. This works whether a\n * job is still queued or already running: a queued job is never picked up,\n * while a running job is observed as cancelled by the {@link PgBossJobRunner}\n * (which polls for the state change and aborts the handler's `AbortSignal`).\n * Interrupting a running handler is cooperative — see {@link Job.run}.\n *\n * @param name - The name of the registered job to cancel.\n * @param id - A single job id, or an array of ids, to cancel.\n * @returns A promise that resolves once the cancellation has been requested.\n * @throws Error if the job name is not found in the registry.\n */\n async cancel(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.cancel(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Resumes one or more previously cancelled jobs, re-queuing them for processing.\n *\n * Only jobs currently in the `cancelled` state are affected.\n *\n * @param name - The name of the registered job to resume.\n * @param id - A single job id, or an array of ids, to resume.\n * @returns A promise that resolves once the jobs have been re-queued.\n * @throws Error if the job name is not found in the registry.\n */\n async resume(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.resume(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Permanently deletes one or more jobs from the PgBoss queue.\n *\n * @param name - The name of the registered job to delete.\n * @param id - A single job id, or an array of ids, to delete.\n * @returns A promise that resolves once the jobs have been deleted.\n * @throws Error if the job name is not found in the registry.\n */\n async deleteJob(name: string, id: string | string[]): Promise<void> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n await this.pgboss.deleteJob(name, id, { db: this.connectionProvider.executor() });\n }\n\n /**\n * Looks up the current state of a single job.\n *\n * @typeParam Payload - The type of the job payload.\n * @param name - The name of the registered job to look up.\n * @param id - The id of the job to look up.\n * @returns A promise that resolves with the {@link JobInfo} for the job, or\n * `null` if no job with that id exists.\n * @throws Error if the job name is not found in the registry.\n */\n async getJob<Payload extends object>(name: string, id: string): Promise<JobInfo<Payload> | null> {\n if (!this.registrations.has(name)) {\n throw new Error(`Job ${name} is not registered`);\n }\n\n const [job] = await this.pgboss.findJobs<Payload>(name, { id, db: this.connectionProvider.executor() });\n if (!job) {\n return null;\n }\n\n return { id: job.id, name: job.name, state: job.state, data: job.data };\n }\n}\n","import { Identifier, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\n\n/**\n * Configuration for a scheduled job registration.\n *\n * Use this type when you need to register a job that runs on a schedule\n * rather than being triggered manually.\n *\n * @example\n * ```typescript\n * const scheduledJob: PgBossJobRegistration = {\n * job: DailyReportJob,\n * cron: '0 9 * * *' // Every day at 9 AM\n * };\n * ```\n */\nexport type PgBossJobRegistration = {\n /** The job class identifier to instantiate when the job runs. */\n job: Identifier<Job>;\n /** A cron expression defining when the job should run. */\n cron: string;\n};\n\n/**\n * Registry map for PgBoss job registrations.\n *\n * This map holds all job registrations, mapping job names to either:\n * - A job class identifier (for on-demand jobs)\n * - A {@link PgBossJobRegistration} object (for scheduled jobs)\n *\n * The registry is used by both {@link PgBossJobBroker} and {@link PgBossJobRunner}\n * to validate job names and resolve job handlers.\n *\n * @example\n * ```typescript\n * const registry = new PgBossJobRegistryMap();\n *\n * // Register an on-demand job\n * registry.set('send-email', SendEmailJob);\n *\n * // Register a scheduled job\n * registry.set('daily-cleanup', {\n * job: CleanupJob,\n * cron: '0 0 * * *'\n * });\n *\n * // Use with dependency injection\n * container.bind(PgBossJobRegistryMap).toValue(registry);\n * ```\n */\n@Injectable()\nexport class PgBossJobRegistryMap extends Map<string, Identifier<Job> | PgBossJobRegistration> {}\n","import { Injectable } from 'injectkit';\nimport { Db } from 'pg-boss';\n\n/**\n * Supplies the pg-boss database executor used when enqueuing or scheduling jobs.\n *\n * pg-boss accepts an optional `db` ({@link Db}) on its send/schedule options. When\n * provided, the job-insert SQL runs on that executor's connection instead of\n * pg-boss's own pool — letting an enqueue participate in an in-flight database\n * transaction so the job row and the surrounding business writes commit or roll\n * back together.\n *\n * The default implementation returns `undefined`, which makes pg-boss fall back\n * to its internal pool (i.e. the standard, non-transactional behavior). To enqueue\n * jobs transactionally, register an override on a request-scoped DI container whose\n * {@link executor} returns a transaction-bound executor — for example pg-boss's\n * `fromKysely(trx)` adapter wrapping the active Kysely transaction.\n *\n * @example\n * ```typescript\n * import { fromKysely } from 'pg-boss';\n * import { PgBossConnectionProvider } from '@maroonedsoftware/jobbroker';\n *\n * // In request scope, bind a provider backed by the active transaction.\n * class TransactionalConnectionProvider extends PgBossConnectionProvider {\n * constructor(private readonly trx: Transaction<DB>) {\n * super();\n * }\n *\n * override executor() {\n * return fromKysely(this.trx);\n * }\n * }\n * ```\n */\n@Injectable()\nexport class PgBossConnectionProvider {\n /**\n * Returns the pg-boss executor to run job-insert SQL against, or `undefined`\n * to use pg-boss's internal connection pool.\n *\n * @returns A transaction-bound {@link Db} executor, or `undefined` for the\n * default pooled (non-transactional) behavior.\n */\n executor(): Db | undefined {\n return undefined;\n }\n}\n","import { Job as PgJob, PgBoss } from 'pg-boss';\nimport { Container, Injectable } from 'injectkit';\nimport { Job } from '../job.js';\nimport { JobRunner } from '../job.runner.js';\nimport { PgBossJobRegistration, PgBossJobRegistryMap } from './pgboss.job.registration.js';\nimport { Logger } from '@maroonedsoftware/logger';\n\n/**\n * Type guard to check if a registration is a scheduled job configuration.\n *\n * @param registration - The registration to check.\n * @returns True if the registration is a {@link PgBossJobRegistration} with cron schedule.\n * @internal\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst isPgBossJobRegistration = (registration: any): registration is PgBossJobRegistration => {\n return registration && 'job' in registration && 'cron' in registration;\n};\n\n/**\n * PgBoss implementation of the {@link JobRunner} interface.\n *\n * This runner processes jobs from PostgreSQL queues using pg-boss. It\n * automatically creates queues for registered jobs, sets up scheduled\n * jobs, and handles job execution with error logging.\n *\n * @example\n * ```typescript\n * // Setup\n * const pgboss = new PgBoss('postgres://...');\n * await pgboss.start();\n *\n * const registry = new PgBossJobRegistryMap();\n * registry.set('send-email', SendEmailJob);\n * registry.set('daily-report', {\n * job: DailyReportJob,\n * cron: '0 9 * * *'\n * });\n *\n * const runner = new PgBossJobRunner(container, registry, pgboss, logger);\n *\n * // Start processing\n * await runner.start();\n *\n * // Graceful shutdown\n * process.on('SIGTERM', async () => {\n * await runner.stop();\n * });\n * ```\n */\n@Injectable()\nexport class PgBossJobRunner extends JobRunner {\n /**\n * How often, in seconds, a running job polls pg-boss to detect that it has\n * been cancelled. When a poll observes the job is no longer present or its\n * state is `cancelled`, the `AbortSignal` passed to the job's handler is\n * aborted so cooperative handlers can stop. Set to `0` to disable polling\n * (running jobs will then only be interruptible on shutdown/timeout).\n *\n * @default 5\n */\n cancelPollIntervalSeconds = 5;\n\n /**\n * Creates a new PgBossJobRunner instance.\n *\n * @param container - The DI container for resolving job instances.\n * @param registrations - The registry map containing all registered jobs.\n * @param pgboss - The pg-boss instance to use for queue operations.\n * @param logger - The logger for recording job execution errors.\n */\n constructor(\n private readonly container: Container,\n private readonly registrations: PgBossJobRegistryMap,\n private readonly pgboss: PgBoss,\n private readonly logger: Logger,\n ) {\n super();\n }\n\n /**\n * Starts the job runner and begins processing registered jobs.\n *\n * For each registered job, this method:\n * 1. Creates the queue if it doesn't exist\n * 2. Sets up the cron schedule (for scheduled jobs)\n * 3. Starts a worker to process jobs from the queue\n *\n * Each item in a batch resolves its `Job` instance from the DI container\n * individually and execution is awaited via `Promise.allSettled`, so pg-boss\n * does not acknowledge a batch until every job has actually finished and\n * one job's failure cannot suppress its sibling's logs.\n *\n * @returns A promise that resolves when all workers are registered with pg-boss.\n */\n async start(): Promise<void> {\n await this.pgboss.start();\n\n for (const [name, registration] of this.registrations.entries()) {\n const queue = await this.pgboss.getQueue(name);\n if (!queue) {\n await this.pgboss.createQueue(name);\n }\n\n let identifier;\n if (isPgBossJobRegistration(registration)) {\n identifier = registration.job;\n await this.pgboss.schedule(name, registration.cron);\n } else {\n identifier = registration;\n }\n\n await this.pgboss.work(name, async (jobs: PgJob<object>[]) => {\n const results = await Promise.allSettled(\n jobs.map(async job => {\n const jobRunner = this.container.get<Job>(identifier);\n const controller = new AbortController();\n // pg-boss aborts `job.signal` on timeout/shutdown; combine it with our\n // own controller, which the cancellation poll aborts. (`signal` is typed\n // as always present, but may be absent when jobs are faked in tests.)\n const pgSignal = (job as { signal?: AbortSignal }).signal;\n const signal = AbortSignal.any(pgSignal ? [controller.signal, pgSignal] : [controller.signal]);\n const stopWatching = this.watchForCancellation(name, job.id, controller);\n try {\n await jobRunner.run(job.data, signal);\n } catch (error) {\n // Log first so a sibling's failure can't suppress this job's diagnostics,\n // then rethrow so `allSettled` records the rejection below.\n this.logger.error(error);\n throw error;\n } finally {\n stopWatching();\n }\n }),\n );\n\n // Every job in the batch is isolated (they run concurrently and each logs its own\n // error), but the work handler itself must reject when any job threw. Otherwise\n // pg-boss treats the whole batch as completed and never applies retryLimit or\n // dead-lettering to the jobs that actually failed.\n const failures = results.filter((result): result is PromiseRejectedResult => result.status === 'rejected').map(result => result.reason);\n if (failures.length === 1) {\n throw failures[0];\n }\n if (failures.length > 1) {\n throw new AggregateError(failures, `${failures.length} of ${jobs.length} jobs in queue \"${name}\" failed`);\n }\n });\n }\n }\n\n /**\n * Polls pg-boss for a running job and aborts the given controller when the job\n * has been cancelled (or has disappeared, e.g. via {@link PgBossJobBroker.deleteJob}).\n *\n * This is what turns {@link PgBossJobBroker.cancel} into a signal the running\n * handler can observe, even when `cancel` is called from a different process:\n * the cancellation is a state change on the shared PostgreSQL row, and every\n * runner polls that row for the jobs it is currently executing.\n *\n * @param name - The queue/job name.\n * @param id - The id of the running job to watch.\n * @param controller - The controller to abort once cancellation is detected.\n * @returns A function that stops the poll; always call it when the job finishes.\n * @internal\n */\n private watchForCancellation(name: string, id: string, controller: AbortController): () => void {\n if (this.cancelPollIntervalSeconds <= 0) {\n return () => {};\n }\n\n const timer = setInterval(async () => {\n try {\n const [job] = await this.pgboss.findJobs(name, { id });\n if (!job || job.state === 'cancelled') {\n controller.abort();\n clearInterval(timer);\n }\n } catch (error) {\n this.logger.error(error);\n }\n }, this.cancelPollIntervalSeconds * 1000);\n\n // Don't let the poll timer keep the process alive on its own.\n timer.unref?.();\n\n return () => clearInterval(timer);\n }\n\n /**\n * Stops the job runner gracefully.\n *\n * This method stops the pg-boss instance, which will:\n * - Stop accepting new jobs\n * - Wait for currently executing jobs to complete\n * - Clean up database connections\n *\n * @returns A promise that resolves when the runner has stopped.\n */\n async stop(): Promise<void> {\n await this.pgboss.stop();\n }\n}\n"],"mappings":";;;;;;;AAAA,SAASA,cAAc;AACvB,SAASC,cAAAA,mBAAkB;AAC3B,SAASC,UAAUC,gBAAgB;;;ACFnC,SAAqBC,kBAAkB;;;;;;;;AAoDhC,IAAMC,uBAAN,cAAmCC,IAAAA;SAAAA;;;AAAsD;;;;;;ACpDhG,SAASC,cAAAA,mBAAkB;;;;;;;;AAoCpB,IAAMC,2BAAN,MAAMA;SAAAA;;;;;;;;;;EAQXC,WAA2B;AACzB,WAAOC;EACT;AACF;;;;;;;;;;;;;;;;;AFRO,IAA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F;;;;;;;;;;;","names":["PgBoss","Injectable","DateTime","Duration","Injectable","PgBossJobRegistryMap","Map","Injectable","PgBossConnectionProvider","executor","undefined","PgBossJobBroker","JobBroker","registrations","pgboss","connectionProvider","send","name","payload","options","has","Error","id","db","executor","toStartAfter","startAfter","Duration","isDuration","as","DateTime","isDateTime","toJSDate","schedule","cron","unschedule","cancel","resume","deleteJob","getJob","job","findJobs","state","data","PgBoss","Container","Injectable","Logger","isPgBossJobRegistration","registration","PgBossJobRunner","JobRunner","cancelPollIntervalSeconds","container","registrations","pgboss","logger","start","name","entries","queue","getQueue","createQueue","identifier","job","schedule","cron","work","jobs","results","Promise","allSettled","map","jobRunner","get","controller","AbortController","pgSignal","signal","AbortSignal","any","stopWatching","watchForCancellation","id","run","data","error","failures","filter","result","status","reason","length","AggregateError","timer","setInterval","findJobs","state","abort","clearInterval","unref","stop"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maroonedsoftware/jobbroker",
3
- "version": "1.8.1",
3
+ "version": "1.8.2",
4
4
  "description": "A flexible background job processing library with support for scheduled and on-demand jobs.",
5
5
  "author": {
6
6
  "name": "Marooned Software",
@@ -47,14 +47,14 @@
47
47
  "dependencies": {
48
48
  "injectkit": "^1.6.0",
49
49
  "luxon": "^3.7.2",
50
- "@maroonedsoftware/logger": "1.1.2",
51
- "@maroonedsoftware/errors": "1.7.1"
50
+ "@maroonedsoftware/errors": "1.8.0",
51
+ "@maroonedsoftware/logger": "1.1.3"
52
52
  },
53
53
  "devDependencies": {
54
54
  "@types/luxon": "^3.7.2",
55
55
  "pg-boss": "^12.24.1",
56
- "@repo/config-typescript": "0.1.0",
57
- "@repo/config-eslint": "0.2.1"
56
+ "@repo/config-eslint": "0.2.1",
57
+ "@repo/config-typescript": "0.1.0"
58
58
  },
59
59
  "peerDependencies": {
60
60
  "pg-boss": "^12.5.4"
@@ -64,6 +64,9 @@
64
64
  "optional": true
65
65
  }
66
66
  },
67
+ "engines": {
68
+ "node": ">=22"
69
+ },
67
70
  "scripts": {
68
71
  "build": "tsup src/index.ts src/pgboss.ts --format esm --sourcemap && tsc --emitDeclarationOnly --declaration",
69
72
  "build:ci": "eslint --max-warnings=0 && pnpm run build",