@rebasepro/cli 0.34.0 → 0.34.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/dist/{agent-setup-CGeAuP0Q.js → agent-setup-kjdKozkF.js} +3 -3
  2. package/dist/{agent-setup-CGeAuP0Q.js.map → agent-setup-kjdKozkF.js.map} +1 -1
  3. package/dist/{api-zx1wSK5a.js → api-CQh_qTyQ.js} +2 -2
  4. package/dist/{api-zx1wSK5a.js.map → api-CQh_qTyQ.js.map} +1 -1
  5. package/dist/{api-keys-DaWN8dyI.js → api-keys-CG2IpknI.js} +5 -5
  6. package/dist/{api-keys-DaWN8dyI.js.map → api-keys-CG2IpknI.js.map} +1 -1
  7. package/dist/{apps-D6vtDrkJ.js → apps-DaaWvv3o.js} +6 -6
  8. package/dist/{apps-D6vtDrkJ.js.map → apps-DaaWvv3o.js.map} +1 -1
  9. package/dist/{atlas-dev-database-D6h65f2x.js → atlas-dev-database-BiDMUr9W.js} +2 -2
  10. package/dist/{atlas-dev-database-D6h65f2x.js.map → atlas-dev-database-BiDMUr9W.js.map} +1 -1
  11. package/dist/{auth-DY7kU0z-.js → auth-bi8x2YX1.js} +12 -12
  12. package/dist/{auth-DY7kU0z-.js.map → auth-bi8x2YX1.js.map} +1 -1
  13. package/dist/{auth-session-DCG96UGH.js → auth-session-BVoxE5tp.js} +4 -4
  14. package/dist/{auth-session-DCG96UGH.js.map → auth-session-BVoxE5tp.js.map} +1 -1
  15. package/dist/{backend-guard-Cf8eMK_f.js → backend-guard--SW3MTSh.js} +2 -2
  16. package/dist/{backend-guard-Cf8eMK_f.js.map → backend-guard--SW3MTSh.js.map} +1 -1
  17. package/dist/{branch-pointer-BJOF2Ubv.js → branch-pointer-BjKUoENm.js} +1 -1
  18. package/dist/{build-D0egCUfU.js → build-D-0VCmbU.js} +11 -11
  19. package/dist/build-D-0VCmbU.js.map +1 -0
  20. package/dist/{bundle-DhdhtD8K.js → bundle-BDTVS9XE.js} +6 -6
  21. package/dist/{bundle-DhdhtD8K.js.map → bundle-BDTVS9XE.js.map} +1 -1
  22. package/dist/{cloud-DOR7bxDw.js → cloud-CR6Hps3B.js} +12 -12
  23. package/dist/{cloud-DOR7bxDw.js.map → cloud-CR6Hps3B.js.map} +1 -1
  24. package/dist/{cms-directories-BaV-Is9a.js → cms-directories-AGHvFwH7.js} +2 -2
  25. package/dist/{cms-directories-BaV-Is9a.js.map → cms-directories-AGHvFwH7.js.map} +1 -1
  26. package/dist/{command-BzSP5gBh.js → command-nWgittn1.js} +3 -3
  27. package/dist/{command-BzSP5gBh.js.map → command-nWgittn1.js.map} +1 -1
  28. package/dist/commands/build.d.ts +2 -1
  29. package/dist/{consent-UV6ObCME.js → consent-C8_Ik_GK.js} +3 -3
  30. package/dist/{consent-UV6ObCME.js.map → consent-C8_Ik_GK.js.map} +1 -1
  31. package/dist/{console-BVoYOLAO.js → console-BBGRHOFg.js} +5 -5
  32. package/dist/{console-BVoYOLAO.js.map → console-BBGRHOFg.js.map} +1 -1
  33. package/dist/{context-xt20FMFA.js → context-C9lz1vTS.js} +2 -2
  34. package/dist/{context-xt20FMFA.js.map → context-C9lz1vTS.js.map} +1 -1
  35. package/dist/{cron-CJ6Xk42E.js → cron-BzzNxkBH.js} +3 -3
  36. package/dist/{cron-CJ6Xk42E.js.map → cron-BzzNxkBH.js.map} +1 -1
  37. package/dist/{cron-BGkXIB1N.js → cron-DuZ3Svjq.js} +4 -4
  38. package/dist/{cron-BGkXIB1N.js.map → cron-DuZ3Svjq.js.map} +1 -1
  39. package/dist/{daemon-D5gdG7gx.js → daemon-BCBMn8hE.js} +2 -2
  40. package/dist/{daemon-D5gdG7gx.js.map → daemon-BCBMn8hE.js.map} +1 -1
  41. package/dist/{data-BpkvtCUe.js → data-1eipHbxJ.js} +3 -3
  42. package/dist/{data-BpkvtCUe.js.map → data-1eipHbxJ.js.map} +1 -1
  43. package/dist/{db-D_iF4E-v.js → db-DAotpOxs.js} +28 -28
  44. package/dist/{db-D_iF4E-v.js.map → db-DAotpOxs.js.map} +1 -1
  45. package/dist/{debug-C7Ss34XB.js → debug-CkiOcfsU.js} +2 -2
  46. package/dist/{debug-C7Ss34XB.js.map → debug-CkiOcfsU.js.map} +1 -1
  47. package/dist/{derive-ChP6vgfi.js → derive-BU5kvcOP.js} +2 -2
  48. package/dist/{derive-ChP6vgfi.js.map → derive-BU5kvcOP.js.map} +1 -1
  49. package/dist/{dev-C7n36E6f.js → dev-Ce9PVQS8.js} +13 -13
  50. package/dist/{dev-C7n36E6f.js.map → dev-Ce9PVQS8.js.map} +1 -1
  51. package/dist/{dev-preflight-BMOf2N6r.js → dev-preflight-DROlafgr.js} +2 -2
  52. package/dist/{dev-preflight-BMOf2N6r.js.map → dev-preflight-DROlafgr.js.map} +1 -1
  53. package/dist/{dev-server-2XHSHM_q.js → dev-server-dsabI0UT.js} +2 -2
  54. package/dist/{dev-server-2XHSHM_q.js.map → dev-server-dsabI0UT.js.map} +1 -1
  55. package/dist/{doctor-D0o54XSQ.js → doctor-Cdu3Llrw.js} +7 -7
  56. package/dist/{doctor-D0o54XSQ.js.map → doctor-Cdu3Llrw.js.map} +1 -1
  57. package/dist/{eject-DK_M9kor.js → eject-Dy-qRYhW.js} +3 -3
  58. package/dist/{eject-DK_M9kor.js.map → eject-Dy-qRYhW.js.map} +1 -1
  59. package/dist/{fold-static-DTpaqbB0.js → fold-static-DzV3EJZm.js} +4 -4
  60. package/dist/{fold-static-DTpaqbB0.js.map → fold-static-DzV3EJZm.js.map} +1 -1
  61. package/dist/{functions-DLuuldt2.js → functions-BCEJnISw.js} +4 -4
  62. package/dist/{functions-DLuuldt2.js.map → functions-BCEJnISw.js.map} +1 -1
  63. package/dist/{generate-view-BMaLQm8H.js → generate-view-CZ0SmsJc.js} +4 -4
  64. package/dist/{generate-view-BMaLQm8H.js.map → generate-view-CZ0SmsJc.js.map} +1 -1
  65. package/dist/{generate_sdk-UT1lwwRT.js → generate_sdk-MAbUUZoK.js} +6 -6
  66. package/dist/{generate_sdk-UT1lwwRT.js.map → generate_sdk-MAbUUZoK.js.map} +1 -1
  67. package/dist/index.es.js +54 -54
  68. package/dist/{init-u5Xmr1Ct.js → init-BctfWO3w.js} +44 -24
  69. package/dist/init-BctfWO3w.js.map +1 -0
  70. package/dist/last-dev-database-w-r9T5Xm.js +2 -0
  71. package/dist/{legacy-layout-DI2VeQSV.js → legacy-layout-CiXWalS6.js} +2 -2
  72. package/dist/{legacy-layout-DI2VeQSV.js.map → legacy-layout-CiXWalS6.js.map} +1 -1
  73. package/dist/{logs-DBYRSs6W.js → logs-B_mS4gCn.js} +4 -4
  74. package/dist/{logs-DBYRSs6W.js.map → logs-B_mS4gCn.js.map} +1 -1
  75. package/dist/{manifest-RjqxfCpb.js → manifest-D6B4LA8x.js} +3 -3
  76. package/dist/{manifest-RjqxfCpb.js.map → manifest-D6B4LA8x.js.map} +1 -1
  77. package/dist/{migrate-Cw1FkvUK.js → migrate-DdcgLMyL.js} +3 -3
  78. package/dist/{migrate-Cw1FkvUK.js.map → migrate-DdcgLMyL.js.map} +1 -1
  79. package/dist/{normalize-imports-E4yA1HfW.js → normalize-imports-CVjOssZ2.js} +2 -2
  80. package/dist/{normalize-imports-E4yA1HfW.js.map → normalize-imports-CVjOssZ2.js.map} +1 -1
  81. package/dist/{package-manager-DSEOwTqM.js → package-manager-DTNNGHyK.js} +29 -12
  82. package/dist/package-manager-DTNNGHyK.js.map +1 -0
  83. package/dist/{path-flags-ekLdkbra.js → path-flags-B7Ydt5nv.js} +2 -2
  84. package/dist/{path-flags-ekLdkbra.js.map → path-flags-B7Ydt5nv.js.map} +1 -1
  85. package/dist/{prepare-BaJe0Zik.js → prepare-CFpYl1Nt.js} +4 -4
  86. package/dist/{prepare-BaJe0Zik.js.map → prepare-CFpYl1Nt.js.map} +1 -1
  87. package/dist/{project-DALmhb5R.js → project-CQ5nKddJ.js} +2 -2
  88. package/dist/{project-DALmhb5R.js.map → project-CQ5nKddJ.js.map} +1 -1
  89. package/dist/{project-command-7EGMemEy.js → project-command-5wM_bJQt.js} +7 -7
  90. package/dist/{project-command-7EGMemEy.js.map → project-command-5wM_bJQt.js.map} +1 -1
  91. package/dist/resolve-GDRel2ne.js +2 -0
  92. package/dist/{resources-CE6BeL94.js → resources-ecA0MEjy.js} +4 -4
  93. package/dist/{resources-CE6BeL94.js.map → resources-ecA0MEjy.js.map} +1 -1
  94. package/dist/{rls-BxWLfEKl.js → rls-B4zGbTKY.js} +3 -3
  95. package/dist/{rls-BxWLfEKl.js.map → rls-B4zGbTKY.js.map} +1 -1
  96. package/dist/{schema-D8xFSBbN.js → schema-CWzzn0cY.js} +11 -11
  97. package/dist/{schema-D8xFSBbN.js.map → schema-CWzzn0cY.js.map} +1 -1
  98. package/dist/{schema-dir-ChcYfWjP.js → schema-dir-Dd1Pzqq5.js} +2 -2
  99. package/dist/{schema-dir-ChcYfWjP.js.map → schema-dir-Dd1Pzqq5.js.map} +1 -1
  100. package/dist/schema-reconcile-DGEMmYJI.js +2 -0
  101. package/dist/{schema-show-C7bY7SgE.js → schema-show-DwYtOp4S.js} +5 -5
  102. package/dist/{schema-show-C7bY7SgE.js.map → schema-show-DwYtOp4S.js.map} +1 -1
  103. package/dist/{skills-C8WdRTFg.js → skills-CWmBTCRW.js} +5 -5
  104. package/dist/{skills-C8WdRTFg.js.map → skills-CWmBTCRW.js.map} +1 -1
  105. package/dist/{start-CN_9C205.js → start-4uhCu_md.js} +6 -6
  106. package/dist/{start-CN_9C205.js.map → start-4uhCu_md.js.map} +1 -1
  107. package/dist/{status-HWlZbY1E.js → status-CVEzoSwX.js} +7 -7
  108. package/dist/{status-HWlZbY1E.js.map → status-CVEzoSwX.js.map} +1 -1
  109. package/dist/{storage-DBE8lgH-.js → storage-Dqf5tyhs.js} +9 -9
  110. package/dist/{storage-DBE8lgH-.js.map → storage-Dqf5tyhs.js.map} +1 -1
  111. package/dist/{storage-objects-ljDmtuH7.js → storage-objects-DbFsemMV.js} +3 -3
  112. package/dist/{storage-objects-ljDmtuH7.js.map → storage-objects-DbFsemMV.js.map} +1 -1
  113. package/dist/{telemetry-DZU2-NCm.js → telemetry-B5RSeQIc.js} +3 -3
  114. package/dist/{telemetry-DZU2-NCm.js.map → telemetry-B5RSeQIc.js.map} +1 -1
  115. package/dist/{telemetry-EVtASbKb.js → telemetry-CJbrRuG3.js} +2 -2
  116. package/dist/{telemetry-EVtASbKb.js.map → telemetry-CJbrRuG3.js.map} +1 -1
  117. package/dist/{upgrade-ZASvgxWM.js → upgrade-CepjhRrz.js} +6 -6
  118. package/dist/{upgrade-ZASvgxWM.js.map → upgrade-CepjhRrz.js.map} +1 -1
  119. package/dist/{users-DrJEtL9k.js → users-Cx5HuaTn.js} +3 -3
  120. package/dist/{users-DrJEtL9k.js.map → users-Cx5HuaTn.js.map} +1 -1
  121. package/dist/utils/package-manager.d.ts +12 -13
  122. package/dist/{verify-BdeqNb-V.js → verify-D-1y5HQS.js} +8 -8
  123. package/dist/{verify-BdeqNb-V.js.map → verify-D-1y5HQS.js.map} +1 -1
  124. package/package.json +10 -10
  125. package/templates/template/npmrc +5 -7
  126. package/dist/build-D0egCUfU.js.map +0 -1
  127. package/dist/init-u5Xmr1Ct.js.map +0 -1
  128. package/dist/last-dev-database-CBVkEUEl.js +0 -2
  129. package/dist/package-manager-DSEOwTqM.js.map +0 -1
  130. package/dist/resolve-C36px9tR.js +0 -2
  131. package/dist/schema-reconcile-D_wvZY91.js +0 -2
@@ -1,5 +1,5 @@
1
- import { F as parseCloudArgs, G as reportError, K as requireClient, X as requireProject, Y as requireKnownAction, f as displayProjectRef, m as emit, v as fail } from "./context-xt20FMFA.js";
2
- import { c as resolveOrigin } from "./debug-C7Ss34XB.js";
1
+ import { F as parseCloudArgs, G as reportError, K as requireClient, X as requireProject, Y as requireKnownAction, f as displayProjectRef, m as emit, v as fail } from "./context-C9lz1vTS.js";
2
+ import { c as resolveOrigin } from "./debug-CkiOcfsU.js";
3
3
  import chalk from "chalk";
4
4
  //#region src/commands/cloud/cron.ts
