@rebasepro/server 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (132) hide show
  1. package/dist/{GCSStorageController-40FyFeSx.js → GCSStorageController-LXeAF6Ks.js} +37 -4
  2. package/dist/GCSStorageController-LXeAF6Ks.js.map +1 -0
  3. package/dist/{S3StorageController-Bl5shp94.js → S3StorageController-CVKMUXo_.js} +59 -11
  4. package/dist/S3StorageController-CVKMUXo_.js.map +1 -0
  5. package/dist/{access-BFAUvsSs.js → access-BDz4FO9D.js} +7 -7
  6. package/dist/access-BDz4FO9D.js.map +1 -0
  7. package/dist/api/openapi-generator.d.ts +13 -1
  8. package/dist/api/rest/api-generator.d.ts +16 -0
  9. package/dist/api/rest/batch.d.ts +9 -0
  10. package/dist/{ast-schema-editor-madTa9Hh.js → ast-schema-editor-C4bDSb61.js} +2 -2
  11. package/dist/{ast-schema-editor-madTa9Hh.js.map → ast-schema-editor-C4bDSb61.js.map} +1 -1
  12. package/dist/auth/admin-users-route.d.ts +3 -0
  13. package/dist/auth/apple-oauth.d.ts +39 -10
  14. package/dist/auth/capabilities.d.ts +2 -0
  15. package/dist/auth/interfaces.d.ts +78 -4
  16. package/dist/auth/otp-routes.d.ts +10 -0
  17. package/dist/{auth-izI7AEzC.js → auth-CZGfVKcL.js} +350 -137
  18. package/dist/auth-CZGfVKcL.js.map +1 -0
  19. package/dist/auth_adapter-B7RUMk6e.js.map +1 -1
  20. package/dist/backend/options.d.ts +29 -1
  21. package/dist/backend-CaG_Jyso.js.map +1 -1
  22. package/dist/{backup-BVbHoKo8.js → backup-BmzY9xdN.js} +8 -8
  23. package/dist/{backup-BVbHoKo8.js.map → backup-BmzY9xdN.js.map} +1 -1
  24. package/dist/boot/env.d.ts +6 -0
  25. package/dist/{branch-routes-B2vvEx53.js → branch-routes-DpgaeTJl.js} +4 -4
  26. package/dist/{branch-routes-B2vvEx53.js.map → branch-routes-DpgaeTJl.js.map} +1 -1
  27. package/dist/{contract-routes-CU2A3JnF.js → contract-routes-vYiBHbjI.js} +3 -3
  28. package/dist/{contract-routes-CU2A3JnF.js.map → contract-routes-vYiBHbjI.js.map} +1 -1
  29. package/dist/cron/cron-loader.d.ts +16 -0
  30. package/dist/{cron-loader-mMhqbVsl.js → cron-loader-C_C-lNgG.js} +39 -10
  31. package/dist/cron-loader-C_C-lNgG.js.map +1 -0
  32. package/dist/{cron-routes-Cs33j_Kr.js → cron-routes-DlwOV6zl.js} +5 -5
  33. package/dist/{cron-routes-Cs33j_Kr.js.map → cron-routes-DlwOV6zl.js.map} +1 -1
  34. package/dist/{cron-scheduler-Be7CNghL.js → cron-scheduler-6ipIm5mm.js} +41 -28
  35. package/dist/cron-scheduler-6ipIm5mm.js.map +1 -0
  36. package/dist/{cron-store-DLn11M8H.js → cron-store-KIOM8LCC.js} +5 -5
  37. package/dist/{cron-store-DLn11M8H.js.map → cron-store-KIOM8LCC.js.map} +1 -1
  38. package/dist/{ddl-bootstrap-CjRrn12l.js → ddl-bootstrap-DhCuwhHM.js} +2 -2
  39. package/dist/{ddl-bootstrap-CjRrn12l.js.map → ddl-bootstrap-DhCuwhHM.js.map} +1 -1
  40. package/dist/dist-DVqwVrBQ.js +22 -0
  41. package/dist/dist-DVqwVrBQ.js.map +1 -0
  42. package/dist/{load-failure-L5hvfDoG.js → dynamic-import-Bi3XK5y-.js} +30 -18
  43. package/dist/dynamic-import-Bi3XK5y-.js.map +1 -0
  44. package/dist/{errors-OMWkKSH-.js → errors-DIWnZIDY.js} +2 -2
  45. package/dist/{errors-OMWkKSH-.js.map → errors-DIWnZIDY.js.map} +1 -1
  46. package/dist/{field-access-DYsvjI_P.js → field-access-KYk8RGOx.js} +3 -2
  47. package/dist/field-access-KYk8RGOx.js.map +1 -0
  48. package/dist/{filter-dialect-TrKFWLqT.js → filter-dialect-CE4bloug.js} +2 -2
  49. package/dist/{filter-dialect-TrKFWLqT.js.map → filter-dialect-CE4bloug.js.map} +1 -1
  50. package/dist/{function-loader-B8YzXEsQ.js → function-loader-CKB9b4uP.js} +15 -6
  51. package/dist/function-loader-CKB9b4uP.js.map +1 -0
  52. package/dist/{function-routes-RxrCHNuM.js → function-routes-DLaXaiQA.js} +2 -2
  53. package/dist/{function-routes-RxrCHNuM.js.map → function-routes-DLaXaiQA.js.map} +1 -1
  54. package/dist/functions/function-loader.d.ts +5 -0
  55. package/dist/functions/index.js +16 -9
  56. package/dist/functions/index.js.map +1 -1
  57. package/dist/{history-recorder-Bsau7h4X.js → history-recorder-BE4HWR-M.js} +4 -4
  58. package/dist/{history-recorder-Bsau7h4X.js.map → history-recorder-BE4HWR-M.js.map} +1 -1
  59. package/dist/{history-store-BQz5YCkW.js → history-store-D-jDz4Nv.js} +2 -2
  60. package/dist/{history-store-BQz5YCkW.js.map → history-store-D-jDz4Nv.js.map} +1 -1
  61. package/dist/index.d.ts +1 -1
  62. package/dist/index.es.js +1361 -232
  63. package/dist/index.es.js.map +1 -1
  64. package/dist/init/docs.d.ts +1 -1
  65. package/dist/init/health.d.ts +13 -0
  66. package/dist/{internal-tables-L2t39RdT.js → internal-tables-CRaBxJeE.js} +57 -2
  67. package/dist/{internal-tables-L2t39RdT.js.map → internal-tables-CRaBxJeE.js.map} +1 -1
  68. package/dist/{jobs-Co6Ni5HP.js → jobs-CXTs9qXH.js} +5 -5
  69. package/dist/{jobs-Co6Ni5HP.js.map → jobs-CXTs9qXH.js.map} +1 -1
  70. package/dist/{jwt-rDS0884_.js → jwt-5EvX3lQa.js} +3 -3
  71. package/dist/{jwt-rDS0884_.js.map → jwt-5EvX3lQa.js.map} +1 -1
  72. package/dist/{keys-BXcdRNhJ.js → keys-DJ1ZNcZi.js} +2 -2
  73. package/dist/{keys-BXcdRNhJ.js.map → keys-DJ1ZNcZi.js.map} +1 -1
  74. package/dist/{logger-CW8pmTS6.js → logger-SigQ2oZJ.js} +17 -10
  75. package/dist/logger-SigQ2oZJ.js.map +1 -0
  76. package/dist/{logs-routes-CBt7mMIL.js → logs-routes-DXLvMasE.js} +3 -3
  77. package/dist/{logs-routes-CBt7mMIL.js.map → logs-routes-DXLvMasE.js.map} +1 -1
  78. package/dist/mcp/mcp-apps.d.ts +53 -0
  79. package/dist/mcp/mcp-routes.d.ts +10 -1
  80. package/dist/mcp/mcp-tools.d.ts +10 -0
  81. package/dist/metrics/index.d.ts +8 -0
  82. package/dist/metrics/realtime.d.ts +25 -0
  83. package/dist/{offline-AvuEcg7u-DFHL98OT.js → offline-BjJdcVBb-BOzzsnrh.js} +35 -7
  84. package/dist/offline-BjJdcVBb-BOzzsnrh.js.map +1 -0
  85. package/dist/{offline-store-BhYXViha-YTmjBpo2.js → offline-store-Cxhh99Q--FB6fSf5A.js} +43 -9
  86. package/dist/offline-store-Cxhh99Q--FB6fSf5A.js.map +1 -0
  87. package/dist/{openapi-generator-CyxEtYEX.js → openapi-generator-B6aw_KuR.js} +41 -7
  88. package/dist/openapi-generator-B6aw_KuR.js.map +1 -0
  89. package/dist/{proxy-BYir8tWK.js → proxy-2nS5N63I.js} +3 -3
  90. package/dist/{proxy-BYir8tWK.js.map → proxy-2nS5N63I.js.map} +1 -1
  91. package/dist/{query-parser-CDXWf2hH.js → query-parser-DFVCjW5i.js} +6 -6
  92. package/dist/{query-parser-CDXWf2hH.js.map → query-parser-DFVCjW5i.js.map} +1 -1
  93. package/dist/{request-timeout-DVjo-c_8.js → request-timeout-Cqm4JXtZ.js} +3 -3
  94. package/dist/{request-timeout-DVjo-c_8.js.map → request-timeout-Cqm4JXtZ.js.map} +1 -1
  95. package/dist/{rls-simulator-routes-bEY7-5-u.js → rls-simulator-routes-D5-XfjzW.js} +4 -4
  96. package/dist/{rls-simulator-routes-bEY7-5-u.js.map → rls-simulator-routes-D5-XfjzW.js.map} +1 -1
  97. package/dist/{schema-editor-routes-Dc3DU_jm.js → schema-editor-routes-DzSe6V0a.js} +4 -4
  98. package/dist/{schema-editor-routes-Dc3DU_jm.js.map → schema-editor-routes-DzSe6V0a.js.map} +1 -1
  99. package/dist/services/routed-realtime-service.d.ts +1 -1
  100. package/dist/{soft-delete-params-BRONCOA2.js → soft-delete-params-9lKBAlDw.js} +2 -2
  101. package/dist/{soft-delete-params-BRONCOA2.js.map → soft-delete-params-9lKBAlDw.js.map} +1 -1
  102. package/dist/{sql-export-routes-QycX8W8S.js → sql-export-routes-BxMqgAFX.js} +4 -4
  103. package/dist/{sql-export-routes-QycX8W8S.js.map → sql-export-routes-BxMqgAFX.js.map} +1 -1
  104. package/dist/{src-Bh9LRPb9.js → src-JQNz7cWv.js} +19 -2
  105. package/dist/{src-Bh9LRPb9.js.map → src-JQNz7cWv.js.map} +1 -1
  106. package/dist/storage/GCSStorageController.d.ts +9 -1
  107. package/dist/storage/LocalStorageController.d.ts +8 -1
  108. package/dist/storage/S3StorageController.d.ts +4 -2
  109. package/dist/storage/index.d.ts +1 -0
  110. package/dist/storage/orphan-sweep.d.ts +67 -0
  111. package/dist/storage/policies.d.ts +1 -1
  112. package/dist/storage/streams.d.ts +17 -0
  113. package/dist/storage/types.d.ts +15 -33
  114. package/dist/{upload-validation-Bgo626uY.js → upload-validation-IYXn4xcm.js} +41 -3
  115. package/dist/upload-validation-IYXn4xcm.js.map +1 -0
  116. package/dist/utils/load-failure.d.ts +9 -0
  117. package/dist/utils/logger.d.ts +9 -4
  118. package/package.json +7 -6
  119. package/dist/GCSStorageController-40FyFeSx.js.map +0 -1
  120. package/dist/S3StorageController-Bl5shp94.js.map +0 -1
  121. package/dist/access-BFAUvsSs.js.map +0 -1
  122. package/dist/auth-izI7AEzC.js.map +0 -1
  123. package/dist/cron-loader-mMhqbVsl.js.map +0 -1
  124. package/dist/cron-scheduler-Be7CNghL.js.map +0 -1
  125. package/dist/field-access-DYsvjI_P.js.map +0 -1
  126. package/dist/function-loader-B8YzXEsQ.js.map +0 -1
  127. package/dist/load-failure-L5hvfDoG.js.map +0 -1
  128. package/dist/logger-CW8pmTS6.js.map +0 -1
  129. package/dist/offline-AvuEcg7u-DFHL98OT.js.map +0 -1
  130. package/dist/offline-store-BhYXViha-YTmjBpo2.js.map +0 -1
  131. package/dist/openapi-generator-CyxEtYEX.js.map +0 -1
  132. package/dist/upload-validation-Bgo626uY.js.map +0 -1
