kizunajs 2.0.0-beta.30 → 2.0.0-beta.32

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/README.md CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  A spec-driven framework for building fully typed REST APIs in TypeScript, where your route declarations produce the validation, the documentation, the clients, and the AI tools.
6
6
 
7
- [![npm](https://img.shields.io/npm/v/kizunajs/beta?color=blue&label=npm)](https://www.npmjs.com/package/kizunajs/v/2.0.0-beta.30)
7
+ [![npm](https://img.shields.io/npm/v/kizunajs/beta?color=blue&label=npm)](https://www.npmjs.com/package/kizunajs/v/2.0.0-beta.32)
8
8
  ![license](https://img.shields.io/badge/license-MIT-blue)
9
9
 
10
10
  [Documentation](https://kizunajs.com)
@@ -1,6 +1,6 @@
1
1
  const require_plugin = require("./plugin-Dw-yCjTY.cjs");
2
2
  const require_error_response = require("./error-response-DN5Dsf8b.cjs");
3
- const require_plugin_server = require("./plugin-server-tW5ZoOud.cjs");
3
+ const require_plugin_server = require("./plugin-server-6sIGS0RF.cjs");
4
4
  const require_schemas = require("./schemas-Bre1FVHq.cjs");
5
5
  let zod = require("zod");
6
6
  //#region src/tool-definitions.ts
@@ -853,6 +853,25 @@ const jobFnAt = (runner, jobKey) => {
853
853
  const candidate = node;
854
854
  return typeof candidate?.run === "function" && typeof candidate.queue === "function" ? candidate : void 0;
855
855
  };
856
+ /**
857
+ * Run a job no caller awaits, rejecting when it fails and reporting the
858
+ * failure to `onError`, or to `logger` without one.
859
+ */
860
+ const attemptJob = async (run, jobKey, onError, logger = console) => {
861
+ try {
862
+ const response = await run();
863
+ if (response.status >= 400) throw new ResponseError(response);
864
+ return response;
865
+ } catch (error) {
866
+ if (!onError) logger.error(`[kizuna] Job "${jobKey}" failed:`, error);
867
+ else try {
868
+ onError(jobKey, error);
869
+ } catch (hookError) {
870
+ logger.error("[kizuna] The jobs onError threw:", hookError);
871
+ }
872
+ throw error;
873
+ }
874
+ };
856
875
  const handlerAt = (handlers, jobKey) => {
857
876
  let current = handlers;
858
877
  for (const segment of jobKey.split(".")) {
@@ -905,13 +924,7 @@ const createJobRunner = (source, handlers, options) => {
905
924
  };
906
925
  const runDetached = (jobKey, input, runAt) => {
907
926
  const start = () => {
908
- invoke(jobKey, input).catch((error) => {
909
- if (options?.onError) {
910
- options.onError(jobKey, error);
911
- return;
912
- }
913
- console.error(`[kizuna] Queued job "${jobKey}" failed:`, error);
914
- });
927
+ attemptJob(() => invoke(jobKey, input), jobKey, options?.onError).catch(() => {});
915
928
  };
916
929
  const time = runAt?.getTime();
917
930
  if (time === void 0 || time <= Date.now()) {
@@ -1618,9 +1631,9 @@ const assembleApi = (contract, parts) => {
1618
1631
  };
1619
1632
  /**
1620
1633
  * The endpoints jobs are served on, in the {@link Routes} shape the request
1621
- * pipeline takes. None when the jobs run in process.
1634
+ * pipeline takes. None in `'long-running'` mode.
1622
1635
  */
1623
- const jobRoutes = (meta) => meta.config?.mode === "in-process" ? {} : {
1636
+ const jobRoutes = (meta) => meta.config?.mode === "long-running" ? {} : {
1624
1637
  [DISPATCH_ROUTE_KEY]: dispatchRoute(meta),
1625
1638
  [RUN_ROUTE_KEY]: runRoute(meta)
1626
1639
  };
@@ -1640,7 +1653,7 @@ const warnUnsupportedJobOptions = (jobs, transport, logger = console) => {
1640
1653
  if (retrying.length === 0) return;
1641
1654
  const named = retrying.map((jobKey) => `"${jobKey}"`).join(", ");
1642
1655
  if (!transport) {
1643
- logger.warn(`[kizuna] ${named} declare \`retry\`, but no transport is configured, so a failed run is not retried. Pass one as \`jobRunner.transport\` in \`kizuna.config.ts\` to make retrying real.`);
1656
+ logger.warn(`[kizuna] ${named} declare \`retry\`, but \`jobRunner.transport\` is \`false\`, so a failed run is not retried. Pass a transport in \`kizuna.config.ts\` to make retrying real.`);
1644
1657
  return;
1645
1658
  }
1646
1659
  if (!transport.supports.retry) logger.warn(`[kizuna] ${named} declare \`retry\`, but the "${transport.name}" transport does not retry, so the count is ignored.`);
@@ -1674,7 +1687,7 @@ const dispatchHandler = (meta) => {
1674
1687
  for (const { jobKey } of require_plugin_server.flattenJobs(meta.jobs)) {
1675
1688
  const jobFn = jobFnAt(runner, jobKey);
1676
1689
  if (!jobFn) continue;
1677
- thunks[jobKey] = () => jobFn.run();
1690
+ thunks[jobKey] = () => attemptJob(() => jobFn.run(), jobKey, meta.onError);
1678
1691
  }
1679
1692
  return (async () => {
1680
1693
  const result = await dispatchDueJobs({ jobs: meta.jobs }, thunks, {
@@ -1735,8 +1748,13 @@ const runHandler = (meta) => {
1735
1748
  body: { detail: `No job named "${job}" on this api.` }
1736
1749
  };
1737
1750
  try {
1738
- return await jobFn.run(input);
1751
+ return await attemptJob(() => jobFn.run(input), job, meta.onError);
1739
1752
  } catch (error) {
1753
+ if (error instanceof ResponseError) return {
1754
+ status: error.status,
1755
+ body: error.body,
1756
+ headers: error.headers
1757
+ };
1740
1758
  if (error instanceof JobInputError) return {
1741
1759
  status: 422,
1742
1760
  body: { detail: `Input for job "${job}" failed validation.` }
@@ -2598,6 +2616,12 @@ Object.defineProperty(exports, "assertNoPathCollisions", {
2598
2616
  return assertNoPathCollisions;
2599
2617
  }
2600
2618
  });
2619
+ Object.defineProperty(exports, "attemptJob", {
2620
+ enumerable: true,
2621
+ get: function() {
2622
+ return attemptJob;
2623
+ }
2624
+ });
2601
2625
  Object.defineProperty(exports, "bearerChallenge", {
2602
2626
  enumerable: true,
2603
2627
  get: function() {
@@ -1,6 +1,6 @@
1
1
  import { g as ROUTES_GROUP, n as PLUGIN_SERVERS_META_KEY, o as pluginRouteTree, p as HANDLER, t as PLUGIN_ROUTES_META_KEY } from "./plugin-xxCxibmu.mjs";
2
2
  import { D as resolveBaseType, E as readObjectShape, O as unwrapOptionalWrappers, c as isBinarySchema, m as readDef, o as findCoercedSchemaPath, p as isVoidSchema, t as ProblemDetailsSchema, u as isFileSchema } from "./error-response-D7urgxeq.mjs";
3
- import { A as deriveToolNames, B as streamSchemas, G as isSuccessStatus, I as routeStreams, K as isZodSchema, M as EVENT_STREAM_MEDIA_TYPE, N as assertValidStreams, P as encodeStreamBody, Q as resolveResponseEtag, R as streamContentType, S as dueSchedules, U as isJsonMediaType, W as isStreamResponse, X as resolveResponseCache, Y as resolveResponseBody, Z as resolveResponseContentType, _ as jobAt, c as cacheHeaders, ct as parsePath, dt as formatValidationError, ft as isRouteDefinition, h as isCompiledJob, k as encodeForWire, lt as allowedMethodsForPath, m as flattenJobs, mt as resolveCoercionPlans, pt as validateRequest, u as deprecationHeaders, ut as flattenRoutes, y as toJobResponse } from "./plugin-server-D8XrYDQU.mjs";
3
+ import { A as deriveToolNames, B as streamSchemas, G as isSuccessStatus, I as routeStreams, K as isZodSchema, M as EVENT_STREAM_MEDIA_TYPE, N as assertValidStreams, P as encodeStreamBody, Q as resolveResponseEtag, R as streamContentType, S as dueSchedules, U as isJsonMediaType, W as isStreamResponse, X as resolveResponseCache, Y as resolveResponseBody, Z as resolveResponseContentType, _ as jobAt, c as cacheHeaders, ct as parsePath, dt as formatValidationError, ft as isRouteDefinition, h as isCompiledJob, k as encodeForWire, lt as allowedMethodsForPath, m as flattenJobs, mt as resolveCoercionPlans, pt as validateRequest, u as deprecationHeaders, ut as flattenRoutes, y as toJobResponse } from "./plugin-server-l_eKX28n.mjs";
4
4
  import { l as authenticationChallenge, p as resolveSecurityRequirements } from "./schemas-DBX8DwFb.mjs";
5
5
  import { z } from "zod";
6
6
  //#region src/tool-definitions.ts
@@ -853,6 +853,25 @@ const jobFnAt = (runner, jobKey) => {
853
853
  const candidate = node;
854
854
  return typeof candidate?.run === "function" && typeof candidate.queue === "function" ? candidate : void 0;
855
855
  };
856
+ /**
857
+ * Run a job no caller awaits, rejecting when it fails and reporting the
858
+ * failure to `onError`, or to `logger` without one.
859
+ */
860
+ const attemptJob = async (run, jobKey, onError, logger = console) => {
861
+ try {
862
+ const response = await run();
863
+ if (response.status >= 400) throw new ResponseError(response);
864
+ return response;
865
+ } catch (error) {
866
+ if (!onError) logger.error(`[kizuna] Job "${jobKey}" failed:`, error);
867
+ else try {
868
+ onError(jobKey, error);
869
+ } catch (hookError) {
870
+ logger.error("[kizuna] The jobs onError threw:", hookError);
871
+ }
872
+ throw error;
873
+ }
874
+ };
856
875
  const handlerAt = (handlers, jobKey) => {
857
876
  let current = handlers;
858
877
  for (const segment of jobKey.split(".")) {
@@ -905,13 +924,7 @@ const createJobRunner = (source, handlers, options) => {
905
924
  };
906
925
  const runDetached = (jobKey, input, runAt) => {
907
926
  const start = () => {
908
- invoke(jobKey, input).catch((error) => {
909
- if (options?.onError) {
910
- options.onError(jobKey, error);
911
- return;
912
- }
913
- console.error(`[kizuna] Queued job "${jobKey}" failed:`, error);
914
- });
927
+ attemptJob(() => invoke(jobKey, input), jobKey, options?.onError).catch(() => {});
915
928
  };
916
929
  const time = runAt?.getTime();
917
930
  if (time === void 0 || time <= Date.now()) {
@@ -1618,9 +1631,9 @@ const assembleApi = (contract, parts) => {
1618
1631
  };
1619
1632
  /**
1620
1633
  * The endpoints jobs are served on, in the {@link Routes} shape the request
1621
- * pipeline takes. None when the jobs run in process.
1634
+ * pipeline takes. None in `'long-running'` mode.
1622
1635
  */
1623
- const jobRoutes = (meta) => meta.config?.mode === "in-process" ? {} : {
1636
+ const jobRoutes = (meta) => meta.config?.mode === "long-running" ? {} : {
1624
1637
  [DISPATCH_ROUTE_KEY]: dispatchRoute(meta),
1625
1638
  [RUN_ROUTE_KEY]: runRoute(meta)
1626
1639
  };
@@ -1640,7 +1653,7 @@ const warnUnsupportedJobOptions = (jobs, transport, logger = console) => {
1640
1653
  if (retrying.length === 0) return;
1641
1654
  const named = retrying.map((jobKey) => `"${jobKey}"`).join(", ");
1642
1655
  if (!transport) {
1643
- logger.warn(`[kizuna] ${named} declare \`retry\`, but no transport is configured, so a failed run is not retried. Pass one as \`jobRunner.transport\` in \`kizuna.config.ts\` to make retrying real.`);
1656
+ logger.warn(`[kizuna] ${named} declare \`retry\`, but \`jobRunner.transport\` is \`false\`, so a failed run is not retried. Pass a transport in \`kizuna.config.ts\` to make retrying real.`);
1644
1657
  return;
1645
1658
  }
1646
1659
  if (!transport.supports.retry) logger.warn(`[kizuna] ${named} declare \`retry\`, but the "${transport.name}" transport does not retry, so the count is ignored.`);
@@ -1674,7 +1687,7 @@ const dispatchHandler = (meta) => {
1674
1687
  for (const { jobKey } of flattenJobs(meta.jobs)) {
1675
1688
  const jobFn = jobFnAt(runner, jobKey);
1676
1689
  if (!jobFn) continue;
1677
- thunks[jobKey] = () => jobFn.run();
1690
+ thunks[jobKey] = () => attemptJob(() => jobFn.run(), jobKey, meta.onError);
1678
1691
  }
1679
1692
  return (async () => {
1680
1693
  const result = await dispatchDueJobs({ jobs: meta.jobs }, thunks, {
@@ -1735,8 +1748,13 @@ const runHandler = (meta) => {
1735
1748
  body: { detail: `No job named "${job}" on this api.` }
1736
1749
  };
1737
1750
  try {
1738
- return await jobFn.run(input);
1751
+ return await attemptJob(() => jobFn.run(input), job, meta.onError);
1739
1752
  } catch (error) {
1753
+ if (error instanceof ResponseError) return {
1754
+ status: error.status,
1755
+ body: error.body,
1756
+ headers: error.headers
1757
+ };
1740
1758
  if (error instanceof JobInputError) return {
1741
1759
  status: 422,
1742
1760
  body: { detail: `Input for job "${job}" failed validation.` }
@@ -2472,4 +2490,4 @@ const headersToObject = (headers) => {
2472
2490
  return result;
2473
2491
  };
2474
2492
  //#endregion
2475
- export { waitUntil as $, parseBodyText as A, toolRefusal as At, routeClaims as B, getHeaderValue as C, buildToolDefinitions as Ct, jobRouter as D, toolInputJsonSchema as Dt, isGuardDenial as E, selectToolRoutes as Et, runRoute as F, insufficientScope as G, matchRoute as H, warnUnsupportedJobOptions as I, JobDispatchError as J, requiresDenial as K, isRawResponse as L, renderJsonResult as M, routerFromRoutes as N, jobRoutes as O, toolJsonSchema as Ot, runHandler as P, jobFnAt as Q, rawResponse as R, extractCredential as S, toolEvents as St, headersToObject as T, describeTool as Tt, sharedSegmentRoute as U, isMalformedPath as V, sortFlattenedRoutes as W, JobInputError as X, defineJobTransport as Y, createJobRunner as Z, contractOf as _, isGroupSet as _t, HANDLER_ARG_KEYS as a, dueJobs as at, dispatchRoute as b, expandStreamTools as bt, ROUTER_META as c, problemFromBody as ct, SCHEMES_META as d, createPermissions as dt, ResponseError as et, adapterContextOf as f, createRoles as ft, callGuard as g, createGroups as gt, boundJobKeys as h, permissionNames as ht, GUARD_SCHEMA_META as i, dispatchSucceeded as it, parseFetchBody as j, jobRunnerFrom as k, toolOptionsOf as kt, RUN_ROUTE_KEY as l, STATUS_TITLES as lt, bearerChallenge as m, isRoles as mt, DISPATCH_ROUTE_KEY as n, DispatchResultSchema as nt, JOBS_META as o, failedJobs as ot, assembleApi as p, isPermissions as pt, withPermissions as q, GUARDS_META as r, dispatchDueJobs as rt, REQUEST_CONTEXT_META as s, problemDetails as st, API_META as t, DispatchFailedSchema as tt, ResponseValidationError as u, getStatusText as ut, defineAdapter as v, assembleRoutes as vt, guardDenyFor as w, buildToolInputSchema as wt, entriesToObject as x, streamToolsOf as xt, dispatchHandler as y, groupRoutes as yt, assertNoPathCollisions as z };
2493
+ export { jobFnAt as $, parseBodyText as A, toolOptionsOf as At, routeClaims as B, getHeaderValue as C, toolEvents as Ct, jobRouter as D, selectToolRoutes as Dt, isGuardDenial as E, describeTool as Et, runRoute as F, insufficientScope as G, matchRoute as H, warnUnsupportedJobOptions as I, JobDispatchError as J, requiresDenial as K, isRawResponse as L, renderJsonResult as M, routerFromRoutes as N, jobRoutes as O, toolInputJsonSchema as Ot, runHandler as P, createJobRunner as Q, rawResponse as R, extractCredential as S, streamToolsOf as St, headersToObject as T, buildToolInputSchema as Tt, sharedSegmentRoute as U, isMalformedPath as V, sortFlattenedRoutes as W, JobInputError as X, defineJobTransport as Y, attemptJob as Z, contractOf as _, createGroups as _t, HANDLER_ARG_KEYS as a, dispatchSucceeded as at, dispatchRoute as b, groupRoutes as bt, ROUTER_META as c, problemDetails as ct, SCHEMES_META as d, getStatusText as dt, waitUntil as et, adapterContextOf as f, createPermissions as ft, callGuard as g, permissionNames as gt, boundJobKeys as h, isRoles as ht, GUARD_SCHEMA_META as i, dispatchDueJobs as it, parseFetchBody as j, toolRefusal as jt, jobRunnerFrom as k, toolJsonSchema as kt, RUN_ROUTE_KEY as l, problemFromBody as lt, bearerChallenge as m, isPermissions as mt, DISPATCH_ROUTE_KEY as n, DispatchFailedSchema as nt, JOBS_META as o, dueJobs as ot, assembleApi as p, createRoles as pt, withPermissions as q, GUARDS_META as r, DispatchResultSchema as rt, REQUEST_CONTEXT_META as s, failedJobs as st, API_META as t, ResponseError as tt, ResponseValidationError as u, STATUS_TITLES as ut, defineAdapter as v, isGroupSet as vt, guardDenyFor as w, buildToolDefinitions as wt, entriesToObject as x, expandStreamTools as xt, dispatchHandler as y, assembleRoutes as yt, assertNoPathCollisions as z };
@@ -1394,8 +1394,8 @@ interface JobFn<Job extends CompiledJob> {
1394
1394
  */
1395
1395
  run: (...args: JobRunArgs<Job>) => Promise<JobHandlerReturn<Job['definition']>>;
1396
1396
  /**
1397
- * Put the job in line and answer without waiting for it. With no transport
1398
- * configured the job runs in this process and is lost on a crash.
1397
+ * Put the job in line and answer without waiting for it. With
1398
+ * `transport: false` the job runs in this process and is lost on a crash.
1399
1399
  */
1400
1400
  queue: (...args: JobQueueArgs<Job>) => Promise<void>;
1401
1401
  }
@@ -1417,8 +1417,10 @@ declare class JobInputError extends Error {
1417
1417
  constructor(job: string, issues: z.core.$ZodIssue[]);
1418
1418
  }
1419
1419
  /**
1420
- * Called when a job queued without a transport rejects. Without one, the
1421
- * failure is logged.
1420
+ * Called for every failed run of a job that no caller awaits: one a worker,
1421
+ * `/jobs/dispatch` or `/jobs/run` ran, or one queued with `transport: false`. A
1422
+ * run fails when its handler throws or answers a status of 400 or more, which
1423
+ * arrives as a `ResponseError`. Without one, the failure is logged.
1422
1424
  */
1423
1425
  type JobErrorHandler = (job: string, error: unknown) => void;
1424
1426
  interface JobRunnerOptions {
@@ -1479,7 +1481,7 @@ type JobsConfig = HttpJobsConfig | InProcessJobsConfig;
1479
1481
  interface HttpJobsConfig {
1480
1482
  /**
1481
1483
  * `'http'` serves `/jobs/dispatch` and `/jobs/run`, guarded by the jobs'
1482
- * identity. `'in-process'` is for a long-running server whose schedules
1484
+ * identity. `'long-running'` is for a long-running server whose schedules
1483
1485
  * `startJobs` ticks, and serves neither.
1484
1486
  */
1485
1487
  mode: 'http';
@@ -1517,7 +1519,7 @@ interface HttpJobsConfig {
1517
1519
  * No job endpoint is served, so the jobs need no identity.
1518
1520
  */
1519
1521
  interface InProcessJobsConfig {
1520
- mode: 'in-process';
1522
+ mode: 'long-running';
1521
1523
  path?: never;
1522
1524
  method?: never;
1523
1525
  windowMs?: never;
@@ -1536,13 +1538,15 @@ type JobRunnerConfig = JobsConfig & JobDeliveryConfig;
1536
1538
  */
1537
1539
  interface JobDeliveryConfig {
1538
1540
  /**
1539
- * Carries a queued job to whatever runs it. Without one, `queue` runs the
1540
- * job in this process and it is lost on a crash.
1541
+ * Carries a queued job to whatever runs it. `false` runs a queued job in
1542
+ * this process, without waiting for it, and loses it on a crash or a
1543
+ * serverless freeze.
1541
1544
  */
1542
- transport?: JobTransport;
1545
+ transport: JobTransport | false;
1543
1546
  /**
1544
- * Reached when a job fails after its response was sent, which is the only
1545
- * point where nothing else can report it.
1547
+ * Reached by every failed run no caller awaits, from a worker,
1548
+ * `/jobs/dispatch`, `/jobs/run`, or `queue` with `transport: false`. Called
1549
+ * once per attempt.
1546
1550
  */
1547
1551
  onError?: JobErrorHandler;
1548
1552
  }
@@ -2488,7 +2492,7 @@ declare const assembleApi: <const R extends Routes>(contract: {
2488
2492
  }, parts: ApiParts) => ApiWithRouter<R>;
2489
2493
  /**
2490
2494
  * The endpoints jobs are served on, in the {@link Routes} shape the request
2491
- * pipeline takes. None when the jobs run in process.
2495
+ * pipeline takes. None in `'long-running'` mode.
2492
2496
  */
2493
2497
  declare const jobRoutes: (meta: JobsMeta) => Routes;
2494
2498
  /**
@@ -1394,8 +1394,8 @@ interface JobFn<Job extends CompiledJob> {
1394
1394
  */
1395
1395
  run: (...args: JobRunArgs<Job>) => Promise<JobHandlerReturn<Job['definition']>>;
1396
1396
  /**
1397
- * Put the job in line and answer without waiting for it. With no transport
1398
- * configured the job runs in this process and is lost on a crash.
1397
+ * Put the job in line and answer without waiting for it. With
1398
+ * `transport: false` the job runs in this process and is lost on a crash.
1399
1399
  */
1400
1400
  queue: (...args: JobQueueArgs<Job>) => Promise<void>;
1401
1401
  }
@@ -1417,8 +1417,10 @@ declare class JobInputError extends Error {
1417
1417
  constructor(job: string, issues: z.core.$ZodIssue[]);
1418
1418
  }
1419
1419
  /**
1420
- * Called when a job queued without a transport rejects. Without one, the
1421
- * failure is logged.
1420
+ * Called for every failed run of a job that no caller awaits: one a worker,
1421
+ * `/jobs/dispatch` or `/jobs/run` ran, or one queued with `transport: false`. A
1422
+ * run fails when its handler throws or answers a status of 400 or more, which
1423
+ * arrives as a `ResponseError`. Without one, the failure is logged.
1422
1424
  */
1423
1425
  type JobErrorHandler = (job: string, error: unknown) => void;
1424
1426
  interface JobRunnerOptions {
@@ -1479,7 +1481,7 @@ type JobsConfig = HttpJobsConfig | InProcessJobsConfig;
1479
1481
  interface HttpJobsConfig {
1480
1482
  /**
1481
1483
  * `'http'` serves `/jobs/dispatch` and `/jobs/run`, guarded by the jobs'
1482
- * identity. `'in-process'` is for a long-running server whose schedules
1484
+ * identity. `'long-running'` is for a long-running server whose schedules
1483
1485
  * `startJobs` ticks, and serves neither.
1484
1486
  */
1485
1487
  mode: 'http';
@@ -1517,7 +1519,7 @@ interface HttpJobsConfig {
1517
1519
  * No job endpoint is served, so the jobs need no identity.
1518
1520
  */
1519
1521
  interface InProcessJobsConfig {
1520
- mode: 'in-process';
1522
+ mode: 'long-running';
1521
1523
  path?: never;
1522
1524
  method?: never;
1523
1525
  windowMs?: never;
@@ -1536,13 +1538,15 @@ type JobRunnerConfig = JobsConfig & JobDeliveryConfig;
1536
1538
  */
1537
1539
  interface JobDeliveryConfig {
1538
1540
  /**
1539
- * Carries a queued job to whatever runs it. Without one, `queue` runs the
1540
- * job in this process and it is lost on a crash.
1541
+ * Carries a queued job to whatever runs it. `false` runs a queued job in
1542
+ * this process, without waiting for it, and loses it on a crash or a
1543
+ * serverless freeze.
1541
1544
  */
1542
- transport?: JobTransport;
1545
+ transport: JobTransport | false;
1543
1546
  /**
1544
- * Reached when a job fails after its response was sent, which is the only
1545
- * point where nothing else can report it.
1547
+ * Reached by every failed run no caller awaits, from a worker,
1548
+ * `/jobs/dispatch`, `/jobs/run`, or `queue` with `transport: false`. Called
1549
+ * once per attempt.
1546
1550
  */
1547
1551
  onError?: JobErrorHandler;
1548
1552
  }
@@ -2488,7 +2492,7 @@ declare const assembleApi: <const R extends Routes>(contract: {
2488
2492
  }, parts: ApiParts) => ApiWithRouter<R>;
2489
2493
  /**
2490
2494
  * The endpoints jobs are served on, in the {@link Routes} shape the request
2491
- * pipeline takes. None when the jobs run in process.
2495
+ * pipeline takes. None in `'long-running'` mode.
2492
2496
  */
2493
2497
  declare const jobRoutes: (meta: JobsMeta) => Routes;
2494
2498
  /**
package/dist/adapter.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_plugin = require("./plugin-Dw-yCjTY.cjs");
3
- const require_plugin_server = require("./plugin-server-tW5ZoOud.cjs");
3
+ const require_plugin_server = require("./plugin-server-6sIGS0RF.cjs");
4
4
  const require_schemas = require("./schemas-Bre1FVHq.cjs");
5
- const require_adapter = require("./adapter-tET-kVcP.cjs");
5
+ const require_adapter = require("./adapter-BcRUajrL.cjs");
6
6
  exports.API_META = require_adapter.API_META;
7
7
  exports.AUTO_GUARD_BRAND = require_plugin.AUTO_GUARD_BRAND;
8
8
  exports.AUTO_RESPONSES_BRAND = require_plugin.AUTO_RESPONSES_BRAND;
@@ -1,3 +1,3 @@
1
1
  import { A as AutoResponsesBrand, B as ROUTES_GROUP, D as AUTO_RESPONSES_BRAND, I as HANDLER_CONTEXT_BRAND, K as RouteDefinition, L as HandlerContextBrand, T as AUTO_GUARD_BRAND, W as ResponseHeaders, Y as RoutePath, Z as Routes, at as ProblemDetails, c as authenticationChallenge, f as resolveSecurityRequirements, st as problemDetails, z as Method } from "./error-response-YbkRMKno.cjs";
2
- import { $ as jobRouter, $i as buildPath, $n as isCompiledJob, $r as SharedSegmentRoute, A as RenderedResult, Aa as insufficientScope, B as bearerChallenge, Bi as buildToolInputSchema, C as JOBS_META, Ci as ValidationFailure, D as REQUEST_CONTEXT_META, Di as formatValidationError, E as MountedOf, Ei as flattenRoutes, F as RouteMatcher, Fn as CompiledJob, G as dispatchHandler, Gi as toolOptionsOf, Gr as RawResponse, Gt as PluginExportValues, H as callGuard, Hi as selectToolRoutes, Ht as PluginArgs, I as SCHEMES_META, J as extractCredential, Jn as Jobs, K as dispatchRoute, Ki as toolRefusal, Kr as isRawResponse, Kt as PluginExportsOf, L as ServerOptions, Li as ToolDefinition, Ln as FlattenedJob, Lt as ApiPlugins, M as RequestContextRun, Ma as withPermissions, N as RequestPipeline, O as ROUTER_META, Oi as isRouteDefinition, P as ResponseValidationError, Q as isGuardDenial, Qn as flattenJobs, Qr as RouteMatch, R as adapterContextOf, Ri as ToolInputSchema, S as HandlerContextOf, Sr as defineJobTransport, T as MountArgsOf, Ti as allowedMethodsForPath, U as contractOf, Ui as toolInputJsonSchema, Ut as PluginDeclaration, V as boundJobKeys, Vi as describeTool, Vn as JobHandler, W as defineAdapter, Wi as toolJsonSchema, Wn as JobHandlers, Wr as isGroupSet, Wt as PluginDefinition, X as guardDenyFor, Xr as MatchResult, Xt as PluginRoutes, Y as getHeaderValue, Z as headersToObject, Zi as PathSegment, Zr as PathParamsResult, Zt as PluginRoutesOf, _ as GuardDeny, _i as RequestContextValues, a as AdapterRequest, ai as BrandedHandlerContext, an as definePlugin, ar as JobInputError, at as routerFromRoutes, b as HANDLER_ARG_KEYS, bi as Router, br as JobWorkerContext, c as ApiBrand, ct as warnUnsupportedJobOptions, d as DISPATCH_ROUTE_KEY, dr as createJobRunner, dt as groupRoutes, ea as parsePath, ei as isMalformedPath, et as jobRoutes, f as ErrorFormatter, fa as encodeStreamBody, fi as GuardedParamNames, fr as jobFnAt, ft as createApiReference, g as GuardDenialBody, gi as RawInputs, gr as JobTransport, gt as resolvePlugins, h as GuardDenial, hi as HandlersFromRoutes, hr as JobMessage, ht as pluginRoutesOf, i as AdapterDefinition, ir as JobFnByKey, it as renderJsonResult, j as RequestContextMap, ja as requiresDenial, k as RUN_ROUTE_KEY, ka as AccessCheckInput, ki as validateRequest, l as ApiParts, li as GuardParams, lr as JobRunner, lt as ApiRouter, m as GUARD_SCHEMA_META, mr as JobDispatchError, mt as pluginRouterOf, n as API_META, na as EncodeStreamOptions, ni as sharedSegmentRoute, nr as JobErrorHandler, nt as parseBodyText, o as AdapterResult, oi as ContextFromAuth, on as pluginRouteTree, ot as runHandler, p as GUARDS_META, pr as JobDescriptor, pt as pluginExportsOf, q as entriesToObject, qr as rawResponse, r as Adapter, ri as sortFlattenedRoutes, rt as parseFetchBody, s as AnyAdapter, sa as StreamContext, si as FlattenedRoute, st as runRoute, t as ADAPTER_CONTEXT, ti as matchRoute, tn as ResolvedPlugin, tr as jobAt, tt as jobRunnerFrom, u as ApiWithRouter, ur as JobRunnerOptions, ut as ResponseError, v as GuardMap, w as JobsMeta, wi as ValidationStage, x as HandleArgs, xi as RoutesWithHandlerContext, xr as ScheduledJob, y as GuardRun, yi as RouteHandler, yr as JobWorker, yt as isStreamResponse, z as assembleApi, zi as buildToolDefinitions } from "./adapter-D50gicHq.cjs";
2
+ import { $ as jobRouter, $i as buildPath, $n as isCompiledJob, $r as SharedSegmentRoute, A as RenderedResult, Aa as insufficientScope, B as bearerChallenge, Bi as buildToolInputSchema, C as JOBS_META, Ci as ValidationFailure, D as REQUEST_CONTEXT_META, Di as formatValidationError, E as MountedOf, Ei as flattenRoutes, F as RouteMatcher, Fn as CompiledJob, G as dispatchHandler, Gi as toolOptionsOf, Gr as RawResponse, Gt as PluginExportValues, H as callGuard, Hi as selectToolRoutes, Ht as PluginArgs, I as SCHEMES_META, J as extractCredential, Jn as Jobs, K as dispatchRoute, Ki as toolRefusal, Kr as isRawResponse, Kt as PluginExportsOf, L as ServerOptions, Li as ToolDefinition, Ln as FlattenedJob, Lt as ApiPlugins, M as RequestContextRun, Ma as withPermissions, N as RequestPipeline, O as ROUTER_META, Oi as isRouteDefinition, P as ResponseValidationError, Q as isGuardDenial, Qn as flattenJobs, Qr as RouteMatch, R as adapterContextOf, Ri as ToolInputSchema, S as HandlerContextOf, Sr as defineJobTransport, T as MountArgsOf, Ti as allowedMethodsForPath, U as contractOf, Ui as toolInputJsonSchema, Ut as PluginDeclaration, V as boundJobKeys, Vi as describeTool, Vn as JobHandler, W as defineAdapter, Wi as toolJsonSchema, Wn as JobHandlers, Wr as isGroupSet, Wt as PluginDefinition, X as guardDenyFor, Xr as MatchResult, Xt as PluginRoutes, Y as getHeaderValue, Z as headersToObject, Zi as PathSegment, Zr as PathParamsResult, Zt as PluginRoutesOf, _ as GuardDeny, _i as RequestContextValues, a as AdapterRequest, ai as BrandedHandlerContext, an as definePlugin, ar as JobInputError, at as routerFromRoutes, b as HANDLER_ARG_KEYS, bi as Router, br as JobWorkerContext, c as ApiBrand, ct as warnUnsupportedJobOptions, d as DISPATCH_ROUTE_KEY, dr as createJobRunner, dt as groupRoutes, ea as parsePath, ei as isMalformedPath, et as jobRoutes, f as ErrorFormatter, fa as encodeStreamBody, fi as GuardedParamNames, fr as jobFnAt, ft as createApiReference, g as GuardDenialBody, gi as RawInputs, gr as JobTransport, gt as resolvePlugins, h as GuardDenial, hi as HandlersFromRoutes, hr as JobMessage, ht as pluginRoutesOf, i as AdapterDefinition, ir as JobFnByKey, it as renderJsonResult, j as RequestContextMap, ja as requiresDenial, k as RUN_ROUTE_KEY, ka as AccessCheckInput, ki as validateRequest, l as ApiParts, li as GuardParams, lr as JobRunner, lt as ApiRouter, m as GUARD_SCHEMA_META, mr as JobDispatchError, mt as pluginRouterOf, n as API_META, na as EncodeStreamOptions, ni as sharedSegmentRoute, nr as JobErrorHandler, nt as parseBodyText, o as AdapterResult, oi as ContextFromAuth, on as pluginRouteTree, ot as runHandler, p as GUARDS_META, pr as JobDescriptor, pt as pluginExportsOf, q as entriesToObject, qr as rawResponse, r as Adapter, ri as sortFlattenedRoutes, rt as parseFetchBody, s as AnyAdapter, sa as StreamContext, si as FlattenedRoute, st as runRoute, t as ADAPTER_CONTEXT, ti as matchRoute, tn as ResolvedPlugin, tr as jobAt, tt as jobRunnerFrom, u as ApiWithRouter, ur as JobRunnerOptions, ut as ResponseError, v as GuardMap, w as JobsMeta, wi as ValidationStage, x as HandleArgs, xi as RoutesWithHandlerContext, xr as ScheduledJob, y as GuardRun, yi as RouteHandler, yr as JobWorker, yt as isStreamResponse, z as assembleApi, zi as buildToolDefinitions } from "./adapter-VoxBoXIp.cjs";
3
3
  export { ADAPTER_CONTEXT, API_META, AUTO_GUARD_BRAND, AUTO_RESPONSES_BRAND, AccessCheckInput, Adapter, AdapterDefinition, AdapterRequest, AdapterResult, AnyAdapter, ApiBrand, ApiParts, ApiPlugins, ApiRouter, ApiWithRouter, AutoResponsesBrand, BrandedHandlerContext, CompiledJob, ContextFromAuth, DISPATCH_ROUTE_KEY, EncodeStreamOptions, ErrorFormatter, FlattenedJob, FlattenedRoute, GUARDS_META, GUARD_SCHEMA_META, GuardDenial, GuardDenialBody, GuardDeny, GuardMap, GuardParams, GuardRun, GuardedParamNames, HANDLER_ARG_KEYS, HANDLER_CONTEXT_BRAND, HandleArgs, HandlerContextBrand, HandlerContextOf, HandlersFromRoutes, JOBS_META, JobDescriptor, JobDispatchError, JobErrorHandler, JobFnByKey, JobHandler, JobHandlers, JobInputError, JobMessage, JobRunner, JobRunnerOptions, JobTransport, JobWorker, JobWorkerContext, Jobs, JobsMeta, MatchResult, Method, MountArgsOf, MountedOf, PathParamsResult, PathSegment, PluginArgs, PluginDeclaration, PluginDefinition, PluginExportValues, PluginExportsOf, PluginRoutes, PluginRoutesOf, ProblemDetails, REQUEST_CONTEXT_META, ROUTER_META, ROUTES_GROUP, RUN_ROUTE_KEY, RawInputs, RawResponse, RenderedResult, RequestContextMap, RequestContextRun, RequestContextValues, RequestPipeline, ResolvedPlugin, ResponseError, ResponseHeaders, ResponseValidationError, RouteDefinition, RouteHandler, RouteMatch, RouteMatcher, RoutePath, Router, Routes, RoutesWithHandlerContext, SCHEMES_META, ScheduledJob, ServerOptions, SharedSegmentRoute, StreamContext, ToolDefinition, ToolInputSchema, ValidationFailure, ValidationStage, adapterContextOf, allowedMethodsForPath, assembleApi, authenticationChallenge, bearerChallenge, boundJobKeys, buildPath, buildToolDefinitions, buildToolInputSchema, callGuard, contractOf, createApiReference, createJobRunner, defineAdapter, defineJobTransport, definePlugin, describeTool, dispatchHandler, dispatchRoute, encodeStreamBody, entriesToObject, extractCredential, flattenJobs, flattenRoutes, formatValidationError, getHeaderValue, groupRoutes, guardDenyFor, headersToObject, insufficientScope, isCompiledJob, isGroupSet, isGuardDenial, isMalformedPath, isRawResponse, isRouteDefinition, isStreamResponse, jobAt, jobFnAt, jobRouter, jobRoutes, jobRunnerFrom, matchRoute, parseBodyText, parseFetchBody, parsePath, pluginExportsOf, pluginRouteTree, pluginRouterOf, pluginRoutesOf, problemDetails, rawResponse, renderJsonResult, requiresDenial, resolvePlugins, resolveSecurityRequirements, routerFromRoutes, runHandler, runRoute, selectToolRoutes, sharedSegmentRoute, sortFlattenedRoutes, toolInputJsonSchema, toolJsonSchema, toolOptionsOf, toolRefusal, validateRequest, warnUnsupportedJobOptions, withPermissions };
@@ -1,3 +1,3 @@
1
1
  import { A as AutoResponsesBrand, B as ROUTES_GROUP, D as AUTO_RESPONSES_BRAND, I as HANDLER_CONTEXT_BRAND, K as RouteDefinition, L as HandlerContextBrand, T as AUTO_GUARD_BRAND, W as ResponseHeaders, Y as RoutePath, Z as Routes, at as ProblemDetails, c as authenticationChallenge, f as resolveSecurityRequirements, st as problemDetails, z as Method } from "./error-response-NoOGdh8H.mjs";
2
- import { $ as jobRouter, $i as buildPath, $n as isCompiledJob, $r as SharedSegmentRoute, A as RenderedResult, Aa as insufficientScope, B as bearerChallenge, Bi as buildToolInputSchema, C as JOBS_META, Ci as ValidationFailure, D as REQUEST_CONTEXT_META, Di as formatValidationError, E as MountedOf, Ei as flattenRoutes, F as RouteMatcher, Fn as CompiledJob, G as dispatchHandler, Gi as toolOptionsOf, Gr as RawResponse, Gt as PluginExportValues, H as callGuard, Hi as selectToolRoutes, Ht as PluginArgs, I as SCHEMES_META, J as extractCredential, Jn as Jobs, K as dispatchRoute, Ki as toolRefusal, Kr as isRawResponse, Kt as PluginExportsOf, L as ServerOptions, Li as ToolDefinition, Ln as FlattenedJob, Lt as ApiPlugins, M as RequestContextRun, Ma as withPermissions, N as RequestPipeline, O as ROUTER_META, Oi as isRouteDefinition, P as ResponseValidationError, Q as isGuardDenial, Qn as flattenJobs, Qr as RouteMatch, R as adapterContextOf, Ri as ToolInputSchema, S as HandlerContextOf, Sr as defineJobTransport, T as MountArgsOf, Ti as allowedMethodsForPath, U as contractOf, Ui as toolInputJsonSchema, Ut as PluginDeclaration, V as boundJobKeys, Vi as describeTool, Vn as JobHandler, W as defineAdapter, Wi as toolJsonSchema, Wn as JobHandlers, Wr as isGroupSet, Wt as PluginDefinition, X as guardDenyFor, Xr as MatchResult, Xt as PluginRoutes, Y as getHeaderValue, Z as headersToObject, Zi as PathSegment, Zr as PathParamsResult, Zt as PluginRoutesOf, _ as GuardDeny, _i as RequestContextValues, a as AdapterRequest, ai as BrandedHandlerContext, an as definePlugin, ar as JobInputError, at as routerFromRoutes, b as HANDLER_ARG_KEYS, bi as Router, br as JobWorkerContext, c as ApiBrand, ct as warnUnsupportedJobOptions, d as DISPATCH_ROUTE_KEY, dr as createJobRunner, dt as groupRoutes, ea as parsePath, ei as isMalformedPath, et as jobRoutes, f as ErrorFormatter, fa as encodeStreamBody, fi as GuardedParamNames, fr as jobFnAt, ft as createApiReference, g as GuardDenialBody, gi as RawInputs, gr as JobTransport, gt as resolvePlugins, h as GuardDenial, hi as HandlersFromRoutes, hr as JobMessage, ht as pluginRoutesOf, i as AdapterDefinition, ir as JobFnByKey, it as renderJsonResult, j as RequestContextMap, ja as requiresDenial, k as RUN_ROUTE_KEY, ka as AccessCheckInput, ki as validateRequest, l as ApiParts, li as GuardParams, lr as JobRunner, lt as ApiRouter, m as GUARD_SCHEMA_META, mr as JobDispatchError, mt as pluginRouterOf, n as API_META, na as EncodeStreamOptions, ni as sharedSegmentRoute, nr as JobErrorHandler, nt as parseBodyText, o as AdapterResult, oi as ContextFromAuth, on as pluginRouteTree, ot as runHandler, p as GUARDS_META, pr as JobDescriptor, pt as pluginExportsOf, q as entriesToObject, qr as rawResponse, r as Adapter, ri as sortFlattenedRoutes, rt as parseFetchBody, s as AnyAdapter, sa as StreamContext, si as FlattenedRoute, st as runRoute, t as ADAPTER_CONTEXT, ti as matchRoute, tn as ResolvedPlugin, tr as jobAt, tt as jobRunnerFrom, u as ApiWithRouter, ur as JobRunnerOptions, ut as ResponseError, v as GuardMap, w as JobsMeta, wi as ValidationStage, x as HandleArgs, xi as RoutesWithHandlerContext, xr as ScheduledJob, y as GuardRun, yi as RouteHandler, yr as JobWorker, yt as isStreamResponse, z as assembleApi, zi as buildToolDefinitions } from "./adapter-DAGfLId-.mjs";
2
+ import { $ as jobRouter, $i as buildPath, $n as isCompiledJob, $r as SharedSegmentRoute, A as RenderedResult, Aa as insufficientScope, B as bearerChallenge, Bi as buildToolInputSchema, C as JOBS_META, Ci as ValidationFailure, D as REQUEST_CONTEXT_META, Di as formatValidationError, E as MountedOf, Ei as flattenRoutes, F as RouteMatcher, Fn as CompiledJob, G as dispatchHandler, Gi as toolOptionsOf, Gr as RawResponse, Gt as PluginExportValues, H as callGuard, Hi as selectToolRoutes, Ht as PluginArgs, I as SCHEMES_META, J as extractCredential, Jn as Jobs, K as dispatchRoute, Ki as toolRefusal, Kr as isRawResponse, Kt as PluginExportsOf, L as ServerOptions, Li as ToolDefinition, Ln as FlattenedJob, Lt as ApiPlugins, M as RequestContextRun, Ma as withPermissions, N as RequestPipeline, O as ROUTER_META, Oi as isRouteDefinition, P as ResponseValidationError, Q as isGuardDenial, Qn as flattenJobs, Qr as RouteMatch, R as adapterContextOf, Ri as ToolInputSchema, S as HandlerContextOf, Sr as defineJobTransport, T as MountArgsOf, Ti as allowedMethodsForPath, U as contractOf, Ui as toolInputJsonSchema, Ut as PluginDeclaration, V as boundJobKeys, Vi as describeTool, Vn as JobHandler, W as defineAdapter, Wi as toolJsonSchema, Wn as JobHandlers, Wr as isGroupSet, Wt as PluginDefinition, X as guardDenyFor, Xr as MatchResult, Xt as PluginRoutes, Y as getHeaderValue, Z as headersToObject, Zi as PathSegment, Zr as PathParamsResult, Zt as PluginRoutesOf, _ as GuardDeny, _i as RequestContextValues, a as AdapterRequest, ai as BrandedHandlerContext, an as definePlugin, ar as JobInputError, at as routerFromRoutes, b as HANDLER_ARG_KEYS, bi as Router, br as JobWorkerContext, c as ApiBrand, ct as warnUnsupportedJobOptions, d as DISPATCH_ROUTE_KEY, dr as createJobRunner, dt as groupRoutes, ea as parsePath, ei as isMalformedPath, et as jobRoutes, f as ErrorFormatter, fa as encodeStreamBody, fi as GuardedParamNames, fr as jobFnAt, ft as createApiReference, g as GuardDenialBody, gi as RawInputs, gr as JobTransport, gt as resolvePlugins, h as GuardDenial, hi as HandlersFromRoutes, hr as JobMessage, ht as pluginRoutesOf, i as AdapterDefinition, ir as JobFnByKey, it as renderJsonResult, j as RequestContextMap, ja as requiresDenial, k as RUN_ROUTE_KEY, ka as AccessCheckInput, ki as validateRequest, l as ApiParts, li as GuardParams, lr as JobRunner, lt as ApiRouter, m as GUARD_SCHEMA_META, mr as JobDispatchError, mt as pluginRouterOf, n as API_META, na as EncodeStreamOptions, ni as sharedSegmentRoute, nr as JobErrorHandler, nt as parseBodyText, o as AdapterResult, oi as ContextFromAuth, on as pluginRouteTree, ot as runHandler, p as GUARDS_META, pr as JobDescriptor, pt as pluginExportsOf, q as entriesToObject, qr as rawResponse, r as Adapter, ri as sortFlattenedRoutes, rt as parseFetchBody, s as AnyAdapter, sa as StreamContext, si as FlattenedRoute, st as runRoute, t as ADAPTER_CONTEXT, ti as matchRoute, tn as ResolvedPlugin, tr as jobAt, tt as jobRunnerFrom, u as ApiWithRouter, ur as JobRunnerOptions, ut as ResponseError, v as GuardMap, w as JobsMeta, wi as ValidationStage, x as HandleArgs, xi as RoutesWithHandlerContext, xr as ScheduledJob, y as GuardRun, yi as RouteHandler, yr as JobWorker, yt as isStreamResponse, z as assembleApi, zi as buildToolDefinitions } from "./adapter-Co19yIKD.mjs";
3
3
  export { ADAPTER_CONTEXT, API_META, AUTO_GUARD_BRAND, AUTO_RESPONSES_BRAND, AccessCheckInput, Adapter, AdapterDefinition, AdapterRequest, AdapterResult, AnyAdapter, ApiBrand, ApiParts, ApiPlugins, ApiRouter, ApiWithRouter, AutoResponsesBrand, BrandedHandlerContext, CompiledJob, ContextFromAuth, DISPATCH_ROUTE_KEY, EncodeStreamOptions, ErrorFormatter, FlattenedJob, FlattenedRoute, GUARDS_META, GUARD_SCHEMA_META, GuardDenial, GuardDenialBody, GuardDeny, GuardMap, GuardParams, GuardRun, GuardedParamNames, HANDLER_ARG_KEYS, HANDLER_CONTEXT_BRAND, HandleArgs, HandlerContextBrand, HandlerContextOf, HandlersFromRoutes, JOBS_META, JobDescriptor, JobDispatchError, JobErrorHandler, JobFnByKey, JobHandler, JobHandlers, JobInputError, JobMessage, JobRunner, JobRunnerOptions, JobTransport, JobWorker, JobWorkerContext, Jobs, JobsMeta, MatchResult, Method, MountArgsOf, MountedOf, PathParamsResult, PathSegment, PluginArgs, PluginDeclaration, PluginDefinition, PluginExportValues, PluginExportsOf, PluginRoutes, PluginRoutesOf, ProblemDetails, REQUEST_CONTEXT_META, ROUTER_META, ROUTES_GROUP, RUN_ROUTE_KEY, RawInputs, RawResponse, RenderedResult, RequestContextMap, RequestContextRun, RequestContextValues, RequestPipeline, ResolvedPlugin, ResponseError, ResponseHeaders, ResponseValidationError, RouteDefinition, RouteHandler, RouteMatch, RouteMatcher, RoutePath, Router, Routes, RoutesWithHandlerContext, SCHEMES_META, ScheduledJob, ServerOptions, SharedSegmentRoute, StreamContext, ToolDefinition, ToolInputSchema, ValidationFailure, ValidationStage, adapterContextOf, allowedMethodsForPath, assembleApi, authenticationChallenge, bearerChallenge, boundJobKeys, buildPath, buildToolDefinitions, buildToolInputSchema, callGuard, contractOf, createApiReference, createJobRunner, defineAdapter, defineJobTransport, definePlugin, describeTool, dispatchHandler, dispatchRoute, encodeStreamBody, entriesToObject, extractCredential, flattenJobs, flattenRoutes, formatValidationError, getHeaderValue, groupRoutes, guardDenyFor, headersToObject, insufficientScope, isCompiledJob, isGroupSet, isGuardDenial, isMalformedPath, isRawResponse, isRouteDefinition, isStreamResponse, jobAt, jobFnAt, jobRouter, jobRoutes, jobRunnerFrom, matchRoute, parseBodyText, parseFetchBody, parsePath, pluginExportsOf, pluginRouteTree, pluginRouterOf, pluginRoutesOf, problemDetails, rawResponse, renderJsonResult, requiresDenial, resolvePlugins, resolveSecurityRequirements, routerFromRoutes, runHandler, runRoute, selectToolRoutes, sharedSegmentRoute, sortFlattenedRoutes, toolInputJsonSchema, toolJsonSchema, toolOptionsOf, toolRefusal, validateRequest, warnUnsupportedJobOptions, withPermissions };
package/dist/adapter.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { a as definePlugin, d as AUTO_RESPONSES_BRAND, g as ROUTES_GROUP, l as AUTO_GUARD_BRAND, m as HANDLER_CONTEXT_BRAND, o as pluginRouteTree } from "./plugin-xxCxibmu.mjs";
2
- import { P as encodeStreamBody, W as isStreamResponse, _ as jobAt, a as pluginRoutesOf, ct as parsePath, dt as formatValidationError, ft as isRouteDefinition, h as isCompiledJob, i as pluginRouterOf, lt as allowedMethodsForPath, m as flattenJobs, o as resolvePlugins, pt as validateRequest, r as pluginExportsOf, st as buildPath, t as createApiReference, ut as flattenRoutes } from "./plugin-server-D8XrYDQU.mjs";
2
+ import { P as encodeStreamBody, W as isStreamResponse, _ as jobAt, a as pluginRoutesOf, ct as parsePath, dt as formatValidationError, ft as isRouteDefinition, h as isCompiledJob, i as pluginRouterOf, lt as allowedMethodsForPath, m as flattenJobs, o as resolvePlugins, pt as validateRequest, r as pluginExportsOf, st as buildPath, t as createApiReference, ut as flattenRoutes } from "./plugin-server-l_eKX28n.mjs";
3
3
  import { l as authenticationChallenge, p as resolveSecurityRequirements } from "./schemas-DBX8DwFb.mjs";
4
- import { A as parseBodyText, At as toolRefusal, C as getHeaderValue, Ct as buildToolDefinitions, D as jobRouter, Dt as toolInputJsonSchema, E as isGuardDenial, Et as selectToolRoutes, F as runRoute, G as insufficientScope, H as matchRoute, I as warnUnsupportedJobOptions, J as JobDispatchError, K as requiresDenial, L as isRawResponse, M as renderJsonResult, N as routerFromRoutes, O as jobRoutes, Ot as toolJsonSchema, P as runHandler, Q as jobFnAt, R as rawResponse, S as extractCredential, T as headersToObject, Tt as describeTool, U as sharedSegmentRoute, V as isMalformedPath, W as sortFlattenedRoutes, X as JobInputError, Y as defineJobTransport, Z as createJobRunner, _ as contractOf, _t as isGroupSet, a as HANDLER_ARG_KEYS, b as dispatchRoute, c as ROUTER_META, d as SCHEMES_META, et as ResponseError, f as adapterContextOf, g as callGuard, h as boundJobKeys, i as GUARD_SCHEMA_META, j as parseFetchBody, k as jobRunnerFrom, kt as toolOptionsOf, l as RUN_ROUTE_KEY, m as bearerChallenge, n as DISPATCH_ROUTE_KEY, o as JOBS_META, p as assembleApi, q as withPermissions, r as GUARDS_META, s as REQUEST_CONTEXT_META, st as problemDetails, t as API_META, u as ResponseValidationError, v as defineAdapter, w as guardDenyFor, wt as buildToolInputSchema, x as entriesToObject, y as dispatchHandler, yt as groupRoutes } from "./adapter-cRyeEuKZ.mjs";
4
+ import { $ as jobFnAt, A as parseBodyText, At as toolOptionsOf, C as getHeaderValue, D as jobRouter, Dt as selectToolRoutes, E as isGuardDenial, Et as describeTool, F as runRoute, G as insufficientScope, H as matchRoute, I as warnUnsupportedJobOptions, J as JobDispatchError, K as requiresDenial, L as isRawResponse, M as renderJsonResult, N as routerFromRoutes, O as jobRoutes, Ot as toolInputJsonSchema, P as runHandler, Q as createJobRunner, R as rawResponse, S as extractCredential, T as headersToObject, Tt as buildToolInputSchema, U as sharedSegmentRoute, V as isMalformedPath, W as sortFlattenedRoutes, X as JobInputError, Y as defineJobTransport, _ as contractOf, a as HANDLER_ARG_KEYS, b as dispatchRoute, bt as groupRoutes, c as ROUTER_META, ct as problemDetails, d as SCHEMES_META, f as adapterContextOf, g as callGuard, h as boundJobKeys, i as GUARD_SCHEMA_META, j as parseFetchBody, jt as toolRefusal, k as jobRunnerFrom, kt as toolJsonSchema, l as RUN_ROUTE_KEY, m as bearerChallenge, n as DISPATCH_ROUTE_KEY, o as JOBS_META, p as assembleApi, q as withPermissions, r as GUARDS_META, s as REQUEST_CONTEXT_META, t as API_META, tt as ResponseError, u as ResponseValidationError, v as defineAdapter, vt as isGroupSet, w as guardDenyFor, wt as buildToolDefinitions, x as entriesToObject, y as dispatchHandler } from "./adapter-CcVfT9VP.mjs";
5
5
  export { API_META, AUTO_GUARD_BRAND, AUTO_RESPONSES_BRAND, DISPATCH_ROUTE_KEY, GUARDS_META, GUARD_SCHEMA_META, HANDLER_ARG_KEYS, HANDLER_CONTEXT_BRAND, JOBS_META, JobDispatchError, JobInputError, REQUEST_CONTEXT_META, ROUTER_META, ROUTES_GROUP, RUN_ROUTE_KEY, ResponseError, ResponseValidationError, SCHEMES_META, adapterContextOf, allowedMethodsForPath, assembleApi, authenticationChallenge, bearerChallenge, boundJobKeys, buildPath, buildToolDefinitions, buildToolInputSchema, callGuard, contractOf, createApiReference, createJobRunner, defineAdapter, defineJobTransport, definePlugin, describeTool, dispatchHandler, dispatchRoute, encodeStreamBody, entriesToObject, extractCredential, flattenJobs, flattenRoutes, formatValidationError, getHeaderValue, groupRoutes, guardDenyFor, headersToObject, insufficientScope, isCompiledJob, isGroupSet, isGuardDenial, isMalformedPath, isRawResponse, isRouteDefinition, isStreamResponse, jobAt, jobFnAt, jobRouter, jobRoutes, jobRunnerFrom, matchRoute, parseBodyText, parseFetchBody, parsePath, pluginExportsOf, pluginRouteTree, pluginRouterOf, pluginRoutesOf, problemDetails, rawResponse, renderJsonResult, requiresDenial, resolvePlugins, resolveSecurityRequirements, routerFromRoutes, runHandler, runRoute, selectToolRoutes, sharedSegmentRoute, sortFlattenedRoutes, toolInputJsonSchema, toolJsonSchema, toolOptionsOf, toolRefusal, validateRequest, warnUnsupportedJobOptions, withPermissions };
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_error_response = require("./error-response-DN5Dsf8b.cjs");
3
- const require_plugin_server = require("./plugin-server-tW5ZoOud.cjs");
3
+ const require_plugin_server = require("./plugin-server-6sIGS0RF.cjs");
4
4
  //#region src/generator.ts
5
5
  /**
6
6
  * Every route the api serves, the app's and the plugins' under their slugs,
@@ -1,5 +1,5 @@
1
1
  import { K as RouteDefinition, W as ResponseHeaders, Z as Routes, j as CachePolicy } from "./error-response-YbkRMKno.cjs";
2
- import { $n as isCompiledJob, At as sanitizeFieldName, Ct as mergeHeaderFields, Dt as resolveResponseEtag, En as ApiDefinition, Et as resolveResponseContentType, Fn as CompiledJob, Ft as toPascalCase, Jn as Jobs, Ln as FlattenedJob, Mt as shortTypeName, Nt as statusToCamelCase, Ot as resolveResponseHeaders, Pt as toCamelCase, Qn as flattenJobs, St as localTypeName, Tt as resolveResponseCache, _a as streamMode, _t as isHintPrefix, bt as isSuccessStatus, ea as parsePath, ga as streamContentType, ha as soleStreamResponse, jt as sanitizeIdentifier, kt as resolveResponseStream, ma as routeStreams, pa as isNamedStream, ta as EVENT_STREAM_MEDIA_TYPE, tr as jobAt, ua as StreamMode, va as streamSchemas, vt as isJsonMediaType, wn as GeneratedFile, wt as resolveResponseBody, xt as isZodSchema, ya as streamStatuses, yt as isStreamResponse } from "./adapter-D50gicHq.cjs";
2
+ import { $n as isCompiledJob, At as sanitizeFieldName, Ct as mergeHeaderFields, Dt as resolveResponseEtag, En as ApiDefinition, Et as resolveResponseContentType, Fn as CompiledJob, Ft as toPascalCase, Jn as Jobs, Ln as FlattenedJob, Mt as shortTypeName, Nt as statusToCamelCase, Ot as resolveResponseHeaders, Pt as toCamelCase, Qn as flattenJobs, St as localTypeName, Tt as resolveResponseCache, _a as streamMode, _t as isHintPrefix, bt as isSuccessStatus, ea as parsePath, ga as streamContentType, ha as soleStreamResponse, jt as sanitizeIdentifier, kt as resolveResponseStream, ma as routeStreams, pa as isNamedStream, ta as EVENT_STREAM_MEDIA_TYPE, tr as jobAt, ua as StreamMode, va as streamSchemas, vt as isJsonMediaType, wn as GeneratedFile, wt as resolveResponseBody, xt as isZodSchema, ya as streamStatuses, yt as isStreamResponse } from "./adapter-VoxBoXIp.cjs";
3
3
  import { z } from "zod";
4
4
 
5
5
  //#region src/zod-internals.d.ts
@@ -1,5 +1,5 @@
1
1
  import { K as RouteDefinition, W as ResponseHeaders, Z as Routes, j as CachePolicy } from "./error-response-NoOGdh8H.mjs";
2
- import { $n as isCompiledJob, At as sanitizeFieldName, Ct as mergeHeaderFields, Dt as resolveResponseEtag, En as ApiDefinition, Et as resolveResponseContentType, Fn as CompiledJob, Ft as toPascalCase, Jn as Jobs, Ln as FlattenedJob, Mt as shortTypeName, Nt as statusToCamelCase, Ot as resolveResponseHeaders, Pt as toCamelCase, Qn as flattenJobs, St as localTypeName, Tt as resolveResponseCache, _a as streamMode, _t as isHintPrefix, bt as isSuccessStatus, ea as parsePath, ga as streamContentType, ha as soleStreamResponse, jt as sanitizeIdentifier, kt as resolveResponseStream, ma as routeStreams, pa as isNamedStream, ta as EVENT_STREAM_MEDIA_TYPE, tr as jobAt, ua as StreamMode, va as streamSchemas, vt as isJsonMediaType, wn as GeneratedFile, wt as resolveResponseBody, xt as isZodSchema, ya as streamStatuses, yt as isStreamResponse } from "./adapter-DAGfLId-.mjs";
2
+ import { $n as isCompiledJob, At as sanitizeFieldName, Ct as mergeHeaderFields, Dt as resolveResponseEtag, En as ApiDefinition, Et as resolveResponseContentType, Fn as CompiledJob, Ft as toPascalCase, Jn as Jobs, Ln as FlattenedJob, Mt as shortTypeName, Nt as statusToCamelCase, Ot as resolveResponseHeaders, Pt as toCamelCase, Qn as flattenJobs, St as localTypeName, Tt as resolveResponseCache, _a as streamMode, _t as isHintPrefix, bt as isSuccessStatus, ea as parsePath, ga as streamContentType, ha as soleStreamResponse, jt as sanitizeIdentifier, kt as resolveResponseStream, ma as routeStreams, pa as isNamedStream, ta as EVENT_STREAM_MEDIA_TYPE, tr as jobAt, ua as StreamMode, va as streamSchemas, vt as isJsonMediaType, wn as GeneratedFile, wt as resolveResponseBody, xt as isZodSchema, ya as streamStatuses, yt as isStreamResponse } from "./adapter-Co19yIKD.mjs";
3
3
  import { z } from "zod";
4
4
 
5
5
  //#region src/zod-internals.d.ts
@@ -1,5 +1,5 @@
1
1
  import { C as readMetaExamples, E as readObjectShape, O as unwrapOptionalWrappers, S as readMetaDescription, T as readModelSchema, _ as readDiscriminatedUnion, b as readMeta, c as isBinarySchema, d as isIntegerSchema, f as isObjectSchema, g as readDeprecation, h as readDefType, i as FILE_PROBE, l as isDiscriminatedUnionSchema, m as readDef, p as isVoidSchema, s as globalRegistrySchemas, u as isFileSchema, v as readDiscriminatorLiteral, w as readMetaId, x as readMetaBrand, y as readDiscriminatorStringLiteral } from "./error-response-D7urgxeq.mjs";
2
- import { $ as resolveResponseHeaders, A as deriveToolNames, B as streamSchemas, F as isNamedStream, G as isSuccessStatus, H as isHintPrefix, I as routeStreams, J as mergeHeaderFields, K as isZodSchema, L as soleStreamResponse, M as EVENT_STREAM_MEDIA_TYPE, Q as resolveResponseEtag, R as streamContentType, U as isJsonMediaType, V as streamStatuses, W as isStreamResponse, X as resolveResponseCache, Y as resolveResponseBody, Z as resolveResponseContentType, _ as jobAt, a as pluginRoutesOf, at as toCamelCase, c as cacheHeaders, ct as parsePath, et as resolveResponseStream, ft as isRouteDefinition, h as isCompiledJob, it as statusToCamelCase, j as toToolName, k as encodeForWire, m as flattenJobs, n as describeIssue, nt as sanitizeIdentifier, ot as toPascalCase, q as localTypeName, rt as shortTypeName, tt as sanitizeFieldName, u as deprecationHeaders, ut as flattenRoutes, z as streamMode } from "./plugin-server-D8XrYDQU.mjs";
2
+ import { $ as resolveResponseHeaders, A as deriveToolNames, B as streamSchemas, F as isNamedStream, G as isSuccessStatus, H as isHintPrefix, I as routeStreams, J as mergeHeaderFields, K as isZodSchema, L as soleStreamResponse, M as EVENT_STREAM_MEDIA_TYPE, Q as resolveResponseEtag, R as streamContentType, U as isJsonMediaType, V as streamStatuses, W as isStreamResponse, X as resolveResponseCache, Y as resolveResponseBody, Z as resolveResponseContentType, _ as jobAt, a as pluginRoutesOf, at as toCamelCase, c as cacheHeaders, ct as parsePath, et as resolveResponseStream, ft as isRouteDefinition, h as isCompiledJob, it as statusToCamelCase, j as toToolName, k as encodeForWire, m as flattenJobs, n as describeIssue, nt as sanitizeIdentifier, ot as toPascalCase, q as localTypeName, rt as shortTypeName, tt as sanitizeFieldName, u as deprecationHeaders, ut as flattenRoutes, z as streamMode } from "./plugin-server-l_eKX28n.mjs";
3
3
  //#region src/generator.ts
4
4
  /**
5
5
  * Every route the api serves, the app's and the plugins' under their slugs,
package/dist/index.cjs CHANGED
@@ -1,9 +1,9 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  const require_plugin = require("./plugin-Dw-yCjTY.cjs");
3
3
  const require_error_response = require("./error-response-DN5Dsf8b.cjs");
4
- const require_plugin_server = require("./plugin-server-tW5ZoOud.cjs");
4
+ const require_plugin_server = require("./plugin-server-6sIGS0RF.cjs");
5
5
  const require_schemas = require("./schemas-Bre1FVHq.cjs");
6
- const require_adapter = require("./adapter-tET-kVcP.cjs");
6
+ const require_adapter = require("./adapter-BcRUajrL.cjs");
7
7
  let zod = require("zod");
8
8
  //#region src/group-routes.ts
9
9
  /**
@@ -645,7 +645,7 @@ const defineConfig = (options) => {
645
645
  const api = buildApi(contract, {
646
646
  guards,
647
647
  requestContext: handlersOf(options.requestContext, RESOLVER),
648
- jobTransport: options.jobRunner?.transport,
648
+ jobTransport: options.jobRunner?.transport || void 0,
649
649
  onJobError: options.jobRunner?.onError
650
650
  }, options.adapter);
651
651
  apiReference.bind(api);
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { $ as SecurityRequirement, A as AutoResponsesBrand, B as ROUTES_GROUP, C as isPermissions, D as AUTO_RESPONSES_BRAND, E as AUTO_GUARD_WRITTEN_BRAND, F as HANDLER, G as RouteAuth, H as ResponseContentType, I as HANDLER_CONTEXT_BRAND, J as RouteHiddenToolCheck, K as RouteDefinition, L as HandlerContextBrand, M as DECLARATION, N as DeclarationKind, O as AuthoredRouteDefinition, P as GuardStatus, Q as SchemeNameOf, R as METHODS, S as createRoles, T as AUTO_GUARD_BRAND, U as ResponseDefinition, V as RequiredPermissions, X as RouteToolOptions, Y as RoutePath, Z as Routes, _ as PermissionSet, a as OAuthFlows, at as ProblemDetails, b as RoleNamesOf, ct as problemFromBody, d as isSecurityScheme, et as StreamDefinition, g as PermissionName, h as PermissionCatalog, i as OAuthFlow, it as GuardSchemaCheck, j as CachePolicy, k as AuthoredRoutes, l as authorizationServerIssuer, lt as STATUS_TITLES, m as GrantNamesOf, n as isProblemDetails, nt as GuardBody, o as OpenApiSecuritySchemeObject, ot as StripProblemEnvelope, p as CatalogOf, q as RouteHandlerFunction, r as ContextOf, rt as GuardOutput, s as SecurityScheme, st as problemDetails, tt as StreamResponseDefinition, u as declaredScopes, ut as getStatusText, v as Permissions, w as isRoles, x as Roles, y as RoleDefinition, z as Method } from "./error-response-YbkRMKno.cjs";
2
- import { $i as buildPath, $n as isCompiledJob, $t as PluginSetupContext, Ai as ModelToolCall, An as RequestContextOf, Ar as nextRuns, Ba as CredentialOf, Bn as JobDefinition, Br as GroupPathsOf, Ca as ToolError, Cn as DiffSettings, Cr as JobSchedule, Da as expandStreamTools, Dn as ApiPluginsOf, Dr as dueSchedules, E as MountedOf, Ea as ToolResult, En as ApiDefinition, Er as cron, Fa as BasicConfig, Fi as ToolRunOptions, Fn as CompiledJob, Fr as RequestContextHeaderInputs, Ga as IdentityParamsOf, Gn as JobResponses, Gt as PluginExportValues, Ha as GrantsOf, Hn as JobHandlerArgs, Hr as ResolvedGroup, Ht as PluginArgs, Ia as BasicCredential, Ii as ToolRunResult, In as CompiledJobs, Ir as RequestContextHeaderValues, It as AnyPlugin, Ja as OAuth2Config, Ji as HasPathParams, Jn as Jobs, Jr as RouteBuilder, Jt as PluginList, Ka as IdentityRole, Kn as JobRunnerConfig, Kt as PluginExportsOf, La as BearerConfig, Li as ToolDefinition, Ln as FlattenedJob, Lr as RequestContextSchema, Lt as ApiPlugins, Mi as ToolAnswer, Mn as SchemesOf, Mr as scheduleExpression, Na as ApiKeyConfig, Ni as ToolEventYield, Nn as AuthoredJobDefinition, Nr as scheduleTimezone, Oa as toolEvents, Oi as isRouteDefinition, On as GuardSchemaOf, Or as firesBetween, Pa as ApiKeyCredential, Pi as ToolRunCall, Pn as AuthoredJobs, Pr as RequestContextConfig, Qi as RoutePathParamsCheck, Qn as flattenJobs, Qt as PluginSetup, Ra as BearerCredential, Rn as HttpJobsConfig, Rr as GroupOptions, Sa as ToolCall, Si as ThrowableReturn, Sn as ApiEntry, Sr as defineJobTransport, T as MountArgsOf, Ta as ToolKeys, Tn as apiEntries, Tr as assertValidSchedule, Ua as GuardHoldings, Un as JobHandlerReturn, Ur as createGroups, Ut as PluginDeclaration, Va as CustomConfig, Vn as JobHandler, Vr as GroupSet, Vt as PluginApi, Wa as Identity, Wn as JobHandlers, Wt as PluginDefinition, Xa as RoleOf, Xi as PathParamsCheck, Xn as JobsConfig, Xt as PluginRoutes, Y as getHeaderValue, Ya as OpenIdConnectConfig, Yi as PathParamName, Yn as JobsArg, Yr as RouteWithHandler, Za as RolesOf, Zn as NoJobs, Zt as PluginRoutesOf, _ as GuardDeny, _a as streamMode, _n as ConfiguredRequestContext, _r as JobTransportDefinition, aa as StreamChunk, ai as BrandedHandlerContext, an as definePlugin, ar as JobInputError, ba as StreamWithTools, bn as JobsOfTree, br as JobWorkerContext, ca as StreamMessage, ci as GuardAnswer, cr as JobRunArgs, da as StreamYield, di as GuardSuccess, dn as ConfiguredCodes, dr as createJobRunner, ea as parsePath, en as PluginsBySlug, er as isJobDefinition, fn as ConfiguredGroups, fr as jobFnAt, ga as streamContentType, gn as ConfiguredPlugins, gr as JobTransport, h as GuardDenial, ha as soleStreamResponse, hn as ConfiguredJobs, hr as JobMessage, ia as StreamBodyOf, ii as AuthContextOf, ir as JobFnByKey, ji as StreamTools, jn as RoutesOf, jr as parseCron, kn as JobsOf, kr as nextRun, la as StreamMessageOf, ln as ConfiguredAdapterContext, lr as JobRunner, ma as routeStreams, mi as HandlerReturn, mn as ConfiguredIdentities, mr as JobDispatchError, nr as JobErrorHandler, oa as StreamComment, oi as ContextFromAuth, or as JobQueueArgs, pa as isNamedStream, pi as HandlerArgs, pn as ConfiguredGuardSchema, pr as JobDescriptor, qa as NoCredential, qi as ExtractPathParams, qn as JobVoidReturn, qt as PluginFactory, ra as StreamBody, rr as JobFn, s as AnyAdapter, sa as StreamContext, sr as JobQueueOptions, ta as EVENT_STREAM_MEDIA_TYPE, tr as jobAt, u as ApiWithRouter, ua as StreamMode, ui as GuardReturn, un as ConfiguredAdapterValue, ur as JobRunnerOptions, ut as ResponseError, vi as RouteGuardBrandOf, vn as ConfiguredRequestContextSchemas, vr as JobTransportSupports, wa as ToolEvents, wn as GeneratedFile, wr as ParsedCron, xa as ToolAt, xi as RoutesWithHandlerContext, xn as KizunaConfigShape, xr as ScheduledJob, xt as isZodSchema, ya as streamStatuses, yn as JobFnOf, yr as JobWorker, yt as isStreamResponse, za as Credential, zn as InProcessJobsConfig, zr as GroupPaths } from "./adapter-D50gicHq.cjs";
2
+ import { $i as buildPath, $n as isCompiledJob, $t as PluginSetupContext, Ai as ModelToolCall, An as RequestContextOf, Ar as nextRuns, Ba as CredentialOf, Bn as JobDefinition, Br as GroupPathsOf, Ca as ToolError, Cn as DiffSettings, Cr as JobSchedule, Da as expandStreamTools, Dn as ApiPluginsOf, Dr as dueSchedules, E as MountedOf, Ea as ToolResult, En as ApiDefinition, Er as cron, Fa as BasicConfig, Fi as ToolRunOptions, Fn as CompiledJob, Fr as RequestContextHeaderInputs, Ga as IdentityParamsOf, Gn as JobResponses, Gt as PluginExportValues, Ha as GrantsOf, Hn as JobHandlerArgs, Hr as ResolvedGroup, Ht as PluginArgs, Ia as BasicCredential, Ii as ToolRunResult, In as CompiledJobs, Ir as RequestContextHeaderValues, It as AnyPlugin, Ja as OAuth2Config, Ji as HasPathParams, Jn as Jobs, Jr as RouteBuilder, Jt as PluginList, Ka as IdentityRole, Kn as JobRunnerConfig, Kt as PluginExportsOf, La as BearerConfig, Li as ToolDefinition, Ln as FlattenedJob, Lr as RequestContextSchema, Lt as ApiPlugins, Mi as ToolAnswer, Mn as SchemesOf, Mr as scheduleExpression, Na as ApiKeyConfig, Ni as ToolEventYield, Nn as AuthoredJobDefinition, Nr as scheduleTimezone, Oa as toolEvents, Oi as isRouteDefinition, On as GuardSchemaOf, Or as firesBetween, Pa as ApiKeyCredential, Pi as ToolRunCall, Pn as AuthoredJobs, Pr as RequestContextConfig, Qi as RoutePathParamsCheck, Qn as flattenJobs, Qt as PluginSetup, Ra as BearerCredential, Rn as HttpJobsConfig, Rr as GroupOptions, Sa as ToolCall, Si as ThrowableReturn, Sn as ApiEntry, Sr as defineJobTransport, T as MountArgsOf, Ta as ToolKeys, Tn as apiEntries, Tr as assertValidSchedule, Ua as GuardHoldings, Un as JobHandlerReturn, Ur as createGroups, Ut as PluginDeclaration, Va as CustomConfig, Vn as JobHandler, Vr as GroupSet, Vt as PluginApi, Wa as Identity, Wn as JobHandlers, Wt as PluginDefinition, Xa as RoleOf, Xi as PathParamsCheck, Xn as JobsConfig, Xt as PluginRoutes, Y as getHeaderValue, Ya as OpenIdConnectConfig, Yi as PathParamName, Yn as JobsArg, Yr as RouteWithHandler, Za as RolesOf, Zn as NoJobs, Zt as PluginRoutesOf, _ as GuardDeny, _a as streamMode, _n as ConfiguredRequestContext, _r as JobTransportDefinition, aa as StreamChunk, ai as BrandedHandlerContext, an as definePlugin, ar as JobInputError, ba as StreamWithTools, bn as JobsOfTree, br as JobWorkerContext, ca as StreamMessage, ci as GuardAnswer, cr as JobRunArgs, da as StreamYield, di as GuardSuccess, dn as ConfiguredCodes, dr as createJobRunner, ea as parsePath, en as PluginsBySlug, er as isJobDefinition, fn as ConfiguredGroups, fr as jobFnAt, ga as streamContentType, gn as ConfiguredPlugins, gr as JobTransport, h as GuardDenial, ha as soleStreamResponse, hn as ConfiguredJobs, hr as JobMessage, ia as StreamBodyOf, ii as AuthContextOf, ir as JobFnByKey, ji as StreamTools, jn as RoutesOf, jr as parseCron, kn as JobsOf, kr as nextRun, la as StreamMessageOf, ln as ConfiguredAdapterContext, lr as JobRunner, ma as routeStreams, mi as HandlerReturn, mn as ConfiguredIdentities, mr as JobDispatchError, nr as JobErrorHandler, oa as StreamComment, oi as ContextFromAuth, or as JobQueueArgs, pa as isNamedStream, pi as HandlerArgs, pn as ConfiguredGuardSchema, pr as JobDescriptor, qa as NoCredential, qi as ExtractPathParams, qn as JobVoidReturn, qt as PluginFactory, ra as StreamBody, rr as JobFn, s as AnyAdapter, sa as StreamContext, sr as JobQueueOptions, ta as EVENT_STREAM_MEDIA_TYPE, tr as jobAt, u as ApiWithRouter, ua as StreamMode, ui as GuardReturn, un as ConfiguredAdapterValue, ur as JobRunnerOptions, ut as ResponseError, vi as RouteGuardBrandOf, vn as ConfiguredRequestContextSchemas, vr as JobTransportSupports, wa as ToolEvents, wn as GeneratedFile, wr as ParsedCron, xa as ToolAt, xi as RoutesWithHandlerContext, xn as KizunaConfigShape, xr as ScheduledJob, xt as isZodSchema, ya as streamStatuses, yn as JobFnOf, yr as JobWorker, yt as isStreamResponse, za as Credential, zn as InProcessJobsConfig, zr as GroupPaths } from "./adapter-VoxBoXIp.cjs";
3
3
  import { a as buildProtectedResourceMetadata, c as ValidationErrorFor, d as isValidationError, i as assertCanonicalResourceUri, n as ProtectedResourceMetadata, o as BuiltinIssueCode, s as ValidationError, t as ProtectedResourceConfig, u as ValidationIssueCode } from "./protected-resource-metadata-B9hMFQ9N.cjs";
4
4
  import { z } from "zod";
5
5
  import { $input, $output } from "zod/v4/core";
@@ -906,9 +906,9 @@ type JobRunnerInput<J extends Jobs> = string extends keyof J ? {
906
906
  jobRunner?: JobRunnerConfig;
907
907
  } : {
908
908
  /**
909
- * How this deployment runs the jobs it declares: over HTTP or in
910
- * process, what carries queued work out of the process, and where a
911
- * failure is reported. The jobs themselves are declared with
909
+ * How this deployment runs the jobs it declares: over HTTP or from a
910
+ * long-running server, what carries queued work out of the process,
911
+ * and where a failure is reported. The jobs themselves are declared with
912
912
  * `k.jobs` and go under `jobs`.
913
913
  */
914
914
  jobRunner: JobRunnerConfig;
package/dist/index.d.mts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { $ as SecurityRequirement, A as AutoResponsesBrand, B as ROUTES_GROUP, C as isPermissions, D as AUTO_RESPONSES_BRAND, E as AUTO_GUARD_WRITTEN_BRAND, F as HANDLER, G as RouteAuth, H as ResponseContentType, I as HANDLER_CONTEXT_BRAND, J as RouteHiddenToolCheck, K as RouteDefinition, L as HandlerContextBrand, M as DECLARATION, N as DeclarationKind, O as AuthoredRouteDefinition, P as GuardStatus, Q as SchemeNameOf, R as METHODS, S as createRoles, T as AUTO_GUARD_BRAND, U as ResponseDefinition, V as RequiredPermissions, X as RouteToolOptions, Y as RoutePath, Z as Routes, _ as PermissionSet, a as OAuthFlows, at as ProblemDetails, b as RoleNamesOf, ct as problemFromBody, d as isSecurityScheme, et as StreamDefinition, g as PermissionName, h as PermissionCatalog, i as OAuthFlow, it as GuardSchemaCheck, j as CachePolicy, k as AuthoredRoutes, l as authorizationServerIssuer, lt as STATUS_TITLES, m as GrantNamesOf, n as isProblemDetails, nt as GuardBody, o as OpenApiSecuritySchemeObject, ot as StripProblemEnvelope, p as CatalogOf, q as RouteHandlerFunction, r as ContextOf, rt as GuardOutput, s as SecurityScheme, st as problemDetails, tt as StreamResponseDefinition, u as declaredScopes, ut as getStatusText, v as Permissions, w as isRoles, x as Roles, y as RoleDefinition, z as Method } from "./error-response-NoOGdh8H.mjs";
2
- import { $i as buildPath, $n as isCompiledJob, $t as PluginSetupContext, Ai as ModelToolCall, An as RequestContextOf, Ar as nextRuns, Ba as CredentialOf, Bn as JobDefinition, Br as GroupPathsOf, Ca as ToolError, Cn as DiffSettings, Cr as JobSchedule, Da as expandStreamTools, Dn as ApiPluginsOf, Dr as dueSchedules, E as MountedOf, Ea as ToolResult, En as ApiDefinition, Er as cron, Fa as BasicConfig, Fi as ToolRunOptions, Fn as CompiledJob, Fr as RequestContextHeaderInputs, Ga as IdentityParamsOf, Gn as JobResponses, Gt as PluginExportValues, Ha as GrantsOf, Hn as JobHandlerArgs, Hr as ResolvedGroup, Ht as PluginArgs, Ia as BasicCredential, Ii as ToolRunResult, In as CompiledJobs, Ir as RequestContextHeaderValues, It as AnyPlugin, Ja as OAuth2Config, Ji as HasPathParams, Jn as Jobs, Jr as RouteBuilder, Jt as PluginList, Ka as IdentityRole, Kn as JobRunnerConfig, Kt as PluginExportsOf, La as BearerConfig, Li as ToolDefinition, Ln as FlattenedJob, Lr as RequestContextSchema, Lt as ApiPlugins, Mi as ToolAnswer, Mn as SchemesOf, Mr as scheduleExpression, Na as ApiKeyConfig, Ni as ToolEventYield, Nn as AuthoredJobDefinition, Nr as scheduleTimezone, Oa as toolEvents, Oi as isRouteDefinition, On as GuardSchemaOf, Or as firesBetween, Pa as ApiKeyCredential, Pi as ToolRunCall, Pn as AuthoredJobs, Pr as RequestContextConfig, Qi as RoutePathParamsCheck, Qn as flattenJobs, Qt as PluginSetup, Ra as BearerCredential, Rn as HttpJobsConfig, Rr as GroupOptions, Sa as ToolCall, Si as ThrowableReturn, Sn as ApiEntry, Sr as defineJobTransport, T as MountArgsOf, Ta as ToolKeys, Tn as apiEntries, Tr as assertValidSchedule, Ua as GuardHoldings, Un as JobHandlerReturn, Ur as createGroups, Ut as PluginDeclaration, Va as CustomConfig, Vn as JobHandler, Vr as GroupSet, Vt as PluginApi, Wa as Identity, Wn as JobHandlers, Wt as PluginDefinition, Xa as RoleOf, Xi as PathParamsCheck, Xn as JobsConfig, Xt as PluginRoutes, Y as getHeaderValue, Ya as OpenIdConnectConfig, Yi as PathParamName, Yn as JobsArg, Yr as RouteWithHandler, Za as RolesOf, Zn as NoJobs, Zt as PluginRoutesOf, _ as GuardDeny, _a as streamMode, _n as ConfiguredRequestContext, _r as JobTransportDefinition, aa as StreamChunk, ai as BrandedHandlerContext, an as definePlugin, ar as JobInputError, ba as StreamWithTools, bn as JobsOfTree, br as JobWorkerContext, ca as StreamMessage, ci as GuardAnswer, cr as JobRunArgs, da as StreamYield, di as GuardSuccess, dn as ConfiguredCodes, dr as createJobRunner, ea as parsePath, en as PluginsBySlug, er as isJobDefinition, fn as ConfiguredGroups, fr as jobFnAt, ga as streamContentType, gn as ConfiguredPlugins, gr as JobTransport, h as GuardDenial, ha as soleStreamResponse, hn as ConfiguredJobs, hr as JobMessage, ia as StreamBodyOf, ii as AuthContextOf, ir as JobFnByKey, ji as StreamTools, jn as RoutesOf, jr as parseCron, kn as JobsOf, kr as nextRun, la as StreamMessageOf, ln as ConfiguredAdapterContext, lr as JobRunner, ma as routeStreams, mi as HandlerReturn, mn as ConfiguredIdentities, mr as JobDispatchError, nr as JobErrorHandler, oa as StreamComment, oi as ContextFromAuth, or as JobQueueArgs, pa as isNamedStream, pi as HandlerArgs, pn as ConfiguredGuardSchema, pr as JobDescriptor, qa as NoCredential, qi as ExtractPathParams, qn as JobVoidReturn, qt as PluginFactory, ra as StreamBody, rr as JobFn, s as AnyAdapter, sa as StreamContext, sr as JobQueueOptions, ta as EVENT_STREAM_MEDIA_TYPE, tr as jobAt, u as ApiWithRouter, ua as StreamMode, ui as GuardReturn, un as ConfiguredAdapterValue, ur as JobRunnerOptions, ut as ResponseError, vi as RouteGuardBrandOf, vn as ConfiguredRequestContextSchemas, vr as JobTransportSupports, wa as ToolEvents, wn as GeneratedFile, wr as ParsedCron, xa as ToolAt, xi as RoutesWithHandlerContext, xn as KizunaConfigShape, xr as ScheduledJob, xt as isZodSchema, ya as streamStatuses, yn as JobFnOf, yr as JobWorker, yt as isStreamResponse, za as Credential, zn as InProcessJobsConfig, zr as GroupPaths } from "./adapter-DAGfLId-.mjs";
2
+ import { $i as buildPath, $n as isCompiledJob, $t as PluginSetupContext, Ai as ModelToolCall, An as RequestContextOf, Ar as nextRuns, Ba as CredentialOf, Bn as JobDefinition, Br as GroupPathsOf, Ca as ToolError, Cn as DiffSettings, Cr as JobSchedule, Da as expandStreamTools, Dn as ApiPluginsOf, Dr as dueSchedules, E as MountedOf, Ea as ToolResult, En as ApiDefinition, Er as cron, Fa as BasicConfig, Fi as ToolRunOptions, Fn as CompiledJob, Fr as RequestContextHeaderInputs, Ga as IdentityParamsOf, Gn as JobResponses, Gt as PluginExportValues, Ha as GrantsOf, Hn as JobHandlerArgs, Hr as ResolvedGroup, Ht as PluginArgs, Ia as BasicCredential, Ii as ToolRunResult, In as CompiledJobs, Ir as RequestContextHeaderValues, It as AnyPlugin, Ja as OAuth2Config, Ji as HasPathParams, Jn as Jobs, Jr as RouteBuilder, Jt as PluginList, Ka as IdentityRole, Kn as JobRunnerConfig, Kt as PluginExportsOf, La as BearerConfig, Li as ToolDefinition, Ln as FlattenedJob, Lr as RequestContextSchema, Lt as ApiPlugins, Mi as ToolAnswer, Mn as SchemesOf, Mr as scheduleExpression, Na as ApiKeyConfig, Ni as ToolEventYield, Nn as AuthoredJobDefinition, Nr as scheduleTimezone, Oa as toolEvents, Oi as isRouteDefinition, On as GuardSchemaOf, Or as firesBetween, Pa as ApiKeyCredential, Pi as ToolRunCall, Pn as AuthoredJobs, Pr as RequestContextConfig, Qi as RoutePathParamsCheck, Qn as flattenJobs, Qt as PluginSetup, Ra as BearerCredential, Rn as HttpJobsConfig, Rr as GroupOptions, Sa as ToolCall, Si as ThrowableReturn, Sn as ApiEntry, Sr as defineJobTransport, T as MountArgsOf, Ta as ToolKeys, Tn as apiEntries, Tr as assertValidSchedule, Ua as GuardHoldings, Un as JobHandlerReturn, Ur as createGroups, Ut as PluginDeclaration, Va as CustomConfig, Vn as JobHandler, Vr as GroupSet, Vt as PluginApi, Wa as Identity, Wn as JobHandlers, Wt as PluginDefinition, Xa as RoleOf, Xi as PathParamsCheck, Xn as JobsConfig, Xt as PluginRoutes, Y as getHeaderValue, Ya as OpenIdConnectConfig, Yi as PathParamName, Yn as JobsArg, Yr as RouteWithHandler, Za as RolesOf, Zn as NoJobs, Zt as PluginRoutesOf, _ as GuardDeny, _a as streamMode, _n as ConfiguredRequestContext, _r as JobTransportDefinition, aa as StreamChunk, ai as BrandedHandlerContext, an as definePlugin, ar as JobInputError, ba as StreamWithTools, bn as JobsOfTree, br as JobWorkerContext, ca as StreamMessage, ci as GuardAnswer, cr as JobRunArgs, da as StreamYield, di as GuardSuccess, dn as ConfiguredCodes, dr as createJobRunner, ea as parsePath, en as PluginsBySlug, er as isJobDefinition, fn as ConfiguredGroups, fr as jobFnAt, ga as streamContentType, gn as ConfiguredPlugins, gr as JobTransport, h as GuardDenial, ha as soleStreamResponse, hn as ConfiguredJobs, hr as JobMessage, ia as StreamBodyOf, ii as AuthContextOf, ir as JobFnByKey, ji as StreamTools, jn as RoutesOf, jr as parseCron, kn as JobsOf, kr as nextRun, la as StreamMessageOf, ln as ConfiguredAdapterContext, lr as JobRunner, ma as routeStreams, mi as HandlerReturn, mn as ConfiguredIdentities, mr as JobDispatchError, nr as JobErrorHandler, oa as StreamComment, oi as ContextFromAuth, or as JobQueueArgs, pa as isNamedStream, pi as HandlerArgs, pn as ConfiguredGuardSchema, pr as JobDescriptor, qa as NoCredential, qi as ExtractPathParams, qn as JobVoidReturn, qt as PluginFactory, ra as StreamBody, rr as JobFn, s as AnyAdapter, sa as StreamContext, sr as JobQueueOptions, ta as EVENT_STREAM_MEDIA_TYPE, tr as jobAt, u as ApiWithRouter, ua as StreamMode, ui as GuardReturn, un as ConfiguredAdapterValue, ur as JobRunnerOptions, ut as ResponseError, vi as RouteGuardBrandOf, vn as ConfiguredRequestContextSchemas, vr as JobTransportSupports, wa as ToolEvents, wn as GeneratedFile, wr as ParsedCron, xa as ToolAt, xi as RoutesWithHandlerContext, xn as KizunaConfigShape, xr as ScheduledJob, xt as isZodSchema, ya as streamStatuses, yn as JobFnOf, yr as JobWorker, yt as isStreamResponse, za as Credential, zn as InProcessJobsConfig, zr as GroupPaths } from "./adapter-Co19yIKD.mjs";
3
3
  import { a as buildProtectedResourceMetadata, c as ValidationErrorFor, d as isValidationError, i as assertCanonicalResourceUri, n as ProtectedResourceMetadata, o as BuiltinIssueCode, s as ValidationError, t as ProtectedResourceConfig, u as ValidationIssueCode } from "./protected-resource-metadata-CfBVsqIk.mjs";
4
4
  import { z } from "zod";
5
5
  import { $input, $output } from "zod/v4/core";
@@ -906,9 +906,9 @@ type JobRunnerInput<J extends Jobs> = string extends keyof J ? {
906
906
  jobRunner?: JobRunnerConfig;
907
907
  } : {
908
908
  /**
909
- * How this deployment runs the jobs it declares: over HTTP or in
910
- * process, what carries queued work out of the process, and where a
911
- * failure is reported. The jobs themselves are declared with
909
+ * How this deployment runs the jobs it declares: over HTTP or from a
910
+ * long-running server, what carries queued work out of the process,
911
+ * and where a failure is reported. The jobs themselves are declared with
912
912
  * `k.jobs` and go under `jobs`.
913
913
  */
914
914
  jobRunner: JobRunnerConfig;
package/dist/index.mjs CHANGED
@@ -1,8 +1,8 @@
1
1
  import { a as definePlugin, c as createRoute, d as AUTO_RESPONSES_BRAND, f as DECLARATION, g as ROUTES_GROUP, h as METHODS, l as AUTO_GUARD_BRAND, m as HANDLER_CONTEXT_BRAND, o as pluginRouteTree, p as HANDLER, u as AUTO_GUARD_WRITTEN_BRAND } from "./plugin-xxCxibmu.mjs";
2
2
  import { E as readObjectShape, m as readDef, n as isProblemDetails, r as createModel, t as ProblemDetailsSchema } from "./error-response-D7urgxeq.mjs";
3
- import { C as firesBetween, D as scheduleExpression, E as parseCron, F as isNamedStream, I as routeStreams, K as isZodSchema, L as soleStreamResponse, M as EVENT_STREAM_MEDIA_TYPE, O as scheduleTimezone, R as streamContentType, S as dueSchedules, T as nextRuns, V as streamStatuses, W as isStreamResponse, Y as resolveResponseBody, _ as jobAt, b as assertValidSchedule, ct as parsePath, f as assertJobRunner, ft as isRouteDefinition, g as isJobDefinition, h as isCompiledJob, l as assertValidDeprecationDates, m as flattenJobs, o as resolvePlugins, p as buildJobs, r as pluginExportsOf, s as assertValidCache, st as buildPath, t as createApiReference, ut as flattenRoutes, v as jobClaims, w as nextRun, x as cron, z as streamMode } from "./plugin-server-D8XrYDQU.mjs";
3
+ import { C as firesBetween, D as scheduleExpression, E as parseCron, F as isNamedStream, I as routeStreams, K as isZodSchema, L as soleStreamResponse, M as EVENT_STREAM_MEDIA_TYPE, O as scheduleTimezone, R as streamContentType, S as dueSchedules, T as nextRuns, V as streamStatuses, W as isStreamResponse, Y as resolveResponseBody, _ as jobAt, b as assertValidSchedule, ct as parsePath, f as assertJobRunner, ft as isRouteDefinition, g as isJobDefinition, h as isCompiledJob, l as assertValidDeprecationDates, m as flattenJobs, o as resolvePlugins, p as buildJobs, r as pluginExportsOf, s as assertValidCache, st as buildPath, t as createApiReference, ut as flattenRoutes, v as jobClaims, w as nextRun, x as cron, z as streamMode } from "./plugin-server-l_eKX28n.mjs";
4
4
  import { a as assertCanonicalResourceUri, c as isValidationError, d as declaredScopes, f as isSecurityScheme, l as authenticationChallenge, o as buildProtectedResourceMetadata, p as resolveSecurityRequirements, u as authorizationServerIssuer } from "./schemas-DBX8DwFb.mjs";
5
- import { B as routeClaims, C as getHeaderValue, I as warnUnsupportedJobOptions, J as JobDispatchError, N as routerFromRoutes, Q as jobFnAt, St as toolEvents, X as JobInputError, Y as defineJobTransport, Z as createJobRunner, at as dueJobs, bt as expandStreamTools, ct as problemFromBody, dt as createPermissions, et as ResponseError, ft as createRoles, gt as createGroups, ht as permissionNames, it as dispatchSucceeded, lt as STATUS_TITLES, mt as isRoles, nt as DispatchResultSchema, o as JOBS_META, ot as failedJobs, p as assembleApi, pt as isPermissions, rt as dispatchDueJobs, st as problemDetails, tt as DispatchFailedSchema, ut as getStatusText, vt as assembleRoutes, xt as streamToolsOf, yt as groupRoutes, z as assertNoPathCollisions } from "./adapter-cRyeEuKZ.mjs";
5
+ import { $ as jobFnAt, B as routeClaims, C as getHeaderValue, Ct as toolEvents, I as warnUnsupportedJobOptions, J as JobDispatchError, N as routerFromRoutes, Q as createJobRunner, St as streamToolsOf, X as JobInputError, Y as defineJobTransport, _t as createGroups, at as dispatchSucceeded, bt as groupRoutes, ct as problemDetails, dt as getStatusText, ft as createPermissions, gt as permissionNames, ht as isRoles, it as dispatchDueJobs, lt as problemFromBody, mt as isPermissions, nt as DispatchFailedSchema, o as JOBS_META, ot as dueJobs, p as assembleApi, pt as createRoles, rt as DispatchResultSchema, st as failedJobs, tt as ResponseError, ut as STATUS_TITLES, xt as expandStreamTools, yt as assembleRoutes, z as assertNoPathCollisions } from "./adapter-CcVfT9VP.mjs";
6
6
  import { z } from "zod";
7
7
  //#region src/group-routes.ts
8
8
  /**
@@ -644,7 +644,7 @@ const defineConfig = (options) => {
644
644
  const api = buildApi(contract, {
645
645
  guards,
646
646
  requestContext: handlersOf(options.requestContext, RESOLVER),
647
- jobTransport: options.jobRunner?.transport,
647
+ jobTransport: options.jobRunner?.transport || void 0,
648
648
  onJobError: options.jobRunner?.onError
649
649
  }, options.adapter);
650
650
  apiReference.bind(api);
@@ -1,6 +1,6 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- const require_plugin_server = require("./plugin-server-tW5ZoOud.cjs");
3
- const require_adapter = require("./adapter-tET-kVcP.cjs");
2
+ const require_plugin_server = require("./plugin-server-6sIGS0RF.cjs");
3
+ const require_adapter = require("./adapter-BcRUajrL.cjs");
4
4
  //#region src/start-jobs.ts
5
5
  /**
6
6
  * The dedupe key an occurrence gets. Every instance ticking the same minute
@@ -96,7 +96,7 @@ const startJobs = (api, options) => {
96
96
  *
97
97
  * A handler that throws, or returns a status of 400 or more, rejects. A
98
98
  * returned status rejects as a `ResponseError`, so a transport can tell a `422`
99
- * from a `503`.
99
+ * from a `503`. Each failed attempt also reaches the jobs' `onError`.
100
100
  *
101
101
  * @example
102
102
  * const worker = await startJobWorker(api);
@@ -127,8 +127,7 @@ const startJobWorker = async (api, options) => {
127
127
  run: async (message) => {
128
128
  const jobFn = require_adapter.jobFnAt(runner, message.job);
129
129
  if (!jobFn) throw new Error(`No handler is bound for job "${message.job}" on this api.`);
130
- const response = await jobFn.run(message.input);
131
- if (response.status >= 400) throw new require_adapter.ResponseError(response);
130
+ await require_adapter.attemptJob(() => jobFn.run(message.input), message.job, meta.onError, logger);
132
131
  }
133
132
  });
134
133
  };
@@ -139,7 +138,7 @@ const stripTrailingSlash = (url) => url.endsWith("/") ? url.slice(0, -1) : url;
139
138
  * Tick the dispatch endpoint over the network on an interval, so `pnpm dev`
140
139
  * exercises the same request your platform cron will make in production.
141
140
  *
142
- * Reach for `startJobs` instead when you schedule in-process: it reads each job's
141
+ * Reach for `startJobs` instead on a long-running server: it reads each job's
143
142
  * own schedule rather than ticking on a fixed interval.
144
143
  *
145
144
  * @example
@@ -153,7 +152,7 @@ const stripTrailingSlash = (url) => url.endsWith("/") ? url.slice(0, -1) : url;
153
152
  const startJobsDevRunner = (contract, options) => {
154
153
  const logger = options.logger ?? console;
155
154
  if (process.env.NODE_ENV === "production") logger.warn("[kizuna/schedule] startJobsDevRunner is running with NODE_ENV=production. It ticks on an interval held in memory, so any tick during a restart or deploy is missed silently. Use your platform scheduler in production.");
156
- if (contract.jobsConfig?.mode === "in-process") throw new Error("[kizuna/schedule] startJobsDevRunner ticks the dispatch endpoint, which `mode: 'in-process'` does not serve. Run the schedules in this process with `startJobs` instead.");
155
+ if (contract.jobsConfig?.mode === "long-running") throw new Error("[kizuna/schedule] startJobsDevRunner ticks the dispatch endpoint, which `mode: 'long-running'` does not serve. Run the schedules in this process with `startJobs` instead.");
157
156
  const method = contract.jobsConfig?.method ?? "POST";
158
157
  const path = `${options.basePath ?? ""}${contract.jobsConfig?.path ?? "/jobs"}/dispatch`;
159
158
  const url = `${stripTrailingSlash(options.baseUrl)}${path}`;
@@ -1,4 +1,4 @@
1
- import { En as ApiDefinition, yr as JobWorker } from "./adapter-D50gicHq.cjs";
1
+ import { En as ApiDefinition, yr as JobWorker } from "./adapter-VoxBoXIp.cjs";
2
2
 
3
3
  //#region src/start-jobs.d.ts
4
4
  interface StartJobsOptions {
@@ -78,7 +78,7 @@ interface StartJobWorkerOptions {
78
78
  *
79
79
  * A handler that throws, or returns a status of 400 or more, rejects. A
80
80
  * returned status rejects as a `ResponseError`, so a transport can tell a `422`
81
- * from a `503`.
81
+ * from a `503`. Each failed attempt also reaches the jobs' `onError`.
82
82
  *
83
83
  * @example
84
84
  * const worker = await startJobWorker(api);
@@ -137,7 +137,7 @@ interface JobsDevRunner {
137
137
  * Tick the dispatch endpoint over the network on an interval, so `pnpm dev`
138
138
  * exercises the same request your platform cron will make in production.
139
139
  *
140
- * Reach for `startJobs` instead when you schedule in-process: it reads each job's
140
+ * Reach for `startJobs` instead on a long-running server: it reads each job's
141
141
  * own schedule rather than ticking on a fixed interval.
142
142
  *
143
143
  * @example
@@ -1,4 +1,4 @@
1
- import { En as ApiDefinition, yr as JobWorker } from "./adapter-DAGfLId-.mjs";
1
+ import { En as ApiDefinition, yr as JobWorker } from "./adapter-Co19yIKD.mjs";
2
2
 
3
3
  //#region src/start-jobs.d.ts
4
4
  interface StartJobsOptions {
@@ -78,7 +78,7 @@ interface StartJobWorkerOptions {
78
78
  *
79
79
  * A handler that throws, or returns a status of 400 or more, rejects. A
80
80
  * returned status rejects as a `ResponseError`, so a transport can tell a `422`
81
- * from a `503`.
81
+ * from a `503`. Each failed attempt also reaches the jobs' `onError`.
82
82
  *
83
83
  * @example
84
84
  * const worker = await startJobWorker(api);
@@ -137,7 +137,7 @@ interface JobsDevRunner {
137
137
  * Tick the dispatch endpoint over the network on an interval, so `pnpm dev`
138
138
  * exercises the same request your platform cron will make in production.
139
139
  *
140
- * Reach for `startJobs` instead when you schedule in-process: it reads each job's
140
+ * Reach for `startJobs` instead on a long-running server: it reads each job's
141
141
  * own schedule rather than ticking on a fixed interval.
142
142
  *
143
143
  * @example
@@ -1,5 +1,5 @@
1
- import { D as scheduleExpression, O as scheduleTimezone, m as flattenJobs, w as nextRun } from "./plugin-server-D8XrYDQU.mjs";
2
- import { $ as waitUntil, Q as jobFnAt, et as ResponseError, h as boundJobKeys, k as jobRunnerFrom, o as JOBS_META } from "./adapter-cRyeEuKZ.mjs";
1
+ import { D as scheduleExpression, O as scheduleTimezone, m as flattenJobs, w as nextRun } from "./plugin-server-l_eKX28n.mjs";
2
+ import { $ as jobFnAt, Z as attemptJob, et as waitUntil, h as boundJobKeys, k as jobRunnerFrom, o as JOBS_META } from "./adapter-CcVfT9VP.mjs";
3
3
  //#region src/start-jobs.ts
4
4
  /**
5
5
  * The dedupe key an occurrence gets. Every instance ticking the same minute
@@ -95,7 +95,7 @@ const startJobs = (api, options) => {
95
95
  *
96
96
  * A handler that throws, or returns a status of 400 or more, rejects. A
97
97
  * returned status rejects as a `ResponseError`, so a transport can tell a `422`
98
- * from a `503`.
98
+ * from a `503`. Each failed attempt also reaches the jobs' `onError`.
99
99
  *
100
100
  * @example
101
101
  * const worker = await startJobWorker(api);
@@ -126,8 +126,7 @@ const startJobWorker = async (api, options) => {
126
126
  run: async (message) => {
127
127
  const jobFn = jobFnAt(runner, message.job);
128
128
  if (!jobFn) throw new Error(`No handler is bound for job "${message.job}" on this api.`);
129
- const response = await jobFn.run(message.input);
130
- if (response.status >= 400) throw new ResponseError(response);
129
+ await attemptJob(() => jobFn.run(message.input), message.job, meta.onError, logger);
131
130
  }
132
131
  });
133
132
  };
@@ -138,7 +137,7 @@ const stripTrailingSlash = (url) => url.endsWith("/") ? url.slice(0, -1) : url;
138
137
  * Tick the dispatch endpoint over the network on an interval, so `pnpm dev`
139
138
  * exercises the same request your platform cron will make in production.
140
139
  *
141
- * Reach for `startJobs` instead when you schedule in-process: it reads each job's
140
+ * Reach for `startJobs` instead on a long-running server: it reads each job's
142
141
  * own schedule rather than ticking on a fixed interval.
143
142
  *
144
143
  * @example
@@ -152,7 +151,7 @@ const stripTrailingSlash = (url) => url.endsWith("/") ? url.slice(0, -1) : url;
152
151
  const startJobsDevRunner = (contract, options) => {
153
152
  const logger = options.logger ?? console;
154
153
  if (process.env.NODE_ENV === "production") logger.warn("[kizuna/schedule] startJobsDevRunner is running with NODE_ENV=production. It ticks on an interval held in memory, so any tick during a restart or deploy is missed silently. Use your platform scheduler in production.");
155
- if (contract.jobsConfig?.mode === "in-process") throw new Error("[kizuna/schedule] startJobsDevRunner ticks the dispatch endpoint, which `mode: 'in-process'` does not serve. Run the schedules in this process with `startJobs` instead.");
154
+ if (contract.jobsConfig?.mode === "long-running") throw new Error("[kizuna/schedule] startJobsDevRunner ticks the dispatch endpoint, which `mode: 'long-running'` does not serve. Run the schedules in this process with `startJobs` instead.");
156
155
  const method = contract.jobsConfig?.method ?? "POST";
157
156
  const path = `${options.basePath ?? ""}${contract.jobsConfig?.path ?? "/jobs"}/dispatch`;
158
157
  const url = `${stripTrailingSlash(options.baseUrl)}${path}`;
@@ -1090,13 +1090,14 @@ const isCompiledJob = (value) => {
1090
1090
  const assertJobRunner = (jobs, config) => {
1091
1091
  const flattened = jobs ? flattenJobs(jobs) : [];
1092
1092
  if (flattened.length === 0) return;
1093
- if (config?.mode === void 0) throw new Error("The jobs do not say how they run. Set `jobRunner: { mode: 'http' }` to serve `/jobs/dispatch` and `/jobs/run`, or `jobRunner: { mode: 'in-process' }` when `startJobs` ticks them in this process.");
1094
- if (config.mode === "in-process" || flattened.some(({ job }) => job.identity !== void 0)) return;
1093
+ if (config?.mode === void 0) throw new Error("The jobs do not say how they run. Set `jobRunner: { mode: 'http' }` to serve `/jobs/dispatch` and `/jobs/run`, or `jobRunner: { mode: 'long-running' }` when `startJobs` ticks them in this process.");
1094
+ if (config.transport === void 0) throw new Error("The jobs do not say where queued work goes. Set `jobRunner.transport` to a transport, such as `pgmqTransport({ pool })`, or to `false` to run a queued job in this process and lose it on a crash.");
1095
+ if (config.mode === "long-running" || flattened.some(({ job }) => job.identity !== void 0)) return;
1095
1096
  const base = config.path ?? "/jobs";
1096
- throw new Error(`The jobs declare no identity, so \`${base}/dispatch\` and \`${base}/run\` would let anyone trigger them. Pass an identity to \`k.jobs\`, or set \`jobRunner: { mode: 'in-process' }\` when the jobs run in this process with \`startJobs\`.`);
1097
+ throw new Error(`The jobs declare no identity, so \`${base}/dispatch\` and \`${base}/run\` would let anyone trigger them. Pass an identity to \`k.jobs\`, or set \`jobRunner: { mode: 'long-running' }\` when the jobs run in this process with \`startJobs\`.`);
1097
1098
  };
1098
1099
  const jobClaims = (jobs, config) => {
1099
- if (!jobs || config?.mode === "in-process" || flattenJobs(jobs).length === 0) return [];
1100
+ if (!jobs || config?.mode === "long-running" || flattenJobs(jobs).length === 0) return [];
1100
1101
  const base = config?.path ?? "/jobs";
1101
1102
  return [{
1102
1103
  method: config?.method ?? "POST",
@@ -1090,13 +1090,14 @@ const isCompiledJob = (value) => {
1090
1090
  const assertJobRunner = (jobs, config) => {
1091
1091
  const flattened = jobs ? flattenJobs(jobs) : [];
1092
1092
  if (flattened.length === 0) return;
1093
- if (config?.mode === void 0) throw new Error("The jobs do not say how they run. Set `jobRunner: { mode: 'http' }` to serve `/jobs/dispatch` and `/jobs/run`, or `jobRunner: { mode: 'in-process' }` when `startJobs` ticks them in this process.");
1094
- if (config.mode === "in-process" || flattened.some(({ job }) => job.identity !== void 0)) return;
1093
+ if (config?.mode === void 0) throw new Error("The jobs do not say how they run. Set `jobRunner: { mode: 'http' }` to serve `/jobs/dispatch` and `/jobs/run`, or `jobRunner: { mode: 'long-running' }` when `startJobs` ticks them in this process.");
1094
+ if (config.transport === void 0) throw new Error("The jobs do not say where queued work goes. Set `jobRunner.transport` to a transport, such as `pgmqTransport({ pool })`, or to `false` to run a queued job in this process and lose it on a crash.");
1095
+ if (config.mode === "long-running" || flattened.some(({ job }) => job.identity !== void 0)) return;
1095
1096
  const base = config.path ?? "/jobs";
1096
- throw new Error(`The jobs declare no identity, so \`${base}/dispatch\` and \`${base}/run\` would let anyone trigger them. Pass an identity to \`k.jobs\`, or set \`jobRunner: { mode: 'in-process' }\` when the jobs run in this process with \`startJobs\`.`);
1097
+ throw new Error(`The jobs declare no identity, so \`${base}/dispatch\` and \`${base}/run\` would let anyone trigger them. Pass an identity to \`k.jobs\`, or set \`jobRunner: { mode: 'long-running' }\` when the jobs run in this process with \`startJobs\`.`);
1097
1098
  };
1098
1099
  const jobClaims = (jobs, config) => {
1099
- if (!jobs || config?.mode === "in-process" || flattenJobs(jobs).length === 0) return [];
1100
+ if (!jobs || config?.mode === "long-running" || flattenJobs(jobs).length === 0) return [];
1100
1101
  const base = config?.path ?? "/jobs";
1101
1102
  return [{
1102
1103
  method: config?.method ?? "POST",
package/dist/plugin.d.cts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { Y as RoutePath } from "./error-response-YbkRMKno.cjs";
2
- import { $t as PluginSetupContext, Bt as PLUGIN_SERVERS_META_KEY, Gt as PluginExportValues, Ht as PluginArgs, It as AnyPlugin, Jt as PluginList, Kt as PluginExportsOf, Lt as ApiPlugins, Qt as PluginSetup, Rt as InstallOptions, Ut as PluginDeclaration, Vt as PluginApi, Wt as PluginDefinition, Xt as PluginRoutes, Yt as PluginRouteBuilder, Zt as PluginRoutesOf, an as definePlugin, cn as ApiContext, en as PluginsBySlug, in as SlugOption, nn as RouteAuthSchema, on as pluginRouteTree, qt as PluginFactory, rn as RoutePathSchema, sn as route, tn as ResolvedPlugin, zt as PLUGIN_ROUTES_META_KEY } from "./adapter-D50gicHq.cjs";
2
+ import { $t as PluginSetupContext, Bt as PLUGIN_SERVERS_META_KEY, Gt as PluginExportValues, Ht as PluginArgs, It as AnyPlugin, Jt as PluginList, Kt as PluginExportsOf, Lt as ApiPlugins, Qt as PluginSetup, Rt as InstallOptions, Ut as PluginDeclaration, Vt as PluginApi, Wt as PluginDefinition, Xt as PluginRoutes, Yt as PluginRouteBuilder, Zt as PluginRoutesOf, an as definePlugin, cn as ApiContext, en as PluginsBySlug, in as SlugOption, nn as RouteAuthSchema, on as pluginRouteTree, qt as PluginFactory, rn as RoutePathSchema, sn as route, tn as ResolvedPlugin, zt as PLUGIN_ROUTES_META_KEY } from "./adapter-VoxBoXIp.cjs";
3
3
  export { AnyPlugin, ApiContext, ApiPlugins, InstallOptions, PLUGIN_ROUTES_META_KEY, PLUGIN_SERVERS_META_KEY, PluginApi, PluginArgs, PluginDeclaration, PluginDefinition, PluginExportValues, PluginExportsOf, PluginFactory, PluginList, PluginRouteBuilder, PluginRoutes, PluginRoutesOf, PluginSetup, PluginSetupContext, PluginsBySlug, ResolvedPlugin, RouteAuthSchema, RoutePath, RoutePathSchema, SlugOption, definePlugin, pluginRouteTree, route };
package/dist/plugin.d.mts CHANGED
@@ -1,3 +1,3 @@
1
1
  import { Y as RoutePath } from "./error-response-NoOGdh8H.mjs";
2
- import { $t as PluginSetupContext, Bt as PLUGIN_SERVERS_META_KEY, Gt as PluginExportValues, Ht as PluginArgs, It as AnyPlugin, Jt as PluginList, Kt as PluginExportsOf, Lt as ApiPlugins, Qt as PluginSetup, Rt as InstallOptions, Ut as PluginDeclaration, Vt as PluginApi, Wt as PluginDefinition, Xt as PluginRoutes, Yt as PluginRouteBuilder, Zt as PluginRoutesOf, an as definePlugin, cn as ApiContext, en as PluginsBySlug, in as SlugOption, nn as RouteAuthSchema, on as pluginRouteTree, qt as PluginFactory, rn as RoutePathSchema, sn as route, tn as ResolvedPlugin, zt as PLUGIN_ROUTES_META_KEY } from "./adapter-DAGfLId-.mjs";
2
+ import { $t as PluginSetupContext, Bt as PLUGIN_SERVERS_META_KEY, Gt as PluginExportValues, Ht as PluginArgs, It as AnyPlugin, Jt as PluginList, Kt as PluginExportsOf, Lt as ApiPlugins, Qt as PluginSetup, Rt as InstallOptions, Ut as PluginDeclaration, Vt as PluginApi, Wt as PluginDefinition, Xt as PluginRoutes, Yt as PluginRouteBuilder, Zt as PluginRoutesOf, an as definePlugin, cn as ApiContext, en as PluginsBySlug, in as SlugOption, nn as RouteAuthSchema, on as pluginRouteTree, qt as PluginFactory, rn as RoutePathSchema, sn as route, tn as ResolvedPlugin, zt as PLUGIN_ROUTES_META_KEY } from "./adapter-Co19yIKD.mjs";
3
3
  export { AnyPlugin, ApiContext, ApiPlugins, InstallOptions, PLUGIN_ROUTES_META_KEY, PLUGIN_SERVERS_META_KEY, PluginApi, PluginArgs, PluginDeclaration, PluginDefinition, PluginExportValues, PluginExportsOf, PluginFactory, PluginList, PluginRouteBuilder, PluginRoutes, PluginRoutesOf, PluginSetup, PluginSetupContext, PluginsBySlug, ResolvedPlugin, RouteAuthSchema, RoutePath, RoutePathSchema, SlugOption, definePlugin, pluginRouteTree, route };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kizunajs",
3
- "version": "2.0.0-beta.30",
3
+ "version": "2.0.0-beta.32",
4
4
  "description": "Route declaration, validation, and the adapter API for Kizuna.js",
5
5
  "keywords": [
6
6
  "kizunajs",
package/src/adapter.ts CHANGED
@@ -41,7 +41,15 @@ import { encodeStreamBody, EVENT_STREAM_MEDIA_TYPE, streamContentType, type Enco
41
41
  import { streamToolsOf } from './tool-events.js';
42
42
  import { createStreamTools, type StreamTools } from './tool-runner.js';
43
43
  import { DEFAULT_JOBS_PATH, flattenJobs, type Jobs, type JobsConfig } from './jobs.js';
44
- import { createJobRunner, jobFnAt, JobInputError, type JobRunner, type JobRunnerOptions, type JobErrorHandler } from './job-runner.js';
44
+ import {
45
+ attemptJob,
46
+ createJobRunner,
47
+ jobFnAt,
48
+ JobInputError,
49
+ type JobRunner,
50
+ type JobRunnerOptions,
51
+ type JobErrorHandler,
52
+ } from './job-runner.js';
45
53
  import {
46
54
  DispatchFailedSchema,
47
55
  DispatchResultSchema,
@@ -378,10 +386,10 @@ export const assembleApi = <const R extends Routes>(
378
386
 
379
387
  /**
380
388
  * The endpoints jobs are served on, in the {@link Routes} shape the request
381
- * pipeline takes. None when the jobs run in process.
389
+ * pipeline takes. None in `'long-running'` mode.
382
390
  */
383
391
  export const jobRoutes = (meta: JobsMeta): Routes =>
384
- meta.config?.mode === 'in-process'
392
+ meta.config?.mode === 'long-running'
385
393
  ? {}
386
394
  : {
387
395
  [DISPATCH_ROUTE_KEY]: dispatchRoute(meta),
@@ -479,8 +487,8 @@ export const warnUnsupportedJobOptions = (
479
487
  const named = retrying.map((jobKey) => `"${jobKey}"`).join(', ');
480
488
  if (!transport) {
481
489
  logger.warn(
482
- `[kizuna] ${named} declare \`retry\`, but no transport is configured, so a failed run is not retried. ` +
483
- 'Pass one as `jobRunner.transport` in `kizuna.config.ts` to make retrying real.'
490
+ `[kizuna] ${named} declare \`retry\`, but \`jobRunner.transport\` is \`false\`, so a failed run is not retried. ` +
491
+ 'Pass a transport in `kizuna.config.ts` to make retrying real.'
484
492
  );
485
493
  return;
486
494
  }
@@ -531,7 +539,7 @@ export const dispatchHandler = <HandlerContext>(meta: JobsMeta): RouteHandler<Ro
531
539
  for (const { jobKey } of flattenJobs(meta.jobs)) {
532
540
  const jobFn = jobFnAt(runner, jobKey);
533
541
  if (!jobFn) continue;
534
- thunks[jobKey] = () => jobFn.run();
542
+ thunks[jobKey] = () => attemptJob(() => jobFn.run(), jobKey, meta.onError);
535
543
  }
536
544
  return (async () => {
537
545
  const result = await dispatchDueJobs({ jobs: meta.jobs } as unknown as ApiDefinition, thunks, {
@@ -601,8 +609,15 @@ export const runHandler = <HandlerContext>(meta: JobsMeta): RouteHandler<RouteDe
601
609
  };
602
610
  }
603
611
  try {
604
- return await jobFn.run(input);
612
+ return await attemptJob(() => jobFn.run(input), job, meta.onError);
605
613
  } catch (error) {
614
+ if (error instanceof ResponseError) {
615
+ return {
616
+ status: error.status,
617
+ body: error.body,
618
+ headers: error.headers,
619
+ };
620
+ }
606
621
  if (error instanceof JobInputError) {
607
622
  return {
608
623
  status: 422,
@@ -289,9 +289,9 @@ type JobRunnerInput<J extends Jobs> = string extends keyof J
289
289
  }
290
290
  : {
291
291
  /**
292
- * How this deployment runs the jobs it declares: over HTTP or in
293
- * process, what carries queued work out of the process, and where a
294
- * failure is reported. The jobs themselves are declared with
292
+ * How this deployment runs the jobs it declares: over HTTP or from a
293
+ * long-running server, what carries queued work out of the process,
294
+ * and where a failure is reported. The jobs themselves are declared with
295
295
  * `k.jobs` and go under `jobs`.
296
296
  */
297
297
  jobRunner: JobRunnerConfig;
@@ -469,7 +469,7 @@ export const defineConfig = <
469
469
  {
470
470
  guards,
471
471
  requestContext: handlersOf(options.requestContext as Record<string, unknown> | undefined, RESOLVER),
472
- jobTransport: options.jobRunner?.transport,
472
+ jobTransport: options.jobRunner?.transport || undefined,
473
473
  onJobError: options.jobRunner?.onError,
474
474
  },
475
475
  options.adapter
package/src/job-runner.ts CHANGED
@@ -2,6 +2,7 @@ import { isCompiledJob, jobAt, toJobResponse, type CompiledJob, type JobHandlerR
2
2
  import { ResponseError } from './response-error.js';
3
3
  import type { JobMessage, JobTransport } from './job-transport.js';
4
4
  import { waitUntil } from './wait-until.js';
5
+ import type { ResponseHeaders } from './types.js';
5
6
  import type { z } from 'zod';
6
7
 
7
8
  /**
@@ -50,8 +51,8 @@ export interface JobFn<Job extends CompiledJob> {
50
51
  */
51
52
  run: (...args: JobRunArgs<Job>) => Promise<JobHandlerReturn<Job['definition']>>;
52
53
  /**
53
- * Put the job in line and answer without waiting for it. With no transport
54
- * configured the job runs in this process and is lost on a crash.
54
+ * Put the job in line and answer without waiting for it. With
55
+ * `transport: false` the job runs in this process and is lost on a crash.
55
56
  */
56
57
  queue: (...args: JobQueueArgs<Job>) => Promise<void>;
57
58
  }
@@ -84,8 +85,10 @@ export class JobInputError extends Error {
84
85
  }
85
86
 
86
87
  /**
87
- * Called when a job queued without a transport rejects. Without one, the
88
- * failure is logged.
88
+ * Called for every failed run of a job that no caller awaits: one a worker,
89
+ * `/jobs/dispatch` or `/jobs/run` ran, or one queued with `transport: false`. A
90
+ * run fails when its handler throws or answers a status of 400 or more, which
91
+ * arrives as a `ResponseError`. Without one, the failure is logged.
89
92
  */
90
93
  export type JobErrorHandler = (job: string, error: unknown) => void;
91
94
 
@@ -124,6 +127,38 @@ export const jobFnAt = (runner: unknown, jobKey: string): JobFnByKey | undefined
124
127
  return typeof candidate?.run === 'function' && typeof candidate.queue === 'function' ? (candidate as JobFnByKey) : undefined;
125
128
  };
126
129
 
130
+ /**
131
+ * Run a job no caller awaits, rejecting when it fails and reporting the
132
+ * failure to `onError`, or to `logger` without one.
133
+ */
134
+ export const attemptJob = async (
135
+ run: () => Promise<unknown>,
136
+ jobKey: string,
137
+ onError: JobErrorHandler | undefined,
138
+ logger: Pick<Console, 'error'> = console
139
+ ): Promise<unknown> => {
140
+ try {
141
+ const response = (await run()) as {
142
+ status: number;
143
+ body: unknown;
144
+ headers?: ResponseHeaders;
145
+ };
146
+ if (response.status >= 400) throw new ResponseError(response);
147
+ return response;
148
+ } catch (error) {
149
+ if (!onError) {
150
+ logger.error(`[kizuna] Job "${jobKey}" failed:`, error);
151
+ } else {
152
+ try {
153
+ onError(jobKey, error);
154
+ } catch (hookError) {
155
+ logger.error('[kizuna] The jobs onError threw:', hookError);
156
+ }
157
+ }
158
+ throw error;
159
+ }
160
+ };
161
+
127
162
  const handlerAt = (handlers: unknown, jobKey: string): unknown => {
128
163
  let current: unknown = handlers;
129
164
  for (const segment of jobKey.split('.')) {
@@ -192,13 +227,7 @@ export const createJobRunner = <Jobs_ extends Jobs>(
192
227
 
193
228
  const runDetached = (jobKey: string, input: unknown, runAt: Date | undefined): void => {
194
229
  const start = (): void => {
195
- void invoke(jobKey, input).catch((error: unknown) => {
196
- if (options?.onError) {
197
- options.onError(jobKey, error);
198
- return;
199
- }
200
- console.error(`[kizuna] Queued job "${jobKey}" failed:`, error);
201
- });
230
+ void attemptJob(() => invoke(jobKey, input), jobKey, options?.onError).catch(() => {});
202
231
  };
203
232
  const time = runAt?.getTime();
204
233
  if (time === undefined || time <= Date.now()) {
@@ -49,7 +49,7 @@ const stripTrailingSlash = (url: string): string => (url.endsWith('/') ? url.sli
49
49
  * Tick the dispatch endpoint over the network on an interval, so `pnpm dev`
50
50
  * exercises the same request your platform cron will make in production.
51
51
  *
52
- * Reach for `startJobs` instead when you schedule in-process: it reads each job's
52
+ * Reach for `startJobs` instead on a long-running server: it reads each job's
53
53
  * own schedule rather than ticking on a fixed interval.
54
54
  *
55
55
  * @example
@@ -70,9 +70,9 @@ export const startJobsDevRunner = (contract: ApiDefinition, options: JobsDevRunn
70
70
  );
71
71
  }
72
72
 
73
- if (contract.jobsConfig?.mode === 'in-process') {
73
+ if (contract.jobsConfig?.mode === 'long-running') {
74
74
  throw new Error(
75
- "[kizuna/schedule] startJobsDevRunner ticks the dispatch endpoint, which `mode: 'in-process'` does not serve. " +
75
+ "[kizuna/schedule] startJobsDevRunner ticks the dispatch endpoint, which `mode: 'long-running'` does not serve. " +
76
76
  'Run the schedules in this process with `startJobs` instead.'
77
77
  );
78
78
  }
package/src/jobs.ts CHANGED
@@ -26,7 +26,7 @@ export type JobsConfig = HttpJobsConfig | InProcessJobsConfig;
26
26
  export interface HttpJobsConfig {
27
27
  /**
28
28
  * `'http'` serves `/jobs/dispatch` and `/jobs/run`, guarded by the jobs'
29
- * identity. `'in-process'` is for a long-running server whose schedules
29
+ * identity. `'long-running'` is for a long-running server whose schedules
30
30
  * `startJobs` ticks, and serves neither.
31
31
  */
32
32
  mode: 'http';
@@ -65,7 +65,7 @@ export interface HttpJobsConfig {
65
65
  * No job endpoint is served, so the jobs need no identity.
66
66
  */
67
67
  export interface InProcessJobsConfig {
68
- mode: 'in-process';
68
+ mode: 'long-running';
69
69
  path?: never;
70
70
  method?: never;
71
71
  windowMs?: never;
@@ -86,13 +86,15 @@ export type JobRunnerConfig = JobsConfig & JobDeliveryConfig;
86
86
  */
87
87
  export interface JobDeliveryConfig {
88
88
  /**
89
- * Carries a queued job to whatever runs it. Without one, `queue` runs the
90
- * job in this process and it is lost on a crash.
89
+ * Carries a queued job to whatever runs it. `false` runs a queued job in
90
+ * this process, without waiting for it, and loses it on a crash or a
91
+ * serverless freeze.
91
92
  */
92
- transport?: JobTransport;
93
+ transport: JobTransport | false;
93
94
  /**
94
- * Reached when a job fails after its response was sent, which is the only
95
- * point where nothing else can report it.
95
+ * Reached by every failed run no caller awaits, from a worker,
96
+ * `/jobs/dispatch`, `/jobs/run`, or `queue` with `transport: false`. Called
97
+ * once per attempt.
96
98
  */
97
99
  onError?: JobErrorHandler;
98
100
  }
@@ -438,25 +440,31 @@ export const isCompiledJob = (value: unknown): value is CompiledJob => {
438
440
  * Throw when declared jobs do not say how they run, or when the job endpoints
439
441
  * would be served with no identity guarding them.
440
442
  */
441
- export const assertJobRunner = (jobs: Jobs | undefined, config: JobsConfig | undefined): void => {
443
+ export const assertJobRunner = (jobs: Jobs | undefined, config: JobRunnerConfig | undefined): void => {
442
444
  const flattened = jobs ? flattenJobs(jobs) : [];
443
445
  if (flattened.length === 0) return;
444
446
  if (config?.mode === undefined) {
445
447
  throw new Error(
446
448
  "The jobs do not say how they run. Set `jobRunner: { mode: 'http' }` to serve `/jobs/dispatch` and `/jobs/run`, " +
447
- "or `jobRunner: { mode: 'in-process' }` when `startJobs` ticks them in this process."
449
+ "or `jobRunner: { mode: 'long-running' }` when `startJobs` ticks them in this process."
448
450
  );
449
451
  }
450
- if (config.mode === 'in-process' || flattened.some(({ job }) => job.identity !== undefined)) return;
452
+ if (config.transport === undefined) {
453
+ throw new Error(
454
+ 'The jobs do not say where queued work goes. Set `jobRunner.transport` to a transport, such as `pgmqTransport({ pool })`, ' +
455
+ 'or to `false` to run a queued job in this process and lose it on a crash.'
456
+ );
457
+ }
458
+ if (config.mode === 'long-running' || flattened.some(({ job }) => job.identity !== undefined)) return;
451
459
  const base = config.path ?? DEFAULT_JOBS_PATH;
452
460
  throw new Error(
453
461
  `The jobs declare no identity, so \`${base}/dispatch\` and \`${base}/run\` would let anyone trigger them. ` +
454
- "Pass an identity to `k.jobs`, or set `jobRunner: { mode: 'in-process' }` when the jobs run in this process with `startJobs`."
462
+ "Pass an identity to `k.jobs`, or set `jobRunner: { mode: 'long-running' }` when the jobs run in this process with `startJobs`."
455
463
  );
456
464
  };
457
465
 
458
466
  export const jobClaims = (jobs: Jobs | undefined, config: JobsConfig | undefined): PathClaim[] => {
459
- if (!jobs || config?.mode === 'in-process' || flattenJobs(jobs).length === 0) return [];
467
+ if (!jobs || config?.mode === 'long-running' || flattenJobs(jobs).length === 0) return [];
460
468
  const base = config?.path ?? DEFAULT_JOBS_PATH;
461
469
  return [
462
470
  {
@@ -8,7 +8,7 @@ import {
8
8
  type JobsMeta,
9
9
  type JobWorker,
10
10
  } from './adapter.js';
11
- import { ResponseError } from './response-error.js';
11
+ import { attemptJob } from './job-runner.js';
12
12
 
13
13
  export interface StartJobWorkerOptions {
14
14
  /**
@@ -36,7 +36,7 @@ export interface StartJobWorkerOptions {
36
36
  *
37
37
  * A handler that throws, or returns a status of 400 or more, rejects. A
38
38
  * returned status rejects as a `ResponseError`, so a transport can tell a `422`
39
- * from a `503`.
39
+ * from a `503`. Each failed attempt also reaches the jobs' `onError`.
40
40
  *
41
41
  * @example
42
42
  * const worker = await startJobWorker(api);
@@ -77,12 +77,7 @@ export const startJobWorker = async (api: unknown, options?: StartJobWorkerOptio
77
77
  run: async (message) => {
78
78
  const jobFn = jobFnAt(runner, message.job);
79
79
  if (!jobFn) throw new Error(`No handler is bound for job "${message.job}" on this api.`);
80
- const response = (await jobFn.run(message.input)) as {
81
- status: number;
82
- body: unknown;
83
- };
84
- // A returned 503 asks for a retry as plainly as a thrown one does.
85
- if (response.status >= 400) throw new ResponseError(response);
80
+ await attemptJob(() => jobFn.run(message.input), message.job, meta.onError, logger);
86
81
  },
87
82
  });
88
83
  };