5
5
  /**
@@ -256,4 +256,4 @@ async function cronCommand(action, rawArgs) {
256
256
  //#endregion
257
257
  export { cronCommand, isMissingRoute, mintRuntimeToken, shortDuration, shortTime };
258
258
 
259
- //# sourceMappingURL=cron-CJ6Xk42E.js.map
259
+ //# sourceMappingURL=cron-BzzNxkBH.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cron-CJ6Xk42E.js","names":[],"sources":["../src/commands/cloud/cron.ts"],"sourcesContent":["/**\n * `rebase cloud cron` — a deployed project's scheduled jobs and their run\n * history, read with the `rebase cloud` login.\n *\n * ## Why this is not just `curl /api/admin/cron`\n *\n * The run history lives in the app itself — `rebase.cron_logs`, served by the\n * runtime's `/api/admin/cron/:id/logs` — behind the app's admin gate. A project\n * owner is signed in to the *control plane*, which that gate has never heard\n * of, and holds none of what it accepts: often no admin account in the app yet,\n * no `rk_` key, and rightly not the service key, which is admin on the whole API.\n * Pod stdout (`rebase cloud debug logs`) covers the last half hour or so; the\n * history covers every run.\n *\n * ## How it reaches the runtime\n *\n * Two legs, each over a channel `rebase cloud debug` already uses:\n *\n * 1. The control plane, as the signed-in person (`debug logs`' channel):\n * `POST /api/functions/runtime-token/<project>` checks the caller may read\n * this project's logs and answers a token — `rpt_…`, ES256, bound to this\n * project, `cron:read` only, minutes long.\n * 2. The runtime at its public address (`debug health`'s channel), with that\n * token as the bearer. The runtime verifies it against the platform's\n * public key and grants `cron:read` and nothing else — it cannot trigger,\n * disable, or read anything but cron.\n *\n * A fresh token per command: nothing is cached, so nothing long-lived ends up\n * on this machine.\n */\nimport chalk from \"chalk\";\nimport type { CronJobLogEntry, CronJobStatus } from \"@rebasepro/types\";\nimport {\n requireClient,\n requireProject,\n parseCloudArgs,\n displayProjectRef,\n emit,\n fail,\n reportError,\n requireKnownAction,\n type CloudClient\n} from \"./context\";\nimport { resolveOrigin } from \"./debug\";\n\n/** The control-plane function that mints runtime tokens. */\nexport const RUNTIME_TOKEN_FUNCTION = \"runtime-token\";\n\n/** The one scope these commands ask the platform for. */\nexport const CRON_READ_SCOPE = \"cron:read\";\n\n/** Where the runtime serves its cron surface. */\nconst CRON_PATH = \"/api/admin/cron\";\n\nconst RUNTIME_TIMEOUT_MS = 15_000;\n\n/** What `runtime-token` answers. */\nexport interface RuntimeTokenResponse {\n /** `rpt_…` — the bearer the runtime accepts. */\n token: string;\n /** ISO timestamp; past it the runtime refuses the token. */\n expiresAt?: string;\n /** What the token was granted, which may be narrower than what was asked. */\n scopes?: string[];\n}\n\n/** What the runtime's `GET /api/admin/cron` answers. */\ninterface CronListResponse {\n jobs?: CronJobStatus[];\n skipped?: number;\n rejected?: Array<{ id: string; name: string; schedule: string; reason: string }>;\n note?: string;\n}\n\n/** The runtime's error envelope, as far as these commands read it. */\ninterface ErrorEnvelope {\n error?: { code?: string; message?: string };\n}\n\n/**\n * A 404 that is about the route, not the project: the JSON envelope a Rebase\n * backend answers for an unmatched path, or the bare one a router answers\n * before that handler exists.\n */\nexport function isMissingRoute(message: string | undefined): boolean {\n return /^No route for |^(404 )?Not Found$/i.test((message ?? \"\").trim());\n}\n\n/**\n * Ask the control plane for a token the project's runtime will accept.\n *\n * A missing route means this control plane has no `runtime-token` function\n * yet, which is a different fix from \"no such project\" and is said so.\n */\nexport async function mintRuntimeToken(\n client: CloudClient,\n projectId: string,\n scopes: string[]\n): Promise<RuntimeTokenResponse> {\n let res: RuntimeTokenResponse;\n try {\n res = await client.functions.invoke<RuntimeTokenResponse>(RUNTIME_TOKEN_FUNCTION, { scopes }, {\n method: \"POST\",\n path: projectId\n });\n } catch (e) {\n const err = e as { status?: number; message?: string };\n if (err.status === 404 && isMissingRoute(err.message)) {\n fail(\n \"This control plane does not issue runtime tokens yet, so the CLI cannot read the app's cron history.\",\n \"Until it does, `rebase cloud debug logs` shows what jobs printed in the last half hour.\",\n \"runtime_token_unavailable\"\n );\n }\n reportError(e, \"Failed to get a runtime token from the control plane\");\n }\n if (typeof res?.token !== \"string\" || res.token.length === 0) {\n fail(\"The control plane answered without a runtime token.\", undefined, \"runtime_token_unavailable\");\n }\n return res;\n}\n\n/**\n * GET a path on the runtime with a platform token, and refuse — with what it\n * means for this command — anything but a 2xx.\n *\n * `notFound` words the 404, which means different things per route: no cron\n * surface at all on the list, no such job on its logs.\n */\nexport async function runtimeGet<T>(\n origin: string,\n path: string,\n token: string,\n notFound: { message: string; hint?: string; code: string }\n): Promise<T> {\n let res: Response;\n try {\n res = await fetch(`${origin}${path}`, {\n headers: { Authorization: `Bearer ${token}`, Accept: \"application/json\" },\n redirect: \"manual\",\n signal: AbortSignal.timeout(RUNTIME_TIMEOUT_MS)\n });\n } catch (e) {\n fail(\n `Could not reach the app at ${origin}: ${e instanceof Error ? e.message : String(e)}`,\n \"`rebase cloud debug health` checks whether the deployment is answering at all.\",\n \"runtime_unreachable\"\n );\n }\n\n const text = await res.text();\n let body: unknown;\n try {\n body = text ? JSON.parse(text) : undefined;\n } catch {\n body = undefined;\n }\n if (res.ok) return body as T;\n\n const error = (body as ErrorEnvelope | undefined)?.error;\n const said = error?.message ? ` (${error.message})` : \"\";\n\n if (res.status === 401) {\n if (error?.code === \"PLATFORM_TOKENS_OFF\" || error?.code === \"INVALID_PLATFORM_TOKEN\") {\n fail(\n `The app refused the platform's token${said}.`,\n \"The platform sets the key it verifies with when it deploys; redeploying the project picks it up.\",\n \"runtime_token_refused\"\n );\n }\n // A runtime that predates platform tokens parses `rpt_…` as a user\n // session and answers the generic refusal.\n fail(\n `This deployment's runtime does not accept platform tokens${said}.`,\n \"Runtimes from before platform tokens accept only an admin of the app, an `rk_` key or the service key. \" +\n \"Redeploy to move to a runtime that accepts them.\",\n \"runtime_token_refused\"\n );\n }\n if (res.status === 404) fail(notFound.message, notFound.hint, notFound.code);\n if (res.status === 501 && error?.code === \"ADMIN_SURFACE_UNAVAILABLE\") {\n fail(`The app has its admin surfaces switched off${said}.`, undefined, \"admin_surface_unavailable\");\n }\n fail(\n `The app answered ${res.status} for ${path}${said}.`,\n res.status >= 500 ? \"`rebase cloud debug errors` shows what the server logged.\" : undefined,\n res.status === 400 ? \"usage\" : \"runtime_error\"\n );\n}\n\n/** Everything both actions need before their one request. */\nasync function connect(rawArgs: string[]): Promise<{ origin: string; token: string }> {\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n // The origin first: a project with no address cannot be read, and that is\n // worth knowing before asking anyone to mint anything.\n const origin = await resolveOrigin(rawArgs, client, url, projectId);\n const { token } = await mintRuntimeToken(client, projectId, [CRON_READ_SCOPE]);\n return { origin, token };\n}\n\nconst NO_CRON_SURFACE = {\n message: \"This deployment serves no cron surface.\",\n hint: \"The app was built without a crons directory, or its runtime does not serve the cron admin routes.\",\n code: \"cron_not_served\"\n};\n\n/** `2026-10-05T10:31:00.000Z` → `2026-10-05 10:31:00Z`, or `—`. */\nexport function shortTime(iso: string | undefined): string {\n if (!iso) return \"—\";\n const date = new Date(iso);\n return Number.isNaN(date.getTime()) ? iso : `${date.toISOString().slice(0, 19).replace(\"T\", \" \")}Z`;\n}\n\n/** Milliseconds as `850ms`, `2.4s` or `3m 10s`. */\nexport function shortDuration(ms: number | undefined): string {\n if (ms === undefined || !Number.isFinite(ms)) return \"\";\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;\n return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;\n}\n\nfunction stateColor(state: string): string {\n if (state === \"error\") return chalk.red(state);\n if (state === \"running\") return chalk.cyan(state);\n if (state === \"disabled\") return chalk.gray(state);\n if (state === \"success\") return chalk.green(state);\n return state;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n cron list\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `cron list` parses — the help page lists exactly these. */\nexport const CRON_LIST_FLAGS = { \"--host\": String };\n\nasync function listCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({\n spec: CRON_LIST_FLAGS,\n rawArgs,\n commandWords: 3,\n command: \"cloud cron list\",\n maxPositionals: 0\n });\n const { origin, token } = await connect(rawArgs);\n const res = await runtimeGet<CronListResponse>(origin, CRON_PATH, token, NO_CRON_SURFACE);\n const jobs = res?.jobs ?? [];\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ⏰ Cron — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${origin}`));\n console.log(\"\");\n if (jobs.length === 0) {\n console.log(chalk.gray(\" No cron jobs are scheduled on this deployment.\"));\n } else {\n // Padded on the plain text: a colour code has length and no width.\n const lastRun = (job: CronJobStatus): { at: string; took: string } => ({\n at: shortTime(job.lastRunAt),\n took: job.lastRunAt ? shortDuration(job.lastDurationMs) : \"\"\n });\n const lastText = (job: CronJobStatus): string => [lastRun(job).at, lastRun(job).took].filter(Boolean).join(\" \");\n const idWidth = Math.max(3, ...jobs.map(job => job.id.length));\n const scheduleWidth = Math.max(8, ...jobs.map(job => job.schedule.length));\n const stateWidth = Math.max(5, ...jobs.map(job => job.state.length));\n const lastWidth = Math.max(8, ...jobs.map(job => lastText(job).length));\n console.log(chalk.gray(\n ` ${\"JOB\".padEnd(idWidth)} ${\"SCHEDULE\".padEnd(scheduleWidth)} ${\"STATE\".padEnd(stateWidth)} ` +\n `${\"LAST RUN\".padEnd(lastWidth)} NEXT RUN`\n ));\n for (const job of jobs) {\n const { at, took } = lastRun(job);\n const pad = (text: string, width: number) => \" \".repeat(Math.max(0, width - text.length));\n console.log(\n ` ${chalk.bold(job.id)}${pad(job.id, idWidth)} ${job.schedule.padEnd(scheduleWidth)} ` +\n `${stateColor(job.state)}${pad(job.state, stateWidth)} ` +\n `${at}${took ? ` ${chalk.gray(took)}` : \"\"}${pad(lastText(job), lastWidth)} ${shortTime(job.nextRunAt)}`\n );\n if (job.state === \"error\" && job.lastError) {\n console.log(chalk.red(` ${\" \".repeat(idWidth)} ${job.lastError}`));\n }\n }\n }\n if (res?.note) {\n console.log(\"\");\n console.log(chalk.yellow(` ⚠ ${res.note}`));\n for (const rejected of res.rejected ?? []) {\n console.log(chalk.yellow(` ${rejected.id} (${rejected.schedule}): ${rejected.reason}`));\n }\n }\n console.log(\"\");\n if (jobs.length > 0) {\n console.log(chalk.gray(\" A job's run history: \") + chalk.bold(\"rebase cloud cron logs <job>\"));\n console.log(\"\");\n }\n },\n {\n origin,\n jobs,\n skipped: res?.skipped ?? 0,\n rejected: res?.rejected ?? [],\n note: res?.note ?? null\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n cron logs <job>\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `cron logs` parses — the help page lists exactly these. */\nexport const CRON_LOGS_FLAGS = { \"--limit\": Number, \"--host\": String };\n\nasync function logsCommand(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parseCloudArgs({\n spec: CRON_LOGS_FLAGS,\n rawArgs,\n commandWords: 3,\n command: \"cloud cron logs\",\n maxPositionals: 1\n });\n const jobId = positionals[0];\n if (!jobId) {\n fail(\"Name the job: `rebase cloud cron logs <job>`.\", \"`rebase cloud cron list` names them.\", \"usage\");\n }\n const limit = flags[\"--limit\"];\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {\n fail(`--limit must be a positive whole number; received ${String(limit)}.`, undefined, \"usage\");\n }\n\n const { origin, token } = await connect(rawArgs);\n const query = limit !== undefined ? `?limit=${limit}` : \"\";\n const res = await runtimeGet<{ logs?: CronJobLogEntry[] }>(\n origin,\n `${CRON_PATH}/${encodeURIComponent(jobId)}/logs${query}`,\n token,\n {\n message: `No cron job named \"${jobId}\" on this deployment (or no cron surface at all).`,\n hint: \"`rebase cloud cron list` names the jobs it runs.\",\n code: \"not_found\"\n }\n );\n const logs = res?.logs ?? [];\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` 📜 Cron runs — ${jobId} on ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` newest first, ${logs.length} run${logs.length === 1 ? \"\" : \"s\"}`)\n );\n console.log(\"\");\n if (logs.length === 0) {\n console.log(chalk.gray(\" This job has no recorded runs.\"));\n console.log(\"\");\n return;\n }\n for (const run of logs) {\n const mark = run.success ? chalk.green(\"✓\") : chalk.red(\"✗\");\n const tags = [shortDuration(run.durationMs), run.manual ? \"manual\" : undefined].filter(Boolean).join(\" \");\n console.log(` ${mark} ${shortTime(run.startedAt)} ${chalk.gray(tags)}`);\n if (run.error) console.log(chalk.red(` ${run.error}`));\n for (const line of run.logs ?? []) console.log(` ${line}`);\n }\n console.log(\"\");\n },\n { origin, job: jobId, logs }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\n\nconst CRON_ACTIONS = [\"list\", \"logs\"] as const;\n\nexport async function cronCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n requireKnownAction(\"cron\", action, CRON_ACTIONS);\n if (action === \"logs\") {\n await logsCommand(rawArgs);\n return;\n }\n await listCommand(rawArgs);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,IAAa,yBAAyB;;AAGtC,IAAa,kBAAkB;;AAG/B,IAAM,YAAY;AAElB,IAAM,qBAAqB;;;;;;AA8B3B,SAAgB,eAAe,SAAsC;CACjE,OAAO,qCAAqC,MAAM,WAAW,GAAA,CAAI,KAAK,CAAC;AAC3E;;;;;;;AAQA,eAAsB,iBAClB,QACA,WACA,QAC6B;CAC7B,IAAI;CACJ,IAAI;EACA,MAAM,MAAM,OAAO,UAAU,OAA6B,wBAAwB,EAAE,OAAO,GAAG;GAC1F,QAAQ;GACR,MAAM;EACV,CAAC;CACL,SAAS,GAAG;EACR,MAAM,MAAM;EACZ,IAAI,IAAI,WAAW,OAAO,eAAe,IAAI,OAAO,GAChD,KACI,wGACA,2FACA,2BACJ;EAEJ,YAAY,GAAG,sDAAsD;CACzE;CACA,IAAI,OAAO,KAAK,UAAU,YAAY,IAAI,MAAM,WAAW,GACvD,KAAK,uDAAuD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,EAAE;CAClB,GACA;EAAE;EAAQ,KAAK;EAAO;CAAK,CAC/B;AACJ;AAMA,IAAM,eAAe,CAAC,QAAQ,MAAM;AAEpC,eAAsB,YAAY,QAA4B,SAAkC;CAC5F,mBAAmB,QAAQ,QAAQ,YAAY;CAC/C,IAAI,WAAW,QAAQ;EACnB,MAAM,YAAY,OAAO;EACzB;CACJ;CACA,MAAM,YAAY,OAAO;AAC7B"}
1
+ {"version":3,"file":"cron-BzzNxkBH.js","names":[],"sources":["../src/commands/cloud/cron.ts"],"sourcesContent":["/**\n * `rebase cloud cron` — a deployed project's scheduled jobs and their run\n * history, read with the `rebase cloud` login.\n *\n * ## Why this is not just `curl /api/admin/cron`\n *\n * The run history lives in the app itself — `rebase.cron_logs`, served by the\n * runtime's `/api/admin/cron/:id/logs` — behind the app's admin gate. A project\n * owner is signed in to the *control plane*, which that gate has never heard\n * of, and holds none of what it accepts: often no admin account in the app yet,\n * no `rk_` key, and rightly not the service key, which is admin on the whole API.\n * Pod stdout (`rebase cloud debug logs`) covers the last half hour or so; the\n * history covers every run.\n *\n * ## How it reaches the runtime\n *\n * Two legs, each over a channel `rebase cloud debug` already uses:\n *\n * 1. The control plane, as the signed-in person (`debug logs`' channel):\n * `POST /api/functions/runtime-token/<project>` checks the caller may read\n * this project's logs and answers a token — `rpt_…`, ES256, bound to this\n * project, `cron:read` only, minutes long.\n * 2. The runtime at its public address (`debug health`'s channel), with that\n * token as the bearer. The runtime verifies it against the platform's\n * public key and grants `cron:read` and nothing else — it cannot trigger,\n * disable, or read anything but cron.\n *\n * A fresh token per command: nothing is cached, so nothing long-lived ends up\n * on this machine.\n */\nimport chalk from \"chalk\";\nimport type { CronJobLogEntry, CronJobStatus } from \"@rebasepro/types\";\nimport {\n requireClient,\n requireProject,\n parseCloudArgs,\n displayProjectRef,\n emit,\n fail,\n reportError,\n requireKnownAction,\n type CloudClient\n} from \"./context\";\nimport { resolveOrigin } from \"./debug\";\n\n/** The control-plane function that mints runtime tokens. */\nexport const RUNTIME_TOKEN_FUNCTION = \"runtime-token\";\n\n/** The one scope these commands ask the platform for. */\nexport const CRON_READ_SCOPE = \"cron:read\";\n\n/** Where the runtime serves its cron surface. */\nconst CRON_PATH = \"/api/admin/cron\";\n\nconst RUNTIME_TIMEOUT_MS = 15_000;\n\n/** What `runtime-token` answers. */\nexport interface RuntimeTokenResponse {\n /** `rpt_…` — the bearer the runtime accepts. */\n token: string;\n /** ISO timestamp; past it the runtime refuses the token. */\n expiresAt?: string;\n /** What the token was granted, which may be narrower than what was asked. */\n scopes?: string[];\n}\n\n/** What the runtime's `GET /api/admin/cron` answers. */\ninterface CronListResponse {\n jobs?: CronJobStatus[];\n skipped?: number;\n rejected?: Array<{ id: string; name: string; schedule: string; reason: string }>;\n note?: string;\n}\n\n/** The runtime's error envelope, as far as these commands read it. */\ninterface ErrorEnvelope {\n error?: { code?: string; message?: string };\n}\n\n/**\n * A 404 that is about the route, not the project: the JSON envelope a Rebase\n * backend answers for an unmatched path, or the bare one a router answers\n * before that handler exists.\n */\nexport function isMissingRoute(message: string | undefined): boolean {\n return /^No route for |^(404 )?Not Found$/i.test((message ?? \"\").trim());\n}\n\n/**\n * Ask the control plane for a token the project's runtime will accept.\n *\n * A missing route means this control plane has no `runtime-token` function\n * yet, which is a different fix from \"no such project\" and is said so.\n */\nexport async function mintRuntimeToken(\n client: CloudClient,\n projectId: string,\n scopes: string[]\n): Promise<RuntimeTokenResponse> {\n let res: RuntimeTokenResponse;\n try {\n res = await client.functions.invoke<RuntimeTokenResponse>(RUNTIME_TOKEN_FUNCTION, { scopes }, {\n method: \"POST\",\n path: projectId\n });\n } catch (e) {\n const err = e as { status?: number; message?: string };\n if (err.status === 404 && isMissingRoute(err.message)) {\n fail(\n \"This control plane does not issue runtime tokens yet, so the CLI cannot read the app's cron history.\",\n \"Until it does, `rebase cloud debug logs` shows what jobs printed in the last half hour.\",\n \"runtime_token_unavailable\"\n );\n }\n reportError(e, \"Failed to get a runtime token from the control plane\");\n }\n if (typeof res?.token !== \"string\" || res.token.length === 0) {\n fail(\"The control plane answered without a runtime token.\", undefined, \"runtime_token_unavailable\");\n }\n return res;\n}\n\n/**\n * GET a path on the runtime with a platform token, and refuse — with what it\n * means for this command — anything but a 2xx.\n *\n * `notFound` words the 404, which means different things per route: no cron\n * surface at all on the list, no such job on its logs.\n */\nexport async function runtimeGet<T>(\n origin: string,\n path: string,\n token: string,\n notFound: { message: string; hint?: string; code: string }\n): Promise<T> {\n let res: Response;\n try {\n res = await fetch(`${origin}${path}`, {\n headers: { Authorization: `Bearer ${token}`, Accept: \"application/json\" },\n redirect: \"manual\",\n signal: AbortSignal.timeout(RUNTIME_TIMEOUT_MS)\n });\n } catch (e) {\n fail(\n `Could not reach the app at ${origin}: ${e instanceof Error ? e.message : String(e)}`,\n \"`rebase cloud debug health` checks whether the deployment is answering at all.\",\n \"runtime_unreachable\"\n );\n }\n\n const text = await res.text();\n let body: unknown;\n try {\n body = text ? JSON.parse(text) : undefined;\n } catch {\n body = undefined;\n }\n if (res.ok) return body as T;\n\n const error = (body as ErrorEnvelope | undefined)?.error;\n const said = error?.message ? ` (${error.message})` : \"\";\n\n if (res.status === 401) {\n if (error?.code === \"PLATFORM_TOKENS_OFF\" || error?.code === \"INVALID_PLATFORM_TOKEN\") {\n fail(\n `The app refused the platform's token${said}.`,\n \"The platform sets the key it verifies with when it deploys; redeploying the project picks it up.\",\n \"runtime_token_refused\"\n );\n }\n // A runtime that predates platform tokens parses `rpt_…` as a user\n // session and answers the generic refusal.\n fail(\n `This deployment's runtime does not accept platform tokens${said}.`,\n \"Runtimes from before platform tokens accept only an admin of the app, an `rk_` key or the service key. \" +\n \"Redeploy to move to a runtime that accepts them.\",\n \"runtime_token_refused\"\n );\n }\n if (res.status === 404) fail(notFound.message, notFound.hint, notFound.code);\n if (res.status === 501 && error?.code === \"ADMIN_SURFACE_UNAVAILABLE\") {\n fail(`The app has its admin surfaces switched off${said}.`, undefined, \"admin_surface_unavailable\");\n }\n fail(\n `The app answered ${res.status} for ${path}${said}.`,\n res.status >= 500 ? \"`rebase cloud debug errors` shows what the server logged.\" : undefined,\n res.status === 400 ? \"usage\" : \"runtime_error\"\n );\n}\n\n/** Everything both actions need before their one request. */\nasync function connect(rawArgs: string[]): Promise<{ origin: string; token: string }> {\n const { client, url } = await requireClient(rawArgs);\n const projectId = await requireProject(rawArgs, client);\n // The origin first: a project with no address cannot be read, and that is\n // worth knowing before asking anyone to mint anything.\n const origin = await resolveOrigin(rawArgs, client, url, projectId);\n const { token } = await mintRuntimeToken(client, projectId, [CRON_READ_SCOPE]);\n return { origin, token };\n}\n\nconst NO_CRON_SURFACE = {\n message: \"This deployment serves no cron surface.\",\n hint: \"The app was built without a crons directory, or its runtime does not serve the cron admin routes.\",\n code: \"cron_not_served\"\n};\n\n/** `2026-10-05T10:31:00.000Z` → `2026-10-05 10:31:00Z`, or `—`. */\nexport function shortTime(iso: string | undefined): string {\n if (!iso) return \"—\";\n const date = new Date(iso);\n return Number.isNaN(date.getTime()) ? iso : `${date.toISOString().slice(0, 19).replace(\"T\", \" \")}Z`;\n}\n\n/** Milliseconds as `850ms`, `2.4s` or `3m 10s`. */\nexport function shortDuration(ms: number | undefined): string {\n if (ms === undefined || !Number.isFinite(ms)) return \"\";\n if (ms < 1000) return `${Math.round(ms)}ms`;\n if (ms < 60_000) return `${(ms / 1000).toFixed(1)}s`;\n return `${Math.floor(ms / 60_000)}m ${Math.round((ms % 60_000) / 1000)}s`;\n}\n\nfunction stateColor(state: string): string {\n if (state === \"error\") return chalk.red(state);\n if (state === \"running\") return chalk.cyan(state);\n if (state === \"disabled\") return chalk.gray(state);\n if (state === \"success\") return chalk.green(state);\n return state;\n}\n\n/* ═══════════════════════════════════════════════════════════════\n cron list\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `cron list` parses — the help page lists exactly these. */\nexport const CRON_LIST_FLAGS = { \"--host\": String };\n\nasync function listCommand(rawArgs: string[]): Promise<void> {\n parseCloudArgs({\n spec: CRON_LIST_FLAGS,\n rawArgs,\n commandWords: 3,\n command: \"cloud cron list\",\n maxPositionals: 0\n });\n const { origin, token } = await connect(rawArgs);\n const res = await runtimeGet<CronListResponse>(origin, CRON_PATH, token, NO_CRON_SURFACE);\n const jobs = res?.jobs ?? [];\n\n emit(\n () => {\n console.log(\"\");\n console.log(chalk.bold(` ⏰ Cron — ${displayProjectRef(rawArgs)}`) + chalk.gray(` ${origin}`));\n console.log(\"\");\n if (jobs.length === 0) {\n console.log(chalk.gray(\" No cron jobs are scheduled on this deployment.\"));\n } else {\n // Padded on the plain text: a colour code has length and no width.\n const lastRun = (job: CronJobStatus): { at: string; took: string } => ({\n at: shortTime(job.lastRunAt),\n took: job.lastRunAt ? shortDuration(job.lastDurationMs) : \"\"\n });\n const lastText = (job: CronJobStatus): string => [lastRun(job).at, lastRun(job).took].filter(Boolean).join(\" \");\n const idWidth = Math.max(3, ...jobs.map(job => job.id.length));\n const scheduleWidth = Math.max(8, ...jobs.map(job => job.schedule.length));\n const stateWidth = Math.max(5, ...jobs.map(job => job.state.length));\n const lastWidth = Math.max(8, ...jobs.map(job => lastText(job).length));\n console.log(chalk.gray(\n ` ${\"JOB\".padEnd(idWidth)} ${\"SCHEDULE\".padEnd(scheduleWidth)} ${\"STATE\".padEnd(stateWidth)} ` +\n `${\"LAST RUN\".padEnd(lastWidth)} NEXT RUN`\n ));\n for (const job of jobs) {\n const { at, took } = lastRun(job);\n const pad = (text: string, width: number) => \" \".repeat(Math.max(0, width - text.length));\n console.log(\n ` ${chalk.bold(job.id)}${pad(job.id, idWidth)} ${job.schedule.padEnd(scheduleWidth)} ` +\n `${stateColor(job.state)}${pad(job.state, stateWidth)} ` +\n `${at}${took ? ` ${chalk.gray(took)}` : \"\"}${pad(lastText(job), lastWidth)} ${shortTime(job.nextRunAt)}`\n );\n if (job.state === \"error\" && job.lastError) {\n console.log(chalk.red(` ${\" \".repeat(idWidth)} ${job.lastError}`));\n }\n }\n }\n if (res?.note) {\n console.log(\"\");\n console.log(chalk.yellow(` ⚠ ${res.note}`));\n for (const rejected of res.rejected ?? []) {\n console.log(chalk.yellow(` ${rejected.id} (${rejected.schedule}): ${rejected.reason}`));\n }\n }\n console.log(\"\");\n if (jobs.length > 0) {\n console.log(chalk.gray(\" A job's run history: \") + chalk.bold(\"rebase cloud cron logs <job>\"));\n console.log(\"\");\n }\n },\n {\n origin,\n jobs,\n skipped: res?.skipped ?? 0,\n rejected: res?.rejected ?? [],\n note: res?.note ?? null\n }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n cron logs <job>\n ═══════════════════════════════════════════════════════════════ */\n\n/** The flags `cron logs` parses — the help page lists exactly these. */\nexport const CRON_LOGS_FLAGS = { \"--limit\": Number, \"--host\": String };\n\nasync function logsCommand(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parseCloudArgs({\n spec: CRON_LOGS_FLAGS,\n rawArgs,\n commandWords: 3,\n command: \"cloud cron logs\",\n maxPositionals: 1\n });\n const jobId = positionals[0];\n if (!jobId) {\n fail(\"Name the job: `rebase cloud cron logs <job>`.\", \"`rebase cloud cron list` names them.\", \"usage\");\n }\n const limit = flags[\"--limit\"];\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) {\n fail(`--limit must be a positive whole number; received ${String(limit)}.`, undefined, \"usage\");\n }\n\n const { origin, token } = await connect(rawArgs);\n const query = limit !== undefined ? `?limit=${limit}` : \"\";\n const res = await runtimeGet<{ logs?: CronJobLogEntry[] }>(\n origin,\n `${CRON_PATH}/${encodeURIComponent(jobId)}/logs${query}`,\n token,\n {\n message: `No cron job named \"${jobId}\" on this deployment (or no cron surface at all).`,\n hint: \"`rebase cloud cron list` names the jobs it runs.\",\n code: \"not_found\"\n }\n );\n const logs = res?.logs ?? [];\n\n emit(\n () => {\n console.log(\"\");\n console.log(\n chalk.bold(` 📜 Cron runs — ${jobId} on ${displayProjectRef(rawArgs)}`) +\n chalk.gray(` newest first, ${logs.length} run${logs.length === 1 ? \"\" : \"s\"}`)\n );\n console.log(\"\");\n if (logs.length === 0) {\n console.log(chalk.gray(\" This job has no recorded runs.\"));\n console.log(\"\");\n return;\n }\n for (const run of logs) {\n const mark = run.success ? chalk.green(\"✓\") : chalk.red(\"✗\");\n const tags = [shortDuration(run.durationMs), run.manual ? \"manual\" : undefined].filter(Boolean).join(\" \");\n console.log(` ${mark} ${shortTime(run.startedAt)} ${chalk.gray(tags)}`);\n if (run.error) console.log(chalk.red(` ${run.error}`));\n for (const line of run.logs ?? []) console.log(` ${line}`);\n }\n console.log(\"\");\n },\n { origin, job: jobId, logs }\n );\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Dispatch\n ═══════════════════════════════════════════════════════════════ */\n\nconst CRON_ACTIONS = [\"list\", \"logs\"] as const;\n\nexport async function cronCommand(action: string | undefined, rawArgs: string[]): Promise<void> {\n requireKnownAction(\"cron\", action, CRON_ACTIONS);\n if (action === \"logs\") {\n await logsCommand(rawArgs);\n return;\n }\n await listCommand(rawArgs);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CA,IAAa,yBAAyB;;AAGtC,IAAa,kBAAkB;;AAG/B,IAAM,YAAY;AAElB,IAAM,qBAAqB;;;;;;AA8B3B,SAAgB,eAAe,SAAsC;CACjE,OAAO,qCAAqC,MAAM,WAAW,GAAA,CAAI,KAAK,CAAC;AAC3E;;;;;;;AAQA,eAAsB,iBAClB,QACA,WACA,QAC6B;CAC7B,IAAI;CACJ,IAAI;EACA,MAAM,MAAM,OAAO,UAAU,OAA6B,wBAAwB,EAAE,OAAO,GAAG;GAC1F,QAAQ;GACR,MAAM;EACV,CAAC;CACL,SAAS,GAAG;EACR,MAAM,MAAM;EACZ,IAAI,IAAI,WAAW,OAAO,eAAe,IAAI,OAAO,GAChD,KACI,wGACA,2FACA,2BACJ;EAEJ,YAAY,GAAG,sDAAsD;CACzE;CACA,IAAI,OAAO,KAAK,UAAU,YAAY,IAAI,MAAM,WAAW,GACvD,KAA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AQ,IAAI,EAAE;CAClB,GACA;EAAE;EAAQ,KAAK;EAAO;CAAK,CAC/B;AACJ;AAMA,IAAM,eAAe,CAAC,QAAQ,MAAM;AAEpC,eAAsB,YAAY,QAA4B,SAAkC;CAC5F,mBAAmB,QAAQ,QAAQ,YAAY;CAC/C,IAAI,WAAW,QAAQ;EACnB,MAAM,YAAY,OAAO;EACzB;CACJ;CACA,MAAM,YAAY,OAAO;AAC7B"}
@@ -1,8 +1,8 @@
1
1
  import { n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
2
2
  import { a as wantsHelp, n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
3
- import { a as projectTarget, c as requestJson, d as PROJECT_TARGET_FLAGS, i as printProjectHelp, l as startProjectCommand, n as isRecord, r as parsedLine } from "./project-command-7EGMemEy.js";
4
- import { M as note, l as confirmDestructive, m as emit, st as success } from "./context-xt20FMFA.js";
5
- import { shortDuration, shortTime } from "./cron-CJ6Xk42E.js";
3
+ import { a as projectTarget, c as requestJson, d as PROJECT_TARGET_FLAGS, i as printProjectHelp, l as startProjectCommand, n as isRecord, r as parsedLine } from "./project-command-5wM_bJQt.js";
4
+ import { M as note, l as confirmDestructive, m as emit, st as success } from "./context-C9lz1vTS.js";
5
+ import { shortDuration, shortTime } from "./cron-BzzNxkBH.js";
6
6
  import chalk from "chalk";
7
7
  //#region src/commands/cron.ts
8
8
  /** Everything the switch below dispatches, for the did-you-mean. */
@@ -295,4 +295,4 @@ function printCronHelp() {
295
295
  //#endregion
296
296
  export { CRON_SUBCOMMANDS, cronCommand };
297
297
 
298
- //# sourceMappingURL=cron-BGkXIB1N.js.map
298
+ //# sourceMappingURL=cron-DuZ3Svjq.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cron-BGkXIB1N.js","names":[],"sources":["../src/commands/cron.ts"],"sourcesContent":["/**\n * CLI command: rebase cron <action>\n *\n * A running app's scheduled jobs (`backend/crons/*`): list them, read a job's\n * run history, run one now, switch one off or back on. Through the app's\n * `/api/admin/cron` surface, with the target every project command resolves.\n *\n * On a Rebase Cloud project (`--project`, `--cloud`) this needs no Studio\n * access: reads ask the control plane for a short `cron:read` platform token,\n * which any member who may read the project's logs holds, and runs or\n * switches ask for `cron:write`, which an organization owner or admin holds on\n * a project whose Studio switch is on. Nothing long-lived is kept.\n * `rebase cloud cron` is the older, read-only spelling of `list` and `logs`.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\nimport type { CronJobLogEntry, CronJobStatus } from \"@rebasepro/types\";\n\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { PROJECT_TARGET_FLAGS } from \"../utils/project-target\";\nimport {\n emit,\n isRecord,\n parsedLine,\n printProjectHelp,\n projectTarget,\n requestJson,\n startProjectCommand,\n type HelpAction\n} from \"../utils/project-command\";\nimport { confirmDestructive, note, success } from \"./cloud/context\";\nimport { shortDuration, shortTime } from \"./cloud/cron\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const CRON_SUBCOMMANDS = [\"list\", \"get\", \"logs\", \"run\", \"enable\", \"disable\", \"reset\"] as const;\n\nconst CRON_PATH = \"/api/admin/cron\";\n\nexport async function cronCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n startProjectCommand(rawArgs);\n if (subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printCronHelp();\n return;\n }\n switch (subcommand ?? \"list\") {\n case \"list\":\n await listJobs(rawArgs);\n break;\n case \"get\":\n await getJob(rawArgs);\n break;\n case \"logs\":\n await jobLogs(rawArgs);\n break;\n case \"run\":\n await runJob(rawArgs);\n break;\n case \"enable\":\n await switchJob(rawArgs, \"enable\");\n break;\n case \"disable\":\n await switchJob(rawArgs, \"disable\");\n break;\n case \"reset\":\n await switchJob(rawArgs, \"reset\");\n break;\n default:\n unknownCommand(subcommand, CRON_SUBCOMMANDS, \"cron\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Reading a job\n ═══════════════════════════════════════════════════════════════ */\n\nfunction isJob(value: unknown): value is CronJobStatus {\n return isRecord(value) && typeof value.id === \"string\" && typeof value.schedule === \"string\";\n}\n\nfunction jobsOf(body: unknown): CronJobStatus[] {\n return isRecord(body) && Array.isArray(body.jobs) ? body.jobs.filter(isJob) : [];\n}\n\nfunction jobOf(body: unknown): CronJobStatus | undefined {\n if (isRecord(body) && isJob(body.job)) return body.job;\n return isJob(body) ? body : undefined;\n}\n\nfunction isLogEntry(value: unknown): value is CronJobLogEntry {\n return isRecord(value) && typeof value.startedAt === \"string\";\n}\n\nfunction stateColor(state: string): string {\n if (state === \"error\") return chalk.red(state);\n if (state === \"running\") return chalk.cyan(state);\n if (state === \"disabled\") return chalk.gray(state);\n return chalk.green(state);\n}\n\nfunction printJob(job: CronJobStatus): void {\n console.log(` ${chalk.bold(job.id)} ${job.schedule} ${stateColor(job.state)}${job.enabled ? \"\" : chalk.gray(\" (off)\")}`);\n if (job.description) console.log(chalk.gray(` ${job.description}`));\n const last = job.lastRunAt ? `${shortTime(job.lastRunAt)} ${chalk.gray(shortDuration(job.lastDurationMs))}` : chalk.gray(\"never\");\n console.log(chalk.gray(\" last \") + last + chalk.gray(\" next \") + shortTime(job.nextRunAt));\n if (job.state === \"error\" && job.lastError) console.log(chalk.red(` ${job.lastError}`));\n}\n\nfunction requireJobId(positionals: string[], command: string): string {\n if (!positionals[0]) throw new UsageError(`rebase ${command} needs a job id: rebase ${command} <job> (\\`rebase cron list\\` names them).`);\n return positionals[0];\n}\n\n/* ═══════════════════════════════════════════════════════════════\n list / get / logs\n ═══════════════════════════════════════════════════════════════ */\n\nexport const CRON_LIST_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nasync function listJobs(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: CRON_LIST_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"cron list\",\n maxPositionals: 0\n }));\n const target = await projectTarget(flags, { command: \"cron list\", platformScopes: [\"cron:read\"] });\n const body = await requestJson(target, CRON_PATH, \"Failed to list cron jobs\");\n const jobs = jobsOf(body);\n emit(() => {\n if (jobs.length === 0) note(`No cron jobs are scheduled on ${target.label}.`);\n for (const job of jobs) printJob(job);\n if (isRecord(body) && typeof body.note === \"string\") note(chalk.yellow(body.note));\n }, body);\n}\n\nexport const CRON_GET_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nasync function getJob(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: CRON_GET_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"cron get\",\n maxPositionals: 1\n }));\n const id = parsedLine(() => requireJobId(positionals, \"cron get\"));\n const target = await projectTarget(flags, { command: \"cron get\", platformScopes: [\"cron:read\"] });\n const body = await requestJson(target, `${CRON_PATH}/${encodeURIComponent(id)}`, `Failed to read cron job ${id}`);\n const job = jobOf(body);\n emit(() => (job ? printJob(job) : console.log(JSON.stringify(body, null, 2))), job ?? body);\n}\n\nexport const CRON_LOGS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--limit\": Number,\n \"-n\": \"--limit\"\n} satisfies arg.Spec;\n\nasync function jobLogs(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: CRON_LOGS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"cron logs\",\n maxPositionals: 1\n }));\n const id = parsedLine(() => {\n const job = requireJobId(positionals, \"cron logs\");\n const limit = flags[\"--limit\"];\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) throw new UsageError(\"--limit takes a positive whole number.\");\n return job;\n });\n const target = await projectTarget(flags, { command: \"cron logs\", platformScopes: [\"cron:read\"] });\n const body = await requestJson(target, `${CRON_PATH}/${encodeURIComponent(id)}/logs`, `Failed to read the runs of ${id}`, {\n query: { limit: flags[\"--limit\"]?.toString() }\n });\n const logs = isRecord(body) && Array.isArray(body.logs) ? body.logs.filter(isLogEntry) : [];\n emit(() => {\n if (logs.length === 0) return note(`${id} has no recorded runs.`);\n for (const run of logs) {\n const mark = run.success ? chalk.green(\"✓\") : chalk.red(\"✗\");\n const tags = [shortDuration(run.durationMs), run.manual ? \"manual\" : undefined].filter(Boolean).join(\" \");\n console.log(` ${mark} ${shortTime(run.startedAt)} ${chalk.gray(tags)}`);\n if (run.error) console.log(chalk.red(` ${run.error}`));\n for (const line of run.logs ?? []) console.log(` ${line}`);\n }\n }, body);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n run / enable / disable / reset\n ═══════════════════════════════════════════════════════════════ */\n\nexport const CRON_RUN_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--async\": Boolean\n} satisfies arg.Spec;\n\nasync function runJob(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: CRON_RUN_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"cron run\",\n maxPositionals: 1\n }));\n const id = parsedLine(() => requireJobId(positionals, \"cron run\"));\n const target = await projectTarget(flags, { command: \"cron run\", platformScopes: [\"cron:write\"] });\n // A run is not undoable — it sends the emails, charges the cards, prunes\n // the rows its code says to — so it says what it is about to do and waits.\n await confirmDestructive({ yes: flags[\"--yes\"] === true, prompt: `Run cron job ${id} now on ${target.label}?` });\n const body = await requestJson(target, `${CRON_PATH}/${encodeURIComponent(id)}/trigger`, `Failed to run ${id}`, {\n method: \"POST\",\n query: flags[\"--async\"] ? { async: \"1\" } : undefined,\n // A synchronous run lasts as long as the job does.\n timeoutMs: flags[\"--async\"] ? 60_000 : 15 * 60_000\n });\n const log = isRecord(body) && isLogEntry(body.log) ? body.log : undefined;\n emit(() => {\n if (flags[\"--async\"]) return success(`Started ${id}; \\`rebase cron logs ${id}\\` shows how it ends.`);\n if (log && !log.success) {\n console.log(chalk.red(` ✗ ${id} failed after ${shortDuration(log.durationMs)}: ${log.error ?? \"no message\"}`));\n for (const line of log.logs ?? []) console.log(` ${line}`);\n process.exitCode = 1;\n return;\n }\n success(`Ran ${id}${log ? ` in ${shortDuration(log.durationMs)}` : \"\"}.`);\n for (const line of log?.logs ?? []) console.log(` ${line}`);\n }, body);\n if (log && !log.success) process.exitCode = 1;\n}\n\nexport const CRON_SWITCH_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\n/**\n * `enable` and `disable` override the job's code for every process, across\n * redeploys; `reset` drops the override, so the code decides again.\n */\nasync function switchJob(rawArgs: string[], how: \"enable\" | \"disable\" | \"reset\"): Promise<void> {\n const command = `cron ${how}`;\n // One literal call per action: the help and parse guards read the command\n // name out of each call.\n const parse = {\n enable: () => parseCommandArgs({ spec: CRON_SWITCH_FLAGS, rawArgs, commandWords: 2, command: \"cron enable\", maxPositionals: 1 }),\n disable: () => parseCommandArgs({ spec: CRON_SWITCH_FLAGS, rawArgs, commandWords: 2, command: \"cron disable\", maxPositionals: 1 }),\n reset: () => parseCommandArgs({ spec: CRON_SWITCH_FLAGS, rawArgs, commandWords: 2, command: \"cron reset\", maxPositionals: 1 })\n }[how];\n const { flags, positionals } = parsedLine(parse);\n const id = parsedLine(() => requireJobId(positionals, command));\n const target = await projectTarget(flags, { command, platformScopes: [\"cron:write\"] });\n if (how === \"disable\") {\n // Silently stopping a scheduled backup is the failure this prompt is for.\n await confirmDestructive({ yes: flags[\"--yes\"] === true, prompt: `Switch off cron job ${id} on ${target.label}, until it is enabled again?` });\n }\n const enabled = how === \"enable\" ? true : how === \"disable\" ? false : null;\n const body = await requestJson(target, `${CRON_PATH}/${encodeURIComponent(id)}`, `Failed to ${how} ${id}`, {\n method: \"PUT\",\n json: { enabled }\n });\n const job = jobOf(body);\n emit(() => {\n success(how === \"reset\" ? `${id} follows its code again.` : `${id} is ${how === \"enable\" ? \"on\" : \"off\"}.`);\n if (job) printJob(job);\n }, body);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Help\n ═══════════════════════════════════════════════════════════════ */\n\nexport const CRON_ACTIONS: HelpAction[] = [\n { action: \"list\", description: \"The scheduled jobs: schedule, state, last and next run (the default)\" },\n { action: \"get\", args: \"<job>\", description: \"One job\" },\n { action: \"logs\", args: \"<job>\", description: \"A job's run history, newest first\", flags: [[\"--limit, -n <n>\", \"At most this many runs\"]] },\n { action: \"run\", args: \"<job>\", description: \"Run a job now (confirms)\", flags: [[\"--async\", \"Answer once it has started; `logs` shows how it ends\"]] },\n { action: \"enable\", args: \"<job>\", description: \"Switch a job on for every process, across redeploys\" },\n { action: \"disable\", args: \"<job>\", description: \"Switch a job off (confirms)\" },\n { action: \"reset\", args: \"<job>\", description: \"Drop the on/off override: the job's code decides again\" }\n];\n\nfunction printCronHelp(): void {\n printProjectHelp({\n command: \"cron\",\n title: \"A running app's scheduled jobs: list, history, run now, switch off\",\n actions: CRON_ACTIONS,\n notes: [\n \"On a Rebase Cloud project, reads need log access and run/enable/disable/reset need an organization owner or admin with Studio switched on.\",\n \"Examples:\",\n \" rebase cron run cleanup-sessions --yes\",\n \" rebase cron logs nightly-backup -n 5 --project acme\"\n ]\n });\n}\n"],"mappings":";;;;;;;;AAmCA,IAAa,mBAAmB;CAAC;CAAQ;CAAO;CAAQ;CAAO;CAAU;CAAW;AAAO;AAE3F,IAAM,YAAY;AAElB,eAAsB,YAAY,YAAgC,SAAkC;CAChG,oBAAoB,OAAO;CAC3B,IAAI,eAAe,YAAY,UAAU,OAAO,GAAG;EAC/C,cAAc;EACd;CACJ;CACA,QAAQ,cAAc,QAAtB;EACI,KAAK;GACD,MAAM,SAAS,OAAO;GACtB;EACJ,KAAK;GACD,MAAM,OAAO,OAAO;GACpB;EACJ,KAAK;GACD,MAAM,QAAQ,OAAO;GACrB;EACJ,KAAK;GACD,MAAM,OAAO,OAAO;GACpB;EACJ,KAAK;GACD,MAAM,UAAU,SAAS,QAAQ;GACjC;EACJ,KAAK;GACD,MAAM,UAAU,SAAS,SAAS;GAClC;EACJ,KAAK;GACD,MAAM,UAAU,SAAS,OAAO;GAChC;EACJ,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WAAW,OAAO,MAAM,EAAE;EAC1G,IAAI,KAAK,SAAS,GAAG;CACzB,GAAG,IAAI;AACX;AAMA,IAAa,eAA6B;CACtC;EAAE,QAAQ;EAAQ,aAAa;CAAuE;CACtG;EAAE,QAAQ;EAAO,MAAM;EAAS,aAAa;CAAU;CACvD;EAAE,QAAQ;EAAQ,MAAM;EAAS,aAAa;EAAqC,OAAO,CAAC,CAAC,mBAAmB,wBAAwB,CAAC;CAAE;CAC1I;EAAE,QAAQ;EAAO,MAAM;EAAS,aAAa;EAA4B,OAAO,CAAC,CAAC,WAAW,sDAAsD,CAAC;CAAE;CACtJ;EAAE,QAAQ;EAAU,MAAM;EAAS,aAAa;CAAsD;CACtG;EAAE,QAAQ;EAAW,MAAM;EAAS,aAAa;CAA8B;CAC/E;EAAE,QAAQ;EAAS,MAAM;EAAS,aAAa;CAAyD;AAC5G;AAEA,SAAS,gBAAsB;CAC3B,iBAAiB;EACb,SAAS;EACT,OAAO;EACP,SAAS;EACT,OAAO;GACH;GACA;GACA;GACA;EACJ;CACJ,CAAC;AACL"}
1
+ {"version":3,"file":"cron-DuZ3Svjq.js","names":[],"sources":["../src/commands/cron.ts"],"sourcesContent":["/**\n * CLI command: rebase cron <action>\n *\n * A running app's scheduled jobs (`backend/crons/*`): list them, read a job's\n * run history, run one now, switch one off or back on. Through the app's\n * `/api/admin/cron` surface, with the target every project command resolves.\n *\n * On a Rebase Cloud project (`--project`, `--cloud`) this needs no Studio\n * access: reads ask the control plane for a short `cron:read` platform token,\n * which any member who may read the project's logs holds, and runs or\n * switches ask for `cron:write`, which an organization owner or admin holds on\n * a project whose Studio switch is on. Nothing long-lived is kept.\n * `rebase cloud cron` is the older, read-only spelling of `list` and `logs`.\n */\nimport type arg from \"arg\";\nimport chalk from \"chalk\";\nimport type { CronJobLogEntry, CronJobStatus } from \"@rebasepro/types\";\n\nimport { parseCommandArgs, UsageError, wantsHelp } from \"../utils/args\";\nimport { unknownCommand } from \"../utils/unknown-command\";\nimport { PROJECT_TARGET_FLAGS } from \"../utils/project-target\";\nimport {\n emit,\n isRecord,\n parsedLine,\n printProjectHelp,\n projectTarget,\n requestJson,\n startProjectCommand,\n type HelpAction\n} from \"../utils/project-command\";\nimport { confirmDestructive, note, success } from \"./cloud/context\";\nimport { shortDuration, shortTime } from \"./cloud/cron\";\n\n/** Everything the switch below dispatches, for the did-you-mean. */\nexport const CRON_SUBCOMMANDS = [\"list\", \"get\", \"logs\", \"run\", \"enable\", \"disable\", \"reset\"] as const;\n\nconst CRON_PATH = \"/api/admin/cron\";\n\nexport async function cronCommand(subcommand: string | undefined, rawArgs: string[]): Promise<void> {\n startProjectCommand(rawArgs);\n if (subcommand === \"--help\" || wantsHelp(rawArgs)) {\n printCronHelp();\n return;\n }\n switch (subcommand ?? \"list\") {\n case \"list\":\n await listJobs(rawArgs);\n break;\n case \"get\":\n await getJob(rawArgs);\n break;\n case \"logs\":\n await jobLogs(rawArgs);\n break;\n case \"run\":\n await runJob(rawArgs);\n break;\n case \"enable\":\n await switchJob(rawArgs, \"enable\");\n break;\n case \"disable\":\n await switchJob(rawArgs, \"disable\");\n break;\n case \"reset\":\n await switchJob(rawArgs, \"reset\");\n break;\n default:\n unknownCommand(subcommand, CRON_SUBCOMMANDS, \"cron\");\n }\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Reading a job\n ═══════════════════════════════════════════════════════════════ */\n\nfunction isJob(value: unknown): value is CronJobStatus {\n return isRecord(value) && typeof value.id === \"string\" && typeof value.schedule === \"string\";\n}\n\nfunction jobsOf(body: unknown): CronJobStatus[] {\n return isRecord(body) && Array.isArray(body.jobs) ? body.jobs.filter(isJob) : [];\n}\n\nfunction jobOf(body: unknown): CronJobStatus | undefined {\n if (isRecord(body) && isJob(body.job)) return body.job;\n return isJob(body) ? body : undefined;\n}\n\nfunction isLogEntry(value: unknown): value is CronJobLogEntry {\n return isRecord(value) && typeof value.startedAt === \"string\";\n}\n\nfunction stateColor(state: string): string {\n if (state === \"error\") return chalk.red(state);\n if (state === \"running\") return chalk.cyan(state);\n if (state === \"disabled\") return chalk.gray(state);\n return chalk.green(state);\n}\n\nfunction printJob(job: CronJobStatus): void {\n console.log(` ${chalk.bold(job.id)} ${job.schedule} ${stateColor(job.state)}${job.enabled ? \"\" : chalk.gray(\" (off)\")}`);\n if (job.description) console.log(chalk.gray(` ${job.description}`));\n const last = job.lastRunAt ? `${shortTime(job.lastRunAt)} ${chalk.gray(shortDuration(job.lastDurationMs))}` : chalk.gray(\"never\");\n console.log(chalk.gray(\" last \") + last + chalk.gray(\" next \") + shortTime(job.nextRunAt));\n if (job.state === \"error\" && job.lastError) console.log(chalk.red(` ${job.lastError}`));\n}\n\nfunction requireJobId(positionals: string[], command: string): string {\n if (!positionals[0]) throw new UsageError(`rebase ${command} needs a job id: rebase ${command} <job> (\\`rebase cron list\\` names them).`);\n return positionals[0];\n}\n\n/* ═══════════════════════════════════════════════════════════════\n list / get / logs\n ═══════════════════════════════════════════════════════════════ */\n\nexport const CRON_LIST_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nasync function listJobs(rawArgs: string[]): Promise<void> {\n const { flags } = parsedLine(() => parseCommandArgs({\n spec: CRON_LIST_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"cron list\",\n maxPositionals: 0\n }));\n const target = await projectTarget(flags, { command: \"cron list\", platformScopes: [\"cron:read\"] });\n const body = await requestJson(target, CRON_PATH, \"Failed to list cron jobs\");\n const jobs = jobsOf(body);\n emit(() => {\n if (jobs.length === 0) note(`No cron jobs are scheduled on ${target.label}.`);\n for (const job of jobs) printJob(job);\n if (isRecord(body) && typeof body.note === \"string\") note(chalk.yellow(body.note));\n }, body);\n}\n\nexport const CRON_GET_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\nasync function getJob(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: CRON_GET_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"cron get\",\n maxPositionals: 1\n }));\n const id = parsedLine(() => requireJobId(positionals, \"cron get\"));\n const target = await projectTarget(flags, { command: \"cron get\", platformScopes: [\"cron:read\"] });\n const body = await requestJson(target, `${CRON_PATH}/${encodeURIComponent(id)}`, `Failed to read cron job ${id}`);\n const job = jobOf(body);\n emit(() => (job ? printJob(job) : console.log(JSON.stringify(body, null, 2))), job ?? body);\n}\n\nexport const CRON_LOGS_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--limit\": Number,\n \"-n\": \"--limit\"\n} satisfies arg.Spec;\n\nasync function jobLogs(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: CRON_LOGS_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"cron logs\",\n maxPositionals: 1\n }));\n const id = parsedLine(() => {\n const job = requireJobId(positionals, \"cron logs\");\n const limit = flags[\"--limit\"];\n if (limit !== undefined && (!Number.isInteger(limit) || limit < 1)) throw new UsageError(\"--limit takes a positive whole number.\");\n return job;\n });\n const target = await projectTarget(flags, { command: \"cron logs\", platformScopes: [\"cron:read\"] });\n const body = await requestJson(target, `${CRON_PATH}/${encodeURIComponent(id)}/logs`, `Failed to read the runs of ${id}`, {\n query: { limit: flags[\"--limit\"]?.toString() }\n });\n const logs = isRecord(body) && Array.isArray(body.logs) ? body.logs.filter(isLogEntry) : [];\n emit(() => {\n if (logs.length === 0) return note(`${id} has no recorded runs.`);\n for (const run of logs) {\n const mark = run.success ? chalk.green(\"✓\") : chalk.red(\"✗\");\n const tags = [shortDuration(run.durationMs), run.manual ? \"manual\" : undefined].filter(Boolean).join(\" \");\n console.log(` ${mark} ${shortTime(run.startedAt)} ${chalk.gray(tags)}`);\n if (run.error) console.log(chalk.red(` ${run.error}`));\n for (const line of run.logs ?? []) console.log(` ${line}`);\n }\n }, body);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n run / enable / disable / reset\n ═══════════════════════════════════════════════════════════════ */\n\nexport const CRON_RUN_FLAGS = {\n ...PROJECT_TARGET_FLAGS,\n \"--async\": Boolean\n} satisfies arg.Spec;\n\nasync function runJob(rawArgs: string[]): Promise<void> {\n const { flags, positionals } = parsedLine(() => parseCommandArgs({\n spec: CRON_RUN_FLAGS,\n rawArgs,\n commandWords: 2,\n command: \"cron run\",\n maxPositionals: 1\n }));\n const id = parsedLine(() => requireJobId(positionals, \"cron run\"));\n const target = await projectTarget(flags, { command: \"cron run\", platformScopes: [\"cron:write\"] });\n // A run is not undoable — it sends the emails, charges the cards, prunes\n // the rows its code says to — so it says what it is about to do and waits.\n await confirmDestructive({ yes: flags[\"--yes\"] === true, prompt: `Run cron job ${id} now on ${target.label}?` });\n const body = await requestJson(target, `${CRON_PATH}/${encodeURIComponent(id)}/trigger`, `Failed to run ${id}`, {\n method: \"POST\",\n query: flags[\"--async\"] ? { async: \"1\" } : undefined,\n // A synchronous run lasts as long as the job does.\n timeoutMs: flags[\"--async\"] ? 60_000 : 15 * 60_000\n });\n const log = isRecord(body) && isLogEntry(body.log) ? body.log : undefined;\n emit(() => {\n if (flags[\"--async\"]) return success(`Started ${id}; \\`rebase cron logs ${id}\\` shows how it ends.`);\n if (log && !log.success) {\n console.log(chalk.red(` ✗ ${id} failed after ${shortDuration(log.durationMs)}: ${log.error ?? \"no message\"}`));\n for (const line of log.logs ?? []) console.log(` ${line}`);\n process.exitCode = 1;\n return;\n }\n success(`Ran ${id}${log ? ` in ${shortDuration(log.durationMs)}` : \"\"}.`);\n for (const line of log?.logs ?? []) console.log(` ${line}`);\n }, body);\n if (log && !log.success) process.exitCode = 1;\n}\n\nexport const CRON_SWITCH_FLAGS = { ...PROJECT_TARGET_FLAGS } satisfies arg.Spec;\n\n/**\n * `enable` and `disable` override the job's code for every process, across\n * redeploys; `reset` drops the override, so the code decides again.\n */\nasync function switchJob(rawArgs: string[], how: \"enable\" | \"disable\" | \"reset\"): Promise<void> {\n const command = `cron ${how}`;\n // One literal call per action: the help and parse guards read the command\n // name out of each call.\n const parse = {\n enable: () => parseCommandArgs({ spec: CRON_SWITCH_FLAGS, rawArgs, commandWords: 2, command: \"cron enable\", maxPositionals: 1 }),\n disable: () => parseCommandArgs({ spec: CRON_SWITCH_FLAGS, rawArgs, commandWords: 2, command: \"cron disable\", maxPositionals: 1 }),\n reset: () => parseCommandArgs({ spec: CRON_SWITCH_FLAGS, rawArgs, commandWords: 2, command: \"cron reset\", maxPositionals: 1 })\n }[how];\n const { flags, positionals } = parsedLine(parse);\n const id = parsedLine(() => requireJobId(positionals, command));\n const target = await projectTarget(flags, { command, platformScopes: [\"cron:write\"] });\n if (how === \"disable\") {\n // Silently stopping a scheduled backup is the failure this prompt is for.\n await confirmDestructive({ yes: flags[\"--yes\"] === true, prompt: `Switch off cron job ${id} on ${target.label}, until it is enabled again?` });\n }\n const enabled = how === \"enable\" ? true : how === \"disable\" ? false : null;\n const body = await requestJson(target, `${CRON_PATH}/${encodeURIComponent(id)}`, `Failed to ${how} ${id}`, {\n method: \"PUT\",\n json: { enabled }\n });\n const job = jobOf(body);\n emit(() => {\n success(how === \"reset\" ? `${id} follows its code again.` : `${id} is ${how === \"enable\" ? \"on\" : \"off\"}.`);\n if (job) printJob(job);\n }, body);\n}\n\n/* ═══════════════════════════════════════════════════════════════\n Help\n ═══════════════════════════════════════════════════════════════ */\n\nexport const CRON_ACTIONS: HelpAction[] = [\n { action: \"list\", description: \"The scheduled jobs: schedule, state, last and next run (the default)\" },\n { action: \"get\", args: \"<job>\", description: \"One job\" },\n { action: \"logs\", args: \"<job>\", description: \"A job's run history, newest first\", flags: [[\"--limit, -n <n>\", \"At most this many runs\"]] },\n { action: \"run\", args: \"<job>\", description: \"Run a job now (confirms)\", flags: [[\"--async\", \"Answer once it has started; `logs` shows how it ends\"]] },\n { action: \"enable\", args: \"<job>\", description: \"Switch a job on for every process, across redeploys\" },\n { action: \"disable\", args: \"<job>\", description: \"Switch a job off (confirms)\" },\n { action: \"reset\", args: \"<job>\", description: \"Drop the on/off override: the job's code decides again\" }\n];\n\nfunction printCronHelp(): void {\n printProjectHelp({\n command: \"cron\",\n title: \"A running app's scheduled jobs: list, history, run now, switch off\",\n actions: CRON_ACTIONS,\n notes: [\n \"On a Rebase Cloud project, reads need log access and run/enable/disable/reset need an organization owner or admin with Studio switched on.\",\n \"Examples:\",\n \" rebase cron run cleanup-sessions --yes\",\n \" rebase cron logs nightly-backup -n 5 --project acme\"\n ]\n });\n}\n"],"mappings":";;;;;;;;AAmCA,IAAa,mBAAmB;CAAC;CAAQ;CAAO;CAAQ;CAAO;CAAU;CAAW;AAAO;AAE3F,IAAM,YAAY;AAElB,eAAsB,YAAY,YAAgC,SAAkC;CAChG,oBAAoB,OAAO;CAC3B,IAAI,eAAe,YAAY,UAAU,OAAO,GAAG;EAC/C,cAAc;EACd;CACJ;CACA,QAAQ,cAAc,QAAtB;EACI,KAAK;GACD,MAAM,SAAS,OAAO;GACtB;EACJ,KAAK;GACD,MAAM,OAAO,OAAO;GACpB;EACJ,KAAK;GACD,MAAM,QAAQ,OAAO;GACrB;EACJ,KAAK;GACD,MAAM,OAAO,OAAO;GACpB;EACJ,KAAK;GACD,MAAM,UAAU,SAAS,QAAQ;GACjC;EACJ,KAAK;GACD,MAAM,UAAU,SAAS,SAAS;GAClC;EACJ,KAAK;GACD,MAAM,UAAU,SAAS,OAAO;GAChC;EACJ,SACI,eAAe,YAAY,kBAAkB,MAAM;CAC3D;AACJ;AAMA,SAAS,MAAM,OAAwC;CACnD,OAAO,SAAS,KAAK,KAAK,OAAO,MAAM,OAAO,YAAY,OAAO,MAAM,aAAa;AACxF;AAEA,SAAS,OAAO,MAAgC;CAC5C,OAAO,SAAS,IAAI,KAAK,MAAM,QAAQ,KAAK,IAAI,IAAI,KAAK,KAAK,OAAO,KAAK,IAAI,CAAC;AACnF;AAEA,SAAS,MAAM,MAA0C;CACrD,IAAI,SAAS,IAAI,KAAK,MAAM,KAAK,GAAG,GAAG,OAAO,KAAK;CACnD,OAAO,MAAM,IAAI,IAAI,OA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EAAU,MAAM;EAAS,aAAa;CAAsD;CACtG;EAAE,QAAQ;EAAW,MAAM;EAAS,aAAa;CAA8B;CAC/E;EAAE,QAAQ;EAAS,MAAM;EAAS,aAAa;CAAyD;AAC5G;AAEA,SAAS,gBAAsB;CAC3B,iBAAiB;EACb,SAAS;EACT,OAAO;EACP,SAAS;EACT,OAAO;GACH;GACA;GACA;GACA;EACJ;CACJ,CAAC;AACL"}
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
2
2
  import { n as cliVersion } from "./version-ONIeo7jl.js";
3
- import { i as runningBackendUrl } from "./dev-server-2XHSHM_q.js";
3
+ import { i as runningBackendUrl } from "./dev-server-dsabI0UT.js";
4
4
  import { a as dataDir, c as pidRunning, d as releaseStartLock, f as stateFile, i as clearState, l as readState, o as devDbDir, r as chooseManagedPort, t as acquireStartLock } from "./state-CYdBvnwA.js";
5
5
  import fs from "fs";
6
6
  import path from "path";
@@ -526,4 +526,4 @@ function ensureGitignore(projectRoot) {
526
526
  //#endregion
527
527
  export { resolveCliEntry as a, managedUrl as i, ensureManagedDatabase as n, resolveSpawn as o, findRunningDaemon as r, daemon_exports as t };
528
528
 
529
- //# sourceMappingURL=daemon-D5gdG7gx.js.map
529
+ //# sourceMappingURL=daemon-BCBMn8hE.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"daemon-D5gdG7gx.js","names":[],"sources":["../src/dev-db/daemon.ts"],"sourcesContent":["/**\n * Starting, finding and stopping the managed database, from the caller's side.\n *\n * Every command that needs Postgres calls {@link ensureManagedDatabase} and\n * gets a connection string back. Whether that started a process or found one\n * already running is not the caller's business, which is the point: `rebase\n * db push`, `rebase dev` and `rebase studio` in three terminals must all reach\n * the same database without coordinating, because two processes opening one\n * PGlite data directory would corrupt it.\n *\n * The hard part is not starting the daemon; it is deciding whether the one the\n * state file describes is still there. A pid can be recycled after a reboot and\n * a port can be taken by a stranger, so believing either on its own would let\n * Rebase send a migration somewhere unintended. {@link isDaemonAlive} asks the\n * daemon to identify itself instead.\n */\n\nimport { randomBytes } from \"crypto\";\nimport { type ChildProcess, execFile, spawn } from \"child_process\";\nimport fs from \"fs\";\nimport net from \"net\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nimport { runningBackendUrl } from \"../utils/dev-server\";\nimport { cliVersion } from \"../utils/version\";\nimport {\n acquireStartLock,\n chooseManagedPort,\n clearState,\n type DaemonState,\n dataDir,\n devDbDir,\n pidRunning,\n readState,\n releaseStartLock,\n stateFile\n} from \"./state\";\n\n/** How long to wait for a first boot. PGlite runs initdb on an empty data dir. */\nconst START_TIMEOUT_MS = 60_000;\n/** Poll interval while waiting for the daemon to publish its state file. */\nconst POLL_INTERVAL_MS = 150;\n/** How long the identity handshake may take before we call it dead. */\nconst IDENTITY_TIMEOUT_MS = 1_500;\n\nexport interface ManagedDatabase {\n /** Connection string for this project's managed database. */\n url: string;\n /** Where the data lives, for diagnostics and `--reset`. */\n dataDir: string;\n port: number;\n pid: number;\n /** True when this call started the daemon rather than finding it. */\n started: boolean;\n /**\n * Connection strings for the additional databases the caller asked for,\n * by declared key — `database(\"analytics\")` → `analytics`. Each is its\n * own PGlite instance behind the same daemon.\n */\n additional: Record<string, string>;\n}\n\n/**\n * PGlite's built-in superuser and database.\n *\n * Fixed by PGlite rather than chosen here, and asserted by the socket spike:\n * `session_user` comes back as `postgres`.\n */\nconst MANAGED_USER = \"postgres\";\nconst MANAGED_DATABASE = \"postgres\";\n\n/**\n * The DSN for the managed development database.\n *\n * **`sslmode=disable` is not decoration.** PGlite's socket server speaks no TLS,\n * and libpq-family clients try SSL first — so Atlas, which `rebase db push`\n * shells out to, failed the whole push with\n * `pq: SSL is not enabled on the server`. Its remedy box then told the reader to\n * append `sslmode=disable` to `DATABASE_URL`, which on this path is not set at\n * all: `rebase init` leaves it commented out precisely so the managed database\n * is used. The advice was correct and unfollowable.\n *\n * Putting it in the URL fixes every consumer at once — Atlas, `pg`, and anything\n * a driver shells out to later — rather than teaching each one about PGlite.\n */\n\n/**\n * The end of `pglite.log`, for an error message that has to carry its own reason.\n *\n * The daemon writes its output to a file because it is detached — it has to\n * outlive the command that started it. That is right, and it means every\n * startup failure used to be reported as a path: \"see pglite.log for the\n * reason\". On a laptop that is a fair trade. In CI it is not a trade at all,\n * because the runner discards the workspace: the log named in the message no\n * longer exists by the time anybody reads the message, so a failed run says\n * only that something failed.\n *\n * So the tail comes with the error. Bounded, because a log that has been\n * appended to across many runs is not something to paste in full.\n */\nexport function pgliteLogTail(projectRoot: string, lines = 12): string {\n try {\n const contents = fs.readFileSync(path.join(devDbDir(projectRoot), \"pglite.log\"), \"utf8\").trimEnd();\n if (!contents) return \" (pglite.log is empty — the daemon wrote nothing before exiting)\";\n return contents.split(\"\\n\").slice(-lines).map(line => ` ${line}`).join(\"\\n\");\n } catch {\n return \" (pglite.log could not be read)\";\n }\n}\n\nexport function managedUrl(port: number): string {\n return `postgresql://${MANAGED_USER}@127.0.0.1:${port}/${MANAGED_DATABASE}?sslmode=disable`;\n}\n\n/**\n * Ask the process behind a state record to prove it is the one we wrote down.\n *\n * A pid check alone answers \"is *a* process running\", and a port check alone\n * answers \"is *something* listening\" — after a reboot both say yes about\n * strangers. The daemon answers with the token from its own state file, so a\n * match is the only evidence accepted.\n */\nexport function isDaemonAlive(state: DaemonState): Promise<boolean> {\n if (!pidRunning(state.pid)) return Promise.resolve(false);\n\n return new Promise((resolve) => {\n const socket = new net.Socket();\n let answer = \"\";\n const settle = (alive: boolean) => {\n socket.removeAllListeners();\n socket.destroy();\n resolve(alive);\n };\n socket.setTimeout(IDENTITY_TIMEOUT_MS);\n socket.once(\"timeout\", () => settle(false));\n socket.once(\"error\", () => settle(false));\n socket.on(\"data\", (chunk) => {\n answer += chunk.toString(\"utf8\");\n if (answer.includes(\"\\n\")) settle(answer.trim() === `rebase-dev-db ${state.token}`);\n });\n socket.once(\"close\", () => settle(answer.trim() === `rebase-dev-db ${state.token}`));\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/**\n * Whether a daemon `started` by one CLI should give way to the CLI `running` now.\n *\n * The database proxy runs inside the daemon, and the daemon outlives every\n * command — so the proxy a project gets is whichever CLI started the daemon\n * last, not the one it upgraded to. True for a daemon from before daemons were\n * stamped, for an older release, and for another build of the same release\n * (two canaries, a canary and its release): canary hashes do not sort by date,\n * and this CLI's proxy is the one it can vouch for. False for a newer release,\n * which an older CLI leaves alone, and when this CLI cannot read its own\n * version.\n */\nexport function daemonOutdated(started: string | undefined, running: string): boolean {\n const core = (version: string): number[] | null => {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n return match ? match.slice(1, 4).map(Number) : null;\n };\n const ours = core(running);\n if (!ours || started === running) return false;\n const theirs = started === undefined ? null : core(started);\n if (!theirs) return true;\n for (let i = 0; i < 3; i++) {\n if (theirs[i] !== ours[i]) return theirs[i] < ours[i];\n }\n return true;\n}\n\n/**\n * Send the daemon one command over its identity socket, and get the reply line.\n *\n * `null` for anything that is not the daemon answering: no connection, another\n * token, no reply in time. The identity line comes first, so a stranger on a\n * recycled port is never mistaken for it.\n */\nfunction askDaemon(state: DaemonState, command: string, timeoutMs = IDENTITY_TIMEOUT_MS): Promise<string | null> {\n return new Promise((resolve) => {\n const socket = new net.Socket();\n let buffered = \"\";\n let identified = false;\n const settle = (reply: string | null) => {\n socket.removeAllListeners();\n socket.destroy();\n resolve(reply);\n };\n socket.setTimeout(timeoutMs);\n socket.once(\"timeout\", () => settle(null));\n socket.once(\"error\", () => settle(null));\n socket.once(\"close\", () => settle(null));\n socket.on(\"data\", (chunk) => {\n buffered += chunk.toString(\"utf8\");\n let newline = buffered.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = buffered.slice(0, newline).trim();\n buffered = buffered.slice(newline + 1);\n if (identified) return settle(line);\n if (line !== `rebase-dev-db ${state.token}`) return settle(null);\n identified = true;\n socket.write(`${command}\\n`);\n newline = buffered.indexOf(\"\\n\");\n }\n });\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/**\n * How many of `lsof -Fn`'s sockets are connections accepted on `ports`.\n *\n * Each socket is a line `n<local>-><remote>`. The daemon's accepted client\n * connections have one of its public ports on the local side; its own\n * connections to the socket server behind the proxy are on other ports.\n */\nexport function acceptedConnections(lsofOutput: string, ports: readonly number[]): number {\n let count = 0;\n for (const line of lsofOutput.split(\"\\n\")) {\n if (!line.startsWith(\"n\") || !line.includes(\"->\")) continue;\n const local = line.slice(1, line.indexOf(\"->\"));\n if (ports.includes(Number(local.slice(local.lastIndexOf(\":\") + 1)))) count++;\n }\n return count;\n}\n\n/**\n * The connections the operating system says the daemon has accepted, or `null`\n * when it cannot be asked.\n *\n * For a daemon from before the `clients` command: it cannot be asked itself.\n * `lsof` ships with macOS and most Linux installs; where it is missing, the\n * answer is \"cannot tell\", and the caller does not restart anything.\n */\nfunction osAcceptedConnections(state: DaemonState): Promise<number | null> {\n const ports = [state.port, ...Object.values(state.databases ?? {}).map(database => database.port)];\n return new Promise((resolve) => {\n execFile(\n \"lsof\",\n [\"-nP\", \"-a\", \"-p\", String(state.pid), `-iTCP:${ports.join(\",\")}`, \"-sTCP:ESTABLISHED\", \"-Fn\"],\n { timeout: 3_000 },\n (error, stdout) => {\n // lsof exits 1 when it finds nothing to list, which is an answer.\n if (error && !(error.code === 1 && stdout.trim() === \"\")) return resolve(null);\n resolve(acceptedConnections(stdout, ports));\n }\n );\n });\n}\n\n/**\n * How many clients are connected to the daemon, over all its databases, or\n * `null` when that cannot be known.\n *\n * Asked of the daemon first (`clients`). A daemon from before that command\n * answers `error unknown command`, and then the operating system is asked.\n */\nexport async function connectedClients(state: DaemonState): Promise<number | null> {\n const reply = await askDaemon(state, \"clients\");\n if (reply === null) return null;\n if (reply.startsWith(\"ok \")) {\n const count = Number(reply.slice(3));\n return Number.isInteger(count) && count >= 0 ? count : null;\n }\n return osAcceptedConnections(state);\n}\n\n/**\n * What to say about a daemon an older CLI started that cannot be restarted\n * here, because something is connected to it — or nothing can say whether\n * anything is.\n */\nexport function outdatedDaemonNotice(\n state: Pick<DaemonState, \"cliVersion\">,\n running: string,\n clients: number | null\n): string[] {\n const startedBy = state.cliVersion ? `Rebase CLI ${state.cliVersion}` : \"an earlier Rebase CLI\";\n const connected = clients === null\n ? \"this CLI cannot tell whether anything is connected to it\"\n : `${clients} client${clients === 1 ? \" is\" : \"s are\"} connected to it`;\n return [\n `⚠ The development database was started by ${startedBy}, and ${connected}, so it keeps running ` +\n `with that CLI's database proxy rather than this one's (${running}).`,\n \" Stop what uses it — `rebase dev`, `rebase console`, a database GUI — then run `rebase db stop`. \" +\n \"The next command starts it again, on this CLI. Data is kept.\"\n ];\n}\n\n/** Said once per daemon in a process: every command that needs the database asks again. */\nconst outdatedNoticeShown = new Set<string>();\n\n/**\n * Restart a daemon an older CLI started, when nothing is connected to it.\n *\n * Returns whether it was stopped — the caller then starts a fresh one. With a\n * client connected, stopping would cut it off mid-session, so it says once\n * what to do instead and leaves the daemon serving.\n */\nasync function giveWayToThisCli(projectRoot: string, state: DaemonState, options: EnsureOptions): Promise<boolean> {\n const running = cliVersion();\n if (!daemonOutdated(state.cliVersion, running)) return false;\n const clients = await connectedClients(state);\n if (clients === 0) {\n if (!options.quiet) {\n options.onProgress?.(\n `Restarting the development database: ${state.cliVersion ? `Rebase CLI ${state.cliVersion}` : \"an earlier Rebase CLI\"} ` +\n `started it, and this is ${running}. Data is kept.`\n );\n }\n return stopManagedDatabase(projectRoot);\n }\n const said = `${path.resolve(projectRoot)}\\0${state.pid}`;\n if (!outdatedNoticeShown.has(said)) {\n outdatedNoticeShown.add(said);\n (options.onNotice ?? ((line: string) => console.error(line)))(outdatedDaemonNotice(state, running, clients).join(\"\\n\"));\n }\n return false;\n}\n\n/** The running daemon for this project, or `null`. Never starts anything. */\nexport async function findRunningDaemon(projectRoot: string): Promise<DaemonState | null> {\n const state = readState(projectRoot);\n if (!state) return null;\n if (await isDaemonAlive(state)) return state;\n\n // The record describes something that is not there. Clearing it is the\n // whole recovery: the next ensure call starts a fresh daemon, and leaving\n // it would make every subsequent check pay the identity timeout.\n clearState(projectRoot);\n\n return null;\n}\n\n/**\n * Resolve the CLI entry point, so the daemon can be spawned as ourselves.\n *\n * A hidden subcommand rather than a second build entry: under `tsx` this file\n * is `src/dev-db/daemon.ts` and in a published CLI it is bundled into\n * `dist/index.js`, and in both cases the executable to re-invoke is the one\n * already running. `rebase dev` re-runs itself the same way to regenerate the\n * SDK types.\n */\nexport function resolveCliEntry(): string {\n // `process.argv[1]` is `bin/rebase.js` for a real invocation, which is\n // exactly what should be re-run. Under a test runner it is the runner, so\n // fall back to this module's own directory.\n const argvEntry = process.argv[1];\n if (argvEntry && fs.existsSync(argvEntry)) return argvEntry;\n\n return fileURLToPath(new URL(\"../index.js\", import.meta.url));\n}\n\n/**\n * How to re-invoke ourselves, which differs between a published CLI and this\n * repository.\n *\n * A published `rebase` is `node bin/rebase.js`, and re-running that is trivial.\n * Inside the monorepo the entry is TypeScript, which plain `node` cannot load —\n * so the daemon has to be started through the same loader that is running now.\n * Getting this wrong fails as a spawn that exits instantly with a syntax error,\n * which is why the caller reads `pglite.log` on failure.\n */\nexport function resolveSpawn(entry: string): { execPath: string; prefixArgs: string[] } {\n if (!/\\.[cm]?ts$/.test(entry)) return { execPath: process.execPath, prefixArgs: [] };\n\n // Node can load TypeScript when tsx is registered as an import hook. tsx is\n // already a dependency of this package, because `rebase dev` runs the\n // backend through it.\n return { execPath: process.execPath, prefixArgs: [\"--import\", \"tsx\"] };\n}\n\nexport interface EnsureOptions {\n /** Silence the \"starting…\" progress line. */\n quiet?: boolean;\n /** Milliseconds of inactivity before the daemon exits. 0 disables. */\n idleTimeoutMs?: number;\n /** Where progress goes. Injected for tests. */\n onProgress?: (message: string) => void;\n /** Override how the daemon process is launched. For tests. */\n spawn?: { execPath: string; prefixArgs: string[] };\n /**\n * Override the CLI entry to re-invoke. For tests.\n *\n * Necessary because under a test runner `process.argv[1]` is the runner\n * itself, which exists and is therefore accepted by {@link resolveCliEntry}\n * — spawning vitest with `__dev-db-daemon` rather than the CLI.\n */\n entry?: string;\n /**\n * Where the notice about a daemon an older CLI started goes, when it\n * cannot be restarted. stderr by default, so `rebase db url` keeps stdout\n * to the URL. Injected for tests.\n */\n onNotice?: (message: string) => void;\n /**\n * Keys of the additional databases the project declares, beyond the\n * default. Each is served by the daemon on request, so a project that\n * adds `database(\"analytics\")` while the daemon is running gets it\n * without a restart.\n */\n additionalKeys?: readonly string[];\n}\n\n/**\n * Ask the running daemon for one additional database, and get its port.\n *\n * The identity socket doubles as the command channel: the daemon answers\n * with its token first, which is how the caller knows it is talking to the\n * daemon the state file describes and not to a stranger on a recycled port.\n */\nfunction ensureAdditionalDatabase(state: DaemonState, key: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const socket = new net.Socket();\n let answer = \"\";\n let identified = false;\n const fail = (message: string) => {\n socket.removeAllListeners();\n socket.destroy();\n reject(new Error(message));\n };\n socket.setTimeout(START_TIMEOUT_MS);\n socket.once(\"timeout\", () => fail(`The development database did not answer for \"${key}\" within ${Math.round(START_TIMEOUT_MS / 1000)}s.`));\n socket.once(\"error\", (err) => fail(`Could not reach the development database for \"${key}\": ${err.message}`));\n socket.on(\"data\", (chunk) => {\n answer += chunk.toString(\"utf8\");\n let newline = answer.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = answer.slice(0, newline).trim();\n answer = answer.slice(newline + 1);\n if (!identified) {\n if (line !== `rebase-dev-db ${state.token}`) return fail(\"The process on the development database's port is not the daemon.\");\n identified = true;\n socket.write(`ensure ${key}\\n`);\n } else if (line.startsWith(\"ok \")) {\n const port = Number(line.slice(3));\n socket.removeAllListeners();\n socket.destroy();\n if (!Number.isInteger(port) || port <= 0) return reject(new Error(`The development database answered with an invalid port for \"${key}\": ${line}`));\n return resolve(port);\n } else {\n return fail(`The development database could not serve \"${key}\": ${line.replace(/^error\\s*/, \"\")}`);\n }\n newline = answer.indexOf(\"\\n\");\n }\n });\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/** Every additional database the caller asked for, as connection strings. */\nasync function adoptWithAdditional(state: DaemonState, started: boolean, keys: readonly string[]): Promise<ManagedDatabase> {\n const additional: Record<string, string> = {};\n for (const key of keys) {\n const known = state.databases?.[key];\n const port = known ? known.port : await ensureAdditionalDatabase(state, key);\n additional[key] = managedUrl(port);\n }\n return { ...adopt(state, started), additional };\n}\n\n/**\n * The project's managed database, started if it is not already running.\n *\n * Safe to call concurrently from several commands: the loser of the race finds\n * the winner's state file during its poll and adopts it rather than starting a\n * second daemon.\n */\nexport async function ensureManagedDatabase(\n projectRoot: string,\n options: EnsureOptions = {}\n): Promise<ManagedDatabase> {\n const keys = options.additionalKeys ?? [];\n const existing = await findRunningDaemon(projectRoot);\n // A daemon an older CLI started is restarted when nothing is connected to\n // it, so the upgrade reaches the proxy inside it. See `daemonOutdated`.\n if (existing && !(await giveWayToThisCli(projectRoot, existing, options))) {\n return adoptWithAdditional(existing, false, keys);\n }\n\n fs.mkdirSync(devDbDir(projectRoot), { recursive: true });\n ensureGitignore(projectRoot);\n\n // Exactly one process may spawn a daemon. Without this, `rebase dev` and\n // `rebase db push` started in the same second both see no state file, both\n // spawn, and two processes open one PGlite data directory — the corruption\n // the single-daemon design exists to prevent.\n if (!acquireStartLock(projectRoot, START_TIMEOUT_MS)) {\n const adopted = await waitForDaemon(projectRoot, START_TIMEOUT_MS);\n if (adopted) return adoptWithAdditional(adopted, false, keys);\n\n // The holder gave up or died without publishing. Falling through to\n // start one ourselves is better than failing: the lock is stale by now,\n // so the next acquire will break it.\n if (!acquireStartLock(projectRoot, 0)) {\n throw new Error(\n \"Another process is starting the development database and did not finish.\\n\" +\n ` Remove ${path.join(devDbDir(projectRoot), \"starting.lock\")} if nothing is running.`\n );\n }\n }\n\n // Where the last daemon listened, so a backend still holding that URL\n // reconnects to this one. See `chooseManagedPort`.\n const port = await chooseManagedPort(projectRoot);\n const token = randomBytes(16).toString(\"hex\");\n const entry = options.entry ?? resolveCliEntry();\n\n const spawnPlan = options.spawn ?? resolveSpawn(entry);\n const args = [\n ...spawnPlan.prefixArgs,\n entry,\n \"__dev-db-daemon\",\n \"--project\", projectRoot,\n \"--port\", String(port),\n \"--token\", token\n ];\n if (options.idleTimeoutMs !== undefined) {\n args.push(\"--idle-timeout\", String(options.idleTimeoutMs));\n }\n\n const log = fs.openSync(path.join(devDbDir(projectRoot), \"pglite.log\"), \"a\");\n const child: ChildProcess = spawn(spawnPlan.execPath, args, {\n // Detached with no stdin and its output on a file: the daemon must\n // survive the command that started it, and must not hold the terminal\n // open when that command exits.\n detached: true,\n stdio: [\"ignore\", log, log]\n });\n child.unref();\n\n try {\n const deadline = Date.now() + START_TIMEOUT_MS;\n let announced = false;\n while (Date.now() < deadline) {\n const state = readState(projectRoot);\n if (state && (await isDaemonAlive(state))) return adoptWithAdditional(state, true, keys);\n\n if (!announced && !options.quiet) {\n announced = true;\n options.onProgress?.(\"Starting the development database…\");\n }\n\n // A daemon that died on startup will never publish a state file, and\n // waiting the full minute for that is a bad way to learn it. The log\n // is the only place the reason exists.\n if (child.exitCode !== null && child.exitCode !== 0) {\n throw new Error(\n `The development database failed to start (exit ${child.exitCode}).\\n` +\n ` ${path.join(devDbDir(projectRoot), \"pglite.log\")} ends:\\n` +\n pgliteLogTail(projectRoot)\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n throw new Error(\n `The development database did not start within ${Math.round(START_TIMEOUT_MS / 1000)}s.\\n` +\n ` ${path.join(devDbDir(projectRoot), \"pglite.log\")} ends:\\n` +\n pgliteLogTail(projectRoot) + \"\\n\" +\n \" To use your own Postgres instead, set DATABASE_URL or pass --database-url.\"\n );\n } finally {\n // Released whether we succeeded, timed out or threw. A lock left behind\n // by a crash is broken by age, but only after a full timeout — which a\n // developer should never have to wait out.\n releaseStartLock(projectRoot);\n }\n}\n\n/** Shape a live state record as the caller's result. */\nfunction adopt(state: DaemonState, started: boolean): ManagedDatabase {\n return {\n url: managedUrl(state.port),\n dataDir: state.dataDir,\n port: state.port,\n pid: state.pid,\n started,\n additional: {}\n };\n}\n\n/** Poll until another process publishes a live daemon, or give up. */\nasync function waitForDaemon(projectRoot: string, timeoutMs: number): Promise<DaemonState | null> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const state = readState(projectRoot);\n if (state && (await isDaemonAlive(state))) return state;\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n return null;\n}\n\n/** Stop the daemon. Returns false when there was nothing running. */\nexport async function stopManagedDatabase(projectRoot: string): Promise<boolean> {\n const state = await findRunningDaemon(projectRoot);\n if (!state) return false;\n\n try {\n process.kill(state.pid, \"SIGTERM\");\n } catch {\n clearState(projectRoot);\n\n return false;\n }\n\n // Wait for it to clear its own state file, which is how it says it closed\n // the data directory cleanly. A hard kill here would risk the WAL.\n const deadline = Date.now() + 10_000;\n while (Date.now() < deadline) {\n if (!fs.existsSync(stateFile(projectRoot))) return true;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n clearState(projectRoot);\n\n return true;\n}\n\n/**\n * What `rebase db stop` says once the daemon is down: the headline, then any\n * detail.\n *\n * \"`rebase dev` will start it again\" was not true of a `rebase dev` that is\n * running: nothing in it watches the database, so its backend answered 503\n * until something else started one. The next command that needs it does, on\n * the port it had (`chooseManagedPort`), and the backend's pool reconnects to\n * that address by itself — so while a backend runs, that is what this says.\n */\nexport function stoppedManagedDatabaseLines(projectRoot: string): string[] {\n const backend = runningBackendUrl(projectRoot);\n if (!backend) {\n return [\"✓ Development database stopped. Data is kept — the next `rebase dev`, or any command that needs it, starts it again.\"];\n }\n return [\n \"✓ Development database stopped. Data is kept.\",\n ` The backend at ${backend} cannot reach it until it is back. The next command that needs it — \\`rebase db url\\`, for one — ` +\n \"starts it on the same port, and the backend reconnects.\"\n ];\n}\n\n/**\n * Stop the daemon and delete the data directory.\n *\n * Destructive and deliberately not clever: it removes the whole directory\n * rather than dropping schemas, because \"give me an empty database\" is the only\n * thing anyone means by it.\n */\nexport async function resetManagedDatabase(projectRoot: string): Promise<void> {\n await stopManagedDatabase(projectRoot);\n fs.rmSync(dataDir(projectRoot), { recursive: true, force: true });\n // Every additional database too: `pgdata__<key>` beside `pgdata`. \"Give\n // me an empty database\" means all of them — a reset that emptied the\n // default and kept the analytics rows would be a surprise on first read.\n const dir = devDbDir(projectRoot);\n if (fs.existsSync(dir)) {\n for (const entry of fs.readdirSync(dir)) {\n if (entry.startsWith(\"pgdata__\")) fs.rmSync(path.join(dir, entry), { recursive: true, force: true });\n }\n }\n clearState(projectRoot);\n}\n\n/**\n * Keep the generated directory out of git.\n *\n * `.rebase/` holds a Postgres data directory and a log. A project that commits\n * it will push hundreds of megabytes and a database that only makes sense on\n * one machine, so the ignore file is written next to the data rather than\n * relying on the project's root `.gitignore` having been updated.\n */\nfunction ensureGitignore(projectRoot: string): void {\n const target = path.join(devDbDir(projectRoot), \".gitignore\");\n if (fs.existsSync(target)) return;\n fs.writeFileSync(\n target,\n \"# Generated by `rebase dev` — a local Postgres data directory and its log.\\n\" +\n \"# Machine-specific and large; never commit it.\\n*\\n\",\n \"utf8\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAM,mBAAmB;;AAEzB,IAAM,mBAAmB;;AAEzB,IAAM,sBAAsB;;;;;;;AAyB5B,IAAM,eAAe;AACrB,IAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BzB,SAAgB,cAAc,aAAqB,QAAQ,IAAY;CACnE,IAAI;EACA,MAAM,WAAW,GAAG,aAAa,KAAK,KAAK,SAAS,WAAW,GAAG,YAAY,GAAG,MAAM,CAAC,CAAC,QAAQ;EACjG,IAAI,CAAC,UAAU,OAAO;EACtB,OAAO,SAAS,MAAM,IAAI,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,KAAI,SAAQ,SAAS,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M,kBAAkB,WAAW;CACjD,IAAI,CAAC,OAAO,OAAO;CAEnB,IAAI;EACA,QAAQ,KAAK,MAAM,KAAK,SAAS;CACrC,QAAQ;EACJ,WAAW,WAAW;EAEtB,OAAO;CACX;CAIA,MAAM,WAAW,KAAK,IAAI,IAAI;CAC9B,OAAO,KAAK,IAAI,IAAI,UAAU;EAC1B,IAAI,CAAC,GAAG,WAAW,UAAU,WAAW,CAAC,GAAG,OAAO;EACnD,MAAM,IAAI,SAAS,YAAY,WAAW,SAAS,GAAG,CAAC;CAC3D;CAEA,WAAW,WAAW;CAEtB,OAAO;AACX;;;;;;;;;;;AAYA,SAAgB,4BAA4B,aAA+B;CACvE,MAAM,UAAU,kBAAkB,WAAW;CAC7C,IAAI,CAAC,SACD,OAAO,CAAC,sHAAsH;CAElI,OAAO,CACH,iDACA,oBAAoB,QAAQ,yJAEhC;AACJ;;;;;;;;AASA,eAAsB,qBAAqB,aAAoC;CAC3E,MAAM,oBAAoB,WAAW;CACrC,GAAG,OAAO,QAAQ,WAAW,GAAG;EAAE,WAAW;EAAM,OAAO;CAAK,CAAC;CAIhE,MAAM,MAAM,SAAS,WAAW;CAChC,IAAI,GAAG,WAAW,GAAG;OACZ,MAAM,SAAS,GAAG,YAAY,GAAG,GAClC,IAAI,MAAM,WAAW,UAAU,GAAG,GAAG,OAAO,KAAK,KAAK,KAAK,KAAK,GAAG;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CAAA;CAG3G,WAAW,WAAW;AAC1B;;;;;;;;;AAUA,SAAS,gBAAgB,aAA2B;CAChD,MAAM,SAAS,KAAK,KAAK,SAAS,WAAW,GAAG,YAAY;CAC5D,IAAI,GAAG,WAAW,MAAM,GAAG;CAC3B,GAAG,cACC,QACA,mIAEA,MACJ;AACJ"}
1
+ {"version":3,"file":"daemon-BCBMn8hE.js","names":[],"sources":["../src/dev-db/daemon.ts"],"sourcesContent":["/**\n * Starting, finding and stopping the managed database, from the caller's side.\n *\n * Every command that needs Postgres calls {@link ensureManagedDatabase} and\n * gets a connection string back. Whether that started a process or found one\n * already running is not the caller's business, which is the point: `rebase\n * db push`, `rebase dev` and `rebase studio` in three terminals must all reach\n * the same database without coordinating, because two processes opening one\n * PGlite data directory would corrupt it.\n *\n * The hard part is not starting the daemon; it is deciding whether the one the\n * state file describes is still there. A pid can be recycled after a reboot and\n * a port can be taken by a stranger, so believing either on its own would let\n * Rebase send a migration somewhere unintended. {@link isDaemonAlive} asks the\n * daemon to identify itself instead.\n */\n\nimport { randomBytes } from \"crypto\";\nimport { type ChildProcess, execFile, spawn } from \"child_process\";\nimport fs from \"fs\";\nimport net from \"net\";\nimport path from \"path\";\nimport { fileURLToPath } from \"url\";\n\nimport { runningBackendUrl } from \"../utils/dev-server\";\nimport { cliVersion } from \"../utils/version\";\nimport {\n acquireStartLock,\n chooseManagedPort,\n clearState,\n type DaemonState,\n dataDir,\n devDbDir,\n pidRunning,\n readState,\n releaseStartLock,\n stateFile\n} from \"./state\";\n\n/** How long to wait for a first boot. PGlite runs initdb on an empty data dir. */\nconst START_TIMEOUT_MS = 60_000;\n/** Poll interval while waiting for the daemon to publish its state file. */\nconst POLL_INTERVAL_MS = 150;\n/** How long the identity handshake may take before we call it dead. */\nconst IDENTITY_TIMEOUT_MS = 1_500;\n\nexport interface ManagedDatabase {\n /** Connection string for this project's managed database. */\n url: string;\n /** Where the data lives, for diagnostics and `--reset`. */\n dataDir: string;\n port: number;\n pid: number;\n /** True when this call started the daemon rather than finding it. */\n started: boolean;\n /**\n * Connection strings for the additional databases the caller asked for,\n * by declared key — `database(\"analytics\")` → `analytics`. Each is its\n * own PGlite instance behind the same daemon.\n */\n additional: Record<string, string>;\n}\n\n/**\n * PGlite's built-in superuser and database.\n *\n * Fixed by PGlite rather than chosen here, and asserted by the socket spike:\n * `session_user` comes back as `postgres`.\n */\nconst MANAGED_USER = \"postgres\";\nconst MANAGED_DATABASE = \"postgres\";\n\n/**\n * The DSN for the managed development database.\n *\n * **`sslmode=disable` is not decoration.** PGlite's socket server speaks no TLS,\n * and libpq-family clients try SSL first — so Atlas, which `rebase db push`\n * shells out to, failed the whole push with\n * `pq: SSL is not enabled on the server`. Its remedy box then told the reader to\n * append `sslmode=disable` to `DATABASE_URL`, which on this path is not set at\n * all: `rebase init` leaves it commented out precisely so the managed database\n * is used. The advice was correct and unfollowable.\n *\n * Putting it in the URL fixes every consumer at once — Atlas, `pg`, and anything\n * a driver shells out to later — rather than teaching each one about PGlite.\n */\n\n/**\n * The end of `pglite.log`, for an error message that has to carry its own reason.\n *\n * The daemon writes its output to a file because it is detached — it has to\n * outlive the command that started it. That is right, and it means every\n * startup failure used to be reported as a path: \"see pglite.log for the\n * reason\". On a laptop that is a fair trade. In CI it is not a trade at all,\n * because the runner discards the workspace: the log named in the message no\n * longer exists by the time anybody reads the message, so a failed run says\n * only that something failed.\n *\n * So the tail comes with the error. Bounded, because a log that has been\n * appended to across many runs is not something to paste in full.\n */\nexport function pgliteLogTail(projectRoot: string, lines = 12): string {\n try {\n const contents = fs.readFileSync(path.join(devDbDir(projectRoot), \"pglite.log\"), \"utf8\").trimEnd();\n if (!contents) return \" (pglite.log is empty — the daemon wrote nothing before exiting)\";\n return contents.split(\"\\n\").slice(-lines).map(line => ` ${line}`).join(\"\\n\");\n } catch {\n return \" (pglite.log could not be read)\";\n }\n}\n\nexport function managedUrl(port: number): string {\n return `postgresql://${MANAGED_USER}@127.0.0.1:${port}/${MANAGED_DATABASE}?sslmode=disable`;\n}\n\n/**\n * Ask the process behind a state record to prove it is the one we wrote down.\n *\n * A pid check alone answers \"is *a* process running\", and a port check alone\n * answers \"is *something* listening\" — after a reboot both say yes about\n * strangers. The daemon answers with the token from its own state file, so a\n * match is the only evidence accepted.\n */\nexport function isDaemonAlive(state: DaemonState): Promise<boolean> {\n if (!pidRunning(state.pid)) return Promise.resolve(false);\n\n return new Promise((resolve) => {\n const socket = new net.Socket();\n let answer = \"\";\n const settle = (alive: boolean) => {\n socket.removeAllListeners();\n socket.destroy();\n resolve(alive);\n };\n socket.setTimeout(IDENTITY_TIMEOUT_MS);\n socket.once(\"timeout\", () => settle(false));\n socket.once(\"error\", () => settle(false));\n socket.on(\"data\", (chunk) => {\n answer += chunk.toString(\"utf8\");\n if (answer.includes(\"\\n\")) settle(answer.trim() === `rebase-dev-db ${state.token}`);\n });\n socket.once(\"close\", () => settle(answer.trim() === `rebase-dev-db ${state.token}`));\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/**\n * Whether a daemon `started` by one CLI should give way to the CLI `running` now.\n *\n * The database proxy runs inside the daemon, and the daemon outlives every\n * command — so the proxy a project gets is whichever CLI started the daemon\n * last, not the one it upgraded to. True for a daemon from before daemons were\n * stamped, for an older release, and for another build of the same release\n * (two canaries, a canary and its release): canary hashes do not sort by date,\n * and this CLI's proxy is the one it can vouch for. False for a newer release,\n * which an older CLI leaves alone, and when this CLI cannot read its own\n * version.\n */\nexport function daemonOutdated(started: string | undefined, running: string): boolean {\n const core = (version: string): number[] | null => {\n const match = /^(\\d+)\\.(\\d+)\\.(\\d+)/.exec(version);\n return match ? match.slice(1, 4).map(Number) : null;\n };\n const ours = core(running);\n if (!ours || started === running) return false;\n const theirs = started === undefined ? null : core(started);\n if (!theirs) return true;\n for (let i = 0; i < 3; i++) {\n if (theirs[i] !== ours[i]) return theirs[i] < ours[i];\n }\n return true;\n}\n\n/**\n * Send the daemon one command over its identity socket, and get the reply line.\n *\n * `null` for anything that is not the daemon answering: no connection, another\n * token, no reply in time. The identity line comes first, so a stranger on a\n * recycled port is never mistaken for it.\n */\nfunction askDaemon(state: DaemonState, command: string, timeoutMs = IDENTITY_TIMEOUT_MS): Promise<string | null> {\n return new Promise((resolve) => {\n const socket = new net.Socket();\n let buffered = \"\";\n let identified = false;\n const settle = (reply: string | null) => {\n socket.removeAllListeners();\n socket.destroy();\n resolve(reply);\n };\n socket.setTimeout(timeoutMs);\n socket.once(\"timeout\", () => settle(null));\n socket.once(\"error\", () => settle(null));\n socket.once(\"close\", () => settle(null));\n socket.on(\"data\", (chunk) => {\n buffered += chunk.toString(\"utf8\");\n let newline = buffered.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = buffered.slice(0, newline).trim();\n buffered = buffered.slice(newline + 1);\n if (identified) return settle(line);\n if (line !== `rebase-dev-db ${state.token}`) return settle(null);\n identified = true;\n socket.write(`${command}\\n`);\n newline = buffered.indexOf(\"\\n\");\n }\n });\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/**\n * How many of `lsof -Fn`'s sockets are connections accepted on `ports`.\n *\n * Each socket is a line `n<local>-><remote>`. The daemon's accepted client\n * connections have one of its public ports on the local side; its own\n * connections to the socket server behind the proxy are on other ports.\n */\nexport function acceptedConnections(lsofOutput: string, ports: readonly number[]): number {\n let count = 0;\n for (const line of lsofOutput.split(\"\\n\")) {\n if (!line.startsWith(\"n\") || !line.includes(\"->\")) continue;\n const local = line.slice(1, line.indexOf(\"->\"));\n if (ports.includes(Number(local.slice(local.lastIndexOf(\":\") + 1)))) count++;\n }\n return count;\n}\n\n/**\n * The connections the operating system says the daemon has accepted, or `null`\n * when it cannot be asked.\n *\n * For a daemon from before the `clients` command: it cannot be asked itself.\n * `lsof` ships with macOS and most Linux installs; where it is missing, the\n * answer is \"cannot tell\", and the caller does not restart anything.\n */\nfunction osAcceptedConnections(state: DaemonState): Promise<number | null> {\n const ports = [state.port, ...Object.values(state.databases ?? {}).map(database => database.port)];\n return new Promise((resolve) => {\n execFile(\n \"lsof\",\n [\"-nP\", \"-a\", \"-p\", String(state.pid), `-iTCP:${ports.join(\",\")}`, \"-sTCP:ESTABLISHED\", \"-Fn\"],\n { timeout: 3_000 },\n (error, stdout) => {\n // lsof exits 1 when it finds nothing to list, which is an answer.\n if (error && !(error.code === 1 && stdout.trim() === \"\")) return resolve(null);\n resolve(acceptedConnections(stdout, ports));\n }\n );\n });\n}\n\n/**\n * How many clients are connected to the daemon, over all its databases, or\n * `null` when that cannot be known.\n *\n * Asked of the daemon first (`clients`). A daemon from before that command\n * answers `error unknown command`, and then the operating system is asked.\n */\nexport async function connectedClients(state: DaemonState): Promise<number | null> {\n const reply = await askDaemon(state, \"clients\");\n if (reply === null) return null;\n if (reply.startsWith(\"ok \")) {\n const count = Number(reply.slice(3));\n return Number.isInteger(count) && count >= 0 ? count : null;\n }\n return osAcceptedConnections(state);\n}\n\n/**\n * What to say about a daemon an older CLI started that cannot be restarted\n * here, because something is connected to it — or nothing can say whether\n * anything is.\n */\nexport function outdatedDaemonNotice(\n state: Pick<DaemonState, \"cliVersion\">,\n running: string,\n clients: number | null\n): string[] {\n const startedBy = state.cliVersion ? `Rebase CLI ${state.cliVersion}` : \"an earlier Rebase CLI\";\n const connected = clients === null\n ? \"this CLI cannot tell whether anything is connected to it\"\n : `${clients} client${clients === 1 ? \" is\" : \"s are\"} connected to it`;\n return [\n `⚠ The development database was started by ${startedBy}, and ${connected}, so it keeps running ` +\n `with that CLI's database proxy rather than this one's (${running}).`,\n \" Stop what uses it — `rebase dev`, `rebase console`, a database GUI — then run `rebase db stop`. \" +\n \"The next command starts it again, on this CLI. Data is kept.\"\n ];\n}\n\n/** Said once per daemon in a process: every command that needs the database asks again. */\nconst outdatedNoticeShown = new Set<string>();\n\n/**\n * Restart a daemon an older CLI started, when nothing is connected to it.\n *\n * Returns whether it was stopped — the caller then starts a fresh one. With a\n * client connected, stopping would cut it off mid-session, so it says once\n * what to do instead and leaves the daemon serving.\n */\nasync function giveWayToThisCli(projectRoot: string, state: DaemonState, options: EnsureOptions): Promise<boolean> {\n const running = cliVersion();\n if (!daemonOutdated(state.cliVersion, running)) return false;\n const clients = await connectedClients(state);\n if (clients === 0) {\n if (!options.quiet) {\n options.onProgress?.(\n `Restarting the development database: ${state.cliVersion ? `Rebase CLI ${state.cliVersion}` : \"an earlier Rebase CLI\"} ` +\n `started it, and this is ${running}. Data is kept.`\n );\n }\n return stopManagedDatabase(projectRoot);\n }\n const said = `${path.resolve(projectRoot)}\\0${state.pid}`;\n if (!outdatedNoticeShown.has(said)) {\n outdatedNoticeShown.add(said);\n (options.onNotice ?? ((line: string) => console.error(line)))(outdatedDaemonNotice(state, running, clients).join(\"\\n\"));\n }\n return false;\n}\n\n/** The running daemon for this project, or `null`. Never starts anything. */\nexport async function findRunningDaemon(projectRoot: string): Promise<DaemonState | null> {\n const state = readState(projectRoot);\n if (!state) return null;\n if (await isDaemonAlive(state)) return state;\n\n // The record describes something that is not there. Clearing it is the\n // whole recovery: the next ensure call starts a fresh daemon, and leaving\n // it would make every subsequent check pay the identity timeout.\n clearState(projectRoot);\n\n return null;\n}\n\n/**\n * Resolve the CLI entry point, so the daemon can be spawned as ourselves.\n *\n * A hidden subcommand rather than a second build entry: under `tsx` this file\n * is `src/dev-db/daemon.ts` and in a published CLI it is bundled into\n * `dist/index.js`, and in both cases the executable to re-invoke is the one\n * already running. `rebase dev` re-runs itself the same way to regenerate the\n * SDK types.\n */\nexport function resolveCliEntry(): string {\n // `process.argv[1]` is `bin/rebase.js` for a real invocation, which is\n // exactly what should be re-run. Under a test runner it is the runner, so\n // fall back to this module's own directory.\n const argvEntry = process.argv[1];\n if (argvEntry && fs.existsSync(argvEntry)) return argvEntry;\n\n return fileURLToPath(new URL(\"../index.js\", import.meta.url));\n}\n\n/**\n * How to re-invoke ourselves, which differs between a published CLI and this\n * repository.\n *\n * A published `rebase` is `node bin/rebase.js`, and re-running that is trivial.\n * Inside the monorepo the entry is TypeScript, which plain `node` cannot load —\n * so the daemon has to be started through the same loader that is running now.\n * Getting this wrong fails as a spawn that exits instantly with a syntax error,\n * which is why the caller reads `pglite.log` on failure.\n */\nexport function resolveSpawn(entry: string): { execPath: string; prefixArgs: string[] } {\n if (!/\\.[cm]?ts$/.test(entry)) return { execPath: process.execPath, prefixArgs: [] };\n\n // Node can load TypeScript when tsx is registered as an import hook. tsx is\n // already a dependency of this package, because `rebase dev` runs the\n // backend through it.\n return { execPath: process.execPath, prefixArgs: [\"--import\", \"tsx\"] };\n}\n\nexport interface EnsureOptions {\n /** Silence the \"starting…\" progress line. */\n quiet?: boolean;\n /** Milliseconds of inactivity before the daemon exits. 0 disables. */\n idleTimeoutMs?: number;\n /** Where progress goes. Injected for tests. */\n onProgress?: (message: string) => void;\n /** Override how the daemon process is launched. For tests. */\n spawn?: { execPath: string; prefixArgs: string[] };\n /**\n * Override the CLI entry to re-invoke. For tests.\n *\n * Necessary because under a test runner `process.argv[1]` is the runner\n * itself, which exists and is therefore accepted by {@link resolveCliEntry}\n * — spawning vitest with `__dev-db-daemon` rather than the CLI.\n */\n entry?: string;\n /**\n * Where the notice about a daemon an older CLI started goes, when it\n * cannot be restarted. stderr by default, so `rebase db url` keeps stdout\n * to the URL. Injected for tests.\n */\n onNotice?: (message: string) => void;\n /**\n * Keys of the additional databases the project declares, beyond the\n * default. Each is served by the daemon on request, so a project that\n * adds `database(\"analytics\")` while the daemon is running gets it\n * without a restart.\n */\n additionalKeys?: readonly string[];\n}\n\n/**\n * Ask the running daemon for one additional database, and get its port.\n *\n * The identity socket doubles as the command channel: the daemon answers\n * with its token first, which is how the caller knows it is talking to the\n * daemon the state file describes and not to a stranger on a recycled port.\n */\nfunction ensureAdditionalDatabase(state: DaemonState, key: string): Promise<number> {\n return new Promise((resolve, reject) => {\n const socket = new net.Socket();\n let answer = \"\";\n let identified = false;\n const fail = (message: string) => {\n socket.removeAllListeners();\n socket.destroy();\n reject(new Error(message));\n };\n socket.setTimeout(START_TIMEOUT_MS);\n socket.once(\"timeout\", () => fail(`The development database did not answer for \"${key}\" within ${Math.round(START_TIMEOUT_MS / 1000)}s.`));\n socket.once(\"error\", (err) => fail(`Could not reach the development database for \"${key}\": ${err.message}`));\n socket.on(\"data\", (chunk) => {\n answer += chunk.toString(\"utf8\");\n let newline = answer.indexOf(\"\\n\");\n while (newline !== -1) {\n const line = answer.slice(0, newline).trim();\n answer = answer.slice(newline + 1);\n if (!identified) {\n if (line !== `rebase-dev-db ${state.token}`) return fail(\"The process on the development database's port is not the daemon.\");\n identified = true;\n socket.write(`ensure ${key}\\n`);\n } else if (line.startsWith(\"ok \")) {\n const port = Number(line.slice(3));\n socket.removeAllListeners();\n socket.destroy();\n if (!Number.isInteger(port) || port <= 0) return reject(new Error(`The development database answered with an invalid port for \"${key}\": ${line}`));\n return resolve(port);\n } else {\n return fail(`The development database could not serve \"${key}\": ${line.replace(/^error\\s*/, \"\")}`);\n }\n newline = answer.indexOf(\"\\n\");\n }\n });\n socket.connect(state.identityPort, \"127.0.0.1\");\n });\n}\n\n/** Every additional database the caller asked for, as connection strings. */\nasync function adoptWithAdditional(state: DaemonState, started: boolean, keys: readonly string[]): Promise<ManagedDatabase> {\n const additional: Record<string, string> = {};\n for (const key of keys) {\n const known = state.databases?.[key];\n const port = known ? known.port : await ensureAdditionalDatabase(state, key);\n additional[key] = managedUrl(port);\n }\n return { ...adopt(state, started), additional };\n}\n\n/**\n * The project's managed database, started if it is not already running.\n *\n * Safe to call concurrently from several commands: the loser of the race finds\n * the winner's state file during its poll and adopts it rather than starting a\n * second daemon.\n */\nexport async function ensureManagedDatabase(\n projectRoot: string,\n options: EnsureOptions = {}\n): Promise<ManagedDatabase> {\n const keys = options.additionalKeys ?? [];\n const existing = await findRunningDaemon(projectRoot);\n // A daemon an older CLI started is restarted when nothing is connected to\n // it, so the upgrade reaches the proxy inside it. See `daemonOutdated`.\n if (existing && !(await giveWayToThisCli(projectRoot, existing, options))) {\n return adoptWithAdditional(existing, false, keys);\n }\n\n fs.mkdirSync(devDbDir(projectRoot), { recursive: true });\n ensureGitignore(projectRoot);\n\n // Exactly one process may spawn a daemon. Without this, `rebase dev` and\n // `rebase db push` started in the same second both see no state file, both\n // spawn, and two processes open one PGlite data directory — the corruption\n // the single-daemon design exists to prevent.\n if (!acquireStartLock(projectRoot, START_TIMEOUT_MS)) {\n const adopted = await waitForDaemon(projectRoot, START_TIMEOUT_MS);\n if (adopted) return adoptWithAdditional(adopted, false, keys);\n\n // The holder gave up or died without publishing. Falling through to\n // start one ourselves is better than failing: the lock is stale by now,\n // so the next acquire will break it.\n if (!acquireStartLock(projectRoot, 0)) {\n throw new Error(\n \"Another process is starting the development database and did not finish.\\n\" +\n ` Remove ${path.join(devDbDir(projectRoot), \"starting.lock\")} if nothing is running.`\n );\n }\n }\n\n // Where the last daemon listened, so a backend still holding that URL\n // reconnects to this one. See `chooseManagedPort`.\n const port = await chooseManagedPort(projectRoot);\n const token = randomBytes(16).toString(\"hex\");\n const entry = options.entry ?? resolveCliEntry();\n\n const spawnPlan = options.spawn ?? resolveSpawn(entry);\n const args = [\n ...spawnPlan.prefixArgs,\n entry,\n \"__dev-db-daemon\",\n \"--project\", projectRoot,\n \"--port\", String(port),\n \"--token\", token\n ];\n if (options.idleTimeoutMs !== undefined) {\n args.push(\"--idle-timeout\", String(options.idleTimeoutMs));\n }\n\n const log = fs.openSync(path.join(devDbDir(projectRoot), \"pglite.log\"), \"a\");\n const child: ChildProcess = spawn(spawnPlan.execPath, args, {\n // Detached with no stdin and its output on a file: the daemon must\n // survive the command that started it, and must not hold the terminal\n // open when that command exits.\n detached: true,\n stdio: [\"ignore\", log, log]\n });\n child.unref();\n\n try {\n const deadline = Date.now() + START_TIMEOUT_MS;\n let announced = false;\n while (Date.now() < deadline) {\n const state = readState(projectRoot);\n if (state && (await isDaemonAlive(state))) return adoptWithAdditional(state, true, keys);\n\n if (!announced && !options.quiet) {\n announced = true;\n options.onProgress?.(\"Starting the development database…\");\n }\n\n // A daemon that died on startup will never publish a state file, and\n // waiting the full minute for that is a bad way to learn it. The log\n // is the only place the reason exists.\n if (child.exitCode !== null && child.exitCode !== 0) {\n throw new Error(\n `The development database failed to start (exit ${child.exitCode}).\\n` +\n ` ${path.join(devDbDir(projectRoot), \"pglite.log\")} ends:\\n` +\n pgliteLogTail(projectRoot)\n );\n }\n\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n throw new Error(\n `The development database did not start within ${Math.round(START_TIMEOUT_MS / 1000)}s.\\n` +\n ` ${path.join(devDbDir(projectRoot), \"pglite.log\")} ends:\\n` +\n pgliteLogTail(projectRoot) + \"\\n\" +\n \" To use your own Postgres instead, set DATABASE_URL or pass --database-url.\"\n );\n } finally {\n // Released whether we succeeded, timed out or threw. A lock left behind\n // by a crash is broken by age, but only after a full timeout — which a\n // developer should never have to wait out.\n releaseStartLock(projectRoot);\n }\n}\n\n/** Shape a live state record as the caller's result. */\nfunction adopt(state: DaemonState, started: boolean): ManagedDatabase {\n return {\n url: managedUrl(state.port),\n dataDir: state.dataDir,\n port: state.port,\n pid: state.pid,\n started,\n additional: {}\n };\n}\n\n/** Poll until another process publishes a live daemon, or give up. */\nasync function waitForDaemon(projectRoot: string, timeoutMs: number): Promise<DaemonState | null> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n const state = readState(projectRoot);\n if (state && (await isDaemonAlive(state))) return state;\n await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL_MS));\n }\n\n return null;\n}\n\n/** Stop the daemon. Returns false when there was nothing running. */\nexport async function stopManagedDatabase(projectRoot: string): Promise<boolean> {\n const state = await findRunningDaemon(projectRoot);\n if (!state) return false;\n\n try {\n process.kill(state.pid, \"SIGTERM\");\n } catch {\n clearState(projectRoot);\n\n return false;\n }\n\n // Wait for it to clear its own state file, which is how it says it closed\n // the data directory cleanly. A hard kill here would risk the WAL.\n const deadline = Date.now() + 10_000;\n while (Date.now() < deadline) {\n if (!fs.existsSync(stateFile(projectRoot))) return true;\n await new Promise((resolve) => setTimeout(resolve, 100));\n }\n\n clearState(projectRoot);\n\n return true;\n}\n\n/**\n * What `rebase db stop` says once the daemon is down: the headline, then any\n * detail.\n *\n * \"`rebase dev` will start it again\" was not true of a `rebase dev` that is\n * running: nothing in it watches the database, so its backend answered 503\n * until something else started one. The next command that needs it does, on\n * the port it had (`chooseManagedPort`), and the backend's pool reconnects to\n * that address by itself — so while a backend runs, that is what this says.\n */\nexport function stoppedManagedDatabaseLines(projectRoot: string): string[] {\n const backend = runningBackendUrl(projectRoot);\n if (!backend) {\n return [\"✓ Development database stopped. Data is kept — the next `rebase dev`, or any command that needs it, starts it again.\"];\n }\n return [\n \"✓ Development database stopped. Data is kept.\",\n ` The backend at ${backend} cannot reach it until it is back. The next command that needs it — \\`rebase db url\\`, for one — ` +\n \"starts it on the same port, and the backend reconnects.\"\n ];\n}\n\n/**\n * Stop the daemon and delete the data directory.\n *\n * Destructive and deliberately not clever: it removes the whole directory\n * rather than dropping schemas, because \"give me an empty database\" is the only\n * thing anyone means by it.\n */\nexport async function resetManagedDatabase(projectRoot: string): Promise<void> {\n await stopManagedDatabase(projectRoot);\n fs.rmSync(dataDir(projectRoot), { recursive: true, force: true });\n // Every additional database too: `pgdata__<key>` beside `pgdata`. \"Give\n // me an empty database\" means all of them — a reset that emptied the\n // default and kept the analytics rows would be a surprise on first read.\n const dir = devDbDir(projectRoot);\n if (fs.existsSync(dir)) {\n for (const entry of fs.readdirSync(dir)) {\n if (entry.startsWith(\"pgdata__\")) fs.rmSync(path.join(dir, entry), { recursive: true, force: true });\n }\n }\n clearState(projectRoot);\n}\n\n/**\n * Keep the generated directory out of git.\n *\n * `.rebase/` holds a Postgres data directory and a log. A project that commits\n * it will push hundreds of megabytes and a database that only makes sense on\n * one machine, so the ignore file is written next to the data rather than\n * relying on the project's root `.gitignore` having been updated.\n */\nfunction ensureGitignore(projectRoot: string): void {\n const target = path.join(devDbDir(projectRoot), \".gitignore\");\n if (fs.existsSync(target)) return;\n fs.writeFileSync(\n target,\n \"# Generated by `rebase dev` — a local Postgres data directory and its log.\\n\" +\n \"# Machine-specific and large; never commit it.\\n*\\n\",\n \"utf8\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,IAAM,mBAAmB;;AAEzB,IAAM,mBAAmB;;AAEzB,IAAM,sBAAsB;;;;;;;AAyB5B,IAAM,eAAe;AACrB,IAAM,mBAAmB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+B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B;CAChD,MAAM,SAAS,KAAK,KAAK,SAAS,WAAW,GAAG,YAAY;CAC5D,IAAI,GAAG,WAAW,MAAM,GAAG;CAC3B,GAAG,cACC,QACA,mIAEA,MACJ;AACJ"}
@@ -1,7 +1,7 @@
1
1
  import { n as unknownCommand } from "./unknown-command-DnZ2uhGs.js";
2
2
  import { a as wantsHelp, n as parseCommandArgs, t as UsageError } from "./args-DHyrshtI.js";
3
- import { a as projectTarget, c as requestJson, d as PROJECT_TARGET_FLAGS, g as readJson, i as printProjectHelp, l as startProjectCommand, n as isRecord, o as recordsOf, r as parsedLine, s as reportTargetError, t as cellText, u as stringOf } from "./project-command-7EGMemEy.js";
4
- import { D as isJsonMode, M as note, k as keyValues, l as confirmDestructive, m as emit, st as success, v as fail } from "./context-xt20FMFA.js";
3
+ import { a as projectTarget, c as requestJson, d as PROJECT_TARGET_FLAGS, g as readJson, i as printProjectHelp, l as startProjectCommand, n as isRecord, o as recordsOf, r as parsedLine, s as reportTargetError, t as cellText, u as stringOf } from "./project-command-5wM_bJQt.js";
4
+ import { D as isJsonMode, M as note, k as keyValues, l as confirmDestructive, m as emit, st as success, v as fail } from "./context-C9lz1vTS.js";
5
5
  import chalk from "chalk";
6
6
  import fs from "fs";
7
7
  //#region src/commands/data.ts
@@ -944,4 +944,4 @@ function printDataHelp() {
944
944
  //#endregion
945
945
  export { DATA_SUBCOMMANDS, dataCommand };
946
946
 
947
- //# sourceMappingURL=data-BpkvtCUe.js.map
947
+ //# sourceMappingURL=data-1eipHbxJ.js.map