@@ -3,9 +3,9 @@ import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
5
  import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
6
- import { S as declareCron } from "./src-Bh9LRPb9.js";
7
- import { a as logger } from "./logger-CW8pmTS6.js";
8
- import { i as warnDeprecated, n as describeLoadFailure, r as nativeDynamicImport, t as SYNTAX_ERROR_ADVICE } from "./load-failure-L5hvfDoG.js";
6
+ import { S as declareCron } from "./src-JQNz7cWv.js";
7
+ import { a as logger } from "./logger-SigQ2oZJ.js";
8
+ import { a as warnDeprecated, i as describeLoadFailure, r as SYNTAX_ERROR_ADVICE, t as nativeDynamicImport } from "./dynamic-import-Bi3XK5y-.js";
9
9
  import * as fs$1 from "fs";
10
10
  import * as path$1 from "path";
11
11
  import { pathToFileURL } from "url";
@@ -17,7 +17,8 @@ var cron_loader_exports = /* @__PURE__ */ __exportAll({
17
17
  loadCronJobsFromDirectory: () => loadCronJobsFromDirectory,
18
18
  loadCronJobsWithDiagnostics: () => loadCronJobsWithDiagnostics,
19
19
  loadCrons: () => loadCrons,
20
- readCronsDirectory: () => readCronsDirectory
20
+ readCronsDirectory: () => readCronsDirectory,
21
+ withHiddenPropertiesOf: () => withHiddenPropertiesOf
21
22
  });
22
23
  /**
23
24
  * Load the cron jobs in a directory, as values.
@@ -75,18 +76,38 @@ function cronJobsFrom(crons) {
75
76
  if (!def || typeof def.schedule !== "string" || typeof def.handler !== "function") throw new Error(`crons["${id}"] is not a cron job: it needs a \`schedule\` string and a \`handler\` function. Author it with \`defineCron({ schedule, handler })\`.`);
76
77
  return {
77
78
  id,
78
- definition: {
79
+ definition: withHiddenPropertiesOf(def, {
79
80
  ...def,
80
81
  schedule: def.schedule,
81
82
  name: def.name || id,
82
83
  enabled: def.enabled !== false,
83
84
  timeoutSeconds: def.timeoutSeconds ?? 300,
84
85
  handler: def.handler
85
- }
86
+ })
86
87
  };
87
88
  });
88
89
  }
89
90
  /**
91
+ * `copy`, with the non-enumerable own properties of `source` that it does not
92
+ * set itself defined on it as they were.
93
+ *
94
+ * A spread copies enumerable properties only, and a definition can carry a
95
+ * mark a surface finds it by: `createBackupCron` puts
96
+ * `Symbol.for("rebase.backupCron")` on its job, non-enumerable so a JSON dump
97
+ * of it is unchanged. Every copy on the way to the scheduler goes through
98
+ * this, or the Backups panel finds no scheduled backup on a deployment that
99
+ * runs one.
100
+ */
101
+ function withHiddenPropertiesOf(source, copy) {
102
+ const hidden = {};
103
+ for (const key of Reflect.ownKeys(source)) {
104
+ if (Object.prototype.hasOwnProperty.call(copy, key)) continue;
105
+ const descriptor = Object.getOwnPropertyDescriptor(source, key);
106
+ if (descriptor && !descriptor.enumerable) hidden[key] = descriptor;
107
+ }
108
+ return Object.defineProperties(copy, hidden);
109
+ }
110
+ /**
90
111
  * @deprecated Use `loadCrons` instead, which returns the jobs as a record keyed
91
112
  * by id. Will be removed in a future release.
92
113
  */
