@mulmoclaude/core 5.12.1 → 5.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/assets/helps/presenthtml.md +24 -0
- package/dist/artifacts/paths.cjs +1 -2
- package/dist/artifacts/paths.js +1 -2
- package/dist/collection/firestore.cjs +1 -2
- package/dist/collection/firestore.js +1 -2
- package/dist/collection/index.cjs +18 -30
- package/dist/collection/index.cjs.map +1 -1
- package/dist/collection/index.js +18 -30
- package/dist/collection/index.js.map +1 -1
- package/dist/collection/paths.cjs +1 -1
- package/dist/collection/paths.js +1 -1
- package/dist/collection/registry/index.cjs +1 -1
- package/dist/collection/registry/index.js +1 -1
- package/dist/collection/registry/server/index.cjs +17 -26
- package/dist/collection/registry/server/index.cjs.map +1 -1
- package/dist/collection/registry/server/index.js +16 -25
- package/dist/collection/registry/server/index.js.map +1 -1
- package/dist/collection/server/index.cjs +5 -5
- package/dist/collection/server/index.js +5 -5
- package/dist/collection-watchers/index.cjs +10 -14
- package/dist/collection-watchers/index.cjs.map +1 -1
- package/dist/collection-watchers/index.js +10 -14
- package/dist/collection-watchers/index.js.map +1 -1
- package/dist/{discovery-DgZRmO7F.cjs → discovery-CYIV1J5l.cjs} +25 -42
- package/dist/{discovery-DgZRmO7F.cjs.map → discovery-CYIV1J5l.cjs.map} +1 -1
- package/dist/{discovery-CbwHtcwk.js → discovery-duLlygnJ.js} +24 -41
- package/dist/{discovery-CbwHtcwk.js.map → discovery-duLlygnJ.js.map} +1 -1
- package/dist/{dist-BZ62pKuU.cjs → dist-734JaRYi.cjs} +2 -4
- package/dist/{dist-BZ62pKuU.cjs.map → dist-734JaRYi.cjs.map} +1 -1
- package/dist/{dist-MFUV9FYo.js → dist-BmO4oSQy.js} +2 -4
- package/dist/{dist-MFUV9FYo.js.map → dist-BmO4oSQy.js.map} +1 -1
- package/dist/errorMessage-D0kR547_.cjs +1 -0
- package/dist/errorMessage-TpKxrmeo.js +1 -0
- package/dist/{errors-zTAsW7dS.js → errors-0QwjDxsv.js} +3 -4
- package/dist/{errors-zTAsW7dS.js.map → errors-0QwjDxsv.js.map} +1 -1
- package/dist/{errors-B0xloJ3E.cjs → errors-B9mCEVG9.cjs} +3 -4
- package/dist/{errors-B0xloJ3E.cjs.map → errors-B9mCEVG9.cjs.map} +1 -1
- package/dist/feeds/index.cjs +2 -2
- package/dist/feeds/index.js +2 -2
- package/dist/feeds/paths.cjs +2 -3
- package/dist/feeds/paths.js +1 -2
- package/dist/feeds/server/index.cjs +23 -37
- package/dist/feeds/server/index.cjs.map +1 -1
- package/dist/feeds/server/index.js +22 -36
- package/dist/feeds/server/index.js.map +1 -1
- package/dist/file-change/index.cjs +2 -3
- package/dist/file-change/index.js +1 -2
- package/dist/files/index.cjs +159 -11
- package/dist/files/index.cjs.map +1 -1
- package/dist/files/index.d.ts +1 -0
- package/dist/files/index.js +154 -12
- package/dist/files/index.js.map +1 -1
- package/dist/files/verified.d.ts +33 -0
- package/dist/global-config/index.cjs +3 -5
- package/dist/global-config/index.cjs.map +1 -1
- package/dist/global-config/index.js +3 -5
- package/dist/global-config/index.js.map +1 -1
- package/dist/google/index.cjs +38 -67
- package/dist/google/index.cjs.map +1 -1
- package/dist/google/index.js +37 -66
- package/dist/google/index.js.map +1 -1
- package/dist/{graph-CURotEkH.cjs → graph-BvVMZfDV.cjs} +6 -11
- package/dist/{graph-CURotEkH.cjs.map → graph-BvVMZfDV.cjs.map} +1 -1
- package/dist/{graph-DBxSOx3v.js → graph-DBbzemby.js} +6 -11
- package/dist/{graph-DBxSOx3v.js.map → graph-DBbzemby.js.map} +1 -1
- package/dist/{iconGlyph-fSBp6k4J.cjs → iconGlyph-CFOiFsmq.cjs} +2 -3
- package/dist/{iconGlyph-fSBp6k4J.cjs.map → iconGlyph-CFOiFsmq.cjs.map} +1 -1
- package/dist/{iconGlyph-D8JeNg7R.js → iconGlyph-D9h__VaM.js} +2 -3
- package/dist/{iconGlyph-D8JeNg7R.js.map → iconGlyph-D9h__VaM.js.map} +1 -1
- package/dist/{ingestTypes-DS9HiR2I.cjs → ingestTypes-CLDvn7kw.cjs} +3 -4
- package/dist/{ingestTypes-DS9HiR2I.cjs.map → ingestTypes-CLDvn7kw.cjs.map} +1 -1
- package/dist/{ingestTypes-Bs31Xt5c.js → ingestTypes-DuXuSBSn.js} +3 -4
- package/dist/{ingestTypes-Bs31Xt5c.js.map → ingestTypes-DuXuSBSn.js.map} +1 -1
- package/dist/{itemId-CVrNibwT.cjs → itemId-D2XAQ8RU.cjs} +9 -17
- package/dist/{itemId-CVrNibwT.cjs.map → itemId-D2XAQ8RU.cjs.map} +1 -1
- package/dist/{itemId-C9s-Jd5s.js → itemId-D_pSpa3U.js} +9 -17
- package/dist/{itemId-C9s-Jd5s.js.map → itemId-D_pSpa3U.js.map} +1 -1
- package/dist/{listen-N_8XdKz_.cjs → listen-OmfLDX1l.cjs} +3 -4
- package/dist/{listen-N_8XdKz_.cjs.map → listen-OmfLDX1l.cjs.map} +1 -1
- package/dist/{listen-DUlzSOzX.js → listen-uiEnXcW9.js} +3 -4
- package/dist/{listen-DUlzSOzX.js.map → listen-uiEnXcW9.js.map} +1 -1
- package/dist/notifier/index.cjs +1 -1
- package/dist/notifier/index.js +1 -1
- package/dist/{notifier-CiemUClt.cjs → notifier-CRTk34EC.cjs} +6 -10
- package/dist/{notifier-CiemUClt.cjs.map → notifier-CRTk34EC.cjs.map} +1 -1
- package/dist/{notifier-dgkC-h80.js → notifier-htdf4ekH.js} +6 -10
- package/dist/{notifier-dgkC-h80.js.map → notifier-htdf4ekH.js.map} +1 -1
- package/dist/{paths-CkJxNZ7T.js → paths-BMQNHdaJ.js} +2 -3
- package/dist/{paths-CkJxNZ7T.js.map → paths-BMQNHdaJ.js.map} +1 -1
- package/dist/{paths-C8-jxR0s.cjs → paths-DUHAueEv.cjs} +2 -3
- package/dist/{paths-C8-jxR0s.cjs.map → paths-DUHAueEv.cjs.map} +1 -1
- package/dist/plugin-vue/i18n.cjs +1 -2
- package/dist/plugin-vue/i18n.js +1 -2
- package/dist/plugin-vue/index.cjs +9 -17
- package/dist/plugin-vue/index.cjs.map +1 -1
- package/dist/plugin-vue/index.js +9 -17
- package/dist/plugin-vue/index.js.map +1 -1
- package/dist/{project-C1ep9pvo.cjs → project-DDTIVEMU.cjs} +2 -3
- package/dist/{project-C1ep9pvo.cjs.map → project-DDTIVEMU.cjs.map} +1 -1
- package/dist/{project-B0j_Vf_Q.js → project-mU6-xLfy.js} +2 -3
- package/dist/{project-B0j_Vf_Q.js.map → project-mU6-xLfy.js.map} +1 -1
- package/dist/prompt-files/index.cjs +4 -6
- package/dist/prompt-files/index.cjs.map +1 -1
- package/dist/prompt-files/index.js +3 -5
- package/dist/prompt-files/index.js.map +1 -1
- package/dist/{promptSafety-DFaOnOWN.js → promptSafety-B8LECAkY.js} +14 -25
- package/dist/{promptSafety-DFaOnOWN.js.map → promptSafety-B8LECAkY.js.map} +1 -1
- package/dist/{promptSafety-yET9jLep.cjs → promptSafety-CjxafW2b.cjs} +14 -25
- package/dist/{promptSafety-yET9jLep.cjs.map → promptSafety-CjxafW2b.cjs.map} +1 -1
- package/dist/{relPath-DW8MC8VO.js → relPath-BkKmqiiF.js} +2 -3
- package/dist/{relPath-DW8MC8VO.js.map → relPath-BkKmqiiF.js.map} +1 -1
- package/dist/{relPath-CTAjGdCL.cjs → relPath-CZiP2S_a.cjs} +3 -4
- package/dist/{relPath-CTAjGdCL.cjs.map → relPath-CZiP2S_a.cjs.map} +1 -1
- package/dist/remote-host/index.cjs +1 -1
- package/dist/remote-host/index.js +1 -1
- package/dist/remote-host/server/index.cjs +14 -25
- package/dist/remote-host/server/index.cjs.map +1 -1
- package/dist/remote-host/server/index.js +14 -25
- package/dist/remote-host/server/index.js.map +1 -1
- package/dist/{remote-host-CR5W9uj4.cjs → remote-host-BW_eH-Nu.cjs} +4 -6
- package/dist/{remote-host-CR5W9uj4.cjs.map → remote-host-BW_eH-Nu.cjs.map} +1 -1
- package/dist/{remote-host-9NNAvUhU.js → remote-host-CSeDNbE6.js} +4 -6
- package/dist/{remote-host-9NNAvUhU.js.map → remote-host-CSeDNbE6.js.map} +1 -1
- package/dist/remote-view/index.cjs +3 -4
- package/dist/remote-view/index.js +3 -4
- package/dist/{rolldown-runtime-VH7oDXx4.cjs → rolldown-runtime-CmQyd0Gu.cjs} +1 -2
- package/dist/{root-BvwBUcol.cjs → root-9lRFeXbm.cjs} +10 -6
- package/dist/{root-BvwBUcol.cjs.map → root-9lRFeXbm.cjs.map} +1 -1
- package/dist/{root-BcS4-Kge.js → root-CqxPNSyK.js} +4 -6
- package/dist/{root-BcS4-Kge.js.map → root-CqxPNSyK.js.map} +1 -1
- package/dist/scheduler/index.cjs +6 -9
- package/dist/scheduler/index.cjs.map +1 -1
- package/dist/scheduler/index.js +5 -8
- package/dist/scheduler/index.js.map +1 -1
- package/dist/{server-CJek9Y3Q.cjs → server-ByKWGQn2.cjs} +25 -41
- package/dist/{server-CJek9Y3Q.cjs.map → server-ByKWGQn2.cjs.map} +1 -1
- package/dist/{server-BtbbQqBY.js → server-CA-alqqN.js} +24 -40
- package/dist/{server-BtbbQqBY.js.map → server-CA-alqqN.js.map} +1 -1
- package/dist/skill-bridge/index.cjs +3 -4
- package/dist/skill-bridge/index.js +2 -3
- package/dist/{slug-BpjumQfe.js → slug-D24AYqCZ.js} +2 -3
- package/dist/{slug-BpjumQfe.js.map → slug-D24AYqCZ.js.map} +1 -1
- package/dist/{slug-JxgB0ru9.cjs → slug-DVkuPjIv.cjs} +2 -3
- package/dist/{slug-JxgB0ru9.cjs.map → slug-DVkuPjIv.cjs.map} +1 -1
- package/dist/{templatePath-27vUZowm.cjs → templatePath-BIh7wqgS.cjs} +2 -3
- package/dist/{templatePath-27vUZowm.cjs.map → templatePath-BIh7wqgS.cjs.map} +1 -1
- package/dist/{templatePath-k_WNbL_Q.js → templatePath-CB3wtVpe.js} +2 -3
- package/dist/{templatePath-k_WNbL_Q.js.map → templatePath-CB3wtVpe.js.map} +1 -1
- package/dist/{text-CjDbP2O1.js → text-BQAuwKVj.js} +2 -3
- package/dist/{text-CjDbP2O1.js.map → text-BQAuwKVj.js.map} +1 -1
- package/dist/{text-CaAh9ZSO.cjs → text-BQiyo5R9.cjs} +2 -3
- package/dist/{text-CaAh9ZSO.cjs.map → text-BQiyo5R9.cjs.map} +1 -1
- package/dist/translation/client.cjs +1 -2
- package/dist/translation/client.js +1 -2
- package/dist/{types-BKVZrtyc.js → types-BLCZTGW2.js} +4 -7
- package/dist/{types-BKVZrtyc.js.map → types-BLCZTGW2.js.map} +1 -1
- package/dist/{types-CNqkLT4M.cjs → types-DPycxnDf.cjs} +4 -7
- package/dist/{types-CNqkLT4M.cjs.map → types-DPycxnDf.cjs.map} +1 -1
- package/dist/utils/fetch.cjs +0 -1
- package/dist/utils/fetch.js +0 -1
- package/dist/utils/index.cjs +3 -3
- package/dist/utils/index.js +3 -3
- package/dist/whisper/client.cjs +2 -4
- package/dist/whisper/client.cjs.map +1 -1
- package/dist/whisper/client.js +2 -4
- package/dist/whisper/client.js.map +1 -1
- package/dist/whisper/index.cjs +9 -15
- package/dist/whisper/index.cjs.map +1 -1
- package/dist/whisper/index.js +8 -14
- package/dist/whisper/index.js.map +1 -1
- package/dist/wiki/index.cjs +5 -7
- package/dist/wiki/index.cjs.map +1 -1
- package/dist/wiki/index.js +5 -7
- package/dist/wiki/index.js.map +1 -1
- package/dist/wiki/paths.cjs +3 -4
- package/dist/wiki/paths.js +2 -3
- package/dist/wiki/server/index.cjs +7 -11
- package/dist/wiki/server/index.cjs.map +1 -1
- package/dist/wiki/server/index.js +6 -10
- package/dist/wiki/server/index.js.map +1 -1
- package/dist/workspace-setup/index.js +4 -9
- package/dist/workspace-setup/index.js.map +1 -1
- package/dist/workspace-setup/slug.js +1 -2
- package/package.json +2 -2
- package/dist/errorMessage-OEQzRwsi.cjs +0 -1
- package/dist/errorMessage-VEiXHRnX.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-host-CR5W9uj4.cjs","names":["isRecord","collection","doc"],"sources":["../src/remote-host/health.ts","../src/remote-host/index.ts"],"sourcesContent":["// Health of the remote-host command channel, as reported by the resilient runner\n// and rendered by a host's toolbar control. Browser-safe on purpose: the client\n// narrows the parsed HTTP payload with the same guard the server writes it from,\n// so the two sides cannot drift on the state names.\n//\n// online — the Firestore subscription is up; the phone can reach this host\n// reconnecting — it died and is being re-subscribed with backoff (self-healing)\n// offline — re-subscribing stopped helping, or nothing is connected at all;\n// recovering needs a re-auth from the browser's parked session\n//\n// Deliberately no UI wording here — how a state reads to a user is each host's\n// i18n, and core owning it would make the shared package a translation authority.\nexport const RUNNER_HEALTH_STATES = [\"online\", \"reconnecting\", \"offline\"] as const;\nexport type RunnerHealthState = (typeof RUNNER_HEALTH_STATES)[number];\n\nexport interface RunnerHealth {\n state: RunnerHealthState;\n /** Last channel error seen, for the popover and the log. Null before the first one. */\n lastError: string | null;\n /** ms epoch of the last state change, so the UI can say how long it has been down. */\n changedAt: number;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null;\n\nexport const isRunnerHealthState = (value: unknown): value is RunnerHealthState => RUNNER_HEALTH_STATES.some((state) => state === value);\n\n/** Narrows a parsed HTTP payload. The client renders whatever this accepts, so a\n * half-shaped health has to read as \"no health reported\" rather than as a state. */\nexport const isRunnerHealth = (value: unknown): value is RunnerHealth =>\n isRecord(value) &&\n isRunnerHealthState(value.state) &&\n (value.lastError === null || typeof value.lastError === \"string\") &&\n typeof value.changedAt === \"number\";\n","// Remote-host command-channel protocol — the browser-safe contract shared by a\n// host (MulmoClaude, MulmoTerminal) and the remote/mobile client (mulmoserver).\n//\n// A host signs in to Firebase as the user, listens to that user's per-host\n// command queue in Firestore, runs a handler, and writes the result back; the\n// remote writes commands and reads results via a real-time listener. This module\n// owns the wire types + the Firestore path helpers. It is the single source of\n// truth so the host runner and the client never drift on the protocol.\n//\n// Ported from ../mulmoserver/src/firestore/commandChannel.ts and the per-host\n// copy that lived in MulmoClaude's server/remoteHost/. The one change vs. those\n// copies: the path helpers take the `firestore` instance as a parameter (rather\n// than importing a module-level singleton) so a single extracted module serves\n// every host's own Firebase init. The hostId is host-specific (\"mulmoclaude\",\n// \"mulmoterminal\") and is supplied by each host.\nimport { CollectionReference, DocumentData, DocumentReference, Firestore, collection, doc } from \"firebase/firestore\";\nimport { isRecord } from \"@mulmoclaude/common\";\n\n// JSON payloads carried by the command channel. Explicit JSON types keep the\n// channel typed without resorting to any/unknown.\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\nexport type JsonObject = Record<string, JsonValue>;\n\n/** Structural JSON view of `T`, recursively.\n *\n * TypeScript gives an implicit index signature to type aliases and mapped\n * types but NOT to interfaces, so a payload assembled from domain interfaces\n * (`Shortcut`, `FeedSummary`, …) cannot satisfy `Record<string, JsonValue>`\n * structurally — even though it is plain JSON at runtime. Mapping over `T`\n * reconstructs it as an anonymous type, which does get that index signature.\n *\n * Recursive on purpose: a top-level-only map would still leave nested\n * interfaces (`{ shortcuts: Shortcut[] }`) unassignable, which is the case\n * every handler here actually has. */\n// The function branch must come BEFORE the object branch: a function IS an\n// object to TypeScript, so without it a function maps to `{}` and sails\n// through — the helper would accept a payload that serialises to nothing.\n// Verified: `toJsonObject({ callback: () => undefined })` compiled clean until\n// this branch existed (CodeRabbit, #2596).\nexport type Jsonify<T> = T extends JsonValue\n ? T\n : T extends (...args: never[]) => unknown\n ? never\n : T extends (infer U)[]\n ? Jsonify<U>[]\n : T extends object\n ? { [K in keyof T]: Jsonify<T[K]> }\n : never;\n\n/** Widen a JSON-shaped handler payload to the channel's `JsonObject`.\n *\n * Exists so the `Jsonify` reasoning above lives in ONE place. Before this,\n * eight remote-host handlers each carried their own `as unknown as JsonObject`\n * with the justification re-argued in eight slightly different comments —\n * which is how a rule stops being reviewable. */\nexport const toJsonObject = <T extends object>(payload: Jsonify<T>): JsonObject => payload as JsonObject;\n\nconst describeNonJson = (value: unknown): string => {\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"object\") return \"a non-plain object\";\n return `a ${typeof value}`;\n};\n\n/** Anything carrying its own JSON form — `Date` above all — must be asked for\n * it rather than walked, because walking a `Date`'s own enumerable keys finds\n * none and flattens the timestamp to `{}`. This is the step `JSON.stringify`\n * performs before it recurses, and the channel used to get it for free. */\nconst hasToJson = (value: object): value is { toJSON: () => unknown } => \"toJSON\" in value && typeof value.toJSON === \"function\";\n\nconst jsonRepresentationOf = (value: object): unknown => (hasToJson(value) ? value.toJSON() : value);\n\n/** Rebuild `value` as JSON, or throw naming the property that cannot be. */\nfunction toJsonValue(value: unknown, path: string): JsonValue {\n if (Array.isArray(value)) return toJsonItems(value, path);\n if (isRecord(value)) {\n const represented = jsonRepresentationOf(value);\n if (represented !== value) return toJsonValue(represented, path);\n return toJsonEntries(value, path);\n }\n return toJsonScalar(value, path);\n}\n\n/** JSON's four scalar forms. Anything else — a function, a class instance, a\n * non-finite number — is what the channel cannot carry. */\nfunction toJsonScalar(value: unknown, path: string): JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw new Error(`${path} is ${describeNonJson(value)}, which JSON cannot represent`);\n}\n\nfunction toJsonItems(items: unknown[], path: string): JsonValue[] {\n // An absent element becomes `null`, matching `JSON.stringify` — an array has\n // to keep its length, so a hole cannot simply be dropped the way a key is.\n // `Array.from` rather than `map`, which SKIPS holes and would leave them in\n // the result: `JSON.stringify` renders a hole as null and hides that, but\n // `1 in arr` / `Object.keys` / `forEach` all still see the gap.\n return Array.from(items, (entry, index) => (entry === undefined ? null : toJsonValue(entry, `${path}[${index}]`)));\n}\n\nfunction toJsonEntries(record: Record<string, unknown>, path: string): JsonObject {\n const usable = Object.entries(record).filter(([, value]) => value !== undefined);\n return Object.fromEntries(usable.map(([key, value]) => [key, toJsonValue(value, `${path}.${key}`)]));\n}\n\n/** Runtime counterpart to `toJsonObject`, for payloads whose values are typed\n * `unknown` — a collection record, a projected view row — so no amount of\n * mapped-type work can PROVE them JSON.\n *\n * Walks the payload and rebuilds it from the values it actually inspected, so\n * the returned `JsonObject` is earned rather than asserted. Absent (`undefined`)\n * properties are dropped exactly as `JSON.stringify` drops them; anything the\n * channel could not carry — a function, a class instance, `NaN` — throws\n * naming its path, instead of reaching Firestore as a silently mangled write. */\nexport const coerceJsonObject = (payload: Record<string, unknown>): JsonObject => toJsonEntries(payload, \"payload\");\n\n// A channel routes commands to one specific host. A host's first machine uses the\n// host's fixed id (\"mulmoclaude\", \"mulmoterminal\"); a host that runs on several\n// machines gives each later one \"<id>-<8 hex>\" (RemoteHostDeps.resolveHostId), and\n// the remote finds those by listing users/{uid}/hosts.\nexport interface Channel {\n uid: string;\n hostId: string;\n}\n\nexport type CommandStatus = \"queued\" | \"processing\" | \"done\" | \"error\";\n\nexport interface CommandError {\n code: string;\n message: string;\n}\n\n// One document in a channel's commands subcollection is one API-call-like\n// request. The remote (mobile) writes method/params; the host writes\n// result/error/status.\nexport interface Command {\n method: string;\n params: JsonObject;\n status: CommandStatus;\n result: JsonValue;\n error: CommandError | null;\n createdBy: \"remote\" | \"host\";\n // Offline-queue fields (all optional; absent ⇒ pre-offline-queue behaviour, so\n // this is backward-compatible with every deployed client). Epoch-millisecond\n // NUMBERS set by the remote at enqueue time — deliberately plain numbers, not\n // Firestore Timestamps, so `isExpired` / `byCreatedAt` stay pure + browser-safe\n // and unit-testable without a Firestore fake. Clock skew over a multi-day expiry\n // window is immaterial. See plans/done/feat-remote-offline-queue.md.\n createdAt?: number; // enqueue time — age/display + best-effort dispatch bias (NOT a strict order guarantee; chat is async)\n expiresAt?: number; // deadline; past it the host deletes the command + its staged attachments\n queuedOffline?: boolean; // emitted while the host was offline (gates the remote's attachment rollback)\n}\n\n// A command is expired once `now` reaches its remote-set deadline. Absent\n// `expiresAt` ⇒ it never expires (pre-offline-queue commands). Pure with an\n// injected `now` for deterministic tests; the runner passes `Date.now()`.\nexport const isExpired = (command: Pick<Command, \"expiresAt\">, now: number): boolean => typeof command.expiresAt === \"number\" && now >= command.expiresAt;\n\n// Best-effort dispatch bias for a drained batch: oldest enqueue first. This is\n// NOT an ordering guarantee — commands run concurrently and may complete out of\n// order (chat is asynchronous, by design); it only nudges which one starts first.\n// A command with no `createdAt` sorts as oldest (0) so it is never starved.\nexport const byCreatedAt = (left: Pick<Command, \"createdAt\">, right: Pick<Command, \"createdAt\">): number => (left.createdAt ?? 0) - (right.createdAt ?? 0);\n\nexport type CommandHandler = (params: JsonObject) => JsonValue | Promise<JsonValue>;\nexport type CommandHandlers = Record<string, CommandHandler>;\n\n/** The param name a collection-serving command uses to say WHICH project's\n * collections it means. Reserved and documented now, before a phone client\n * ships, because the parts that are hard to change later are the ones being\n * written today. Four rules go with it:\n *\n * 1. **It is an OPAQUE scope, never a path.** The phone is a genuinely remote\n * client; an absolute root in a command, an artifact or a token publishes\n * the user's home directory over the wire. Mint a project id host-side and\n * resolve it host-side.\n * 2. **The phone must be able to LEARN the list.** A picker needs\n * `{ id, label }` pairs from the host — a command of its own, or a field on\n * an existing listing. Designing the scope value now is what keeps that the\n * ONLY new thing when the feature lands.\n * 3. **Handlers RESOLVE a scope; they do not hard-code one.** Write each\n * collection handler as \"read the scope from params, defaulting to the\n * host's root\" rather than calling the workspace accessor inline. Today\n * every call resolves the default and behaves exactly as it does now; the\n * day the param arrives, no handler changes.\n * 4. **The artifact stays host-built.** A remote view's srcdoc, its inlined\n * image thumbnails and its token are assembled on the host, so the phone\n * never resolves a path itself. That is what makes (1) hold without\n * trusting the client. */\nexport const COMMAND_SCOPE_PARAM = \"project\";\n\n/** Read the opaque project scope off a command's params, or `undefined` for\n * \"the host's own root\" — which is what every command means today. A\n * non-string (or empty) value is treated as absent rather than as an error: a\n * scope the host cannot resolve must fall back to the default, never to a\n * guess. Hosts pass the result to their own id → root resolver; this module\n * deliberately never sees a path. */\nexport const readCommandScope = (params: JsonObject): string | undefined => {\n const raw = params[COMMAND_SCOPE_PARAM];\n return typeof raw === \"string\" && raw.trim().length > 0 ? raw.trim() : undefined;\n};\n\n// Bumped when the command-channel wire protocol changes in a way the remote must\n// gate on. Advertised in the presence doc so the remote can check compatibility\n// before issuing commands.\n//\n// v2: offline queueing. The host honours `expiresAt` (deletes an expired command\n// + its staged attachments instead of spawning a stale chat). A remote MUST see\n// protocolVersion >= 2 before queueing a startChat while the host is offline —\n// a v1 host silently ignores `expiresAt`, so a queued chat would spawn stale on\n// reconnect with its uploads never cleaned up.\nexport const REMOTE_HOST_PROTOCOL_VERSION = 2;\n\n// The presence doc's payload: online flag + a capability advertisement. Written\n// by the host on every heartbeat; the remote reads it from the presence listener\n// it already runs (no extra round trip, known the instant the host is online).\n// Browser-safe so the mobile client compiles against the same shape.\n// `updatedAt` (a Firestore serverTimestamp) is added by the runner at write time\n// and is intentionally not part of this capability contract.\n// Which machine a presence comes from, for a host that can run on several machines\n// under one account (mulmoterminal#3092): a stable id the host recognises itself by,\n// and the name the remote shows for it.\nexport interface HostMachine {\n machineId: string;\n label: string;\n}\n\nexport interface HostPresence {\n online: boolean;\n hostId: string;\n protocolVersion: number;\n // Method names the host serves — the keys of the live handler table.\n capabilities: string[];\n machineId?: string;\n label?: string;\n}\n\n// Build the presence payload from the live handler table. Capabilities are\n// `Object.keys(handlers)` so registering a handler is the ONLY step needed to\n// advertise it — there is no second list to keep in sync.\nexport const buildHostPresence = (channel: Channel, handlers: CommandHandlers, online: boolean, machine?: HostMachine): HostPresence => ({\n online,\n hostId: channel.hostId,\n protocolVersion: REMOTE_HOST_PROTOCOL_VERSION,\n capabilities: Object.keys(handlers),\n ...(machine ? { machineId: machine.machineId, label: machine.label } : {}),\n});\n\n// Per-host command queue: users/{uid}/hosts/{hostId}/commands.\nexport const commandsCollection = (firestore: Firestore, channel: Channel): CollectionReference<DocumentData> =>\n collection(firestore, \"users\", channel.uid, \"hosts\", channel.hostId, \"commands\");\n\n// Presence doc for a host: users/{uid}/hosts/{hostId}. The host heartbeats\n// { online, updatedAt } here; the remote reads it to know if the host is up.\nexport const hostDoc = (firestore: Firestore, channel: Channel): DocumentReference<DocumentData> =>\n doc(firestore, \"users\", channel.uid, \"hosts\", channel.hostId);\n\n// Channel health as the resilient runner reports it. Browser-safe alongside the\n// wire types because the control that renders it runs in the client.\nexport { RUNNER_HEALTH_STATES, isRunnerHealth, isRunnerHealthState } from \"./health.js\";\nexport type { RunnerHealth, RunnerHealthState } from \"./health.js\";\n"],"mappings":";;;AAYA,IAAa,uBAAuB;CAAC;CAAU;CAAgB;AAAS;AAWxE,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU;AAE9G,IAAa,uBAAuB,UAA+C,qBAAqB,MAAM,UAAU,UAAU,KAAK;;;AAIvI,IAAa,kBAAkB,UAC7B,SAAS,KAAK,KACd,oBAAoB,MAAM,KAAK,MAC9B,MAAM,cAAc,QAAQ,OAAO,MAAM,cAAc,aACxD,OAAO,MAAM,cAAc;;;;;;;;;ACsB7B,IAAa,gBAAkC,YAAoC;AAEnF,IAAM,mBAAmB,UAA2B;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,KAAK,OAAO;AACrB;;;;;AAMA,IAAM,aAAa,UAAsD,YAAY,SAAS,OAAO,MAAM,WAAW;AAEtH,IAAM,wBAAwB,UAA4B,UAAU,KAAK,IAAI,MAAM,OAAO,IAAI;;AAG9F,SAAS,YAAY,OAAgB,MAAyB;CAC5D,IAAI,MAAM,QAAQ,KAAK,GAAG,OAAO,YAAY,OAAO,IAAI;CACxD,IAAIA,aAAAA,SAAS,KAAK,GAAG;EACnB,MAAM,cAAc,qBAAqB,KAAK;EAC9C,IAAI,gBAAgB,OAAO,OAAO,YAAY,aAAa,IAAI;EAC/D,OAAO,cAAc,OAAO,IAAI;CAClC;CACA,OAAO,aAAa,OAAO,IAAI;AACjC;;;AA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QAAQ;CAAM,IAAI,CAAC;AAC1E;AAGA,IAAa,sBAAsB,WAAsB,aAAA,GACvDC,mBAAAA,WAAAA,CAAW,WAAW,SAAS,QAAQ,KAAK,SAAS,QAAQ,QAAQ,UAAU;AAIjF,IAAa,WAAW,WAAsB,aAAA,GAC5CC,mBAAAA,IAAAA,CAAI,WAAW,SAAS,QAAQ,KAAK,SAAS,QAAQ,MAAM"}
|
|
1
|
+
{"version":3,"file":"remote-host-BW_eH-Nu.cjs","names":["isRecord","collection","doc"],"sources":["../src/remote-host/health.ts","../src/remote-host/index.ts"],"sourcesContent":["// Health of the remote-host command channel, as reported by the resilient runner\n// and rendered by a host's toolbar control. Browser-safe on purpose: the client\n// narrows the parsed HTTP payload with the same guard the server writes it from,\n// so the two sides cannot drift on the state names.\n//\n// online — the Firestore subscription is up; the phone can reach this host\n// reconnecting — it died and is being re-subscribed with backoff (self-healing)\n// offline — re-subscribing stopped helping, or nothing is connected at all;\n// recovering needs a re-auth from the browser's parked session\n//\n// Deliberately no UI wording here — how a state reads to a user is each host's\n// i18n, and core owning it would make the shared package a translation authority.\nexport const RUNNER_HEALTH_STATES = [\"online\", \"reconnecting\", \"offline\"] as const;\nexport type RunnerHealthState = (typeof RUNNER_HEALTH_STATES)[number];\n\nexport interface RunnerHealth {\n state: RunnerHealthState;\n /** Last channel error seen, for the popover and the log. Null before the first one. */\n lastError: string | null;\n /** ms epoch of the last state change, so the UI can say how long it has been down. */\n changedAt: number;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null;\n\nexport const isRunnerHealthState = (value: unknown): value is RunnerHealthState => RUNNER_HEALTH_STATES.some((state) => state === value);\n\n/** Narrows a parsed HTTP payload. The client renders whatever this accepts, so a\n * half-shaped health has to read as \"no health reported\" rather than as a state. */\nexport const isRunnerHealth = (value: unknown): value is RunnerHealth =>\n isRecord(value) &&\n isRunnerHealthState(value.state) &&\n (value.lastError === null || typeof value.lastError === \"string\") &&\n typeof value.changedAt === \"number\";\n","// Remote-host command-channel protocol — the browser-safe contract shared by a\n// host (MulmoClaude, MulmoTerminal) and the remote/mobile client (mulmoserver).\n//\n// A host signs in to Firebase as the user, listens to that user's per-host\n// command queue in Firestore, runs a handler, and writes the result back; the\n// remote writes commands and reads results via a real-time listener. This module\n// owns the wire types + the Firestore path helpers. It is the single source of\n// truth so the host runner and the client never drift on the protocol.\n//\n// Ported from ../mulmoserver/src/firestore/commandChannel.ts and the per-host\n// copy that lived in MulmoClaude's server/remoteHost/. The one change vs. those\n// copies: the path helpers take the `firestore` instance as a parameter (rather\n// than importing a module-level singleton) so a single extracted module serves\n// every host's own Firebase init. The hostId is host-specific (\"mulmoclaude\",\n// \"mulmoterminal\") and is supplied by each host.\nimport { CollectionReference, DocumentData, DocumentReference, Firestore, collection, doc } from \"firebase/firestore\";\nimport { isRecord } from \"@mulmoclaude/common\";\n\n// JSON payloads carried by the command channel. Explicit JSON types keep the\n// channel typed without resorting to any/unknown.\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\nexport type JsonObject = Record<string, JsonValue>;\n\n/** Structural JSON view of `T`, recursively.\n *\n * TypeScript gives an implicit index signature to type aliases and mapped\n * types but NOT to interfaces, so a payload assembled from domain interfaces\n * (`Shortcut`, `FeedSummary`, …) cannot satisfy `Record<string, JsonValue>`\n * structurally — even though it is plain JSON at runtime. Mapping over `T`\n * reconstructs it as an anonymous type, which does get that index signature.\n *\n * Recursive on purpose: a top-level-only map would still leave nested\n * interfaces (`{ shortcuts: Shortcut[] }`) unassignable, which is the case\n * every handler here actually has. */\n// The function branch must come BEFORE the object branch: a function IS an\n// object to TypeScript, so without it a function maps to `{}` and sails\n// through — the helper would accept a payload that serialises to nothing.\n// Verified: `toJsonObject({ callback: () => undefined })` compiled clean until\n// this branch existed (CodeRabbit, #2596).\nexport type Jsonify<T> = T extends JsonValue\n ? T\n : T extends (...args: never[]) => unknown\n ? never\n : T extends (infer U)[]\n ? Jsonify<U>[]\n : T extends object\n ? { [K in keyof T]: Jsonify<T[K]> }\n : never;\n\n/** Widen a JSON-shaped handler payload to the channel's `JsonObject`.\n *\n * Exists so the `Jsonify` reasoning above lives in ONE place. Before this,\n * eight remote-host handlers each carried their own `as unknown as JsonObject`\n * with the justification re-argued in eight slightly different comments —\n * which is how a rule stops being reviewable. */\nexport const toJsonObject = <T extends object>(payload: Jsonify<T>): JsonObject => payload as JsonObject;\n\nconst describeNonJson = (value: unknown): string => {\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"object\") return \"a non-plain object\";\n return `a ${typeof value}`;\n};\n\n/** Anything carrying its own JSON form — `Date` above all — must be asked for\n * it rather than walked, because walking a `Date`'s own enumerable keys finds\n * none and flattens the timestamp to `{}`. This is the step `JSON.stringify`\n * performs before it recurses, and the channel used to get it for free. */\nconst hasToJson = (value: object): value is { toJSON: () => unknown } => \"toJSON\" in value && typeof value.toJSON === \"function\";\n\nconst jsonRepresentationOf = (value: object): unknown => (hasToJson(value) ? value.toJSON() : value);\n\n/** Rebuild `value` as JSON, or throw naming the property that cannot be. */\nfunction toJsonValue(value: unknown, path: string): JsonValue {\n if (Array.isArray(value)) return toJsonItems(value, path);\n if (isRecord(value)) {\n const represented = jsonRepresentationOf(value);\n if (represented !== value) return toJsonValue(represented, path);\n return toJsonEntries(value, path);\n }\n return toJsonScalar(value, path);\n}\n\n/** JSON's four scalar forms. Anything else — a function, a class instance, a\n * non-finite number — is what the channel cannot carry. */\nfunction toJsonScalar(value: unknown, path: string): JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw new Error(`${path} is ${describeNonJson(value)}, which JSON cannot represent`);\n}\n\nfunction toJsonItems(items: unknown[], path: string): JsonValue[] {\n // An absent element becomes `null`, matching `JSON.stringify` — an array has\n // to keep its length, so a hole cannot simply be dropped the way a key is.\n // `Array.from` rather than `map`, which SKIPS holes and would leave them in\n // the result: `JSON.stringify` renders a hole as null and hides that, but\n // `1 in arr` / `Object.keys` / `forEach` all still see the gap.\n return Array.from(items, (entry, index) => (entry === undefined ? null : toJsonValue(entry, `${path}[${index}]`)));\n}\n\nfunction toJsonEntries(record: Record<string, unknown>, path: string): JsonObject {\n const usable = Object.entries(record).filter(([, value]) => value !== undefined);\n return Object.fromEntries(usable.map(([key, value]) => [key, toJsonValue(value, `${path}.${key}`)]));\n}\n\n/** Runtime counterpart to `toJsonObject`, for payloads whose values are typed\n * `unknown` — a collection record, a projected view row — so no amount of\n * mapped-type work can PROVE them JSON.\n *\n * Walks the payload and rebuilds it from the values it actually inspected, so\n * the returned `JsonObject` is earned rather than asserted. Absent (`undefined`)\n * properties are dropped exactly as `JSON.stringify` drops them; anything the\n * channel could not carry — a function, a class instance, `NaN` — throws\n * naming its path, instead of reaching Firestore as a silently mangled write. */\nexport const coerceJsonObject = (payload: Record<string, unknown>): JsonObject => toJsonEntries(payload, \"payload\");\n\n// A channel routes commands to one specific host. A host's first machine uses the\n// host's fixed id (\"mulmoclaude\", \"mulmoterminal\"); a host that runs on several\n// machines gives each later one \"<id>-<8 hex>\" (RemoteHostDeps.resolveHostId), and\n// the remote finds those by listing users/{uid}/hosts.\nexport interface Channel {\n uid: string;\n hostId: string;\n}\n\nexport type CommandStatus = \"queued\" | \"processing\" | \"done\" | \"error\";\n\nexport interface CommandError {\n code: string;\n message: string;\n}\n\n// One document in a channel's commands subcollection is one API-call-like\n// request. The remote (mobile) writes method/params; the host writes\n// result/error/status.\nexport interface Command {\n method: string;\n params: JsonObject;\n status: CommandStatus;\n result: JsonValue;\n error: CommandError | null;\n createdBy: \"remote\" | \"host\";\n // Offline-queue fields (all optional; absent ⇒ pre-offline-queue behaviour, so\n // this is backward-compatible with every deployed client). Epoch-millisecond\n // NUMBERS set by the remote at enqueue time — deliberately plain numbers, not\n // Firestore Timestamps, so `isExpired` / `byCreatedAt` stay pure + browser-safe\n // and unit-testable without a Firestore fake. Clock skew over a multi-day expiry\n // window is immaterial. See plans/done/feat-remote-offline-queue.md.\n createdAt?: number; // enqueue time — age/display + best-effort dispatch bias (NOT a strict order guarantee; chat is async)\n expiresAt?: number; // deadline; past it the host deletes the command + its staged attachments\n queuedOffline?: boolean; // emitted while the host was offline (gates the remote's attachment rollback)\n}\n\n// A command is expired once `now` reaches its remote-set deadline. Absent\n// `expiresAt` ⇒ it never expires (pre-offline-queue commands). Pure with an\n// injected `now` for deterministic tests; the runner passes `Date.now()`.\nexport const isExpired = (command: Pick<Command, \"expiresAt\">, now: number): boolean => typeof command.expiresAt === \"number\" && now >= command.expiresAt;\n\n// Best-effort dispatch bias for a drained batch: oldest enqueue first. This is\n// NOT an ordering guarantee — commands run concurrently and may complete out of\n// order (chat is asynchronous, by design); it only nudges which one starts first.\n// A command with no `createdAt` sorts as oldest (0) so it is never starved.\nexport const byCreatedAt = (left: Pick<Command, \"createdAt\">, right: Pick<Command, \"createdAt\">): number => (left.createdAt ?? 0) - (right.createdAt ?? 0);\n\nexport type CommandHandler = (params: JsonObject) => JsonValue | Promise<JsonValue>;\nexport type CommandHandlers = Record<string, CommandHandler>;\n\n/** The param name a collection-serving command uses to say WHICH project's\n * collections it means. Reserved and documented now, before a phone client\n * ships, because the parts that are hard to change later are the ones being\n * written today. Four rules go with it:\n *\n * 1. **It is an OPAQUE scope, never a path.** The phone is a genuinely remote\n * client; an absolute root in a command, an artifact or a token publishes\n * the user's home directory over the wire. Mint a project id host-side and\n * resolve it host-side.\n * 2. **The phone must be able to LEARN the list.** A picker needs\n * `{ id, label }` pairs from the host — a command of its own, or a field on\n * an existing listing. Designing the scope value now is what keeps that the\n * ONLY new thing when the feature lands.\n * 3. **Handlers RESOLVE a scope; they do not hard-code one.** Write each\n * collection handler as \"read the scope from params, defaulting to the\n * host's root\" rather than calling the workspace accessor inline. Today\n * every call resolves the default and behaves exactly as it does now; the\n * day the param arrives, no handler changes.\n * 4. **The artifact stays host-built.** A remote view's srcdoc, its inlined\n * image thumbnails and its token are assembled on the host, so the phone\n * never resolves a path itself. That is what makes (1) hold without\n * trusting the client. */\nexport const COMMAND_SCOPE_PARAM = \"project\";\n\n/** Read the opaque project scope off a command's params, or `undefined` for\n * \"the host's own root\" — which is what every command means today. A\n * non-string (or empty) value is treated as absent rather than as an error: a\n * scope the host cannot resolve must fall back to the default, never to a\n * guess. Hosts pass the result to their own id → root resolver; this module\n * deliberately never sees a path. */\nexport const readCommandScope = (params: JsonObject): string | undefined => {\n const raw = params[COMMAND_SCOPE_PARAM];\n return typeof raw === \"string\" && raw.trim().length > 0 ? raw.trim() : undefined;\n};\n\n// Bumped when the command-channel wire protocol changes in a way the remote must\n// gate on. Advertised in the presence doc so the remote can check compatibility\n// before issuing commands.\n//\n// v2: offline queueing. The host honours `expiresAt` (deletes an expired command\n// + its staged attachments instead of spawning a stale chat). A remote MUST see\n// protocolVersion >= 2 before queueing a startChat while the host is offline —\n// a v1 host silently ignores `expiresAt`, so a queued chat would spawn stale on\n// reconnect with its uploads never cleaned up.\nexport const REMOTE_HOST_PROTOCOL_VERSION = 2;\n\n// The presence doc's payload: online flag + a capability advertisement. Written\n// by the host on every heartbeat; the remote reads it from the presence listener\n// it already runs (no extra round trip, known the instant the host is online).\n// Browser-safe so the mobile client compiles against the same shape.\n// `updatedAt` (a Firestore serverTimestamp) is added by the runner at write time\n// and is intentionally not part of this capability contract.\n// Which machine a presence comes from, for a host that can run on several machines\n// under one account (mulmoterminal#3092): a stable id the host recognises itself by,\n// and the name the remote shows for it.\nexport interface HostMachine {\n machineId: string;\n label: string;\n}\n\nexport interface HostPresence {\n online: boolean;\n hostId: string;\n protocolVersion: number;\n // Method names the host serves — the keys of the live handler table.\n capabilities: string[];\n machineId?: string;\n label?: string;\n}\n\n// Build the presence payload from the live handler table. Capabilities are\n// `Object.keys(handlers)` so registering a handler is the ONLY step needed to\n// advertise it — there is no second list to keep in sync.\nexport const buildHostPresence = (channel: Channel, handlers: CommandHandlers, online: boolean, machine?: HostMachine): HostPresence => ({\n online,\n hostId: channel.hostId,\n protocolVersion: REMOTE_HOST_PROTOCOL_VERSION,\n capabilities: Object.keys(handlers),\n ...(machine ? { machineId: machine.machineId, label: machine.label } : {}),\n});\n\n// Per-host command queue: users/{uid}/hosts/{hostId}/commands.\nexport const commandsCollection = (firestore: Firestore, channel: Channel): CollectionReference<DocumentData> =>\n collection(firestore, \"users\", channel.uid, \"hosts\", channel.hostId, \"commands\");\n\n// Presence doc for a host: users/{uid}/hosts/{hostId}. The host heartbeats\n// { online, updatedAt } here; the remote reads it to know if the host is up.\nexport const hostDoc = (firestore: Firestore, channel: Channel): DocumentReference<DocumentData> =>\n doc(firestore, \"users\", channel.uid, \"hosts\", channel.hostId);\n\n// Channel health as the resilient runner reports it. Browser-safe alongside the\n// wire types because the control that renders it runs in the client.\nexport { RUNNER_HEALTH_STATES, isRunnerHealth, isRunnerHealthState } from \"./health.js\";\nexport type { RunnerHealth, RunnerHealthState } from \"./health.js\";\n"],"mappings":";;;AAYA,IAAa,uBAAuB;CAAC;CAAU;CAAgB;AAAS;AAWxE,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU;AAE9G,IAAa,uBAAuB,UAA+C,qBAAqB,MAAM,UAAU,UAAU,KAAK;;;AAIvI,IAAa,kBAAkB,UAC7B,SAAS,KAAK,KACd,oBAAoB,MAAM,KAAK,MAC9B,MAAM,cAAc,QAAQ,OAAO,MAAM,cAAc,aACxD,OAAO,MAAM,cAAc;;;;;;;;ACsB7B,IAAa,gBAAkC,YAAoC;AAEnF,IAAM,mBAAmB,UAA2B;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,OAAO,KAAK,OAAO;AACrB;;;;;AAMA,IAAM,aAAa,UAAsD,YAAY,SAAS,OAAO,MAAM,WAAW;AAEtH,IAAM,wBAAwB,UAA4B,UAAU,KAAK,IAAI,MAAM,OAAO,IAAI;;AAG9F,SAAS,YAAY,OAAgB,MAAyB;CAC5D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IAAI,KAAK,CAAC,CAAC,SAAS,IAAI,IAAI,KAAK,IAAI,KAAA;AACzE;AAWA,IAAa,+BAA+B;AA6B5C,IAAa,qBAAqB,SAAkB,UAA2B,QAAiB,aAAyC;CACvI;CACA,QAAQ,QAAQ;CAChB,iBAAA;CACA,cAAc,OAAO,KAAK,QAAQ;CAClC,GAAI,UAAU;EAAE,WAAW,QAAQ;EAAW,OAAO,QAAQ;CAAM,IAAI,CAAC;AAC1E;AAGA,IAAa,sBAAsB,WAAsB,aAAA,GACvDC,mBAAAA,WAAAA,CAAW,WAAW,SAAS,QAAQ,KAAK,SAAS,QAAQ,QAAQ,UAAU;AAIjF,IAAa,WAAW,WAAsB,aAAA,GAC5CC,mBAAAA,IAAAA,CAAI,WAAW,SAAS,QAAQ,KAAK,SAAS,QAAQ,MAAM"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { c as isRecord$1 } from "./dist-
|
|
1
|
+
import { c as isRecord$1 } from "./dist-BmO4oSQy.js";
|
|
2
2
|
import { collection, doc } from "firebase/firestore";
|
|
3
|
-
|
|
3
|
+
// src/remote-host/health.ts
|
|
4
4
|
var RUNNER_HEALTH_STATES = [
|
|
5
5
|
"online",
|
|
6
6
|
"reconnecting",
|
|
@@ -11,8 +11,7 @@ var isRunnerHealthState = (value) => RUNNER_HEALTH_STATES.some((state) => state
|
|
|
11
11
|
/** Narrows a parsed HTTP payload. The client renders whatever this accepts, so a
|
|
12
12
|
* half-shaped health has to read as "no health reported" rather than as a state. */
|
|
13
13
|
var isRunnerHealth = (value) => isRecord(value) && isRunnerHealthState(value.state) && (value.lastError === null || typeof value.lastError === "string") && typeof value.changedAt === "number";
|
|
14
|
-
|
|
15
|
-
//#region src/remote-host/index.ts
|
|
14
|
+
// src/remote-host/index.ts
|
|
16
15
|
/** Widen a JSON-shaped handler payload to the channel's `JsonObject`.
|
|
17
16
|
*
|
|
18
17
|
* Exists so the `Jsonify` reasoning above lives in ONE place. Before this,
|
|
@@ -113,7 +112,6 @@ var buildHostPresence = (channel, handlers, online, machine) => ({
|
|
|
113
112
|
});
|
|
114
113
|
var commandsCollection = (firestore, channel) => collection(firestore, "users", channel.uid, "hosts", channel.hostId, "commands");
|
|
115
114
|
var hostDoc = (firestore, channel) => doc(firestore, "users", channel.uid, "hosts", channel.hostId);
|
|
116
|
-
//#endregion
|
|
117
115
|
export { coerceJsonObject as a, isExpired as c, RUNNER_HEALTH_STATES as d, isRunnerHealth as f, byCreatedAt as i, readCommandScope as l, REMOTE_HOST_PROTOCOL_VERSION as n, commandsCollection as o, isRunnerHealthState as p, buildHostPresence as r, hostDoc as s, COMMAND_SCOPE_PARAM as t, toJsonObject as u };
|
|
118
116
|
|
|
119
|
-
//# sourceMappingURL=remote-host-
|
|
117
|
+
//# sourceMappingURL=remote-host-CSeDNbE6.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"remote-host-9NNAvUhU.js","names":["isRecord"],"sources":["../src/remote-host/health.ts","../src/remote-host/index.ts"],"sourcesContent":["// Health of the remote-host command channel, as reported by the resilient runner\n// and rendered by a host's toolbar control. Browser-safe on purpose: the client\n// narrows the parsed HTTP payload with the same guard the server writes it from,\n// so the two sides cannot drift on the state names.\n//\n// online — the Firestore subscription is up; the phone can reach this host\n// reconnecting — it died and is being re-subscribed with backoff (self-healing)\n// offline — re-subscribing stopped helping, or nothing is connected at all;\n// recovering needs a re-auth from the browser's parked session\n//\n// Deliberately no UI wording here — how a state reads to a user is each host's\n// i18n, and core owning it would make the shared package a translation authority.\nexport const RUNNER_HEALTH_STATES = [\"online\", \"reconnecting\", \"offline\"] as const;\nexport type RunnerHealthState = (typeof RUNNER_HEALTH_STATES)[number];\n\nexport interface RunnerHealth {\n state: RunnerHealthState;\n /** Last channel error seen, for the popover and the log. Null before the first one. */\n lastError: string | null;\n /** ms epoch of the last state change, so the UI can say how long it has been down. */\n changedAt: number;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null;\n\nexport const isRunnerHealthState = (value: unknown): value is RunnerHealthState => RUNNER_HEALTH_STATES.some((state) => state === value);\n\n/** Narrows a parsed HTTP payload. The client renders whatever this accepts, so a\n * half-shaped health has to read as \"no health reported\" rather than as a state. */\nexport const isRunnerHealth = (value: unknown): value is RunnerHealth =>\n isRecord(value) &&\n isRunnerHealthState(value.state) &&\n (value.lastError === null || typeof value.lastError === \"string\") &&\n typeof value.changedAt === \"number\";\n","// Remote-host command-channel protocol — the browser-safe contract shared by a\n// host (MulmoClaude, MulmoTerminal) and the remote/mobile client (mulmoserver).\n//\n// A host signs in to Firebase as the user, listens to that user's per-host\n// command queue in Firestore, runs a handler, and writes the result back; the\n// remote writes commands and reads results via a real-time listener. This module\n// owns the wire types + the Firestore path helpers. It is the single source of\n// truth so the host runner and the client never drift on the protocol.\n//\n// Ported from ../mulmoserver/src/firestore/commandChannel.ts and the per-host\n// copy that lived in MulmoClaude's server/remoteHost/. The one change vs. those\n// copies: the path helpers take the `firestore` instance as a parameter (rather\n// than importing a module-level singleton) so a single extracted module serves\n// every host's own Firebase init. The hostId is host-specific (\"mulmoclaude\",\n// \"mulmoterminal\") and is supplied by each host.\nimport { CollectionReference, DocumentData, DocumentReference, Firestore, collection, doc } from \"firebase/firestore\";\nimport { isRecord } from \"@mulmoclaude/common\";\n\n// JSON payloads carried by the command channel. Explicit JSON types keep the\n// channel typed without resorting to any/unknown.\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\nexport type JsonObject = Record<string, JsonValue>;\n\n/** Structural JSON view of `T`, recursively.\n *\n * TypeScript gives an implicit index signature to type aliases and mapped\n * types but NOT to interfaces, so a payload assembled from domain interfaces\n * (`Shortcut`, `FeedSummary`, …) cannot satisfy `Record<string, JsonValue>`\n * structurally — even though it is plain JSON at runtime. Mapping over `T`\n * reconstructs it as an anonymous type, which does get that index signature.\n *\n * Recursive on purpose: a top-level-only map would still leave nested\n * interfaces (`{ shortcuts: Shortcut[] }`) unassignable, which is the case\n * every handler here actually has. */\n// The function branch must come BEFORE the object branch: a function IS an\n// object to TypeScript, so without it a function maps to `{}` and sails\n// through — the helper would accept a payload that serialises to nothing.\n// Verified: `toJsonObject({ callback: () => undefined })` compiled clean until\n// this branch existed (CodeRabbit, #2596).\nexport type Jsonify<T> = T extends JsonValue\n ? T\n : T extends (...args: never[]) => unknown\n ? never\n : T extends (infer U)[]\n ? Jsonify<U>[]\n : T extends object\n ? { [K in keyof T]: Jsonify<T[K]> }\n : never;\n\n/** Widen a JSON-shaped handler payload to the channel's `JsonObject`.\n *\n * Exists so the `Jsonify` reasoning above lives in ONE place. Before this,\n * eight remote-host handlers each carried their own `as unknown as JsonObject`\n * with the justification re-argued in eight slightly different comments —\n * which is how a rule stops being reviewable. */\nexport const toJsonObject = <T extends object>(payload: Jsonify<T>): JsonObject => payload as JsonObject;\n\nconst describeNonJson = (value: unknown): string => {\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"object\") return \"a non-plain object\";\n return `a ${typeof value}`;\n};\n\n/** Anything carrying its own JSON form — `Date` above all — must be asked for\n * it rather than walked, because walking a `Date`'s own enumerable keys finds\n * none and flattens the timestamp to `{}`. This is the step `JSON.stringify`\n * performs before it recurses, and the channel used to get it for free. */\nconst hasToJson = (value: object): value is { toJSON: () => unknown } => \"toJSON\" in value && typeof value.toJSON === \"function\";\n\nconst jsonRepresentationOf = (value: object): unknown => (hasToJson(value) ? value.toJSON() : value);\n\n/** Rebuild `value` as JSON, or throw naming the property that cannot be. */\nfunction toJsonValue(value: unknown, path: string): JsonValue {\n if (Array.isArray(value)) return toJsonItems(value, path);\n if (isRecord(value)) {\n const represented = jsonRepresentationOf(value);\n if (represented !== value) return toJsonValue(represented, path);\n return toJsonEntries(value, path);\n }\n return toJsonScalar(value, path);\n}\n\n/** JSON's four scalar forms. Anything else — a function, a class instance, a\n * non-finite number — is what the channel cannot carry. */\nfunction toJsonScalar(value: unknown, path: string): JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw new Error(`${path} is ${describeNonJson(value)}, which JSON cannot represent`);\n}\n\nfunction toJsonItems(items: unknown[], path: string): JsonValue[] {\n // An absent element becomes `null`, matching `JSON.stringify` — an array has\n // to keep its length, so a hole cannot simply be dropped the way a key is.\n // `Array.from` rather than `map`, which SKIPS holes and would leave them in\n // the result: `JSON.stringify` renders a hole as null and hides that, but\n // `1 in arr` / `Object.keys` / `forEach` all still see the gap.\n return Array.from(items, (entry, index) => (entry === undefined ? null : toJsonValue(entry, `${path}[${index}]`)));\n}\n\nfunction toJsonEntries(record: Record<string, unknown>, path: string): JsonObject {\n const usable = Object.entries(record).filter(([, value]) => value !== undefined);\n return Object.fromEntries(usable.map(([key, value]) => [key, toJsonValue(value, `${path}.${key}`)]));\n}\n\n/** Runtime counterpart to `toJsonObject`, for payloads whose values are typed\n * `unknown` — a collection record, a projected view row — so no amount of\n * mapped-type work can PROVE them JSON.\n *\n * Walks the payload and rebuilds it from the values it actually inspected, so\n * the returned `JsonObject` is earned rather than asserted. Absent (`undefined`)\n * properties are dropped exactly as `JSON.stringify` drops them; anything the\n * channel could not carry — a function, a class instance, `NaN` — throws\n * naming its path, instead of reaching Firestore as a silently mangled write. */\nexport const coerceJsonObject = (payload: Record<string, unknown>): JsonObject => toJsonEntries(payload, \"payload\");\n\n// A channel routes commands to one specific host. A host's first machine uses the\n// host's fixed id (\"mulmoclaude\", \"mulmoterminal\"); a host that runs on several\n// machines gives each later one \"<id>-<8 hex>\" (RemoteHostDeps.resolveHostId), and\n// the remote finds those by listing users/{uid}/hosts.\nexport interface Channel {\n uid: string;\n hostId: string;\n}\n\nexport type CommandStatus = \"queued\" | \"processing\" | \"done\" | \"error\";\n\nexport interface CommandError {\n code: string;\n message: string;\n}\n\n// One document in a channel's commands subcollection is one API-call-like\n// request. The remote (mobile) writes method/params; the host writes\n// result/error/status.\nexport interface Command {\n method: string;\n params: JsonObject;\n status: CommandStatus;\n result: JsonValue;\n error: CommandError | null;\n createdBy: \"remote\" | \"host\";\n // Offline-queue fields (all optional; absent ⇒ pre-offline-queue behaviour, so\n // this is backward-compatible with every deployed client). Epoch-millisecond\n // NUMBERS set by the remote at enqueue time — deliberately plain numbers, not\n // Firestore Timestamps, so `isExpired` / `byCreatedAt` stay pure + browser-safe\n // and unit-testable without a Firestore fake. Clock skew over a multi-day expiry\n // window is immaterial. See plans/done/feat-remote-offline-queue.md.\n createdAt?: number; // enqueue time — age/display + best-effort dispatch bias (NOT a strict order guarantee; chat is async)\n expiresAt?: number; // deadline; past it the host deletes the command + its staged attachments\n queuedOffline?: boolean; // emitted while the host was offline (gates the remote's attachment rollback)\n}\n\n// A command is expired once `now` reaches its remote-set deadline. Absent\n// `expiresAt` ⇒ it never expires (pre-offline-queue commands). Pure with an\n// injected `now` for deterministic tests; the runner passes `Date.now()`.\nexport const isExpired = (command: Pick<Command, \"expiresAt\">, now: number): boolean => typeof command.expiresAt === \"number\" && now >= command.expiresAt;\n\n// Best-effort dispatch bias for a drained batch: oldest enqueue first. This is\n// NOT an ordering guarantee — commands run concurrently and may complete out of\n// order (chat is asynchronous, by design); it only nudges which one starts first.\n// A command with no `createdAt` sorts as oldest (0) so it is never starved.\nexport const byCreatedAt = (left: Pick<Command, \"createdAt\">, right: Pick<Command, \"createdAt\">): number => (left.createdAt ?? 0) - (right.createdAt ?? 0);\n\nexport type CommandHandler = (params: JsonObject) => JsonValue | Promise<JsonValue>;\nexport type CommandHandlers = Record<string, CommandHandler>;\n\n/** The param name a collection-serving command uses to say WHICH project's\n * collections it means. Reserved and documented now, before a phone client\n * ships, because the parts that are hard to change later are the ones being\n * written today. Four rules go with it:\n *\n * 1. **It is an OPAQUE scope, never a path.** The phone is a genuinely remote\n * client; an absolute root in a command, an artifact or a token publishes\n * the user's home directory over the wire. Mint a project id host-side and\n * resolve it host-side.\n * 2. **The phone must be able to LEARN the list.** A picker needs\n * `{ id, label }` pairs from the host — a command of its own, or a field on\n * an existing listing. Designing the scope value now is what keeps that the\n * ONLY new thing when the feature lands.\n * 3. **Handlers RESOLVE a scope; they do not hard-code one.** Write each\n * collection handler as \"read the scope from params, defaulting to the\n * host's root\" rather than calling the workspace accessor inline. Today\n * every call resolves the default and behaves exactly as it does now; the\n * day the param arrives, no handler changes.\n * 4. **The artifact stays host-built.** A remote view's srcdoc, its inlined\n * image thumbnails and its token are assembled on the host, so the phone\n * never resolves a path itself. That is what makes (1) hold without\n * trusting the client. */\nexport const COMMAND_SCOPE_PARAM = \"project\";\n\n/** Read the opaque project scope off a command's params, or `undefined` for\n * \"the host's own root\" — which is what every command means today. A\n * non-string (or empty) value is treated as absent rather than as an error: a\n * scope the host cannot resolve must fall back to the default, never to a\n * guess. Hosts pass the result to their own id → root resolver; this module\n * deliberately never sees a path. */\nexport const readCommandScope = (params: JsonObject): string | undefined => {\n const raw = params[COMMAND_SCOPE_PARAM];\n return typeof raw === \"string\" && raw.trim().length > 0 ? raw.trim() : undefined;\n};\n\n// Bumped when the command-channel wire protocol changes in a way the remote must\n// gate on. Advertised in the presence doc so the remote can check compatibility\n// before issuing commands.\n//\n// v2: offline queueing. The host honours `expiresAt` (deletes an expired command\n// + its staged attachments instead of spawning a stale chat). A remote MUST see\n// protocolVersion >= 2 before queueing a startChat while the host is offline —\n// a v1 host silently ignores `expiresAt`, so a queued chat would spawn stale on\n// reconnect with its uploads never cleaned up.\nexport const REMOTE_HOST_PROTOCOL_VERSION = 2;\n\n// The presence doc's payload: online flag + a capability advertisement. Written\n// by the host on every heartbeat; the remote reads it from the presence listener\n// it already runs (no extra round trip, known the instant the host is online).\n// Browser-safe so the mobile client compiles against the same shape.\n// `updatedAt` (a Firestore serverTimestamp) is added by the runner at write time\n// and is intentionally not part of this capability contract.\n// Which machine a presence comes from, for a host that can run on several machines\n// under one account (mulmoterminal#3092): a stable id the host recognises itself by,\n// and the name the remote shows for it.\nexport interface HostMachine {\n machineId: string;\n label: string;\n}\n\nexport interface HostPresence {\n online: boolean;\n hostId: string;\n protocolVersion: number;\n // Method names the host serves — the keys of the live handler table.\n capabilities: string[];\n machineId?: string;\n label?: string;\n}\n\n// Build the presence payload from the live handler table. Capabilities are\n// `Object.keys(handlers)` so registering a handler is the ONLY step needed to\n// advertise it — there is no second list to keep in sync.\nexport const buildHostPresence = (channel: Channel, handlers: CommandHandlers, online: boolean, machine?: HostMachine): HostPresence => ({\n online,\n hostId: channel.hostId,\n protocolVersion: REMOTE_HOST_PROTOCOL_VERSION,\n capabilities: Object.keys(handlers),\n ...(machine ? { machineId: machine.machineId, label: machine.label } : {}),\n});\n\n// Per-host command queue: users/{uid}/hosts/{hostId}/commands.\nexport const commandsCollection = (firestore: Firestore, channel: Channel): CollectionReference<DocumentData> =>\n collection(firestore, \"users\", channel.uid, \"hosts\", channel.hostId, \"commands\");\n\n// Presence doc for a host: users/{uid}/hosts/{hostId}. The host heartbeats\n// { online, updatedAt } here; the remote reads it to know if the host is up.\nexport const hostDoc = (firestore: Firestore, channel: Channel): DocumentReference<DocumentData> =>\n doc(firestore, \"users\", channel.uid, \"hosts\", channel.hostId);\n\n// Channel health as the resilient runner reports it. Browser-safe alongside the\n// wire types because the control that renders it runs in the client.\nexport { RUNNER_HEALTH_STATES, isRunnerHealth, isRunnerHealthState } from \"./health.js\";\nexport type { RunnerHealth, RunnerHealthState } from \"./health.js\";\n"],"mappings":";;;AAYA,IAAa,uBAAuB;CAAC;CAAU;CAAgB;AAAS;AAWxE,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU;AAE9G,IAAa,uBAAuB,UAA+C,qBAAqB,MAAM,UAAU,UAAU,KAAK;;;AAIvI,IAAa,kBAAkB,UAC7B,SAAS,KAAK,KACd,oBAAoB,MAAM,KAAK,MAC9B,MAAM,cAAc,QAAQ,OAAO,MAAM,cAAc,aACxD,OAAO,MAAM,cAAc;;;;;;;;;ACsB7B,IAAa,gBAAkC,YAAoC;AAEnF,IAAM,mBAAmB,UAA2B;CAClD,IAAI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,SAAqC,QAAyB,OAAO,QAAQ,cAAc,YAAY,OAAO,QAAQ;AAMhJ,IAAa,eAAe,MAAkC,WAA+C,KAAK,aAAa,MAAM,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;AA2BxJ,IAAa,sBAAsB;;;;;;;AAQnC,IAAa,oBAAoB,WAA2C;CAC1E,MAAM,MAAM,OAAO;CACnB,OAAO,OAAO,QAAQ,YAAY,IAAI,KAAK,CAAC,CAAC,SAAS,IAAI,IAAI,KAAK,IAAI,KAAA;AACzE;AAWA,IAAa,+BAA+B;AA6B5C,IAAa,qBAAqB,SAAkB,UAA2B,QAAiB,aAAyC;CACvI;CACA,QAAQ,QAAQ;CAChB,iBAAA;CACA,cAAc,OAAO,KAAK,QAAQ;CAClC,GAAI,UAAU;EAAE,WAAW,QAAQ;EAAW,OAAO,QAAQ;CAAM,IAAI,CAAC;AAC1E;AAGA,IAAa,sBAAsB,WAAsB,YACvD,WAAW,WAAW,SAAS,QAAQ,KAAK,SAAS,QAAQ,QAAQ,UAAU;AAIjF,IAAa,WAAW,WAAsB,YAC5C,IAAI,WAAW,SAAS,QAAQ,KAAK,SAAS,QAAQ,MAAM"}
|
|
1
|
+
{"version":3,"file":"remote-host-CSeDNbE6.js","names":["isRecord"],"sources":["../src/remote-host/health.ts","../src/remote-host/index.ts"],"sourcesContent":["// Health of the remote-host command channel, as reported by the resilient runner\n// and rendered by a host's toolbar control. Browser-safe on purpose: the client\n// narrows the parsed HTTP payload with the same guard the server writes it from,\n// so the two sides cannot drift on the state names.\n//\n// online — the Firestore subscription is up; the phone can reach this host\n// reconnecting — it died and is being re-subscribed with backoff (self-healing)\n// offline — re-subscribing stopped helping, or nothing is connected at all;\n// recovering needs a re-auth from the browser's parked session\n//\n// Deliberately no UI wording here — how a state reads to a user is each host's\n// i18n, and core owning it would make the shared package a translation authority.\nexport const RUNNER_HEALTH_STATES = [\"online\", \"reconnecting\", \"offline\"] as const;\nexport type RunnerHealthState = (typeof RUNNER_HEALTH_STATES)[number];\n\nexport interface RunnerHealth {\n state: RunnerHealthState;\n /** Last channel error seen, for the popover and the log. Null before the first one. */\n lastError: string | null;\n /** ms epoch of the last state change, so the UI can say how long it has been down. */\n changedAt: number;\n}\n\nconst isRecord = (value: unknown): value is Record<string, unknown> => typeof value === \"object\" && value !== null;\n\nexport const isRunnerHealthState = (value: unknown): value is RunnerHealthState => RUNNER_HEALTH_STATES.some((state) => state === value);\n\n/** Narrows a parsed HTTP payload. The client renders whatever this accepts, so a\n * half-shaped health has to read as \"no health reported\" rather than as a state. */\nexport const isRunnerHealth = (value: unknown): value is RunnerHealth =>\n isRecord(value) &&\n isRunnerHealthState(value.state) &&\n (value.lastError === null || typeof value.lastError === \"string\") &&\n typeof value.changedAt === \"number\";\n","// Remote-host command-channel protocol — the browser-safe contract shared by a\n// host (MulmoClaude, MulmoTerminal) and the remote/mobile client (mulmoserver).\n//\n// A host signs in to Firebase as the user, listens to that user's per-host\n// command queue in Firestore, runs a handler, and writes the result back; the\n// remote writes commands and reads results via a real-time listener. This module\n// owns the wire types + the Firestore path helpers. It is the single source of\n// truth so the host runner and the client never drift on the protocol.\n//\n// Ported from ../mulmoserver/src/firestore/commandChannel.ts and the per-host\n// copy that lived in MulmoClaude's server/remoteHost/. The one change vs. those\n// copies: the path helpers take the `firestore` instance as a parameter (rather\n// than importing a module-level singleton) so a single extracted module serves\n// every host's own Firebase init. The hostId is host-specific (\"mulmoclaude\",\n// \"mulmoterminal\") and is supplied by each host.\nimport { CollectionReference, DocumentData, DocumentReference, Firestore, collection, doc } from \"firebase/firestore\";\nimport { isRecord } from \"@mulmoclaude/common\";\n\n// JSON payloads carried by the command channel. Explicit JSON types keep the\n// channel typed without resorting to any/unknown.\nexport type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };\nexport type JsonObject = Record<string, JsonValue>;\n\n/** Structural JSON view of `T`, recursively.\n *\n * TypeScript gives an implicit index signature to type aliases and mapped\n * types but NOT to interfaces, so a payload assembled from domain interfaces\n * (`Shortcut`, `FeedSummary`, …) cannot satisfy `Record<string, JsonValue>`\n * structurally — even though it is plain JSON at runtime. Mapping over `T`\n * reconstructs it as an anonymous type, which does get that index signature.\n *\n * Recursive on purpose: a top-level-only map would still leave nested\n * interfaces (`{ shortcuts: Shortcut[] }`) unassignable, which is the case\n * every handler here actually has. */\n// The function branch must come BEFORE the object branch: a function IS an\n// object to TypeScript, so without it a function maps to `{}` and sails\n// through — the helper would accept a payload that serialises to nothing.\n// Verified: `toJsonObject({ callback: () => undefined })` compiled clean until\n// this branch existed (CodeRabbit, #2596).\nexport type Jsonify<T> = T extends JsonValue\n ? T\n : T extends (...args: never[]) => unknown\n ? never\n : T extends (infer U)[]\n ? Jsonify<U>[]\n : T extends object\n ? { [K in keyof T]: Jsonify<T[K]> }\n : never;\n\n/** Widen a JSON-shaped handler payload to the channel's `JsonObject`.\n *\n * Exists so the `Jsonify` reasoning above lives in ONE place. Before this,\n * eight remote-host handlers each carried their own `as unknown as JsonObject`\n * with the justification re-argued in eight slightly different comments —\n * which is how a rule stops being reviewable. */\nexport const toJsonObject = <T extends object>(payload: Jsonify<T>): JsonObject => payload as JsonObject;\n\nconst describeNonJson = (value: unknown): string => {\n if (typeof value === \"number\") return String(value);\n if (typeof value === \"object\") return \"a non-plain object\";\n return `a ${typeof value}`;\n};\n\n/** Anything carrying its own JSON form — `Date` above all — must be asked for\n * it rather than walked, because walking a `Date`'s own enumerable keys finds\n * none and flattens the timestamp to `{}`. This is the step `JSON.stringify`\n * performs before it recurses, and the channel used to get it for free. */\nconst hasToJson = (value: object): value is { toJSON: () => unknown } => \"toJSON\" in value && typeof value.toJSON === \"function\";\n\nconst jsonRepresentationOf = (value: object): unknown => (hasToJson(value) ? value.toJSON() : value);\n\n/** Rebuild `value` as JSON, or throw naming the property that cannot be. */\nfunction toJsonValue(value: unknown, path: string): JsonValue {\n if (Array.isArray(value)) return toJsonItems(value, path);\n if (isRecord(value)) {\n const represented = jsonRepresentationOf(value);\n if (represented !== value) return toJsonValue(represented, path);\n return toJsonEntries(value, path);\n }\n return toJsonScalar(value, path);\n}\n\n/** JSON's four scalar forms. Anything else — a function, a class instance, a\n * non-finite number — is what the channel cannot carry. */\nfunction toJsonScalar(value: unknown, path: string): JsonValue {\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n throw new Error(`${path} is ${describeNonJson(value)}, which JSON cannot represent`);\n}\n\nfunction toJsonItems(items: unknown[], path: string): JsonValue[] {\n // An absent element becomes `null`, matching `JSON.stringify` — an array has\n // to keep its length, so a hole cannot simply be dropped the way a key is.\n // `Array.from` rather than `map`, which SKIPS holes and would leave them in\n // the result: `JSON.stringify` renders a hole as null and hides that, but\n // `1 in arr` / `Object.keys` / `forEach` all still see the gap.\n return Array.from(items, (entry, index) => (entry === undefined ? null : toJsonValue(entry, `${path}[${index}]`)));\n}\n\nfunction toJsonEntries(record: Record<string, unknown>, path: string): JsonObject {\n const usable = Object.entries(record).filter(([, value]) => value !== undefined);\n return Object.fromEntries(usable.map(([key, value]) => [key, toJsonValue(value, `${path}.${key}`)]));\n}\n\n/** Runtime counterpart to `toJsonObject`, for payloads whose values are typed\n * `unknown` — a collection record, a projected view row — so no amount of\n * mapped-type work can PROVE them JSON.\n *\n * Walks the payload and rebuilds it from the values it actually inspected, so\n * the returned `JsonObject` is earned rather than asserted. Absent (`undefined`)\n * properties are dropped exactly as `JSON.stringify` drops them; anything the\n * channel could not carry — a function, a class instance, `NaN` — throws\n * naming its path, instead of reaching Firestore as a silently mangled write. */\nexport const coerceJsonObject = (payload: Record<string, unknown>): JsonObject => toJsonEntries(payload, \"payload\");\n\n// A channel routes commands to one specific host. A host's first machine uses the\n// host's fixed id (\"mulmoclaude\", \"mulmoterminal\"); a host that runs on several\n// machines gives each later one \"<id>-<8 hex>\" (RemoteHostDeps.resolveHostId), and\n// the remote finds those by listing users/{uid}/hosts.\nexport interface Channel {\n uid: string;\n hostId: string;\n}\n\nexport type CommandStatus = \"queued\" | \"processing\" | \"done\" | \"error\";\n\nexport interface CommandError {\n code: string;\n message: string;\n}\n\n// One document in a channel's commands subcollection is one API-call-like\n// request. The remote (mobile) writes method/params; the host writes\n// result/error/status.\nexport interface Command {\n method: string;\n params: JsonObject;\n status: CommandStatus;\n result: JsonValue;\n error: CommandError | null;\n createdBy: \"remote\" | \"host\";\n // Offline-queue fields (all optional; absent ⇒ pre-offline-queue behaviour, so\n // this is backward-compatible with every deployed client). Epoch-millisecond\n // NUMBERS set by the remote at enqueue time — deliberately plain numbers, not\n // Firestore Timestamps, so `isExpired` / `byCreatedAt` stay pure + browser-safe\n // and unit-testable without a Firestore fake. Clock skew over a multi-day expiry\n // window is immaterial. See plans/done/feat-remote-offline-queue.md.\n createdAt?: number; // enqueue time — age/display + best-effort dispatch bias (NOT a strict order guarantee; chat is async)\n expiresAt?: number; // deadline; past it the host deletes the command + its staged attachments\n queuedOffline?: boolean; // emitted while the host was offline (gates the remote's attachment rollback)\n}\n\n// A command is expired once `now` reaches its remote-set deadline. Absent\n// `expiresAt` ⇒ it never expires (pre-offline-queue commands). Pure with an\n// injected `now` for deterministic tests; the runner passes `Date.now()`.\nexport const isExpired = (command: Pick<Command, \"expiresAt\">, now: number): boolean => typeof command.expiresAt === \"number\" && now >= command.expiresAt;\n\n// Best-effort dispatch bias for a drained batch: oldest enqueue first. This is\n// NOT an ordering guarantee — commands run concurrently and may complete out of\n// order (chat is asynchronous, by design); it only nudges which one starts first.\n// A command with no `createdAt` sorts as oldest (0) so it is never starved.\nexport const byCreatedAt = (left: Pick<Command, \"createdAt\">, right: Pick<Command, \"createdAt\">): number => (left.createdAt ?? 0) - (right.createdAt ?? 0);\n\nexport type CommandHandler = (params: JsonObject) => JsonValue | Promise<JsonValue>;\nexport type CommandHandlers = Record<string, CommandHandler>;\n\n/** The param name a collection-serving command uses to say WHICH project's\n * collections it means. Reserved and documented now, before a phone client\n * ships, because the parts that are hard to change later are the ones being\n * written today. Four rules go with it:\n *\n * 1. **It is an OPAQUE scope, never a path.** The phone is a genuinely remote\n * client; an absolute root in a command, an artifact or a token publishes\n * the user's home directory over the wire. Mint a project id host-side and\n * resolve it host-side.\n * 2. **The phone must be able to LEARN the list.** A picker needs\n * `{ id, label }` pairs from the host — a command of its own, or a field on\n * an existing listing. Designing the scope value now is what keeps that the\n * ONLY new thing when the feature lands.\n * 3. **Handlers RESOLVE a scope; they do not hard-code one.** Write each\n * collection handler as \"read the scope from params, defaulting to the\n * host's root\" rather than calling the workspace accessor inline. Today\n * every call resolves the default and behaves exactly as it does now; the\n * day the param arrives, no handler changes.\n * 4. **The artifact stays host-built.** A remote view's srcdoc, its inlined\n * image thumbnails and its token are assembled on the host, so the phone\n * never resolves a path itself. That is what makes (1) hold without\n * trusting the client. */\nexport const COMMAND_SCOPE_PARAM = \"project\";\n\n/** Read the opaque project scope off a command's params, or `undefined` for\n * \"the host's own root\" — which is what every command means today. A\n * non-string (or empty) value is treated as absent rather than as an error: a\n * scope the host cannot resolve must fall back to the default, never to a\n * guess. Hosts pass the result to their own id → root resolver; this module\n * deliberately never sees a path. */\nexport const readCommandScope = (params: JsonObject): string | undefined => {\n const raw = params[COMMAND_SCOPE_PARAM];\n return typeof raw === \"string\" && raw.trim().length > 0 ? raw.trim() : undefined;\n};\n\n// Bumped when the command-channel wire protocol changes in a way the remote must\n// gate on. Advertised in the presence doc so the remote can check compatibility\n// before issuing commands.\n//\n// v2: offline queueing. The host honours `expiresAt` (deletes an expired command\n// + its staged attachments instead of spawning a stale chat). A remote MUST see\n// protocolVersion >= 2 before queueing a startChat while the host is offline —\n// a v1 host silently ignores `expiresAt`, so a queued chat would spawn stale on\n// reconnect with its uploads never cleaned up.\nexport const REMOTE_HOST_PROTOCOL_VERSION = 2;\n\n// The presence doc's payload: online flag + a capability advertisement. Written\n// by the host on every heartbeat; the remote reads it from the presence listener\n// it already runs (no extra round trip, known the instant the host is online).\n// Browser-safe so the mobile client compiles against the same shape.\n// `updatedAt` (a Firestore serverTimestamp) is added by the runner at write time\n// and is intentionally not part of this capability contract.\n// Which machine a presence comes from, for a host that can run on several machines\n// under one account (mulmoterminal#3092): a stable id the host recognises itself by,\n// and the name the remote shows for it.\nexport interface HostMachine {\n machineId: string;\n label: string;\n}\n\nexport interface HostPresence {\n online: boolean;\n hostId: string;\n protocolVersion: number;\n // Method names the host serves — the keys of the live handler table.\n capabilities: string[];\n machineId?: string;\n label?: string;\n}\n\n// Build the presence payload from the live handler table. Capabilities are\n// `Object.keys(handlers)` so registering a handler is the ONLY step needed to\n// advertise it — there is no second list to keep in sync.\nexport const buildHostPresence = (channel: Channel, handlers: CommandHandlers, online: boolean, machine?: HostMachine): HostPresence => ({\n online,\n hostId: channel.hostId,\n protocolVersion: REMOTE_HOST_PROTOCOL_VERSION,\n capabilities: Object.keys(handlers),\n ...(machine ? { machineId: machine.machineId, label: machine.label } : {}),\n});\n\n// Per-host command queue: users/{uid}/hosts/{hostId}/commands.\nexport const commandsCollection = (firestore: Firestore, channel: Channel): CollectionReference<DocumentData> =>\n collection(firestore, \"users\", channel.uid, \"hosts\", channel.hostId, \"commands\");\n\n// Presence doc for a host: users/{uid}/hosts/{hostId}. The host heartbeats\n// { online, updatedAt } here; the remote reads it to know if the host is up.\nexport const hostDoc = (firestore: Firestore, channel: Channel): DocumentReference<DocumentData> =>\n doc(firestore, \"users\", channel.uid, \"hosts\", channel.hostId);\n\n// Channel health as the resilient runner reports it. Browser-safe alongside the\n// wire types because the control that renders it runs in the client.\nexport { RUNNER_HEALTH_STATES, isRunnerHealth, isRunnerHealthState } from \"./health.js\";\nexport type { RunnerHealth, RunnerHealthState } from \"./health.js\";\n"],"mappings":";;;AAYA,IAAa,uBAAuB;CAAC;CAAU;CAAgB;AAAS;AAWxE,IAAM,YAAY,UAAqD,OAAO,UAAU,YAAY,UAAU;AAE9G,IAAa,uBAAuB,UAA+C,qBAAqB,MAAM,UAAU,UAAU,KAAK;;;AAIvI,IAAa,kBAAkB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O,OAAO,YAAY,OAAO,KAAK,CAAC,KAAK,WAAW,CAAC,KAAK,YAAY,OAAO,GAAG,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC;AACrG;;;;;;;;;;AAWA,IAAa,oBAAoB,YAAiD,cAAc,SAAS,SAAS;AA0ClH,IAAa,aAAa,SAAqC,QAAyB,OAAO,QAAQ,cAAc,YAAY,OAAO,QAAQ;AAMhJ,IAAa,eAAe,MAAkC,WAA+C,KAAK,aAAa,MAAM,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;AA2BxJ,IAAa,sBAAsB;;;;;;;AAQnC,IAAa,oBAAoB,WAA2C;CAC1E,MAAM,MAAM,OAAO;CACnB,OAAO,OAAO,QAAQ,YAAY,IAAI,KAAK,CAAC,CAAC,SAAS,IAAI,IAAI,KAAK,IAAI,KAAA;AACzE;AAWA,IAAa,+BAA+B;AA6B5C,IAAa,qBAAqB,SAAkB,UAA2B,QAAiB,aAAyC;CACvI;CACA,QAAQ,QAAQ;CAChB,iBAAA;CACA,cAAc,OAAO,KAAK,QAAQ;CAClC,GAAI,UAAU;EAAE,WAAW,QAAQ;EAAW,OAAO,QAAQ;CAAM,IAAI,CAAC;AAC1E;AAGA,IAAa,sBAAsB,WAAsB,YACvD,WAAW,WAAW,SAAS,QAAQ,KAAK,SAAS,QAAQ,QAAQ,UAAU;AAIjF,IAAa,WAAW,WAAsB,YAC5C,IAAI,WAAW,SAAS,QAAQ,KAAK,SAAS,QAAQ,MAAM"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_dist = require("../dist-
|
|
3
|
-
const require_project = require("../project-
|
|
4
|
-
|
|
2
|
+
const require_dist = require("../dist-734JaRYi.cjs");
|
|
3
|
+
const require_project = require("../project-DDTIVEMU.cjs");
|
|
4
|
+
// src/remote-view/index.ts
|
|
5
5
|
/** Bump when the bootstrap/message contract changes shape; the bootstrap
|
|
6
6
|
* exposes it as `__MC_VIEW.protocol` so a parent can refuse a stale view.
|
|
7
7
|
* v2 (phase 4) adds the mutate pair below — a backward-compatible superset,
|
|
@@ -286,7 +286,6 @@ async function handleRemoteViewMessage(data, handlers, reply) {
|
|
|
286
286
|
await answerGetItems(msg.requestId, request, handlers, reply);
|
|
287
287
|
return true;
|
|
288
288
|
}
|
|
289
|
-
//#endregion
|
|
290
289
|
exports.DEFAULT_IMAGE_MAX_EDGE = DEFAULT_IMAGE_MAX_EDGE;
|
|
291
290
|
exports.DEFAULT_PAGE_LIMIT = DEFAULT_PAGE_LIMIT;
|
|
292
291
|
exports.MAX_PAGE_LIMIT = MAX_PAGE_LIMIT;
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { c as isRecord } from "../dist-
|
|
2
|
-
import { n as projectRecordFields } from "../project-
|
|
3
|
-
|
|
1
|
+
import { c as isRecord } from "../dist-BmO4oSQy.js";
|
|
2
|
+
import { n as projectRecordFields } from "../project-mU6-xLfy.js";
|
|
3
|
+
// src/remote-view/index.ts
|
|
4
4
|
/** Bump when the bootstrap/message contract changes shape; the bootstrap
|
|
5
5
|
* exposes it as `__MC_VIEW.protocol` so a parent can refuse a stale view.
|
|
6
6
|
* v2 (phase 4) adds the mutate pair below — a backward-compatible superset,
|
|
@@ -285,7 +285,6 @@ async function handleRemoteViewMessage(data, handlers, reply) {
|
|
|
285
285
|
await answerGetItems(msg.requestId, request, handlers, reply);
|
|
286
286
|
return true;
|
|
287
287
|
}
|
|
288
|
-
//#endregion
|
|
289
288
|
export { DEFAULT_IMAGE_MAX_EDGE, DEFAULT_PAGE_LIMIT, MAX_PAGE_LIMIT, REMOTE_VIEW_ITEMS_MAX_BYTES, REMOTE_VIEW_MAX_BYTES, REMOTE_VIEW_MESSAGES, REMOTE_VIEW_PROTOCOL, SANDBOXED_VIEW_CDN_ALLOWLIST, buildRemoteViewCsp, buildRemoteViewSrcdoc, clampImageMaxEdge, clampLimit, clampOffset, handleRemoteViewMessage, normalizeFields, normalizeMutate, pageFromItems, projectItems, readIdParam };
|
|
290
289
|
|
|
291
290
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// \0rolldown/runtime.js
|
|
2
2
|
var __create = Object.create;
|
|
3
3
|
var __defProp = Object.defineProperty;
|
|
4
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
@@ -19,7 +19,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
|
|
|
19
19
|
value: mod,
|
|
20
20
|
enumerable: true
|
|
21
21
|
}) : target, mod));
|
|
22
|
-
//#endregion
|
|
23
22
|
Object.defineProperty(exports, "__toESM", {
|
|
24
23
|
enumerable: true,
|
|
25
24
|
get: function() {
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
const require_rolldown_runtime = require("./rolldown-runtime-
|
|
1
|
+
const require_rolldown_runtime = require("./rolldown-runtime-CmQyd0Gu.cjs");
|
|
2
2
|
let node_fs = require("node:fs");
|
|
3
3
|
let node_path = require("node:path");
|
|
4
4
|
node_path = require_rolldown_runtime.__toESM(node_path, 1);
|
|
5
5
|
let node_crypto = require("node:crypto");
|
|
6
|
-
|
|
6
|
+
// src/files/atomic.ts
|
|
7
7
|
var DEFAULT_UNIQUE_TMP = true;
|
|
8
8
|
function tmpPathFor(filePath, uniqueTmp) {
|
|
9
9
|
return uniqueTmp ?? DEFAULT_UNIQUE_TMP ? `${filePath}.${(0, node_crypto.randomBytes)(6).toString("hex")}.tmp` : `${filePath}.tmp`;
|
|
@@ -95,8 +95,7 @@ function writeFileAtomicSync(filePath, content, opts = {}) {
|
|
|
95
95
|
throw err;
|
|
96
96
|
}
|
|
97
97
|
}
|
|
98
|
-
|
|
99
|
-
//#region src/files/root.ts
|
|
98
|
+
// src/files/root.ts
|
|
100
99
|
/** The canonical form of a root, for every place a root becomes an IDENTITY
|
|
101
100
|
* rather than a path to read.
|
|
102
101
|
*
|
|
@@ -114,13 +113,18 @@ function writeFileAtomicSync(filePath, content, opts = {}) {
|
|
|
114
113
|
function canonicalRoot(root) {
|
|
115
114
|
return node_path.default.resolve(root);
|
|
116
115
|
}
|
|
117
|
-
//#endregion
|
|
118
116
|
Object.defineProperty(exports, "canonicalRoot", {
|
|
119
117
|
enumerable: true,
|
|
120
118
|
get: function() {
|
|
121
119
|
return canonicalRoot;
|
|
122
120
|
}
|
|
123
121
|
});
|
|
122
|
+
Object.defineProperty(exports, "renameWithWindowsRetry", {
|
|
123
|
+
enumerable: true,
|
|
124
|
+
get: function() {
|
|
125
|
+
return renameWithWindowsRetry;
|
|
126
|
+
}
|
|
127
|
+
});
|
|
124
128
|
Object.defineProperty(exports, "writeFileAtomic", {
|
|
125
129
|
enumerable: true,
|
|
126
130
|
get: function() {
|
|
@@ -134,4 +138,4 @@ Object.defineProperty(exports, "writeFileAtomicSync", {
|
|
|
134
138
|
}
|
|
135
139
|
});
|
|
136
140
|
|
|
137
|
-
//# sourceMappingURL=root-
|
|
141
|
+
//# sourceMappingURL=root-9lRFeXbm.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"root-BvwBUcol.cjs","names":["randomBytes","promises","renameSync","path","path"],"sources":["../src/files/atomic.ts","../src/files/root.ts"],"sourcesContent":["// rename(2) is atomic on POSIX; Node's Windows fallback (copy+unlink) is still safer than truncating in place.\n// Readers always see either the old file or the new — never a half-written one.\n//\n// Single source of truth for atomic file writes across the whole monorepo\n// (host, core, plugins). Previously copy-pasted four times, so a Windows retry\n// fix landed in only one (#2399, precedent #2222).\n\nimport { mkdirSync, promises, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\nexport interface WriteAtomicOptions {\n mode?: number;\n /** Give the staging file a random suffix so concurrent writers to the same\n * destination can't collide at the OS layer.\n *\n * Defaults to `true`, and opting out is almost always wrong. A shared\n * `${filePath}.tmp` means two writers of one file race: the second write\n * overwrites the first's staging file, or one rename/unlink pulls it out\n * from under the other, surfacing as `ENOENT … rename '<file>.tmp'`. That is\n * not theoretical — it fired in production on session meta, where ten\n * distinct callers (`setClaudeSessionId`, `backfillOrigin`,\n * `incrementUserQueryCount`, …) all write the same `<sessionId>.json`\n * (#2222).\n *\n * Pass `false` only when you specifically need the staging path to be\n * predictable (e.g. a single-writer token file, or a test that pre-creates\n * it to force a write failure). */\n uniqueTmp?: boolean;\n}\n\n// Unique staging names are the safe default: the cost is a random suffix, the\n// cost of the alternative is a lost update under concurrency (#2222).\nconst DEFAULT_UNIQUE_TMP = true;\n\nfunction tmpPathFor(filePath: string, uniqueTmp: boolean | undefined): string {\n return (uniqueTmp ?? DEFAULT_UNIQUE_TMP) ? `${filePath}.${randomBytes(6).toString(\"hex\")}.tmp` : `${filePath}.tmp`;\n}\n\n// On Windows, AV / Search Indexer / Defender briefly hold handles and rename trips EPERM/EBUSY/EACCES. Retry loop is\n// gated to Windows because POSIX EPERM means a real perm problem (read-only fs, sticky, cross-device) — retrying\n// just adds latency before the inevitable throw.\nconst IS_WINDOWS = process.platform === \"win32\";\n// The ASYNC ladder is generous because waiting is nearly free there — the call\n// yields, and a write that would otherwise throw is worth a few seconds. The\n// previous ~430 ms budget was not enough on a loaded Windows CI runner: the\n// notifier's `active.json` write lost the rename and threw, and the listener\n// waiting on it timed out ten seconds later, so the operation failed while the\n// contention it was retrying through had long since cleared (#2972 follow-up).\nconst RENAME_RETRY_DELAYS_MS = [30, 100, 300, 600, 1000, 2000] as const;\n// The SYNC ladder stays short on purpose. `sleepSync` parks the whole thread,\n// so a long budget here does not delay one write — it freezes the process. A\n// caller that cannot afford to yield cannot afford to wait either; failing\n// after ~430 ms and letting the caller decide beats a four-second stall.\nconst RENAME_RETRY_DELAYS_SYNC_MS = [30, 100, 300] as const;\n\nfunction hasErrnoCode(err: unknown): err is { code: string } {\n return typeof err === \"object\" && err !== null && \"code\" in err && typeof err.code === \"string\";\n}\n\n// `isWindows` is a parameter (defaulting to the real platform) so the safety-critical decision is testable on any OS.\n/** The retry budgets, exported so a test can assert what they cost rather than\n * hard-coding a second copy of the numbers. */\nexport const RENAME_RETRY_BUDGET_MS = RENAME_RETRY_DELAYS_MS.reduce((total, delay) => total + delay, 0);\nexport const RENAME_RETRY_BUDGET_SYNC_MS = RENAME_RETRY_DELAYS_SYNC_MS.reduce((total, delay) => total + delay, 0);\n\nexport function isTransientRenameError(err: unknown, isWindows: boolean = IS_WINDOWS): boolean {\n if (!isWindows || !hasErrnoCode(err)) return false;\n return err.code === \"EPERM\" || err.code === \"EBUSY\" || err.code === \"EACCES\";\n}\n\n// Injectable so a test can drive the retry path (fail-then-succeed rename, no-op sleep, isWindows=true) on any OS.\nexport interface RenameRetryDeps {\n rename: (fromPath: string, toPath: string) => Promise<void>;\n sleep: (millis: number) => Promise<void>;\n isWindows: boolean;\n}\n\nconst defaultRenameRetryDeps: RenameRetryDeps = {\n rename: (fromPath, toPath) => promises.rename(fromPath, toPath),\n sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),\n isWindows: IS_WINDOWS,\n};\n\nexport async function renameWithWindowsRetry(fromPath: string, toPath: string, deps: RenameRetryDeps = defaultRenameRetryDeps): Promise<void> {\n for (const delayMs of RENAME_RETRY_DELAYS_MS) {\n try {\n await deps.rename(fromPath, toPath);\n return;\n } catch (err) {\n if (!isTransientRenameError(err, deps.isWindows)) throw err;\n await deps.sleep(delayMs);\n }\n }\n // Final attempt — let any error propagate.\n await deps.rename(fromPath, toPath);\n}\n\n// Atomics.wait parks the thread instead of busy-spinning. Only on the Windows-rename retry path, and only on the SYNC\n// ladder, whose budget is capped at ~430ms precisely because this blocks everything.\nconst SYNC_SLEEP_BUF = new Int32Array(new SharedArrayBuffer(4));\nfunction sleepSync(millis: number): void {\n Atomics.wait(SYNC_SLEEP_BUF, 0, 0, millis);\n}\n\n// Deliberate async/sync twin of RenameRetryDeps: `sleep` blocks the thread instead of returning a Promise.\nexport interface RenameRetryDepsSync {\n rename: (fromPath: string, toPath: string) => void;\n sleep: (millis: number) => void;\n isWindows: boolean;\n}\n\nconst defaultRenameRetryDepsSync: RenameRetryDepsSync = {\n rename: (fromPath, toPath) => renameSync(fromPath, toPath),\n sleep: sleepSync,\n isWindows: IS_WINDOWS,\n};\n\nexport function renameSyncWithWindowsRetry(fromPath: string, toPath: string, deps: RenameRetryDepsSync = defaultRenameRetryDepsSync): void {\n for (const delayMs of RENAME_RETRY_DELAYS_SYNC_MS) {\n try {\n deps.rename(fromPath, toPath);\n return;\n } catch (err) {\n if (!isTransientRenameError(err, deps.isWindows)) throw err;\n deps.sleep(delayMs);\n }\n }\n deps.rename(fromPath, toPath);\n}\n\n// Forcing utf-8 on a Uint8Array would re-encode the bytes — wrong for PNGs and other binary blobs.\nfunction writeOptionsFor(content: string | Uint8Array, mode: number | undefined): { encoding?: \"utf-8\" | undefined; mode?: number | undefined } {\n return typeof content === \"string\" ? { encoding: \"utf-8\", mode } : { mode };\n}\n\nexport async function writeFileAtomic(filePath: string, content: string | Uint8Array, opts: WriteAtomicOptions = {}): Promise<void> {\n const tmp = tmpPathFor(filePath, opts.uniqueTmp);\n await promises.mkdir(path.dirname(filePath), { recursive: true });\n try {\n await promises.writeFile(tmp, content, writeOptionsFor(content, opts.mode));\n await renameWithWindowsRetry(tmp, filePath);\n } catch (err) {\n await promises.unlink(tmp).catch(() => {});\n throw err;\n }\n}\n\nexport function writeFileAtomicSync(filePath: string, content: string | Uint8Array, opts: WriteAtomicOptions = {}): void {\n const tmp = tmpPathFor(filePath, opts.uniqueTmp);\n mkdirSync(path.dirname(filePath), { recursive: true });\n try {\n writeFileSync(tmp, content, writeOptionsFor(content, opts.mode));\n renameSyncWithWindowsRetry(tmp, filePath);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best-effort cleanup\n }\n throw err;\n }\n}\n","// The canonical form of a workspace / project root.\n//\n// Lives here rather than in the collection engine because a root is an IDENTITY\n// in several subsystems that do not depend on each other — a watcher generation\n// key, a change payload, a completion-bell id, a scheduled task id — and every\n// one of them has to agree on it or the same project registers twice.\n\nimport path from \"node:path\";\n\n/** The canonical form of a root, for every place a root becomes an IDENTITY\n * rather than a path to read.\n *\n * `path.resolve` only — it collapses `.`/`..` and the trailing separator, so\n * `/work/project` and `/work/project/` are one root instead of two watcher\n * generations over the same tree, two bells per record, and two scheduled\n * refresh jobs.\n *\n * Deliberately NOT `realpath`. Resolving symlinks is async (so it could not run\n * on a synchronous claim path), it fails for a root that does not exist yet,\n * and it would put a path the host never named into an id that is written to\n * disk. The policy is therefore lexical: a host that hands the same tree under\n * two different symlink spellings gets two roots, and it is the host's job to\n * name a project the same way every time. */\nexport function canonicalRoot(root: string): string {\n return path.resolve(root);\n}\n"],"mappings":";;;;;;AAiCA,IAAM,qBAAqB;AAE3B,SAAS,WAAW,UAAkB,WAAwC;CAC5E,OAAQ,aAAa,qBAAsB,GAAG,SAAS,IAAA,GAAGA,YAAAA,YAAAA,CAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE,QAAQ,GAAG,SAAS;AAC/G;AAKA,IAAM,aAAa,QAAQ,aAAa;AAOxC,IAAM,yBAAyB;CAAC;CAAI;CAAK;CAAK;CAAK;CAAM;AAAI;AAK7D,IAAM,8BAA8B;CAAC;CAAI;CAAK;AAAG;AAEjD,SAAS,aAAa,KAAuC;CAC3D,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,OAAO,IAAI,SAAS;AACzF;AAKsC,uBAAuB,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AAC3D,4BAA4B,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AAEhH,SAAgB,uBAAuB,KAAc,YAAqB,YAAqB;CAC7F,IAAI,CAAC,aAAa,CAAC,aAAa,GAAG,GAAG,OAAO;CAC7C,OAAO,IAAI,SAAS,WAAW,IAAI,SAAS,WAAW,IAAI,SAAS;AACtE;AASA,IAAM,yBAA0C;CAC9C,SAAS,UAAU,WAAWC,Q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AAMF,QAAAA,SAAS,UAAU,KAAK,SAAS,gBAAgB,SAAS,KAAK,IAAI,CAAC;EAC1E,MAAM,uBAAuB,KAAK,QAAQ;CAC5C,SAAS,KAAK;EACZ,MAAMA,QAAAA,SAAS,OAAO,GAAG,CAAC,CAAC,YAAY,CAAC,CAAC;EACzC,MAAM;CACR;AACF;AAEA,SAAgB,oBAAoB,UAAkB,SAA8B,OAA2B,CAAC,GAAS;CACvH,MAAM,MAAM,WAAW,UAAU,KAAK,SAAS;CAC/C,CAAA,GAAA,QAAA,UAAA,CAAUE,UAAAA,QAAK,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;CACrD,IAAI;EACF,CAAA,GAAA,QAAA,cAAA,CAAc,KAAK,SAAS,gBAAgB,SAAS,KAAK,IAAI,CAAC;EAC/D,2BAA2B,KAAK,QAAQ;CAC1C,SAAS,KAAK;EACZ,IAAI;GACF,CAAA,GAAA,QAAA,WAAA,CAAW,GAAG;EAChB,QAAQ,CAER;EACA,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;AC3IA,SAAgB,cAAc,MAAsB;CAClD,OAAOC,UAAAA,QAAK,QAAQ,IAAI;AAC1B"}
|
|
1
|
+
{"version":3,"file":"root-9lRFeXbm.cjs","names":["randomBytes","promises","renameSync","path","path"],"sources":["../src/files/atomic.ts","../src/files/root.ts"],"sourcesContent":["// rename(2) is atomic on POSIX; Node's Windows fallback (copy+unlink) is still safer than truncating in place.\n// Readers always see either the old file or the new — never a half-written one.\n//\n// Single source of truth for atomic file writes across the whole monorepo\n// (host, core, plugins). Previously copy-pasted four times, so a Windows retry\n// fix landed in only one (#2399, precedent #2222).\n\nimport { mkdirSync, promises, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\nexport interface WriteAtomicOptions {\n mode?: number;\n /** Give the staging file a random suffix so concurrent writers to the same\n * destination can't collide at the OS layer.\n *\n * Defaults to `true`, and opting out is almost always wrong. A shared\n * `${filePath}.tmp` means two writers of one file race: the second write\n * overwrites the first's staging file, or one rename/unlink pulls it out\n * from under the other, surfacing as `ENOENT … rename '<file>.tmp'`. That is\n * not theoretical — it fired in production on session meta, where ten\n * distinct callers (`setClaudeSessionId`, `backfillOrigin`,\n * `incrementUserQueryCount`, …) all write the same `<sessionId>.json`\n * (#2222).\n *\n * Pass `false` only when you specifically need the staging path to be\n * predictable (e.g. a single-writer token file, or a test that pre-creates\n * it to force a write failure). */\n uniqueTmp?: boolean;\n}\n\n// Unique staging names are the safe default: the cost is a random suffix, the\n// cost of the alternative is a lost update under concurrency (#2222).\nconst DEFAULT_UNIQUE_TMP = true;\n\nfunction tmpPathFor(filePath: string, uniqueTmp: boolean | undefined): string {\n return (uniqueTmp ?? DEFAULT_UNIQUE_TMP) ? `${filePath}.${randomBytes(6).toString(\"hex\")}.tmp` : `${filePath}.tmp`;\n}\n\n// On Windows, AV / Search Indexer / Defender briefly hold handles and rename trips EPERM/EBUSY/EACCES. Retry loop is\n// gated to Windows because POSIX EPERM means a real perm problem (read-only fs, sticky, cross-device) — retrying\n// just adds latency before the inevitable throw.\nconst IS_WINDOWS = process.platform === \"win32\";\n// The ASYNC ladder is generous because waiting is nearly free there — the call\n// yields, and a write that would otherwise throw is worth a few seconds. The\n// previous ~430 ms budget was not enough on a loaded Windows CI runner: the\n// notifier's `active.json` write lost the rename and threw, and the listener\n// waiting on it timed out ten seconds later, so the operation failed while the\n// contention it was retrying through had long since cleared (#2972 follow-up).\nconst RENAME_RETRY_DELAYS_MS = [30, 100, 300, 600, 1000, 2000] as const;\n// The SYNC ladder stays short on purpose. `sleepSync` parks the whole thread,\n// so a long budget here does not delay one write — it freezes the process. A\n// caller that cannot afford to yield cannot afford to wait either; failing\n// after ~430 ms and letting the caller decide beats a four-second stall.\nconst RENAME_RETRY_DELAYS_SYNC_MS = [30, 100, 300] as const;\n\nfunction hasErrnoCode(err: unknown): err is { code: string } {\n return typeof err === \"object\" && err !== null && \"code\" in err && typeof err.code === \"string\";\n}\n\n// `isWindows` is a parameter (defaulting to the real platform) so the safety-critical decision is testable on any OS.\n/** The retry budgets, exported so a test can assert what they cost rather than\n * hard-coding a second copy of the numbers. */\nexport const RENAME_RETRY_BUDGET_MS = RENAME_RETRY_DELAYS_MS.reduce((total, delay) => total + delay, 0);\nexport const RENAME_RETRY_BUDGET_SYNC_MS = RENAME_RETRY_DELAYS_SYNC_MS.reduce((total, delay) => total + delay, 0);\n\nexport function isTransientRenameError(err: unknown, isWindows: boolean = IS_WINDOWS): boolean {\n if (!isWindows || !hasErrnoCode(err)) return false;\n return err.code === \"EPERM\" || err.code === \"EBUSY\" || err.code === \"EACCES\";\n}\n\n// Injectable so a test can drive the retry path (fail-then-succeed rename, no-op sleep, isWindows=true) on any OS.\nexport interface RenameRetryDeps {\n rename: (fromPath: string, toPath: string) => Promise<void>;\n sleep: (millis: number) => Promise<void>;\n isWindows: boolean;\n}\n\nconst defaultRenameRetryDeps: RenameRetryDeps = {\n rename: (fromPath, toPath) => promises.rename(fromPath, toPath),\n sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),\n isWindows: IS_WINDOWS,\n};\n\nexport async function renameWithWindowsRetry(fromPath: string, toPath: string, deps: RenameRetryDeps = defaultRenameRetryDeps): Promise<void> {\n for (const delayMs of RENAME_RETRY_DELAYS_MS) {\n try {\n await deps.rename(fromPath, toPath);\n return;\n } catch (err) {\n if (!isTransientRenameError(err, deps.isWindows)) throw err;\n await deps.sleep(delayMs);\n }\n }\n // Final attempt — let any error propagate.\n await deps.rename(fromPath, toPath);\n}\n\n// Atomics.wait parks the thread instead of busy-spinning. Only on the Windows-rename retry path, and only on the SYNC\n// ladder, whose budget is capped at ~430ms precisely because this blocks everything.\nconst SYNC_SLEEP_BUF = new Int32Array(new SharedArrayBuffer(4));\nfunction sleepSync(millis: number): void {\n Atomics.wait(SYNC_SLEEP_BUF, 0, 0, millis);\n}\n\n// Deliberate async/sync twin of RenameRetryDeps: `sleep` blocks the thread instead of returning a Promise.\nexport interface RenameRetryDepsSync {\n rename: (fromPath: string, toPath: string) => void;\n sleep: (millis: number) => void;\n isWindows: boolean;\n}\n\nconst defaultRenameRetryDepsSync: RenameRetryDepsSync = {\n rename: (fromPath, toPath) => renameSync(fromPath, toPath),\n sleep: sleepSync,\n isWindows: IS_WINDOWS,\n};\n\nexport function renameSyncWithWindowsRetry(fromPath: string, toPath: string, deps: RenameRetryDepsSync = defaultRenameRetryDepsSync): void {\n for (const delayMs of RENAME_RETRY_DELAYS_SYNC_MS) {\n try {\n deps.rename(fromPath, toPath);\n return;\n } catch (err) {\n if (!isTransientRenameError(err, deps.isWindows)) throw err;\n deps.sleep(delayMs);\n }\n }\n deps.rename(fromPath, toPath);\n}\n\n// Forcing utf-8 on a Uint8Array would re-encode the bytes — wrong for PNGs and other binary blobs.\nfunction writeOptionsFor(content: string | Uint8Array, mode: number | undefined): { encoding?: \"utf-8\" | undefined; mode?: number | undefined } {\n return typeof content === \"string\" ? { encoding: \"utf-8\", mode } : { mode };\n}\n\nexport async function writeFileAtomic(filePath: string, content: string | Uint8Array, opts: WriteAtomicOptions = {}): Promise<void> {\n const tmp = tmpPathFor(filePath, opts.uniqueTmp);\n await promises.mkdir(path.dirname(filePath), { recursive: true });\n try {\n await promises.writeFile(tmp, content, writeOptionsFor(content, opts.mode));\n await renameWithWindowsRetry(tmp, filePath);\n } catch (err) {\n await promises.unlink(tmp).catch(() => {});\n throw err;\n }\n}\n\nexport function writeFileAtomicSync(filePath: string, content: string | Uint8Array, opts: WriteAtomicOptions = {}): void {\n const tmp = tmpPathFor(filePath, opts.uniqueTmp);\n mkdirSync(path.dirname(filePath), { recursive: true });\n try {\n writeFileSync(tmp, content, writeOptionsFor(content, opts.mode));\n renameSyncWithWindowsRetry(tmp, filePath);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best-effort cleanup\n }\n throw err;\n }\n}\n","// The canonical form of a workspace / project root.\n//\n// Lives here rather than in the collection engine because a root is an IDENTITY\n// in several subsystems that do not depend on each other — a watcher generation\n// key, a change payload, a completion-bell id, a scheduled task id — and every\n// one of them has to agree on it or the same project registers twice.\n\nimport path from \"node:path\";\n\n/** The canonical form of a root, for every place a root becomes an IDENTITY\n * rather than a path to read.\n *\n * `path.resolve` only — it collapses `.`/`..` and the trailing separator, so\n * `/work/project` and `/work/project/` are one root instead of two watcher\n * generations over the same tree, two bells per record, and two scheduled\n * refresh jobs.\n *\n * Deliberately NOT `realpath`. Resolving symlinks is async (so it could not run\n * on a synchronous claim path), it fails for a root that does not exist yet,\n * and it would put a path the host never named into an id that is written to\n * disk. The policy is therefore lexical: a host that hands the same tree under\n * two different symlink spellings gets two roots, and it is the host's job to\n * name a project the same way every time. */\nexport function canonicalRoot(root: string): string {\n return path.resolve(root);\n}\n"],"mappings":";;;;;;AAiCA,IAAM,qBAAqB;AAE3B,SAAS,WAAW,UAAkB,WAAwC;CAC5E,OAAQ,aAAa,qBAAsB,GAAG,SAAS,IAAA,GAAGA,YAAAA,YAAAA,CAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE,QAAQ,GAAG,SAAS;AAC/G;AAKA,IAAM,aAAa,QAAQ,aAAa;AAOxC,IAAM,yBAAyB;CAAC;CAAI;CAAK;CAAK;CAAK;CAAM;AAAI;AAK7D,IAAM,8BAA8B;CAAC;CAAI;CAAK;AAAG;AAEjD,SAAS,aAAa,KAAuC;CAC3D,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,OAAO,IAAI,SAAS;AACzF;AAKsC,uBAAuB,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AAC3D,4BAA4B,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AAEhH,SAAgB,uBAAuB,KAAc,YAAqB,YAAqB;CAC7F,IAAI,CAAC,aAAa,CAAC,aAAa,GAAG,GAAG,OAAO;CAC7C,OAAO,IAAI,SAAS,WAAW,IAAI,SAAS,WAAW,IAAI,SAAS;AACt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,GAAG,EAAE,WAAW,KAAK,CAAC;CAChE,IAAI;EACF,MAAMF,QAAAA,SAAS,UAAU,KAAK,SAAS,gBAAgB,SAAS,KAAK,IAAI,CAAC;EAC1E,MAAM,uBAAuB,KAAK,QAAQ;CAC5C,SAAS,KAAK;EACZ,MAAMA,QAAAA,SAAS,OAAO,GAAG,CAAC,CAAC,YAAY,CAAC,CAAC;EACzC,MAAM;CACR;AACF;AAEA,SAAgB,oBAAoB,UAAkB,SAA8B,OAA2B,CAAC,GAAS;CACvH,MAAM,MAAM,WAAW,UAAU,KAAK,SAAS;CAC/C,CAAA,GAAA,QAAA,UAAA,CAAUE,UAAAA,QAAK,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;CACrD,IAAI;EACF,CAAA,GAAA,QAAA,cAAA,CAAc,KAAK,SAAS,gBAAgB,SAAS,KAAK,IAAI,CAAC;EAC/D,2BAA2B,KAAK,QAAQ;CAC1C,SAAS,KAAK;EACZ,IAAI;GACF,CAAA,GAAA,QAAA,WAAA,CAAW,GAAG;EAChB,QAAQ,CAER;EACA,MAAM;CACR;AACF;;;;;;;;;;;;;;;;AC3IA,SAAgB,cAAc,MAAsB;CAClD,OAAOC,UAAAA,QAAK,QAAQ,IAAI;AAC1B"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { mkdirSync, promises, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
2
2
|
import path from "node:path";
|
|
3
3
|
import { randomBytes } from "node:crypto";
|
|
4
|
-
|
|
4
|
+
// src/files/atomic.ts
|
|
5
5
|
var DEFAULT_UNIQUE_TMP = true;
|
|
6
6
|
function tmpPathFor(filePath, uniqueTmp) {
|
|
7
7
|
return uniqueTmp ?? DEFAULT_UNIQUE_TMP ? `${filePath}.${randomBytes(6).toString("hex")}.tmp` : `${filePath}.tmp`;
|
|
@@ -93,8 +93,7 @@ function writeFileAtomicSync(filePath, content, opts = {}) {
|
|
|
93
93
|
throw err;
|
|
94
94
|
}
|
|
95
95
|
}
|
|
96
|
-
|
|
97
|
-
//#region src/files/root.ts
|
|
96
|
+
// src/files/root.ts
|
|
98
97
|
/** The canonical form of a root, for every place a root becomes an IDENTITY
|
|
99
98
|
* rather than a path to read.
|
|
100
99
|
*
|
|
@@ -112,7 +111,6 @@ function writeFileAtomicSync(filePath, content, opts = {}) {
|
|
|
112
111
|
function canonicalRoot(root) {
|
|
113
112
|
return path.resolve(root);
|
|
114
113
|
}
|
|
115
|
-
|
|
116
|
-
export { writeFileAtomic as n, writeFileAtomicSync as r, canonicalRoot as t };
|
|
114
|
+
export { writeFileAtomicSync as i, renameWithWindowsRetry as n, writeFileAtomic as r, canonicalRoot as t };
|
|
117
115
|
|
|
118
|
-
//# sourceMappingURL=root-
|
|
116
|
+
//# sourceMappingURL=root-CqxPNSyK.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"root-BcS4-Kge.js","names":[],"sources":["../src/files/atomic.ts","../src/files/root.ts"],"sourcesContent":["// rename(2) is atomic on POSIX; Node's Windows fallback (copy+unlink) is still safer than truncating in place.\n// Readers always see either the old file or the new — never a half-written one.\n//\n// Single source of truth for atomic file writes across the whole monorepo\n// (host, core, plugins). Previously copy-pasted four times, so a Windows retry\n// fix landed in only one (#2399, precedent #2222).\n\nimport { mkdirSync, promises, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\nexport interface WriteAtomicOptions {\n mode?: number;\n /** Give the staging file a random suffix so concurrent writers to the same\n * destination can't collide at the OS layer.\n *\n * Defaults to `true`, and opting out is almost always wrong. A shared\n * `${filePath}.tmp` means two writers of one file race: the second write\n * overwrites the first's staging file, or one rename/unlink pulls it out\n * from under the other, surfacing as `ENOENT … rename '<file>.tmp'`. That is\n * not theoretical — it fired in production on session meta, where ten\n * distinct callers (`setClaudeSessionId`, `backfillOrigin`,\n * `incrementUserQueryCount`, …) all write the same `<sessionId>.json`\n * (#2222).\n *\n * Pass `false` only when you specifically need the staging path to be\n * predictable (e.g. a single-writer token file, or a test that pre-creates\n * it to force a write failure). */\n uniqueTmp?: boolean;\n}\n\n// Unique staging names are the safe default: the cost is a random suffix, the\n// cost of the alternative is a lost update under concurrency (#2222).\nconst DEFAULT_UNIQUE_TMP = true;\n\nfunction tmpPathFor(filePath: string, uniqueTmp: boolean | undefined): string {\n return (uniqueTmp ?? DEFAULT_UNIQUE_TMP) ? `${filePath}.${randomBytes(6).toString(\"hex\")}.tmp` : `${filePath}.tmp`;\n}\n\n// On Windows, AV / Search Indexer / Defender briefly hold handles and rename trips EPERM/EBUSY/EACCES. Retry loop is\n// gated to Windows because POSIX EPERM means a real perm problem (read-only fs, sticky, cross-device) — retrying\n// just adds latency before the inevitable throw.\nconst IS_WINDOWS = process.platform === \"win32\";\n// The ASYNC ladder is generous because waiting is nearly free there — the call\n// yields, and a write that would otherwise throw is worth a few seconds. The\n// previous ~430 ms budget was not enough on a loaded Windows CI runner: the\n// notifier's `active.json` write lost the rename and threw, and the listener\n// waiting on it timed out ten seconds later, so the operation failed while the\n// contention it was retrying through had long since cleared (#2972 follow-up).\nconst RENAME_RETRY_DELAYS_MS = [30, 100, 300, 600, 1000, 2000] as const;\n// The SYNC ladder stays short on purpose. `sleepSync` parks the whole thread,\n// so a long budget here does not delay one write — it freezes the process. A\n// caller that cannot afford to yield cannot afford to wait either; failing\n// after ~430 ms and letting the caller decide beats a four-second stall.\nconst RENAME_RETRY_DELAYS_SYNC_MS = [30, 100, 300] as const;\n\nfunction hasErrnoCode(err: unknown): err is { code: string } {\n return typeof err === \"object\" && err !== null && \"code\" in err && typeof err.code === \"string\";\n}\n\n// `isWindows` is a parameter (defaulting to the real platform) so the safety-critical decision is testable on any OS.\n/** The retry budgets, exported so a test can assert what they cost rather than\n * hard-coding a second copy of the numbers. */\nexport const RENAME_RETRY_BUDGET_MS = RENAME_RETRY_DELAYS_MS.reduce((total, delay) => total + delay, 0);\nexport const RENAME_RETRY_BUDGET_SYNC_MS = RENAME_RETRY_DELAYS_SYNC_MS.reduce((total, delay) => total + delay, 0);\n\nexport function isTransientRenameError(err: unknown, isWindows: boolean = IS_WINDOWS): boolean {\n if (!isWindows || !hasErrnoCode(err)) return false;\n return err.code === \"EPERM\" || err.code === \"EBUSY\" || err.code === \"EACCES\";\n}\n\n// Injectable so a test can drive the retry path (fail-then-succeed rename, no-op sleep, isWindows=true) on any OS.\nexport interface RenameRetryDeps {\n rename: (fromPath: string, toPath: string) => Promise<void>;\n sleep: (millis: number) => Promise<void>;\n isWindows: boolean;\n}\n\nconst defaultRenameRetryDeps: RenameRetryDeps = {\n rename: (fromPath, toPath) => promises.rename(fromPath, toPath),\n sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),\n isWindows: IS_WINDOWS,\n};\n\nexport async function renameWithWindowsRetry(fromPath: string, toPath: string, deps: RenameRetryDeps = defaultRenameRetryDeps): Promise<void> {\n for (const delayMs of RENAME_RETRY_DELAYS_MS) {\n try {\n await deps.rename(fromPath, toPath);\n return;\n } catch (err) {\n if (!isTransientRenameError(err, deps.isWindows)) throw err;\n await deps.sleep(delayMs);\n }\n }\n // Final attempt — let any error propagate.\n await deps.rename(fromPath, toPath);\n}\n\n// Atomics.wait parks the thread instead of busy-spinning. Only on the Windows-rename retry path, and only on the SYNC\n// ladder, whose budget is capped at ~430ms precisely because this blocks everything.\nconst SYNC_SLEEP_BUF = new Int32Array(new SharedArrayBuffer(4));\nfunction sleepSync(millis: number): void {\n Atomics.wait(SYNC_SLEEP_BUF, 0, 0, millis);\n}\n\n// Deliberate async/sync twin of RenameRetryDeps: `sleep` blocks the thread instead of returning a Promise.\nexport interface RenameRetryDepsSync {\n rename: (fromPath: string, toPath: string) => void;\n sleep: (millis: number) => void;\n isWindows: boolean;\n}\n\nconst defaultRenameRetryDepsSync: RenameRetryDepsSync = {\n rename: (fromPath, toPath) => renameSync(fromPath, toPath),\n sleep: sleepSync,\n isWindows: IS_WINDOWS,\n};\n\nexport function renameSyncWithWindowsRetry(fromPath: string, toPath: string, deps: RenameRetryDepsSync = defaultRenameRetryDepsSync): void {\n for (const delayMs of RENAME_RETRY_DELAYS_SYNC_MS) {\n try {\n deps.rename(fromPath, toPath);\n return;\n } catch (err) {\n if (!isTransientRenameError(err, deps.isWindows)) throw err;\n deps.sleep(delayMs);\n }\n }\n deps.rename(fromPath, toPath);\n}\n\n// Forcing utf-8 on a Uint8Array would re-encode the bytes — wrong for PNGs and other binary blobs.\nfunction writeOptionsFor(content: string | Uint8Array, mode: number | undefined): { encoding?: \"utf-8\" | undefined; mode?: number | undefined } {\n return typeof content === \"string\" ? { encoding: \"utf-8\", mode } : { mode };\n}\n\nexport async function writeFileAtomic(filePath: string, content: string | Uint8Array, opts: WriteAtomicOptions = {}): Promise<void> {\n const tmp = tmpPathFor(filePath, opts.uniqueTmp);\n await promises.mkdir(path.dirname(filePath), { recursive: true });\n try {\n await promises.writeFile(tmp, content, writeOptionsFor(content, opts.mode));\n await renameWithWindowsRetry(tmp, filePath);\n } catch (err) {\n await promises.unlink(tmp).catch(() => {});\n throw err;\n }\n}\n\nexport function writeFileAtomicSync(filePath: string, content: string | Uint8Array, opts: WriteAtomicOptions = {}): void {\n const tmp = tmpPathFor(filePath, opts.uniqueTmp);\n mkdirSync(path.dirname(filePath), { recursive: true });\n try {\n writeFileSync(tmp, content, writeOptionsFor(content, opts.mode));\n renameSyncWithWindowsRetry(tmp, filePath);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best-effort cleanup\n }\n throw err;\n }\n}\n","// The canonical form of a workspace / project root.\n//\n// Lives here rather than in the collection engine because a root is an IDENTITY\n// in several subsystems that do not depend on each other — a watcher generation\n// key, a change payload, a completion-bell id, a scheduled task id — and every\n// one of them has to agree on it or the same project registers twice.\n\nimport path from \"node:path\";\n\n/** The canonical form of a root, for every place a root becomes an IDENTITY\n * rather than a path to read.\n *\n * `path.resolve` only — it collapses `.`/`..` and the trailing separator, so\n * `/work/project` and `/work/project/` are one root instead of two watcher\n * generations over the same tree, two bells per record, and two scheduled\n * refresh jobs.\n *\n * Deliberately NOT `realpath`. Resolving symlinks is async (so it could not run\n * on a synchronous claim path), it fails for a root that does not exist yet,\n * and it would put a path the host never named into an id that is written to\n * disk. The policy is therefore lexical: a host that hands the same tree under\n * two different symlink spellings gets two roots, and it is the host's job to\n * name a project the same way every time. */\nexport function canonicalRoot(root: string): string {\n return path.resolve(root);\n}\n"],"mappings":";;;;AAiCA,IAAM,qBAAqB;AAE3B,SAAS,WAAW,UAAkB,WAAwC;CAC5E,OAAQ,aAAa,qBAAsB,GAAG,SAAS,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE,QAAQ,GAAG,SAAS;AAC/G;AAKA,IAAM,aAAa,QAAQ,aAAa;AAOxC,IAAM,yBAAyB;CAAC;CAAI;CAAK;CAAK;CAAK;CAAM;AAAI;AAK7D,IAAM,8BAA8B;CAAC;CAAI;CAAK;AAAG;AAEjD,SAAS,aAAa,KAAuC;CAC3D,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,OAAO,IAAI,SAAS;AACzF;AAKsC,uBAAuB,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AAC3D,4BAA4B,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AAEhH,SAAgB,uBAAuB,KAAc,YAAqB,YAAqB;CAC7F,IAAI,CAAC,aAAa,CAAC,aAAa,GAAG,GAAG,OAAO;CAC7C,OAAO,IAAI,SAAS,WAAW,IAAI,SAAS,WAAW,IAAI,SAAS;AACtE;AASA,IAAM,yBAA0C;CAC9C,SAAS,UAAU,WAAW,SAAS,OAAO,UAAU,MAAM;CAC9D,QAAQ,WAAW,IAAI,SAAS,YAAY,WAAW,SAAS,MAAM,CAAC;CACvE,WAAW;AACb;AAEA,eAAsB,uBAAuB,UAAkB,QAAgB,OAAwB,wBAAuC;CAC5I,KAAK,MAAM,WAAW,wBACpB,IAAI;EACF,MAAM,KA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S;CACvH,MAAM,MAAM,WAAW,UAAU,KAAK,SAAS;CAC/C,UAAU,KAAK,QAAQ,QAAQ,GAAG,EAAE,WAAW,KAAK,CAAC;CACrD,IAAI;EACF,cAAc,KAAK,SAAS,gBAAgB,SAAS,KAAK,IAAI,CAAC;EAC/D,2BAA2B,KAAK,QAAQ;CAC1C,SAAS,KAAK;EACZ,IAAI;GACF,WAAW,GAAG;EAChB,QAAQ,CAER;EACA,MAAM;CACR;AACF;;;;;;;;;;;;;;;;;AC3IA,SAAgB,cAAc,MAAsB;CAClD,OAAO,KAAK,QAAQ,IAAI;AAC1B"}
|
|
1
|
+
{"version":3,"file":"root-CqxPNSyK.js","names":[],"sources":["../src/files/atomic.ts","../src/files/root.ts"],"sourcesContent":["// rename(2) is atomic on POSIX; Node's Windows fallback (copy+unlink) is still safer than truncating in place.\n// Readers always see either the old file or the new — never a half-written one.\n//\n// Single source of truth for atomic file writes across the whole monorepo\n// (host, core, plugins). Previously copy-pasted four times, so a Windows retry\n// fix landed in only one (#2399, precedent #2222).\n\nimport { mkdirSync, promises, renameSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { randomBytes } from \"node:crypto\";\n\nexport interface WriteAtomicOptions {\n mode?: number;\n /** Give the staging file a random suffix so concurrent writers to the same\n * destination can't collide at the OS layer.\n *\n * Defaults to `true`, and opting out is almost always wrong. A shared\n * `${filePath}.tmp` means two writers of one file race: the second write\n * overwrites the first's staging file, or one rename/unlink pulls it out\n * from under the other, surfacing as `ENOENT … rename '<file>.tmp'`. That is\n * not theoretical — it fired in production on session meta, where ten\n * distinct callers (`setClaudeSessionId`, `backfillOrigin`,\n * `incrementUserQueryCount`, …) all write the same `<sessionId>.json`\n * (#2222).\n *\n * Pass `false` only when you specifically need the staging path to be\n * predictable (e.g. a single-writer token file, or a test that pre-creates\n * it to force a write failure). */\n uniqueTmp?: boolean;\n}\n\n// Unique staging names are the safe default: the cost is a random suffix, the\n// cost of the alternative is a lost update under concurrency (#2222).\nconst DEFAULT_UNIQUE_TMP = true;\n\nfunction tmpPathFor(filePath: string, uniqueTmp: boolean | undefined): string {\n return (uniqueTmp ?? DEFAULT_UNIQUE_TMP) ? `${filePath}.${randomBytes(6).toString(\"hex\")}.tmp` : `${filePath}.tmp`;\n}\n\n// On Windows, AV / Search Indexer / Defender briefly hold handles and rename trips EPERM/EBUSY/EACCES. Retry loop is\n// gated to Windows because POSIX EPERM means a real perm problem (read-only fs, sticky, cross-device) — retrying\n// just adds latency before the inevitable throw.\nconst IS_WINDOWS = process.platform === \"win32\";\n// The ASYNC ladder is generous because waiting is nearly free there — the call\n// yields, and a write that would otherwise throw is worth a few seconds. The\n// previous ~430 ms budget was not enough on a loaded Windows CI runner: the\n// notifier's `active.json` write lost the rename and threw, and the listener\n// waiting on it timed out ten seconds later, so the operation failed while the\n// contention it was retrying through had long since cleared (#2972 follow-up).\nconst RENAME_RETRY_DELAYS_MS = [30, 100, 300, 600, 1000, 2000] as const;\n// The SYNC ladder stays short on purpose. `sleepSync` parks the whole thread,\n// so a long budget here does not delay one write — it freezes the process. A\n// caller that cannot afford to yield cannot afford to wait either; failing\n// after ~430 ms and letting the caller decide beats a four-second stall.\nconst RENAME_RETRY_DELAYS_SYNC_MS = [30, 100, 300] as const;\n\nfunction hasErrnoCode(err: unknown): err is { code: string } {\n return typeof err === \"object\" && err !== null && \"code\" in err && typeof err.code === \"string\";\n}\n\n// `isWindows` is a parameter (defaulting to the real platform) so the safety-critical decision is testable on any OS.\n/** The retry budgets, exported so a test can assert what they cost rather than\n * hard-coding a second copy of the numbers. */\nexport const RENAME_RETRY_BUDGET_MS = RENAME_RETRY_DELAYS_MS.reduce((total, delay) => total + delay, 0);\nexport const RENAME_RETRY_BUDGET_SYNC_MS = RENAME_RETRY_DELAYS_SYNC_MS.reduce((total, delay) => total + delay, 0);\n\nexport function isTransientRenameError(err: unknown, isWindows: boolean = IS_WINDOWS): boolean {\n if (!isWindows || !hasErrnoCode(err)) return false;\n return err.code === \"EPERM\" || err.code === \"EBUSY\" || err.code === \"EACCES\";\n}\n\n// Injectable so a test can drive the retry path (fail-then-succeed rename, no-op sleep, isWindows=true) on any OS.\nexport interface RenameRetryDeps {\n rename: (fromPath: string, toPath: string) => Promise<void>;\n sleep: (millis: number) => Promise<void>;\n isWindows: boolean;\n}\n\nconst defaultRenameRetryDeps: RenameRetryDeps = {\n rename: (fromPath, toPath) => promises.rename(fromPath, toPath),\n sleep: (millis) => new Promise((resolve) => setTimeout(resolve, millis)),\n isWindows: IS_WINDOWS,\n};\n\nexport async function renameWithWindowsRetry(fromPath: string, toPath: string, deps: RenameRetryDeps = defaultRenameRetryDeps): Promise<void> {\n for (const delayMs of RENAME_RETRY_DELAYS_MS) {\n try {\n await deps.rename(fromPath, toPath);\n return;\n } catch (err) {\n if (!isTransientRenameError(err, deps.isWindows)) throw err;\n await deps.sleep(delayMs);\n }\n }\n // Final attempt — let any error propagate.\n await deps.rename(fromPath, toPath);\n}\n\n// Atomics.wait parks the thread instead of busy-spinning. Only on the Windows-rename retry path, and only on the SYNC\n// ladder, whose budget is capped at ~430ms precisely because this blocks everything.\nconst SYNC_SLEEP_BUF = new Int32Array(new SharedArrayBuffer(4));\nfunction sleepSync(millis: number): void {\n Atomics.wait(SYNC_SLEEP_BUF, 0, 0, millis);\n}\n\n// Deliberate async/sync twin of RenameRetryDeps: `sleep` blocks the thread instead of returning a Promise.\nexport interface RenameRetryDepsSync {\n rename: (fromPath: string, toPath: string) => void;\n sleep: (millis: number) => void;\n isWindows: boolean;\n}\n\nconst defaultRenameRetryDepsSync: RenameRetryDepsSync = {\n rename: (fromPath, toPath) => renameSync(fromPath, toPath),\n sleep: sleepSync,\n isWindows: IS_WINDOWS,\n};\n\nexport function renameSyncWithWindowsRetry(fromPath: string, toPath: string, deps: RenameRetryDepsSync = defaultRenameRetryDepsSync): void {\n for (const delayMs of RENAME_RETRY_DELAYS_SYNC_MS) {\n try {\n deps.rename(fromPath, toPath);\n return;\n } catch (err) {\n if (!isTransientRenameError(err, deps.isWindows)) throw err;\n deps.sleep(delayMs);\n }\n }\n deps.rename(fromPath, toPath);\n}\n\n// Forcing utf-8 on a Uint8Array would re-encode the bytes — wrong for PNGs and other binary blobs.\nfunction writeOptionsFor(content: string | Uint8Array, mode: number | undefined): { encoding?: \"utf-8\" | undefined; mode?: number | undefined } {\n return typeof content === \"string\" ? { encoding: \"utf-8\", mode } : { mode };\n}\n\nexport async function writeFileAtomic(filePath: string, content: string | Uint8Array, opts: WriteAtomicOptions = {}): Promise<void> {\n const tmp = tmpPathFor(filePath, opts.uniqueTmp);\n await promises.mkdir(path.dirname(filePath), { recursive: true });\n try {\n await promises.writeFile(tmp, content, writeOptionsFor(content, opts.mode));\n await renameWithWindowsRetry(tmp, filePath);\n } catch (err) {\n await promises.unlink(tmp).catch(() => {});\n throw err;\n }\n}\n\nexport function writeFileAtomicSync(filePath: string, content: string | Uint8Array, opts: WriteAtomicOptions = {}): void {\n const tmp = tmpPathFor(filePath, opts.uniqueTmp);\n mkdirSync(path.dirname(filePath), { recursive: true });\n try {\n writeFileSync(tmp, content, writeOptionsFor(content, opts.mode));\n renameSyncWithWindowsRetry(tmp, filePath);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best-effort cleanup\n }\n throw err;\n }\n}\n","// The canonical form of a workspace / project root.\n//\n// Lives here rather than in the collection engine because a root is an IDENTITY\n// in several subsystems that do not depend on each other — a watcher generation\n// key, a change payload, a completion-bell id, a scheduled task id — and every\n// one of them has to agree on it or the same project registers twice.\n\nimport path from \"node:path\";\n\n/** The canonical form of a root, for every place a root becomes an IDENTITY\n * rather than a path to read.\n *\n * `path.resolve` only — it collapses `.`/`..` and the trailing separator, so\n * `/work/project` and `/work/project/` are one root instead of two watcher\n * generations over the same tree, two bells per record, and two scheduled\n * refresh jobs.\n *\n * Deliberately NOT `realpath`. Resolving symlinks is async (so it could not run\n * on a synchronous claim path), it fails for a root that does not exist yet,\n * and it would put a path the host never named into an id that is written to\n * disk. The policy is therefore lexical: a host that hands the same tree under\n * two different symlink spellings gets two roots, and it is the host's job to\n * name a project the same way every time. */\nexport function canonicalRoot(root: string): string {\n return path.resolve(root);\n}\n"],"mappings":";;;;AAiCA,IAAM,qBAAqB;AAE3B,SAAS,WAAW,UAAkB,WAAwC;CAC5E,OAAQ,aAAa,qBAAsB,GAAG,SAAS,GAAG,YAAY,CAAC,CAAC,CAAC,SAAS,KAAK,EAAE,QAAQ,GAAG,SAAS;AAC/G;AAKA,IAAM,aAAa,QAAQ,aAAa;AAOxC,IAAM,yBAAyB;CAAC;CAAI;CAAK;CAAK;CAAK;CAAM;AAAI;AAK7D,IAAM,8BAA8B;CAAC;CAAI;CAAK;AAAG;AAEjD,SAAS,aAAa,KAAuC;CAC3D,OAAO,OAAO,QAAQ,YAAY,QAAQ,QAAQ,UAAU,OAAO,OAAO,IAAI,SAAS;AACzF;AAKsC,uBAAuB,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AAC3D,4BAA4B,QAAQ,OAAO,UAAU,QAAQ,OAAO,CAAC;AAEhH,SAAgB,uBAAuB,KAAc,YAAqB,YAAqB;CAC7F,IAAI,CAAC,aAAa,CAAC,aAAa,GAAG,GAAG,OAAO;CAC7C,OAAO,IAAI,SAAS,WAAW,IAAI,SAAS,WAAW,IAAI,SAAS;AACtE;AASA,IAAM,yBAA0C;CAC9C,SAAS,UAAU,WAAW,SAAS,OAAO,UAAU,MAAM;CAC9D,QAAQ,WAAW,IAAI,SAAS,YAAY,WAAW,SAAS,MAAM,CAAC;CACvE,WAAW;AACb;AAEA,eAAsB,uBAAuB,UAAkB,QAAgB,OAAwB,wBAAuC;CAC5I,KAAK,MAAM,WAAW,wBACpB,IAAI;EACF,MAAM,KAAK,OAAO,UAAU,MAAM;EAClC;CACF,SAAS,KAAK;EACZ,IAAI,CAAC,uBAAuB,KAAK,KAAK,SAAS,GAAG,MAAM;EACxD,MAAM,KAAK,MAAM,OAAO;CAC1B;CAGF,MAAM,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,SAAS,KAAK,IAAI,CAAC;EAC/D,2BAA2B,KAAK,QAAQ;CAC1C,SAAS,KAAK;EACZ,IAAI;GACF,WAAW,GAAG;EAChB,QAAQ,CAER;EACA,MAAM;CACR;AACF;;;;;;;;;;;;;;;;AC3IA,SAAgB,cAAc,MAAsB;CAClD,OAAO,KAAK,QAAQ,IAAI;AAC1B"}
|
package/dist/scheduler/index.cjs
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_rolldown_runtime = require("../rolldown-runtime-
|
|
3
|
-
const require_dist = require("../dist-
|
|
4
|
-
require("../errors-
|
|
2
|
+
const require_rolldown_runtime = require("../rolldown-runtime-CmQyd0Gu.cjs");
|
|
3
|
+
const require_dist = require("../dist-734JaRYi.cjs");
|
|
4
|
+
require("../errors-B9mCEVG9.cjs");
|
|
5
5
|
let node_fs = require("node:fs");
|
|
6
6
|
let node_path = require("node:path");
|
|
7
7
|
node_path = require_rolldown_runtime.__toESM(node_path, 1);
|
|
8
8
|
let node_fs_promises = require("node:fs/promises");
|
|
9
9
|
let _receptron_task_scheduler = require("@receptron/task-scheduler");
|
|
10
|
-
|
|
10
|
+
// src/scheduler/schedule-window.ts
|
|
11
11
|
var ONE_SECOND_MS$1 = 1e3;
|
|
12
12
|
var ONE_DAY_MS = 86400 * ONE_SECOND_MS$1;
|
|
13
13
|
/** An interval this engine can never turn into a window. Zero divides by zero
|
|
@@ -82,8 +82,7 @@ function unfireableScheduleReason(schedule) {
|
|
|
82
82
|
value: schedule.time
|
|
83
83
|
};
|
|
84
84
|
}
|
|
85
|
-
|
|
86
|
-
//#region src/scheduler/task-manager.ts
|
|
85
|
+
// src/scheduler/task-manager.ts
|
|
87
86
|
var ONE_SECOND_MS = 1e3;
|
|
88
87
|
var ONE_MINUTE_MS = 60 * ONE_SECOND_MS;
|
|
89
88
|
var DEFAULT_FIRING_STAGGER_MS = ONE_SECOND_MS;
|
|
@@ -253,8 +252,7 @@ function createTaskManager(options) {
|
|
|
253
252
|
}
|
|
254
253
|
};
|
|
255
254
|
}
|
|
256
|
-
|
|
257
|
-
//#region src/scheduler/adapter.ts
|
|
255
|
+
// src/scheduler/adapter.ts
|
|
258
256
|
var SCHEDULER_CONFIG_DIR = "config/scheduler";
|
|
259
257
|
var SCHEDULER_DATA_DIR = "data/scheduler/logs";
|
|
260
258
|
var NOOP_LOG = {
|
|
@@ -522,7 +520,6 @@ function computeNextScheduledFor(schedule) {
|
|
|
522
520
|
if (unfireableScheduleReason(schedule) !== null) return null;
|
|
523
521
|
return windowToIso((0, _receptron_task_scheduler.nextWindowAfter)(toLibrarySchedule(schedule), Date.now() + 1));
|
|
524
522
|
}
|
|
525
|
-
//#endregion
|
|
526
523
|
Object.defineProperty(exports, "TASK_TRIGGERS", {
|
|
527
524
|
enumerable: true,
|
|
528
525
|
get: function() {
|