@@ -135,13 +156,18 @@ async function legacyLoad(directory, importModule) {
135
156
  * Never throws, for the same reason the function loader does not: one
136
157
  * malformed file must not take the server down, and the other jobs in the
137
158
  * directory are still worth scheduling.
159
+ *
160
+ * `failed` is the part of `problems` that threw or did not parse: the rest are
161
+ * files with no job in them, as `readFunctionsDirectory` has it.
138
162
  */
139
163
  async function readCronsDirectory(directory, importModule = nativeDynamicImport) {
140
164
  const crons = {};
141
165
  const problems = [];
166
+ const failed = [];
142
167
  if (!fs$1.existsSync(directory)) return {
143
168
  crons,
144
- problems
169
+ problems,
170
+ failed
145
171
  };
146
172
  const files = fs$1.readdirSync(directory);
147
173
  for (const file of files) if ((file.endsWith(".ts") || file.endsWith(".js")) && !file.startsWith(".") && !file.includes(".test.") && !file.endsWith(".d.ts") && file !== "index.ts" && file !== "index.js") {
@@ -166,7 +192,9 @@ async function readCronsDirectory(directory, importModule = nativeDynamicImport)
166
192
  logger.info(`⏰ Loaded cron job: ${id} (${definition.schedule}${definition.timezone ? ` ${definition.timezone}` : " in the process's local time"})`);
167
193
  } catch (err) {
168
194
  const message = err instanceof Error ? err.message : String(err);
169
- problems.push(describeLoadFailure(file, err));
195
+ const failure = describeLoadFailure(file, err);
196
+ problems.push(failure);
197
+ failed.push(failure);
170
198
  logger.debug(`[cron] Failed to load ${file}: ${message}`);
171
199
  }
172
200
  }
@@ -177,7 +205,8 @@ async function readCronsDirectory(directory, importModule = nativeDynamicImport)
177
205
  }
178
206
  return {
179
207
  crons,
180
- problems
208
+ problems,
209
+ failed
181
210
  };
182
211
  }
183
212
  /**
@@ -199,4 +228,4 @@ function cronResourceOptions(definition) {
199
228
  //#endregion
200
229
  export { loadCrons as a, loadCronJobsWithDiagnostics as i, declareCrons as n, loadCronJobsFromDirectory as r, cron_loader_exports as t };
201
230
 
202
- //# sourceMappingURL=cron-loader-mMhqbVsl.js.map
231
+ //# sourceMappingURL=cron-loader-C_C-lNgG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cron-loader-C_C-lNgG.js","names":[],"sources":["../src/cron/cron-loader.ts"],"sourcesContent":["import * as fs from \"fs\";\nimport * as path from \"path\";\nimport { pathToFileURL } from \"url\";\nimport { declareCron, type CronJobDefinition, type CronResourceOptions } from \"@rebasepro/types\";\nimport { logger } from \"../utils/logger.js\";\nimport { nativeDynamicImport, type ModuleImporter } from \"../utils/dynamic-import.js\";\nimport { describeLoadFailure, SYNTAX_ERROR_ADVICE } from \"../utils/load-failure.js\";\nimport { warnDeprecated } from \"@rebasepro/common\";\nimport type { LoadDirectoryOptions } from \"../functions/function-loader.js\";\n\n/**\n * Cron jobs as values: the job id, to its definition.\n *\n * `crons: { \"nightly-report\": nightlyReport }` schedules `nightlyReport` as the\n * job `nightly-report` — the same thing a file named `crons/nightly-report.ts`\n * does. {@link loadCrons} returns exactly this shape, so\n * `crons: await loadCrons(dir)` and `cronsDir: dir` schedule the same jobs.\n *\n * A value is what the author wrote — `defineCron({...})` — with no defaults\n * filled in. The scheduler fills them in when it registers the job.\n */\nexport type CronsRecord = Record<string, CronJobDefinition>;\n\n/** A job as the scheduler registers it: its id, and its definition with defaults filled in. */\nexport interface LoadedCronJob {\n /** Job ID derived from filename (e.g. \"cleanup-sessions\"). */\n id: string;\n /** The full definition. */\n definition: CronJobDefinition;\n}\n\n/** {@link loadCronJobsWithDiagnostics}' answer: what loaded, and what did not. */\nexport interface LoadedCronJobs {\n jobs: LoadedCronJob[];\n /** One entry per file that will NOT be scheduled, with the reason. */\n problems: string[];\n}\n\n/**\n * Load the cron jobs in a directory, as values.\n *\n * Each file default-exports a `CronJobDefinition` — `defineCron({...})`. The\n * filename without its extension is the record key, which is the job id:\n * `crons/cleanup-sessions.ts` → `{ \"cleanup-sessions\": definition }`.\n *\n * Loading declares nothing: the definitions come back exactly as written, and\n * whoever uses them decides what they are for — a backend schedules them, the\n * build's derive step records them in the resource graph ({@link declareCrons}).\n *\n * Never throws for a bad file: it is skipped, logged, and passed to\n * `options.onSkip`.\n *\n * @example\n * ```ts\n * const crons = await loadCrons(path.resolve(\"crons\"));\n * const backend = await createRebaseBackend({ database, crons, provision: true });\n * ```\n */\nexport async function loadCrons(directory: string, options: LoadDirectoryOptions = {}): Promise<CronsRecord> {\n const { crons, problems } = await readCronsDirectory(directory, options.importModule);\n if (options.onSkip) for (const problem of problems) options.onSkip(problem);\n return crons;\n}\n\n/**\n * Record each cron in the project's resource graph — what `rebase resources`\n * lists and a host reads to know a schedule exists, without running it.\n *\n * Keyed by the same id the scheduler, the routes and the Studio use, and built\n * from the definitions as written: a default the scheduler fills in\n * (`enabled: true`, `timeoutSeconds: 300`) is this process's, not something the\n * author declared.\n */\nexport function declareCrons(crons: CronsRecord): void {\n for (const [id, definition] of Object.entries(crons)) {\n declareCron(id, cronResourceOptions(definition));\n }\n}\n\n/**\n * The jobs a scheduler registers, from cron values: the definitions with this\n * process's defaults filled in.\n *\n * Spread first, then normalise. Rebuilding the object field by field dropped\n * `catchUpWindowSeconds` once — and since this is the path every job takes to\n * the scheduler, catch-up never ran for any job authored the documented way. A\n * field added to `CronJobDefinition` tomorrow would be dropped the same way.\n *\n * @throws when a value has no `schedule` or no `handler`. A file like that is\n * skipped by the loader with a reason; a value handed over in code is refused,\n * because the caller is right there to fix it.\n */\nexport function cronJobsFrom(crons: CronsRecord): LoadedCronJob[] {\n return Object.entries(crons).map(([id, definition]) => {\n const def = definition as Partial<CronJobDefinition> | undefined;\n if (!def || typeof def.schedule !== \"string\" || typeof def.handler !== \"function\") {\n throw new Error(\n `crons[\"${id}\"] is not a cron job: it needs a \\`schedule\\` string and a \\`handler\\` function. ` +\n \"Author it with `defineCron({ schedule, handler })`.\"\n );\n }\n return {\n id,\n definition: withHiddenPropertiesOf(def, {\n ...def,\n schedule: def.schedule,\n name: def.name || id,\n enabled: def.enabled !== false,\n // `??`, not `||`: zero and NaN are values the author wrote, and\n // the scheduler refuses both by name (they end up under\n // `rejected`). `|| 300` swallowed them, so a job written with\n // `0` meaning \"no limit\" ran with five minutes and was listed as\n // healthy. `Infinity` is \"none\".\n timeoutSeconds: def.timeoutSeconds ?? 300,\n handler: def.handler\n })\n };\n });\n}\n\n/**\n * `copy`, with the non-enumerable own properties of `source` that it does not\n * set itself defined on it as they were.\n *\n * A spread copies enumerable properties only, and a definition can carry a\n * mark a surface finds it by: `createBackupCron` puts\n * `Symbol.for(\"rebase.backupCron\")` on its job, non-enumerable so a JSON dump\n * of it is unchanged. Every copy on the way to the scheduler goes through\n * this, or the Backups panel finds no scheduled backup on a deployment that\n * runs one.\n */\nexport function withHiddenPropertiesOf<T extends object>(source: object, copy: T): T {\n const hidden: PropertyDescriptorMap = {};\n for (const key of Reflect.ownKeys(source)) {\n if (Object.prototype.hasOwnProperty.call(copy, key)) continue;\n const descriptor = Object.getOwnPropertyDescriptor(source, key);\n if (descriptor && !descriptor.enumerable) hidden[key] = descriptor;\n }\n return Object.defineProperties(copy, hidden);\n}\n\n/**\n * @deprecated Use `loadCrons` instead, which returns the jobs as a record keyed\n * by id. Will be removed in a future release.\n */\nexport async function loadCronJobsFromDirectory(\n directory: string,\n importModule: ModuleImporter = nativeDynamicImport\n): Promise<LoadedCronJob[]> {\n warnDeprecated(\n \"server.loadCronJobsFromDirectory\",\n \"`loadCronJobsFromDirectory` is deprecated; use `loadCrons(dir)`, which returns `{ [id]: definition }`.\"\n );\n return (await legacyLoad(directory, importModule)).jobs;\n}\n\n/**\n * @deprecated Use `loadCrons` instead, with `onSkip` to collect the files it\n * skipped — and `declareCrons` where the jobs belong in the resource graph,\n * which this used to do as a side effect of loading. Will be removed in a\n * future release.\n */\nexport async function loadCronJobsWithDiagnostics(\n directory: string,\n importModule: ModuleImporter = nativeDynamicImport\n): Promise<LoadedCronJobs> {\n warnDeprecated(\n \"server.loadCronJobsWithDiagnostics\",\n \"`loadCronJobsWithDiagnostics` is deprecated; use `loadCrons(dir, { onSkip })`, which returns \" +\n \"`{ [id]: definition }`, and `declareCrons(crons)` to record them in the resource graph.\"\n );\n return legacyLoad(directory, importModule);\n}\n\n/**\n * What the deprecated loaders did: load, declare every job in the resource\n * graph, and hand back normalised jobs. A job the graph refuses is skipped as a\n * problem, as it was when the declaration ran inside the loader.\n */\nasync function legacyLoad(directory: string, importModule: ModuleImporter): Promise<LoadedCronJobs> {\n const { crons, problems } = await readCronsDirectory(directory, importModule);\n const declared: CronsRecord = {};\n for (const [id, definition] of Object.entries(crons)) {\n try {\n declareCron(id, cronResourceOptions(definition));\n declared[id] = definition;\n } catch (err) {\n problems.push(describeLoadFailure(id, err));\n }\n }\n return { jobs: cronJobsFrom(declared), problems };\n}\n\n/**\n * Read a directory of cron files: the definitions that loaded, keyed by id, and\n * one `<file> (<reason>)` per file that will NOT be scheduled.\n *\n * A job that does not load does not run, and the only trace used to be one\n * `warn` per file in the boot log — next to nothing at 3am when the report that\n * should have been mailed was not. So the skips are counted, summarised in one\n * place, and answered by `GET /api/admin/cron`.\n *\n * Never throws, for the same reason the function loader does not: one\n * malformed file must not take the server down, and the other jobs in the\n * directory are still worth scheduling.\n *\n * `failed` is the part of `problems` that threw or did not parse: the rest are\n * files with no job in them, as `readFunctionsDirectory` has it.\n */\nexport async function readCronsDirectory(\n directory: string,\n importModule: ModuleImporter = nativeDynamicImport\n): Promise<{ crons: CronsRecord; problems: string[]; failed: string[] }> {\n const crons: CronsRecord = {};\n // Aggregated so a broken job surfaces as one loud summary rather than a\n // warning buried per-file among the boot noise.\n const problems: string[] = [];\n const failed: string[] = [];\n\n if (!fs.existsSync(directory)) {\n return { crons, problems, failed };\n }\n\n const files = fs.readdirSync(directory);\n for (const file of files) {\n if (\n (file.endsWith(\".ts\") || file.endsWith(\".js\")) &&\n // Dotfiles: notably macOS bsdtar AppleDouble sidecars (`._foo.ts`),\n // binary blobs that cannot be imported.\n !file.startsWith(\".\") &&\n !file.includes(\".test.\") &&\n !file.endsWith(\".d.ts\") &&\n file !== \"index.ts\" &&\n file !== \"index.js\"\n ) {\n const filePath = path.join(directory, file);\n try {\n const fileUrl = pathToFileURL(filePath).href;\n\n const mod = await importModule(fileUrl);\n\n const exported: unknown = mod.default;\n\n if (!exported || typeof exported !== \"object\") {\n problems.push(`${file} (no default export)`);\n logger.warn(`[cron] ${file}: no valid default export. Skipping.`);\n continue;\n }\n\n const def = exported as Record<string, unknown>;\n if (typeof def.schedule !== \"string\" || def.schedule.trim() === \"\" || typeof def.handler !== \"function\") {\n problems.push(`${file} (default export has no 'schedule' or no 'handler')`);\n logger.warn(`[cron] ${file}: default export missing required 'schedule' or 'handler'. Skipping.`);\n continue;\n }\n\n const id = path.basename(file, path.extname(file));\n const definition = exported as CronJobDefinition;\n crons[id] = definition;\n logger.info(\n `⏰ Loaded cron job: ${id} (${definition.schedule}` +\n `${definition.timezone ? ` ${definition.timezone}` : \" in the process's local time\"})`\n );\n } catch (err: unknown) {\n const message =\n err instanceof Error ? err.message : String(err);\n const failure = describeLoadFailure(file, err);\n problems.push(failure);\n failed.push(failure);\n // At `debug`: the aggregate warning below lists every problem\n // by file, so this line was the same text a second time — and\n // when the throw is a Zod error, that text is ten lines of\n // serialised issues. The reader met it twice before reaching\n // the sentence that says what to do.\n logger.debug(`[cron] Failed to load ${file}: ${message}`);\n }\n }\n }\n\n if (problems.length > 0) {\n // Advice keyed to what went wrong, as the functions loader does:\n // `defineCron` is the remedy for a wrong export shape, not for a typo.\n const syntax = problems.some(p => p.includes(\"(syntax error\"));\n const other = problems.some(p => !p.includes(\"(syntax error\"));\n logger.warn(\n `[cron] ${problems.length} cron file(s) were skipped and will NOT be scheduled:\\n` +\n problems.map((p) => ` - ${p}`).join(\"\\n\") + \"\\n\" +\n [\n ...(syntax ? [SYNTAX_ERROR_ADVICE] : []),\n ...(other ? [\" Fix these or author them with `defineCron(...)` for a typed, compile-checked contract.\"] : [])\n ].join(\"\\n\")\n );\n }\n\n return { crons, problems, failed };\n}\n\n/**\n * The declaration a definition makes: every field a host can read without the\n * handler. Spelled once here so the graph and the scheduler cannot disagree\n * about what a cron is.\n */\nexport function cronResourceOptions(definition: CronJobDefinition): CronResourceOptions {\n return {\n schedule: definition.schedule,\n ...(definition.timezone !== undefined ? { timezone: definition.timezone } : {}),\n ...(definition.description !== undefined ? { description: definition.description } : {}),\n ...(definition.enabled !== undefined ? { enabled: definition.enabled } : {}),\n ...(definition.timeoutSeconds !== undefined ? { timeoutSeconds: definition.timeoutSeconds } : {}),\n ...(definition.catchUpWindowSeconds !== undefined ? { catchUpWindowSeconds: definition.catchUpWindowSeconds } : {}),\n ...(definition.name ? { label: definition.name } : {})\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,eAAsB,UAAU,WAAmB,UAAgC,CAAC,GAAyB;CACzG,MAAM,EAAE,OAAO,aAAa,MAAM,mBAAmB,W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AAW,mBAAmB,KAAA,IAAY,EAAE,gBAAgB,WAAW,eAAe,IAAI,CAAC;EAC/F,GAAI,WAAW,yBAAyB,KAAA,IAAY,EAAE,sBAAsB,WAAW,qBAAqB,IAAI,CAAC;EACjH,GAAI,WAAW,OAAO,EAAE,OAAO,WAAW,KAAK,IAAI,CAAC;CACxD;AACJ"}
@@ -3,10 +3,10 @@ import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
5
  import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
6
- import { r as isAlreadyExecutingSkip } from "./cron-scheduler-Be7CNghL.js";
7
- import { a as logger } from "./logger-CW8pmTS6.js";
8
- import { a as resolveListLimitParam } from "./query-parser-CDXWf2hH.js";
9
- import { i as errorHandler, t as ApiError } from "./errors-OMWkKSH-.js";
6
+ import { r as isAlreadyExecutingSkip } from "./cron-scheduler-6ipIm5mm.js";
7
+ import { a as logger } from "./logger-SigQ2oZJ.js";
8
+ import { a as resolveListLimitParam } from "./query-parser-DFVCjW5i.js";
9
+ import { i as errorHandler, t as ApiError } from "./errors-DIWnZIDY.js";
10
10
  import { Hono } from "hono";
11
11
  //#region src/cron/cron-routes.ts
12
12
  var cron_routes_exports = /* @__PURE__ */ __exportAll({ createCronRoutes: () => createCronRoutes });
@@ -116,4 +116,4 @@ function createCronRoutes(scheduler, skipped = 0) {
116
116
  //#endregion
117
117
  export { cron_routes_exports as n, createCronRoutes as t };
118
118
 
119
- //# sourceMappingURL=cron-routes-Cs33j_Kr.js.map
119
+ //# sourceMappingURL=cron-routes-DlwOV6zl.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cron-routes-Cs33j_Kr.js","names":[],"sources":["../src/cron/cron-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport type { HonoEnv } from \"../api/types\";\nimport { isAlreadyExecutingSkip, type CronScheduler } from \"./cron-scheduler\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { resolveListLimitParam } from \"../api/rest/query-parser\";\nimport { logger } from \"../utils/logger.js\";\n\n/** Who made a change, as `cron_job_state.updated_by` records it. */\nfunction actorOf(c: Context<HonoEnv>): string | undefined {\n const user = c.get(\"user\");\n if (typeof user === \"object\" && user !== null && typeof user.uid === \"string\") return user.uid;\n const apiKey = c.get(\"apiKey\");\n return apiKey ? `api-key:${apiKey.id}` : undefined;\n}\n\n/**\n * The manual trigger's `?async` switch. Absent means synchronous, as it always\n * was; anything other than a plain yes or no is refused rather than read as\n * one, so `?async=yes-please` does not quietly hold the request open.\n */\nfunction readAsyncFlag(raw: string | undefined): boolean {\n if (raw === undefined) return false;\n const value = raw.trim().toLowerCase();\n if (value === \"1\" || value === \"true\") return true;\n if (value === \"\" || value === \"0\" || value === \"false\") return false;\n throw ApiError.badRequest(`?async must be 1, true, 0 or false — got \"${raw}\"`);\n}\n\n/**\n * Create admin REST routes for managing cron jobs.\n *\n * Routes:\n * GET / → list all cron jobs\n * GET /:id → get a single job's status\n * POST /:id/trigger → manually trigger a job (`?async=1`: 202 once it has started)\n * GET /:id/logs → get execution logs for a job\n * PUT /:id → update job (enable/disable, or `null` to follow the code)\n *\n * Every answer about a job's state is read from the store, not from this\n * process's memory: the process serving these routes is often not the one\n * running the jobs (the `api` role never starts its scheduler), and is only\n * ever one replica of several.\n */\nexport function createCronRoutes(scheduler: CronScheduler, skipped = 0): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n // Hono's onError does NOT propagate from parent to child routers, so this\n // child router registers its own handler to format thrown ApiErrors.\n router.onError(errorHandler);\n\n // List all jobs\n router.get(\"/\", async (c) => {\n const jobs = await scheduler.fetchJobs();\n // A file that failed to load is not a job, so it appears nowhere in\n // this list — and \"my job is missing\" and \"my job is not scheduled\"\n // look identical from here. Say how many were dropped, as the\n // functions listing does, so the Studio panel and anyone with curl can\n // see it without boot-log access.\n //\n // Two ways to be dropped, counted together and reported apart. A file\n // the loader could not read has only a count: the failure happened\n // before there was a job to name. A schedule the scheduler refused has a\n // name and a reason — most often \"Expected 5 fields, got 6\", from an\n // expression copied out of a tool that supports seconds — and quoting it\n // here turns a job that silently never fires into a one-line fix.\n const rejected = scheduler.listRejectedJobs();\n const total = skipped + rejected.length;\n return c.json({\n jobs,\n ...(total > 0 && {\n skipped: total,\n ...(rejected.length > 0 && { rejected }),\n note: [\n skipped > 0 ? `${skipped} cron file(s) failed to load` : undefined,\n // Not \"an invalid schedule\": a job is also refused for an\n // unknown timezone or a timeout that is not a positive\n // number, and `rejected` says which.\n rejected.length > 0 ? `${rejected.length} job(s) were refused` : undefined\n ].filter(Boolean).join(\" and \") +\n \" — NOT scheduled. \" +\n (rejected.length > 0\n ? \"See `rejected` for the reason; \"\n : \"\") +\n \"the server log has the rest.\"\n })\n });\n });\n\n // Get single job\n router.get(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const job = await scheduler.fetchJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n return c.json({ job });\n });\n\n // Trigger a job manually\n router.post(\"/:id/trigger\", async (c) => {\n const id = c.req.param(\"id\");\n const asyncRun = readAsyncFlag(c.req.query(\"async\"));\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n // `?async=1`: answer once the run has started rather than when it\n // ends. A long job's synchronous answer is cut by any proxy with a\n // shorter timeout than the job (60 s is common) while the run carries\n // on; this one is not. The outcome is in `GET /:id/logs`, as the entry\n // with `manual: true` and this `startedAt`.\n if (asyncRun) {\n const outcome = await scheduler.startJob(id);\n if (!outcome) throw ApiError.notFound(`Cron job \"${id}\" not found`);\n if (!outcome.started) {\n throw ApiError.conflict(\n `Cron job \"${id}\" is already executing — try again when that run has finished`,\n \"CRON_JOB_ALREADY_EXECUTING\",\n { log: outcome.log }\n );\n }\n return c.json({\n accepted: true,\n startedAt: outcome.startedAt,\n job: await scheduler.fetchJob(id)\n }, 202);\n }\n\n const log = await scheduler.triggerJob(id);\n // Nothing ran, so this is not a success: the job is executing already —\n // on this process, or on whichever one holds its run lease (the worker,\n // seen from the api role). The skip is in the run history either way;\n // `details.log` carries it, and its line names the process.\n if (log && isAlreadyExecutingSkip(log)) {\n throw ApiError.conflict(\n `Cron job \"${id}\" is already executing — try again when that run has finished`,\n \"CRON_JOB_ALREADY_EXECUTING\",\n { log }\n );\n }\n return c.json({ log,\njob: await scheduler.fetchJob(id) });\n });\n\n // Get job logs\n router.get(\"/:id/logs\", async (c) => {\n const id = c.req.param(\"id\");\n // Validated, not `parseInt`-ed. `?limit=abc` used to reach the store as\n // `NaN`, where Postgres refused `LIMIT NaN`, the store swallowed the\n // error and returned `[]` — a 200 with an empty list, which reads as\n // \"this job has never run\". The data plane answers 400 for the same\n // input; so does this now.\n const limit = resolveListLimitParam(c.req.query(\"limit\") ?? null, { defaultLimit: 50 });\n\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n const logs = await scheduler.getJobLogsFromDb(id, limit).catch((err: unknown) => {\n // Not an empty 200: Studio shows that as \"No executions yet\".\n logger.error(`[cron] Could not read the run history of \"${id}\"`, { error: err });\n throw ApiError.serviceUnavailable(\n `The run history of cron job \"${id}\" could not be read. The server log has the reason.`\n );\n });\n return c.json({ logs });\n });\n\n // Enable/disable a job — for every process, and across redeploys\n router.put(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const body: unknown = await c.req.json().catch(() => ({}));\n const enabled = typeof body === \"object\" && body !== null && \"enabled\" in body ? body.enabled : undefined;\n\n if (typeof enabled !== \"boolean\" && enabled !== null) {\n throw ApiError.badRequest(\n \"Missing 'enabled' in body: true or false to override the job's code, or null to follow it again\"\n );\n }\n\n if (!scheduler.getJob(id)) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n try {\n await scheduler.persistJobEnabled(id, enabled, actorOf(c));\n } catch (err) {\n logger.error(`[cron] Could not save the enabled state of \"${id}\"`, { error: err });\n throw ApiError.serviceUnavailable(\n `The change to cron job \"${id}\" could not be saved, so no process was changed. ` +\n \"The server log has the reason.\"\n );\n }\n\n return c.json({ job: await scheduler.fetchJob(id) });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;AASA,SAAS,QAAQ,GAAyC;CACtD,MAAM,OAAO,EAAE,IAAI,MAAM;CACzB,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,OAAO,KAAK,QAAQ,UAAU,OAAO,KAAK;CAC3F,MAAM,SAAS,EAAE,IAAI,QAAQ;CAC7B,OAAO,SAAS,WAAW,OAAO,OAAO,KAAA;AAC7C;;;;;;AAOA,SAAS,cAAc,KAAkC;CACrD,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,MAAM,QAAQ,IAAI,KAAK,CAAC,CAAC,YAAY;CACrC,IAAI,UAAU,OAAO,UAAU,QAAQ,OAAO;CAC9C,IAAI,UAAU,MAAM,UAAU,OAAO,UAAU,SAAS,OAAO;CAC/D,MAAM,SAAS,WAAW,6CAA6C,IAAI,EAAE;AACjF;;;;;;;;;;;;;;;;AAiBA,SAAgB,iBAAiB,WAA0B,UAAU,GAAkB;CACnF,MAAM,SAAS,IAAI,KAAc;CAGjC,OAAO,QAAQ,YAAY;CAG3B,OAAO,IAAI,KAAK,OAAO,MAAM;EACzB,MAAM,OAAO,MAAM,UAAU,UAAU;EAavC,MAAM,WAAW,UAAU,iBAAiB;EAC5C,MAAM,QAAQ,UAAU,SAAS;EACjC,OAAO,EAAE,KAAK;GACV;GACA,GAAI,QAAQ,KAAK;IACb,SAAS;IACT,GAAI,SAAS,SAAS,KAAK,EAAE,SAAS;IACtC,MAAM,CACF,UAAU,IAAI,GAAG,QAAQ,gCAAgC,KAAA,GAIzD,SAAS,SAAS,IAAI,GAAG,SAAS,OAAO,wBAAwB,KAAA,CACrE,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,OAAO,IAC1B,wBACC,SAAS,SAAS,IACb,o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F,IAAI,CADQ,UAAU,OAAO,EACxB,GACD,MAAM,SAAS,SAAS,aAAa,GAAG,YAAY;EAGxD,MAAM,OAAO,MAAM,UAAU,iBAAiB,IAAI,KAAK,CAAC,CAAC,OAAO,QAAiB;GAE7E,OAAO,MAAM,6CAA6C,GAAG,IAAI,EAAE,OAAO,IAAI,CAAC;GAC/E,MAAM,SAAS,mBACX,gCAAgC,GAAG,oDACvC;EACJ,CAAC;EACD,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC;CAC1B,CAAC;CAGD,OAAO,IAAI,QAAQ,OAAO,MAAM;EAC5B,MAAM,KAAK,EAAE,IAAI,MAAM,IAAI;EAC3B,MAAM,OAAgB,MAAM,EAAE,IAAI,KAAK,CAAC,CAAC,aAAa,CAAC,EAAE;EACzD,MAAM,UAAU,OAAO,SAAS,YAAY,SAAS,QAAQ,aAAa,OAAO,KAAK,UAAU,KAAA;EAEhG,IAAI,OAAO,YAAY,aAAa,YAAY,MAC5C,MAAM,SAAS,WACX,iGACJ;EAGJ,IAAI,CAAC,UAAU,OAAO,EAAE,GACpB,MAAM,SAAS,SAAS,aAAa,GAAG,YAAY;EAGxD,IAAI;GACA,MAAM,UAAU,kBAAkB,IAAI,SAAS,QAAQ,CAAC,CAAC;EAC7D,SAAS,KAAK;GACV,OAAO,MAAM,+CAA+C,GAAG,IAAI,EAAE,OAAO,IAAI,CAAC;GACjF,MAAM,SAAS,mBACX,2BAA2B,GAAG,gFAElC;EACJ;EAEA,OAAO,EAAE,KAAK,EAAE,KAAK,MAAM,UAAU,SAAS,EAAE,EAAE,CAAC;CACvD,CAAC;CAED,OAAO;AACX"}
1
+ {"version":3,"file":"cron-routes-DlwOV6zl.js","names":[],"sources":["../src/cron/cron-routes.ts"],"sourcesContent":["import { Hono } from \"hono\";\nimport type { Context } from \"hono\";\nimport type { HonoEnv } from \"../api/types\";\nimport { isAlreadyExecutingSkip, type CronScheduler } from \"./cron-scheduler\";\nimport { ApiError, errorHandler } from \"../api/errors\";\nimport { resolveListLimitParam } from \"../api/rest/query-parser\";\nimport { logger } from \"../utils/logger.js\";\n\n/** Who made a change, as `cron_job_state.updated_by` records it. */\nfunction actorOf(c: Context<HonoEnv>): string | undefined {\n const user = c.get(\"user\");\n if (typeof user === \"object\" && user !== null && typeof user.uid === \"string\") return user.uid;\n const apiKey = c.get(\"apiKey\");\n return apiKey ? `api-key:${apiKey.id}` : undefined;\n}\n\n/**\n * The manual trigger's `?async` switch. Absent means synchronous, as it always\n * was; anything other than a plain yes or no is refused rather than read as\n * one, so `?async=yes-please` does not quietly hold the request open.\n */\nfunction readAsyncFlag(raw: string | undefined): boolean {\n if (raw === undefined) return false;\n const value = raw.trim().toLowerCase();\n if (value === \"1\" || value === \"true\") return true;\n if (value === \"\" || value === \"0\" || value === \"false\") return false;\n throw ApiError.badRequest(`?async must be 1, true, 0 or false — got \"${raw}\"`);\n}\n\n/**\n * Create admin REST routes for managing cron jobs.\n *\n * Routes:\n * GET / → list all cron jobs\n * GET /:id → get a single job's status\n * POST /:id/trigger → manually trigger a job (`?async=1`: 202 once it has started)\n * GET /:id/logs → get execution logs for a job\n * PUT /:id → update job (enable/disable, or `null` to follow the code)\n *\n * Every answer about a job's state is read from the store, not from this\n * process's memory: the process serving these routes is often not the one\n * running the jobs (the `api` role never starts its scheduler), and is only\n * ever one replica of several.\n */\nexport function createCronRoutes(scheduler: CronScheduler, skipped = 0): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n // Hono's onError does NOT propagate from parent to child routers, so this\n // child router registers its own handler to format thrown ApiErrors.\n router.onError(errorHandler);\n\n // List all jobs\n router.get(\"/\", async (c) => {\n const jobs = await scheduler.fetchJobs();\n // A file that failed to load is not a job, so it appears nowhere in\n // this list — and \"my job is missing\" and \"my job is not scheduled\"\n // look identical from here. Say how many were dropped, as the\n // functions listing does, so the Studio panel and anyone with curl can\n // see it without boot-log access.\n //\n // Two ways to be dropped, counted together and reported apart. A file\n // the loader could not read has only a count: the failure happened\n // before there was a job to name. A schedule the scheduler refused has a\n // name and a reason — most often \"Expected 5 fields, got 6\", from an\n // expression copied out of a tool that supports seconds — and quoting it\n // here turns a job that silently never fires into a one-line fix.\n const rejected = scheduler.listRejectedJobs();\n const total = skipped + rejected.length;\n return c.json({\n jobs,\n ...(total > 0 && {\n skipped: total,\n ...(rejected.length > 0 && { rejected }),\n note: [\n skipped > 0 ? `${skipped} cron file(s) failed to load` : undefined,\n // Not \"an invalid schedule\": a job is also refused for an\n // unknown timezone or a timeout that is not a positive\n // number, and `rejected` says which.\n rejected.length > 0 ? `${rejected.length} job(s) were refused` : undefined\n ].filter(Boolean).join(\" and \") +\n \" — NOT scheduled. \" +\n (rejected.length > 0\n ? \"See `rejected` for the reason; \"\n : \"\") +\n \"the server log has the rest.\"\n })\n });\n });\n\n // Get single job\n router.get(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const job = await scheduler.fetchJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n return c.json({ job });\n });\n\n // Trigger a job manually\n router.post(\"/:id/trigger\", async (c) => {\n const id = c.req.param(\"id\");\n const asyncRun = readAsyncFlag(c.req.query(\"async\"));\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n // `?async=1`: answer once the run has started rather than when it\n // ends. A long job's synchronous answer is cut by any proxy with a\n // shorter timeout than the job (60 s is common) while the run carries\n // on; this one is not. The outcome is in `GET /:id/logs`, as the entry\n // with `manual: true` and this `startedAt`.\n if (asyncRun) {\n const outcome = await scheduler.startJob(id);\n if (!outcome) throw ApiError.notFound(`Cron job \"${id}\" not found`);\n if (!outcome.started) {\n throw ApiError.conflict(\n `Cron job \"${id}\" is already executing — try again when that run has finished`,\n \"CRON_JOB_ALREADY_EXECUTING\",\n { log: outcome.log }\n );\n }\n return c.json({\n accepted: true,\n startedAt: outcome.startedAt,\n job: await scheduler.fetchJob(id)\n }, 202);\n }\n\n const log = await scheduler.triggerJob(id);\n // Nothing ran, so this is not a success: the job is executing already —\n // on this process, or on whichever one holds its run lease (the worker,\n // seen from the api role). The skip is in the run history either way;\n // `details.log` carries it, and its line names the process.\n if (log && isAlreadyExecutingSkip(log)) {\n throw ApiError.conflict(\n `Cron job \"${id}\" is already executing — try again when that run has finished`,\n \"CRON_JOB_ALREADY_EXECUTING\",\n { log }\n );\n }\n return c.json({ log,\njob: await scheduler.fetchJob(id) });\n });\n\n // Get job logs\n router.get(\"/:id/logs\", async (c) => {\n const id = c.req.param(\"id\");\n // Validated, not `parseInt`-ed. `?limit=abc` used to reach the store as\n // `NaN`, where Postgres refused `LIMIT NaN`, the store swallowed the\n // error and returned `[]` — a 200 with an empty list, which reads as\n // \"this job has never run\". The data plane answers 400 for the same\n // input; so does this now.\n const limit = resolveListLimitParam(c.req.query(\"limit\") ?? null, { defaultLimit: 50 });\n\n const job = scheduler.getJob(id);\n if (!job) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n const logs = await scheduler.getJobLogsFromDb(id, limit).catch((err: unknown) => {\n // Not an empty 200: Studio shows that as \"No executions yet\".\n logger.error(`[cron] Could not read the run history of \"${id}\"`, { error: err });\n throw ApiError.serviceUnavailable(\n `The run history of cron job \"${id}\" could not be read. The server log has the reason.`\n );\n });\n return c.json({ logs });\n });\n\n // Enable/disable a job — for every process, and across redeploys\n router.put(\"/:id\", async (c) => {\n const id = c.req.param(\"id\");\n const body: unknown = await c.req.json().catch(() => ({}));\n const enabled = typeof body === \"object\" && body !== null && \"enabled\" in body ? body.enabled : undefined;\n\n if (typeof enabled !== \"boolean\" && enabled !== null) {\n throw ApiError.badRequest(\n \"Missing 'enabled' in body: true or false to override the job's code, or null to follow it again\"\n );\n }\n\n if (!scheduler.getJob(id)) {\n throw ApiError.notFound(`Cron job \"${id}\" not found`);\n }\n\n try {\n await scheduler.persistJobEnabled(id, enabled, actorOf(c));\n } catch (err) {\n logger.error(`[cron] Could not save the enabled state of \"${id}\"`, { error: err });\n throw ApiError.serviceUnavailable(\n `The change to cron job \"${id}\" could not be saved, so no process was changed. ` +\n \"The server log has the reason.\"\n );\n }\n\n return c.json({ job: await scheduler.fetchJob(id) });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;AASA,SAAS,QAAQ,GAAyC;CACtD,MAAM,OAAO,EAAE,IAAI,MAAM;CACzB,IAAI,OAAO,SAAS,YAAY,SAAS,QAAQ,OAAO,KAAK,QAAQ,UAAU,OAAO,KAAK;CAC3F,MAAM,SAAS,EAAE,IAAI,QAAQ;CAC7B,OAAO,SAAS,WAAW,OAAO,OAAO,KAAA;AAC7C;;;;;;AAOA,SAAS,cAAc,KAAkC;CACrD,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,MAAM,QAAQ,IAAI,KAAK,CAAC,CAAC,YAAY;CACrC,IAAI,UAAU,OAAO,UAAU,QAAQ,OAAO;CAC9C,IAAI,UAAU,MAAM,UAAU,OAAO,UAAU,SAAS,OAAO;CAC/D,MAAM,SAAS,WAAW,6CAA6C,IAAI,EAAE;AACjF;;;;;;;;;;;;;;;;AAiBA,SAAgB,iBAAiB,WAA0B,UAAU,GAAkB;CACnF,MAAM,SAAS,IAAI,KAAc;CAGjC,OAAO,QAAQ,YAAY;CAG3B,OAAO,IAAI,KAAK,OAAO,MAAM;EACzB,MAAM,OAAO,MAAM,UAAU,UAAU;EAavC,MAAM,WAAW,UAAU,iBAAiB;EAC5C,MAAM,QAAQ,UAAU,SAAS;EACjC,OAAO,EAAE,KAAK;GACV;GACA,GAAI,QAAQ,KAAK;IACb,SAAS;IACT,GAAI,SAAS,SAAS,KAAK,EAAE,SAAS;IACtC,MAAM,CACF,UAAU,IAAI,GAAG,QAAQ,gCAAgC,KAAA,GAIzD,SAAS,SAAS,IAAI,GAAG,SAAS,OAAO,wBAAwB,KAAA,CACrE,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,KAAK,OAAO,IAC1B,wBACC,SAAS,SAAS,IACb,oCACA,MACN;GACR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,UAAU,OAAO,EACxB,GACD,MAAM,SAAS,SAAS,aAAa,GAAG,YAAY;EAGxD,MAAM,OAAO,MAAM,UAAU,iBAAiB,IAAI,KAAK,CAAC,CAAC,OAAO,QAAiB;GAE7E,OAAO,MAAM,6CAA6C,GAAG,IAAI,EAAE,OAAO,IAAI,CAAC;GAC/E,MAAM,SAAS,mBACX,gCAAgC,GAAG,oDACvC;EACJ,CAAC;EACD,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC;CAC1B,CAAC;CAGD,OAAO,IAAI,QAAQ,OAAO,MAAM;EAC5B,MAAM,KAAK,EAAE,IAAI,MAAM,IAAI;EAC3B,MAAM,OAAgB,MAAM,EAAE,IAAI,KAAK,CAAC,CAAC,aAAa,CAAC,EAAE;EACzD,MAAM,UAAU,OAAO,SAAS,YAAY,SAAS,QAAQ,aAAa,OAAO,KAAK,UAAU,KAAA;EAEhG,IAAI,OAAO,YAAY,aAAa,YAAY,MAC5C,MAAM,SAAS,WACX,iGACJ;EAGJ,IAAI,CAAC,UAAU,OAAO,EAAE,GACpB,MAAM,SAAS,SAAS,aAAa,GAAG,YAAY;EAGxD,IAAI;GACA,MAAM,UAAU,kBAAkB,IAAI,SAAS,QAAQ,CAAC,CAAC;EAC7D,SAAS,KAAK;GACV,OAAO,MAAM,+CAA+C,GAAG,IAAI,EAAE,OAAO,IAAI,CAAC;GACjF,MAAM,SAAS,mBACX,2BAA2B,GAAG,gFAElC;EACJ;EAEA,OAAO,EAAE,KAAK,EAAE,KAAK,MAAM,UAAU,SAAS,EAAE,EAAE,CAAC;CACvD,CAAC;CAED,OAAO;AACX"}
@@ -3,8 +3,8 @@ import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
5
  import { n as __exportAll } from "./rolldown-runtime-dW7B1o5h.js";
6
- import "./src-Bh9LRPb9.js";
7
- import { a as logger, s as redactSensitiveText, u as stringifyForLog } from "./logger-CW8pmTS6.js";
6
+ import "./src-JQNz7cWv.js";
7
+ import { a as logger, s as redactSensitiveText, u as stringifyForLog } from "./logger-SigQ2oZJ.js";
8
8
  import { randomUUID } from "node:crypto";
9
9
  import { hostname } from "node:os";
10
10
  //#region ../types/src/types/env_boolean.ts
@@ -162,30 +162,36 @@ var cron_scheduler_exports = /* @__PURE__ */ __exportAll({
162
162
  * Supports: `*`, `N`, `N-M`, `N/S`, `N-M/S`, `*\/S`, and comma-separated combinations.
163
163
  */
164
164
  function expandCronField(field, min, max) {
165
+ const number = (token) => {
166
+ if (!/^\d+$/.test(token)) throw new Error(`Invalid value "${token}" in cron field "${field}"`);
167
+ return Number(token);
168
+ };
169
+ const range = (token) => {
170
+ const bounds = token.split("-");
171
+ if (bounds.length !== 2) throw new Error(`Invalid range "${token}" in cron field "${field}"`);
172
+ const [a, b] = bounds.map(number);
173
+ if (a > b) throw new Error(`Range "${token}" in cron field "${field}" runs backwards`);
174
+ return [a, b];
175
+ };
165
176
  const results = /* @__PURE__ */ new Set();
166
177
  for (const segment of field.split(",")) {
167
178
  const trimmed = segment.trim();
168
179
  if (trimmed === "*") for (let i = min; i <= max; i++) results.add(i);
169
180
  else if (trimmed.includes("/")) {
170
- const [rangeStr, stepStr] = trimmed.split("/");
171
- const step = parseInt(stepStr, 10);
172
- if (isNaN(step) || step <= 0) throw new Error(`Invalid step value "${stepStr}" in cron field "${field}"`);
181
+ const parts = trimmed.split("/");
182
+ if (parts.length !== 2) throw new Error(`Invalid step expression "${trimmed}" in cron field "${field}"`);
183
+ const [rangeStr, stepStr] = parts;
184
+ if (!/^\d+$/.test(stepStr) || Number(stepStr) <= 0) throw new Error(`Invalid step value "${stepStr}" in cron field "${field}"`);
185
+ const step = Number(stepStr);
173
186
  let start = min;
174
187
  let end = max;
175
- if (rangeStr !== "*") if (rangeStr.includes("-")) {
176
- const [a, b] = rangeStr.split("-").map(Number);
177
- start = a;
178
- end = b;
179
- } else start = parseInt(rangeStr, 10);
188
+ if (rangeStr !== "*") if (rangeStr.includes("-")) [start, end] = range(rangeStr);
189
+ else start = number(rangeStr);
180
190
  for (let i = start; i <= end; i += step) results.add(i);
181
191
  } else if (trimmed.includes("-")) {
182
- const [a, b] = trimmed.split("-").map(Number);
192
+ const [a, b] = range(trimmed);
183
193
  for (let i = a; i <= b; i++) results.add(i);
184
- } else {
185
- const val = parseInt(trimmed, 10);
186
- if (isNaN(val)) throw new Error(`Invalid value "${trimmed}" in cron field "${field}"`);
187
- results.add(val);
188
- }
194
+ } else results.add(number(trimmed));
189
195
  }
190
196
  return [...results].sort((a, b) => a - b);
191
197
  }
@@ -261,7 +267,8 @@ function parseCronFields(expression) {
261
267
  hours: expandCronField(hourField, 0, 23),
262
268
  doms: expandCronField(domField, 1, 31),
263
269
  months: expandCronField(monField, 1, 12),
264
- dows: expandCronField(dowField, 0, 6)
270
+ dows: expandCronField(dowField, 0, 6),
271
+ eitherDay: !domField.startsWith("*") && !dowField.startsWith("*")
265
272
  };
266
273
  }
267
274
  /**
@@ -344,7 +351,10 @@ function offsetAt(instantMs, wall) {
344
351
  }
345
352
  /** Whether a wall-clock day — month, day of month, weekday — can hold a slot. */
346
353
  function dayMatches(wall, fields) {
347
- return fields.months.includes(wall.month) && fields.doms.includes(wall.dom) && fields.dows.includes(wall.dow);
354
+ if (!fields.months.includes(wall.month)) return false;
355
+ const dom = fields.doms.includes(wall.dom);
356
+ const dow = fields.dows.includes(wall.dow);
357
+ return fields.eitherDay ? dom || dow : dom && dow;
348
358
  }
349
359
  /** Whether a wall-clock minute matches every field of the expression. */
350
360
  function wallMatches(wall, fields) {
@@ -972,7 +982,7 @@ var CronScheduler = class {
972
982
  const begun = new Promise((resolve) => {
973
983
  onStart = resolve;
974
984
  });
975
- const run = this.executeJob(job, true, void 0, onStart);
985
+ const run = this.executeJob(job, true, { onStart });
976
986
  const first = await Promise.race([begun.then((startedAt) => ({ startedAt })), run.then((log) => ({ log }))]);
977
987
  if ("startedAt" in first) return {
978
988
  started: true,
@@ -1250,7 +1260,7 @@ var CronScheduler = class {
1250
1260
  return;
1251
1261
  }
1252
1262
  }
1253
- await this.executeJob(job, false);
1263
+ await this.executeJob(job, false, { slot: nextRun });
1254
1264
  if (this.started && this.shouldArm(job)) this.scheduleNext(id);
1255
1265
  }, delay);
1256
1266
  if (timer && typeof timer === "object" && "unref" in timer) timer.unref();
@@ -1304,7 +1314,10 @@ var CronScheduler = class {
1304
1314
  if (!claimed) continue;
1305
1315
  const lateBy = Math.round((now.getTime() - slot.getTime()) / 1e3);
1306
1316
  logger.info(`[cron] Catching up missed slot ${slotIso} for "${job.id}" (${lateBy}s late)`);
1307
- await this.executeJob(job, false, `⏰ Catch-up run for missed slot ${slotIso} (${lateBy}s late)`);
1317
+ await this.executeJob(job, false, {
1318
+ slot,
1319
+ seedLog: `⏰ Catch-up run for missed slot ${slotIso} (${lateBy}s late)`
1320
+ });
1308
1321
  } catch (err) {
1309
1322
  logger.error(`[cron] Catch-up failed for "${job.id}"`, { error: err });
1310
1323
  }
@@ -1329,12 +1342,12 @@ var CronScheduler = class {
1329
1342
  * - Persists to store (non-blocking) if available
1330
1343
  * - Always restores state even on catastrophic errors
1331
1344
  */
1332
- executeJob(job, manual, seedLog, onStart) {
1345
+ executeJob(job, manual, run = {}) {
1333
1346
  const abort = new AbortController();
1334
1347
  this.runControllers.add(abort);
1335
- const run = this.runJob(job, manual, abort, seedLog, onStart);
1336
- this.track(run);
1337
- return run.finally(() => {
1348
+ const execution = this.runJob(job, manual, abort, run);
1349
+ this.track(execution);
1350
+ return execution.finally(() => {
1338
1351
  this.runControllers.delete(abort);
1339
1352
  });
1340
1353
  }
@@ -1346,7 +1359,7 @@ var CronScheduler = class {
1346
1359
  };
1347
1360
  work.then(release, release);
1348
1361
  }
1349
- async runJob(job, manual, abort, seedLog, onStart) {
1362
+ async runJob(job, manual, abort, { slot, seedLog, onStart }) {
1350
1363
  if (job.executing) return this.recordSkip(job, "already_executing", manual);
1351
1364
  job.executing = true;
1352
1365
  const lease = await this.acquireLease(job);
@@ -1359,7 +1372,7 @@ var CronScheduler = class {
1359
1372
  const capturedLogs = createLogCapture(seedLog || void 0);
1360
1373
  const ctx = {
1361
1374
  jobId: job.id,
1362
- scheduledAt: startedAt,
1375
+ scheduledAt: slot ?? startedAt,
1363
1376
  signal: abort.signal,
1364
1377
  log: (...args) => {
1365
1378
  const line = args.map((a) => typeof a === "string" ? a : JSON.stringify(a)).join(" ");
@@ -1454,4 +1467,4 @@ var CronScheduler = class {
1454
1467
  //#endregion
1455
1468
  export { parseEnvBoolean as a, validateCronExpression as i, cron_scheduler_exports as n, isAlreadyExecutingSkip as r, CronScheduler as t };
1456
1469
 
1457
- //# sourceMappingURL=cron-scheduler-Be7CNghL.js.map
1470
+ //# sourceMappingURL=cron-scheduler-6ipIm5mm.js.map