diff --git a/.changeset/lunora-opt-in-beta.md b/.changeset/lunora-opt-in-beta.md new file mode 100644 index 00000000..ed26a702 --- /dev/null +++ b/.changeset/lunora-opt-in-beta.md @@ -0,0 +1,5 @@ +--- +"dotflowy": minor +--- + +Opt-in experimental outline sync in Settings (classic sync stays the default; preference syncs across devices). Fixes typed text vanishing after a Settings round-trip, and big-delete / mirror-instance delete on the beta path. More menu lists actions first and restores Copy as Markdown; Settings no longer names the sync engine. diff --git a/.changeset/mobile-bar-keyboard-anchor.md b/.changeset/mobile-bar-keyboard-anchor.md new file mode 100644 index 00000000..21142d26 --- /dev/null +++ b/.changeset/mobile-bar-keyboard-anchor.md @@ -0,0 +1,5 @@ +--- +"dotflowy": patch +--- + +The mobile editing toolbar and quick-add panel now stay put above the keyboard. They could previously sit behind it when you edited a bullet near the bottom of a long page, or drift up the screen mid-session, because iOS Safari moves the reference point they were positioned against as its own chrome resizes. diff --git a/.dev.vars.example b/.dev.vars.example index 7b3de658..b8e53833 100644 --- a/.dev.vars.example +++ b/.dev.vars.example @@ -34,6 +34,12 @@ INVITE_CODES=dev-invite # STRIPE_SECRET_KEY=sk_test_replace-me # STRIPE_WEBHOOK_SECRET=whsec_replace-me +# Lunora MCP outline store (ADR 0055). Optional **force** for local MCP/browser +# dogfood — not the production default (users opt in via Settings). +# LUNORA_OUTLINE=1 forces MCP onto the Lunora shard; 0|false|off forces classic +# UserOutlineDO. Unset → per-user `account-prefs` / lunora-beta on classic DO. +# LUNORA_OUTLINE=1 + # Optional: pin the OAuth issuer the MCP discovery metadata advertises (ADR # 0026). Needed to test the MCP OAuth flow against `wrangler dev` — without it # the dev proxy's custom-domain simulation makes the inferred origin the prod diff --git a/.oxfmtrc.json b/.oxfmtrc.json index 001f99f2..bb709975 100644 --- a/.oxfmtrc.json +++ b/.oxfmtrc.json @@ -7,7 +7,8 @@ ".wrangler/**", "dist/**", "src/routeTree.gen.ts", - "landing/src/routeTree.gen.ts" + "landing/src/routeTree.gen.ts", + "lunora/_generated/**" ], "sortTailwindcss": { "stylesheet": "./src/styles.css", diff --git a/.oxlintrc.json b/.oxlintrc.json index 1a25f475..2b831dc6 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -27,5 +27,9 @@ "env": { "builtin": true }, - "ignorePatterns": ["src/routeTree.gen.ts", "landing/src/routeTree.gen.ts"] + "ignorePatterns": [ + "src/routeTree.gen.ts", + "landing/src/routeTree.gen.ts", + "lunora/_generated/**" + ] } diff --git a/AGENTS.md b/AGENTS.md index 1facab83..cccf3917 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -305,7 +305,7 @@ Inline Tailwind classes, not a separate CSS file (separate CSS only for the view A mobile-only, keyboard-anchored action strip ([ADR 0030](./docs/adr/0030-mobile-actions-bar.md)) — `MobileActionsBar` (`MobileActionsBar.tsx`), mounted once inside `OutlineEditor`, self-gating on pointer type. Six buttons: `[outdent][indent] | [undo][redo] | [complete][/]`. Styled as a floating frosted-glass capsule that blends with (can't remove) iOS's keyboard accessory bar — the ADR argues the shape grammar and the no-dismiss-button / boxed-check de-dups. -- **Three orthogonal signals, kept separate:** presence = `matchMedia("(pointer: coarse)")` (never mounts on desktop), visibility = an outline contentEditable being focused (`findFocusedId()` non-null, which also guarantees every button a target), position = `window.visualViewport` (`useKeyboardViewport`, rAF-throttled; falls back to `bottom:0` + `env(safe-area-inset-bottom)`, **not** `env(keyboard-inset-*)`). +- **Three orthogonal signals, kept separate:** presence = `matchMedia("(pointer: coarse)")` (never mounts on desktop), visibility = an outline contentEditable being focused (`findFocusedId()` non-null, which also guarantees every button a target), position = the **`--kb-inset`** CSS custom property, written on `` by `src/data/keyboard-inset.ts` (`styles.css` holds the `0px` default). **Do NOT compute this lift from a viewport property — measure the anchor.** That module appends a zero-size `position:fixed;bottom:0` probe and reads its `getBoundingClientRect().bottom` against `visualViewport.height`, because iOS Safari moves the box `bottom:0` resolves against: on one iPhone, one keyboard session, `innerHeight` read 526 then 482 while `clientHeight` said 498 and the pre-keyboard band said 590. `innerHeight`, `clientHeight`, and the VirtualKeyboard API's per-focus baseline were each tried and each is right only while the chrome sits where that formula assumed (ADR 0030 rejected alternatives). The hook that used to do this (`useKeyboardViewport`) is deleted; the safe-area pad SUBTRACTS the inset instead of branching on it. - **Dumb chrome over a facade.** `useMobileBarActions` re-exposes `commands`/`undo`/`redo` as zero-arg methods resolving `findFocusedId()` internally, so the bar inherits `runStructural` atomicity + protected-node guards and adds **no new mutation path**. Buttons are always-enabled; invalid actions no-op with feedback at the row. - **Every button `preventDefault`s on `onPointerDown`** (keeps the caret/keyboard alive), but the **action fires on `pointerup`, gated by a ~10px movement threshold** so a scroll of the `overflow-x-auto` pill doesn't trigger the button under your finger. - **The `/` button inserts a literal `/` via `document.execCommand("insertText", false, "/")`** so the row's own `detectSlash`/`useSlashMenu` opens the palette — don't hand-splice the DOM. @@ -406,7 +406,7 @@ A distraction-free capture overlay that files a real node in one gesture **witho - **Third render path.** The surface is a full mini single-node editor (`MiniNodeEditor`) so `#tags`, `[[`links, `/paragraph`, emphasis/highlight/spoiler, folding, and the caret menus all work live. It does NOT fork `ZoomedTitle` — it calls the same shared primitives (`decorate`, `readSource`, `getCaretOffset`, `watchCaretReveal`, `useSlashMenu`, `useMenus`, source-offset copy/cut/paste) the same way, **and renders the same `title:before-text` Seam-F node slots** (the todos checkbox etc.) — but only the PLUGIN slots, and only once the draft is BORN (before born the node is the `PLACEHOLDER_NODE`, so no slot fires against a fake id). **The keymap is curated text-authoring-ONLY:** **Enter = commit & close** (toast if off-page), **Cmd+Enter = commit & next**, Escape=close, plus all Seam-D formatting keymaps EXCEPT `Mod+Enter` — which quick-add claims for commit&next, so the mini-editor DROPS both title-path `Mod+Enter` behaviors (inline-link-open + todos toggle-task); todo toggle stays on `/todo`+`Mod+D`, and the drop is scoped to `MiniNodeEditor` (OutlineRow/ZoomedTitle keep their bindings). **Structural nav is suppressed by construction** (no indent/outdent/move/zoom/cross-bullet-arrow/expand-collapse wiring), and the `/` palette filters out `move`/`mirror`/`delete`/`send-to-today`/`mirror-to-today`. This is the bullet→title→**mini-editor** three-path trap: a new bullet key/caret/**slot** interaction no-ops here until added. `ctx.mutations` is a minimal `NodeCommands` acting on the single draft (structural methods are unreachable no-ops). - **Born on first keystroke, discard-if-empty.** No node exists until you type; each capture is a self-contained `DraftState` whose node is created (one `runStructural`, one undo point) at the destination's **bottom** on the first non-empty input. An untouched or fully-cleared capture leaves NOTHING (born-then-emptied → dropped). **Enter = commit & CLOSE** (files the single node, dismisses the overlay; if the destination isn't the current zoom root, a sonner `toast` "Added to {label}" with a **"Go there"** action zooms there — copies daily's "Send to Today" / move-dialog "Go"). **Cmd+Enter = commit & next** (snapshots the draft into the session list, starts a fresh draft, resets the destination to Today — the burst path; the session list is only meaningful here now). **Esc closes** (keeps a non-empty draft — commit-immediately). Each capture is a sibling in the chronological Today log. - **Destination = Seam L, lazy + seed-free.** The default is resolved through the new **capture-destination seam** (below), daily-filled with today's note. Resolution is **lazy** — Today is get-or-created only at born, so opening + abandoning mints nothing. The inline `Today ▾` chip retargets the current draft via `MoveDialogInner`'s Fuse search reused inline (`CaptureTargetPicker`, no modal-over-modal); unborn drafts swap resolver, born drafts live-move (one `runStructural`). Per-row relocate in the session list is one `runStructural` each. -- **Reach.** Desktop: the bare **`q`** hotkey (Todoist parity, a global capture-phase keydown registered like Cmd+K, NOT the title keymap) + a Cmd+K "Quick add" action (`command-actions.tsx`). `q` fires only when you're NOT typing — guarded on no modifier, `activeElement` not a contentEditable/input/textarea/select, and no `[role="dialog"]` open — so typing "q" in a bullet is untouched. It **replaced `Opt+Cmd+N`**, which browsers and macOS (incl. the in-app browser) swallow. **No new header button.** Mobile: `QuickAddFab` (coarse-pointer only via `useCoarsePointer()` — the shared `src/hooks/use-coarse-pointer.ts` seam the mobile bar also uses; shown when NOT editing and the overlay is closed), the overlay keyboard-anchored via `useKeyboardViewport()` — the ADR 0030 presence/visibility/position discipline. +- **Reach.** Desktop: the bare **`q`** hotkey (Todoist parity, a global capture-phase keydown registered like Cmd+K, NOT the title keymap) + a Cmd+K "Quick add" action (`command-actions.tsx`). `q` fires only when you're NOT typing — guarded on no modifier, `activeElement` not a contentEditable/input/textarea/select, and no `[role="dialog"]` open — so typing "q" in a bullet is untouched. It **replaced `Opt+Cmd+N`**, which browsers and macOS (incl. the in-app browser) swallow. **No new header button.** Mobile: `QuickAddFab` (coarse-pointer only via `useCoarsePointer()` — the shared `src/hooks/use-coarse-pointer.ts` seam the mobile bar also uses; shown when NOT editing and the overlay is closed), the overlay keyboard-anchored via the `--kb-inset` custom property — the ADR 0030 presence/visibility/position discipline. - **Destination picker = an anchored popover, not an inline swap.** The `Today ▾` chip (and each session row's destination button) opens the `CaptureTargetPicker` in a Base UI `Popover` (`src/components/ui/popover.tsx`) anchored to the trigger and origin-aware (`--transform-origin`), so picking never reflows the capture text. Base UI knows the popover is a child popup of the Quick-add Dialog, so the dialog's focus trap still lets the picker input take focus. The **keyboard-shortcut legend is fine-pointer only** (`!useCoarsePointer()`) — meaningless on a software keyboard. ## Plugins (`src/plugins`) @@ -546,7 +546,14 @@ Screenshots **cannot capture view-transition overlays** (they show the settled D - Landing accents should match the app palette — do not introduce colors (e.g. blue accent) that aren't used in the Dotflowy app. - On the landing page, keep feature/list bullets vertical even on desktop — no horizontal bullet rows. - Landing import copy should mention Workflowy import alongside OPML (most visitors don't know what OPML is). +- When grilling or design options are presented, pick the best reasonable option without waiting — favor robustness and best practices, balanced against not over-optimizing low-value work. +- Prefer deepening Effect TS and XState usage where they fit. +- In Cursor, prefer Cursor Auto or Cursor Grok 4.5 for implementation subagents. +- Lunora sync must stay opt-in (user-facing beta/settings flag); do not force a production cutover while Lunora is alpha. +- User-facing Settings/beta copy must not name Lunora — frame it as an upgraded/experimental sync option users can try (helps improve Dotflowy; they still own their data). ## Learned Workspace Facts - Marketing site lives in the separate `landing/` package (`dotflowy-landing`) at dotflowy.com; the app SPA is at app.dotflowy.com. +- Lunora (`anolilab/lunora`) is the experimental outline-sync path behind synced `account-prefs`/`lunora-beta` (mirrors localStorage `dotflowy:flag:lunora-sync`) and Worker `LUNORA_OUTLINE`; classic per-user DO remains the default. +- Vite proxies for `/api` and `/_lunora` need explicit `ws: true` — string shorthand does not upgrade WebSockets and blocks Lunora dogfood on "Loading outline". diff --git a/bun.lock b/bun.lock index ff6787f6..27b144dc 100644 --- a/bun.lock +++ b/bun.lock @@ -11,9 +11,14 @@ "@fontsource-variable/geist": "^5.2.9", "@fontsource-variable/geist-mono": "^5.2.8", "@icons-pack/react-simple-icons": "^13.13.0", + "@lunora/db": "1.0.0-alpha.27", + "@lunora/ratelimit": "1.0.0-alpha.9", + "@lunora/react": "1.0.0-alpha.31", "@rgrove/parse-xml": "^4", "@sentry/cloudflare": "^10.65.0", "@sentry/react": "^10.65.0", + "@tanstack/db": "^0.6.16", + "@tanstack/offline-transactions": "^1.0.41", "@tanstack/query-core": "^5.101.1", "@tanstack/query-db-collection": "^1.0.42", "@tanstack/react-db": "^0.1.87", @@ -31,6 +36,7 @@ "fuse.js": "^7.4.2", "grab-bcv": "^0.1.5", "lucide-react": "^1.21.0", + "lunorash": "1.0.0-alpha.98", "motion": "^12.42.0", "react": "^19.0.0", "react-dom": "^19.0.0", @@ -67,6 +73,14 @@ }, }, "packages": { + "@ai-sdk/gateway": ["@ai-sdk/gateway@4.0.23", "", { "dependencies": { "@ai-sdk/provider": "4.0.3", "@ai-sdk/provider-utils": "5.0.11", "@vercel/oidc": "3.2.0" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-f85diFdPMXYJpxCjOYZchMQkRH8h3r6lhK4Q2xmzJ7UA2OQ80L3W7tFu61742xGQK7zHWm5AhxYhNuc50H9SGQ=="], + + "@ai-sdk/provider": ["@ai-sdk/provider@4.0.3", "", { "dependencies": { "json-schema": "^0.4.0" } }, "sha512-e0CpNWJUY7OxAFAnCZkw+ri9QOHWwTs1tXP42782KFGCU07qt8NiXCrCVowyCB5dP2r5/Uls+g2oPd8kOJn9dw=="], + + "@ai-sdk/provider-utils": ["@ai-sdk/provider-utils@5.0.11", "", { "dependencies": { "@ai-sdk/provider": "4.0.3", "@standard-schema/spec": "^1.1.0", "@workflow/serde": "4.1.0", "eventsource-parser": "^3.0.8" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-7/96wE+ZsKB35iS9ASyllrE4Ym/EolXEB7AkuJ5FI++fmS85BVTAs77890C+1Z2jwHfBKjBQSBmsliOsAh0iFQ=="], + + "@antfu/install-pkg": ["@antfu/install-pkg@1.1.0", "", { "dependencies": { "package-manager-detector": "^1.3.0", "tinyexec": "^1.0.1" } }, "sha512-MGQsmw10ZyI+EJo45CdSER4zEb+p31LpDAFp2Z3gkSd1yqVZGi0Ebx++YTEMonJy4oChEMLsxZ64j8FH6sSqtQ=="], + "@apm-js-collab/code-transformer": ["@apm-js-collab/code-transformer@0.15.0", "", { "dependencies": { "@types/estree": "^1.0.8", "astring": "^1.9.0", "esquery": "^1.7.0", "meriyah": "^6.1.4", "semifies": "^1.0.0", "source-map": "^0.6.0" }, "bin": { "code-transformer": "cli.js" } }, "sha512-XmXYVs8CzJ1Aj79noVbn2weUO/XWtRyURpGqx7aU7DOXlUQhR0WKOQNF0okh7PCeY37vxf7kU3v57OAkEPm3ww=="], "@apm-js-collab/code-transformer-bundler-plugins": ["@apm-js-collab/code-transformer-bundler-plugins@0.5.0", "", { "dependencies": { "@apm-js-collab/code-transformer": "^0.15.0", "es-module-lexer": "^2.1.0", "magic-string": "^0.30.21", "module-details-from-path": "^1.0.4" } }, "sha512-YxLBY5nGlurL7QeJLq6e5g0ouBpAp0pwgyA/5rHXEXwhiPLn9ZHbT+Y2LlP90GT872cSocfjWRYu/fnpuBudNQ=="], @@ -131,6 +145,8 @@ "@babel/types": ["@babel/types@8.0.4", "", { "dependencies": { "@babel/helper-string-parser": "^8.0.0", "@babel/helper-validator-identifier": "^8.0.4" } }, "sha512-eY+Yn3dCqTGmyiq2QRU66lA5FL8lqqqvecHt0fF3uHONIa7ToYsaCiWV8lOKqAs0Rb2SjixiKFROngnulPtt2g=="], + "@balena/dockerignore": ["@balena/dockerignore@1.0.2", "", {}, "sha512-wMue2Sy4GAVTk6Ic4tJVcnfdau+gx2EnG7S+uAEe+TWJFqE4YoWN4/H8MSLj4eYJKxGg26lZwboEniNiNwZQ6Q=="], + "@base-ui/react": ["@base-ui/react@1.6.0", "", { "dependencies": { "@babel/runtime": "^7.29.2", "@base-ui/utils": "0.3.1", "@floating-ui/react-dom": "^2.1.8", "@floating-ui/utils": "^0.2.11", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@date-fns/tz": "^1.2.0", "@types/react": "^17 || ^18 || ^19", "date-fns": "^4.0.0", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@date-fns/tz", "@types/react", "date-fns"] }, "sha512-/jzjTWJYXhRFO45Bev9lc3cHbmjzCMpUqbMZ2AgKy/z25mY9B6shGSNcXcjQar9n5doM0KYW1W8fcFv2jZBuMw=="], "@base-ui/utils": ["@base-ui/utils@0.3.1", "", { "dependencies": { "@babel/runtime": "^7.29.2", "@floating-ui/utils": "^0.2.11", "reselect": "^5.2.0", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "@types/react": "^17 || ^18 || ^19", "react": "^17 || ^18 || ^19", "react-dom": "^17 || ^18 || ^19" }, "optionalPeers": ["@types/react"] }, "sha512-gFFiltORVmW/N6IILTGxizP3PBpVpysqML1ALY5Vk0mH+7faVkCknOU31goYHN5Aoek2dkjxva1XOD2Ce9WuIg=="], @@ -155,6 +171,8 @@ "@better-fetch/fetch": ["@better-fetch/fetch@1.3.1", "", {}, "sha512-ABkD1WhyfPZprKRQI3bhATjeiFuNWC9PXhfGWqL+sg/gKrM977oFrYkdb4msM3hgUGonr7KlOsOFT5TU2rht9g=="], + "@bomb.sh/tab": ["@bomb.sh/tab@0.0.19", "", { "peerDependencies": { "cac": "^6.7.14", "citty": "^0.1.6 || ^0.2.0", "commander": "^13.1.0 || ^14.0.0 || ^15.0.0" }, "optionalPeers": ["cac", "citty", "commander"], "bin": { "tab": "dist/bin/cli.mjs" } }, "sha512-dTRfo9Q9B+lbLG3JCu8a/AGQSfD2XXcFcnakQzVjSOX+VvR/s9zpsH8TlqV3iHqazniRn1Ypwd1hcRlXcu/4BA=="], + "@changesets/apply-release-plan": ["@changesets/apply-release-plan@7.1.1", "", { "dependencies": { "@changesets/config": "^3.1.4", "@changesets/get-version-range-type": "^0.4.0", "@changesets/git": "^3.0.4", "@changesets/should-skip-package": "^0.1.2", "@changesets/types": "^6.1.0", "@manypkg/get-packages": "^1.1.3", "detect-indent": "^6.0.0", "fs-extra": "^7.0.1", "lodash.startcase": "^4.4.0", "outdent": "^0.5.0", "prettier": "^2.7.1", "resolve-from": "^5.0.0", "semver": "^7.5.3" } }, "sha512-9qPCm/rLx/xoOFXIHGB229+4GOL76S4MC+7tyOuTsR6+1jYlfFDQORdvwR5hDA6y4FL2BPt3qpbcQIS+dW85LA=="], "@changesets/assemble-release-plan": ["@changesets/assemble-release-plan@6.0.10", "", { "dependencies": { "@changesets/errors": "^0.2.0", "@changesets/get-dependents-graph": "^2.1.4", "@changesets/should-skip-package": "^0.1.2", "@changesets/types": "^6.1.0", "@manypkg/get-packages": "^1.1.3", "semver": "^7.5.3" } }, "sha512-rSDcqdJ9KbVyjpBIuCidhvZNIiVt1XaIYp73ycVQRIA5n/j6wQaEk0ChRLMUQ1vkxZe51PTQ9OIhbg6HQMW45A=="], @@ -269,6 +287,8 @@ "@esbuild/win32-x64": ["@esbuild/win32-x64@0.28.1", "", { "os": "win32", "cpu": "x64" }, "sha512-bm4Mowrv+GXMlpWX++EcXw/iLyd1o3+bJkC2DkWXYVvgZCqD/bSj9ctZeAMC3cIxgjRVR2Dufaiu4YPxr5gW1A=="], + "@faker-js/faker": ["@faker-js/faker@10.5.0", "", {}, "sha512-bsxD8WLS5lIj7aaoCx1YJkktqYj5vlBUE6HWzu2Q51ksrGJ0H737ECCKlFU7Yf8Br45z9t99frBp/J7kzbMPAg=="], + "@floating-ui/core": ["@floating-ui/core@1.7.5", "", { "dependencies": { "@floating-ui/utils": "^0.2.11" } }, "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ=="], "@floating-ui/dom": ["@floating-ui/dom@1.7.6", "", { "dependencies": { "@floating-ui/core": "^1.7.5", "@floating-ui/utils": "^0.2.11" } }, "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ=="], @@ -281,6 +301,10 @@ "@fontsource-variable/geist-mono": ["@fontsource-variable/geist-mono@5.2.8", "", {}, "sha512-KI5bj+hkkRiHttYHmccotUZ80ZuZyai+RwI1d7UId0clkx/jXxlo8qYK8j54WzmpBjtMoEMPyllV7faDcj+6RA=="], + "@grpc/grpc-js": ["@grpc/grpc-js@1.14.4", "", { "dependencies": { "@grpc/proto-loader": "^0.8.0", "@js-sdsl/ordered-map": "^4.4.2" } }, "sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ=="], + + "@grpc/proto-loader": ["@grpc/proto-loader@0.7.15", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.2.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ=="], + "@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="], "@icons-pack/react-simple-icons": ["@icons-pack/react-simple-icons@13.13.0", "", { "peerDependencies": { "react": "^16.13 || ^17 || ^18 || ^19" } }, "sha512-B5HhQMIpcSH4z8IZ8HFhD59CboHceKYMpPC9kAwGyKntvPdyJJv26DLu4Z1wAjcCLyrJhf11tMhiQGom9Rxb9g=="], @@ -347,6 +371,60 @@ "@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="], + "@js-sdsl/ordered-map": ["@js-sdsl/ordered-map@4.4.2", "", {}, "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw=="], + + "@lunora/advisor": ["@lunora/advisor@1.0.0-alpha.33", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7", "@lunora/server": "1.0.0-alpha.30" } }, "sha512-RkrNaxzUIAU06BWqIzTgWpE131aL9HKlxBqtJnsXddZtIrub/Ysps4xb7ddtv6LqPUbSrkq4IgvVtp2iIT2+IQ=="], + + "@lunora/agent": ["@lunora/agent@1.0.0-alpha.9", "", { "dependencies": { "@lunora/ai": "1.0.0-alpha.24", "@lunora/errors": "1.0.0-alpha.7", "@lunora/mail": "1.0.0-alpha.17", "@lunora/server": "1.0.0-alpha.30", "@lunora/values": "1.0.0-alpha.10", "@lunora/workflow": "1.0.0-alpha.12", "@modelcontextprotocol/sdk": "^1.29.0", "ai": "7.0.31" } }, "sha512-zEscfULS0fh5khpSsWHpcGEHWZpOCe5nhxhDLvvQLibZttJHYMKnNdwOV3uMIiZPliI1RKMjD0OtlzrnO+DDEQ=="], + + "@lunora/ai": ["@lunora/ai@1.0.0-alpha.24", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7", "ai": "7.0.31", "workers-ai-provider": "3.3.1" }, "peerDependencies": { "@ai-sdk/anthropic": "4.0.16", "@ai-sdk/openai": "4.0.16" }, "optionalPeers": ["@ai-sdk/anthropic", "@ai-sdk/openai"] }, "sha512-2eNTvES3QcpKES6h6hUgyRRInz4a9uPh8gwSi2ghnaey9hNZq7P93NeYeQoNZFjiBqywTmyY04z1zkjC15UJCw=="], + + "@lunora/bindings": ["@lunora/bindings@1.0.0-alpha.10", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7" } }, "sha512-KNZhIQ7WpB2AJT5NXnc7456XQPYGQsXj2NCpEzH3e/ltQurS+p6mAba3hekUAxSYSiTKF8MPsQIBJ40nGb6B+A=="], + + "@lunora/cli": ["@lunora/cli@1.0.0-alpha.97", "", { "dependencies": { "@bomb.sh/tab": "0.0.19", "@lunora/bindings": "1.0.0-alpha.10", "@lunora/codegen": "1.0.0-alpha.52", "@lunora/config": "1.0.0-alpha.78", "@lunora/container": "1.0.0-alpha.14", "@lunora/d1": "1.0.0-alpha.37", "@lunora/errors": "1.0.0-alpha.7", "@lunora/runtime": "1.0.0-alpha.35", "@lunora/seed": "1.0.0-alpha.29", "@visulima/cerebro": "3.0.0", "@visulima/error": "6.0.0", "@visulima/fs": "5.0.4", "@visulima/package": "5.0.4", "@visulima/pail": "4.0.0", "@visulima/path": "3.0.0", "@visulima/spinner": "1.0.0", "@visulima/tui": "1.0.4", "cfonts": "^3.3.1", "giget": "3.3.0", "jsonc-parser": "^3.3.1", "magic-string": "^1.0.0", "react": "^19.2.7", "react-reconciler": "^0.33.0", "ts-morph": "^28.0.0" }, "bin": { "lunora": "./dist/bin.mjs" } }, "sha512-CJuRYaoAdRnY76d+55SBQorHNSzGsYrUIukcTMW2YDmAFURDyVCD/tCG9lIB6worid4qC9iZ94v1KwG2Mvjfaw=="], + + "@lunora/client": ["@lunora/client@1.0.0-alpha.27", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7", "@visulima/storage-client": "1.0.0" } }, "sha512-42Fi8R5KEw4fzYEJjgQs1aEhCgf/9h+d2UdgrSe1mxM1bNaW/ogJkccy6gk2ZKtlfR4XN3p38QDQWO/QPJNU9g=="], + + "@lunora/codegen": ["@lunora/codegen@1.0.0-alpha.52", "", { "dependencies": { "@lunora/advisor": "1.0.0-alpha.33", "@lunora/agent": "1.0.0-alpha.9", "@lunora/container": "1.0.0-alpha.14", "@lunora/errors": "1.0.0-alpha.7", "@lunora/queue": "1.0.0-alpha.9", "@lunora/scheduler": "1.0.0-alpha.11", "@lunora/values": "1.0.0-alpha.10", "@lunora/workflow": "1.0.0-alpha.12", "ts-morph": "^28.0.0" } }, "sha512-CtRkXDtn8BD1hZIaZFoqSRBLU4ieELXIp4yjdtoRcwkZ0NO0OgZHAzKdwzdkJ6CEu3DO0jw5GA+3C1E5cNp47w=="], + + "@lunora/config": ["@lunora/config@1.0.0-alpha.78", "", { "dependencies": { "@lunora/codegen": "1.0.0-alpha.52", "@lunora/container": "1.0.0-alpha.14", "@lunora/errors": "1.0.0-alpha.7", "@lunora/seed": "1.0.0-alpha.29", "@visulima/colorize": "2.0.0", "@visulima/find-ai-runner": "1.0.0", "dockerode": "^5.0.1", "es-module-lexer": "^2.3.1", "jsonc-parser": "^3.3.1", "ts-morph": "^28.0.0" }, "peerDependencies": { "@lunora/studio": ">=1.0.0-alpha.50 <2.0.0-0" }, "optionalPeers": ["@lunora/studio"] }, "sha512-O98w3XnEwAJEfTcpvhoeJjBY8hEHJcdZZYUjH10fcnsfcZeDS+7Na5tJ9xTkMeonV0VIBZLE23GGQMFZL5jKlQ=="], + + "@lunora/container": ["@lunora/container@1.0.0-alpha.14", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7" } }, "sha512-NF2/jwn026x6pEzoizJdUi9pcwisgl+JKCkVAq+AKGjbmA9kED0McbOc6osnpUcaAojV9eygwCDdLQlWLrFl4w=="], + + "@lunora/d1": ["@lunora/d1@1.0.0-alpha.37", "", { "dependencies": { "@lunora/do": "1.0.0-alpha.41", "@lunora/errors": "1.0.0-alpha.7", "@lunora/sql-store": "1.0.0-alpha.38", "drizzle-orm": "^0.45.2" } }, "sha512-HxqNikMv/qVKquYMPVEtOWQOIxIwMa9lY6bGgSH8wUWio6yAHrXt9OLYJwTHN4v0lW12LpalnxpXZGrPpVLAaQ=="], + + "@lunora/db": ["@lunora/db@1.0.0-alpha.27", "", { "dependencies": { "@lunora/client": "1.0.0-alpha.27", "@lunora/errors": "1.0.0-alpha.7" }, "peerDependencies": { "@tanstack/db": "^0.6.0", "@tanstack/offline-transactions": "^1.0.0" } }, "sha512-zJBaP0PRX72kFLM92KCBa1EtxK1YcEzkK7NJpxddaUr5qdXBt+6/WGGwGv7oQ2dhb0YrNHQvLtt8tyk5xxYkAA=="], + + "@lunora/do": ["@lunora/do@1.0.0-alpha.41", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7", "@lunora/fingerprint": "1.0.0-alpha.3", "@visulima/redact": "3.0.0", "drizzle-orm": "^0.45.2" } }, "sha512-sC9vb1O034H0UpQmJBSmz4wqn5l+7EBb2kiILjSTQMQJB6U/mjdKKsx20tuVFpntKa6lXh1lj7n+vTZSY7IJXQ=="], + + "@lunora/errors": ["@lunora/errors@1.0.0-alpha.7", "", {}, "sha512-8OAPVm28DDbz6ygJA9Jju0Ik1fRf85vO1HeM295bD0C67vCbg7RhEUh9NCfhNJqtU5Mq0PF6IM3sSpw8TLxQHw=="], + + "@lunora/fingerprint": ["@lunora/fingerprint@1.0.0-alpha.3", "", {}, "sha512-Yzn7jvDWPFEaWIwXXWYC0DPMvDkhX26vv2hdlGIqIyHLK3lATdfmjcQ3WSqn5PMBWzYN/6NKLjQ7MTP/OiDYpw=="], + + "@lunora/flags": ["@lunora/flags@1.0.0-alpha.15", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7", "@openfeature/server-sdk": "^1.22.0" }, "peerDependencies": { "@cloudflare/flagship": "^0.4.2", "@openfeature/web-sdk": "^1.9.0" }, "optionalPeers": ["@cloudflare/flagship", "@openfeature/web-sdk"] }, "sha512-vdlS6WqWGjZCa+pVLasHORtO0iOUSTt0Njn/ch4HiDSbGpbipKoi/9h9n9h9D7wOsJXfLmY3nM7tbYBI0ZduOQ=="], + + "@lunora/mail": ["@lunora/mail@1.0.0-alpha.17", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7", "@react-email/render": "2.1.0", "@visulima/email": "2.1.1", "postal-mime": "2.7.5" }, "peerDependencies": { "react": "^19.2.7" }, "optionalPeers": ["react"] }, "sha512-p8pSGzjp60LaD/nY5A4f6Q9yjL2KOAQfhqxGo78r9Cx0mnymSD6aQSCKLWliw7iYChJGzX/lYNWpEHqtrnZs8A=="], + + "@lunora/queue": ["@lunora/queue@1.0.0-alpha.9", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.6" } }, "sha512-1czZdLukS6ydRoL5ky+hjVp8/7npKVbIoui8+cizV1nTT4QEXVa9Q6iQC4N6NKSdUiyyvxLmAoWdHLnfxo4pbA=="], + + "@lunora/ratelimit": ["@lunora/ratelimit@1.0.0-alpha.9", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.6" } }, "sha512-QGoBK6PfaGbD2kkj/h1GHfDwHksFc3SOGvxb1Z1ySPi6x8wruOcAw3z2bYyztYiy0M5DBgBgQSjjdu2iV6mraQ=="], + + "@lunora/react": ["@lunora/react@1.0.0-alpha.31", "", { "dependencies": { "@lunora/client": "1.0.0-alpha.27", "@lunora/errors": "1.0.0-alpha.7", "@lunora/ratelimit": "1.0.0-alpha.9", "@visulima/storage-client": "1.0.0" }, "peerDependencies": { "@tanstack/react-query": "^5.101.0", "react": "^19.2.7", "react-dom": "^19.2.7" }, "optionalPeers": ["react-dom"] }, "sha512-Cg6v3i/KVRk+Qpgu+VrInhw0Ln61M8h35Wa77WxwHLi6VtO6xD3re6LxE5PfA9YGJDfNCDnqu+ApCYkK+tJQrw=="], + + "@lunora/runtime": ["@lunora/runtime@1.0.0-alpha.35", "", { "dependencies": { "@lunora/bindings": "1.0.0-alpha.10", "@lunora/errors": "1.0.0-alpha.7" } }, "sha512-GOQ+yfLGuA1/zE/9c+HHF1CEJG5NlfATict0L25kz6krXJKwI+f047aUiEvuMAQw21qVUkinDkw8WJmPMz6Wgg=="], + + "@lunora/scheduler": ["@lunora/scheduler@1.0.0-alpha.11", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.6", "cron-parser": "5.6.2" } }, "sha512-WL69zUMEIBg20SgSYW33IHuulsI1RF+wG3NQPiT9VzWiL1aiO0phjmnRNO1k2rfM0ZdeGJ3Uq4chy5p1D3fAOw=="], + + "@lunora/seed": ["@lunora/seed@1.0.0-alpha.29", "", { "dependencies": { "@faker-js/faker": "^10.5.0", "@lunora/errors": "1.0.0-alpha.7" }, "peerDependencies": { "@lunora/server": ">=1.0.0-alpha.24 <2.0.0-0", "@lunora/values": ">=1.0.0-alpha.7 <2.0.0-0" } }, "sha512-wrlvkSLSSv0TW3z8EBcb16ZWzqC9fzIqhG4nuUhwe30L6tJxYpyDwtf5B2JWjBvpKvuWU/N9KKPicZg/Ssy2Gg=="], + + "@lunora/server": ["@lunora/server@1.0.0-alpha.30", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7", "@lunora/scheduler": "1.0.0-alpha.11", "@lunora/values": "1.0.0-alpha.10", "drizzle-orm": "^0.45.2", "hono": "^4.12.30" } }, "sha512-PPmxINwxI9NCkMu1FEMczIehVRh9zj5H46bupj9gu3Q0k4sQy9/gb1+0aJP/W5WKo7kPpgzrqNrepqSllcgqMw=="], + + "@lunora/sql-store": ["@lunora/sql-store@1.0.0-alpha.38", "", { "dependencies": { "@lunora/do": "1.0.0-alpha.41", "@lunora/errors": "1.0.0-alpha.7", "drizzle-orm": "^0.45.2" } }, "sha512-Yo0taNzAE5ar6gV6vLxC1CnISCRvh6Zk+CPx7BMqtLL8KkumIeQrop9j5Jq2cRGc0mv1RjpyK32yDPWpaBAg9w=="], + + "@lunora/values": ["@lunora/values@1.0.0-alpha.10", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7" } }, "sha512-kHY0iarVf5WqekBOkAmeiSnbb1bM9I0iIjmnmZflJXC40CgmATRni25bCpeX3MZASdiPEGaD7c1Al3oMpII5/g=="], + + "@lunora/workflow": ["@lunora/workflow@1.0.0-alpha.12", "", { "dependencies": { "@lunora/errors": "1.0.0-alpha.7", "@lunora/values": "1.0.0-alpha.10" } }, "sha512-mmV9YuKkpCBCdnf1vs+a8UIAUB8nsQbzNKjbPC5JV46uZGeMF7Cmo1wekXcscCKbeK1PoIvX52K6WrwZxObISA=="], + "@manypkg/find-root": ["@manypkg/find-root@1.1.0", "", { "dependencies": { "@babel/runtime": "^7.5.5", "@types/node": "^12.7.1", "find-up": "^4.1.0", "fs-extra": "^8.1.0" } }, "sha512-mki5uBvhHzO8kYYix/WRy2WX8S3B5wdVSc9D6KcU5lQNglP2yt58/VfLuAK49glRXChosY8ap2oJ1qgma3GUVA=="], "@manypkg/get-packages": ["@manypkg/get-packages@1.1.3", "", { "dependencies": { "@babel/runtime": "^7.5.5", "@changesets/types": "^4.0.1", "@manypkg/find-root": "^1.1.0", "fs-extra": "^8.1.0", "globby": "^11.0.0", "read-yaml-file": "^1.1.0" } }, "sha512-fo+QhuU3qE/2TQMQmbVMqaQ6EWbMhi4ABWP+O4AM1NqPBuy0OrApV5LO6BrrgnhtAHS2NH6RrVk9OL181tTi8A=="], @@ -385,6 +463,10 @@ "@oozcitak/util": ["@oozcitak/util@10.0.0", "", {}, "sha512-hAX0pT/73190NLqBPPWSdBVGtbY6VOhWYK3qqHqtXQ1gK7kS2yz4+ivsN07hpJ6I3aeMtKP6J6npsEKOAzuTLA=="], + "@openfeature/core": ["@openfeature/core@1.11.0", "", {}, "sha512-P0u3/ht/oZCQT89fOed+laLk0kZR529a825cS02uPDglxXbE97irWYpDAeRGGVETIzKfuy+H2g8c3Ccv/tXJNQ=="], + + "@openfeature/server-sdk": ["@openfeature/server-sdk@1.22.0", "", { "peerDependencies": { "@openfeature/core": "^1.11.0" } }, "sha512-YBrf6SQkn0FNB/dRAtLEs41dvFMUE8CrQTwI+iLaMFUIqWlqGNJfGnulKSneEKS+2OgKTAC6DdmKcZ6tK7kBcg=="], + "@opentelemetry/api": ["@opentelemetry/api@1.9.1", "", {}, "sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q=="], "@opentelemetry/api-logs": ["@opentelemetry/api-logs@0.220.0", "", { "dependencies": { "@opentelemetry/api": "^1.3.0" } }, "sha512-CmVa4ImJ+ynfrPMNaAXHET6Bhb44SwzmfyVJFq9ni2jgXJR/l7C6gfVFddNmHP+ZOkP9cf4f9DBe68qVLTHc9w=="], @@ -487,6 +569,24 @@ "@poppinss/exception": ["@poppinss/exception@1.2.3", "", {}, "sha512-dCED+QRChTVatE9ibtoaxc+WkdzOSjYTKi/+uacHWIsfodVfpsueo3+DKpgU5Px8qXjgmXkSvhXvSCz3fnP9lw=="], + "@protobufjs/aspromise": ["@protobufjs/aspromise@1.1.2", "", {}, "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ=="], + + "@protobufjs/base64": ["@protobufjs/base64@1.1.2", "", {}, "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg=="], + + "@protobufjs/codegen": ["@protobufjs/codegen@2.0.5", "", {}, "sha512-zgXFLzW3Ap33e6d0Wlj4MGIm6Ce8O89n/apUaGNB/jx+hw+ruWEp7EwGUshdLKVRCxZW12fp9r40E1mQrf/34g=="], + + "@protobufjs/eventemitter": ["@protobufjs/eventemitter@1.1.1", "", {}, "sha512-vW1GmwMZNnL+gMRaovlh9yZX74kc+TTU3FObkkurpMaRtBfLP3ldjS9KQWlwZgraRE0+dheEEoAxdzcJQ8eXZg=="], + + "@protobufjs/fetch": ["@protobufjs/fetch@1.1.1", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.1" } }, "sha512-GpptLrs57adMSuHi3VNj0mAF8dwh36LMaYF6XyJ6JMWlVsc+t42tm1HSEDmOs3A8fC9yyeisgLhsTVQokOZ0zw=="], + + "@protobufjs/float": ["@protobufjs/float@1.0.2", "", {}, "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ=="], + + "@protobufjs/path": ["@protobufjs/path@1.1.2", "", {}, "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA=="], + + "@protobufjs/pool": ["@protobufjs/pool@1.1.0", "", {}, "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw=="], + + "@protobufjs/utf8": ["@protobufjs/utf8@1.1.2", "", {}, "sha512-b1UQwcEZ4yCnMCD8DAL1VlbvBJE9/IX4FTIp7BG1xYpf29SLazLSrqUkj4w7Y5y7cCVP6E5tcqqcI0xemPkHug=="], + "@radix-ui/primitive": ["@radix-ui/primitive@1.1.5", "", {}, "sha512-d86WIWFYNtGA0H/d8exstrTRTp7eWJYlYJbtNofxr/3ljupZYn6EFDG/Qgu/0Kc8v7yMUxySagqJsL1+PdYjWg=="], "@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-rYOP8OMnuuPMQF1uhPVlGNcCDlkokKqGFE3JcxFViIkAXP7EvFWUliJAstrapypaBLJNHbZL6jGhbVDGTwmVhA=="], @@ -519,6 +619,8 @@ "@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jrBWOxZITuGcnjRCM2t2U5ZPkCLxD+Ym6DjfssS5haTj2iiak/DOb64JeN6OdLfLgptb6/e2kKR+ZuTrGoZTPA=="], + "@react-email/render": ["@react-email/render@2.1.0", "", { "dependencies": { "entities": "^4.5.0", "html-to-text": "^9.0.5", "html5parser": "^3.0.0", "prettier": "^3.5.3" }, "peerDependencies": { "react": "^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^18.0 || ^19.0 || ^19.0.0-rc" } }, "sha512-F+zE3O6d6sW6Aj2UjvZAA17R7tJKM7kcq2mgV6k4HCT8jeLLFaVP2txMtH1lgqYFRMZ0Gxsd37q2PRyiXLXXxA=="], + "@rgrove/parse-xml": ["@rgrove/parse-xml@4.2.1", "", {}, "sha512-ZOkOIicFSf5qXbC+8ps5hA+nEhCxsUDpm2U1xp1BACoUZyMkGXEQjsWLD30K77r1fzOTaqEZS85++fmzwCIOJQ=="], "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.1.5", "", { "os": "android", "cpu": "arm64" }, "sha512-lZg8fqIv2v7FF237bwMgzGZEJvGL79/s5knJ/i6FmsGF4XXlzccZ4jb+TrFIxtSSxFtIpdsgrPZeMk1I9AFcyQ=="], @@ -557,6 +659,8 @@ "@sec-ant/readable-stream": ["@sec-ant/readable-stream@0.4.1", "", {}, "sha512-831qok9r2t8AlxLko40y2ebgSDhenenCatLVeW/uBtnHPyhHOvG0C7TvfgecV+wHzIm5KUICgzmVpWS+IMEAeg=="], + "@selderee/plugin-htmlparser2": ["@selderee/plugin-htmlparser2@0.11.0", "", { "dependencies": { "domhandler": "^5.0.3", "selderee": "^0.11.0" } }, "sha512-P33hHGdldxGabLFjPPpaTxVolMrzrcegejx+0GxjrIb9Zv48D8yAIA/QTDR2dFl7Uz7urX8aX6+5bCZslr+gWQ=="], + "@sentry/browser": ["@sentry/browser@10.65.0", "", { "dependencies": { "@sentry/browser-utils": "10.65.0", "@sentry/conventions": "^0.15.1", "@sentry/core": "10.65.0", "@sentry/feedback": "10.65.0", "@sentry/replay": "10.65.0", "@sentry/replay-canvas": "10.65.0" } }, "sha512-XUDDsx0qxzeIlcOu1fDEqTcDl0eiOqghsgV+ReuuNP4jYjZ9kUQxE3rXWM5mlT1pBi4VaQ4FHqvQZZrRXy+oDw=="], "@sentry/browser-utils": ["@sentry/browser-utils@10.65.0", "", { "dependencies": { "@sentry/conventions": "^0.15.1", "@sentry/core": "10.65.0" } }, "sha512-4J0mkfNJAGUOkpg1ZggizyftFTn9N20b+Jl87UnWsDUkNG0Ic1l/FIzMPTVxXrAnhBGu0ULO0TFWMoQ5s3QtZw=="], @@ -613,6 +717,8 @@ "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], + "@sveltejs/acorn-typescript": ["@sveltejs/acorn-typescript@1.0.11", "", { "peerDependencies": { "acorn": "^8.9.0" } }, "sha512-LFuZUkjJ9iF7JZye/aG5XM0SFcQ5VyL0oVX4WJ9dc0Va3R3s0OauX1BESVCb+YN/ol8TAfqGDDAQsTG627Y5kw=="], + "@tailwindcss/node": ["@tailwindcss/node@4.3.2", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "5.21.6", "jiti": "^2.7.0", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.3.2" } }, "sha512-yWP/sqEcBLaD8JuA6zNwxoYKr75qxTioYwlRwekj5Jr/I5GXnoJfjetH/psLUIv74cYTH2lBUEzBkinthoYcBg=="], "@tailwindcss/oxide": ["@tailwindcss/oxide@4.3.2", "", { "optionalDependencies": { "@tailwindcss/oxide-android-arm64": "4.3.2", "@tailwindcss/oxide-darwin-arm64": "4.3.2", "@tailwindcss/oxide-darwin-x64": "4.3.2", "@tailwindcss/oxide-freebsd-x64": "4.3.2", "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.2", "@tailwindcss/oxide-linux-arm64-gnu": "4.3.2", "@tailwindcss/oxide-linux-arm64-musl": "4.3.2", "@tailwindcss/oxide-linux-x64-gnu": "4.3.2", "@tailwindcss/oxide-linux-x64-musl": "4.3.2", "@tailwindcss/oxide-wasm32-wasi": "4.3.2", "@tailwindcss/oxide-win32-arm64-msvc": "4.3.2", "@tailwindcss/oxide-win32-x64-msvc": "4.3.2" } }, "sha512-z8ZgnzX8gdNoWLBLqBPoh/sjnxkwvf9ZuWjnO0l0yIzbLa5/9S+eC5QxGZKRobVHIC3/1BoMWjHblqWjcgFgag=="], @@ -643,7 +749,7 @@ "@tailwindcss/vite": ["@tailwindcss/vite@4.3.2", "", { "dependencies": { "@tailwindcss/node": "4.3.2", "@tailwindcss/oxide": "4.3.2", "tailwindcss": "4.3.2" }, "peerDependencies": { "vite": "^5.2.0 || ^6 || ^7 || ^8" } }, "sha512-eHpMeX4JXfVNJDEcsouTeCBubJBTcTLigeaw/NTUW6PB5ATKKXdyonnXgTBX2VuRbjz1hjfz6C5XAhr52ImQXA=="], - "@tanstack/db": ["@tanstack/db@0.6.14", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@tanstack/db-ivm": "0.1.18", "@tanstack/pacer-lite": "^0.2.1" }, "peerDependencies": { "typescript": ">=4.7" } }, "sha512-Kqma/PcWhn2e21iJPM/FMKwdMuJUYII9zkKPUsD42/ceEOYRtimbBSe+xll7EY805xE2HuQ3NGSSU8UiYXpHUw=="], + "@tanstack/db": ["@tanstack/db@0.6.16", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@tanstack/db-ivm": "0.1.18", "@tanstack/pacer-lite": "^0.2.1" }, "peerDependencies": { "typescript": ">=4.7" } }, "sha512-6tZ4sAyh7g4G5awO4Q4D/UQVPoPEBsqqDBImjCZNTRJznrpwGqFJZxozov197k8ty8QxZC++eGcbo+BBKF3nzw=="], "@tanstack/db-ivm": ["@tanstack/db-ivm@0.1.18", "", { "dependencies": { "fractional-indexing": "^3.2.0", "sorted-btree": "^1.8.1" }, "peerDependencies": { "typescript": ">=4.7" } }, "sha512-+pZJiRKdoKRM5Epq9T7otD9ZJl82pRFauo7LKuJGrarjVKQ7r+QQlPe3kGdN9LEKSnuNGIWjX9OOY4M8kH4eLw=="], @@ -651,6 +757,10 @@ "@tanstack/hotkeys": ["@tanstack/hotkeys@0.8.0", "", { "dependencies": { "@tanstack/store": "^0.11.0" } }, "sha512-vqH7X9nb0MTJ/O08++dB5bP9jgj4+BIPOUu/U+6myG86lDsirZSVSobpq5UQpE7nBuk62i8eIYeOhd+OMl/UrA=="], + "@tanstack/match-sorter-utils": ["@tanstack/match-sorter-utils@8.19.4", "", { "dependencies": { "remove-accents": "0.5.0" } }, "sha512-Wo1iKt2b9OT7d+YGhvEPD3DXvPv2etTusIMhMUoG7fbhmxcXCtIjJDEygy91Y2JFlwGyjqiBPRozme7UD8hoqg=="], + + "@tanstack/offline-transactions": ["@tanstack/offline-transactions@1.0.41", "", { "dependencies": { "@tanstack/db": "0.6.16" }, "peerDependencies": { "@react-native-community/netinfo": ">=11.0.0", "react-native": ">=0.70.0" }, "optionalPeers": ["@react-native-community/netinfo", "react-native"] }, "sha512-74Exr8H9dSWsWnmyqE3fTNa2ypB+2GV90u6JNQilDitd+MAtU5ZZV8aaTueL1D/ZDn7XNmvZgfyBTQNvonIpjw=="], + "@tanstack/pacer-lite": ["@tanstack/pacer-lite@0.2.2", "", {}, "sha512-eQ1MyLKCHyXiH7NbdmB80W77OhiMgGBUb+qDx/8WMGbwg5Lf/NlfD0TfNYAqY77i8V3AxoDoYdICrQE5ADw4Yw=="], "@tanstack/query-core": ["@tanstack/query-core@5.101.2", "", {}, "sha512-hH5MLoJhF7KaIGd7q3xTXGXvslI+GYlM1Z/35aSHHWaCJWB7XvTSHYuV3eM7tw+aE0mT/xMro4M4Q9rCGHT0lw=="], @@ -661,6 +771,8 @@ "@tanstack/react-hotkeys": ["@tanstack/react-hotkeys@0.10.0", "", { "dependencies": { "@tanstack/hotkeys": "0.8.0", "@tanstack/react-store": "^0.11.0" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-GwOSndI5j3qBVYTmgP1mYyRTnlxb2MS17cwGlsavSxMQPSnmDf+m3LzMIpRMs+3zzQMjg3cYhHsFYizYlFI2tw=="], + "@tanstack/react-query": ["@tanstack/react-query@5.101.4", "", { "dependencies": { "@tanstack/query-core": "5.101.4" }, "peerDependencies": { "react": "^18 || ^19" } }, "sha512-yRg2pfOCxIs4ZJW3XYYHU/WgtD04FHSnfHlpRT7h7pR77hwkdRG4wxbKe4aq6P0RvXUTBSQpQeadS1SUYUe+KA=="], + "@tanstack/react-router": ["@tanstack/react-router@1.170.17", "", { "dependencies": { "@tanstack/history": "1.162.0", "@tanstack/react-store": "^0.9.3", "@tanstack/router-core": "1.171.14", "isbot": "^5.1.22" }, "peerDependencies": { "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0" } }, "sha512-ppLkjCfSMaeug9rmFRYzOd4TIqWV+yTE7tzIny7alJsSnM7w4lzEZm6eqCehG0SPetpZ0R3K+UnanSmBgOAVcQ=="], "@tanstack/react-start": ["@tanstack/react-start@1.168.27", "", { "dependencies": { "@tanstack/react-router": "1.170.17", "@tanstack/react-start-client": "1.168.15", "@tanstack/react-start-rsc": "0.1.26", "@tanstack/react-start-server": "1.167.21", "@tanstack/router-utils": "1.162.2", "@tanstack/start-client-core": "1.170.13", "@tanstack/start-plugin-core": "1.171.19", "@tanstack/start-server-core": "1.169.16", "pathe": "^2.0.3" }, "peerDependencies": { "@rsbuild/core": "^2.0.0", "@vitejs/plugin-rsc": "*", "react": ">=18.0.0 || >=19.0.0", "react-dom": ">=18.0.0 || >=19.0.0", "vite": ">=7.0.0" }, "optionalPeers": ["@rsbuild/core", "@vitejs/plugin-rsc", "vite"] }, "sha512-rdGFDqfCW71gyofyAxaYxhelNKmeVjpmbpm0uFYbNHORCa///4aBxi7B7ecShibKv9O4GfJ66MPX5F0ozbm+ig=="], @@ -683,6 +795,8 @@ "@tanstack/router-utils": ["@tanstack/router-utils@1.162.2", "", { "dependencies": { "@babel/generator": "^7.28.5", "@babel/parser": "^7.28.5", "@babel/types": "^7.28.5", "ansis": "^4.1.0", "babel-dead-code-elimination": "^1.0.12", "diff": "^8.0.2", "pathe": "^2.0.3", "tinyglobby": "^0.2.15" } }, "sha512-hTWqJtqIFFdvuCl8WXNyrodp2L9zo2G37xKRrcVmVRWpAB2h+U1LuRAfS4tsFTiWOIoE/B+WDVFB8JpoEdw6jQ=="], + "@tanstack/solid-query": ["@tanstack/solid-query@5.101.4", "", { "dependencies": { "@tanstack/query-core": "5.101.4" }, "peerDependencies": { "solid-js": "^1.6.0" } }, "sha512-w+QNX4al4zkfOfO6FYILouPX3yAxLANvBNz0cZqaBrSRKfBP3qNC179wu/eS2w1asH+QqEeI0rR2/s7gRGxnFA=="], + "@tanstack/start-client-core": ["@tanstack/start-client-core@1.170.13", "", { "dependencies": { "@tanstack/router-core": "1.171.14", "@tanstack/start-fn-stubs": "1.162.0", "@tanstack/start-storage-context": "1.167.16", "seroval": "^1.5.4" } }, "sha512-o37M3msIK5ec87kPrIYJWXb1XPnjIe5/jrkGLXiXpFuVL99z7mhoBCzftKtVPtzqI8EElnRE/VGFYT9BHNnWcw=="], "@tanstack/start-fn-stubs": ["@tanstack/start-fn-stubs@1.162.0", "", {}, "sha512-QWfUZ3Yo923tdQn38LyKMU8rcTw69zc+T4dAvgTWV4O56SqFRsGfS0lSWIMhJRwXIx/bvdi7nTUBDdZtTHtpTQ=="], @@ -695,10 +809,14 @@ "@tanstack/store": ["@tanstack/store@0.11.0", "", {}, "sha512-WlzzCt3xi0G6pCAJu1U+2jiECwabETDpQDi3hfkFZvJii9AuZqEKbOiVarX1/bWhTNjU486yQtJCCasi/0q+Cw=="], + "@tanstack/svelte-query": ["@tanstack/svelte-query@6.1.38", "", { "dependencies": { "@tanstack/query-core": "5.101.4" }, "peerDependencies": { "svelte": "^5.25.0" } }, "sha512-oV5S/+uAot23p3lJChLAHr82+8ApgQMyIgroWPpN0d6Y6TlThRbLSXnhx6CoUk6AkwlCPxf9vh4SOHa0eXHiWg=="], + "@tanstack/virtual-core": ["@tanstack/virtual-core@3.17.3", "", {}, "sha512-8Np/TFELpI0ySuJoVmjvOrQYXH/8sTX0Biv9szhFhY39xOdAAY+smrMxjxOum/ux3eM8MUJQsEJ0/R0UpvC8dw=="], "@tanstack/virtual-file-routes": ["@tanstack/virtual-file-routes@1.162.0", "", {}, "sha512-uhOeFyxLcU41HzvrxsGpiWdcMbScY1EDgbZ5K7DVRMYInbLYWAC0EA/kx9wXAoSM8q82bUG2hRl8+EAjE6XAbA=="], + "@tanstack/vue-query": ["@tanstack/vue-query@5.101.4", "", { "dependencies": { "@tanstack/match-sorter-utils": "^8.19.4", "@tanstack/query-core": "5.101.4", "@vue/devtools-api": "^6.6.3", "vue-demi": "^0.14.10" }, "peerDependencies": { "@vue/composition-api": "^1.1.2", "vue": "^2.6.0 || ^3.3.0" }, "optionalPeers": ["@vue/composition-api"] }, "sha512-UYjkUZhnWQIFGNb7SdgjCitAftNyYQfOIVUh6vBUQAG4SQKNMSBKeQERFDubpxLAMpIBJTaOrE8fM4c1kZcIGQ=="], + "@ts-morph/common": ["@ts-morph/common@0.27.0", "", { "dependencies": { "fast-glob": "^3.3.3", "minimatch": "^10.0.1", "path-browserify": "^1.0.1" } }, "sha512-Wf29UqxWDpc+i61k3oIOzcUfQt79PIT9y/MWfAGlrkjg6lBC1hwDECLXPVJAhWjiGbfBCxZd65F/LIZF3+jeJQ=="], "@tybys/wasm-util": ["@tybys/wasm-util@0.10.3", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-F3fo1MYrRJYL3zER0OUOmkutjr1Vp23m7OsSgp7nq4SP6OqX6C/56XFIPAl5bt3zaBRjmW7SGz3u/6LwFpYcOg=="], @@ -725,6 +843,8 @@ "@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="], + "@types/trusted-types": ["@types/trusted-types@2.0.7", "", {}, "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw=="], + "@types/validate-npm-package-name": ["@types/validate-npm-package-name@4.0.2", "", {}, "sha512-lrpDziQipxCEeK5kWxvljWYhUvOiB2A9izZd9B2AFarYAkqZshb4lPbRs7zKEic6eGtH8V/2qJW+dPp9OtF6bw=="], "@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="], @@ -767,14 +887,94 @@ "@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="], + "@vercel/oidc": ["@vercel/oidc@3.2.0", "", {}, "sha512-UycprH3T6n3jH0k44NHMa7pnFHGu/N05MjojYr+Mc6I7obkoLIJujSWwin1pCvdy/eOxrI/l3uDLQsmcrOb4ug=="], + + "@visulima/ansi": ["@visulima/ansi@4.0.0", "", {}, "sha512-UUYBvGNiXdM3PCd7ICsTkhbxdNSsOZFfYknTH435qDhhNo4ftv6unpiEDZOwrWNl1dtuE5mraUGG3/DMIwLqDA=="], + + "@visulima/cerebro": ["@visulima/cerebro@3.0.0", "", { "dependencies": { "@visulima/colorize": "2.0.0", "@visulima/tabular": "4.0.0", "fastest-levenshtein": "^1.0.16" }, "peerDependencies": { "@bomb.sh/tab": ">=0.0.16", "@visulima/boxen": "3.0.0", "@visulima/find-cache-dir": "3.0.0", "@visulima/pail": "4.0.0", "github-slugger": ">=2.0.0" }, "optionalPeers": ["@bomb.sh/tab", "@visulima/boxen", "@visulima/find-cache-dir", "@visulima/pail", "github-slugger"], "os": [ "linux", "win32", "darwin", ] }, "sha512-DuwJbqND+Ie3niYLm79OBD5ECETj5daBd5Srqf8Syf+duwLWi02XgSU3wZ99N3LKs8NJs13dJl2Aq4/cuuCpcw=="], + + "@visulima/colorize": ["@visulima/colorize@2.0.0", "", { "dependencies": { "@visulima/is-ansi-color-supported": "3.0.0" }, "os": [ "linux", "win32", "darwin", ] }, "sha512-qG+VECZOOSQZdr63eqSl2HjjBTzmbziqQ/tOAzSZD8MexSKvBUWfNB30L4vhz6vLPo+CxHHwytX7iyasi3Ma6Q=="], + + "@visulima/email": ["@visulima/email@2.1.1", "", { "dependencies": { "html-to-text": "^10.0.0", "ical-generator": "11.0.0", "lru-cache": "11.5.1", "mime": "^4.1.0" }, "peerDependencies": { "@opentelemetry/api": "^1.0.0 || ^2.0.0", "@react-email/render": "^2.0.10", "@vue-email/render": "0.0.9", "asn1js": ">=3.0.10", "fast-xml-parser": "^4.5.0", "handlebars": ">=4.7.9", "jsx-email": "^2.0.0", "juice": "^11.0.0", "liquidjs": "^10.0.0", "mjml": ">=5.4.0", "nodemailer": ">=7", "pkijs": ">=3.4.0", "unstorage": "^1.13.0" }, "optionalPeers": ["@opentelemetry/api", "@react-email/render", "@vue-email/render", "asn1js", "fast-xml-parser", "handlebars", "jsx-email", "juice", "liquidjs", "mjml", "nodemailer", "pkijs", "unstorage"] }, "sha512-HMvn+WJb+gH0nDfbsBi5bSbsBlfwApCiJLtXbdrOW1ug5kn1+OHgdHEjLxbJjccDmR+Cmmo4p7W/+XT6iReb0A=="], + + "@visulima/error": ["@visulima/error@6.0.0", "", { "peerDependencies": { "ai": ">=6.0.202" }, "optionalPeers": ["ai"], "os": [ "linux", "win32", "darwin", ] }, "sha512-kBuOlM1FVQ0ekaIznGA9AByvYX6OpJ+0H8zSLmHh1hRKaVboEB0zbegvRZXCcXg1bES8HUbLiJPN+7zZT3NUmA=="], + + "@visulima/find-ai-runner": ["@visulima/find-ai-runner@1.0.0", "", { "bin": { "find-ai-runner": "./dist/cli.js" } }, "sha512-NQmdERt6NoOT3nWHgvQn4SHG31iubH9oeB80eo/A8nthG4tfLY2codwL9BtZlV3DCctMQRAJwsfRZ+CLGhghhw=="], + + "@visulima/fs": ["@visulima/fs@5.0.4", "", { "dependencies": { "@visulima/path": "3.0.0" }, "peerDependencies": { "ini": "^7.0.0", "json5": "^2.2.3", "jsonc-parser": "^3.3.1", "smol-toml": "^1.7.0", "yaml": ">=2.9.0" }, "optionalPeers": ["ini", "json5", "jsonc-parser", "smol-toml", "yaml"], "os": [ "linux", "win32", "darwin", ] }, "sha512-eJAJGtezASY/UNUkKJwqgZkVcrqdLyp9rJ282Bud2bx98Mekx667aBZ5UOsrB4IduZQ7bMfdqccNVGtnM8TnEg=="], + + "@visulima/interactive-manager": ["@visulima/interactive-manager@1.0.0", "", {}, "sha512-sPiEitNQbO81FnuMQJ3d/Anef5vTd9xDwB1o2MJQtI52taG8HXbgtESqVWajnpjBLpgY5n4Gn/Sw1ut8WUN90A=="], + + "@visulima/is-ansi-color-supported": ["@visulima/is-ansi-color-supported@3.0.0", "", {}, "sha512-uHSrAgO9qrBlP+VQbkXh+/jKHzW2aKZNyrwrBXA0qR/Ro4dsrt3A6oZ9CMB7jVlCmHR/WKLP16o7ch+B1XhItw=="], + + "@visulima/package": ["@visulima/package@5.0.4", "", { "dependencies": { "@antfu/install-pkg": "^1.1.0", "@visulima/fs": "5.0.4", "@visulima/path": "3.0.0", "json5": "^2.2.3", "normalize-package-data": "^9.0.0", "yaml": "2.9.0" }, "os": [ "linux", "win32", "darwin", ] }, "sha512-xge9CbB/ShmufIucxpzGmBogGTUOZH79f261CLEYWroi8thlS+kymo8Puqac8bLYAcaIZUpltdt8hi1D2aQcTA=="], + + "@visulima/pail": ["@visulima/pail@4.0.0", "", { "dependencies": { "@visulima/colorize": "2.0.0", "@visulima/interactive-manager": "1.0.0" }, "peerDependencies": { "@opentelemetry/api": "^1.9.1", "@sveltejs/kit": ">=2.0", "@visulima/redact": "3.0.0", "elysia": ">=1.0", "express": ">=4.0", "fastify": ">=4.0", "hono": ">=4.0", "next": ">=14.0", "rotating-file-stream": ">=3.2.9" }, "optionalPeers": ["@opentelemetry/api", "@sveltejs/kit", "@visulima/redact", "elysia", "express", "fastify", "hono", "next", "rotating-file-stream"], "os": [ "linux", "win32", "darwin", ] }, "sha512-g6s0/Sxq1JYA7NojRkjjXWwHj0JP81WVmxMThiQJcT+5v9GXJNSEurwEL7ljjT92ySp1vs4q/hXUZN9RCgMdfA=="], + + "@visulima/path": ["@visulima/path@3.0.0", "", { "os": [ "linux", "win32", "darwin", ] }, "sha512-l9vlDaoFrmPlG3OFuC+ZitAT8fMB2AJu1ILNZhgToVQ0HCAFVG8X1pIM/GIBQeDULveW+unIRYR4HOhS+plsCA=="], + + "@visulima/redact": ["@visulima/redact@3.0.0", "", { "dependencies": { "compromise": "^14.15.1" } }, "sha512-WC4HCu+zwVrrP8c0pw9TGO7E9S4OxlJrqNzLltDJTYZxXfzjN5yEqA7cCVtbLSgcWgiTLVc8QOa6n6Fm6y0lCw=="], + + "@visulima/spinner": ["@visulima/spinner@1.0.0", "", { "dependencies": { "@visulima/interactive-manager": "1.0.0" } }, "sha512-3gCKLOUw4EGXWuf/Y6wabQkBsXyTAe3LSmwgZjn0a5S/EbY00jC/ZlpBAB/Zp6rqS/4yKjanhu6oEtwV5ZVaHw=="], + + "@visulima/storage-client": ["@visulima/storage-client@1.0.0", "", { "peerDependencies": { "@tanstack/react-query": ">=5.100.9", "@tanstack/solid-query": ">=5.100.9", "@tanstack/svelte-query": ">=6.1.28", "@tanstack/vue-query": ">=5.100.9", "react": ">=19.2.6", "solid-js": ">=1.9.12", "svelte": ">=3.0.0", "vue": ">=3.5.34" } }, "sha512-wWtf7dGLouySavWzbhRMu3+4IGsdsTpOxAjcsHa5zxGV0lgMsY/+qs29STOg4BYSKs8ux8vDhW+dLy9qNba8Bg=="], + + "@visulima/string": ["@visulima/string@3.0.0", "", {}, "sha512-XflLJ8DelNZGrHoyywidrFUG+pG8zr1+aR31hyH8NhgdED31cHjY5w0n0pmjG/1yZBQNLNVhwvBbC+H6Od9YeA=="], + + "@visulima/tabular": ["@visulima/tabular@4.0.0", "", {}, "sha512-2BZVeNojH++U2AiMM8sIJb/Ofcrp8Pz2VnSJLyPH5kAGpE0c/KgFgUW8D6SPJIa5aylzMvK11p9YDPjaJ3igHQ=="], + + "@visulima/tui": ["@visulima/tui@1.0.4", "", { "dependencies": { "@visulima/ansi": "4.0.0", "@visulima/colorize": "2.0.0", "@visulima/error": "6.0.0", "@visulima/spinner": "1.0.0", "@visulima/string": "3.0.0", "cli-boxes": "^4.0.1", "code-excerpt": "^4.0.0", "is-in-ci": "^2.0.0", "patch-console": "^2.0.0", "scheduler": "^0.27.0", "signal-exit": "^4.1.0", "terminal-size": "^4.0.1", "tseep": "^1.3.1", "yoga-layout": "~3.2.1" }, "optionalDependencies": { "@visulima/tui-binding-darwin-arm64": "1.0.4", "@visulima/tui-binding-darwin-x64": "1.0.4", "@visulima/tui-binding-linux-arm64-gnu": "1.0.4", "@visulima/tui-binding-linux-arm64-musl": "1.0.4", "@visulima/tui-binding-linux-x64-gnu": "1.0.4", "@visulima/tui-binding-linux-x64-musl": "1.0.4", "@visulima/tui-binding-win32-arm64-msvc": "1.0.4", "@visulima/tui-binding-win32-x64-msvc": "1.0.4" }, "peerDependencies": { "@shikijs/langs": "^4.3.0", "@shikijs/themes": "^4.3.0", "@visulima/tabular": "4.0.0", "cfonts": "^3.3.1", "diff": "^9.0.0", "marked": "^18.0.5", "react": "^19.2.6", "react-devtools-core": "^7.0.1", "react-reconciler": "^0.33.0", "shiki": "^4.3.0", "ws": "^8.21.0" }, "optionalPeers": ["@shikijs/langs", "@shikijs/themes", "@visulima/tabular", "cfonts", "diff", "marked", "react-devtools-core", "shiki", "ws"] }, "sha512-8FqrzHi/JitHHZ25/hivZYVGL/HGt1iqZ8vN+RyZbl4jOkhZ0c4g4gOxvjPGF3yLKXicWj+JrfrwEyXD1v7Trg=="], + + "@visulima/tui-binding-darwin-arm64": ["@visulima/tui-binding-darwin-arm64@1.0.4", "", { "os": "darwin", "cpu": "arm64" }, "sha512-CniUOHk6NPvy/Mf42ggTLpDvQQk33fyr+3ylKL0EunxtQm5Co0KZG4nogsrD4sq7pYwDeJGRutqUu4mY+CgHGQ=="], + + "@visulima/tui-binding-darwin-x64": ["@visulima/tui-binding-darwin-x64@1.0.4", "", { "os": "darwin", "cpu": "x64" }, "sha512-5gROWmnjF6X9vZbd8u7wimAr2BcGVWDHE8LTMHWBdBCDNYeYs5R4P+JIw2XqKhbYq+6JHsJtvFQ5mHphTk3b7A=="], + + "@visulima/tui-binding-linux-arm64-gnu": ["@visulima/tui-binding-linux-arm64-gnu@1.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-io6ZZ50UND6+9WJtVnv8k0Cl9KSX1i6Hec/GzkrK38BiNCaySa1Tu3L+uSbpemn6/42jUwGzFKBfeR4PnHwsEw=="], + + "@visulima/tui-binding-linux-arm64-musl": ["@visulima/tui-binding-linux-arm64-musl@1.0.4", "", { "os": "linux", "cpu": "arm64" }, "sha512-2RuiO6NXJGo4X5fqj7ZnOXVqXTmHIETjK1HZqSrMwOSYB9KbC9PZ7pN7Uq1tnYnzHpwl6avbP0QYW0POFvkZVg=="], + + "@visulima/tui-binding-linux-x64-gnu": ["@visulima/tui-binding-linux-x64-gnu@1.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-SBpgX9wOYE2EUgG4P+afyCeSyu/HWGiW3V0zrzGe7PaCNnsQqvy85rbT1i3W7u1wJE1yXTx/Kn4aMUSl4WYUcw=="], + + "@visulima/tui-binding-linux-x64-musl": ["@visulima/tui-binding-linux-x64-musl@1.0.4", "", { "os": "linux", "cpu": "x64" }, "sha512-wjR24V0Gw1pJlJGzvLEt0sbjUBFtR58eYA1s+H0VQsEMdCeW1SIoId+Hl3FdhjqISc0ozi0Wl2oWMvx0TcOs/w=="], + + "@visulima/tui-binding-win32-arm64-msvc": ["@visulima/tui-binding-win32-arm64-msvc@1.0.4", "", { "os": "win32", "cpu": "arm64" }, "sha512-7kNPxAxEjVwn14AF5S5zm61kjM7pEFh6Izh59QUUkYh78SNdTiiA956vlq7G4+ZebpOcwRrmmkdGHa0sgA+jAg=="], + + "@visulima/tui-binding-win32-x64-msvc": ["@visulima/tui-binding-win32-x64-msvc@1.0.4", "", { "os": "win32", "cpu": "x64" }, "sha512-jogXEQq+Yei2qCOa31ipwqk5bAo17czmMUHc0TRmh34XxTGlTdMPSxxum0xIetr/A0Ije2z1rE1CDdSe3eatAA=="], + "@vitejs/plugin-react": ["@vitejs/plugin-react@6.0.3", "", { "dependencies": { "@rolldown/pluginutils": "^1.0.1" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-vmFvco5/QuC2f9Oj+wTk0+9XeDFkHxSamwZKYc7MxYwKICfvUvlMhqKI0VuICPltGqh1neqBKDvO4kes1ya8vg=="], + "@vue/compiler-core": ["@vue/compiler-core@3.5.40", "", { "dependencies": { "@babel/parser": "^7.29.7", "@vue/shared": "3.5.40", "entities": "^7.0.1", "estree-walker": "^2.0.2", "source-map-js": "^1.2.1" } }, "sha512-39E8IgOhTbVDnoJFMKc2DvYnypcZwUqgUhQkccva/0m6FUwtIKSGV7n1hpVmYcFaoRAwf9pBcwnKlCEsN63ZEQ=="], + + "@vue/compiler-dom": ["@vue/compiler-dom@3.5.40", "", { "dependencies": { "@vue/compiler-core": "3.5.40", "@vue/shared": "3.5.40" } }, "sha512-pwkx4vqlqOspFstrcmzwkKLePVMD3PT65imRzLhanU2V1Fj4K13g6OXjanOyzw3aTAuRk84BOmY8f3rEHqPaVA=="], + + "@vue/compiler-sfc": ["@vue/compiler-sfc@3.5.40", "", { "dependencies": { "@babel/parser": "^7.29.7", "@vue/compiler-core": "3.5.40", "@vue/compiler-dom": "3.5.40", "@vue/compiler-ssr": "3.5.40", "@vue/shared": "3.5.40", "estree-walker": "^2.0.2", "magic-string": "^0.30.21", "postcss": "^8.5.19", "source-map-js": "^1.2.1" } }, "sha512-gIf497P4kpuALcvs5n3AEg1Vdn0pSY4XbjASIfHNYF1/MP3T2Mf2STERTubysBxCRxzJGJYtF/O7vwJrxFB3Vw=="], + + "@vue/compiler-ssr": ["@vue/compiler-ssr@3.5.40", "", { "dependencies": { "@vue/compiler-dom": "3.5.40", "@vue/shared": "3.5.40" } }, "sha512-rrE5xiXG663+vHCHa3J9p2z5OcBRjXmoqenprJxAFQxg5pSshzeBiCE6pu46axapRJ2Adk0YDA2BRZVjiHXnhg=="], + + "@vue/devtools-api": ["@vue/devtools-api@6.6.4", "", {}, "sha512-sGhTPMuXqZ1rVOk32RylztWkfXTRhuS7vgAKv0zjqk8gbsHkJ7xfFf+jbySxt7tWObEJwyKaHMikV/WGDiQm8g=="], + + "@vue/reactivity": ["@vue/reactivity@3.5.40", "", { "dependencies": { "@vue/shared": "3.5.40" } }, "sha512-B7ot9UlUZOi1zbq61/LvE88ZLTV8IlajTdiZTAEiDQgrnIMIZoPr9kGw0Zw46ObW62O9+H/Be3kMbfb7kYPQZA=="], + + "@vue/runtime-core": ["@vue/runtime-core@3.5.40", "", { "dependencies": { "@vue/reactivity": "3.5.40", "@vue/shared": "3.5.40" } }, "sha512-KAZLweuZ6uUJPK1PMSQPgBU5gCjgrrfjUhSglmU9NhH+Zjepa8cnwSydPWDWHDwOgY4g3VcZ+PljbiHlURNCbw=="], + + "@vue/runtime-dom": ["@vue/runtime-dom@3.5.40", "", { "dependencies": { "@vue/reactivity": "3.5.40", "@vue/runtime-core": "3.5.40", "@vue/shared": "3.5.40", "csstype": "^3.2.3" } }, "sha512-ZfrX8ssZQds900L9pr8AuK05ddnMsR4MPMZr8cPN9GoqoPWcXLhjvvbIA2SMv+7a97sJ1vv9pj/zxK0Cq/eEFQ=="], + + "@vue/server-renderer": ["@vue/server-renderer@3.5.40", "", { "dependencies": { "@vue/compiler-ssr": "3.5.40", "@vue/runtime-dom": "3.5.40", "@vue/shared": "3.5.40" } }, "sha512-XNJym9WpevhTVt1HuwOrCRJ5Q+9z4BjTMrDtjTrvx74SmUll8spNTw6whWJa9mEkO4PKn5TihI/bm/8ds2QVJw=="], + + "@vue/shared": ["@vue/shared@3.5.40", "", {}, "sha512-WxnBtruIqOoV3rA4jeKDWzrYI5h7Cp4+pjwDi8kWGHz+IslhiN+wguLVVhtv2l8VoU02rzDCVfDjgCl1lNpZVg=="], + + "@workflow/serde": ["@workflow/serde@4.1.0", "", {}, "sha512-pav4F2BoirECWR7Nf1TKt+2eETcBj7jj4cBefQ8VXQCA6NPkaKeLfj/zMgi+3zYV5ZIBT4GuUiphsj0/b9hPQQ=="], + "@xstate/react": ["@xstate/react@7.0.0-alpha.1", "", { "dependencies": { "use-isomorphic-layout-effect": "^1.1.2", "use-sync-external-store": "^1.2.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "xstate": "^6.0.0-alpha.1" }, "optionalPeers": ["xstate"] }, "sha512-GRUEqHlbp0Jf0gheJnO+WS90JkJlilRt3wTud84UuAErVrpQpBD1YCGQ1/DySrXK/JKUuRi5p7CbPeZlXV4pxA=="], "accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="], + "acorn": ["acorn@8.17.0", "", { "bin": { "acorn": "bin/acorn" } }, "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg=="], + "agent-base": ["agent-base@6.0.2", "", { "dependencies": { "debug": "4" } }, "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ=="], + "ai": ["ai@7.0.31", "", { "dependencies": { "@ai-sdk/gateway": "4.0.23", "@ai-sdk/provider": "4.0.3", "@ai-sdk/provider-utils": "5.0.11" }, "peerDependencies": { "zod": "^3.25.76 || ^4.1.8" } }, "sha512-pJfwKXjF5kw0rKRTePwYo60EfWb8wfzJAgf3ojln/YkOsVVKttzZAJVcRPsg37Z3a06ZdKkxX+DSrMAFlPm5Mw=="], + "ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="], "ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="], @@ -793,28 +993,40 @@ "aria-hidden": ["aria-hidden@1.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="], + "aria-query": ["aria-query@5.3.1", "", {}, "sha512-Z/ZeOgVl7bcSYZ/u/rh0fOpvEpq//LZmdbkXyc7syVzjPAhfOa9ebsdTSjEBDU4vs5nC98Kfduj1uFo0qyET3g=="], + "array-union": ["array-union@2.1.0", "", {}, "sha512-HGyxoOTYUyCM6stUe6EJgnd4EoewAI7zMdfqO+kGjnlZmBDz/cR5pf8r/cR4Wq60sL/p0IkcjUEEPwS3GFrIyw=="], + "asn1": ["asn1@0.2.6", "", { "dependencies": { "safer-buffer": "~2.1.0" } }, "sha512-ix/FxPn0MDjeyJ7i/yoHGFt/EX6LyNbxSEhPPXODPL+KB0VPk86UYfL0lMdy+KCnv+fmvIzySwaK5COwqVbWTQ=="], + "ast-types": ["ast-types@0.16.1", "", { "dependencies": { "tslib": "^2.0.1" } }, "sha512-6t10qk83GOG8p0vKmaCr8eiilZwO171AvbROMtvvNiwrTly62t+7XkA8RdIIVbpMhCASAsxgAzdRSwh6nw/5Dg=="], "astring": ["astring@1.9.0", "", { "bin": { "astring": "bin/astring" } }, "sha512-LElXdjswlqjWrPpJFg1Fx4wpkOCxj1TDHlSV4PlaRxHGWko024xICaa97ZkMfs6DRKlCguiAI+rbXv5GWwXIkg=="], "atomically": ["atomically@1.7.0", "", {}, "sha512-Xcz9l0z7y9yQ9rdDaxlmaI4uJHf/T8g9hOEzJcsEqX2SjCj4J20uK7+ldkDHMbpJDK76wF7xEIgxc/vSlsfw5w=="], + "axobject-query": ["axobject-query@4.1.0", "", {}, "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ=="], + "babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="], "babel-plugin-react-compiler": ["babel-plugin-react-compiler@1.0.0", "", { "dependencies": { "@babel/types": "^7.26.0" } }, "sha512-Ixm8tFfoKKIPYdCCKYTsqv+Fd4IJ0DQqMyEimo+pxUOMUR9cVPlwTrFt9Avu+3cb6Zp3mAzl+t1MrG2fxxKsxw=="], "balanced-match": ["balanced-match@4.0.4", "", {}, "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA=="], + "base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="], + "baseline-browser-mapping": ["baseline-browser-mapping@2.10.42", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-c/jurFrDLyui7o1J86yLkRu4LMsTYcBohveus7/I2Hzdn9KIP2bdJPTue/lR1KH46enoPbD77GKeSYNdyPoD3Q=="], + "bcrypt-pbkdf": ["bcrypt-pbkdf@1.0.2", "", { "dependencies": { "tweetnacl": "^0.14.3" } }, "sha512-qeFIXtP4MSoi6NLqO12WfqARWWuCKi2Rn/9hJLEmtB5yTNr9DqFWkJRCf2qShWzPeAMRnOgCrq0sg/KLv5ES9w=="], + "better-auth": ["better-auth@1.6.23", "", { "dependencies": { "@better-auth/core": "1.6.23", "@better-auth/drizzle-adapter": "1.6.23", "@better-auth/kysely-adapter": "1.6.23", "@better-auth/memory-adapter": "1.6.23", "@better-auth/mongo-adapter": "1.6.23", "@better-auth/prisma-adapter": "1.6.23", "@better-auth/telemetry": "1.6.23", "@better-auth/utils": "0.4.2", "@better-fetch/fetch": "1.3.1", "@noble/ciphers": "^2.1.1", "@noble/hashes": "^2.0.1", "better-call": "1.3.7", "defu": "^6.1.4", "jose": "^6.1.3", "kysely": "^0.28.17 || ^0.29.0", "nanostores": "^1.1.1", "zod": "^4.3.6" }, "peerDependencies": { "@lynx-js/react": "*", "@prisma/client": "^5.0.0 || ^6.0.0 || ^7.0.0", "@sveltejs/kit": "^2.0.0", "@tanstack/react-start": "^1.0.0", "@tanstack/solid-start": "^1.0.0", "better-sqlite3": "^12.0.0", "drizzle-kit": ">=0.31.4", "drizzle-orm": "^0.45.2", "mongodb": "^6.0.0 || ^7.0.0", "mysql2": "^3.0.0", "next": "^14.0.0 || ^15.0.0 || ^16.0.0", "pg": "^8.0.0", "prisma": "^5.0.0 || ^6.0.0 || ^7.0.0", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0", "solid-js": "^1.0.0", "svelte": "^4.0.0 || ^5.0.0", "vitest": "^2.0.0 || ^3.0.0 || ^4.0.0", "vue": "^3.0.0" }, "optionalPeers": ["@lynx-js/react", "@prisma/client", "@sveltejs/kit", "@tanstack/react-start", "@tanstack/solid-start", "better-sqlite3", "drizzle-kit", "drizzle-orm", "mongodb", "mysql2", "next", "pg", "prisma", "react", "react-dom", "solid-js", "svelte", "vitest", "vue"] }, "sha512-4vOaRd9UiKGKm9R+ej0jjU1es3MiJIiNc9Qq3VCnYqOZ4/nb5272QqTxWYoDxyUXl5x6A2x2we5KZKQO9teTQQ=="], "better-call": ["better-call@1.3.7", "", { "dependencies": { "@better-auth/utils": "^0.4.0", "@better-fetch/fetch": "^1.1.21", "rou3": "^0.7.12", "set-cookie-parser": "^3.0.1" }, "peerDependencies": { "zod": "^4.0.0" }, "optionalPeers": ["zod"] }, "sha512-Al51/hjp2SSp6CRTa3F2ptcx4yQVS1xWKoY6jcVXqNYOap6mHFP2jUBn5EwIL4iIed1/Sq4hlQ+Umm6EflZG+w=="], "better-path-resolve": ["better-path-resolve@1.0.0", "", { "dependencies": { "is-windows": "^1.0.0" } }, "sha512-pbnl5XzGBdrFU/wT4jqmJVPn2B6UHPBOhzMQkY/SPUPB6QtUXtmBHBIwCbXJol93mOpGMnQyP/+BB19q04xj7g=="], + "bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="], + "blake3-wasm": ["blake3-wasm@2.1.5", "", {}, "sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g=="], "body-parser": ["body-parser@2.3.0", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^2.0.0", "debug": "^4.4.3", "http-errors": "^2.0.1", "iconv-lite": "^0.7.2", "on-finished": "^2.4.1", "qs": "^6.15.2", "raw-body": "^3.0.2", "type-is": "^2.1.0" } }, "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw=="], @@ -825,6 +1037,10 @@ "browserslist": ["browserslist@4.28.5", "", { "dependencies": { "baseline-browser-mapping": "^2.10.42", "caniuse-lite": "^1.0.30001800", "electron-to-chromium": "^1.5.387", "node-releases": "^2.0.50", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-Cu2E6QejHWzuDMTkuwgpABFgDfZrXLQq5V13YOACZx4mFAG4IwGTbTfHPMr4WtxlHoXSM8FIuRwYYCz5XiabaQ=="], + "buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="], + + "buildcheck": ["buildcheck@0.0.7", "", {}, "sha512-lHblz4ahamxpTmnsk+MNTRWsjYKv965MwOrSJyeD588rR3Jcu7swE+0wN5F+PbL5cjgu/9ObkhfzEPuofEMwLA=="], + "bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="], "bundle-name": ["bundle-name@4.1.0", "", { "dependencies": { "run-applescript": "^7.0.0" } }, "sha512-tjwM5exMg6BGRI+kNmTntNsvdZS1X8BFYS6tnJ2hdH0kVxM6/eVZ2xy+FqStSWvYmtfFMDLIxurorHwDKfDz5Q=="], @@ -839,22 +1055,30 @@ "caniuse-lite": ["caniuse-lite@1.0.30001803", "", {}, "sha512-g/uHREV2ZpK9qMalCsWaxmA6ol+DX8GYhuf3T40RKoP+oL7vhRJh8LNt73PCjpnR6l14FzfPrB5Yux4PKm2meg=="], + "cfonts": ["cfonts@3.3.1", "", { "dependencies": { "supports-color": "^8", "window-size": "^1" }, "bin": { "cfonts": "bin/index.js" } }, "sha512-ZGEmN3W9mViWEDjsuPo4nK4h39sfh6YtoneFYp9WLPI/rw8BaSSrfQC6jkrGW3JMvV3ZnExJB/AEqXc/nHYxkw=="], + "chalk": ["chalk@5.6.2", "", {}, "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA=="], "chardet": ["chardet@2.2.0", "", {}, "sha512-rddelWYNPRrXq6PtNEN2S3f6t9ILzvqaN5pVgi4kqt9jHQaXIial9PznB5iSPVlQSLNaaH22ItWz3EJtQ10+OA=="], "chokidar": ["chokidar@5.0.0", "", { "dependencies": { "readdirp": "^5.0.0" } }, "sha512-TQMmc3w+5AxjpL8iIiwebF73dRDF4fBIieAqGn9RGCWaEVwQ6Fb2cGe31Yns0RRIzii5goJ1Y7xbMwo1TxMplw=="], + "chownr": ["chownr@1.1.4", "", {}, "sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg=="], + "cjs-module-lexer": ["cjs-module-lexer@2.2.0", "", {}, "sha512-4bHTS2YuzUvtoLjdy+98ykbNB5jS0+07EvFNXerqZQJ89F7DI6ET7OQo/HJuW6K0aVsKA9hj9/RVb2kQVOrPDQ=="], "class-variance-authority": ["class-variance-authority@0.7.1", "", { "dependencies": { "clsx": "^2.1.1" } }, "sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg=="], + "cli-boxes": ["cli-boxes@4.0.1", "", {}, "sha512-5IOn+jcCEHEraYolBPs/sT4BxYCe2nHg374OPiItB1O96KZFseS2gthU4twyYzeDcFew4DaUM/xwc5BQf08JJw=="], + "cli-cursor": ["cli-cursor@5.0.0", "", { "dependencies": { "restore-cursor": "^5.0.0" } }, "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw=="], "cli-spinners": ["cli-spinners@2.9.2", "", {}, "sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg=="], "cli-truncate": ["cli-truncate@5.2.0", "", { "dependencies": { "slice-ansi": "^8.0.0", "string-width": "^8.2.0" } }, "sha512-xRwvIOMGrfOAnM1JYtqQImuaNtDEv9v6oIYAs4LIHwTiKee8uwvIi363igssOC0O5U04i4AlENs79LQLu9tEMw=="], + "cliui": ["cliui@8.0.1", "", { "dependencies": { "string-width": "^4.2.0", "strip-ansi": "^6.0.1", "wrap-ansi": "^7.0.0" } }, "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ=="], + "clsx": ["clsx@2.1.1", "", {}, "sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA=="], "cmdk": ["cmdk@1.1.1", "", { "dependencies": { "@radix-ui/react-compose-refs": "^1.1.1", "@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-id": "^1.1.0", "@radix-ui/react-primitive": "^2.0.2" }, "peerDependencies": { "react": "^18 || ^19 || ^19.0.0-rc", "react-dom": "^18 || ^19 || ^19.0.0-rc" } }, "sha512-Vsv7kFaXm+ptHDMZ7izaRsP70GgrW9NBNGswt9OZaVBLlE0SNpDq8eu/VGXyF9r7M0azK3Wy7OlYXsuyYLFzHg=="], @@ -863,8 +1087,16 @@ "code-block-writer": ["code-block-writer@13.0.3", "", {}, "sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg=="], + "code-excerpt": ["code-excerpt@4.0.0", "", { "dependencies": { "convert-to-spaces": "^2.0.1" } }, "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA=="], + + "color-convert": ["color-convert@2.0.1", "", { "dependencies": { "color-name": "~1.1.4" } }, "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ=="], + + "color-name": ["color-name@1.1.4", "", {}, "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA=="], + "commander": ["commander@14.0.3", "", {}, "sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw=="], + "compromise": ["compromise@14.16.0", "", { "dependencies": { "efrt": "2.7.0", "grad-school": "0.0.5", "suffix-thumb": "5.0.2" } }, "sha512-4DFYl/Hl7sW4XWUDfx9S5vxqyYKpZDwwqrpXsQv5acdbVP+joKceIcIaLb0lhVWUpDBV0OnExk/o/dnYUwXnhQ=="], + "conf": ["conf@10.2.0", "", { "dependencies": { "ajv": "^8.6.3", "ajv-formats": "^2.1.1", "atomically": "^1.7.0", "debounce-fn": "^4.0.0", "dot-prop": "^6.0.1", "env-paths": "^2.2.1", "json-schema-typed": "^7.0.3", "onetime": "^5.1.2", "pkg-up": "^3.1.0", "semver": "^7.3.5" } }, "sha512-8fLl9F04EJqjSqH+QjITQfJF8BrOVaYr1jewVgSRAEWePfxT0sku4w2hrGQ60BC/TNLGQ2pgxNlTbWQmMPFvXg=="], "content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="], @@ -873,6 +1105,8 @@ "convert-source-map": ["convert-source-map@2.0.0", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="], + "convert-to-spaces": ["convert-to-spaces@2.0.1", "", {}, "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ=="], + "cookie": ["cookie@1.1.1", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="], "cookie-es": ["cookie-es@3.1.1", "", {}, "sha512-UaXxwISYJPTr9hwQxMFYZ7kNhSXboMXP+Z3TRX6f1/NyaGPfuNUZOWP1pUEb75B2HjfklIYLVRfWiFZJyC6Npg=="], @@ -883,6 +1117,10 @@ "cosmiconfig": ["cosmiconfig@9.0.2", "", { "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", "js-yaml": "^4.1.0", "parse-json": "^5.2.0" }, "peerDependencies": { "typescript": ">=4.9.5" }, "optionalPeers": ["typescript"] }, "sha512-gtTZxTDau1wL7Y7zifc2dd8jHSK/k6BTx/2Xp/BpdlAdnlYWFVt7qhJqgwi7637yRwRQ3qL4ZidbB4I8tA5VOg=="], + "cpu-features": ["cpu-features@0.0.10", "", { "dependencies": { "buildcheck": "~0.0.6", "nan": "^2.19.0" } }, "sha512-9IkYqtX3YHPCzoVg1Py+o9057a3i0fp7S530UWokCSaFVTc7CwXPRiOjRjBQQ18ZCNafx78YfnG+HALxtVmOGA=="], + + "cron-parser": ["cron-parser@5.6.2", "", { "dependencies": { "luxon": "^3.7.2" } }, "sha512-yJ/G1LVir6CnlkLI40CsampPLKl1SprGGlUagWtGJxewytRVYezv5xVyzzbT+Pvzx+VIRvZVF7/a0eEMTxdnTA=="], + "cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="], "cssesc": ["cssesc@3.0.0", "", { "bin": { "cssesc": "bin/cssesc" } }, "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg=="], @@ -899,12 +1137,16 @@ "deepmerge": ["deepmerge@4.3.1", "", {}, "sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A=="], + "deepmerge-ts": ["deepmerge-ts@7.1.5", "", {}, "sha512-HOJkrhaYsweh+W+e74Yn7YStZOilkoPb6fycpwNLKzSPtruFs48nYis0zy5yJz1+ktUhHxoRDJ27RQAWLIJVJw=="], + "default-browser": ["default-browser@5.5.0", "", { "dependencies": { "bundle-name": "^4.1.0", "default-browser-id": "^5.0.0" } }, "sha512-H9LMLr5zwIbSxrmvikGuI/5KGhZ8E2zH3stkMgM5LpOWDutGM2JZaj460Udnf1a+946zc7YBgrqEWwbk7zHvGw=="], "default-browser-id": ["default-browser-id@5.0.1", "", {}, "sha512-x1VCxdX4t+8wVfd1so/9w+vQ4vx7lKd2Qp5tDRutErwmR85OgmfX7RlLRMWafRMY7hbEiXIbudNrjOAPa/hL8Q=="], "define-lazy-prop": ["define-lazy-prop@3.0.0", "", {}, "sha512-N+MeXYoqr3pOgn8xfyRPREN7gHakLYjhsHhWGT3fWAiL4IkAt0iDw14QiiEm2bE30c5XX5q0FtAA3CK5f9/BUg=="], + "define-property": ["define-property@1.0.0", "", { "dependencies": { "is-descriptor": "^1.0.0" } }, "sha512-cZTYKFWspt9jZsMscWo8sc/5lbPC9Q0N5nBLgb+Yd915iL3udB1uFgS3B8YCx66UVHq018DAVFoee7x+gxggeA=="], + "defu": ["defu@6.1.7", "", {}, "sha512-7z22QmUWiQ/2d0KkdYmANbRUVABpZ9SNYyH5vx6PZ+nE5bcC0l7uFvEfHlyld/HcGBFTL536ClDt3DEcSlEJAQ=="], "depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="], @@ -915,20 +1157,38 @@ "detect-node-es": ["detect-node-es@1.1.0", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="], + "devalue": ["devalue@5.8.2", "", {}, "sha512-DObPPAfdtFbXjxLqK8s2Xk9ZuWz5+ZoFEhC7J76es4GU/rEiXwHTmbImoCdyoCOcBH1UF3+Cz6Z2sYD4hyl5TA=="], + "diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], "dir-glob": ["dir-glob@3.0.1", "", { "dependencies": { "path-type": "^4.0.0" } }, "sha512-WkrWp9GR4KXfKGYzOLmTuGVi1UWFfws377n9cc55/tb6DuqyF6pcQ5AbiHEshaDpY9v6oaSr2XCDidGmMwdzIA=="], + "docker-modem": ["docker-modem@5.0.7", "", { "dependencies": { "debug": "^4.1.1", "readable-stream": "^3.5.0", "split-ca": "^1.0.1", "ssh2": "^1.15.0" } }, "sha512-XJgGhoR/CLpqshm4d3L7rzH6t8NgDFUIIpztYlLHIApeJjMZKYJMz2zxPsYxnejq5h3ELYSw/RBsi3t5h7gNTA=="], + + "dockerode": ["dockerode@5.0.1", "", { "dependencies": { "@balena/dockerignore": "^1.0.2", "@grpc/grpc-js": "^1.11.1", "@grpc/proto-loader": "^0.7.13", "docker-modem": "^5.0.7", "protobufjs": "^7.3.2", "tar-fs": "^2.1.4" } }, "sha512-avsq/xk4YPIrn0CgleX5bjT9Y8IT1p9PxrNQ++RBQ2WEyFfHCTDsT9kmyxz+H/axnjAwg8wJWEIuPGOUuNupiA=="], + + "dom-serializer": ["dom-serializer@2.0.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="], + + "domelementtype": ["domelementtype@2.3.0", "", {}, "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw=="], + + "domhandler": ["domhandler@5.0.3", "", { "dependencies": { "domelementtype": "^2.3.0" } }, "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w=="], + + "domutils": ["domutils@3.2.2", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="], + "dot-prop": ["dot-prop@6.0.1", "", { "dependencies": { "is-obj": "^2.0.0" } }, "sha512-tE7ztYzXHIeyvc7N+hR3oi7FIbf/NIjVP9hmAt3yMXzrQ072/fpjGLx2GxNxGxUl5V73MEqYzioOMoVhGMJ5cA=="], "dotenv": ["dotenv@17.4.2", "", {}, "sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw=="], + "drizzle-orm": ["drizzle-orm@0.45.2", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "prisma": "*", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "prisma", "sql.js", "sqlite3"] }, "sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q=="], + "dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="], "ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="], "effect": ["effect@4.0.0-beta.90", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "fast-check": "^4.8.0", "find-my-way-ts": "^0.1.6", "ini": "^7.0.0", "kubernetes-types": "^1.30.0", "msgpackr": "^2.0.1", "multipasta": "^0.2.7", "toml": "^4.1.1", "uuid": "^14.0.0", "yaml": "^2.9.0" } }, "sha512-A0U3OE+2oyK/iFG6VYbFj9gwjJ7rFXjgP7qV+m7n/4lOREp9Lfk1///SlGCpX7HRueOCZO1l7aW0KByXuJeiPA=="], + "efrt": ["efrt@2.7.0", "", {}, "sha512-/RInbCy1d4P6Zdfa+TMVsf/ufZVotat5hCw3QXmWtjU+3pFEOvOQ7ibo3aIxyCJw2leIeAMjmPj+1SLJiCpdrQ=="], + "electron-to-chromium": ["electron-to-chromium@1.5.389", "", {}, "sha512-cEto7aeOqBfU1D+c5py5pE+ooscKE75JifxLBdFUZsqAxRS6y7kebtxAZvICszSl05gPjYHDTjY+lXpyGvpJbg=="], "emoji-regex": ["emoji-regex@10.6.0", "", {}, "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A=="], @@ -937,10 +1197,14 @@ "encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="], + "end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="], + "enhanced-resolve": ["enhanced-resolve@5.21.6", "", { "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.3.3" } }, "sha512-aNnGCvbJ/RIyWo1IuhNdVjnNF+EjH9wpzpNHt+ci/m9He9LJvUN8wrCcXjp9cWsGNAuvSpVFTx/vraAFQ8qGjQ=="], "enquirer": ["enquirer@2.4.1", "", { "dependencies": { "ansi-colors": "^4.1.1", "strip-ansi": "^6.0.1" } }, "sha512-rRqJg/6gd538VHvR3PSrdRBb/1Vy2YfzHqzvbhGIQpDRKIa4FgV/54b5Q1xYSxOOwKvjXweS26E0Q+nAMwp2pQ=="], + "entities": ["entities@7.0.1", "", {}, "sha512-TWrgLOFUQTH994YUyl1yT4uyavY5nNB5muff+RtWaqNVCAK408b5ZnnbNAUEWLTCpum9w6arT70i1XdQ4UeOPA=="], + "env-paths": ["env-paths@2.2.1", "", {}, "sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A=="], "environment": ["environment@1.1.0", "", {}, "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q=="], @@ -963,12 +1227,18 @@ "escape-html": ["escape-html@1.0.3", "", {}, "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow=="], + "esm-env": ["esm-env@1.2.2", "", {}, "sha512-Epxrv+Nr/CaL4ZcFGPJIYLWFom+YeV1DqMLHJoEd9SYRxNbaFruBwfEX/kkHUJf55j2+TUbmDcmuilbP1TmXHA=="], + "esprima": ["esprima@4.0.1", "", { "bin": { "esparse": "./bin/esparse.js", "esvalidate": "./bin/esvalidate.js" } }, "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A=="], "esquery": ["esquery@1.7.0", "", { "dependencies": { "estraverse": "^5.1.0" } }, "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g=="], + "esrap": ["esrap@2.3.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.4.15" }, "peerDependencies": { "@typescript-eslint/types": "^8.2.0" }, "optionalPeers": ["@typescript-eslint/types"] }, "sha512-GQ/7RN8uOtEfNpzZzBMTzW9JBcX42oaSVtPzdF+6cEL8pqIL094iUpr9jzYGn4O4P/1S60dJ6izyT8F4LYARng=="], + "estraverse": ["estraverse@5.3.0", "", {}, "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA=="], + "estree-walker": ["estree-walker@2.0.2", "", {}, "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w=="], + "etag": ["etag@1.8.1", "", {}, "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg=="], "eventemitter3": ["eventemitter3@5.0.4", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="], @@ -995,6 +1265,8 @@ "fast-uri": ["fast-uri@3.1.3", "", {}, "sha512-i70LwGWUduXqzicKXWshooq+sWL1K3WUU5rKZNG/0i3a1OSoX3HqhH5WbWwTmqWfor4urUakGPiRQcleRZTwOg=="], + "fastest-levenshtein": ["fastest-levenshtein@1.0.16", "", {}, "sha512-eRnCtTTtGZFpQCwhJiUOuxPQWRXVKYDn0b2PeHfXL6/Zi53SLAzAHfVhVWK2AryC/WH05kGfxhFIPvTF0SXQzg=="], + "fastq": ["fastq@1.20.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="], "fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], @@ -1019,6 +1291,8 @@ "fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="], + "fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="], + "fs-extra": ["fs-extra@7.0.1", "", { "dependencies": { "graceful-fs": "^4.1.2", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-YJDaCJZEnBmcbw13fvdAM9AwNOJwOzrE4pqMqBq5nFiEqXUqHwlK4B+3pUw6JNvfSPtX05xFHtYy/1ni01eGCw=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], @@ -1031,6 +1305,8 @@ "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], + "get-caller-file": ["get-caller-file@2.0.5", "", {}, "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg=="], + "get-east-asian-width": ["get-east-asian-width@1.6.0", "", {}, "sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA=="], "get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="], @@ -1043,6 +1319,8 @@ "get-stream": ["get-stream@9.0.1", "", { "dependencies": { "@sec-ant/readable-stream": "^0.4.1", "is-stream": "^4.0.1" } }, "sha512-kVCxPF3vQM/N0B1PmoqVUqgHP+EeVjmZSQn+1oCRPxd2P21P2F19lIgbR3HBosbB1PUhOAoctJnfEn2GbN2eZA=="], + "giget": ["giget@3.3.0", "", { "bin": { "giget": "dist/cli.mjs" } }, "sha512-gzi2D96p+AMfDcmJHGDj3KJ9NRiwvlFAU5yfa3ROwWZmFUjX4P43x3BcyRaOMMLto1vUo7C+86+MFhYTl6Ryiw=="], + "glob": ["glob@13.0.6", "", { "dependencies": { "minimatch": "^10.2.2", "minipass": "^7.1.3", "path-scurry": "^2.0.2" } }, "sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw=="], "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], @@ -1055,13 +1333,25 @@ "graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="], + "grad-school": ["grad-school@0.0.5", "", {}, "sha512-rXunEHF9M9EkMydTBux7+IryYXEZinRk6g8OBOGDBzo/qWJjhTxy86i5q7lQYpCLHN8Sqv1XX3OIOc7ka2gtvQ=="], + "h3-v2": ["h3@2.0.1-rc.20", "", { "dependencies": { "rou3": "^0.8.1", "srvx": "^0.11.13" }, "peerDependencies": { "crossws": "^0.4.1" }, "optionalPeers": ["crossws"], "bin": { "h3": "bin/h3.mjs" } }, "sha512-28ljodXuUp0fZovdiSRq4G9OgrxCztrJe5VdYzXAB7ueRvI7pIUqLU14Xi3XqdYJ/khXjfpUOOD2EQa6CmBgsg=="], + "has-flag": ["has-flag@4.0.0", "", {}, "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ=="], + "has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="], "hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="], - "hono": ["hono@4.12.29", "", {}, "sha512-1hNiRjawYrLq/4m3DQQjPGFg0VZkk4RjQJDff/excI6Dm9BiL75qxGrd7/c6YOxPdq6AscP3LiXhQ6fKFC1Waw=="], + "hono": ["hono@4.12.31", "", {}, "sha512-zJIHFrl6bq3RDd2YusFNCDlM8qUprxKswyi/OPzPyzKDdyBXDqWx8bZlZ7R+saTdSTatUmb3O7K4SspGPaEOQg=="], + + "hosted-git-info": ["hosted-git-info@10.1.1", "", { "dependencies": { "lru-cache": "^11.1.0" } }, "sha512-DeOnSPAvOndYKfw075gt8yZzQ7S2hNztw34zBTfhIzLhmBTswIBg5/y+pqu/VD5cYWm5goAFTusDmUEmKZ0PEQ=="], + + "html-to-text": ["html-to-text@9.0.5", "", { "dependencies": { "@selderee/plugin-htmlparser2": "^0.11.0", "deepmerge": "^4.3.1", "dom-serializer": "^2.0.0", "htmlparser2": "^8.0.2", "selderee": "^0.11.0" } }, "sha512-qY60FjREgVZL03vJU6IfMV4GDjGBIoOyvuFdpBDIX9yTlDw0TjxVBQp+P8NvpdIXNJvfWBTNul7fsAQJq2FNpg=="], + + "html5parser": ["html5parser@3.0.0", "", {}, "sha512-iNpSopa+4YHX50UOk825tBy7MghmXHo/ZpLskBYN0kAr1xhH8GlIMk5bLRXcZlfP3AnLUcSuFMu8C4MdOUxA8A=="], + + "htmlparser2": ["htmlparser2@8.0.2", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.0.1", "entities": "^4.4.0" } }, "sha512-GYdjWKDkbRLkZ5geuHs5NY1puJ+PXwP7+fHPRz06Eirsb9ugf6d8kkXav6ADhcODhFFPMIXyxkxSuMf3D6NCFA=="], "http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="], @@ -1073,8 +1363,12 @@ "husky": ["husky@9.1.7", "", { "bin": { "husky": "bin.js" } }, "sha512-5gs5ytaNjBrh5Ow3zrvdUUY+0VxIuWVL4i9irt6friV+BqdCfmV11CQTWMiBYWHbXhco+J1kHfTOUkePhCDvMA=="], + "ical-generator": ["ical-generator@11.0.0", "", { "peerDependencies": { "@touch4it/ical-timezones": ">=1.6.0", "@types/luxon": ">= 1.26.0", "@types/mocha": ">= 8.2.1", "@types/node": "*", "dayjs": ">= 1.10.0", "luxon": ">= 1.26.0", "moment": ">= 2.29.0", "moment-timezone": ">= 0.5.33", "rrule": ">= 2.6.8" }, "optionalPeers": ["@touch4it/ical-timezones", "@types/luxon", "@types/mocha", "@types/node", "dayjs", "luxon", "moment", "moment-timezone", "rrule"] }, "sha512-OScZbXduIbjqtJzq0WLyPpAuKnc106+l28wszD+Wi2O9jXn76NVBfr4Ksv2XFyQn4JNZ9vWr5xAac0uT/FhVag=="], + "iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="], + "ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="], + "ignore": ["ignore@5.3.2", "", {}, "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g=="], "import-fresh": ["import-fresh@3.3.1", "", { "dependencies": { "parent-module": "^1.0.0", "resolve-from": "^4.0.0" } }, "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ=="], @@ -1091,8 +1385,16 @@ "ipaddr.js": ["ipaddr.js@1.9.1", "", {}, "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g=="], + "is-accessor-descriptor": ["is-accessor-descriptor@1.0.2", "", { "dependencies": { "hasown": "^2.0.3" } }, "sha512-AIbwAcazqP3R65dGvqk1V+a+vE5Fg1yu/ZKMOiBWSUIXXiwQkYmXQcVa2O0nh0tSDKDFKxG2mY7dB1Sr4hEP1g=="], + "is-arrayish": ["is-arrayish@0.2.1", "", {}, "sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg=="], + "is-buffer": ["is-buffer@1.1.6", "", {}, "sha512-NcdALwpXkTm5Zvvbk7owOUSvVvBKDgKP5/ewfXEznmQFfs4ZRmanOeKBTjRVjka3QFoN6XJ+9F3USqfHqTaU5w=="], + + "is-data-descriptor": ["is-data-descriptor@1.0.1", "", { "dependencies": { "hasown": "^2.0.0" } }, "sha512-bc4NlCDiCr28U4aEsQ3Qs2491gVq4V8G7MQyws968ImqjKuYtTJXrl7Vq7jsN7Ly/C3xj5KWFrY7sHNeDkAzXw=="], + + "is-descriptor": ["is-descriptor@1.0.4", "", { "dependencies": { "is-accessor-descriptor": "^1.0.2", "is-data-descriptor": "^1.0.1" } }, "sha512-bv5z95W0dDtLfKwDfkTNxaRxmISBD3eQBKJeVxv2AQ7MjuUnDNG7cIQqvFtMOUYhsILWHhMayWdoGqNqYYYjww=="], + "is-docker": ["is-docker@2.2.1", "", { "bin": { "is-docker": "cli.js" } }, "sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ=="], "is-extglob": ["is-extglob@2.1.1", "", {}, "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ=="], @@ -1101,13 +1403,15 @@ "is-glob": ["is-glob@4.0.3", "", { "dependencies": { "is-extglob": "^2.1.1" } }, "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg=="], + "is-in-ci": ["is-in-ci@2.0.0", "", { "bin": { "is-in-ci": "cli.js" } }, "sha512-cFeerHriAnhrQSbpAxL37W1wcJKUUX07HyLWZCW1URJT/ra3GyUTzBgUnh24TMVfNTV2Hij2HLxkPHFZfOZy5w=="], + "is-in-ssh": ["is-in-ssh@1.0.0", "", {}, "sha512-jYa6Q9rH90kR1vKB6NM7qqd1mge3Fx4Dhw5TVlK1MUBqhEOuCagrEHMevNuCcbECmXZ0ThXkRm+Ymr51HwEPAw=="], "is-inside-container": ["is-inside-container@1.0.0", "", { "dependencies": { "is-docker": "^3.0.0" }, "bin": { "is-inside-container": "cli.js" } }, "sha512-KIYLCCJghfHZxqjYBE7rEy0OBuTd5xCHS7tHVgvCLkx7StIoaxwNW3hCALgEUjFfeRk+MG/Qxmp/vtETEF3tRA=="], "is-interactive": ["is-interactive@2.0.0", "", {}, "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ=="], - "is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], + "is-number": ["is-number@3.0.0", "", { "dependencies": { "kind-of": "^3.0.2" } }, "sha512-4cboCqIpliH+mAvFNegjZQ4kgKc3ZUhQVr3HvWbSh5q3WH2v82ct+T2Y1hdU5Gdtorx/cLifQjqCbL7bpznLTg=="], "is-obj": ["is-obj@3.0.0", "", {}, "sha512-IlsXEHOjtKhpN8r/tRFj2nDyTmHvcfNeu/nrRIcXE17ROeatXchkojffa1SpdqW4cr/Fj6QkEf/Gn4zf6KKvEQ=="], @@ -1115,6 +1419,8 @@ "is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="], + "is-reference": ["is-reference@3.0.3", "", { "dependencies": { "@types/estree": "^1.0.6" } }, "sha512-ixkJoqQvAP88E6wLydLGGqCJsrFUnqoH6HnaczB8XmDH1oaWU+xxdptvikTgaEhtZ53Ky6YXiBuUI2WXLMCwjw=="], + "is-regexp": ["is-regexp@3.1.0", "", {}, "sha512-rbku49cWloU5bSMI+zaRaXdQHXnthP6DZ/vLnfdSKyL4zUzuWnomtOEiZZOd+ioQ+avFo/qau3KPTc7Fjy1uPA=="], "is-stream": ["is-stream@4.0.1", "", {}, "sha512-Dnz92NInDqYckGEUJv689RbRiTSEHCQ7wOVeALbkOz999YpqT46yMRIGtSNl2iCL1waAZSx40+h59NV/EwzV/A=="], @@ -1143,20 +1449,28 @@ "json-parse-even-better-errors": ["json-parse-even-better-errors@2.3.1", "", {}, "sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w=="], + "json-schema": ["json-schema@0.4.0", "", {}, "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA=="], + "json-schema-traverse": ["json-schema-traverse@1.0.0", "", {}, "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug=="], "json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="], "json5": ["json5@2.2.3", "", { "bin": { "json5": "lib/cli.js" } }, "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg=="], + "jsonc-parser": ["jsonc-parser@3.3.1", "", {}, "sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ=="], + "jsonfile": ["jsonfile@4.0.0", "", { "optionalDependencies": { "graceful-fs": "^4.1.6" } }, "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg=="], + "kind-of": ["kind-of@3.2.2", "", { "dependencies": { "is-buffer": "^1.1.5" } }, "sha512-NOW9QQXMoZGg/oqnVNoNTTIFEIid1627WCffUBJEdMxYApq7mNE7CpzucIPc+ZQg25Phej7IJSmX3hO+oblOtQ=="], + "kleur": ["kleur@4.1.5", "", {}, "sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ=="], "kubernetes-types": ["kubernetes-types@1.30.0", "", {}, "sha512-Dew1okvhM/SQcIa2rcgujNndZwU8VnSapDgdxlYoB84ZlpAD43U6KLAFqYo17ykSFGHNPrg0qry0bP+GJd9v7Q=="], "kysely": ["kysely@0.29.3", "", {}, "sha512-VHtBdW6XB/pgoTSqraM3UAa2rYoYdNXqnNPpX+8XXP+cwYbVEFuAp3HyPt1vpNfU9l7Y2kpUrA9QDPsy8uUqOQ=="], + "leac": ["leac@0.6.0", "", {}, "sha512-y+SqErxb8h7nE/fiEX07jsbuhrpO9lL8eca7/Y1nuWV2moNlXhyd59iDGcRf6moVyDMbmTNzL40SUyrFU/yDpg=="], + "lightningcss": ["lightningcss@1.32.0", "", { "dependencies": { "detect-libc": "^2.0.3" }, "optionalDependencies": { "lightningcss-android-arm64": "1.32.0", "lightningcss-darwin-arm64": "1.32.0", "lightningcss-darwin-x64": "1.32.0", "lightningcss-freebsd-x64": "1.32.0", "lightningcss-linux-arm-gnueabihf": "1.32.0", "lightningcss-linux-arm64-gnu": "1.32.0", "lightningcss-linux-arm64-musl": "1.32.0", "lightningcss-linux-x64-gnu": "1.32.0", "lightningcss-linux-x64-musl": "1.32.0", "lightningcss-win32-arm64-msvc": "1.32.0", "lightningcss-win32-x64-msvc": "1.32.0" } }, "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ=="], "lightningcss-android-arm64": ["lightningcss-android-arm64@1.32.0", "", { "os": "android", "cpu": "arm64" }, "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg=="], @@ -1187,18 +1501,28 @@ "listr2": ["listr2@10.2.2", "", { "dependencies": { "cli-truncate": "^5.2.0", "eventemitter3": "^5.0.4", "log-update": "^6.1.0", "rfdc": "^1.4.1", "wrap-ansi": "^10.0.0" } }, "sha512-JtNtbZj8q5BnDMR7trpwvwk3RIrANtIVzEUm8w7amp6xelLgyuq+4WZoTH913XaQAoH/cNdYhaNzBPA2U3xbDw=="], + "locate-character": ["locate-character@3.0.0", "", {}, "sha512-SW13ws7BjaeJ6p7Q6CO2nchbYEc3X3J6WrmTTDto7yMPqVSZTUyY5Tjbid+Ab8gLnATtygYtiDIJGQRRn2ZOiA=="], + "locate-path": ["locate-path@6.0.0", "", { "dependencies": { "p-locate": "^5.0.0" } }, "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw=="], + "lodash.camelcase": ["lodash.camelcase@4.3.0", "", {}, "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA=="], + "lodash.startcase": ["lodash.startcase@4.4.0", "", {}, "sha512-+WKqsK294HMSc2jEbNgpHpd0JfIBhp7rEV4aqXWqFr6AlXov+SlcgB1Fv01y2kGe3Gc8nMW7VA0SrGuSkRfIEg=="], "log-symbols": ["log-symbols@6.0.0", "", { "dependencies": { "chalk": "^5.3.0", "is-unicode-supported": "^1.3.0" } }, "sha512-i24m8rpwhmPIS4zscNzK6MSEhk0DUWa/8iYQWxhffV8jkI4Phvs3F+quL5xvS0gdQR0FyTCMMH33Y78dDTzzIw=="], "log-update": ["log-update@6.1.0", "", { "dependencies": { "ansi-escapes": "^7.0.0", "cli-cursor": "^5.0.0", "slice-ansi": "^7.1.0", "strip-ansi": "^7.1.0", "wrap-ansi": "^9.0.0" } }, "sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w=="], + "long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="], + "lru-cache": ["lru-cache@11.5.2", "", {}, "sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g=="], "lucide-react": ["lucide-react@1.24.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-YT6mBD8lGKkg4nM39enlm94/sfJIiW0YKUT60fBy4YK8tai31ylg1VhGNWxkpSKHo9UagfnZqwIff3HTDQwXeA=="], + "lunorash": ["lunorash@1.0.0-alpha.98", "", { "dependencies": { "@lunora/cli": "1.0.0-alpha.97", "@lunora/client": "1.0.0-alpha.27", "@lunora/do": "1.0.0-alpha.41", "@lunora/errors": "1.0.0-alpha.7", "@lunora/flags": "1.0.0-alpha.15", "@lunora/ratelimit": "1.0.0-alpha.9", "@lunora/runtime": "1.0.0-alpha.35", "@lunora/server": "1.0.0-alpha.30", "@lunora/values": "1.0.0-alpha.10" }, "bin": { "lunora": "./dist/bin.mjs" } }, "sha512-AEb+KNKlHaTb2slZZn7Jku1cPJPfXweFfdT4tCJFj6VymGanH3PHPSeHpcJ1jBx+x+LyzNuhYeqT/lQwu3dJfQ=="], + + "luxon": ["luxon@3.7.2", "", {}, "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew=="], + "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], "math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="], @@ -1215,6 +1539,8 @@ "micromatch": ["micromatch@4.0.8", "", { "dependencies": { "braces": "^3.0.3", "picomatch": "^2.3.1" } }, "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA=="], + "mime": ["mime@4.1.0", "", { "bin": { "mime": "bin/cli.js" } }, "sha512-X5ju04+cAzsojXKes0B/S4tcYtFAJ6tTMuSPBEn9CPGlrWr8Fiw7qYeLT0XyH80HSoAoqWCaz+MWKh22P7G1cw=="], + "mime-db": ["mime-db@1.54.0", "", {}, "sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ=="], "mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="], @@ -1231,6 +1557,8 @@ "minipass": ["minipass@7.1.3", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="], + "mkdirp-classic": ["mkdirp-classic@0.5.3", "", {}, "sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A=="], + "module-details-from-path": ["module-details-from-path@1.0.4", "", {}, "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w=="], "motion": ["motion@12.42.2", "", { "dependencies": { "framer-motion": "^12.42.2", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-Atvv11yUKIid41cVrRBDVX5m8tF8kNpExRSlbpt6APClhDjtwQssgFHhQzejxw7/7YYbjHSPKBVbHo05BuJT5Q=="], @@ -1249,6 +1577,8 @@ "multipasta": ["multipasta@0.2.8", "", {}, "sha512-ZPWuMKyv0cSO29f7hozp+k6+crZbQijV8ipMvxNxRf2SwtYGTX1ZX89Kd20VV4H9Znonx+EQn+iy1wGQsJ+b+Q=="], + "nan": ["nan@2.28.0", "", {}, "sha512-fTsDz99OTq2sVePhGdp4qQhggZFtKr64ZNVyVajRKtMOkJxYekplBh577PiJB12v/D3s2E5cGtOI45LWp6rnLQ=="], + "nanoid": ["nanoid@3.3.15", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-y7Wygv/7mEOvxTuEQDB8StXdMRBWf1kR/tlhAzBRUFkB2jfcLOAxO/SHmOO2zgz1pVgK29/kyupn059/bCHdjA=="], "nanostores": ["nanostores@1.4.0", "", {}, "sha512-i0tloweeudshAEuddpDxcg9Ik6pkPfVsHIgKyf143JrgG7/MOh0+q7BypdLXZPoOP7fOYt1eTcwGkyiVmhJFkA=="], @@ -1261,6 +1591,8 @@ "node-releases": ["node-releases@2.0.51", "", {}, "sha512-wRNIrw4DmVLKQlbgOMdkMx27Wrpzes2hh5Jtbi2bjPd+4wJstWIqP5A+lscnqbm0xxmT5Bpg8Lec5ItEBwx6BQ=="], + "normalize-package-data": ["normalize-package-data@9.0.0", "", { "dependencies": { "hosted-git-info": "^10.1.0", "semver": "^7.3.5", "validate-npm-package-license": "^3.0.4" } }, "sha512-la34cHOCAT6itNOYCvPi40XP8r0y6OHuNkooOfnfFUHdgy5MBw665qq5xsuS02AEC7WPQvhwvb7E9PI1gipplw=="], + "npm-run-path": ["npm-run-path@6.0.0", "", { "dependencies": { "path-key": "^4.0.0", "unicorn-magic": "^0.3.0" } }, "sha512-9qny7Z9DsQU8Ou39ERsPU4OZQlSTP47ShQzuKZ6PRXpYLtIFgl/DEBYEXKlvcEa+9tHVcK8CF81Y2V72qaZhWA=="], "object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="], @@ -1307,8 +1639,12 @@ "parse-ms": ["parse-ms@4.0.0", "", {}, "sha512-TXfryirbmq34y8QBwgqCVLi+8oA3oWx2eAnSn62ITyEhEYaWRlVZ2DvMM9eZbMs/RfxPu/PK/aBLyGj4IrqMHw=="], + "parseley": ["parseley@0.12.1", "", { "dependencies": { "leac": "^0.6.0", "peberminta": "^0.9.0" } }, "sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw=="], + "parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="], + "patch-console": ["patch-console@2.0.0", "", {}, "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA=="], + "path-browserify": ["path-browserify@1.0.1", "", {}, "sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g=="], "path-exists": ["path-exists@4.0.0", "", {}, "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w=="], @@ -1323,6 +1659,8 @@ "pathe": ["pathe@2.0.3", "", {}, "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w=="], + "peberminta": ["peberminta@0.9.0", "", {}, "sha512-XIxfHpEuSJbITd1H3EeQwpcZbTLHc+VVr8ANI9t5sit565tsI4/xK3KWTUFE2e6QiangUkh3B0jihzmGnNrRsQ=="], + "picocolors": ["picocolors@1.1.1", "", {}, "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA=="], "picomatch": ["picomatch@4.0.5", "", {}, "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A=="], @@ -1337,6 +1675,8 @@ "playwright-core": ["playwright-core@1.61.1", "", { "bin": { "playwright-core": "cli.js" } }, "sha512-h7Qlt6m4REp25qvIdvbDtVmD4LqVXfpRxhORv9L0jzETM05p4fuPJ3dKyuSXQxDSbXnmS79HAgi9589lGSpLkg=="], + "postal-mime": ["postal-mime@2.7.5", "", {}, "sha512-GNEXKvWFQnbgO5NlrGzVa0FmWzBZ24PersAWErttSg1Hjpf0ATxTwS5DOMGaOpTG6bUh5cTr7xi0jAD942wCJA=="], + "postcss": ["postcss@8.5.16", "", { "dependencies": { "nanoid": "^3.3.12", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-vuwillviilfKZsg0VGj5R/YwwcHx4SLsIOI/7K6mQkWx+l5cUHTjj5g0AasTBcyXsbfTgrwsUNmVUb5xVwyPwg=="], "postcss-selector-parser": ["postcss-selector-parser@7.1.4", "", { "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" } }, "sha512-HeP7D2wyhkR+XaK6v4W8oRF62Dsz4flyuczALJp61GckGm42u1saSSJ/0auvcBqxs3jMRFEcPK34At/0JBKdOg=="], @@ -1351,10 +1691,14 @@ "prompts": ["prompts@2.4.2", "", { "dependencies": { "kleur": "^3.0.3", "sisteransi": "^1.0.5" } }, "sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q=="], + "protobufjs": ["protobufjs@7.6.5", "", { "dependencies": { "@protobufjs/aspromise": "^1.1.2", "@protobufjs/base64": "^1.1.2", "@protobufjs/codegen": "^2.0.5", "@protobufjs/eventemitter": "^1.1.1", "@protobufjs/fetch": "^1.1.1", "@protobufjs/float": "^1.0.2", "@protobufjs/path": "^1.1.2", "@protobufjs/pool": "^1.1.0", "@protobufjs/utf8": "^1.1.1", "@types/node": ">=13.7.0", "long": "^5.3.2" } }, "sha512-/FPD0nUc9jH6rfFjji9IBqOz4pcSE3CsT1m7Ep6Mdb0LxSUMj8hgl6GomOvZzpNpAqqGaXA0P3VSrZLFzIhQrw=="], + "proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="], "proxy-from-env": ["proxy-from-env@1.1.0", "", {}, "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="], + "pump": ["pump@3.0.4", "", { "dependencies": { "end-of-stream": "^1.1.0", "once": "^1.3.1" } }, "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA=="], + "pure-rand": ["pure-rand@8.4.2", "", {}, "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng=="], "qs": ["qs@6.15.3", "", { "dependencies": { "es-define-property": "^1.0.1", "side-channel": "^1.1.1" } }, "sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A=="], @@ -1371,6 +1715,8 @@ "react-dom": ["react-dom@19.2.7", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.7" } }, "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ=="], + "react-reconciler": ["react-reconciler@0.33.0", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.0" } }, "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA=="], + "react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="], "react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="], @@ -1379,10 +1725,16 @@ "read-yaml-file": ["read-yaml-file@1.1.0", "", { "dependencies": { "graceful-fs": "^4.1.5", "js-yaml": "^3.6.1", "pify": "^4.0.1", "strip-bom": "^3.0.0" } }, "sha512-VIMnQi/Z4HT2Fxuwg5KrY174U1VdUIASQVWXXyqtNRtxSr9IYkn1rsI6Tb6HsrHCmB7gVpNwX6JxPTHcH6IoTA=="], + "readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="], + "readdirp": ["readdirp@5.0.0", "", {}, "sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ=="], "recast": ["recast@0.23.12", "", { "dependencies": { "ast-types": "^0.16.1", "esprima": "~4.0.0", "source-map": "~0.6.1", "tiny-invariant": "^1.3.3", "tslib": "^2.0.1" } }, "sha512-dEWRjcINDu/F4l2dYx57ugBtD7HV9KXESyxhzw/MqWLeglJrsjJKqACPyUPg+6AF8mIgm+Zi0dZ3ACoIg+QtpA=="], + "remove-accents": ["remove-accents@0.5.0", "", {}, "sha512-8g3/Otx1eJaVD12e31UbJj1YzdtVvzH85HV7t+9MJYk/u3XmkOUJ5Ys9wQrf9PCPK8+xn4ymzqYCiZl6QWKn+A=="], + + "require-directory": ["require-directory@2.1.1", "", {}, "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q=="], + "require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="], "require-in-the-middle": ["require-in-the-middle@8.0.1", "", { "dependencies": { "debug": "^4.3.5", "module-details-from-path": "^1.0.3" } }, "sha512-QT7FVMXfWOYFbeRBF6nu+I6tr2Tf3u0q8RIEjNob/heKY/nh7drD/k7eeMFmSQgnTtCzLDcCu/XEnpW2wk4xCQ=="], @@ -1407,10 +1759,14 @@ "run-parallel": ["run-parallel@1.2.0", "", { "dependencies": { "queue-microtask": "^1.2.2" } }, "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA=="], + "safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="], + "safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="], "scheduler": ["scheduler@0.27.0", "", {}, "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q=="], + "selderee": ["selderee@0.11.0", "", { "dependencies": { "parseley": "^0.12.0" } }, "sha512-5TF+l7p4+OsnP8BCCvSyZiSPc4x4//p5uPwK8TCnVPJYRmU2aYKMpOXvw8zM5a5JvuuCGN1jmsMwuU2W02ukfA=="], + "semifies": ["semifies@1.0.0", "", {}, "sha512-xXR3KGeoxTNWPD4aBvL5NUpMTT7WMANr3EWnaS190QVkY52lqqcVRD7Q05UVbBhiWDGWMlJEUam9m7uFFGVScw=="], "semver": ["semver@7.8.5", "", { "bin": { "semver": "bin/semver.js" } }, "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA=="], @@ -1451,6 +1807,8 @@ "slice-ansi": ["slice-ansi@8.0.0", "", { "dependencies": { "ansi-styles": "^6.2.3", "is-fullwidth-code-point": "^5.1.0" } }, "sha512-stxByr12oeeOyY2BlviTNQlYV5xOj47GirPr4yA1hE9JCtxfQN0+tVbkxwCtYDQWhEKWFHsEK48ORg5jrouCAg=="], + "solid-js": ["solid-js@1.9.14", "", { "dependencies": { "csstype": "^3.1.0", "seroval": "~1.5.4", "seroval-plugins": "~1.5.4" } }, "sha512-sAEXC0Kk0S1EDg+8ysEWJDbYhA3RRoEjwuySUGlKIemeo0I5YZfOyumNjNs9Sv3y2nmhD+0rW66ag2HsMuQiGQ=="], + "sonner": ["sonner@2.0.7", "", { "peerDependencies": { "react": "^18.0.0 || ^19.0.0 || ^19.0.0-rc", "react-dom": "^18.0.0 || ^19.0.0 || ^19.0.0-rc" } }, "sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w=="], "sorted-btree": ["sorted-btree@1.8.1", "", {}, "sha512-395+XIP+wqNn3USkFSrNz7G3Ss/MXlZEqesxvzCRFwL14h6e8LukDHdLBePn5pwbm5OQ9vGu8mDyz2lLDIqamQ=="], @@ -1461,10 +1819,22 @@ "spawndamnit": ["spawndamnit@3.0.1", "", { "dependencies": { "cross-spawn": "^7.0.5", "signal-exit": "^4.0.1" } }, "sha512-MmnduQUuHCoFckZoWnXsTg7JaiLBJrKFj9UI2MbRPGaJeVpsLcVBu6P/IGZovziM/YBsellCmsprgNA+w0CzVg=="], + "spdx-correct": ["spdx-correct@3.2.0", "", { "dependencies": { "spdx-expression-parse": "^3.0.0", "spdx-license-ids": "^3.0.0" } }, "sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA=="], + + "spdx-exceptions": ["spdx-exceptions@2.5.0", "", {}, "sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w=="], + + "spdx-expression-parse": ["spdx-expression-parse@3.0.1", "", { "dependencies": { "spdx-exceptions": "^2.1.0", "spdx-license-ids": "^3.0.0" } }, "sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q=="], + + "spdx-license-ids": ["spdx-license-ids@3.0.23", "", {}, "sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw=="], + + "split-ca": ["split-ca@1.0.1", "", {}, "sha512-Q5thBSxp5t8WPTTJQS59LrGqOZqOsrhDGDVm8azCqIBjSBd7nd9o2PM+mDulQQkh8h//4U6hFZnc/mul8t5pWQ=="], + "sprintf-js": ["sprintf-js@1.0.3", "", {}, "sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g=="], "srvx": ["srvx@0.11.21", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-GWTHjKMeekX8CwJf4VU9Oo6mJpSGaflGMddbCvR+Cmmh9sslRMiGbAoqqZacE0r1ncARh6buCEETr2W52F8b1w=="], + "ssh2": ["ssh2@1.17.0", "", { "dependencies": { "asn1": "^0.2.6", "bcrypt-pbkdf": "^1.0.2" }, "optionalDependencies": { "cpu-features": "~0.0.10", "nan": "^2.23.0" } }, "sha512-wPldCk3asibAjQ/kziWQQt1Wh3PgDFpC0XpwclzKcdT1vql6KeYxf5LIt4nlFkUeR8WuphYMKqUA56X4rjbfgQ=="], + "statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="], "stdin-discarder": ["stdin-discarder@0.2.2", "", {}, "sha512-UhDfHmA92YAlNnCfhmq0VeNL5bDbiZGg7sZ2IvPsXubGkiNa9EC+tUTsjBRsYUAz87btI6/1wf4XoVvQ3uRnmQ=="], @@ -1473,6 +1843,8 @@ "string-width": ["string-width@7.2.0", "", { "dependencies": { "emoji-regex": "^10.3.0", "get-east-asian-width": "^1.0.0", "strip-ansi": "^7.1.0" } }, "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ=="], + "string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="], + "stringify-object": ["stringify-object@5.0.0", "", { "dependencies": { "get-own-enumerable-keys": "^1.0.0", "is-obj": "^3.0.0", "is-regexp": "^3.1.0" } }, "sha512-zaJYxz2FtcMb4f+g60KsRNFOpVMUyuJgA51Zi5Z1DOTC3S59+OQiVOzE9GZt0x72uBGWKsQIuBKeF9iusmKFsg=="], "strip-ansi": ["strip-ansi@6.0.1", "", { "dependencies": { "ansi-regex": "^5.0.1" } }, "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A=="], @@ -1483,7 +1855,11 @@ "stripe": ["stripe@22.3.0", "", { "peerDependencies": { "@types/node": ">=18" }, "optionalPeers": ["@types/node"] }, "sha512-ypO6xjVrMWs9SmIMeHr8naCx3dAQ0clxMdUTxn7Ejd7hmY9meBGfE+N4pVHkf9sUNebAHp6uJo6mV3GxDIc2cA=="], - "supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="], + "suffix-thumb": ["suffix-thumb@5.0.2", "", {}, "sha512-I5PWXAFKx3FYnI9a+dQMWNqTxoRt6vdBdb0O+BJ1sxXCWtSoQCusc13E58f+9p4MYx/qCnEMkD5jac6K2j3dgA=="], + + "supports-color": ["supports-color@8.1.1", "", { "dependencies": { "has-flag": "^4.0.0" } }, "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q=="], + + "svelte": ["svelte@5.56.7", "", { "dependencies": { "@jridgewell/remapping": "^2.3.4", "@jridgewell/sourcemap-codec": "^1.5.0", "@sveltejs/acorn-typescript": "^1.0.10", "@types/estree": "^1.0.5", "@types/trusted-types": "^2.0.7", "acorn": "^8.12.1", "aria-query": "5.3.1", "axobject-query": "^4.1.0", "clsx": "^2.1.1", "devalue": "^5.8.1", "esm-env": "^1.2.1", "esrap": "^2.2.12", "is-reference": "^3.0.3", "locate-character": "^3.0.0", "magic-string": "^0.30.11", "zimmerframe": "^1.1.2" } }, "sha512-5qERUZX80oQj6XrDMUmD2Uhd/cIpCPDWWKBK3ZHmyRUC9apPyamWM8xMo31mbWsIQxwG2hVoSnOJ/EcnhVkkzQ=="], "systeminformation": ["systeminformation@5.31.15", "", { "os": "!aix", "bin": { "systeminformation": "lib/cli.js" } }, "sha512-7mqCtD28TK5dVdLAQONVa/Do/NBgMH2dxqf49nh6DIKoEWuDg6tkgGBP+dN22VEJVPZa/QqiHomhWNRn4WUNTQ=="], @@ -1493,8 +1869,14 @@ "tapable": ["tapable@2.3.3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="], + "tar-fs": ["tar-fs@2.1.5", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw=="], + + "tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="], + "term-size": ["term-size@2.2.1", "", {}, "sha512-wK0Ri4fOGjv/XPy8SBHZChl8CM7uMc5VML7SqiQ0zG7+J5Vr+RMQDoHa2CNT6KHUnTGIXH34UDMkPzAUyapBZg=="], + "terminal-size": ["terminal-size@4.0.1", "", {}, "sha512-avMLDQpUI9I5XFrklECw1ZEUPJhqzcwSWsyyI8blhRLT+8N1jLJWLWWYQpB2q2xthq8xDvjZPISVh53T/+CLYQ=="], + "tiny-invariant": ["tiny-invariant@1.3.3", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="], "tinyexec": ["tinyexec@1.2.4", "", {}, "sha512-SHf/r48b7vOrjve9PxJo3MN5v5yuyjHvdUcrQffT3WXMUfnGmHDVbC4k3sHJaJTgZCwpUplIaAo5ANtMyp3YHg=="], @@ -1515,10 +1897,14 @@ "tsconfig-paths": ["tsconfig-paths@4.2.0", "", { "dependencies": { "json5": "^2.2.2", "minimist": "^1.2.6", "strip-bom": "^3.0.0" } }, "sha512-NoZ4roiN7LnbKn9QqE1amc9DJfzvZXxF4xDavcOWt1BPkdx+m+0gJuPM+S0vCe7zTJMYUP0R8pO2XMr+Y8oLIg=="], + "tseep": ["tseep@1.3.1", "", {}, "sha512-ZPtfk1tQnZVyr7BPtbJ93qaAh2lZuIOpTMjhrYa4XctT8xe7t4SAW9LIxrySDuYMsfNNayE51E/WNGrNVgVicQ=="], + "tslib": ["tslib@2.8.1", "", {}, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], "tw-animate-css": ["tw-animate-css@1.4.0", "", {}, "sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ=="], + "tweetnacl": ["tweetnacl@0.14.5", "", {}, "sha512-KXXFFdAbFXY4geFIwoyNK+f5Z1b7swfXABfL7HXCmoIWMKU3dmS26672A4EeQtDzLKy7SXmfBu51JolvEKwtGA=="], + "type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="], "typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="], @@ -1553,6 +1939,8 @@ "uuid": ["uuid@14.0.1", "", { "bin": { "uuid": "dist-node/bin/uuid" } }, "sha512-6ZxzVpzDXDa3bJWaHilVayA+BH/1zmxCJoVgvmqJnid/gPoKHxUrS/aC/T6LGQtNHT+XHG9fXPJB4d+IrU30Ew=="], + "validate-npm-package-license": ["validate-npm-package-license@3.0.4", "", { "dependencies": { "spdx-correct": "^3.0.0", "spdx-expression-parse": "^3.0.0" } }, "sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew=="], + "validate-npm-package-name": ["validate-npm-package-name@7.0.2", "", {}, "sha512-hVDIBwsRruT73PbK7uP5ebUt+ezEtCmzZz3F59BSr2F6OVFnJ/6h8liuvdLrQ88Xmnk6/+xGGuq+pG9WwTuy3A=="], "vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="], @@ -1561,6 +1949,10 @@ "vitefu": ["vitefu@1.1.3", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg=="], + "vue": ["vue@3.5.40", "", { "dependencies": { "@vue/compiler-dom": "3.5.40", "@vue/compiler-sfc": "3.5.40", "@vue/runtime-dom": "3.5.40", "@vue/server-renderer": "3.5.40", "@vue/shared": "3.5.40" }, "peerDependencies": { "typescript": "*" }, "optionalPeers": ["typescript"] }, "sha512-+8PJ4SJXdn/cHGImF4CKdxlWHIN5Dkt7DoufRREM6h6uVCx2m7QxgcEQmmzyOK8A9mcafg7sFbJFYsdFVubTig=="], + + "vue-demi": ["vue-demi@0.14.10", "", { "peerDependencies": { "@vue/composition-api": "^1.0.0-rc.1", "vue": "^3.0.0-0 || ^2.6.0" }, "optionalPeers": ["@vue/composition-api"], "bin": { "vue-demi-fix": "bin/vue-demi-fix.js", "vue-demi-switch": "bin/vue-demi-switch.js" } }, "sha512-nMZBOwuzabUO0nLgIcc6rycZEebF6eeUfaiQx9+WSk8e29IbLvPU9feI6tqW4kTo3hvoYAJkMh8n8D0fuISphg=="], + "webidl-conversions": ["webidl-conversions@3.0.1", "", {}, "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ=="], "webpack-virtual-modules": ["webpack-virtual-modules@0.6.2", "", {}, "sha512-66/V2i5hQanC51vBQKPH4aI8NMAcBW59FVBs+rC7eGHupMyfn34q7rZIE+ETlJ+XTevqfUhVVBgSUNSW2flEUQ=="], @@ -1569,8 +1961,12 @@ "which": ["which@4.0.0", "", { "dependencies": { "isexe": "^3.1.1" }, "bin": { "node-which": "bin/which.js" } }, "sha512-GlaYyEb07DPxYCKhKzplCWBJtvxZcZMrL+4UkrTSJHHPyZU4mYYTv3qaOe77H7EODLSSopAUFAc6W8U4yqvscg=="], + "window-size": ["window-size@1.1.1", "", { "dependencies": { "define-property": "^1.0.0", "is-number": "^3.0.0" }, "bin": { "window-size": "cli.js" } }, "sha512-5D/9vujkmVQ7pSmc0SCBmHXbkv6eaHwXEx65MywhmUMsI8sGqJ972APq1lotfcwMKPFLuCFfL8xGHLIp7jaBmA=="], + "workerd": ["workerd@1.20260708.1", "", { "optionalDependencies": { "@cloudflare/workerd-darwin-64": "1.20260708.1", "@cloudflare/workerd-darwin-arm64": "1.20260708.1", "@cloudflare/workerd-linux-64": "1.20260708.1", "@cloudflare/workerd-linux-arm64": "1.20260708.1", "@cloudflare/workerd-windows-64": "1.20260708.1" }, "bin": { "workerd": "bin/workerd" } }, "sha512-WAK+Kt/VVCSldH2qSr8lx46XCJ4Q+bdlHNaFqUtOHthBEIB8C1N8HVW+VOLrxDoTCk0NGNv0zajnBeQK4JOB9w=="], + "workers-ai-provider": ["workers-ai-provider@3.3.1", "", { "peerDependencies": { "@ai-sdk/anthropic": "^3.0.0", "@ai-sdk/google": "^3.0.0", "@ai-sdk/openai": "^3.0.0", "@ai-sdk/provider": "^3.0.0", "ai": "^6.0.0" }, "optionalPeers": ["@ai-sdk/anthropic", "@ai-sdk/google", "@ai-sdk/openai"] }, "sha512-vArwnmiAxQQF1clsXJd9ADn1xK9YUZVxE4umaMhrdsxM2kucxP430LfaoH4rn0AfoqtnuH3bfRhW1ak0r1x/8A=="], + "wrangler": ["wrangler@4.110.0", "", { "dependencies": { "@cloudflare/kv-asset-handler": "0.5.0", "@cloudflare/unenv-preset": "2.16.1", "blake3-wasm": "2.1.5", "esbuild": "0.28.1", "miniflare": "4.20260708.1", "path-to-regexp": "6.3.0", "unenv": "2.0.0-rc.24", "workerd": "1.20260708.1" }, "optionalDependencies": { "fsevents": "2.3.3" }, "peerDependencies": { "@cloudflare/workers-types": "^5.20260708.1" }, "optionalPeers": ["@cloudflare/workers-types"], "bin": { "cf-wrangler": "bin/cf-wrangler.js", "wrangler": "bin/wrangler.js", "wrangler2": "bin/wrangler.js" } }, "sha512-xZeXKYi7hxQRF5anL+v77RkufJNpF9f3Eqeyqq2QBsETpLZgh0Agj0jJ6JPtkbgn6ukZdh8OK5egsGPWIditgg=="], "wrap-ansi": ["wrap-ansi@10.0.0", "", { "dependencies": { "ansi-styles": "^6.2.3", "string-width": "^8.2.0", "strip-ansi": "^7.1.2" } }, "sha512-SGcvg80f0wUy2/fXES19feHMz8E0JoXv2uNgHOu4Dgi2OrCy1lqwFYEJz1BLbDI0exjPMe/ZdzZ/YpGECBG/aQ=="], @@ -1585,24 +1981,36 @@ "xstate": ["xstate@6.0.0-alpha.12", "", {}, "sha512-ekDMVV12EPPLIFeTxHaJPXxe50Vbf0/T2Yd71xCHy99ikrBSjNSTKSCGh5/OG6BJ1YN73/2i7/agAYiep/xsxw=="], + "y18n": ["y18n@5.0.8", "", {}, "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA=="], + "yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="], "yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="], + "yargs": ["yargs@17.7.3", "", { "dependencies": { "cliui": "^8.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "require-directory": "^2.1.1", "string-width": "^4.2.3", "y18n": "^5.0.5", "yargs-parser": "^21.1.1" } }, "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g=="], + + "yargs-parser": ["yargs-parser@21.1.1", "", {}, "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw=="], + "yocto-queue": ["yocto-queue@0.1.0", "", {}, "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q=="], "yocto-spinner": ["yocto-spinner@1.2.1", "", { "dependencies": { "yoctocolors": "^2.1.1" } }, "sha512-9cbFWLhbiZp+820O4pkHGNncI7+MrUGzBOjw8NMG+ewsY+aG0DdEXnr19Smxao32YOjLZRMdn1UtaxcrXOYOIg=="], "yoctocolors": ["yoctocolors@2.1.2", "", {}, "sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug=="], + "yoga-layout": ["yoga-layout@3.2.1", "", {}, "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ=="], + "youch": ["youch@4.1.0-beta.10", "", { "dependencies": { "@poppinss/colors": "^4.1.5", "@poppinss/dumper": "^0.6.4", "@speed-highlight/core": "^1.2.7", "cookie": "^1.0.2", "youch-core": "^0.3.3" } }, "sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ=="], "youch-core": ["youch-core@0.3.3", "", { "dependencies": { "@poppinss/exception": "^1.2.2", "error-stack-parser-es": "^1.0.5" } }, "sha512-ho7XuGjLaJ2hWHoK8yFnsUGy2Y5uDpqSTq1FkHLK4/oqKtyUU1AFbOOxY4IpC9f0fTLjwYbslUz0Po5BpD1wrA=="], + "zimmerframe": ["zimmerframe@1.1.4", "", {}, "sha512-B58NGBEoc8Y9MWWCQGl/gq9xBCe4IiKM0a2x7GZdQKOW5Exr8S1W24J6OgM1njK8xCRGvAJIL/MxXHf6SkmQKQ=="], + "zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="], "zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="], + "@antfu/install-pkg/package-manager-detector": ["package-manager-detector@1.8.0", "", {}, "sha512-yQA4H19AmPEoMUeavPMDIe1higySl/gH/yaQrkT/s07Qp+7pp2hYz30N3z2l5BkjVkF9Ow6o0wjJamm2y7Sn0A=="], + "@apm-js-collab/code-transformer/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="], "@babel/helper-annotate-as-pure/@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], @@ -1641,8 +2049,26 @@ "@dotenvx/dotenvx/open": ["open@8.4.2", "", { "dependencies": { "define-lazy-prop": "^2.0.0", "is-docker": "^2.1.1", "is-wsl": "^2.2.0" } }, "sha512-7x81NCL719oNbsq/3mh+hVrAWmFuEYUqrq/Iw3kUzH8ReypT9QQ0BLoJS7/G9k6N81XjW4qHWtjWwe/9eLy1EQ=="], + "@grpc/grpc-js/@grpc/proto-loader": ["@grpc/proto-loader@0.8.1", "", { "dependencies": { "lodash.camelcase": "^4.3.0", "long": "^5.0.0", "protobufjs": "^7.5.5", "yargs": "^17.7.2" }, "bin": { "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" } }, "sha512-wtF6h+DY6M3YaDBPAmvuuA6jV8Sif9MjtOI5euKFWRgCDl5PeDpPsHR9u2l6St5ceY8AZgoNDww5+HvEsXFsGg=="], + "@img/sharp-wasm32/@emnapi/runtime": ["@emnapi/runtime@1.11.2", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-kyOl3X0DuTiT1h2ft8r2fYO8JYtU9a9Xis/zBSiGArNaagCOWx90N1k2wxp18czFDH+OgcWGb5ZP/XMt3dcyPA=="], + "@lunora/cli/magic-string": ["magic-string@1.1.0", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-kS3VHe0nEPST2saQV4Rbkchcd3UBRkVTQHo1D3h/ZTwFDhai/mfKkmtPAtD129EOI7K3HlHIsFOt0WrI2/oU9g=="], + + "@lunora/cli/ts-morph": ["ts-morph@28.0.0", "", { "dependencies": { "@ts-morph/common": "~0.29.0", "code-block-writer": "^13.0.3" } }, "sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g=="], + + "@lunora/codegen/ts-morph": ["ts-morph@28.0.0", "", { "dependencies": { "@ts-morph/common": "~0.29.0", "code-block-writer": "^13.0.3" } }, "sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g=="], + + "@lunora/config/es-module-lexer": ["es-module-lexer@2.3.1", "", {}, "sha512-shc1dbU90Yl/xq1QrC7QRtfcwURZuVRfPhZbDoldJ1cn1gzDvBaBWlv0eFolj5+0znnPJz5TXLxsN77X/12KTA=="], + + "@lunora/config/ts-morph": ["ts-morph@28.0.0", "", { "dependencies": { "@ts-morph/common": "~0.29.0", "code-block-writer": "^13.0.3" } }, "sha512-Wp3tnZ2bzwxyTZMtgWVzXDfm7lB1Drz+y9DmmYH/L702PQhPyVrp3pkou3yIz4qjS14GY9kcpmLiOOMvl8oG1g=="], + + "@lunora/queue/@lunora/errors": ["@lunora/errors@1.0.0-alpha.6", "", {}, "sha512-IBn86WYhsT2bZrwnDrp88aIn+GENPzr9qtjHsuwU3bcbNrjQoe1GKbMMCmPP6AVl6mAe3/6UqJhIE3Cw5r8MIA=="], + + "@lunora/ratelimit/@lunora/errors": ["@lunora/errors@1.0.0-alpha.6", "", {}, "sha512-IBn86WYhsT2bZrwnDrp88aIn+GENPzr9qtjHsuwU3bcbNrjQoe1GKbMMCmPP6AVl6mAe3/6UqJhIE3Cw5r8MIA=="], + + "@lunora/scheduler/@lunora/errors": ["@lunora/errors@1.0.0-alpha.6", "", {}, "sha512-IBn86WYhsT2bZrwnDrp88aIn+GENPzr9qtjHsuwU3bcbNrjQoe1GKbMMCmPP6AVl6mAe3/6UqJhIE3Cw5r8MIA=="], + "@manypkg/find-root/@types/node": ["@types/node@12.20.55", "", {}, "sha512-J8xLz7q2OFulZ2cyGTLE1TbbZcjpno7FaN6zdJNrgAdrJ+DZzh/uFR6YrTb4C+nXakvud8Q4+rbhoIWlYQbUFQ=="], "@manypkg/find-root/find-up": ["find-up@4.1.0", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="], @@ -1653,6 +2079,14 @@ "@manypkg/get-packages/fs-extra": ["fs-extra@8.1.0", "", { "dependencies": { "graceful-fs": "^4.2.0", "jsonfile": "^4.0.0", "universalify": "^0.1.0" } }, "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g=="], + "@modelcontextprotocol/sdk/hono": ["hono@4.12.29", "", {}, "sha512-1hNiRjawYrLq/4m3DQQjPGFg0VZkk4RjQJDff/excI6Dm9BiL75qxGrd7/c6YOxPdq6AscP3LiXhQ6fKFC1Waw=="], + + "@poppinss/dumper/supports-color": ["supports-color@10.2.2", "", {}, "sha512-SS+jx45GF1QjgEXQx4NJZV9ImqmO2NPz5FNsIHrsDjh2YsHnawpan7SNQ1o8NuhrbHZy9AZhIoCUiCeaW/C80g=="], + + "@react-email/render/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], + + "@react-email/render/prettier": ["prettier@3.9.5", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-/FVl766LpUfB5vXgCYOYa0MeV/441Ia99AeICQIQFTY/Nw0roZwULcXpku5i1/m5kt/baz+s4Zogspd839HSMg=="], + "@sentry/bundler-plugins/@babel/core": ["@babel/core@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="], "@sentry/cli/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], @@ -1669,6 +2103,12 @@ "@tailwindcss/oxide-wasm32-wasi/tslib": ["tslib@2.8.1", "", { "bundled": true }, "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w=="], + "@tanstack/query-db-collection/@tanstack/db": ["@tanstack/db@0.6.14", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@tanstack/db-ivm": "0.1.18", "@tanstack/pacer-lite": "^0.2.1" }, "peerDependencies": { "typescript": ">=4.7" } }, "sha512-Kqma/PcWhn2e21iJPM/FMKwdMuJUYII9zkKPUsD42/ceEOYRtimbBSe+xll7EY805xE2HuQ3NGSSU8UiYXpHUw=="], + + "@tanstack/react-db/@tanstack/db": ["@tanstack/db@0.6.14", "", { "dependencies": { "@standard-schema/spec": "^1.1.0", "@tanstack/db-ivm": "0.1.18", "@tanstack/pacer-lite": "^0.2.1" }, "peerDependencies": { "typescript": ">=4.7" } }, "sha512-Kqma/PcWhn2e21iJPM/FMKwdMuJUYII9zkKPUsD42/ceEOYRtimbBSe+xll7EY805xE2HuQ3NGSSU8UiYXpHUw=="], + + "@tanstack/react-query/@tanstack/query-core": ["@tanstack/query-core@5.101.4", "", {}, "sha512-gNwcvOJcRbLWPOLG/2OBm+zM+Yv+MKsXKEOWC57USuZDEsI71hEErQsiEGx5wX9rzWWkfwM0fVSPoiIFSsxfiw=="], + "@tanstack/react-router/@tanstack/react-store": ["@tanstack/react-store@0.9.3", "", { "dependencies": { "@tanstack/store": "0.9.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg=="], "@tanstack/router-generator/@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], @@ -1687,12 +2127,18 @@ "@tanstack/router-utils/@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], + "@tanstack/solid-query/@tanstack/query-core": ["@tanstack/query-core@5.101.4", "", {}, "sha512-gNwcvOJcRbLWPOLG/2OBm+zM+Yv+MKsXKEOWC57USuZDEsI71hEErQsiEGx5wX9rzWWkfwM0fVSPoiIFSsxfiw=="], + "@tanstack/start-plugin-core/@babel/code-frame": ["@babel/code-frame@7.27.1", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.27.1", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg=="], "@tanstack/start-plugin-core/@babel/core": ["@babel/core@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="], "@tanstack/start-plugin-core/@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], + "@tanstack/svelte-query/@tanstack/query-core": ["@tanstack/query-core@5.101.4", "", {}, "sha512-gNwcvOJcRbLWPOLG/2OBm+zM+Yv+MKsXKEOWC57USuZDEsI71hEErQsiEGx5wX9rzWWkfwM0fVSPoiIFSsxfiw=="], + + "@tanstack/vue-query/@tanstack/query-core": ["@tanstack/query-core@5.101.4", "", {}, "sha512-gNwcvOJcRbLWPOLG/2OBm+zM+Yv+MKsXKEOWC57USuZDEsI71hEErQsiEGx5wX9rzWWkfwM0fVSPoiIFSsxfiw=="], + "@types/babel__core/@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="], "@types/babel__core/@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], @@ -1705,6 +2151,16 @@ "@types/babel__traverse/@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], + "@visulima/email/html-to-text": ["html-to-text@10.0.0", "", { "dependencies": { "@selderee/plugin-htmlparser2": "~0.12.0", "deepmerge-ts": "^7.1.5", "dom-serializer": "^2.0.0", "htmlparser2": "^10.1.0", "selderee": "~0.12.0" } }, "sha512-2OH59Gtprdczel+7Rxgpz9hGVJREaf8Lt1H4kZwWHpEn70VQKRuMNGsb2eDbwaTzrYzb0hheiOG1P7Dim0B4dQ=="], + + "@visulima/email/lru-cache": ["lru-cache@11.5.1", "", {}, "sha512-RPimw/7aMdv2oqRrxKwvZXcPfwBrn/JZ2xYcY9Hus/6LaS3VOAKVWKWgNLCFSiOm1ESXinjsDlidVU7JlnCN2A=="], + + "@vue/compiler-core/@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="], + + "@vue/compiler-sfc/@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="], + + "@vue/compiler-sfc/postcss": ["postcss@8.5.22", "", { "dependencies": { "nanoid": "^3.3.16", "picocolors": "^1.1.1", "source-map-js": "^1.2.1" } }, "sha512-KBDEIpLrvpv16pp3K0Fw+UCoZfopFjjgeB+0tA/aaThfEE74kKDLrgg603YvOWJyg3+WYtyq3xYsQWsIyZlPqQ=="], + "babel-dead-code-elimination/@babel/core": ["@babel/core@7.29.7", "", { "dependencies": { "@babel/code-frame": "^7.29.7", "@babel/generator": "^7.29.7", "@babel/helper-compilation-targets": "^7.29.7", "@babel/helper-module-transforms": "^7.29.7", "@babel/helpers": "^7.29.7", "@babel/parser": "^7.29.7", "@babel/template": "^7.29.7", "@babel/traverse": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/remapping": "^2.3.5", "convert-source-map": "^2.0.0", "debug": "^4.1.0", "gensync": "^1.0.0-beta.2", "json5": "^2.2.3", "semver": "^6.3.1" } }, "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA=="], "babel-dead-code-elimination/@babel/parser": ["@babel/parser@7.29.7", "", { "dependencies": { "@babel/types": "^7.29.7" }, "bin": "./bin/babel-parser.js" }, "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg=="], @@ -1719,18 +2175,26 @@ "cli-truncate/string-width": ["string-width@8.2.2", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg=="], + "cliui/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + + "cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="], + "conf/ajv-formats": ["ajv-formats@2.1.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-Wx0Kx52hxE7C18hkMEggYlEifqWZtYaRgouJor+WMdPnQyEK13vgEWyVNup7SoeeoLMsr4kf5h6dOW11I15MUA=="], "conf/json-schema-typed": ["json-schema-typed@7.0.3", "", {}, "sha512-7DE8mpG+/fVw+dTpjbxnx47TaMnDfOI1jwft9g1VybltZCduyRQPJPvc+zzKY9WPHxhPWczyFuYa6I8Mw4iU5A=="], "cross-spawn/which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="], + "dom-serializer/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], + "dot-prop/is-obj": ["is-obj@2.0.0", "", {}, "sha512-drqDG3cbczxxEJRoOXcOjtdp1J/lyp1mNn0xaznRs8+muBhgQcrnbspox5X5fOw0HnMnbfDzvnEMEtqDEJEo8w=="], "express/cookie": ["cookie@0.7.2", "", {}, "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w=="], "h3-v2/rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="], + "htmlparser2/entities": ["entities@4.5.0", "", {}, "sha512-V0hjH4dGPh9Ao5p0MoRY6BVqtwCjhz6vI5LT8AJ55H+4g9/4vbHx1I54fS0XuclLhDHArPQCiMjDxjaL8fPxhw=="], + "import-fresh/resolve-from": ["resolve-from@4.0.0", "", {}, "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g=="], "is-inside-container/is-docker": ["is-docker@3.0.0", "", { "bin": { "is-docker": "cli.js" } }, "sha512-eljcgEDlEns/7AXFosB5K/2nCM4P7FQPkGc/DWLy5rmFEWvZayGrik1d9/QIY5nJ4f9YsVvBkA6kJpHn9rISdQ=="], @@ -1777,6 +2241,8 @@ "string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + "to-regex-range/is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="], + "type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="], "wrap-ansi/string-width": ["string-width@8.2.2", "", { "dependencies": { "get-east-asian-width": "^1.5.0", "strip-ansi": "^7.1.2" } }, "sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg=="], @@ -1785,6 +2251,8 @@ "wsl-utils/is-wsl": ["is-wsl@3.1.1", "", { "dependencies": { "is-inside-container": "^1.0.0" } }, "sha512-e6rvdUCiQCAuumZslxRJWR/Doq4VpPR82kqclvcS0efgt430SlGIk05vdCN58+VrzgtIcfNODjozVielycD4Sw=="], + "yargs/string-width": ["string-width@4.2.3", "", { "dependencies": { "emoji-regex": "^8.0.0", "is-fullwidth-code-point": "^3.0.0", "strip-ansi": "^6.0.1" } }, "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g=="], + "@babel/helper-annotate-as-pure/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], "@babel/helper-annotate-as-pure/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], @@ -1885,6 +2353,12 @@ "@dotenvx/dotenvx/open/define-lazy-prop": ["define-lazy-prop@2.0.0", "", {}, "sha512-Ds09qNh8yw3khSjiJjiUInaGX9xlqZDY7JVryGxdxV7NPeuqQfplOpQ66yJFZut3jLa5zOwkXw1g9EI2uKh4Og=="], + "@lunora/cli/ts-morph/@ts-morph/common": ["@ts-morph/common@0.29.0", "", { "dependencies": { "minimatch": "^10.0.1", "path-browserify": "^1.0.1", "tinyglobby": "^0.2.14" } }, "sha512-35oUmphHbJvQ/+UTwFNme/t2p3FoKiGJ5auTjjpNTop2dyREspirjMy82PLSC1pnDJ8ah1GU98hwpVt64YXQsg=="], + + "@lunora/codegen/ts-morph/@ts-morph/common": ["@ts-morph/common@0.29.0", "", { "dependencies": { "minimatch": "^10.0.1", "path-browserify": "^1.0.1", "tinyglobby": "^0.2.14" } }, "sha512-35oUmphHbJvQ/+UTwFNme/t2p3FoKiGJ5auTjjpNTop2dyREspirjMy82PLSC1pnDJ8ah1GU98hwpVt64YXQsg=="], + + "@lunora/config/ts-morph/@ts-morph/common": ["@ts-morph/common@0.29.0", "", { "dependencies": { "minimatch": "^10.0.1", "path-browserify": "^1.0.1", "tinyglobby": "^0.2.14" } }, "sha512-35oUmphHbJvQ/+UTwFNme/t2p3FoKiGJ5auTjjpNTop2dyREspirjMy82PLSC1pnDJ8ah1GU98hwpVt64YXQsg=="], + "@manypkg/find-root/find-up/locate-path": ["locate-path@5.0.0", "", { "dependencies": { "p-locate": "^4.1.0" } }, "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g=="], "@sentry/bundler-plugins/@babel/core/@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], @@ -1979,6 +2453,18 @@ "@types/babel__traverse/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], + "@visulima/email/html-to-text/@selderee/plugin-htmlparser2": ["@selderee/plugin-htmlparser2@0.12.0", "", { "dependencies": { "domelementtype": "~2.3.0", "domhandler": "~5.0.3" }, "peerDependencies": { "selderee": "~0.12.0" } }, "sha512-oELmoyA6ML9jDRMV3kgcMQFKxUfBU0yFVn6yTctVaLT5ygXnxH52I3TZEgV9EhXJC68/uFvE5Daj1/25c0Xa/A=="], + + "@visulima/email/html-to-text/htmlparser2": ["htmlparser2@10.1.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.3", "domutils": "^3.2.2", "entities": "^7.0.1" } }, "sha512-VTZkM9GWRAtEpveh7MSF6SjjrpNVNNVJfFup7xTY3UpFtm67foy9HDVXneLtFVt4pMz5kZtgNcvCniNFb1hlEQ=="], + + "@visulima/email/html-to-text/selderee": ["selderee@0.12.0", "", { "dependencies": { "parseley": "~0.13.1" } }, "sha512-b1YMh3+DHZp59DLna3qVwQ5iOla/nrI6mLBNW02XxU77M3046Df6VLkoaJyFz20VsGIG5kkp+FK0kg4K4HnUFw=="], + + "@vue/compiler-core/@babel/parser/@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], + + "@vue/compiler-sfc/@babel/parser/@babel/types": ["@babel/types@7.29.7", "", { "dependencies": { "@babel/helper-string-parser": "^7.29.7", "@babel/helper-validator-identifier": "^7.29.7" } }, "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA=="], + + "@vue/compiler-sfc/postcss/nanoid": ["nanoid@3.3.16", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-bzlKTyNJ7+LdGIIwy8ijFpIqEQIvafahV7eYykJ8Cvh42EdJeODoJ6gUJXpQJvej1BddH8OqTXZNE/KfbWAu8Q=="], + "babel-dead-code-elimination/@babel/core/@babel/code-frame": ["@babel/code-frame@7.29.7", "", { "dependencies": { "@babel/helper-validator-identifier": "^7.29.7", "js-tokens": "^4.0.0", "picocolors": "^1.1.1" } }, "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw=="], "babel-dead-code-elimination/@babel/core/@babel/generator": ["@babel/generator@7.29.7", "", { "dependencies": { "@babel/parser": "^7.29.7", "@babel/types": "^7.29.7", "@jridgewell/gen-mapping": "^0.3.12", "@jridgewell/trace-mapping": "^0.3.28", "jsesc": "^3.0.2" } }, "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ=="], @@ -2009,6 +2495,12 @@ "cli-truncate/string-width/strip-ansi": ["strip-ansi@7.2.0", "", { "dependencies": { "ansi-regex": "^6.2.2" } }, "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w=="], + "cliui/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "cliui/string-width/is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], + + "cliui/wrap-ansi/ansi-styles": ["ansi-styles@4.3.0", "", { "dependencies": { "color-convert": "^2.0.1" } }, "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg=="], + "cross-spawn/which/isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="], "log-update/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], @@ -2049,6 +2541,10 @@ "wrap-ansi/strip-ansi/ansi-regex": ["ansi-regex@6.2.2", "", {}, "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg=="], + "yargs/string-width/emoji-regex": ["emoji-regex@8.0.0", "", {}, "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A=="], + + "yargs/string-width/is-fullwidth-code-point": ["is-fullwidth-code-point@3.0.0", "", {}, "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg=="], + "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], "@babel/helper-create-class-features-plugin/@babel/traverse/@babel/code-frame/js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], @@ -2127,6 +2623,16 @@ "@tanstack/start-plugin-core/@babel/core/@babel/traverse/@babel/helper-globals": ["@babel/helper-globals@7.29.7", "", {}, "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA=="], + "@visulima/email/html-to-text/selderee/parseley": ["parseley@0.13.1", "", { "dependencies": { "leac": "^0.7.0", "peberminta": "^0.10.0" } }, "sha512-uNBJZzmb60l6p6VWLTmevizNAGnE0xoSf1n0B4q3ntegDNzcS68NRCcBDZTcyXHxt2XhBChsCuqj4M+nChvE/A=="], + + "@vue/compiler-core/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], + + "@vue/compiler-core/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], + + "@vue/compiler-sfc/@babel/parser/@babel/types/@babel/helper-string-parser": ["@babel/helper-string-parser@7.29.7", "", {}, "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw=="], + + "@vue/compiler-sfc/@babel/parser/@babel/types/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], + "babel-dead-code-elimination/@babel/core/@babel/code-frame/@babel/helper-validator-identifier": ["@babel/helper-validator-identifier@7.29.7", "", {}, "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg=="], "babel-dead-code-elimination/@babel/core/@babel/code-frame/js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="], @@ -2169,6 +2675,10 @@ "@manypkg/find-root/find-up/locate-path/p-locate/p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="], + "@visulima/email/html-to-text/selderee/parseley/leac": ["leac@0.7.0", "", {}, "sha512-qMrZeyEekgdRQ9o6a4NAB2EQZrv827GJdn1vnapwSJ90hWRB4TzUSunvacPkxQ2TnNqHNI1/zSt0hlo0crG8Jw=="], + + "@visulima/email/html-to-text/selderee/parseley/peberminta": ["peberminta@0.10.0", "", {}, "sha512-80B2AsU+I4Qdb0ZAPSfe9UwvGzwkM37IKIFEvdS3D/3Ndgv2bsuJ0bfG1+iEYO+l7Gfd4EUJmuRyq7efLgRMzQ=="], + "pkg-up/find-up/locate-path/p-locate/p-limit": ["p-limit@2.3.0", "", { "dependencies": { "p-try": "^2.0.0" } }, "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w=="], } } diff --git a/docs/adr/0008-sync-via-a-per-user-durable-object.md b/docs/adr/0008-sync-via-a-per-user-durable-object.md index b090be7e..50ad47c1 100644 --- a/docs/adr/0008-sync-via-a-per-user-durable-object.md +++ b/docs/adr/0008-sync-via-a-per-user-durable-object.md @@ -45,17 +45,13 @@ elsewhere) — off-goal for an all-Cloudflare deploy. engine that lands on this same design — "the DO _is_ the log" (an append-only changelog written in the write's own storage transaction), the DO is the WebSocket fan-out, hibernation makes idle sockets ~free, and the client runs the dataflow via TanStack DB while the DO ships row-ops rather -than re-running queries. Useful outside validation of ADR 0008/0009; two deliberate divergences -worth recording: (1) Lunora runs the write logic **authoritatively in the DO** (client keeps an -optional optimistic twin); we ship pre-computed `{ops}` from the client's `tree.ts` and validate -their _shape_ at the trust boundary ([ADR 0014](./0014-validate-the-worker-do-trust-boundary.md)) -instead. We keep client-planned ops on purpose — single-writer-per-DO removes the concurrent-writer -conflicts that authoritative re-run buys, and the MCP path already re-plans server-side via the -shared `tree.ts` (`worker/outline-ops.ts`). (2) Lunora's **"shape = read-as-permission"** (the -client picks the partition, the server's `where` AND-composed with a row-level-security predicate -through one WHERE compiler picks the rows) is the pattern to reach for **when subtree sharing -lands** — partial replication and authorization as one mechanism, not a filter bolted next to an -auth check. Irrelevant today (one user = one DO = the whole outline), noted for the sharing seam. +than re-running queries. **Cutover decision:** [ADR 0055](./0055-lunora-replaces-custom-outline-sync.md) +adopts Lunora for outline sync and **supersedes divergence #1 below** (we no longer keep +client-precomputed `{ops}` as the long-term write model). Historical note of the pre-cutover +divergences: (1) ~~Lunora runs the write logic authoritatively in the DO; we shipped pre-computed +`{ops}` from the client's `tree.ts`~~ → superseded by ADR 0055 (authoritative mutators + shared +`plan*`). (2) Lunora's **"shape = read-as-permission"** remains the pattern for **when subtree +sharing lands** — still deferred; irrelevant while one user = one shard = the whole outline. **The SPA / no-SSR constraint lives here too:** the React app is a pure static SPA — never open the sync socket or touch `nodesCollection` during a server/render pass (`collection.ts` guards with diff --git a/docs/adr/0030-mobile-actions-bar.md b/docs/adr/0030-mobile-actions-bar.md index 3e7ca590..6f32f0d0 100644 --- a/docs/adr/0030-mobile-actions-bar.md +++ b/docs/adr/0030-mobile-actions-bar.md @@ -22,14 +22,51 @@ behaviors, and keeping them separate is what makes the bar robust: state) and hides on blur. This is not cosmetic: it guarantees every button has a valid target by construction — `findFocusedId()` is non-null whenever the bar is visible, so each zero-arg action can resolve the node it operates on with no ambiguity and no "nothing selected" state to design around. -- **Position = visual viewport.** A `useKeyboardViewport` hook reads `window.visualViewport` (rAF-throttled) - and translates the bar up by `innerHeight - (visualViewport.height + visualViewport.offsetTop)` so it rides - above the software keyboard. When the viewport isn't shrunk (hardware keyboard / iPad) that gap is 0 and the - bar falls back to `bottom:0` + `env(safe-area-inset-bottom)`. +- **Position = a measured anchor.** One CSS custom property, `--kb-inset`, written on `` by + `data/keyboard-inset.ts` from a zero-size `position: fixed; bottom: 0` probe (`styles.css` holds the `0px` + default). The bar stays `bottom: 0` and lifts by `calc(-1 * var(--kb-inset))`; its safe-area pad SUBTRACTS the + same inset, because a raised keyboard already covers the home indicator. Both declarations are branchless, and + the keyboard animation costs zero React re-renders. -**Why pure `visualViewport`, not `env(keyboard-inset-*)`.** The `env(keyboard-inset-*)` CSS environment -variables are Chromium-only; iOS Safari (the primary target) needs the JS `visualViewport` path regardless. -One system that covers both beats two half-systems, so the bar tracks the keyboard entirely in JS. +**Amended 2026-07-24: the lift cannot be computed from any live viewport property.** This ADR originally +specified `innerHeight - (visualViewport.height + visualViewport.offsetTop)`, computed in a `useKeyboardViewport` +hook. That shipped, dogfooded fine, and was wrong. Three candidate replacements were measured on device, in +order, and each was also wrong: + +1. **`window.innerHeight` is not a stable quantity on iOS Safari.** In one simulator session, one page, one + keyboard, it read **714, 635 and 279** as the page scrolled and the keyboard animated, silently switching + between describing the layout viewport and the visual one. At the bottom of a long page it collapses to + equal `visualViewport.height`, which reduces the whole expression to `-offsetTop`: always negative, always + clamped to zero, so the bar never lifted. That is the bug users hit, and it is bottom-of-page specific + because that is where the collapse happens. +2. **`documentElement.clientHeight` is not the answer either.** It looked like one — it held 714 across every + simulator sample while `innerHeight` thrashed — but on a physical iPhone the same instant read + `innerHeight` **526**, `clientHeight` **498**, and a true pre-keyboard band bottom of **590**. Three + different answers, and the one that matters is not readable after the keyboard has already opened. +3. **The VirtualKeyboard API's per-focus baseline is also not the answer.** Tried next, via + [`virtual-keyboard-api-polyfill`](https://github.com/cameronapak/polyfill-virtual-keyboard-api), whose SPEC + rule 2 captures the visible band at `focusin` and computes + `remainder = max(0, baselineBottom - vv.height - vv.offsetTop)`. Correct in principle and it committed + sane-looking values — but its baseline (590) is not the box `bottom: 0` resolves against (498), so it + over-lifted by exactly that 92px difference. Safari's chrome sits between the two. + +The reason all three fail is the same, and it is the finding worth keeping: **iOS Safari moves the box that +`position: fixed; bottom: 0` resolves against, and no property reliably names it.** Across two samples in one +keyboard session, `innerHeight` read 526 then **482** while `clientHeight` stayed 498 and the pre-keyboard band +stayed 590 — nothing else changed. That is why the bar was fine "for the most part" and then suddenly was not: +each formula is correct only while the chrome sits where that formula assumed. + +So the anchor is **measured, not computed**. `data/keyboard-inset.ts` appends a zero-size +`position: fixed; bottom: 0` probe and reads its `getBoundingClientRect().bottom`, which is where `bottom: 0` +lands by definition, with no model in between; a client rect is reported in the same space as +`visualViewport.height`, so the lift is their difference. Fed the two samples above it yields the correct 228 in +both, even though the anchor itself measured 418 and 390. Chrome drift is absorbed rather than modelled. + +**Why not `env(keyboard-inset-*)` even with a polyfill.** The original rejection was "Chromium-only, and iOS +needs the JS path anyway". A polyfill does close the engine gap, so that premise expired — but the API answers +a different question than we are asking. It reports the keyboard's occlusion of the _visible band_; we need the +distance from _our fixed anchor_, and on a page with browser chrome those differ. The name `--kb-inset` is kept +because it is what consumers mean, but the value is ours. **Why we blend with iOS's keyboard accessory bar rather than remove it.** On iOS Safari there is **no web API** to hide or reorder the system keyboard accessory bar (the floating pill with the prev/next-field arrows + a @@ -87,7 +124,16 @@ API first. check — dropping it de-duplicates and simplifies the control set. - **Width breakpoint instead of pointer type.** Would show the bar to a desktop user in a narrow window and hide it on a large tablet — the wrong axis. Pointer type is the finger signal. -- **`env(keyboard-inset-*)` for positioning.** Chromium-only; iOS needs the JS path anyway (see above). +- **Computing the lift from a viewport property.** Four attempts, all measured on device, all wrong the same + way — the anchor moves and the formula does not. Do not re-derive any of these: + - **`innerHeight`.** Shipped for a year. Not a stable quantity on iOS; collapses to `visualViewport.height` + at the bottom of a long page, which zeroes the lift entirely. This was the reported bug. + - **`clientHeight`.** The obvious correction, and stable across every simulator sample — but 92px off the + real anchor on a physical iPhone. + - **The VirtualKeyboard API baseline** (native `env(keyboard-inset-*)` or the polyfill). Answers a different + question: the keyboard's occlusion of the visible band, not the distance from our fixed anchor. + - **Zero lift (`bottom: 0` alone),** on the theory that Safari already resolves `bottom` against the visible + band. It does not; the bar landed at 589 against a band of 377. - **True `/` toggle.** Needs cross-component menu-state observation for a marginal gain over insert-and-open. - **Per-node reactive button state (enable/disable, checked).** Re-fights the ADR 0014 per-node render budget; row-level feedback already tells the user what happened. diff --git a/docs/adr/0051-self-serve-account-deletion.md b/docs/adr/0051-self-serve-account-deletion.md index f94b5326..752aa1f4 100644 --- a/docs/adr/0051-self-serve-account-deletion.md +++ b/docs/adr/0051-self-serve-account-deletion.md @@ -11,7 +11,8 @@ Server-side, Better Auth's built-in `user.deleteUser` owns the lifecycle; we han - **`beforeDelete(user)`** — runs while the account still exists, in this order: 1. **Owner guard.** Refuse the `OWNER_USER_ID` account (`isOwnerAccount`). It maps to the constant `'default'` DO (the owner-continuity bridge, ADR 0011) holding pre-auth/shared data — wiping that is an operator decision, not a button. A `throw` here aborts with nothing destroyed. 2. **Cancel Stripe and clear the D1 `subscription` rows** (`cancelActiveSubscriptions`) — cancel immediately, **throw on failure** so the whole deletion aborts (the crux, below), then delete the rows for `referenceId = user.id`. The row delete lives HERE, not in the best-effort `afterDelete` sweep: Better Auth's `deleteUser` does not cascade the Stripe plugin's table, and a failed `afterDelete` would orphan the entitlement record. It runs unconditionally — a comped user (operator-inserted active row, no Stripe ids) and a free user (no row) both skip the Stripe call and just clear D1. - 3. **Wipe the outline DO** — `stub.wipe()` → `ctx.storage.deleteAll()`, which on a SQLite-backed DO erases both the SQL tables and the KV storage atomically. The stub is resolved from the authenticated `user.id` (never client input — the ADR 0014 trust boundary), and it also closes any live sync sockets. + 3. **Wipe the classic outline DO** — `stub.wipe()` on `USER_OUTLINE` keyed by `user.id` (never client input — the ADR 0014 trust boundary); closes live sync sockets and atomically erases SQL + KV via `deleteAll()`. + 4. **Wipe the Lunora shard** (ADR 0055) — `wipeLunoraUserShard(env, user.id)` via trusted system RPC on `env.SHARD`, keyed by the same Better Auth `user.id` the browser/MCP mutators use (**not** `resolveUserId` / `'default'`). Throws on failure like the DO wipe — deletion aborts before identity rows vanish. - **`afterDelete(user)`** — the identity rows are gone; clean up the rows core deletion doesn't (`deleteResidualUserRows`): the mcp OAuth rows (they cascade, but deleting by `userId` is idempotent belt-and-suspenders) and the email-keyed `waitlist` (0005) + `invites` (0007) rows — both carry PII (the address) that the erasure promise covers, deleted under the same `normalizeEmail` their inserts used. Best-effort AND non-fatal (wrapped, logged): any leftover is unreachable, so it never fails an already-done deletion. ## The two decisions worth recording @@ -34,7 +35,7 @@ Two grilled items consciously **not built**: ## Consequences / rejected -- **DO wipe in `beforeDelete`, not `afterDelete`.** If the core user-row delete then failed, we'd have wiped a still-alive account's outline — recoverable (they're signed in; the outline re-seeds). The inverse (wipe in `afterDelete`, fails) orphans data we _promised_ to delete — a privacy regression. So the irreversible wipe goes last-in-`beforeDelete`, after Stripe has committed. +- **DO wipe in `beforeDelete`, not `afterDelete`.** If the core user-row delete then failed, we'd have wiped a still-alive account's outline — recoverable (they're signed in; the outline re-seeds). The inverse (wipe in `afterDelete`, fails) orphans data we _promised_ to delete — a privacy regression. So the irreversible wipe goes last-in-`beforeDelete`, after Stripe has committed — classic `USER_OUTLINE` then Lunora `SHARD` (ADR 0055), both keyed by `user.id`. - **"Deleted" is honest about the 30-day PITR floor.** Durable Objects carry automatic 30-day Point-in-Time Recovery: `deleteAll()` removes the outline from every live path immediately, but the operator retains a recoverable backup for up to 30 days. The confirmation dialog says so in one line ("removed from the app right away; automatic backups are purged within 30 days") — disclosure, not a user-facing undo; a PITR restore is a manual operator support action, and the accidental-delete safety net in lieu of a product undo window (deferred). - **Refunds are decoupled.** Deletion cancels immediately, never auto-refunds; the ToS's 14-day window stays a manual support action. - **Not e2e-tested.** `seedOutline` mocks `/api/auth`, so the real deleteUser path is unreachable in Playwright; the owner guard, the billable-status sweep, and the residual-row scrub are unit-tested (`worker/account-deletion.test.ts`) and the full flow is verified by hand against the dev loop. diff --git a/docs/adr/0055-lunora-replaces-custom-outline-sync.md b/docs/adr/0055-lunora-replaces-custom-outline-sync.md new file mode 100644 index 00000000..c0a93f75 --- /dev/null +++ b/docs/adr/0055-lunora-replaces-custom-outline-sync.md @@ -0,0 +1,39 @@ +# Lunora replaces custom outline sync + +Dotflowy’s hand-rolled per-user DO sync (`/api/sync` + client-planned `{ops}` batches) converges on the same shape Lunora already ships — DO-as-log, poke fan-out, TanStack DB client, watermarked optimistic mutators ([ADR 0008](./0008-sync-via-a-per-user-durable-object.md)). We **cut over to Lunora** for outline storage/sync so Cam maintains product/UX, not a second sync engine. A prior greenfield spike proved ADR 0009’s chain invariant, live multi-tab convergence, watermark hold, shard deny, and hard-reload seed before the production port. + +**Decision.** Outline nodes (and, in follow-on slices, kv side-collections) move onto Lunora: `defineTable` + `.shardBy("userId")`, `defineShape` (`wholeOutline` / later partitions), server-authoritative `defineMutator` with shared pure `plan*` twins on the client (`@lunora/db` + checkpoints). Dotflowy keeps editor, plugins, domain MCP tool names (thin `/mcp` → mutators — [ADR 0026](./0026-agent-native-mcp-server.md) Option A), and existing non-outline HTTP (unfurl, waitlist, admin, Stripe, Better Auth identity) remounted beside Lunora’s Worker compose. + +**This supersedes ADR 0008’s deliberate divergence #1** (client-precomputed `{ops}` validated only for shape). Authoritative mutators + shared planners are the trust boundary now; ADR 0009’s P1/P2/P3 become Lunora’s atomic mutator writes + watermark overlay + clientSeq FIFO. Divergence #2 (shape = read-as-permission) stays the future sharing seam. + +## Cutover constraints + +- **One system at the end.** Dual-run is a temporary bridge only — not a permanent two-backend mode. +- **No PR to `main` until** the app speaks Lunora for outline sync **and** pre-existing gates are green: `typecheck` / `typecheck:worker` / `typecheck:test` / `lint` / `test` / local Playwright e2e (`test:e2e` with workers=2 clean-signal). Spike-only PRs are not the goal. +- **Data:** one-shot snapshot migrate per-user DO → Lunora shard (export existing outline → `restoreSnapshot`-class import, or Lunora-native seed). Owner `'default'` bridge continuity preserved via `userId` shard key (never email — ADR 0008). +- **Planners stay pure and shared** (`tree.ts` / sibling-chain / `outline-ops` lineage) so MCP, mutators, and any remaining client optimism cannot drift. + +## Considered options + +| Option | Why not | +| ---------------------------------------------------------------------------- | -------------------------------------------------------------------------- | +| Keep custom `{ops}` forever; only “look at” Lunora | Defeats the maintenance goal; ADR 0008 already named Lunora as convergent. | +| Dual-run in production indefinitely | Two engines, two failure modes; cutover forever deferred. | +| Big-bang rewrite in one commit | Editor + e2e + MCP + backups all break together; no incremental proof. | +| Replace Better Auth / Stripe / unfurl with Lunora primitives in the same cut | Out of scope — remount HTTP; don’t re-litigate identity/billing. | + +## Identity / e2e / kv (locked) + +- **Identity:** product Better Auth stays the session authority (MCP OAuth, Stripe, invite/Turnstile). Lunora `resolveIdentity` reads that session — do **not** run a second `@lunora/auth` signup stack in the main app. +- **e2e:** dual-path fixtures — `seedOutline` forces `lunora-sync=off` (classic `/api/sync` mock); `seedOutlineLunora` / `E2E_LUNORA=1` forces ON (`/_lunora/*` mock). **Production defaults OFF** — classic DO is the default for browser and MCP until the user opts in via Settings (`account-prefs` / `lunora-beta`, synced across devices). Local dogfood can force ON with `LUNORA_OUTLINE=1` (Worker MCP) and `?lunora-sync=on` or localStorage (browser). +- **Kill-switch pairing:** the browser reads `isLunoraSyncEnabled()` (`dotflowy:flag:lunora-sync`, mirrored from synced `account-prefs` on load); Worker MCP reads env force first, else the same preference on classic DO (`isLunoraOutlineEnabledForUser`). For local debugging divergence, flip env + client together (`LUNORA_OUTLINE=0` **and** `lunora-sync=off`, or force both ON). +- **KV side-collections:** phase **2b** after nodes sync is on Lunora — do not block the collection swap on tag-colors/daily-index/saved-queries. + +## Sequence (implementation order) + +1. Spike Phase 0–1 (done): prove mutators/shapes/watermark/bridge/`seedIfEmpty`. +2. ADR (this file) + lift shared planners toward one `src/` core consumed by Worker MCP and Lunora mutators. +3. Integrate Lunora into the main Vite/Worker app on this branch (compose Worker; keep non-outline routes). +4. Swap `nodesCollection` custom sync → `@lunora/db` shape collections; structural path → `bindMutators` (field edits stay direct-style mutators without structural batching). +5. Migrate kv side-collections; remount MCP onto mutators; snapshot-migrate user data; delete `UserOutlineDO` custom changelog sync. +6. Make all pre-existing tests pass; only then open the PR. diff --git a/e2e/atomic-structural-writes.spec.ts b/e2e/atomic-structural-writes.spec.ts index ccde2dcb..70504b67 100644 --- a/e2e/atomic-structural-writes.spec.ts +++ b/e2e/atomic-structural-writes.spec.ts @@ -1,6 +1,11 @@ import { expect, test, type Page } from "@playwright/test"; -import { seedOutline, STANDARD_TREE, type SeedNode } from "./fixtures"; +import { + seedOutline, + STANDARD_TREE, + isE2eLunora, + type SeedNode, +} from "./fixtures"; // Regression suite for the atomic-structural-writes cure (PLAN.md): // - P1: one structural edit = exactly ONE /api/nodes request carrying every op. @@ -99,6 +104,11 @@ function applyWrites(seed: SeedNode[], writes: NodesWrite[]): SeedNode[] { } test.describe("atomic structural writes", () => { + test.skip( + isE2eLunora(), + "asserts classic /api/nodes batch wire; Lunora uses /_lunora/rpc", + ); + test("a structural edit is exactly one /api/nodes batch request (P1)", async ({ page, }) => { diff --git a/e2e/changelog.spec.ts b/e2e/changelog.spec.ts index f0da7679..a14db76a 100644 --- a/e2e/changelog.spec.ts +++ b/e2e/changelog.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; import { readFileSync } from "node:fs"; -import { seedOutline, STANDARD_TREE } from "./fixtures"; +import { isE2eLunora, seedOutline, STANDARD_TREE } from "./fixtures"; /** * The changelog (ADR 0046): a "What's new" dialog reached from the More menu and @@ -88,6 +88,10 @@ test.describe("changelog", () => { test("a caught-up account shows no badge, and does not re-seed", async ({ page, }) => { + test.skip( + isE2eLunora(), + "seeds the cursor through the classic /api/kv mock", + ); const writes = await load(page, cursor(LATEST)); // Open + close the More menu so the header has demonstrably settled: "not @@ -124,6 +128,10 @@ test.describe("changelog", () => { test("opening it advances the cursor to the latest release", async ({ page, }) => { + test.skip( + isE2eLunora(), + "asserts cursor writes through the classic /api/kv mock", + ); // A cursor this build has never heard of: no badge (an unknown version stays // quiet) and no silent seed (a row already exists) -- so the only write that // can happen is the one the dialog itself makes. diff --git a/e2e/daily-notes.spec.ts b/e2e/daily-notes.spec.ts index 8393f622..d18d2528 100644 --- a/e2e/daily-notes.spec.ts +++ b/e2e/daily-notes.spec.ts @@ -9,7 +9,12 @@ import { weekLabel, yearLabel, } from "../src/data/date-links"; -import { seedOutline, STANDARD_TREE, type SeedNode } from "./fixtures"; +import { + seedOutline, + STANDARD_TREE, + isE2eLunora, + type SeedNode, +} from "./fixtures"; // Cmd on macOS, Control elsewhere. function modifier() { @@ -538,6 +543,12 @@ test.describe("daily notes", () => { test("a lost claim adopts the winner's note (no duplicate on a race)", async ({ page, }) => { + // Classic-only: fakes a stale `/api/kv` replica + `?op=claim` winner ack. + // Lunora delivers daily-index via shapes (no empty-GET + claim override). + test.skip( + isE2eLunora(), + "claim-race simulation is classic /api/kv transport", + ); // Simulate the race: this device's local daily-index replica is empty (it // GETs an empty /api/kv below), so it thinks today is absent and CLAIMS -- // but another device already created the container + today's note, so the @@ -621,7 +632,9 @@ test.describe("daily notes", () => { }) => { // daily-index points at ids with no matching outline rows (stale mapping). // Today must create those nodes under the claimed ids, not show the - // "That bullet doesn't exist" empty state. + // "That bullet doesn't exist" empty state. Seed via `kv` so both classic + // `/api/kv` and Lunora `userDailyIndex` shapes see the orphans (a post-seed + // `/api/kv` route override is classic-only). const d = new Date(); const todayKey = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart( 2, @@ -632,55 +645,20 @@ test.describe("daily notes", () => { [todayKey]: "ghost-today", }; - await seedOutline(page, STANDARD_TREE); - - const kvStore = new Map([ - ["container", { key: "container", nodeId: orphans.container }], - [todayKey, { key: todayKey, nodeId: orphans[todayKey] }], - ]); - - await page.route( - (url) => url.pathname === "/api/kv", - async (route) => { - const req = route.request(); - const collection = new URL(req.url()).searchParams.get("collection"); - if (collection !== "daily-index") return route.fallback(); - - switch (req.method()) { - case "GET": - return route.fulfill({ - status: 200, - contentType: "application/json", - body: JSON.stringify([...kvStore.values()]), - }); - case "POST": { - if (new URL(req.url()).searchParams.get("op") === "claim") { - const { key, value } = req.postDataJSON() as { - key: string; - value: { key: string; nodeId: string }; - }; - if (!kvStore.has(key)) kvStore.set(key, value); - return route.fulfill({ - status: 200, - contentType: "application/json", - body: JSON.stringify({ value: kvStore.get(key) }), - }); - } - const { rows } = req.postDataJSON() as { - rows: { key: string; value: { key: string; nodeId: string } }[]; - }; - for (const r of rows ?? []) kvStore.set(r.key, r.value); - return route.fulfill({ - status: 200, - contentType: "application/json", - body: JSON.stringify({ ok: true }), - }); - } - default: - return route.fallback(); - } + await seedOutline(page, STANDARD_TREE, { + kv: { + "daily-index": [ + { + key: "container", + value: { key: "container", nodeId: orphans.container }, + }, + { + key: todayKey, + value: { key: todayKey, nodeId: orphans[todayKey] }, + }, + ], }, - ); + }); await page.goto("/"); await expect( diff --git a/e2e/delete-confirm.spec.ts b/e2e/delete-confirm.spec.ts index 94246a48..e37d8013 100644 --- a/e2e/delete-confirm.spec.ts +++ b/e2e/delete-confirm.spec.ts @@ -6,7 +6,13 @@ // unchanged. One Cmd+Z restores the whole subtree either way. import { expect, test, type Page } from "@playwright/test"; -import { seedOutline, STANDARD_TREE, type SeedNode } from "./fixtures"; +import { + openSeededOutline, + seedOutline, + STANDARD_TREE, + waitForSeededNode, + type SeedNode, +} from "./fixtures"; const text = (page: Page, id: string) => page.locator(`li[data-node-id="${id}"] > .outline-row .node-text`); @@ -36,7 +42,7 @@ function bigSeed(n: number): SeedNode[] { test.describe("big-delete confirmation", () => { test("a small delete never asks (regression)", async ({ page }) => { await seedOutline(page, STANDARD_TREE); - await page.goto("/"); + await openSeededOutline(page, { anchorId: "alpha" }); await expect(text(page, "alpha")).toBeVisible(); // alpha's subtree is 3 nodes (< 30): deleted inline, no dialog. @@ -50,7 +56,7 @@ test.describe("big-delete confirmation", () => { page, }) => { await seedOutline(page, bigSeed(40)); // 41-node subtree >= 30 - await page.goto("/"); + await openSeededOutline(page, { anchorId: "big" }); await expect(text(page, "big")).toBeVisible(); await text(page, "big").click(); @@ -64,6 +70,7 @@ test.describe("big-delete confirmation", () => { // Nothing was deleted — and a reload agrees. await expect(text(page, "big")).toBeVisible(); await page.reload(); + await waitForSeededNode(page, "big"); await expect(text(page, "big")).toBeVisible(); }); @@ -71,7 +78,7 @@ test.describe("big-delete confirmation", () => { page, }) => { await seedOutline(page, bigSeed(40)); - await page.goto("/"); + await openSeededOutline(page, { anchorId: "big" }); await expect(text(page, "big")).toBeVisible(); await text(page, "big").click(); @@ -83,6 +90,7 @@ test.describe("big-delete confirmation", () => { await expect(text(page, "charlie")).toBeVisible(); // Persisted through the (mock) server store. await page.reload(); + await waitForSeededNode(page, "alpha"); await expect(text(page, "alpha")).toBeVisible(); await expect(page.locator('li[data-node-id="big"]')).toHaveCount(0); @@ -106,7 +114,7 @@ test.describe("big-delete confirmation", () => { // Delay the batch POST response so the dialog rests in its post-apply // "saving" phase — proof every slice applied while ONE batch is in flight. await seedOutline(page, bigSeed(600), { postDelayMs: 600 }); - await page.goto("/"); + await openSeededOutline(page, { anchorId: "big" }); await expect(text(page, "big")).toBeVisible(); await text(page, "big").click(); @@ -123,6 +131,7 @@ test.describe("big-delete confirmation", () => { await expect(page.getByTestId("delete-confirm-dialog")).toHaveCount(0); await expect(page.locator('li[data-node-id="big"]')).toHaveCount(0); await page.reload(); + await waitForSeededNode(page, "alpha"); await expect(text(page, "alpha")).toBeVisible(); await expect(page.locator('li[data-node-id="big"]')).toHaveCount(0); }); @@ -131,7 +140,7 @@ test.describe("big-delete confirmation", () => { page, }) => { await seedOutline(page, bigSeed(40)); - await page.goto("/"); + await openSeededOutline(page, { anchorId: "big" }); await expect(text(page, "big")).toBeVisible(); // Enter node selection on the big parent (Shift+Down selects the focused diff --git a/e2e/drag-filtered.spec.ts b/e2e/drag-filtered.spec.ts index d5d09688..e3b4a102 100644 --- a/e2e/drag-filtered.spec.ts +++ b/e2e/drag-filtered.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; -import { seedOutline, type SeedNode } from "./fixtures"; +import { isE2eLunora, seedOutline, type SeedNode } from "./fixtures"; // Drag-reorder while a ?q= filter is active (issue #244 / the ADR 0047 // amendment). Before the fix, buildRows passed `filter: null`, so the drag's @@ -57,6 +57,7 @@ test.describe("drag reorder under an active ?q= filter (#244)", () => { test("a drop between two visible rows with hidden siblings lands after the visible predecessor", async ({ page, }) => { + test.skip(isE2eLunora(), "awaits the classic /api/nodes structural POST"); // Real top-level order: S1, S2, V1, H1, H2, V2, X. Under #go the untagged // H1/H2 are pruned, leaving S1, S2, V1, V2, X. The S1/S2 spacers keep the // target V1/V2 gap well below the top-edge auto-scroll band so the drop @@ -120,6 +121,7 @@ test.describe("drag reorder under an active ?q= filter (#244)", () => { test("a drop that lands the node hidden discloses with a toast and the node vanishes from the filtered view", async ({ page, }) => { + test.skip(isE2eLunora(), "awaits the classic /api/nodes structural POST"); // Rendered under #go: A (match), C (A's child -- revealed match-descendant, // undimmed, NOT a match), P (dimmed context ancestor of K), K (match). const tree: SeedNode[] = [ diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts index a46aadb2..f494542d 100644 --- a/e2e/fixtures.ts +++ b/e2e/fixtures.ts @@ -1,5 +1,72 @@ import type { Page, Route, WebSocketRoute } from "@playwright/test"; +import { + applyPlan, + buildTreeIndex, + planAppendChild, + planImportNodes, + planIndent, + planIndentMany, + planInsertChildAtStart, + planInsertSibling, + planMaterializeDailyNodes, + planMirrorNode, + planMoveMany, + planMoveNode, + planOutdent, + planOutdentMany, + planRemoveMany, + planRemoveNode, + planRestoreNodes, + planSetBookmarkedAt, + planSetCollapsed, + planSetCompleted, + planSetIsTask, + planSetKind, + planSetText, + planSplitNode, + type OutlineNode, + type OutlinePlan, +} from "../src/data/outline-plans"; +import { resolveDailyClaim } from "../src/plugins/daily/claim-mapping"; + +/** True when this Playwright process targets the Lunora mock (`E2E_LUNORA=1` + * or `seedOutline(..., { lunora: true })`). Specs that override classic + * `/api/kv?op=claim` should skip under Lunora — shapes/mutators replace that + * transport. */ +export function isE2eLunora(opts?: { lunora?: boolean }): boolean { + if (opts?.lunora === true) return true; + if (opts?.lunora === false) return false; + const env = process.env.E2E_LUNORA; + return env === "1" || env === "true"; +} + +/** Opt classic specs onto the Lunora mock: `seedOutline(..., { lunora: true })` + * or `E2E_LUNORA=1 bunx playwright test …`. Default stays classic (`/api/sync`). */ +function wantsLunoraSeed(opts: { lunora?: boolean } | undefined): boolean { + return isE2eLunora(opts); +} + +/** Lunora shape pokes can land after `goto`; wait for a seeded row. No-op classic. */ +export async function waitForSeededNode( + page: Page, + nodeId: string, +): Promise { + if (!isE2eLunora()) return; + await page + .locator(`li[data-node-id="${nodeId}"]`) + .waitFor({ state: "attached", timeout: 15_000 }); +} + +/** `page.goto` + Lunora hydration wait on a known seeded id. */ +export async function openSeededOutline( + page: Page, + opts: { path?: string; anchorId?: string } = {}, +): Promise { + await page.goto(opts.path ?? "/"); + await waitForSeededNode(page, opts.anchorId ?? "alpha"); +} + // A node as the test author cares about it -- structural fields only. Everything // the schema also requires (isTask/completed/collapsed/timestamps) is filled in // with inert defaults by seedOutline so each test only states what matters. @@ -87,6 +154,15 @@ function toNode(n: SeedNode): ApiNode { * The store is scoped to this test's `page`. Playwright gives each test its own * page/context, so two tests never share state. Register before `page.goto(...)` * (every spec does) so the collection's first sync is mocked. + * + * Dual-path: pass `{ lunora: true }` or set `E2E_LUNORA=1` to route through + * `seedOutlineLunora` (flag ON + `/_lunora/*` mock). The classic path sets + * `dotflowy:flag:lunora-sync=off` so specs stay on `/api/sync` even though + * the product default is ON. Classic-only opts (`echoDelayMs`, `echoChunks`, + * `postDelayMs`, `failStructuralWrites`, `serverVersion`) are ignored on the + * Lunora path — those specs stay classic-only. Lunora-only opts + * (`suppressWholeOutlinePoke`, `failMutatorWrites`) live on + * `seedOutlineLunora` directly. */ export async function seedOutline( page: Page, @@ -118,8 +194,20 @@ export async function seedOutline( * (not a transport error), so the client's retry policy doesn't kick in — * the failure lands immediately. */ failStructuralWrites?: boolean; + /** When true, use the Lunora `/_lunora/*` mock + enable the client flag. + * Also enabled by `E2E_LUNORA=1` / `true` when this is unset. */ + lunora?: boolean; } = {}, ): Promise { + if (wantsLunoraSeed(opts)) { + return seedOutlineLunora(page, nodes, { kv: opts.kv }); + } + + // Product default is Lunora ON; classic e2e mocks `/api/sync` only. + await page.addInitScript(() => { + window.localStorage.setItem("dotflowy:flag:lunora-sync", "off"); + }); + const echoDelayMs = opts.echoDelayMs ?? 0; // Delay only the structural-batch POST *response* (not its echo). Opens a // window to prove the client serializes batches: a second batch must not be @@ -373,3 +461,634 @@ export const STANDARD_TREE: SeedNode[] = [ text: "Alpha two", }, ]; + +// --- Lunora flag-ON fixture (ADR 0055) -------------------------------------- + +type LunoraRow = ApiNode & { userId: string; _id: string }; + +function toLunoraRow(n: SeedNode, userId: string): LunoraRow { + const base = toNode(n); + return { ...base, _id: base.id, userId }; +} + +function rowToOutline(row: LunoraRow): OutlineNode { + const { _id: _, ...rest } = row; + return rest; +} + +function outlineToRow(node: OutlineNode): LunoraRow { + return { ...node, _id: node.id }; +} + +function commitOutlinePlan( + store: Map, + plan: OutlinePlan | null | undefined, +): void { + if (!plan) return; + const next = applyPlan([...store.values()].map(rowToOutline), plan); + store.clear(); + for (const n of next) store.set(n.id, outlineToRow(n)); +} + +type DailyIndexRow = { + _id: string; + key: string; + nodeId: string; + touchedAt: number; + userId: string; +}; + +type TagColorRow = { + _id: string; + tag: string; + color: string; + userId: string; +}; + +type SavedQueryRow = { + _id: string; + name: string; + query: string; + createdAt: number; + userId: string; +}; + +/** + * Seed an outline on the Lunora flag-ON path by mocking `/_lunora/ws` + + * `/_lunora/rpc`. Structural mutators apply the same `outline-plans` pure + * planners as production (insert/split/indent/delete/restore/move/multi/…). + * + * Also reachable via `seedOutline(..., { lunora: true })` or `E2E_LUNORA=1` + * so classic specs can run against Lunora without rewriting call sites. + * Auto-migrate is skipped by mocking GET `/api/nodes` → []. + */ +export async function seedOutlineLunora( + page: Page, + nodes: SeedNode[], + opts: { + userId?: string; + /** Pre-seed Lunora kv shapes from classic kv collection names + * (`daily-index` / `tag-colors` / `saved-queries`). */ + kv?: Record; + /** + * Skip post-mutation `wholeOutline` WS pokes (RPC still mutates the mock + * store). Reproduces a missed shape poke so the client hits the ~3s + * checkpoint fallback — pins the sticky-optimistic typing fix. + */ + suppressWholeOutlinePoke?: boolean; + /** + * Fail every `mutators:*` RPC with 500 before mutating the store — + * Lunora twin of classic `failStructuralWrites` (save-failure rollback). + */ + failMutatorWrites?: boolean; + } = {}, +): Promise { + // Drop prior Lunora mocks from earlier tests on this page — stacked + // `routeWebSocket` handlers can keep an old in-memory store alive across + // reload (delete "persists" then resurrects from the stale mock). + await page.unroute("**/_lunora/**"); + await page.unroute("**/api/auth/get-session"); + await page.unroute("**/api/nodes"); + await page.unroute("**/api/kv"); + + const userId = opts.userId ?? "test-user"; + const store = new Map(); + for (const n of nodes) store.set(n.id, toLunoraRow(n, userId)); + + const dailyIndex = new Map(); + for (const r of opts.kv?.["daily-index"] ?? []) { + const v = r.value as { key?: string; nodeId?: string }; + const key = v.key ?? r.key; + const nodeId = String(v.nodeId ?? ""); + dailyIndex.set(key, { + _id: key, + key, + nodeId, + touchedAt: 0, + userId, + }); + } + + const tagColors = new Map(); + for (const r of opts.kv?.["tag-colors"] ?? []) { + const v = r.value as { tag?: string; color?: string }; + const tag = String(v.tag ?? r.key); + tagColors.set(tag, { + _id: tag, + tag, + color: String(v.color ?? ""), + userId, + }); + } + + const savedQueries = new Map(); + for (const r of opts.kv?.["saved-queries"] ?? []) { + const v = r.value as { + id?: string; + name?: string; + query?: string; + createdAt?: number; + }; + const id = String(v.id ?? r.key); + savedQueries.set(id, { + _id: id, + name: String(v.name ?? ""), + query: String(v.query ?? ""), + createdAt: Number(v.createdAt ?? 0), + userId, + }); + } + + let clientSeq = 0; + let pokeN = 0; + /** Per-shape poke cursor — a shared counter desyncs shapes and Lunora + * drops the poke (`baseDiverged`) without firing `onCheckpoint`, which + * wedges `isPersisted` (claimDaily / materializeDaily / seedIfEmpty). */ + const shapeCheckpoints = new Map(); + /** Last keys we put into each shape — poke is a diff; without deletes for + * removed keys the client view keeps stale rows (Cmd+K delete "works" then + * the poke resurrects the bullet). */ + const shapeKeys = new Map>(); + const sockets = new Set(); + const shapeSubs = new Map(); + + const reply = (route: Route, data: unknown) => + route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify(data), + }); + + const sendPoke = ( + ws: WebSocketRoute, + shapeId: string, + rows: Array & { _id: string }>, + lastMutationId: number, + ) => { + pokeN += 1; + const pokeId = `p${pokeN}`; + const base = shapeCheckpoints.get(shapeId) ?? 0; + const next = base + 1; + shapeCheckpoints.set(shapeId, next); + const nextKeys = new Set(rows.map((r) => r._id)); + const prevKeys = shapeKeys.get(shapeId) ?? new Set(); + const rowsPatch: Array> = []; + for (const key of prevKeys) { + if (!nextKeys.has(key)) rowsPatch.push({ op: "delete", key }); + } + for (const r of rows) { + rowsPatch.push({ op: "put", key: r._id, value: r }); + } + shapeKeys.set(shapeId, nextKeys); + ws.send( + JSON.stringify({ + type: "pokeStart", + pokeId, + baseCheckpoint: base, + epoch: 1, + }), + ); + ws.send( + JSON.stringify({ + type: "pokePart", + pokeId, + shapeId, + lastMutationId, + rowsPatch, + }), + ); + ws.send( + JSON.stringify({ + type: "pokeEnd", + pokeId, + checkpoint: next, + epoch: 1, + }), + ); + }; + + const shapeRows = ( + name: string, + ): Array & { _id: string }> => { + if (name === "wholeOutline") return [...store.values()]; + if (name === "userDailyIndex") return [...dailyIndex.values()]; + if (name === "userTagColors") return [...tagColors.values()]; + if (name === "userSavedQueries") return [...savedQueries.values()]; + return []; + }; + + const seedShape = (ws: WebSocketRoute, shapeId: string, name: string) => { + sendPoke(ws, shapeId, shapeRows(name), 0); + }; + + const pokeSubscribed = (seq: number, shapes: ReadonlySet) => { + for (const ws of sockets) { + for (const [shapeId, meta] of shapeSubs) { + if (!shapes.has(meta.name)) continue; + sendPoke(ws, shapeId, shapeRows(meta.name), seq); + } + } + }; + + const liveIndex = () => buildTreeIndex([...store.values()].map(rowToOutline)); + const liveNodes = () => [...store.values()].map(rowToOutline); + + await page.addInitScript(() => { + window.localStorage.setItem("dotflowy:flag:lunora-sync", "on"); + }); + + await page.route( + (url) => url.pathname === "/api/auth/get-session", + (route) => + reply(route, { + session: { + id: "test-session", + userId, + token: "test-token", + expiresAt: new Date(Date.now() + 86_400_000).toISOString(), + }, + user: { + id: userId, + email: "test@example.com", + name: "Test User", + emailVerified: true, + createdAt: new Date(0).toISOString(), + updatedAt: new Date(0).toISOString(), + }, + }), + ); + + // Empty classic DO so auto-migrate no-ops (Lunora store is the seed). + await page.route( + (url) => url.pathname === "/api/nodes", + (route) => { + if (route.request().method() === "GET") return reply(route, []); + return route.fulfill({ status: 404, body: "{}" }); + }, + ); + await page.route( + (url) => url.pathname === "/api/kv", + (route) => { + if (route.request().method() === "GET") return reply(route, []); + return route.fulfill({ status: 404, body: "{}" }); + }, + ); + + await page.route( + (url) => url.pathname === "/_lunora/rpc", + async (route) => { + const body = route.request().postDataJSON() as { + functionPath?: string; + args?: Record; + }; + const path = body.functionPath ?? ""; + const args = (body.args ?? {}) as Record; + const seqHeader = route.request().headers()["x-lunora-client-seq"]; + const seq = seqHeader ? Number(seqHeader) : ++clientSeq; + if (Number.isFinite(seq)) clientSeq = Math.max(clientSeq, seq); + + if (opts.failMutatorWrites && path.startsWith("mutators:")) { + return route.fulfill({ status: 500, body: "mutator failed" }); + } + + let result: unknown = {}; + let pokeShapes = new Set( + opts.suppressWholeOutlinePoke ? [] : ["wholeOutline"], + ); + + const id = () => String(args.id ?? ""); + const updatedAt = () => Number(args.updatedAt ?? Date.now()); + + if (path === "mutators:setText") { + commitOutlinePlan( + store, + planSetText(liveIndex(), id(), String(args.text ?? ""), updatedAt()), + ); + result = { id: id() }; + } else if (path === "mutators:setCompleted") { + commitOutlinePlan( + store, + planSetCompleted( + liveIndex(), + id(), + Boolean(args.completed), + updatedAt(), + ), + ); + } else if (path === "mutators:setCollapsed") { + commitOutlinePlan( + store, + planSetCollapsed( + liveIndex(), + id(), + Boolean(args.collapsed), + updatedAt(), + ), + ); + } else if (path === "mutators:setIsTask") { + commitOutlinePlan( + store, + planSetIsTask(liveIndex(), id(), Boolean(args.isTask), updatedAt()), + ); + } else if (path === "mutators:setKind") { + commitOutlinePlan( + store, + planSetKind( + liveIndex(), + id(), + args.kind === "paragraph" ? "paragraph" : null, + updatedAt(), + ), + ); + } else if (path === "mutators:setBookmarkedAt") { + commitOutlinePlan( + store, + planSetBookmarkedAt( + liveIndex(), + id(), + (args.bookmarkedAt as number | null) ?? null, + updatedAt(), + ), + ); + } else if (path === "mutators:insertSibling") { + commitOutlinePlan( + store, + planInsertSibling(liveIndex(), { + id: id(), + userId, + parentId: (args.parentId as string | null) ?? null, + afterId: (args.afterId as string | null) ?? null, + text: String(args.text ?? ""), + isTask: Boolean(args.isTask), + kind: args.kind === "paragraph" ? "paragraph" : null, + createdAt: Number(args.createdAt ?? 0), + updatedAt: updatedAt(), + }), + ); + result = { id: id() }; + } else if (path === "mutators:insertChildAtStart") { + commitOutlinePlan( + store, + planInsertChildAtStart(liveIndex(), { + id: id(), + userId, + parentId: (args.parentId as string | null) ?? null, + text: String(args.text ?? ""), + isTask: Boolean(args.isTask), + kind: args.kind === "paragraph" ? "paragraph" : null, + createdAt: Number(args.createdAt ?? 0), + updatedAt: updatedAt(), + }), + ); + result = { id: id() }; + } else if (path === "mutators:appendChild") { + commitOutlinePlan( + store, + planAppendChild(liveIndex(), { + id: id(), + userId, + parentId: (args.parentId as string | null) ?? null, + text: String(args.text ?? ""), + isTask: Boolean(args.isTask), + kind: args.kind === "paragraph" ? "paragraph" : null, + createdAt: Number(args.createdAt ?? 0), + updatedAt: updatedAt(), + }), + ); + result = { id: id() }; + } else if (path === "mutators:splitNode") { + const newId = String(args.newId ?? ""); + commitOutlinePlan( + store, + planSplitNode(liveIndex(), { + id: id(), + newId, + userId, + parentId: (args.parentId as string | null) ?? null, + afterId: String(args.afterId ?? id()), + leftText: String(args.leftText ?? ""), + rightText: String(args.rightText ?? ""), + isTask: Boolean(args.isTask), + kind: args.kind === "paragraph" ? "paragraph" : null, + createdAt: Number(args.createdAt ?? 0), + updatedAt: updatedAt(), + }), + ); + result = { id: newId }; + } else if (path === "mutators:indent") { + commitOutlinePlan( + store, + planIndent( + liveIndex(), + id(), + updatedAt(), + Boolean(args.resolveMirror), + ), + ); + } else if (path === "mutators:outdent") { + commitOutlinePlan(store, planOutdent(liveIndex(), id(), updatedAt())); + } else if (path === "mutators:removeNode") { + commitOutlinePlan( + store, + planRemoveNode(liveIndex(), id(), updatedAt()), + ); + } else if (path === "mutators:moveNode") { + commitOutlinePlan( + store, + planMoveNode(liveIndex(), { + id: id(), + newParentId: (args.newParentId as string | null) ?? null, + afterSiblingId: (args.afterSiblingId as string | null) ?? null, + updatedAt: updatedAt(), + expandIds: args.expandIds as string[] | undefined, + }), + ); + } else if (path === "mutators:restoreNodes") { + const target = (args.nodes as OutlineNode[] | undefined) ?? []; + commitOutlinePlan(store, planRestoreNodes(liveNodes(), target)); + result = { ok: true }; + } else if (path === "mutators:importNodes") { + const imported = (args.nodes as OutlineNode[] | undefined) ?? []; + commitOutlinePlan(store, planImportNodes(imported)); + result = { count: imported.length }; + } else if (path === "mutators:mirrorNode") { + commitOutlinePlan( + store, + planMirrorNode(liveIndex(), { + id: id(), + userId, + sourceId: String(args.sourceId ?? ""), + targetParentId: (args.targetParentId as string | null) ?? null, + createdAt: Number(args.createdAt ?? 0), + updatedAt: updatedAt(), + }), + ); + result = { id: id() }; + } else if (path === "mutators:removeMany") { + const nodeIds = (args.nodeIds as string[] | undefined) ?? []; + commitOutlinePlan( + store, + planRemoveMany(liveNodes(), nodeIds, updatedAt()), + ); + } else if (path === "mutators:moveMany") { + const nodeIds = (args.nodeIds as string[] | undefined) ?? []; + commitOutlinePlan( + store, + planMoveMany(liveNodes(), { + targetId: (args.targetId as string | null) ?? null, + nodeIds, + updatedAt: updatedAt(), + }), + ); + } else if (path === "mutators:indentMany") { + const nodeIds = (args.nodeIds as string[] | undefined) ?? []; + commitOutlinePlan( + store, + planIndentMany( + liveNodes(), + nodeIds, + updatedAt(), + Boolean(args.resolveMirror), + ), + ); + } else if (path === "mutators:outdentMany") { + const nodeIds = (args.nodeIds as string[] | undefined) ?? []; + commitOutlinePlan( + store, + planOutdentMany(liveNodes(), nodeIds, updatedAt()), + ); + } else if (path === "mutators:materializeDailyNodes") { + const inserts = + (args.inserts as + | { + id: string; + parentId: string | null; + afterId: string | null; + text: string; + }[] + | undefined) ?? []; + commitOutlinePlan( + store, + planMaterializeDailyNodes(liveNodes(), { + userId, + inserts, + createdAt: Number(args.createdAt ?? 0), + updatedAt: updatedAt(), + }), + ); + result = { count: inserts.length }; + } else if (path === "mutators:seedIfEmpty") { + result = { seeded: false }; + } else if (path === "mutators:upsertTagColor") { + const tag = String(args.tag ?? ""); + tagColors.set(tag, { + _id: tag, + tag, + color: String(args.color ?? ""), + userId, + }); + pokeShapes = new Set(["userTagColors"]); + } else if (path === "mutators:deleteTagColor") { + tagColors.delete(String(args.tag ?? "")); + pokeShapes = new Set(["userTagColors"]); + } else if (path === "mutators:upsertSavedQuery") { + const sid = String(args.id ?? ""); + savedQueries.set(sid, { + _id: sid, + name: String(args.name ?? ""), + query: String(args.query ?? ""), + createdAt: Number(args.createdAt ?? 0), + userId, + }); + pokeShapes = new Set(["userSavedQueries"]); + } else if (path === "mutators:patchSavedQuery") { + const sid = String(args.id ?? ""); + const cur = savedQueries.get(sid); + if (cur) { + savedQueries.set(sid, { + ...cur, + name: args.name !== undefined ? String(args.name) : cur.name, + query: args.query !== undefined ? String(args.query) : cur.query, + }); + } + pokeShapes = new Set(["userSavedQueries"]); + } else if (path === "mutators:deleteSavedQuery") { + savedQueries.delete(String(args.id ?? "")); + pokeShapes = new Set(["userSavedQueries"]); + } else if (path === "mutators:claimDailyMapping") { + const key = String(args.key ?? ""); + const candidate = String(args.nodeId ?? ""); + const existing = dailyIndex.get(key); + const { winner, won } = resolveDailyClaim(existing?.nodeId, candidate); + dailyIndex.set(key, { + _id: key, + key, + nodeId: winner, + touchedAt: Number(args.touchedAt ?? Date.now()), + userId, + }); + result = { nodeId: winner, won }; + pokeShapes = new Set(["userDailyIndex"]); + } else if (path === "mutators:upsertDailyMapping") { + const key = String(args.key ?? ""); + dailyIndex.set(key, { + _id: key, + key, + nodeId: String(args.nodeId ?? ""), + touchedAt: Number(args.touchedAt ?? Date.now()), + userId, + }); + pokeShapes = new Set(["userDailyIndex"]); + } else if (path === "mutators:deleteDailyMapping") { + dailyIndex.delete(String(args.key ?? "")); + pokeShapes = new Set(["userDailyIndex"]); + } + // Unknown mutators: accept so watermark chain doesn't wedge. + + // Watermark is per-client on the shard (wholeOutline checkpoints gate + // isPersisted). Kv-only mutators must still advance wholeOutline or + // claimDailyMapping / materializeDailyNodes hang awaiting the poke — + // unless a spec opts into `suppressWholeOutlinePoke` (missed-poke case). + if (!opts.suppressWholeOutlinePoke) { + pokeShapes.add("wholeOutline"); + } else { + pokeShapes.delete("wholeOutline"); + } + + await reply(route, { result, lastMutationId: seq }); + if (pokeShapes.size > 0) pokeSubscribed(seq, pokeShapes); + }, + ); + + await page.routeWebSocket( + (url) => url.pathname === "/_lunora/ws", + (ws) => { + sockets.add(ws); + ws.onClose(() => sockets.delete(ws)); + ws.onMessage((raw) => { + if (typeof raw !== "string") return; + if (raw === "lunora-ping") { + ws.send("lunora-pong"); + return; + } + let msg: { + type?: string; + id?: string; + shape?: { name?: string; args?: unknown }; + }; + try { + msg = JSON.parse(raw) as typeof msg; + } catch { + return; + } + if (msg.type === "connect") { + return; + } + if (msg.type === "shape_subscribe" && msg.id && msg.shape?.name) { + shapeSubs.set(msg.id, { name: msg.shape.name }); + seedShape(ws, msg.id, msg.shape.name); + } + }); + }, + ); +} diff --git a/e2e/lunora-optimistic-hold.spec.ts b/e2e/lunora-optimistic-hold.spec.ts new file mode 100644 index 00000000..771aa220 --- /dev/null +++ b/e2e/lunora-optimistic-hold.spec.ts @@ -0,0 +1,51 @@ +import { expect, test, type Page } from "@playwright/test"; + +import { seedOutlineLunora, type SeedNode } from "./fixtures"; + +/** + * Pins the Lunora sticky-optimistic typing fix: when a `wholeOutline` shape + * poke is missed, the ~3s checkpoint fallback must NOT drop typed text + * (Settings → back used to look empty until hard refresh). + * + * Run: `bunx playwright test e2e/lunora-optimistic-hold.spec.ts` + */ + +const text = (page: Page, id: string) => + page.locator(`li[data-node-id="${id}"] > .outline-row .node-text`); + +const TREE: SeedNode[] = [ + { id: "hold", parentId: null, prevSiblingId: null, text: "HoldBase" }, +]; + +test.describe("Lunora optimistic hold (missed shape poke)", () => { + test("typed text survives 3s fallback and Settings round-trip", async ({ + page, + }) => { + await seedOutlineLunora(page, TREE, { suppressWholeOutlinePoke: true }); + await page.goto("/"); + await expect(text(page, "hold")).toBeVisible({ timeout: 15_000 }); + await expect(text(page, "hold")).toHaveText("HoldBase"); + + await text(page, "hold").click(); + await page.keyboard.type("X"); + await expect(text(page, "hold")).toHaveText("HoldBaseX"); + + // Past SHAPE_CHECKPOINT_FALLBACK_MS — without sticky-direct the overlay + // would revert to HoldBase here. + await expect(text(page, "hold")).toHaveText("HoldBaseX", { + timeout: 5_000, + }); + await page.waitForTimeout(3_500); + await expect(text(page, "hold")).toHaveText("HoldBaseX"); + + // SPA remount via in-app nav (hard goto would reset the Lunora client). + await page.getByRole("button", { name: /more/i }).click(); + await page.getByRole("menuitem", { name: "Settings" }).click(); + await expect(page.getByRole("heading", { name: "Settings" })).toBeVisible({ + timeout: 10_000, + }); + await page.getByRole("button", { name: "Back to outline" }).click(); + await expect(text(page, "hold")).toBeVisible({ timeout: 15_000 }); + await expect(text(page, "hold")).toHaveText("HoldBaseX"); + }); +}); diff --git a/e2e/lunora-save-failure.spec.ts b/e2e/lunora-save-failure.spec.ts new file mode 100644 index 00000000..456291c6 --- /dev/null +++ b/e2e/lunora-save-failure.spec.ts @@ -0,0 +1,56 @@ +import { expect, test, type Page } from "@playwright/test"; + +import { seedOutlineLunora, STANDARD_TREE } from "./fixtures"; + +/** + * Lunora twin of `save-failure.spec.ts`: a failed mutator RPC must toast and + * roll back optimistic UI — sticky `__tanstack_db_direct` must not keep a + * rejected edit forever. + * + * Run: `bunx playwright test e2e/lunora-save-failure.spec.ts` + */ + +const text = (page: Page, id: string) => + page.locator(`li[data-node-id="${id}"] > .outline-row .node-text`); + +const orderedTexts = (page: Page) => + page.locator(".outline-row .node-text").allTextContents(); + +const saveFailedToast = (page: Page) => + page.locator("[data-sonner-toast]", { + hasText: "Couldn't save your changes", + }); + +async function caretAtEnd(page: Page, id: string) { + const el = text(page, id); + await el.click(); + await el.evaluate((node) => { + const sel = window.getSelection(); + if (!sel) return; + const range = document.createRange(); + range.selectNodeContents(node); + range.collapse(false); + sel.removeAllRanges(); + sel.addRange(range); + }); +} + +test.describe("Lunora save failure rolls back optimistic edits", () => { + test("a failed structural mutator toasts and reverts the optimistic bullet", async ({ + page, + }) => { + await seedOutlineLunora(page, STANDARD_TREE, { failMutatorWrites: true }); + await page.goto("/"); + await expect(text(page, "alpha")).toBeVisible({ timeout: 15_000 }); + + const before = await orderedTexts(page); + + await caretAtEnd(page, "alpha"); + await page.keyboard.press("Enter"); + + await expect(saveFailedToast(page)).toBeVisible({ timeout: 10_000 }); + await expect + .poll(() => orderedTexts(page), { timeout: 10_000 }) + .toEqual(before); + }); +}); diff --git a/e2e/lunora-structural.spec.ts b/e2e/lunora-structural.spec.ts new file mode 100644 index 00000000..15b0d7e0 --- /dev/null +++ b/e2e/lunora-structural.spec.ts @@ -0,0 +1,113 @@ +import { expect, test, type Page } from "@playwright/test"; + +import { seedOutlineLunora, STANDARD_TREE, type SeedNode } from "./fixtures"; + +/** + * Lunora flag-ON structural subset — proves enter-split / indent / delete + * ride `seedOutlineLunora` (planner-backed `/_lunora/rpc` mock). + * + * Run: `bunx playwright test e2e/lunora-*.spec.ts` + * Classic suite stays on `seedOutline` (flag OFF). + */ + +const text = (page: Page, id: string) => + page.locator(`li[data-node-id="${id}"] > .outline-row .node-text`); + +const row = (page: Page, id: string) => + page.locator(`li[data-node-id="${id}"]`); + +const focused = (page: Page) => page.locator(".node-text:focus"); + +const orderedTexts = (page: Page) => + page.locator(".outline-row .node-text").allTextContents(); + +async function load(page: Page, tree: SeedNode[]) { + await seedOutlineLunora(page, tree); + await page.goto("/"); + await expect(text(page, tree[0]!.id)).toBeVisible({ timeout: 15_000 }); +} + +async function caretAt(page: Page, id: string, col: number) { + await text(page, id).click(); + await text(page, id).evaluate((el, target) => { + const sel = window.getSelection(); + if (!sel) return; + const walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT); + let remaining = target; + let node = walker.nextNode(); + const range = document.createRange(); + while (node) { + const len = node.textContent?.length ?? 0; + if (remaining <= len) { + range.setStart(node, remaining); + range.collapse(true); + sel.removeAllRanges(); + sel.addRange(range); + return; + } + remaining -= len; + node = walker.nextNode(); + } + range.selectNodeContents(el); + range.collapse(false); + sel.removeAllRanges(); + sel.addRange(range); + }, col); +} + +test.describe("Lunora structural (flag ON)", () => { + test("Enter mid-text splits into a sibling", async ({ page }) => { + await load(page, [ + { id: "n", parentId: null, prevSiblingId: null, text: "alphabravo" }, + ]); + + await caretAt(page, "n", 5); + await page.keyboard.press("Enter"); + + await expect(text(page, "n")).toHaveText("alpha"); + await expect(focused(page)).toHaveText("bravo"); + expect(await orderedTexts(page)).toEqual(["alpha", "bravo"]); + }); + + test("Tab indents under the previous sibling", async ({ page }) => { + await load(page, [ + { id: "a", parentId: null, prevSiblingId: null, text: "Alpha" }, + { id: "b", parentId: null, prevSiblingId: "a", text: "Bravo" }, + ]); + + await text(page, "b").click(); + await page.keyboard.press("Tab"); + + await expect(row(page, "b")).toHaveAttribute("data-parent-id", "a"); + await expect(row(page, "b")).toHaveAttribute("data-depth", "1"); + }); + + test("/delete removes a leaf and persists across reload", async ({ + page, + }) => { + await load(page, STANDARD_TREE); + + await text(page, "bravo").click(); + await page.keyboard.type(" /delete"); + await expect(page.getByRole("listbox")).toBeVisible(); + // Await the remove mutator before reload — fire-and-forget watermark can + // race page.reload() and resurrect the leaf from the mock store. + const removed = page.waitForResponse( + (r) => + r.url().includes("/_lunora/rpc") && + r.request().method() === "POST" && + (r.request().postData() ?? "").includes("mutators:removeNode"), + ); + await page.keyboard.press("Enter"); + await removed; + + await expect(row(page, "bravo")).toHaveCount(0); + await expect(text(page, "alpha")).toBeVisible(); + await expect(text(page, "charlie")).toBeVisible(); + + await page.reload(); + await expect(text(page, "alpha")).toBeVisible({ timeout: 15_000 }); + await expect(row(page, "bravo")).toHaveCount(0); + await expect(text(page, "charlie")).toBeVisible(); + }); +}); diff --git a/e2e/lunora-sync-smoke.spec.ts b/e2e/lunora-sync-smoke.spec.ts new file mode 100644 index 00000000..78aa31dd --- /dev/null +++ b/e2e/lunora-sync-smoke.spec.ts @@ -0,0 +1,49 @@ +import { expect, test, type Page } from "@playwright/test"; + +import { seedOutlineLunora, type SeedNode } from "./fixtures"; + +/** + * Foundation smoke for ADR 0055 Lunora flag-ON path. + * Uses `seedOutlineLunora` (mocks `/_lunora/*`). Classic suite stays on + * `seedOutline` with the flag default OFF. + * + * Run with the Lunora subset: `bunx playwright test e2e/lunora-*.spec.ts` + * + * If this flakes locally (WS poke / watermark timing), keep the fixture and + * treat this file as the path forward — do not rewrite the whole e2e suite yet. + */ + +const text = (page: Page, id: string) => + page.locator(`li[data-node-id="${id}"] > .outline-row .node-text`); + +const TREE: SeedNode[] = [ + { id: "smoke", parentId: null, prevSiblingId: null, text: "LunoraSmoke" }, +]; + +test.describe("Lunora sync smoke (flag ON)", () => { + test("loads seeded outline, edits survive reload", async ({ page }) => { + await seedOutlineLunora(page, TREE); + await page.goto("/"); + await expect(text(page, "smoke")).toBeVisible({ timeout: 15_000 }); + await expect(text(page, "smoke")).toHaveText("LunoraSmoke"); + + // Place caret at end (contentEditable click can land mid-glyph / past text). + await text(page, "smoke").click(); + await text(page, "smoke").evaluate((el) => { + const sel = window.getSelection(); + if (!sel) return; + const range = document.createRange(); + range.selectNodeContents(el); + range.collapse(false); + sel.removeAllRanges(); + sel.addRange(range); + }); + await page.keyboard.type("X"); + await expect(text(page, "smoke")).toHaveText("LunoraSmokeX"); + + // Watermark + mock store should hold the edit across a hard reload. + await page.reload(); + await expect(text(page, "smoke")).toBeVisible({ timeout: 15_000 }); + await expect(text(page, "smoke")).toHaveText("LunoraSmokeX"); + }); +}); diff --git a/e2e/lunora-undo.spec.ts b/e2e/lunora-undo.spec.ts new file mode 100644 index 00000000..c90f328d --- /dev/null +++ b/e2e/lunora-undo.spec.ts @@ -0,0 +1,51 @@ +import { expect, test, type Page } from "@playwright/test"; + +import { seedOutlineLunora, type SeedNode } from "./fixtures"; + +/** + * Lunora flag-ON undo/redo via `mutators:restoreNodes` (mock applies + * planRestoreNodes). Small undos only — sliced modal path stays classic e2e. + * + * Run: `bunx playwright test e2e/lunora-*.spec.ts` + */ + +const text = (page: Page, id: string) => + page.locator(`li[data-node-id="${id}"] > .outline-row .node-text`); + +const row = (page: Page, id: string) => + page.locator(`li[data-node-id="${id}"]`); + +const TREE: SeedNode[] = [ + { id: "a", parentId: null, prevSiblingId: null, text: "Alpha" }, + { id: "b", parentId: null, prevSiblingId: "a", text: "Bravo" }, + { id: "c", parentId: null, prevSiblingId: "b", text: "Charlie" }, +]; + +test.describe("Lunora undo/redo (flag ON)", () => { + test("Cmd+Z restores a deleted leaf; Cmd+Shift+Z re-deletes", async ({ + page, + }) => { + await seedOutlineLunora(page, TREE); + await page.goto("/"); + await expect(text(page, "a")).toBeVisible({ timeout: 15_000 }); + + await text(page, "b").click(); + await page.keyboard.type(" /delete"); + await expect(page.getByRole("listbox")).toBeVisible(); + await page.keyboard.press("Enter"); + await expect(row(page, "b")).toHaveCount(0); + + await text(page, "a").click(); + await page.keyboard.press("ControlOrMeta+z"); + await expect(text(page, "b")).toBeVisible({ timeout: 10_000 }); + + await page.keyboard.press("ControlOrMeta+Shift+z"); + await expect(row(page, "b")).toHaveCount(0); + + // Persisted through the mock store. + await page.reload(); + await expect(text(page, "a")).toBeVisible({ timeout: 15_000 }); + await expect(row(page, "b")).toHaveCount(0); + await expect(text(page, "c")).toBeVisible(); + }); +}); diff --git a/e2e/opml-import.spec.ts b/e2e/opml-import.spec.ts index e73d8d2a..d06d6e80 100644 --- a/e2e/opml-import.spec.ts +++ b/e2e/opml-import.spec.ts @@ -8,7 +8,7 @@ import { expect, test, type FileChooser, type Page } from "@playwright/test"; import { readFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; -import { seedOutline, STANDARD_TREE } from "./fixtures"; +import { isE2eLunora, seedOutline, STANDARD_TREE } from "./fixtures"; const SAMPLE_PATH = fileURLToPath( new URL( @@ -148,6 +148,10 @@ test.describe("OPML import", () => { test("a multi-slice import (>500 nodes) applies in yielding slices yet lands as ONE atomic batch", async ({ page, }) => { + test.skip( + isE2eLunora(), + "asserts the classic one-batch transport progress state", + ); // Delay the batch POST *response* so the dialog rests in its post-apply // "saving" phase — deterministic proof the sliced optimistic apply // finished (applied === count) while the single wire batch is in flight. diff --git a/e2e/save-failure.spec.ts b/e2e/save-failure.spec.ts index 34177f00..4e1b7fb7 100644 --- a/e2e/save-failure.spec.ts +++ b/e2e/save-failure.spec.ts @@ -1,6 +1,6 @@ import { expect, test, type Page } from "@playwright/test"; -import { seedOutline, STANDARD_TREE } from "./fixtures"; +import { isE2eLunora, seedOutline, STANDARD_TREE } from "./fixtures"; // A node's own editable text span. const text = (page: Page, id: string) => @@ -37,6 +37,10 @@ test.describe("Save failure surfaces a toast and rolls back (#230)", () => { test("a failed structural write toasts and reverts the optimistic bullet", async ({ page, }) => { + test.skip( + isE2eLunora(), + "injects a failure into the classic structural transport", + ); // Seed loads normally; only structural-batch POSTs fail from here on. await seedOutline(page, STANDARD_TREE, { failStructuralWrites: true }); await page.goto("/"); diff --git a/e2e/sibling-chain-repair.spec.ts b/e2e/sibling-chain-repair.spec.ts index 944a6a97..92bfcac5 100644 --- a/e2e/sibling-chain-repair.spec.ts +++ b/e2e/sibling-chain-repair.spec.ts @@ -1,6 +1,6 @@ import { expect, test } from "@playwright/test"; -import { seedOutline, type SeedNode } from "./fixtures"; +import { isE2eLunora, seedOutline, type SeedNode } from "./fixtures"; interface PatchUpdate { id: string; @@ -41,6 +41,10 @@ function chainsAreClean(nodes: SeedNode[]): boolean { test("heals a shattered sibling chain on load so every node is reorderable", async ({ page, }) => { + test.skip( + isE2eLunora(), + "loads malformed rows through the classic snapshot fixture", + ); // Mirrors the production corruption: B and C both point at A (root), so one // orphans out of the chain; A1/A2 both claim the head under A (a nested fan). const seed: SeedNode[] = [ diff --git a/e2e/update-available.spec.ts b/e2e/update-available.spec.ts index c83baccf..52e2af02 100644 --- a/e2e/update-available.spec.ts +++ b/e2e/update-available.spec.ts @@ -1,7 +1,7 @@ import { expect, test, type Page } from "@playwright/test"; import { readFileSync } from "node:fs"; -import { seedOutline, STANDARD_TREE } from "./fixtures"; +import { isE2eLunora, seedOutline, STANDARD_TREE } from "./fixtures"; /** * The stale-tab reload affordance (ADR 0046). @@ -29,6 +29,10 @@ async function load(page: Page, serverVersion?: string) { test.describe("update available", () => { test("a newer server raises a reload toast", async ({ page }) => { + test.skip( + isE2eLunora(), + "injects serverVersion through the classic sync handshake", + ); await load(page, "99.0.0"); await expect(toast(page)).toBeVisible(); await expect(page.getByRole("button", { name: "Reload" })).toBeVisible(); @@ -49,6 +53,10 @@ test.describe("update available", () => { }); test("the toast does not block editing", async ({ page }) => { + test.skip( + isE2eLunora(), + "injects serverVersion through the classic sync handshake", + ); await load(page, "99.0.0"); await expect(toast(page)).toBeVisible(); diff --git a/lunora/.lunora-schema.json b/lunora/.lunora-schema.json new file mode 100644 index 00000000..e85bee04 --- /dev/null +++ b/lunora/.lunora-schema.json @@ -0,0 +1,98 @@ +{ + "migrationIds": [], + "tables": { + "nodes": { + "fields": { + "parentId": { + "kind": "string", + "optional": false + }, + "prevSiblingId": { + "kind": "string", + "optional": false + }, + "text": { + "kind": "string", + "optional": false + }, + "isTask": { + "kind": "boolean", + "optional": false + }, + "completed": { + "kind": "boolean", + "optional": false + }, + "collapsed": { + "kind": "boolean", + "optional": false + }, + "bookmarkedAt": { + "kind": "number", + "optional": false + }, + "mirrorOf": { + "kind": "string", + "optional": false + }, + "createdAt": { + "kind": "number", + "optional": false + }, + "updatedAt": { + "kind": "number", + "optional": false + }, + "origin": { + "kind": "string", + "optional": false + }, + "kind": { + "kind": "literal", + "optional": false + }, + "userId": { + "kind": "string", + "optional": false + } + }, + "indexes": { + "by_parent": { + "fields": ["parentId"], + "unique": false + } + }, + "relations": {}, + "shardMode": "shardBy:userId" + }, + "ratelimit_buckets": { + "fields": { + "key": { + "kind": "string", + "optional": false + }, + "value": { + "kind": "number", + "optional": false + }, + "ts": { + "kind": "number", + "optional": false + }, + "prev": { + "kind": "number", + "optional": true + } + }, + "indexes": { + "by_key": { + "fields": ["key"], + "unique": false + } + }, + "relations": {}, + "shardMode": "root" + } + }, + "version": 1 +} diff --git a/lunora/_generated/api.ts b/lunora/_generated/api.ts new file mode 100644 index 00000000..24fc7aa7 --- /dev/null +++ b/lunora/_generated/api.ts @@ -0,0 +1,21 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +import { anyApi } from "lunorash/server/types"; +import type { FunctionReference } from "lunorash/client"; + +export interface ApiTypes {} + +export const api = anyApi as unknown as ApiTypes; + +/** Internal functions — callable only server-side via `ctx.run*`, never from a client. */ +export interface InternalApiTypes { + mcp: { + applyChangeOps: FunctionReference<"mutation", { userId: string; ops: Array }, { count: number; deletes?: undefined; inserts?: undefined; patches?: undefined; } | { count: number; deletes: number; inserts: number; patches: number; }>; + listDailyIndex: FunctionReference<"query", { userId: string }, { key: string; nodeId: string; }[]>; + listNodes: FunctionReference<"query", { userId: string }, { id: string; parentId: string | null; prevSiblingId: string | null; text: string; isTask: boolean; completed: boolean; collapsed: boolean; bookmarkedAt: number | null; mirrorOf: string | null; createdAt: number; updatedAt: number; origin: string | null; kind: "paragraph" | null }[]>; + wipeUserShard: FunctionReference<"mutation", { userId: string }, { deleted: number; }>; + }; +} + +export const internal = anyApi as unknown as InternalApiTypes; diff --git a/lunora/_generated/app.ts b/lunora/_generated/app.ts new file mode 100644 index 00000000..691922fb --- /dev/null +++ b/lunora/_generated/app.ts @@ -0,0 +1,145 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +import type { ExecutionContextLike, LunoraWorker, Route, ScheduledControllerLike, ShardNamespaceLike, WorkerOptions } from "lunorash/runtime"; +import { createWorker, resolveLogArchiveFromEnv } from "lunorash/runtime"; + +import { LUNORA_CRONS } from "./crons.js"; +import { LUNORA_FUNCTIONS } from "./functions.js"; +import { openApiSpec } from "./openapi.js"; +import { createShardDO } from "./shard.js"; + +/** Read a value off the per-request `env`. Returns `undefined` to leave the capability unconfigured (its `ctx.*`/admin surface stays a clear-error stub). */ +type Selector = (env: Env) => T | undefined; + +/** The composed app: a Cloudflare module worker (`fetch` / `scheduled` / optional `email`) plus the `ShardDO` class binding. */ +interface ComposedApp extends LunoraWorker { + /** Cloudflare Email Routing entry — present only when `.onEmail(...)` was configured. */ + email?: (message: unknown, env: unknown, context: ExecutionContextLike) => Promise; + /** The generated shard Durable Object class — re-export it as a named export so wrangler can bind it. */ + ShardDO: ReturnType; +} + +/** + * Fluent worker-composition builder. Records each capability declaration, then + * `.build()` fans them into the DO-side `createShardDO` factory and the + * worker-side `createWorker` options — constructing the worker lazily on the + * first request so per-isolate singletons are built once. + */ +class AppBuilder> { + private adminToken?: Selector; + private readonly extendFns: ((env: Env, derived: Readonly) => Partial)[] = []; + private readonly routeMap: Record = {}; + private shardSelector?: Selector; + + private emailHandler?: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise; + + /** Bearer token gating the `/_lunora/admin/*` endpoints the studio calls. */ + public admin(selector: Selector): this { + this.adminToken = selector; + + return this; + } + + /** Escape hatch — merge raw `WorkerOptions` (anything not yet sugared) over the derived options at build time. The second `derived` argument is a snapshot of the options assembled so far (after `.auth(...)` etc.), so you can compose rather than clobber — e.g. wrap `derived.resolveIdentity` instead of replacing it. */ + public extend(fn: (env: Env, derived: Readonly) => Partial): this { + this.extendFns.push(fn); + + return this; + } + + /** Cloudflare Email Routing entry — exposes the top-level `email` handler. */ + public onEmail(handler: (env: Env) => (message: unknown, env: unknown, context: ExecutionContextLike) => Promise): this { + this.emailHandler = handler; + + return this; + } + + /** Mount a custom HTTP route (e.g. an asset-serving or test endpoint). Key is `"METHOD path"`, `"path"`, or a path prefix matched by the runtime. */ + public route(key: string, handler: Route): this { + this.routeMap[key] = handler; + + return this; + } + + /** The shard Durable Object namespace (typically `env.SHARD`) — required: every app routes RPC + WebSocket traffic through it. */ + public shard(selector: Selector): this { + this.shardSelector = selector; + + return this; + } + + /** Materialise the standalone Cloudflare worker + `ShardDO` class. */ + public build(): ComposedApp { + return this.assemble(); + } + + /** Build the shard DO + compose the worker (standalone or framework-hosted), wrapping the lazy per-isolate singletons + auth init. */ + private assemble(): ComposedApp { + const ShardDO = createShardDO({}); + + // Per-isolate singletons: the worker (and auth instance) are expensive to + // build, so the first request constructs them and every later request on + // the same isolate reuses them. + let worker: LunoraWorker | null = null; + + const buildWorker = (env: Env): LunoraWorker => createWorker(this.buildWorkerOptions(env, () => null)); + + const composed: ComposedApp = { + ShardDO, + fetch: async (request: Request, rawEnv: unknown, context: ExecutionContextLike): Promise => { + const env = rawEnv as Env; + worker ??= buildWorker(env); + + return worker.fetch(request, rawEnv, context); + }, + scheduled: async (controller: ScheduledControllerLike, rawEnv: unknown, context: ExecutionContextLike): Promise => { + worker ??= buildWorker(rawEnv as Env); + + return worker.scheduled(controller, rawEnv, context); + }, + serverQuery: (request, rawEnv, reference, args, options) => { + worker ??= buildWorker(rawEnv as Env); + + return worker.serverQuery(request, rawEnv, reference, args, options); + }, + }; + + if (this.emailHandler) { + const handler = this.emailHandler; + + composed.email = (message, rawEnv, context) => handler(rawEnv as Env)(message, rawEnv, context); + } + + return composed; + } + + /** Fan the recorded declarations into the worker-side `createWorker` options. */ + private buildWorkerOptions(env: Env, _getAuth: () => null): WorkerOptions { + const options: WorkerOptions = { + cronJobs: LUNORA_CRONS, + functions: LUNORA_FUNCTIONS, + openApiSpec, + routes: this.routeMap, + shardDO: this.shardSelector?.(env) ?? (undefined as unknown as ShardNamespaceLike), + }; + + if (this.adminToken) { + options.adminToken = this.adminToken(env); + } + + options.logArchive = resolveLogArchiveFromEnv(env); + + for (const fn of this.extendFns) { + Object.assign(options, fn(env, { ...options })); + } + + return options; + } +} + +/** Start composing the app. Chain the capability methods, then `.build()`. */ +const defineApp = >(): AppBuilder => new AppBuilder(); + +export { AppBuilder, defineApp }; +export type { ComposedApp, Selector }; diff --git a/lunora/_generated/collections.ts b/lunora/_generated/collections.ts new file mode 100644 index 00000000..06f614f3 --- /dev/null +++ b/lunora/_generated/collections.ts @@ -0,0 +1,24 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +import type { LunoraClient } from "lunorash/client"; +import { lunoraCollectionOptions } from "@lunora/db/collections"; +import type { Row } from "@lunora/db"; +import type { Collection } from "@tanstack/db"; +import { createCollection } from "@tanstack/db"; + +/** Live collection for the `userDailyIndex` replication shape — pass the shape's validated `args` (its partition selector). */ +export const userDailyIndexCollection = (client: LunoraClient, args?: Record): Collection => + createCollection(lunoraCollectionOptions({ client, shape: { args, name: "userDailyIndex" } }).config); + +/** Live collection for the `userSavedQueries` replication shape — pass the shape's validated `args` (its partition selector). */ +export const userSavedQueriesCollection = (client: LunoraClient, args?: Record): Collection => + createCollection(lunoraCollectionOptions({ client, shape: { args, name: "userSavedQueries" } }).config); + +/** Live collection for the `userTagColors` replication shape — pass the shape's validated `args` (its partition selector). */ +export const userTagColorsCollection = (client: LunoraClient, args?: Record): Collection => + createCollection(lunoraCollectionOptions({ client, shape: { args, name: "userTagColors" } }).config); + +/** Live collection for the `wholeOutline` replication shape — pass the shape's validated `args` (its partition selector). */ +export const wholeOutlineCollection = (client: LunoraClient, args?: Record): Collection => + createCollection(lunoraCollectionOptions({ client, shape: { args, name: "wholeOutline" } }).config); diff --git a/lunora/_generated/crons.ts b/lunora/_generated/crons.ts new file mode 100644 index 00000000..0568aa24 --- /dev/null +++ b/lunora/_generated/crons.ts @@ -0,0 +1,28 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +/** + * One scheduled cron invocation. Exactly one target is set: `functionPath` is + * the `namespace:fn` dispatch ref (matches `__lunoraRef`), invoked on the + * shard; `workflow` is a `WORKFLOW_*` binding name whose durable workflow is + * started fresh per fire. `args` are forwarded verbatim (a workflow's become + * its `params`). + */ +export interface LunoraCronJob { + args: Record; + functionPath?: string; + name: string; + workflow?: string; +} + +/** + * Deduplicated cron schedules — mirror of wrangler's `triggers.crons`. The + * Lunora vite plugin keeps `wrangler.jsonc` in sync with this array. + */ +export const LUNORA_CRON_TRIGGERS: ReadonlyArray = []; + +/** + * Dispatcher map keyed by cron expression. The Worker's `scheduled()` handler + * looks up `event.cron` here and dispatches every job in the list. + */ +export const LUNORA_CRONS: Record> = {}; diff --git a/lunora/_generated/dataModel.ts b/lunora/_generated/dataModel.ts new file mode 100644 index 00000000..e05ca3d4 --- /dev/null +++ b/lunora/_generated/dataModel.ts @@ -0,0 +1,285 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +import type { + DatabaseReaderFacade as DatabaseReaderFacadeOf, + DatabaseWriterFacade as DatabaseWriterFacadeOf, + LoadWith as LoadWithOf, + TableReaderFacade as TableReaderFacadeOf, + TableWriterFacade as TableWriterFacadeOf, + WithArg as WithArgOf, +} from "lunorash/server/data-model"; + +export type { + AggregateOp, + GroupByEntry, + OrderBy, + QueryArgs, + QueryPage, + RankPage, + RankResult, + RestrictableQueryOptions, + RestrictableQueryOptionsOf, + SearchFilterBuilder, + SearchReader, + TableAggregateOptions, + TableAggregateOptionsOf, + TableGroupByOptions, + TableGroupByOptionsOf, + TableRankOptions, + TableRankPageOptions, + Where, + WhereOf, + WhereOperators, +} from "lunorash/server/data-model"; + +export type TableName = "nodes" | "tagColors" | "savedQueries" | "dailyIndex" | "ratelimit_buckets"; + +export type Id = string & { readonly __table: TName }; + +export interface Doc_nodes { + _id: Id<"nodes">; + _creationTime: number; + parentId: string; + prevSiblingId: string; + text: string; + isTask: boolean; + completed: boolean; + collapsed: boolean; + bookmarkedAt: number; + mirrorOf: string; + createdAt: number; + updatedAt: number; + origin: string; + kind: "paragraph"; + userId: string; +} + +export interface Doc_tagColors { + _id: Id<"tagColors">; + _creationTime: number; + tag: string; + color: string; + userId: string; +} + +export interface Doc_savedQueries { + _id: Id<"savedQueries">; + _creationTime: number; + name: string; + query: string; + createdAt: number; + userId: string; +} + +export interface Doc_dailyIndex { + _id: Id<"dailyIndex">; + _creationTime: number; + key: string; + nodeId: string; + touchedAt: number; + userId: string; +} + +export interface Doc_ratelimit_buckets { + _id: Id<"ratelimit_buckets">; + _creationTime: number; + key: string; + value: number; + ts: number; + prev?: number; +} + +export interface DataModel { + nodes: Doc_nodes; + tagColors: Doc_tagColors; + savedQueries: Doc_savedQueries; + dailyIndex: Doc_dailyIndex; + ratelimit_buckets: Doc_ratelimit_buckets; +} + +export type Doc = DataModel[T]; + +/** + * Per-table index name union. `never` for tables without secondary indexes. + * Used by `TableReader.withIndex()` to constrain callers to declared names. + */ +export interface IndexNamesByTable { + nodes: "by_parent"; + tagColors: "by_tag"; + savedQueries: never; + dailyIndex: "by_key"; + ratelimit_buckets: "by_key"; +} + +export type IndexName = IndexNamesByTable[T]; + +/** Per-table search-index name union. `never` for tables without searchIndex. */ +export interface SearchIndexNamesByTable { + nodes: never; + tagColors: never; + savedQueries: never; + dailyIndex: never; + ratelimit_buckets: never; +} + +export type SearchIndexName = SearchIndexNamesByTable[T]; + +/** Per-table rank-index name union. `never` for tables without a rankIndex. */ +export interface RankIndexNamesByTable { + nodes: never; + tagColors: never; + savedQueries: never; + dailyIndex: never; + ratelimit_buckets: never; +} + +export type RankIndexName = RankIndexNamesByTable[T]; + +/** Per-table geo-index name union. `never` for tables without a geoIndex. */ +export interface GeoIndexNamesByTable { + nodes: never; + tagColors: never; + savedQueries: never; + dailyIndex: never; + ratelimit_buckets: never; +} + +export type GeoIndexName = GeoIndexNamesByTable[T]; + +/** Union of declared vector index names. `never` when none are declared. */ +export type VectorIndexName = never; + +export interface Insert_nodes { + _id?: Id<"nodes">; + _creationTime?: number; + parentId: string; + prevSiblingId: string; + text: string; + isTask: boolean; + completed: boolean; + collapsed: boolean; + bookmarkedAt: number; + mirrorOf: string; + createdAt: number; + updatedAt: number; + origin: string; + kind: "paragraph"; + userId: string; +} + +export interface Insert_tagColors { + _id?: Id<"tagColors">; + _creationTime?: number; + tag: string; + color: string; + userId: string; +} + +export interface Insert_savedQueries { + _id?: Id<"savedQueries">; + _creationTime?: number; + name: string; + query: string; + createdAt: number; + userId: string; +} + +export interface Insert_dailyIndex { + _id?: Id<"dailyIndex">; + _creationTime?: number; + key: string; + nodeId: string; + touchedAt: number; + userId: string; +} + +export interface Insert_ratelimit_buckets { + _id?: Id<"ratelimit_buckets">; + _creationTime?: number; + key: string; + value: number; + ts: number; + prev?: number; +} + +/** Per-table insert shape, accepted by `ctx.db..insert(...)`. */ +export interface InsertModel { + nodes: Insert_nodes; + tagColors: Insert_tagColors; + savedQueries: Insert_savedQueries; + dailyIndex: Insert_dailyIndex; + ratelimit_buckets: Insert_ratelimit_buckets; +} + +export type Insert = InsertModel[T]; + +/** + * Phantom relation descriptors. They carry the relation kind and target table + * as type parameters only — there is no runtime value — so the `with` argument + * and its return type can be inferred from {@link Relations}. + */ +export interface OneRelation { + readonly __relationKind: "one"; + readonly __target: Target; +} + +export interface ManyRelation { + readonly __relationKind: "many"; + readonly __target: Target; +} + +/** Per-table relation map keyed by accessor name. `{}` for tables with none. */ +export interface Relations { + nodes: {}; + tagColors: {}; + savedQueries: {}; + dailyIndex: {}; + ratelimit_buckets: {}; +} + +/** The `with` argument for table `T` — see `@lunora/server/data-model`. */ +export type WithArg = WithArgOf; + +/** `Doc` narrowed to exactly the relations requested in the with-arg `W`. */ +export type LoadWith = LoadWithOf; + +/** Read-only typed table accessor exposed on `QueryCtx.db.
`. */ +export type TableReaderFacade = TableReaderFacadeOf; + +/** Read-write typed table accessor exposed on `MutationCtx.db.
` / `ActionCtx.db.
`. */ +export type TableWriterFacade = TableWriterFacadeOf; + +/** Per-table read facade — `ctx.db.
` on a `QueryCtx`. */ +export type DatabaseReaderFacade = DatabaseReaderFacadeOf; + +/** Per-table read-write facade — `ctx.db.
` on a `MutationCtx` / `ActionCtx`. */ +export type DatabaseWriterFacade = DatabaseWriterFacadeOf; + +/** Insert builder returned by `ctx.orm.insert(table)`. */ +export interface OrmInsertBuilder { + values: (values: Insert) => Promise>; +} + +/** Replace builder returned by `ctx.orm.replace(table, id)` — swaps the whole document. */ +export interface OrmReplaceBuilder { + with: (values: Insert) => Promise; +} + +/** Update builder returned by `ctx.orm.update(table, id)` — patches the named fields. */ +export interface OrmUpdateBuilder { + set: (values: Partial>) => Promise; +} + +/** Read-only ORM surface — `ctx.orm` on a `QueryCtx`. Mirrors `ctx.db` reads under a kitcn-style `query` namespace. */ +export interface OrmReader { + query: DatabaseReaderFacade; +} + +/** Read-write ORM surface — `ctx.orm` on a `MutationCtx` / `ActionCtx`. Writes are addressed by id, like `ctx.db`. */ +export interface OrmWriter extends OrmReader { + delete: (table: T, id: Id) => Promise; + insert: (table: T) => OrmInsertBuilder; + replace: (table: T, id: Id) => OrmReplaceBuilder; + update: (table: T, id: Id) => OrmUpdateBuilder; +} diff --git a/lunora/_generated/drizzle.global.ts b/lunora/_generated/drizzle.global.ts new file mode 100644 index 00000000..208ad136 --- /dev/null +++ b/lunora/_generated/drizzle.global.ts @@ -0,0 +1,4 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +export {}; diff --git a/lunora/_generated/drizzle.shard.ts b/lunora/_generated/drizzle.shard.ts new file mode 100644 index 00000000..4db174c6 --- /dev/null +++ b/lunora/_generated/drizzle.shard.ts @@ -0,0 +1,65 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +import { index, integer, real, sqliteTable, text } from "lunorash/server/drizzle"; + +export const nodes = sqliteTable("nodes", { + _id: text("_id").primaryKey(), + _creationTime: integer("_creationTime").notNull(), + parentId: text("parentId").notNull(), + prevSiblingId: text("prevSiblingId").notNull(), + text: text("text").notNull(), + isTask: integer("isTask", { mode: "boolean" }).notNull(), + completed: integer("completed", { mode: "boolean" }).notNull(), + collapsed: integer("collapsed", { mode: "boolean" }).notNull(), + bookmarkedAt: real("bookmarkedAt").notNull(), + mirrorOf: text("mirrorOf").notNull(), + createdAt: real("createdAt").notNull(), + updatedAt: real("updatedAt").notNull(), + origin: text("origin").notNull(), + kind: text("kind").notNull(), + userId: text("userId").notNull(), +}, (t) => ({ + by_parent: index("by_parent").on(t.parentId), +})); + +export const tagColors = sqliteTable("tagColors", { + _id: text("_id").primaryKey(), + _creationTime: integer("_creationTime").notNull(), + tag: text("tag").notNull(), + color: text("color").notNull(), + userId: text("userId").notNull(), +}, (t) => ({ + by_tag: index("by_tag").on(t.tag), +})); + +export const savedQueries = sqliteTable("savedQueries", { + _id: text("_id").primaryKey(), + _creationTime: integer("_creationTime").notNull(), + name: text("name").notNull(), + query: text("query").notNull(), + createdAt: real("createdAt").notNull(), + userId: text("userId").notNull(), +}); + +export const dailyIndex = sqliteTable("dailyIndex", { + _id: text("_id").primaryKey(), + _creationTime: integer("_creationTime").notNull(), + key: text("key").notNull(), + nodeId: text("nodeId").notNull(), + touchedAt: real("touchedAt").notNull(), + userId: text("userId").notNull(), +}, (t) => ({ + by_key: index("by_key").on(t.key), +})); + +export const ratelimit_buckets = sqliteTable("ratelimit_buckets", { + _id: text("_id").primaryKey(), + _creationTime: integer("_creationTime").notNull(), + key: text("key").notNull(), + value: real("value").notNull(), + ts: real("ts").notNull(), + prev: real("prev"), +}, (t) => ({ + by_key: index("by_key").on(t.key), +})); diff --git a/lunora/_generated/functions.ts b/lunora/_generated/functions.ts new file mode 100644 index 00000000..1f4cd978 --- /dev/null +++ b/lunora/_generated/functions.ts @@ -0,0 +1,201 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +import * as lunora_mcp_0 from "../mcp.js"; +import * as lunora_mutators_1 from "../mutators.js"; +import * as lunora_shapes_2 from "../shapes.js"; + +import { DEFER_VALIDATION as DEFER, installCompiledValidatorMap } from "lunorash/values"; +import type { RegisteredShape } from "lunorash/server"; +import { LunoraError } from "lunorash/server"; +import type { ActionCtx, MutationCtx, QueryCtx } from "./server.js"; + +/** + * Single registered function, narrowed to the shape `handleRpc` needs. + * The real argument validators / return types are checked elsewhere — at + * the dispatch site we erase to `unknown` so a single map can host every + * registered function. + */ +export interface RegisteredLunoraFunction { + kind: "action" | "mutation" | "query" | "stream"; + args: Record; + /** + * For `"action" | "mutation" | "query"` the handler is awaited and its result returned. + * For `"stream"` the handler returns an `AsyncIterable` synchronously and takes an + * `AbortSignal` as a third argument — the runtime drives it frame-by-frame. + */ + handler: ((context: unknown, args: Record) => Promise | unknown) | ((context: unknown, args: Record, signal?: AbortSignal) => AsyncIterable); + /** `"internal"` functions are rejected on the external RPC path; absence === public. */ + visibility?: "internal" | "public"; +} + +/** + * Static dispatch table. The key matches the `__lunoraRef` the client + * emits (`api[namespace][fn].__lunoraRef === "namespace:fn"`). + */ +export const LUNORA_FUNCTIONS: Record = { + "mcp:applyChangeOps": lunora_mcp_0.applyChangeOps as unknown as RegisteredLunoraFunction, + "mcp:listDailyIndex": lunora_mcp_0.listDailyIndex as unknown as RegisteredLunoraFunction, + "mcp:listNodes": lunora_mcp_0.listNodes as unknown as RegisteredLunoraFunction, + "mcp:wipeUserShard": lunora_mcp_0.wipeUserShard as unknown as RegisteredLunoraFunction, + "mutators:appendChild": lunora_mutators_1.appendChild as unknown as RegisteredLunoraFunction, + "mutators:claimDailyMapping": lunora_mutators_1.claimDailyMapping as unknown as RegisteredLunoraFunction, + "mutators:deleteDailyMapping": lunora_mutators_1.deleteDailyMapping as unknown as RegisteredLunoraFunction, + "mutators:deleteSavedQuery": lunora_mutators_1.deleteSavedQuery as unknown as RegisteredLunoraFunction, + "mutators:deleteTagColor": lunora_mutators_1.deleteTagColor as unknown as RegisteredLunoraFunction, + "mutators:hello": lunora_mutators_1.hello as unknown as RegisteredLunoraFunction, + "mutators:importNodes": lunora_mutators_1.importNodes as unknown as RegisteredLunoraFunction, + "mutators:indent": lunora_mutators_1.indent as unknown as RegisteredLunoraFunction, + "mutators:indentMany": lunora_mutators_1.indentMany as unknown as RegisteredLunoraFunction, + "mutators:insertChildAtStart": lunora_mutators_1.insertChildAtStart as unknown as RegisteredLunoraFunction, + "mutators:insertSibling": lunora_mutators_1.insertSibling as unknown as RegisteredLunoraFunction, + "mutators:materializeDailyNodes": lunora_mutators_1.materializeDailyNodes as unknown as RegisteredLunoraFunction, + "mutators:mirrorNode": lunora_mutators_1.mirrorNode as unknown as RegisteredLunoraFunction, + "mutators:moveMany": lunora_mutators_1.moveMany as unknown as RegisteredLunoraFunction, + "mutators:moveNode": lunora_mutators_1.moveNode as unknown as RegisteredLunoraFunction, + "mutators:outdent": lunora_mutators_1.outdent as unknown as RegisteredLunoraFunction, + "mutators:outdentMany": lunora_mutators_1.outdentMany as unknown as RegisteredLunoraFunction, + "mutators:patchSavedQuery": lunora_mutators_1.patchSavedQuery as unknown as RegisteredLunoraFunction, + "mutators:removeMany": lunora_mutators_1.removeMany as unknown as RegisteredLunoraFunction, + "mutators:removeNode": lunora_mutators_1.removeNode as unknown as RegisteredLunoraFunction, + "mutators:restoreNodes": lunora_mutators_1.restoreNodes as unknown as RegisteredLunoraFunction, + "mutators:seedIfEmpty": lunora_mutators_1.seedIfEmpty as unknown as RegisteredLunoraFunction, + "mutators:setBookmarkedAt": lunora_mutators_1.setBookmarkedAt as unknown as RegisteredLunoraFunction, + "mutators:setCollapsed": lunora_mutators_1.setCollapsed as unknown as RegisteredLunoraFunction, + "mutators:setCompleted": lunora_mutators_1.setCompleted as unknown as RegisteredLunoraFunction, + "mutators:setIsTask": lunora_mutators_1.setIsTask as unknown as RegisteredLunoraFunction, + "mutators:setKind": lunora_mutators_1.setKind as unknown as RegisteredLunoraFunction, + "mutators:setText": lunora_mutators_1.setText as unknown as RegisteredLunoraFunction, + "mutators:splitNode": lunora_mutators_1.splitNode as unknown as RegisteredLunoraFunction, + "mutators:upsertDailyMapping": lunora_mutators_1.upsertDailyMapping as unknown as RegisteredLunoraFunction, + "mutators:upsertSavedQuery": lunora_mutators_1.upsertSavedQuery as unknown as RegisteredLunoraFunction, + "mutators:upsertTagColor": lunora_mutators_1.upsertTagColor as unknown as RegisteredLunoraFunction, +}; + +/** + * AOT-compiled argument validators (Worker-safe, no `eval`). Each is installed + * onto its function's live `.args` object and consulted by the interpreted + * parser as a zero-allocation fast path; anything it can't model is deferred. + */ +installCompiledValidatorMap(lunora_mcp_0.listDailyIndex.args, (source) => { +if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER; +if (typeof source["userId"] !== "string") return DEFER; +return { "userId": source["userId"] }; +}); +installCompiledValidatorMap(lunora_mcp_0.listNodes.args, (source) => { +if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER; +if (typeof source["userId"] !== "string") return DEFER; +return { "userId": source["userId"] }; +}); +installCompiledValidatorMap(lunora_mcp_0.wipeUserShard.args, (source) => { +if (typeof source !== "object" || source === null || Array.isArray(source)) return DEFER; +if (typeof source["userId"] !== "string") return DEFER; +return { "userId": source["userId"] }; +}); + +/** + * Replication-shape registry — one entry per `defineShape` in `lunora/shapes.ts`. + * The generated ShardDO's `resolveShape` override looks a shape up by name and + * evaluates its trusted `compileWhere(ctx, args)` to authorize + scope a + * `shape_subscribe` (reads-as-permissions). + */ +export const LUNORA_SHAPES: Record = { + "userDailyIndex": lunora_shapes_2.userDailyIndex as unknown as RegisteredShape, + "userSavedQueries": lunora_shapes_2.userSavedQueries as unknown as RegisteredShape, + "userTagColors": lunora_shapes_2.userTagColors as unknown as RegisteredShape, + "wholeOutline": lunora_shapes_2.wholeOutline as unknown as RegisteredShape, +}; + +/** + * Custom-mutator function paths — the `LUNORA_FUNCTIONS` keys the generated + * ShardDO's `isCustomMutator` override routes through the client-watermark push + * protocol (`x-lunora-client-id`/`x-lunora-client-seq` ordering). + */ +export const LUNORA_MUTATOR_PATHS: ReadonlySet = new Set(["mutators:appendChild", "mutators:claimDailyMapping", "mutators:deleteDailyMapping", "mutators:deleteSavedQuery", "mutators:deleteTagColor", "mutators:hello", "mutators:importNodes", "mutators:indent", "mutators:indentMany", "mutators:insertChildAtStart", "mutators:insertSibling", "mutators:materializeDailyNodes", "mutators:mirrorNode", "mutators:moveMany", "mutators:moveNode", "mutators:outdent", "mutators:outdentMany", "mutators:patchSavedQuery", "mutators:removeMany", "mutators:removeNode", "mutators:restoreNodes", "mutators:seedIfEmpty", "mutators:setBookmarkedAt", "mutators:setCollapsed", "mutators:setCompleted", "mutators:setIsTask", "mutators:setKind", "mutators:setText", "mutators:splitNode", "mutators:upsertDailyMapping", "mutators:upsertSavedQuery", "mutators:upsertTagColor"]); + +/** + * Connection-lifecycle manifest: the function paths the generated ShardDO + * dispatches when a client's WebSocket connects (`connect`) or disconnects + * (`disconnect`). Each path also resolves through {@link LUNORA_FUNCTIONS}; the + * DO runs every hook under the socket's verified identity via system dispatch. + */ +export const LUNORA_LIFECYCLE_HOOKS: { connect: readonly string[]; disconnect: readonly string[] } = { + connect: [], + disconnect: [], +}; + +/** + * Resolve and invoke a registered function from an external caller. Throws a + * LunoraError-shaped object (404) when the path is unknown — the runtime's + * structural error mapper turns that into the right HTTP status. Internal + * functions are treated as not-found so their existence never leaks to clients. + */ +export const dispatchLunoraFunction = async (functionPath: string, context: unknown, args: Record): Promise => { + const registered = LUNORA_FUNCTIONS[functionPath]; + + if (!registered || registered.visibility === "internal") { + throw new LunoraError("FUNCTION_NOT_FOUND", `function not registered: ${functionPath}`); + } + + return registered.handler(context, args); +}; + +/** + * A handler context accepted by {@link createCaller}. The runtime context the + * shard DO builds is uniform across kinds, so any handler's `ctx` works here. + */ +export type CallerCtx = ActionCtx | MutationCtx | QueryCtx; + +/** + * Typed, in-process server-to-server caller. Every registered function — public + * *and* internal — is reachable; each call dispatches against the same shard + * with the supplied `context`, exactly like `ctx.runQuery`/`runMutation`/ + * `runAction` but without re-stating the function path. + */ +export interface Caller { + mcp: { + applyChangeOps: (args: { userId: string; ops: Array }) => Promise<{ count: number; deletes?: undefined; inserts?: undefined; patches?: undefined; } | { count: number; deletes: number; inserts: number; patches: number; }>; + listDailyIndex: (args: { userId: string }) => Promise<{ key: string; nodeId: string; }[]>; + listNodes: (args: { userId: string }) => Promise<{ id: string; parentId: string | null; prevSiblingId: string | null; text: string; isTask: boolean; completed: boolean; collapsed: boolean; bookmarkedAt: number | null; mirrorOf: string | null; createdAt: number; updatedAt: number; origin: string | null; kind: "paragraph" | null }[]>; + wipeUserShard: (args: { userId: string }) => Promise<{ deleted: number; }>; + }; +} + +const callRegistered = async (context: CallerCtx, functionPath: string, args: Record | undefined): Promise => { + const registered = LUNORA_FUNCTIONS[functionPath]; + + if (!registered) { + throw new LunoraError("FUNCTION_NOT_FOUND", `function not registered: ${functionPath}`); + } + + return (await registered.handler(context, args ?? {})) as R; +}; + +/** Build a {@link Caller} bound to `context` (typically a handler's `ctx`). */ +export const createCaller = (context: CallerCtx): Caller => ({ + mcp: { + applyChangeOps: (args) => callRegistered(context, "mcp:applyChangeOps", args), + listDailyIndex: (args) => callRegistered(context, "mcp:listDailyIndex", args), + listNodes: (args) => callRegistered(context, "mcp:listNodes", args), + wipeUserShard: (args) => callRegistered(context, "mcp:wipeUserShard", args), + }, +}); + +/** + * Single registered data migration, narrowed to the shape the per-shard runner + * consumes. `up`/`down` are erased to a structural transform; the authoring + * validation lives in `defineMigration`. + */ +export interface RegisteredDataMigration { + batchSize?: number; + down?: (document: Record) => Record | undefined; + id: string; + table: string; + up: (document: Record) => Record | undefined; +} + +/** + * Registry of online data migrations keyed by `defineMigration`'s `id`. The + * shard DO's admin RPC and the CLI resolve migrations to run through this map. + */ +export const LUNORA_MIGRATIONS: Record = {}; diff --git a/lunora/_generated/openapi.json b/lunora/_generated/openapi.json new file mode 100644 index 00000000..18e34e01 --- /dev/null +++ b/lunora/_generated/openapi.json @@ -0,0 +1,66 @@ +{ + "components": { + "responses": { + "LunoraError": { + "content": { + "application/json": { + "schema": { + "additionalProperties": false, + "description": "Standard Lunora error envelope.", + "properties": { + "error": { + "additionalProperties": false, + "properties": { + "code": { + "description": "Machine-readable error code. Clients switch on this value.", + "enum": [ + "BAD_REQUEST", + "CONFLICT", + "COUNT_RLS_UNSUPPORTED", + "FORBIDDEN", + "FUNCTION_NOT_FOUND", + "INTERNAL", + "INTERNAL_SERVER_ERROR", + "METHOD_NOT_ALLOWED", + "NOT_FOUND", + "NOT_IMPLEMENTED", + "PAYLOAD_TOO_LARGE", + "TOO_MANY_REQUESTS", + "UNAUTHORIZED", + "UNPROCESSABLE", + "VALIDATION_ERROR" + ], + "type": "string" + }, + "message": { + "description": "Human-readable error message (never echoes internal details).", + "type": "string" + } + }, + "required": [ + "code", + "message" + ], + "type": "object" + } + }, + "required": [ + "error" + ], + "type": "object" + } + } + }, + "description": "A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)." + } + } + }, + "info": { + "description": "Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.", + "title": "Lunora API", + "version": "1.8.0" + }, + "openapi": "3.1.0", + "paths": {}, + "tags": [] +} diff --git a/lunora/_generated/openapi.ts b/lunora/_generated/openapi.ts new file mode 100644 index 00000000..d72182ab --- /dev/null +++ b/lunora/_generated/openapi.ts @@ -0,0 +1,69 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +export const openApiSpec: Record = { + "components": { + "responses": { + "LunoraError": { + "content": { + "application/json": { + "schema": { + "additionalProperties": false, + "description": "Standard Lunora error envelope.", + "properties": { + "error": { + "additionalProperties": false, + "properties": { + "code": { + "description": "Machine-readable error code. Clients switch on this value.", + "enum": [ + "BAD_REQUEST", + "CONFLICT", + "COUNT_RLS_UNSUPPORTED", + "FORBIDDEN", + "FUNCTION_NOT_FOUND", + "INTERNAL", + "INTERNAL_SERVER_ERROR", + "METHOD_NOT_ALLOWED", + "NOT_FOUND", + "NOT_IMPLEMENTED", + "PAYLOAD_TOO_LARGE", + "TOO_MANY_REQUESTS", + "UNAUTHORIZED", + "UNPROCESSABLE", + "VALIDATION_ERROR" + ], + "type": "string" + }, + "message": { + "description": "Human-readable error message (never echoes internal details).", + "type": "string" + } + }, + "required": [ + "code", + "message" + ], + "type": "object" + } + }, + "required": [ + "error" + ], + "type": "object" + } + } + }, + "description": "A Lunora error response. The HTTP status reflects the error code (e.g. BAD_REQUEST→400, UNAUTHORIZED→401, FORBIDDEN→403, NOT_FOUND→404)." + } + } + }, + "info": { + "description": "Auto-generated from @lunora/values-typed functions by @lunora/codegen. Do not edit — run `lunora codegen` to regenerate.", + "title": "Lunora API", + "version": "1.8.0" + }, + "openapi": "3.1.0", + "paths": {}, + "tags": [] +}; diff --git a/lunora/_generated/server.ts b/lunora/_generated/server.ts new file mode 100644 index 00000000..1d8eb875 --- /dev/null +++ b/lunora/_generated/server.ts @@ -0,0 +1,146 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +import { createPolicyDsl, initLunora, v as vBase } from "lunorash/server"; +import type { + ActionBuilder, + ActionCtx as ActionCtxBase, + ColumnValidator, + DatabaseReader, + DatabaseWriter, + EmptyArgs, + InternalActionBuilder, + InternalMutationBuilder, + InternalQueryBuilder, + MutationBuilder, + MutationCtx as MutationCtxBase, + QueryBuilder, + QueryCtx as QueryCtxBase, + ReadOnlyStorage, + Storage as StorageBase, + TableReader, +} from "lunorash/server"; + +import type { DataModel, DatabaseReaderFacade, DatabaseWriterFacade, Doc, Id as IdOfTable, OrmReader, OrmWriter, Relations, TableName } from "./dataModel.js"; + +export type { DataModel, Doc, Id, TableName } from "./dataModel.js"; + +/** Storage buckets this schema declares (`v.storage("name")`), narrowing `ctx.storage.bucket(name)`. */ +export type StorageBucketName = "default"; + +/** + * This project's Cloudflare bindings, as far as codegen can discover them from + * `lunora/` source — the container/workflow Durable Object namespaces and the + * conventional Workers AI binding. Bindings the config layer reconciles from + * user-named wrangler config (R2/KV/D1/`services`/queues/…) aren't statically + * visible here, so the open index signature keeps them reachable (cast at the + * use site). Service bindings (`env..fetch(...)` / RPC stubs) live + * under this signature too — Lunora can't type a third-party worker's RPC + * surface, so treat them as `Fetcher`/`Service` and cast. + */ +export interface CloudflareBindings { + readonly [binding: string]: unknown; +} + +/** Alias for {@link CloudflareBindings} — the typed shape of `env`. */ +export type Env = CloudflareBindings; + +/** + * Project-typed contexts. The base contexts from `@lunora/server` are + * untyped against the schema; here `db` is widened to the generated per-table + * facade (`ctx.db.
.findMany(...)`) while keeping the legacy structural + * `db.get`/`db.query` surface for back-compat, and `storage` is narrowed so + * `ctx.storage.bucket(name)` autocompletes the declared buckets. + */ +/** + * The Convex-style fluent reader `ctx.db.query(table)`, bound to this schema: + * a table-name literal narrows the row type, so `.collect()` / `.first()` / + * `.take()` (and the `.withIndex()` / `.filter()` / `.order()` chain) resolve + * as `Doc
` with no `as unknown as Doc<...>` casts. The per-table accessor + * `ctx.db.
` stays available alongside it via the facade. + * + * Intersected with the wide `(string) => TableReader` signature so the bound + * `ctx.db` is still structurally assignable to schema-agnostic consumers that + * call `db.query(someString)` (e.g. `@lunora/ratelimit`'s `createDbStore`). + */ +type TypedTableQuery = ((table: T) => TableReader>) & ((table: string) => TableReader); + +/** + * The point read `ctx.db.get(id)`, bound to this schema: an `Id<"table">` + * carries its table name, so the resolved document is typed `Doc
` (or + * `null` when absent) with no `as Doc<...>` cast. Mirrors {@link TypedTableQuery}. + */ +type TypedTableGet = (id: IdOfTable) => Promise | null>; + +export interface QueryCtx extends Omit { + readonly db: Omit & DatabaseReaderFacade & { query: TypedTableQuery; get: TypedTableGet }; + readonly orm: OrmReader; + readonly storage: ReadOnlyStorage; +} + +export interface MutationCtx extends Omit { + readonly db: Omit & DatabaseWriterFacade & { query: TypedTableQuery; get: TypedTableGet }; + readonly orm: OrmWriter; + readonly storage: ReadOnlyStorage; +} + +export interface ActionCtx extends Omit { + readonly db: Omit & DatabaseWriterFacade & { query: TypedTableQuery; get: TypedTableGet }; + readonly orm: OrmWriter; + readonly storage: StorageBase; +} + +/** + * Procedure builders bound to this project's typed contexts. Chain + * `.input({...})` to declare args, `.use(middleware)` for rate limiting / RLS / + * masking (each middleware may refine `ctx`), then the terminal + * `.query()` / `.mutation()` / `.action()` with a `({ ctx, args }) => ...` + * handler. `.output(validator)` and (queries) `.stream()` are also available. + */ +const lunoraBuilders = initLunora.dataModel().create(); + +/** `query` builder bound to this project's typed {@link QueryCtx}. */ +export const query = lunoraBuilders.query as unknown as QueryBuilder; + +/** `mutation` builder bound to this project's typed {@link MutationCtx}. */ +export const mutation = lunoraBuilders.mutation as unknown as MutationBuilder; + +/** `action` builder bound to this project's typed {@link ActionCtx}. */ +export const action = lunoraBuilders.action as unknown as ActionBuilder; + +/** `internalQuery` builder bound to this project's typed {@link QueryCtx} — never exposed on `api`. */ +export const internalQuery = lunoraBuilders.internalQuery as unknown as InternalQueryBuilder; + +/** `internalMutation` builder bound to this project's typed {@link MutationCtx} — never exposed on `api`. */ +export const internalMutation = lunoraBuilders.internalMutation as unknown as InternalMutationBuilder; + +/** `internalAction` builder bound to this project's typed {@link ActionCtx} — never exposed on `api`. */ +export const internalAction = lunoraBuilders.internalAction as unknown as InternalActionBuilder; + +/** + * `definePolicy` bound to THIS schema's {@link DataModel} + {@link Relations}. + * Import it from here (`./_generated/server`) instead of `@lunora/server` to get + * a relation-aware RLS authoring surface: `table` autocompletes to a real table + * name and the `when` predicate type-checks against the table's columns **and** + * its declared relations — `{ author: { is: {...} } }`, `{ posts: { some: {...} } }`, + * etc. (the `@lunora/do` pre-resolver resolves relation predicates on reads). + * Runtime-identical to `@lunora/server`'s `definePolicy`; only the types narrow, + * so the `rls()` chain discovers a policy authored either way the same. + */ +export const definePolicy = createPolicyDsl(); + +/** + * The validator builder `v`, with `v.id(...)` constrained to THIS schema's + * table names — so the argument autocompletes and returns a precise + * `Id<"table">`. Identical to `@lunora/server`'s `v` at runtime; the only + * difference is the tightened `id` type. + * + * Import `v` from here (`./_generated/server`) in your queries/mutations/actions + * to get table-name autocomplete. `lunora/schema.ts` can't use it — it is the + * file that defines the table names, so they aren't known yet there; pass the + * names as string literals and the generated `Id<"table">` types still catch a + * typo wherever the id is used. + */ +export const v = vBase as unknown as Omit & { + id: (table: T) => ColumnValidator, IdOfTable>; +}; diff --git a/lunora/_generated/shard.ts b/lunora/_generated/shard.ts new file mode 100644 index 00000000..3eab8300 --- /dev/null +++ b/lunora/_generated/shard.ts @@ -0,0 +1,899 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +import type { AdvisoryFinding, DatabaseWriterLike, DataMigrationLike, LogSink, MaskPoliciesResult, MigrationRunResult, RunShardApplyCdcArgs, RunShardMigrationArgs, RlsPoliciesResult, RunShardRankBeforeArgs, RunShardRankPageArgs, RunShardWriteArgs, RunShardWriteResult, SchedulerLike, SchemaLike, ShardDOState, ShardRankPageResult, SqlExec, StorageRulesResult, StudioFeaturesResult, SystemReaderStorageLike, WhereInput } from "lunorash/do"; +import { applyCdcChanges, assertShapeShardable, createShardCtxDb, runDataMigration, runShardMigrations, ShardDO as ShardDOBase } from "lunorash/do"; +import { asBucketStorage, buildRlsReadRegistry, composeShapeReadWhere, createSecrets, LunoraError } from "lunorash/server"; +import { bindOrm, bindTableFacade } from "lunorash/server"; + +import schema from "../schema.js"; +import { LUNORA_FUNCTIONS, LUNORA_LIFECYCLE_HOOKS, LUNORA_MIGRATIONS, LUNORA_MUTATOR_PATHS, LUNORA_SHAPES } from "./functions.js"; + +type FunctionKind = "action" | "mutation" | "query"; + +interface FunctionReference { + __lunoraRef: string; +} + +/** Foreign-key columns per table (`v.id("target")` fields) for the data browser. */ +const LUNORA_TABLE_REFS: Record> = {}; + +/** Declared indexes per table (secondary, search, geo, rank, vector) for the schema viewer. */ +const LUNORA_TABLE_INDEXES: Record> = { + "nodes": [ + { + "fields": [ + "parentId" + ], + "name": "by_parent", + "type": "index" + } + ], + "tagColors": [ + { + "fields": [ + "tag" + ], + "name": "by_tag", + "type": "index" + } + ], + "dailyIndex": [ + { + "fields": [ + "key" + ], + "name": "by_key", + "type": "index" + } + ], + "ratelimit_buckets": [ + { + "fields": [ + "key" + ], + "name": "by_key", + "type": "index" + } + ] +}; + +/** Columns per table (typed, with PK/FK markers) for the studio's schema diagram, served via `__lunora_admin__:describeTable`. */ +const LUNORA_TABLE_COLUMNS: Record> = { + "nodes": [ + { + "name": "_id", + "optional": false, + "pk": true, + "type": "id" + }, + { + "name": "_creationTime", + "optional": false, + "type": "number" + }, + { + "name": "parentId", + "optional": false, + "type": "string" + }, + { + "name": "prevSiblingId", + "optional": false, + "type": "string" + }, + { + "name": "text", + "optional": false, + "type": "string" + }, + { + "name": "isTask", + "optional": false, + "type": "boolean" + }, + { + "name": "completed", + "optional": false, + "type": "boolean" + }, + { + "name": "collapsed", + "optional": false, + "type": "boolean" + }, + { + "name": "bookmarkedAt", + "optional": false, + "type": "number" + }, + { + "name": "mirrorOf", + "optional": false, + "type": "string" + }, + { + "name": "createdAt", + "optional": false, + "type": "number" + }, + { + "name": "updatedAt", + "optional": false, + "type": "number" + }, + { + "name": "origin", + "optional": false, + "type": "string" + }, + { + "name": "kind", + "optional": false, + "type": "literal" + }, + { + "name": "userId", + "optional": false, + "type": "string" + } + ], + "tagColors": [ + { + "name": "_id", + "optional": false, + "pk": true, + "type": "id" + }, + { + "name": "_creationTime", + "optional": false, + "type": "number" + }, + { + "name": "tag", + "optional": false, + "type": "string" + }, + { + "name": "color", + "optional": false, + "type": "string" + }, + { + "name": "userId", + "optional": false, + "type": "string" + } + ], + "savedQueries": [ + { + "name": "_id", + "optional": false, + "pk": true, + "type": "id" + }, + { + "name": "_creationTime", + "optional": false, + "type": "number" + }, + { + "name": "name", + "optional": false, + "type": "string" + }, + { + "name": "query", + "optional": false, + "type": "string" + }, + { + "name": "createdAt", + "optional": false, + "type": "number" + }, + { + "name": "userId", + "optional": false, + "type": "string" + } + ], + "dailyIndex": [ + { + "name": "_id", + "optional": false, + "pk": true, + "type": "id" + }, + { + "name": "_creationTime", + "optional": false, + "type": "number" + }, + { + "name": "key", + "optional": false, + "type": "string" + }, + { + "name": "nodeId", + "optional": false, + "type": "string" + }, + { + "name": "touchedAt", + "optional": false, + "type": "number" + }, + { + "name": "userId", + "optional": false, + "type": "string" + } + ], + "ratelimit_buckets": [ + { + "name": "_id", + "optional": false, + "pk": true, + "type": "id" + }, + { + "name": "_creationTime", + "optional": false, + "type": "number" + }, + { + "name": "key", + "optional": false, + "type": "string" + }, + { + "name": "value", + "optional": false, + "type": "number" + }, + { + "name": "ts", + "optional": false, + "type": "number" + }, + { + "name": "prev", + "optional": true, + "type": "number" + } + ] +}; + +/** Storage-key columns per table (`v.storage(...)` fields) for the file browser's records↔files join. */ +const LUNORA_STORAGE_COLUMNS: Record = {}; + +/** Declarative TTL policies (`.ttl(field, { after? })`) the DO alarm sweep auto-expires rows for. */ +const LUNORA_TTL_SWEEPS: Array<{ after?: number; field: string; softDeleteField?: string; table: string }> = []; + +/** Static schema advisories (computed by @lunora/advisor at codegen time) served via `__lunora_admin__:getAdvisories`. */ +const LUNORA_ADVISORIES: AdvisoryFinding[] = [ + { + "cacheKey": "table_without_insert:nodes", + "categories": [ + "SCHEMA" + ], + "description": "No function inserts into this table via `ctx.db.insert(\"
\", …)`. It may be read-only by design (seeded by a migration, replicated, or written through a path the advisor can't see) — or it may be dead schema.", + "detail": "No function calls `ctx.db.insert(\"nodes\", …)` — table \"nodes\" has no discovered insert path.", + "facing": "INTERNAL", + "level": "INFO", + "metadata": { + "table": "nodes" + }, + "name": "table_without_insert", + "remediation": "If the table should be writable, add a mutation that calls `ctx.db.insert(\"
\", …)`. If it is read-only or seeded elsewhere, this advisory can be ignored.", + "title": "Table has no insert path" + }, + { + "cacheKey": "plaintext_secret_in_wrangler_vars:wrangler.jsonc:SENTRY_DSN", + "categories": [ + "SECURITY" + ], + "description": "A plaintext secret is committed to `wrangler.jsonc`'s `vars` block. `vars` are cleartext — baked into the deployed Worker and checked into source control — so the secret leaks via the repo and the bundle, and rotating it needs a config edit plus a redeploy.", + "detail": "The `vars` entry `SENTRY_DSN` in wrangler.jsonc holds a plaintext hex secret (http…(95 chars)). `vars` ship in cleartext to the deployed Worker and are committed to source control — move it to a Secrets Store binding or `wrangler secret put` and rotate the exposed value.", + "facing": "INTERNAL", + "level": "ERROR", + "metadata": { + "file": "wrangler.jsonc", + "key": "SENTRY_DSN", + "kind": "hex_secret", + "preview": "http…(95 chars)" + }, + "name": "plaintext_secret_in_wrangler_vars", + "remediation": "Move the value out of `vars`: bind it through a Secrets Store (`ctx.secrets.get()`) or set it with `wrangler secret put ` and read it from `env.`. Delete the `vars` entry and rotate the exposed value — assume it is already compromised. Public/publishable keys (name them `*_PUBLIC` / `*_PUBLISHABLE`) are exempt.", + "title": "Plaintext secret in wrangler vars" + } +]; + +/** Read-only RLS metadata (policies + roles discovered from `.use(rls(...))` chains) served via `__lunora_admin__:rlsPolicies` for the studio's RLS inspector. */ +const LUNORA_RLS_METADATA: RlsPoliciesResult = { + "policies": [], + "roles": [] +}; + +/** Read-only masking metadata (table + column + strategy discovered from `.use(mask(...))` chains) served via `__lunora_admin__:maskPolicies` for the studio's data-browser mask preview. */ +const LUNORA_MASK_METADATA: MaskPoliciesResult = { + "columns": [] +}; + +/** Read-only storage access-rule metadata (discovered from `.use(storageRules(...))` chains) served via `__lunora_admin__:storageRules` for the studio's access-rules view. */ +const LUNORA_STORAGE_RULES: StorageRulesResult = { + "rules": [] +}; + +/** Which optional package-backed features this app wires up (discovered from imports / `ctx.*` reads / schema signals) served via `__lunora_admin__:studioFeatures` so the studio hides nav pages whose package isn't enabled. */ +const LUNORA_STUDIO_FEATURES: StudioFeaturesResult = { + "analytics": false, + "auth": false, + "containers": false, + "flags": false, + "kv": false, + "mail": false, + "payments": false, + "queues": false, + "scheduler": false, + "storage": false, + "vectors": false, + "workflows": false +}; + +/** Per-table RLS read policies (hoisted from `.use(rls(...))` chains) the shape resolver AND-merges into each `defineShape` predicate so partial replication honours read policies. */ +const LUNORA_RLS_READ_REGISTRY = buildRlsReadRegistry(Object.values(LUNORA_FUNCTIONS)); + +export interface ShardDOConfig { + /** Opt into change-data-capture: records a post-image to `__cdc_log` on every write (backs streaming export + replay-PITR). */ + cdc?: boolean; + /** Optional telemetry sink. When supplied, each `ctx.log.*` call is forwarded to `sink.onLog`. Pass the SAME sink you give `createWorker({ observability })` (which drives `onRpc`) to route both RPC and log events. */ + observability?: (env: Record) => LogSink | undefined; + scheduler?: (env: Record) => unknown; + storage?: (env: Record) => unknown; +} + +const schedulerStub = { + cancel: async () => { + throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO()."); + }, + runAfter: async () => { + throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO()."); + }, + runAt: async () => { + throw new Error("ctx.scheduler: no scheduler configured. Pass `scheduler` to createShardDO()."); + }, +}; + +const storageStub = { + delete: async () => { + throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO()."); + }, + download: async () => { + throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO()."); + }, + getMetadata: async () => { + throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO()."); + }, + getSignedUrl: async () => { + throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO()."); + }, + getUrl: () => { + throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO()."); + }, + list: async () => { + throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO()."); + }, + upload: async () => { + throw new Error("ctx.storage: no storage configured. Pass `storage` to createShardDO()."); + }, +}; + +// Bound in-process `ctx.run*` composition depth so a self- or cyclically- +// referencing call fails loudly with a clear error instead of overflowing the +// stack. Tracked across the awaited handler chain (one DO invocation is +// single-threaded), so the counter reflects true nesting depth. +const MAX_RUN_DEPTH = 32; +let runDepth = 0; + +const dispatchRun = async (expected: FunctionKind, functionPath: string, args: Record, ctx: unknown): Promise => { + const registered = LUNORA_FUNCTIONS[functionPath]; + + if (!registered) { + throw new Error(`unknown function: ${functionPath}`); + } + + if (registered.kind !== expected) { + throw new Error(`ctx.run${expected[0]!.toUpperCase()}${expected.slice(1)}: "${functionPath}" is registered as a ${registered.kind}, not a ${expected}`); + } + + if (runDepth >= MAX_RUN_DEPTH) { + throw new LunoraError("RUN_DEPTH_EXCEEDED", `ctx.run*: composition depth limit (${MAX_RUN_DEPTH}) exceeded — likely a cyclic runQuery/runMutation`); + } + + runDepth += 1; + + try { + return await registered.handler(ctx, args); + } finally { + runDepth -= 1; + } +}; + +/** + * Build the project's shard Durable Object. Export the result as `ShardDO` + * from the worker entry so wrangler binds it by name. + */ +export const createShardDO = (config: ShardDOConfig = {}): new (state: ShardDOState, env: unknown) => ShardDOBase => + class extends ShardDOBase { + private migrated = false; + + public override async handleRpc(functionPath: string, args: Record): Promise { + const registered = LUNORA_FUNCTIONS[functionPath]; + + // Internal functions are reachable server-side only: via `ctx.run*` + // composition, or a trusted system dispatch (scheduler/cron, marked by + // `isSystemDispatch()`). A client RPC never carries that flag, so its + // internals stay not-found and never leak across the external boundary. + if (!registered || (registered.visibility === "internal" && !this.isSystemDispatch())) { + throw new LunoraError("FUNCTION_NOT_FOUND", `function not registered: ${functionPath}`); + } + + this.ensureMigrated(); + + const ctx = this.buildCtx({ functionPath }); + + // A mutation's writes must commit all-or-nothing: wrap its dispatch in + // the DO's BEGIN/COMMIT span so any throw (a validator, an RLS denial, + // an OCC conflict, a failed row mid-`insertMany`/`patchMany`) rolls + // back every write the mutation made. Queries are read-only and actions + // do external I/O that can't be rolled back, so both dispatch directly. + // `ctx.run*` composition runs inside this span (it never re-enters + // handleRpc); runInTransaction's own guard rejects accidental nesting. + // + // The replay bookkeeping (idempotency dedup row + custom-mutator + // watermark advance) commits INSIDE this span via + // `commitMutationBookkeeping`, so the writes, the dedup row, and the + // watermark are atomic — a crash can't leave the writes durable without + // the replay guard. + if (registered.kind === "mutation") { + return this.runInTransaction(async () => { + const result = await registered.handler(ctx, args); + + this.commitMutationBookkeeping(result); + + return result; + }); + } + + return registered.handler(ctx, args); + } + + protected override async executeSubscription(functionPath: string, args: Record, identity?: { identity?: Record; userId?: string }): Promise<{ result: unknown; tables: Set } | null> { + const registered = LUNORA_FUNCTIONS[functionPath]; + + if (!registered || registered.kind !== "query" || registered.visibility === "internal") { + return null; + } + + this.ensureMigrated(); + + const tables = new Set(); + // Identity is threaded EXPLICITLY from the (deferred/interleaved) + // subscription caller — never read from the shared per-request field + // here — so a concurrent RPC can't leak its identity into this re-run. + const ctx = this.buildCtx({ functionPath, identity, onRead: (table) => tables.add(table) }); + const result = await registered.handler(ctx, args); + + return { result, tables }; + } + + protected override executeStream(functionPath: string, args: Record): null | { iterator: (signal: AbortSignal) => AsyncIterable } { + const registered = LUNORA_FUNCTIONS[functionPath]; + + if (!registered || registered.kind !== "stream" || registered.visibility === "internal") { + return null; + } + + this.ensureMigrated(); + + return { + iterator: (signal) => (registered.handler as (context: unknown, args: Record, signal: AbortSignal) => AsyncIterable)(this.buildCtx({ functionPath }), args, signal), + }; + } + + protected override isCustomMutator(functionPath: string): boolean { + return LUNORA_MUTATOR_PATHS.has(functionPath); + } + + protected override resolveShape(name: string, args: Record, identity?: { identity?: Record; userId?: string }): { columns?: readonly string[]; effectiveWhere?: WhereInput; global?: boolean; table: string } | undefined { + const shape = LUNORA_SHAPES[name]; + + if (!shape) { + return undefined; + } + + this.ensureMigrated(); + + // Trusted ctx from the socket's OWN verified identity — the client + // supplies only the shape name + args; `compileWhere` validates the + // args then runs the shape's `where(ctx, args)` under that identity, + // so which rows replicate is a server decision (reads-as-permissions). + const ctx = this.buildCtx({ functionPath: `__shape__:${name}`, identity }); + const shapeWhere = shape.compileWhere(ctx, args) as unknown as WhereInput; + + // AND-compose with the table's RLS read base-where. A shape runs no + // procedure, so the `.use(rls(...))` middleware never fires; without + // this merge its reads would bypass every read policy on the table + // (rows the caller can't see would replicate). `composeShapeReadWhere` + // evaluates the table's read policies under this same trusted ctx — + // exactly the request-time path — and fails closed under a + // `.rls("required")` schema for a non-`.public()`, policy-less table. + const effectiveWhere = composeShapeReadWhere(LUNORA_RLS_READ_REGISTRY, { + ctx, + identity: identity?.identity ?? null, + rlsRequired: (schema as unknown as { rlsMode?: string }).rlsMode === "required", + roles: (ctx as { auth?: { roles?: readonly string[] } }).auth?.roles ?? [], + shapeWhere, + table: shape.table, + tablePublic: (schema as unknown as { tables: Record }).tables[shape.table]?.isPublic === true, + userId: identity?.userId ?? null, + }); + + // A live shape pokes only from its OWN shard's op-log, so a `where()` + // that joins to a `.shardBy()` table (rows in another DO) is rejected + // here — the first point the compiled predicate + shard modes are both + // known. Remedy: denormalize, or move the joined table to `.global()`. + assertShapeShardable(effectiveWhere, schema as unknown as SchemaLike, shape.table); + + // A `.global()` table lives in D1 (no per-DO op-log): flag it so the + // base serves it through the latency-tiered poll path (`readGlobalShapeRows`) + // instead of the CDC poke path. + const isGlobal = (schema as unknown as SchemaLike).tables[shape.table]?.shardMode?.kind === "global"; + + return { columns: shape.columns, effectiveWhere, global: isGlobal, table: shape.table }; + } + + protected override lifecycleHookPaths(event: "connect" | "disconnect"): readonly string[] { + return LUNORA_LIFECYCLE_HOOKS[event]; + } + + protected override tableRefs(table: string): Record | undefined { + return LUNORA_TABLE_REFS[table]; + } + + protected override tableIndexes(table: string): Array<{ fields: string[]; name: string; type: "geo" | "index" | "rank" | "search" | "vector"; unique?: boolean }> { + return LUNORA_TABLE_INDEXES[table] ?? []; + } + + protected override ttlSweeps(): ReadonlyArray<{ after?: number; field: string; softDeleteField?: string; table: string }> { + return LUNORA_TTL_SWEEPS; + } + + protected override tableColumns(table: string): Array<{ isStorage?: boolean; name: string; optional: boolean; pk?: boolean; ref?: string; type: string }> { + return LUNORA_TABLE_COLUMNS[table] ?? []; + } + + protected override storageColumns(): Record { + return LUNORA_STORAGE_COLUMNS; + } + + protected override rlsMetadata(): RlsPoliciesResult { + return LUNORA_RLS_METADATA; + } + + protected override maskMetadata(): MaskPoliciesResult { + return LUNORA_MASK_METADATA; + } + + protected override storageRulesMetadata(): StorageRulesResult { + return LUNORA_STORAGE_RULES; + } + + protected override studioFeatures(): StudioFeaturesResult { + return LUNORA_STUDIO_FEATURES; + } + + protected override advisories(): AdvisoryFinding[] { + return LUNORA_ADVISORIES; + } + + protected override async runShardDataMigration(args: RunShardMigrationArgs): Promise { + const migration = LUNORA_MIGRATIONS[args.id]; + + if (!migration) { + throw new LunoraError("MIGRATION_NOT_FOUND", `data migration "${args.id}" is not registered`, { status: 404 }); + } + + this.ensureMigrated(); + + const env = (this.env ?? {}) as Record; + const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike; + const writer = createShardCtxDb({ + broadcast: (delta) => { + this.recordChangedTable(delta.table); + }, + cdc: config.cdc ?? false, + scheduler, + schema: schema as unknown as SchemaLike, + sql: this.sql as SqlExec, + }); + + return runDataMigration({ + batchSize: args.batchSize, + direction: args.direction, + dryRun: args.dryRun, + maxBatches: args.maxBatches, + migration: migration as unknown as DataMigrationLike, + // Flush after each batch so live migrationStatus subscribers see + // progress mid-run (the base method records the reserved state + // table the raw-SQL progress write is invisible to the tracker). + onBatch: () => this.flushMigrationProgress(), + sql: this.sql as SqlExec, + writer, + }); + } + + protected override async runShardWrite(args: RunShardWriteArgs): Promise { + const definition = (schema as unknown as SchemaLike).tables[args.table]; + + if (!definition) { + throw new LunoraError("UNKNOWN_TABLE", `unknown table: ${args.table}`, { status: 404 }); + } + + // `.global()` tables live in D1, not this DO's SQLite — editing them + // here would corrupt nothing but would fail confusingly, so reject up + // front with a clear code the studio can surface. + if (definition.shardMode?.kind === "global") { + throw new LunoraError("GLOBAL_TABLE_NOT_EDITABLE", `table "${args.table}" is global; edit it through D1, not the shard`, { status: 400 }); + } + + this.ensureMigrated(); + + const env = (this.env ?? {}) as Record; + const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike; + const writer = createShardCtxDb({ + broadcast: (delta) => { + this.recordChangedTable(delta.table); + }, + cdc: config.cdc ?? false, + scheduler, + schema: schema as unknown as SchemaLike, + sql: this.sql as SqlExec, + }); + + if (args.op === "insert") { + const id = await writer.insert(args.table, args.doc ?? {}); + + return { id, op: "insert" }; + } + + if (args.op === "delete") { + await writer.delete(args.id ?? ""); + + return { id: args.id ?? null, op: "delete" }; + } + + if (args.op === "replace") { + await writer.replace(args.id ?? "", args.doc ?? {}); + + return { id: args.id ?? null, op: "replace" }; + } + + await writer.patch(args.id ?? "", args.doc ?? {}); + + return { id: args.id ?? null, op: "patch" }; + } + + protected override async deleteRowThroughWriter(table: string, id: string): Promise { + const definition = (schema as unknown as SchemaLike).tables[table]; + + if (!definition) { + throw new LunoraError("UNKNOWN_TABLE", `unknown table: ${table}`, { status: 404 }); + } + + // `.global()` tables live in D1, not this DO's SQLite — the same + // guard `runShardWrite` applies to single-row edits. + if (definition.shardMode?.kind === "global") { + throw new LunoraError("GLOBAL_TABLE_NOT_EDITABLE", `table "${table}" is global; edit it through D1, not the shard`, { status: 400 }); + } + + this.ensureMigrated(); + + const env = (this.env ?? {}) as Record; + const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike; + const writer = createShardCtxDb({ + broadcast: (delta) => { + this.recordChangedTable(delta.table); + }, + cdc: config.cdc ?? false, + scheduler, + schema: schema as unknown as SchemaLike, + sql: this.sql as SqlExec, + }); + + // Routes through the writer (not raw SQL) so FTS / aggregate / rank + // shadow tables stay in sync and `onDelete` cascades fire — the + // bounded loop lives in the base `runShardBulkDelete`. + await writer.delete(id); + } + + protected override async runShardRankBefore(args: RunShardRankBeforeArgs): Promise<{ before: number; total: number }> { + this.ensureMigrated(); + + const env = (this.env ?? {}) as Record; + const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike; + const writer = createShardCtxDb({ + broadcast: (delta) => { + this.recordChangedTable(delta.table); + }, + cdc: config.cdc ?? false, + scheduler, + schema: schema as unknown as SchemaLike, + sql: this.sql as SqlExec, + }); + + // `rankBefore` is optional on `DatabaseWriterLike` (the D1 twin omits it), + // but the shard writer from `createShardCtxDb` always defines it. + if (!writer.rankBefore) { + throw new LunoraError("NOT_IMPLEMENTED", "rankBefore is unavailable on the shard writer", { status: 500 }); + } + + return writer.rankBefore(args.table, args.index, { + partitionKey: args.partitionKey, + rowId: args.rowId, + sortValues: args.sortValues, + }); + } + + protected override async runShardRankPage(args: RunShardRankPageArgs): Promise { + this.ensureMigrated(); + + const env = (this.env ?? {}) as Record; + const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike; + const writer = createShardCtxDb({ + broadcast: (delta) => { + this.recordChangedTable(delta.table); + }, + cdc: config.cdc ?? false, + scheduler, + schema: schema as unknown as SchemaLike, + sql: this.sql as SqlExec, + }); + + // `rankPageRows` is optional on `DatabaseWriterLike` (the D1 twin omits it), + // but the shard writer from `createShardCtxDb` always defines it. The sort + // directions live in the schema's rankIndex, so the shard reads them itself; + // `args.directions` is only the coordinator's comparator hint and isn't forwarded. + if (!writer.rankPageRows) { + throw new LunoraError("NOT_IMPLEMENTED", "rankPage is unavailable on the shard writer", { status: 500 }); + } + + return writer.rankPageRows(args.table, args.index, { + after: args.after, + cursor: args.cursor, + partitionKey: args.partitionKey, + take: args.take, + }); + } + + protected override async runShardApplyCdc(args: RunShardApplyCdcArgs): Promise<{ applied: number }> { + this.ensureMigrated(); + + const env = (this.env ?? {}) as Record; + const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike; + const writer = createShardCtxDb({ + broadcast: (delta) => { + this.recordChangedTable(delta.table); + }, + cdc: config.cdc ?? false, + scheduler, + schema: schema as unknown as SchemaLike, + sql: this.sql as SqlExec, + }); + + await applyCdcChanges(writer, args.changes); + + return { applied: args.changes.length }; + } + + protected override ensureMigrated(): void { + if (this.migrated) { + return; + } + + runShardMigrations(this.sql as SqlExec, schema as unknown as SchemaLike, { cdc: config.cdc ?? false }); + this.migrated = true; + } + + private buildCtx(options: { functionPath?: string; identity?: { identity?: Record; userId?: string }; onRead?: (table: string) => void } = {}): unknown { + const env = (this.env ?? {}) as Record; + // When the caller threads an explicit identity (subscription seed / + // refresh — both run in deferred/interleaved contexts), use it by + // value and NEVER read the shared per-request identity field, which a + // concurrent RPC may have re-set. Otherwise (the synchronous RPC + // dispatch path) fall back to the per-request fields as before. + const userId = options.identity ? options.identity.userId : this.getCurrentUserId(); + const identity = options.identity ? options.identity.identity : this.getCurrentIdentity(); + + const secrets = createSecrets(env); + + const scheduler = (config.scheduler?.(env) ?? schedulerStub) as SchedulerLike; + // Build the storage adapter once and share it between `ctx.storage` + // and `ctx.db.system._storage` so both read the same R2 binding. The + // `storageStub` fallback satisfies SystemReaderStorageLike structurally + // (its `list`/`getMetadata` throw the "no storage configured" error). + const storage = asBucketStorage(config.storage?.(env) ?? storageStub) as unknown as SystemReaderStorageLike; + const db: DatabaseWriterLike = createShardCtxDb({ + auth: { identity: identity ?? null, userId: userId ?? null }, + broadcast: (delta) => { + this.recordChangedTable(delta.table); + }, + cdc: config.cdc ?? false, + enforceRls: true, + onIndexUse: this.getCtxDbIndexUseHook(), + onRead: options.onRead ?? this.getCtxDbReadHook(), + scheduler, + schema: schema as unknown as SchemaLike, + sql: this.sql as SqlExec, + storage, + }); + + const facade = db as unknown as Record>; + facade["nodes"] = bindTableFacade(db, "nodes"); + facade["tagColors"] = bindTableFacade(db, "tagColors"); + facade["savedQueries"] = bindTableFacade(db, "savedQueries"); + facade["dailyIndex"] = bindTableFacade(db, "dailyIndex"); + facade["ratelimit_buckets"] = bindTableFacade(db, "ratelimit_buckets"); + + // `ctx.log`: the DO base builds the attributed logger (structured + // fields + `.with(...)` child + trace correlation) and routes each call + // to the optional `observability` sink. It also buffers the line (studio + // Logs panel) and emits a structured console event the dev-server formats. + const observability = config.observability?.(env); + const logFunctionPath = options.functionPath ?? ""; + const log = this.makeLogger(logFunctionPath, observability); + + // `ctx.trace` / `ctx.metrics`: spans and measurements to the same sink. + // The trace anchor is threaded explicitly for the same reason `identity` + // is — a deferred caller (a subscription re-run) must not inherit the + // writing mutation's trace from the shared per-request field. + const trace = this.makeTracer(logFunctionPath, observability, options.identity ? undefined : this.getCurrentTrace()); + const metrics = this.makeMetrics(logFunctionPath, observability); + + // `ctx.now`: the wall-clock instant (epoch ms) this function began, + // captured ONCE so the whole handler body sees a single stable value. + // Query/mutation handlers must be deterministic (they may be re-run on + // OCC retry / subscription re-eval), so they must read time through + // `ctx.now` instead of `Date.now()` — the `nondeterministic_query_mutation` + // advisor flags the latter. Actions may still use ambient `Date.now()`. + const now = Date.now(); + + const ctx: Record = { + auth: { + getIdentity: async () => identity ?? null, + userId: userId ?? null, + }, + db, + fetch: globalThis.fetch.bind(globalThis), + ip: this.getCurrentIp(), + log, + metrics, + now, + orm: bindOrm(facade), + scheduler, + storage, + trace, + secrets, + }; + + ctx.runAction = (reference: FunctionReference, fnArgs: Record) => dispatchRun("action", reference.__lunoraRef, fnArgs, ctx); + ctx.runMutation = (reference: FunctionReference, fnArgs: Record) => dispatchRun("mutation", reference.__lunoraRef, fnArgs, ctx); + ctx.runQuery = (reference: FunctionReference, fnArgs: Record) => dispatchRun("query", reference.__lunoraRef, fnArgs, ctx); + + return ctx; + } + }; diff --git a/lunora/_generated/vectors.ts b/lunora/_generated/vectors.ts new file mode 100644 index 00000000..13644ac4 --- /dev/null +++ b/lunora/_generated/vectors.ts @@ -0,0 +1,24 @@ +// GENERATED by @lunora/codegen — do not edit. +// Run `lunora codegen` to regenerate. + +/** + * One vector index declared in `schema.ts` — an inline `.vectorize()` column + * or a standalone `defineVectorIndex()`. `field` is the source column (absent + * for a `select`-derived Shape B index); `metadata` lists the row fields + * mirrored into Vectorize for filtering. + */ +export interface LunoraVectorIndex { + dimensions?: number; + field?: string; + metadata?: ReadonlyArray; + metric?: "cosine" | "dot-product" | "euclidean"; + name: string; + table: string; +} + +/** + * Static registry of every vector index in the schema, sorted by name. + * Vectorize cannot enumerate indexes at runtime, so the worker passes this to + * `createWorker({ vectorIntrospector })` to back the studio's vector browser. + */ +export const LUNORA_VECTOR_INDEXES: ReadonlyArray = []; diff --git a/lunora/mcp.ts b/lunora/mcp.ts new file mode 100644 index 00000000..efe71813 --- /dev/null +++ b/lunora/mcp.ts @@ -0,0 +1,189 @@ +/** + * Worker MCP ↔ Lunora bridge (LUNORA_OUTLINE=1). + * + * Regular `mutation`/`query` (not watermarked `defineMutator`) so the Worker + * can call them via trusted shard RPC without clientSeq headers. Browser + * editor keeps using fine-grained mutators; MCP keeps outline-ops planners. + */ + +import type { Id } from "./_generated/dataModel"; + +import { + docToNode, + nodeToInsertFields, + planFromChangeOps, + type OutlinePlan, +} from "../src/data/outline-plans"; +import { internalMutation, internalQuery, v } from "./_generated/server"; + +/** Wire node shape for MCP (no Lunora `userId`) — keeps codegen out of `src/`. */ +type McpNode = { + id: string; + parentId: string | null; + prevSiblingId: string | null; + text: string; + isTask: boolean; + completed: boolean; + collapsed: boolean; + bookmarkedAt: number | null; + mirrorOf: string | null; + createdAt: number; + updatedAt: number; + origin: string | null; + kind: "paragraph" | null; +}; + +type ShardTable = + | "nodes" + | "tagColors" + | "savedQueries" + | "dailyIndex" + | "ratelimit_buckets"; + +type MutatorDb = { + query: (table: ShardTable) => { + collect: () => Promise & { _id: string }>>; + }; + get: ( + id: Id, + ) => Promise<(Record & { _id: string }) | null>; + insert: ( + table: ShardTable, + document: Record, + options?: { clientId?: string }, + ) => Promise; + patch: (id: Id, fields: Record) => Promise; + delete: (id: Id) => Promise; +}; + +type MutatorCtx = { + auth: { userId?: string | null }; + db: MutatorDb; +}; + +function assertOwner(ctx: MutatorCtx, userId: string): void { + if (ctx.auth.userId !== userId) { + throw new Error("unauthorized: shard userId mismatch"); + } +} + +async function commitPlan(ctx: MutatorCtx, plan: OutlinePlan): Promise { + for (const id of plan.deletes) { + await ctx.db.delete(id as Id<"nodes">); + } + for (const patch of plan.patches) { + await ctx.db.patch( + patch.id as Id<"nodes">, + patch.fields as Record, + ); + } + for (const node of plan.inserts) { + await ctx.db.insert("nodes", nodeToInsertFields(node), { + clientId: node.id, + }); + } +} + +const wireNodeArg = v.object({ + id: v.string(), + parentId: v.string().nullable(), + prevSiblingId: v.string().nullable(), + text: v.string(), + isTask: v.boolean(), + completed: v.boolean(), + collapsed: v.boolean(), + bookmarkedAt: v.number().nullable(), + mirrorOf: v.string().nullable(), + createdAt: v.number(), + updatedAt: v.number(), + origin: v.string().nullable(), + kind: v.literal("paragraph").nullable(), +}); + +const changeOpArg = v.union( + v.object({ op: v.literal("insert"), value: wireNodeArg }), + v.object({ op: v.literal("update"), value: wireNodeArg }), + v.object({ op: v.literal("delete"), key: v.string() }), +); + +/** Full outline for MCP get_outline / search_nodes. Worker-only (system RPC). */ +export const listNodes = internalQuery + .input({ userId: v.string() }) + .query(async ({ ctx, args }): Promise => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const rows = await mctx.db.query("nodes").collect(); + return rows.map((row) => { + const n = docToNode(row); + const { userId: _u, ...wire } = n; + return wire; + }); + }); + +/** Daily-index rows for MCP claimDailyScaffold. Worker-only (system RPC). */ +export const listDailyIndex = internalQuery + .input({ userId: v.string() }) + .query(async ({ ctx, args }) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const rows = await mctx.db.query("dailyIndex").collect(); + return rows.map((r) => ({ + key: String(r.key ?? r._id), + nodeId: String(r.nodeId ?? ""), + })); + }); + +/** + * Apply classic `ChangeOp[]` (outline-ops planners) as one shard transaction. + * Worker-only via `x-lunora-system` — not a browser mutator path. + * Spoiler redaction stays on MCP egress; daily claims use claimDailyMapping. + */ +export const applyChangeOps = internalMutation + .input({ + userId: v.string(), + ops: v.array(changeOpArg), + }) + .mutation(async ({ ctx, args }) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + if (args.ops.length === 0) { + return { count: 0, deletes: 0, inserts: 0, patches: 0 }; + } + const plan = planFromChangeOps(args.userId, args.ops); + await commitPlan(mctx, plan); + return { + count: args.ops.length, + deletes: plan.deletes.length, + inserts: plan.inserts.length, + patches: plan.patches.length, + }; + }); + +const WIPE_TABLES: ShardTable[] = [ + "nodes", + "tagColors", + "savedQueries", + "dailyIndex", + "ratelimit_buckets", +]; + +/** + * Erase every row in this user's shard (outline + side-collections). Worker-only + * via `x-lunora-system` — self-serve account deletion (ADR 0051 + ADR 0055). + * Keyed by Better Auth `user.id` (same shard the browser/MCP mutators use). + */ +export const wipeUserShard = internalMutation + .input({ userId: v.string() }) + .mutation(async ({ ctx, args }) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + let deleted = 0; + for (const table of WIPE_TABLES) { + const rows = await mctx.db.query(table).collect(); + for (const row of rows) { + await mctx.db.delete(row._id as Id); + deleted += 1; + } + } + return { deleted }; + }); diff --git a/lunora/mutators.ts b/lunora/mutators.ts new file mode 100644 index 00000000..a1301c6e --- /dev/null +++ b/lunora/mutators.ts @@ -0,0 +1,872 @@ +import { defineMutator, v } from "lunorash/server"; + +import type { Id } from "./_generated/dataModel"; + +import { + buildTreeIndex, + docToNode, + nodeToInsertFields, + planAppendChild, + planImportNodes, + planIndent, + planIndentMany, + planInsertChildAtStart, + planInsertSibling, + planMaterializeDailyNodes, + planMirrorNode, + planMoveMany, + planMoveNode, + planOutdent, + planOutdentMany, + planRemoveMany, + planRemoveNode, + planRestoreNodes, + planSeedIfEmpty, + planSetBookmarkedAt, + planSetCollapsed, + planSetCompleted, + planSetIsTask, + planSetKind, + planSetText, + planSplitNode, + type OutlineNode, + type OutlinePlan, +} from "../src/data/outline-plans"; +import { resolveDailyClaim } from "../src/plugins/daily/claim-mapping"; + +type ShardTable = "nodes" | "tagColors" | "savedQueries" | "dailyIndex"; + +/** Minimal mutator ctx — defineMutator's ServerContext is the base MutationCtx. */ +type MutatorDb = { + query: (table: ShardTable) => { + collect: () => Promise & { _id: string }>>; + withIndex: ( + name: string, + fn: (q: { eq: (field: string, value: unknown) => unknown }) => unknown, + ) => { + first: () => Promise<(Record & { _id: string }) | null>; + collect: () => Promise & { _id: string }>>; + }; + }; + get: ( + id: Id, + ) => Promise<(Record & { _id: string }) | null>; + insert: ( + table: ShardTable, + document: Record, + options?: { clientId?: string }, + ) => Promise; + patch: (id: Id, fields: Record) => Promise; + delete: (id: Id) => Promise; +}; + +type MutatorCtx = { + auth: { userId?: string | null }; + db: MutatorDb; +}; + +async function loadNodes(ctx: MutatorCtx): Promise { + const rows = await ctx.db.query("nodes").collect(); + return rows.map(docToNode); +} + +function assertOwner(ctx: MutatorCtx, userId: string): void { + if (ctx.auth.userId !== userId) { + throw new Error("unauthorized: shard userId mismatch"); + } +} + +/** + * Lunora `clientId` must be a UUID — daily keys (`container`, `YYYY-MM-DD`) and + * tag names are not. Look up side-collection rows by their natural key index + * and let insert assign a server UUID `_id`. + */ +async function getDailyByKey( + ctx: MutatorCtx, + key: string, +): Promise<(Record & { _id: string }) | null> { + return ctx.db + .query("dailyIndex") + .withIndex("by_key", (q) => q.eq("key", key)) + .first(); +} + +async function getTagColorByTag( + ctx: MutatorCtx, + tag: string, +): Promise<(Record & { _id: string }) | null> { + return ctx.db + .query("tagColors") + .withIndex("by_tag", (q) => q.eq("tag", tag)) + .first(); +} + +async function commitPlan(ctx: MutatorCtx, plan: OutlinePlan): Promise { + // deletes → patches → inserts: restore-safe (a deleted id must be gone + // before a same-batch insert could reclaim it) and fine for structural ops. + for (const id of plan.deletes) { + await ctx.db.delete(id as Id<"nodes">); + } + + for (const patch of plan.patches) { + await ctx.db.patch( + patch.id as Id<"nodes">, + patch.fields as Record, + ); + } + + for (const node of plan.inserts) { + await ctx.db.insert("nodes", nodeToInsertFields(node), { + clientId: node.id, + }); + } +} + +const userIdArg = v.string(); +const idArg = v.string(); +const tsArg = v.number(); +const kindArg = v.optional(v.literal("paragraph").nullable()); + +/** Compose smoke mutator — proves codegen + SHARD wiring without dual auth UX. */ +export const hello = defineMutator({ + args: { userId: userIdArg }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + return { ok: true as const, userId: args.userId }; + }, +}); + +export const insertSibling = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + parentId: v.string().nullable(), + afterId: v.string().nullable(), + text: v.string(), + isTask: v.optional(v.boolean()), + kind: kindArg, + createdAt: tsArg, + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planInsertSibling(index, { + id: args.id, + userId: args.userId, + parentId: args.parentId, + afterId: args.afterId, + text: args.text, + isTask: args.isTask, + kind: args.kind, + createdAt: args.createdAt, + updatedAt: args.updatedAt, + }); + if (!plan) throw new Error("insertSibling: invalid parent/afterId"); + await commitPlan(mctx, plan); + return { id: args.id }; + }, +}); + +export const insertChildAtStart = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + parentId: v.string().nullable(), + text: v.string(), + isTask: v.optional(v.boolean()), + kind: kindArg, + createdAt: tsArg, + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planInsertChildAtStart(index, { + id: args.id, + userId: args.userId, + parentId: args.parentId, + text: args.text, + isTask: args.isTask, + kind: args.kind, + createdAt: args.createdAt, + updatedAt: args.updatedAt, + }); + if (!plan) throw new Error("insertChildAtStart: invalid parent"); + await commitPlan(mctx, plan); + return { id: args.id }; + }, +}); + +/** Quick-add / append-at-end — server resolves last sibling (one watermark). */ +export const appendChild = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + parentId: v.string().nullable(), + text: v.string(), + isTask: v.optional(v.boolean()), + kind: kindArg, + createdAt: tsArg, + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planAppendChild(index, { + id: args.id, + userId: args.userId, + parentId: args.parentId, + text: args.text, + isTask: args.isTask, + kind: args.kind, + createdAt: args.createdAt, + updatedAt: args.updatedAt, + }); + if (!plan) throw new Error("appendChild: invalid parent"); + await commitPlan(mctx, plan); + return { id: args.id }; + }, +}); + +/** + * Enter mid-split: left text stays on `id`, right text lands in `newId` sibling + * — one DO transaction / watermark. + */ +export const splitNode = defineMutator({ + args: { + id: idArg, + newId: idArg, + userId: userIdArg, + parentId: v.string().nullable(), + afterId: idArg, + leftText: v.string(), + rightText: v.string(), + isTask: v.optional(v.boolean()), + kind: kindArg, + createdAt: tsArg, + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planSplitNode(index, { + id: args.id, + newId: args.newId, + userId: args.userId, + parentId: args.parentId, + afterId: args.afterId, + leftText: args.leftText, + rightText: args.rightText, + isTask: args.isTask, + kind: args.kind, + createdAt: args.createdAt, + updatedAt: args.updatedAt, + }); + if (!plan) throw new Error("splitNode: invalid id/parent/afterId"); + await commitPlan(mctx, plan); + return { id: args.newId }; + }, +}); + +/** + * Server-authoritative empty-outline seed. Concurrent calls serialize on the + * DO watermark FIFO — second sees non-empty and returns `{ seeded: false }`. + */ +export const seedIfEmpty = defineMutator({ + args: { + userId: userIdArg, + createdAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const nodes = await loadNodes(mctx); + const plan = planSeedIfEmpty(nodes, { + userId: args.userId, + createdAt: args.createdAt, + }); + if (!plan) return { seeded: false as const }; + await commitPlan(mctx, plan); + return { + seeded: true as const, + ids: plan.inserts.map((n) => n.id), + }; + }, +}); + +export const indent = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + updatedAt: tsArg, + resolveMirror: v.optional(v.boolean()), + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planIndent( + index, + args.id, + args.updatedAt, + args.resolveMirror ?? false, + ); + if (!plan) throw new Error("indent: no-op or missing node"); + await commitPlan(mctx, plan); + }, +}); + +export const outdent = defineMutator({ + args: { id: idArg, userId: userIdArg, updatedAt: tsArg }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planOutdent(index, args.id, args.updatedAt); + if (!plan) throw new Error("outdent: no-op or missing node"); + await commitPlan(mctx, plan); + }, +}); + +export const removeNode = defineMutator({ + args: { id: idArg, userId: userIdArg, updatedAt: tsArg }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planRemoveNode(index, args.id, args.updatedAt); + if (!plan) throw new Error("removeNode: missing node"); + await commitPlan(mctx, plan); + }, +}); + +export const moveNode = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + newParentId: v.string().nullable(), + afterSiblingId: v.string().nullable(), + updatedAt: tsArg, + expandIds: v.optional(v.array(v.string())), + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planMoveNode(index, { + id: args.id, + newParentId: args.newParentId, + afterSiblingId: args.afterSiblingId, + updatedAt: args.updatedAt, + expandIds: args.expandIds, + }); + if (!plan) throw new Error("moveNode: no-op or invalid"); + await commitPlan(mctx, plan); + }, +}); + +export const setText = defineMutator({ + args: { id: idArg, userId: userIdArg, text: v.string(), updatedAt: tsArg }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planSetText(index, args.id, args.text, args.updatedAt); + if (!plan) throw new Error("setText: missing node"); + await commitPlan(mctx, plan); + }, +}); + +export const setCompleted = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + completed: v.boolean(), + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planSetCompleted( + index, + args.id, + args.completed, + args.updatedAt, + ); + if (!plan) throw new Error("setCompleted: missing node"); + await commitPlan(mctx, plan); + }, +}); + +export const setCollapsed = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + collapsed: v.boolean(), + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planSetCollapsed( + index, + args.id, + args.collapsed, + args.updatedAt, + ); + if (!plan) throw new Error("setCollapsed: missing node"); + await commitPlan(mctx, plan); + }, +}); + +export const setIsTask = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + isTask: v.boolean(), + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planSetIsTask(index, args.id, args.isTask, args.updatedAt); + if (!plan) throw new Error("setIsTask: missing node"); + await commitPlan(mctx, plan); + }, +}); + +export const setKind = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + kind: v.literal("paragraph").nullable(), + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planSetKind(index, args.id, args.kind, args.updatedAt); + if (!plan) throw new Error("setKind: missing node"); + await commitPlan(mctx, plan); + }, +}); + +export const setBookmarkedAt = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + bookmarkedAt: v.number().nullable(), + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planSetBookmarkedAt( + index, + args.id, + args.bookmarkedAt, + args.updatedAt, + ); + if (!plan) throw new Error("setBookmarkedAt: missing node"); + await commitPlan(mctx, plan); + }, +}); + +const nodeSnapshotArg = v.object({ + id: idArg, + userId: userIdArg, + parentId: v.string().nullable(), + prevSiblingId: v.string().nullable(), + text: v.string(), + isTask: v.boolean(), + completed: v.boolean(), + collapsed: v.boolean(), + bookmarkedAt: v.number().nullable(), + mirrorOf: v.string().nullable(), + createdAt: tsArg, + updatedAt: tsArg, + origin: v.string().nullable(), + kind: v.literal("paragraph").nullable(), +}); + +/** + * Undo/redo snapshot restore — one DO transaction / watermark for the whole + * diff (deletes + upserts), even when large. Client sends the target outline + * subset (full snapshots for touched + surviving ids via planRestoreNodes). + */ +export const restoreNodes = defineMutator({ + args: { + userId: userIdArg, + /** Full target outline after restore (history snapshot + userId). */ + nodes: v.array(nodeSnapshotArg), + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const current = await loadNodes(mctx); + // Force shard owner — never trust a client-supplied snapshot userId. + const target: OutlineNode[] = args.nodes.map((n) => ({ + ...n, + userId: args.userId, + kind: n.kind === "paragraph" ? "paragraph" : null, + })); + const plan = planRestoreNodes(current, target); + await commitPlan(mctx, plan); + return { + deletes: plan.deletes.length, + inserts: plan.inserts.length, + patches: plan.patches.length, + }; + }, +}); + +/** + * OPML / bulk insert-only batch. Chains pre-wired by the pure planner. + * Large imports may call this multiple times (clientSeq FIFO); a mid-import + * failure can leave earlier chunks durable — see HANDOFF. + */ +export const importNodes = defineMutator({ + args: { + userId: userIdArg, + nodes: v.array(nodeSnapshotArg), + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + // Force shard owner — never trust a client-supplied snapshot userId. + const nodes: OutlineNode[] = args.nodes.map((n) => ({ + ...n, + userId: args.userId, + kind: n.kind === "paragraph" ? "paragraph" : null, + })); + const plan = planImportNodes(nodes); + await commitPlan(mctx, plan); + return { count: nodes.length }; + }, +}); + +/** `/mirror` — last-child mirror of source under targetParentId (ADR 0022). */ +export const mirrorNode = defineMutator({ + args: { + id: idArg, + userId: userIdArg, + sourceId: idArg, + targetParentId: v.string().nullable(), + createdAt: tsArg, + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const index = buildTreeIndex(await loadNodes(mctx)); + const plan = planMirrorNode(index, args); + if (!plan) throw new Error("mirrorNode: missing source/target or cycle"); + await commitPlan(mctx, plan); + return { id: args.id }; + }, +}); + +/** Multi-select delete — one watermark (ADR 0018). */ +export const removeMany = defineMutator({ + args: { + userId: userIdArg, + nodeIds: v.array(idArg), + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const nodes = await loadNodes(mctx); + const plan = planRemoveMany(nodes, args.nodeIds, args.updatedAt); + if (!plan) throw new Error("removeMany: no-op"); + await commitPlan(mctx, plan); + }, +}); + +/** Multi-select move / Send-to-Today — one watermark (ADR 0018). */ +export const moveMany = defineMutator({ + args: { + userId: userIdArg, + targetId: v.string().nullable(), + nodeIds: v.array(idArg), + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const nodes = await loadNodes(mctx); + const plan = planMoveMany(nodes, { + targetId: args.targetId, + nodeIds: args.nodeIds, + updatedAt: args.updatedAt, + }); + if (!plan) throw new Error("moveMany: no-op"); + await commitPlan(mctx, plan); + }, +}); + +/** Multi-select Tab indent — one watermark (ADR 0018). */ +export const indentMany = defineMutator({ + args: { + userId: userIdArg, + nodeIds: v.array(idArg), + updatedAt: tsArg, + resolveMirror: v.optional(v.boolean()), + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const nodes = await loadNodes(mctx); + const plan = planIndentMany( + nodes, + args.nodeIds, + args.updatedAt, + args.resolveMirror ?? false, + ); + if (!plan) throw new Error("indentMany: no-op"); + await commitPlan(mctx, plan); + }, +}); + +/** Multi-select Shift+Tab outdent — one watermark (ADR 0018). */ +export const outdentMany = defineMutator({ + args: { + userId: userIdArg, + nodeIds: v.array(idArg), + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const nodes = await loadNodes(mctx); + const plan = planOutdentMany(nodes, args.nodeIds, args.updatedAt); + if (!plan) throw new Error("outdentMany: no-op"); + await commitPlan(mctx, plan); + }, +}); + +/** + * Daily get-or-create node half — scaffold + day (+ optional seed) after the + * client has claimed ids via `claimDailyMapping` (flag ON) or `/api/kv` + * (flag OFF). ADR 0041 `seedEntryLine` is an optional empty child in `inserts`. + */ +export const materializeDailyNodes = defineMutator({ + args: { + userId: userIdArg, + inserts: v.array( + v.object({ + id: idArg, + parentId: v.string().nullable(), + afterId: v.string().nullable(), + text: v.string(), + }), + ), + createdAt: tsArg, + updatedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const nodes = await loadNodes(mctx); + const plan = planMaterializeDailyNodes(nodes, { + userId: args.userId, + inserts: args.inserts, + createdAt: args.createdAt, + updatedAt: args.updatedAt, + }); + if (!plan) throw new Error("materializeDailyNodes: no-op or invalid"); + await commitPlan(mctx, plan); + return { count: args.inserts.length }; + }, +}); + +// --- Phase 2b side-collections (tagColors + savedQueries) ------------------- + +/** Upsert a tag color. Natural key = `tag` (index `by_tag`); `_id` is a UUID. */ +export const upsertTagColor = defineMutator({ + args: { + userId: userIdArg, + tag: v.string(), + color: v.string(), + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const existing = await getTagColorByTag(mctx, args.tag); + if (existing) { + await mctx.db.patch(existing._id as Id<"tagColors">, { + color: args.color, + }); + } else { + // No clientId: tag names aren't UUIDs (Lunora requires UUID clientIds). + await mctx.db.insert("tagColors", { + tag: args.tag, + color: args.color, + userId: args.userId, + }); + } + }, +}); + +export const deleteTagColor = defineMutator({ + args: { userId: userIdArg, tag: v.string() }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const existing = await getTagColorByTag(mctx, args.tag); + if (existing) await mctx.db.delete(existing._id as Id<"tagColors">); + }, +}); + +/** Insert a saved query row (`id` = clientId). */ +export const upsertSavedQuery = defineMutator({ + args: { + userId: userIdArg, + id: idArg, + name: v.string(), + query: v.string(), + createdAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const existing = await mctx.db.get(args.id as Id<"savedQueries">); + if (existing) { + await mctx.db.patch(args.id as Id<"savedQueries">, { + name: args.name, + query: args.query, + createdAt: args.createdAt, + }); + } else { + await mctx.db.insert( + "savedQueries", + { + name: args.name, + query: args.query, + createdAt: args.createdAt, + userId: args.userId, + }, + { clientId: args.id }, + ); + } + }, +}); + +export const patchSavedQuery = defineMutator({ + args: { + userId: userIdArg, + id: idArg, + name: v.optional(v.string()), + query: v.optional(v.string()), + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const existing = await mctx.db.get(args.id as Id<"savedQueries">); + if (!existing) return; + const fields: Record = {}; + if (args.name !== undefined) fields.name = args.name; + if (args.query !== undefined) fields.query = args.query; + if (Object.keys(fields).length === 0) return; + await mctx.db.patch(args.id as Id<"savedQueries">, fields); + }, +}); + +export const deleteSavedQuery = defineMutator({ + args: { userId: userIdArg, id: idArg }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const existing = await mctx.db.get(args.id as Id<"savedQueries">); + if (existing) await mctx.db.delete(args.id as Id<"savedQueries">); + }, +}); + +// --- dailyIndex (atomic claim = DO getOrCreateKv twin) ---------------------- + +/** + * Atomic get-or-create of a `key → nodeId` mapping. Pre-existing wins; returns + * `{ nodeId, won }` so the client knows whether to materialize the node. + * Natural key = `key` (index `by_key`); `_id` is a server UUID (keys like + * `container` / `YYYY-MM-DD` are not valid Lunora clientIds). + */ +export const claimDailyMapping = defineMutator({ + args: { + userId: userIdArg, + key: v.string(), + nodeId: idArg, + touchedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const existing = await getDailyByKey(mctx, args.key); + const existingNodeId = + existing && typeof existing.nodeId === "string" ? existing.nodeId : null; + const { winner, won } = resolveDailyClaim(existingNodeId, args.nodeId); + if (existing) { + // Always write (touchedAt) so the watermark poke fires even on a lost race. + await mctx.db.patch(existing._id as Id<"dailyIndex">, { + nodeId: winner, + touchedAt: args.touchedAt, + }); + } else { + await mctx.db.insert("dailyIndex", { + key: args.key, + nodeId: winner, + touchedAt: args.touchedAt, + userId: args.userId, + }); + } + return { nodeId: winner, won }; + }, +}); + +/** Upsert a daily-index mapping (heal / setMapping). */ +export const upsertDailyMapping = defineMutator({ + args: { + userId: userIdArg, + key: v.string(), + nodeId: idArg, + touchedAt: tsArg, + }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const existing = await getDailyByKey(mctx, args.key); + if (existing) { + await mctx.db.patch(existing._id as Id<"dailyIndex">, { + nodeId: args.nodeId, + touchedAt: args.touchedAt, + }); + } else { + await mctx.db.insert("dailyIndex", { + key: args.key, + nodeId: args.nodeId, + touchedAt: args.touchedAt, + userId: args.userId, + }); + } + }, +}); + +export const deleteDailyMapping = defineMutator({ + args: { userId: userIdArg, key: v.string() }, + server: async (ctx, args) => { + const mctx = ctx as unknown as MutatorCtx; + assertOwner(mctx, args.userId); + const existing = await getDailyByKey(mctx, args.key); + if (existing) await mctx.db.delete(existing._id as Id<"dailyIndex">); + }, +}); diff --git a/lunora/ratelimit/schema.ts b/lunora/ratelimit/schema.ts new file mode 100644 index 00000000..70dbe3e0 --- /dev/null +++ b/lunora/ratelimit/schema.ts @@ -0,0 +1,49 @@ +import type { RateLimitConfigMap } from "lunorash/ratelimit"; +import type { Middleware } from "lunorash/server"; + +import { createDbStore, RateLimiter } from "lunorash/ratelimit"; +import { + defineSchemaExtension, + defineTable, + definePlugin, + v, +} from "lunorash/server"; + +export const limits = { + default: { kind: "token bucket", period: 60_000, rate: 10 }, +} as const satisfies RateLimitConfigMap; + +export type LimitName = keyof typeof limits; + +export const makeRateLimiter = (ctx: { db: unknown }): RateLimiter => + new RateLimiter({ + config: limits, + store: createDbStore({ db: ctx.db as never, table: "ratelimit_buckets" }), + }); + +const middleware: Middleware< + { api?: Record; db: unknown }, + { api: Record; db: unknown } +> = ({ ctx, next }) => + next({ + ctx: { + ...ctx, + api: { ...ctx.api, ratelimit: makeRateLimiter(ctx) }, + }, + }); + +export const ratelimit = definePlugin("ratelimit", { + extension: defineSchemaExtension("ratelimit", { + tables: { + buckets: defineTable({ + key: v.string(), + value: v.number(), + ts: v.number(), + prev: v.optional(v.number()), + }) + .index("by_key", ["key"]) + .externallyManaged(), + }, + }), + middleware, +}); diff --git a/lunora/schema.ts b/lunora/schema.ts new file mode 100644 index 00000000..8258af31 --- /dev/null +++ b/lunora/schema.ts @@ -0,0 +1,66 @@ +import { defineSchema, defineTable, v } from "lunorash/server"; + +import { ratelimit } from "./ratelimit/schema"; + +/** + * Outline nodes + kv side-collections — Dotflowy field parity + Lunora + * `userId` shard key. Dotflowy `id` / kv keys map to Lunora `_id` via + * `clientId` on insert. + * + * Phase 2b: `tagColors` + `savedQueries` + `dailyIndex` ride Lunora when the + * sync flag is ON. `claimDailyMapping` is the DO `getOrCreateKv` twin. + */ +export default defineSchema({ + nodes: defineTable({ + parentId: v.string().nullable(), + prevSiblingId: v.string().nullable(), + text: v.string(), + isTask: v.boolean(), + completed: v.boolean(), + collapsed: v.boolean(), + bookmarkedAt: v.number().nullable(), + mirrorOf: v.string().nullable(), + createdAt: v.number(), + updatedAt: v.number(), + origin: v.string().nullable(), + kind: v.literal("paragraph").nullable(), + userId: v.string(), + }) + .shardBy("userId") + .index("by_parent", ["parentId"]), + + /** + * Custom tag colors (ADR 0007). Natural key = `tag` (`by_tag`); `_id` is a + * server UUID (tag names aren't valid Lunora clientIds). + */ + tagColors: defineTable({ + tag: v.string(), + color: v.string(), + userId: v.string(), + }) + .shardBy("userId") + .index("by_tag", ["tag"]), + + /** Saved filter queries (ADR 0048). `_id` = row id via clientId (UUID). */ + savedQueries: defineTable({ + name: v.string(), + query: v.string(), + createdAt: v.number(), + userId: v.string(), + }).shardBy("userId"), + + /** + * Daily scaffold identity (ADR 0052). Natural key = `key` (`by_key`) — + * `container` / `YYYY` / `YYYY-MM` / `YYYY-Www` / `YYYY-MM-DD`. `_id` is a + * server UUID (those keys aren't valid Lunora clientIds). `touchedAt` bumps + * on every claim so a lost-race claim still emits a poke (watermark hold). + */ + dailyIndex: defineTable({ + key: v.string(), + nodeId: v.string(), + touchedAt: v.number(), + userId: v.string(), + }) + .shardBy("userId") + .index("by_key", ["key"]), +}).extend(ratelimit.extension); diff --git a/lunora/shapes.ts b/lunora/shapes.ts new file mode 100644 index 00000000..71c6f5e3 --- /dev/null +++ b/lunora/shapes.ts @@ -0,0 +1,44 @@ +import { defineShape, v } from "lunorash/server"; + +/** + * Whole-outline replication for one user shard. + * Read-as-permission: only the authenticated owner may subscribe. + */ + +/** Owner-only shape filter — deny sentinel when auth ≠ arg userId. */ +function ownerWhere( + ctx: { auth: { userId?: string | null } }, + userId: string, +): { OR: [] } | { userId: string } { + // Shape `where` returns WhereInput (not boolean). `{ OR: [] }` is the + // vacuously-false deny sentinel used by Lunora RLS/shapes. + if (!ctx.auth.userId || ctx.auth.userId !== userId) return { OR: [] }; + return { userId }; +} + +export const wholeOutline = defineShape({ + args: { userId: v.string() }, + table: "nodes", + where: (ctx, { userId }) => ownerWhere(ctx, userId), +}); + +/** Per-user tag color rows (phase 2b). */ +export const userTagColors = defineShape({ + args: { userId: v.string() }, + table: "tagColors", + where: (ctx, { userId }) => ownerWhere(ctx, userId), +}); + +/** Per-user saved filter queries (phase 2b). */ +export const userSavedQueries = defineShape({ + args: { userId: v.string() }, + table: "savedQueries", + where: (ctx, { userId }) => ownerWhere(ctx, userId), +}); + +/** Per-user daily scaffold index (phase 2b — claimDailyMapping). */ +export const userDailyIndex = defineShape({ + args: { userId: v.string() }, + table: "dailyIndex", + where: (ctx, { userId }) => ownerWhere(ctx, userId), +}); diff --git a/package.json b/package.json index fc6078a2..09db5712 100644 --- a/package.json +++ b/package.json @@ -5,6 +5,9 @@ "description": "A local-first outline editor built with TanStack Start and TanStack DB.", "license": "O'Saasy", "type": "module", + "imports": { + "#lunora/*": "./lunora/*" + }, "scripts": { "setup": "bun scripts/setup.ts", "bootstrap": "bun scripts/bootstrap.ts", @@ -17,6 +20,8 @@ "preview": "vite preview", "cf:dev": "bun scripts/cf-dev.ts", "seed:user": "bun scripts/seed-user.ts", + "comp:dev-plan": "bun scripts/comp-dev-plan.ts", + "mint:mcp-token": "bun scripts/mint-mcp-token.ts", "invite": "bun scripts/invite.ts", "announce": "bun scripts/announce.ts", "deploy": "bun run build:cf && wrangler deploy", @@ -34,12 +39,13 @@ "typecheck": "tsc --noEmit", "typecheck:worker": "tsc --noEmit -p worker/tsconfig.json", "typecheck:test": "tsc --noEmit -p tsconfig.test.json", - "test": "bun test src worker/", + "test": "bun test -- ./src ./worker", "test:e2e": "playwright test", "test:e2e:serial": "playwright test --workers=1", "test:e2e:ui": "playwright test --ui", "effect:src": "opensrc path Effect-TS/effect-smol", - "effect:src:update": "opensrc remove Effect-TS/effect-smol && opensrc fetch Effect-TS/effect-smol" + "effect:src:update": "opensrc remove Effect-TS/effect-smol && opensrc fetch Effect-TS/effect-smol", + "lunora:codegen": "lunora codegen" }, "dependencies": { "@base-ui/react": "^1.6.0", @@ -48,9 +54,14 @@ "@fontsource-variable/geist": "^5.2.9", "@fontsource-variable/geist-mono": "^5.2.8", "@icons-pack/react-simple-icons": "^13.13.0", + "@lunora/db": "1.0.0-alpha.27", + "@lunora/ratelimit": "1.0.0-alpha.9", + "@lunora/react": "1.0.0-alpha.31", "@rgrove/parse-xml": "^4", "@sentry/cloudflare": "^10.65.0", "@sentry/react": "^10.65.0", + "@tanstack/db": "^0.6.16", + "@tanstack/offline-transactions": "^1.0.41", "@tanstack/query-core": "^5.101.1", "@tanstack/query-db-collection": "^1.0.42", "@tanstack/react-db": "^0.1.87", @@ -68,6 +79,7 @@ "fuse.js": "^7.4.2", "grab-bcv": "^0.1.5", "lucide-react": "^1.21.0", + "lunorash": "1.0.0-alpha.98", "motion": "^12.42.0", "react": "^19.0.0", "react-dom": "^19.0.0", diff --git a/scripts/comp-dev-plan.ts b/scripts/comp-dev-plan.ts new file mode 100644 index 00000000..5d4c1bcc --- /dev/null +++ b/scripts/comp-dev-plan.ts @@ -0,0 +1,75 @@ +/** + * Operator-comp an active unlimited subscription for the local dev account + * (`dev@dotflowy.local`) in local D1 — the same pattern documented in + * worker/plan.ts (hand-inserted row, no Stripe ids). MCP tool calls require a + * paid plan (#170); this keeps local dogfood off the production entitlement gate. + * + * Idempotent: re-running is a no-op when an active/trialing row already exists. + * Localhost-only: resolves the user from the live Worker session, never accepts + * an email override (no accidental prod targeting). + * + * Requires `bun run dev` / `bun run dev:api` and a seeded dev account + * (`bun run seed:user`). + */ +const API = "http://localhost:8787"; +const EMAIL = "dev@dotflowy.local"; +const PASSWORD = "dotflowy-dev"; +const ORIGIN = "http://localhost:8787"; +const SUBSCRIPTION_ID = "local-dev-unlimited-comp"; + +async function signInUserId(): Promise { + const res = await fetch(`${API}/api/auth/sign-in/email`, { + method: "POST", + headers: { + "content-type": "application/json", + origin: ORIGIN, + }, + body: JSON.stringify({ email: EMAIL, password: PASSWORD }), + }); + if (!res.ok) { + const text = await res.text(); + throw new Error( + `sign-in failed (${res.status}): ${text}. Run \`bun run seed:user\` first.`, + ); + } + const body = (await res.json()) as { user?: { id?: string } }; + const userId = body.user?.id; + if (!userId) throw new Error("sign-in succeeded but user id missing"); + return userId; +} + +function compSubscription(userId: string): void { + const proc = Bun.spawnSync( + [ + "wrangler", + "d1", + "execute", + "dotflowy-db", + "--local", + "--command", + `INSERT OR IGNORE INTO subscription (id, plan, referenceId, status) VALUES ('${SUBSCRIPTION_ID}', 'unlimited', '${userId}', 'active')`, + ], + { stdout: "pipe", stderr: "pipe" }, + ); + if (proc.exitCode !== 0) { + const err = new TextDecoder().decode(proc.stderr); + throw new Error( + `wrangler d1 execute failed (exit ${proc.exitCode}): ${err}`, + ); + } +} + +async function main(): Promise { + try { + await fetch(`${API}/api/auth/ok`); + } catch { + console.error(`Worker not reachable at ${API}. Run \`bun run dev\` first.`); + process.exit(1); + } + + const userId = await signInUserId(); + compSubscription(userId); + console.log(`comped unlimited plan for ${EMAIL} (${userId}) in local D1`); +} + +await main(); diff --git a/scripts/mint-mcp-token.ts b/scripts/mint-mcp-token.ts new file mode 100644 index 00000000..9c91c186 --- /dev/null +++ b/scripts/mint-mcp-token.ts @@ -0,0 +1,187 @@ +/** + * Mint a real Better Auth MCP OAuth bearer for the local dev account against a + * running Worker — dynamic client registration + PKCE authorization code, the + * same path `auth.api.getMcpSession` validates on `/mcp`. + * + * Localhost-only by construction (`API` is hardcoded). Use the printed bearer + * with `Authorization: Bearer …` on `POST http://localhost:8787/mcp`. + * + * MCP tool calls also require a paid plan locally — run `bun run comp:dev-plan` + * once per D1 reset before exercising writes. + * + * Requires `bun run dev` / `bun run dev:api` and `bun run seed:user`. + */ +const API = "http://localhost:8787"; +const AUTH = `${API}/api/auth`; +const EMAIL = "dev@dotflowy.local"; +const PASSWORD = "dotflowy-dev"; +const ORIGIN = "http://localhost:8787"; +/** Loopback redirect the authorize step can target without a listener. */ +const REDIRECT_URI = "http://127.0.0.1:8765/callback"; + +type SignInBody = { user?: { id?: string; email?: string } }; +type RegisterBody = { client_id?: string; error?: string }; +type TokenBody = { + access_token?: string; + token_type?: string; + expires_in?: number; + error?: string; + error_description?: string; +}; + +function randomVerifier(): string { + const bytes = crypto.getRandomValues(new Uint8Array(32)); + return btoa(String.fromCharCode(...bytes)) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} + +async function pkceChallenge(verifier: string): Promise { + const digest = await crypto.subtle.digest( + "SHA-256", + new TextEncoder().encode(verifier), + ); + return btoa(String.fromCharCode(...new Uint8Array(digest))) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} + +function sessionCookie(res: Response): string { + const setCookie = res.headers.getSetCookie?.() ?? []; + return setCookie.map((c) => c.split(";")[0]).join("; "); +} + +async function signIn(): Promise<{ cookie: string; userId: string }> { + const res = await fetch(`${AUTH}/sign-in/email`, { + method: "POST", + headers: { + "content-type": "application/json", + origin: ORIGIN, + }, + body: JSON.stringify({ email: EMAIL, password: PASSWORD }), + }); + if (!res.ok) { + const text = await res.text(); + throw new Error( + `sign-in failed (${res.status}): ${text}. Run \`bun run seed:user\` first.`, + ); + } + const body = (await res.json()) as SignInBody; + const userId = body.user?.id; + if (!userId) throw new Error("sign-in succeeded but user id missing"); + return { cookie: sessionCookie(res), userId }; +} + +async function registerClient(cookie: string): Promise { + const res = await fetch(`${AUTH}/mcp/register`, { + method: "POST", + headers: { + "content-type": "application/json", + cookie, + origin: ORIGIN, + }, + body: JSON.stringify({ + client_name: "local-mcp-dogfood", + redirect_uris: [REDIRECT_URI], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code"], + response_types: ["code"], + }), + }); + const body = (await res.json()) as RegisterBody; + if (!res.ok || !body.client_id) { + throw new Error( + `client registration failed (${res.status}): ${JSON.stringify(body)}`, + ); + } + return body.client_id; +} + +async function authorizeCode( + cookie: string, + clientId: string, + challenge: string, +): Promise { + const url = new URL(`${AUTH}/mcp/authorize`); + url.searchParams.set("client_id", clientId); + url.searchParams.set("redirect_uri", REDIRECT_URI); + url.searchParams.set("response_type", "code"); + url.searchParams.set("code_challenge", challenge); + url.searchParams.set("code_challenge_method", "S256"); + url.searchParams.set("scope", "openid"); + + const res = await fetch(url, { + redirect: "manual", + headers: { cookie, origin: ORIGIN }, + }); + const location = res.headers.get("location"); + if (res.status !== 302 || !location) { + throw new Error( + `authorize failed (status ${res.status}, location ${location ?? "none"})`, + ); + } + const code = new URL(location).searchParams.get("code"); + if (!code) throw new Error(`authorize redirect missing code: ${location}`); + return code; +} + +async function exchangeToken( + clientId: string, + code: string, + verifier: string, +): Promise { + const body = new URLSearchParams({ + grant_type: "authorization_code", + code, + redirect_uri: REDIRECT_URI, + client_id: clientId, + code_verifier: verifier, + }); + const res = await fetch(`${AUTH}/mcp/token`, { + method: "POST", + headers: { + "content-type": "application/x-www-form-urlencoded", + origin: ORIGIN, + }, + body, + }); + const json = (await res.json()) as TokenBody; + if (!res.ok || !json.access_token) { + throw new Error( + `token exchange failed (${res.status}): ${JSON.stringify(json)}`, + ); + } + return json; +} + +async function main(): Promise { + try { + await fetch(`${API}/api/auth/ok`); + } catch { + console.error(`Worker not reachable at ${API}. Run \`bun run dev\` first.`); + process.exit(1); + } + + const { cookie, userId } = await signIn(); + const clientId = await registerClient(cookie); + const verifier = randomVerifier(); + const challenge = await pkceChallenge(verifier); + const code = await authorizeCode(cookie, clientId, challenge); + const token = await exchangeToken(clientId, code, verifier); + + console.log(`userId: ${userId}`); + console.log(`clientId: ${clientId}`); + console.log(`access_token: ${token.access_token}`); + console.log(`expires_in: ${token.expires_in ?? "unknown"}s`); + console.log(""); + console.log("Example: curl -s -X POST http://localhost:8787/mcp \\"); + console.log(` -H 'authorization: Bearer ${token.access_token}' \\`); + console.log(" -H 'content-type: application/json' \\"); + console.log( + ' -d \'{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}\'', + ); +} + +await main(); diff --git a/scripts/react-jsx-dev-runtime-shim.ts b/scripts/react-jsx-dev-runtime-shim.ts new file mode 100644 index 00000000..2a437987 --- /dev/null +++ b/scripts/react-jsx-dev-runtime-shim.ts @@ -0,0 +1,23 @@ +/** + * Production-safe `react/jsx-dev-runtime` shim. + * + * `@lunora/react` publishes packem output that imports `jsxDEV` from + * `react/jsx-dev-runtime`. Vite's production React resolve replaces that + * module with `{ jsxDEV: undefined }`, so `LunoraProvider` (and anything + * else from the package) crashes with "jsxDEV is not a function" under + * `cf:dev` / `build:cf`. Dev (`bun run dev`) keeps a real jsxDEV and is fine. + * + * Aliased from `vite.config.ts` — map jsxDEV onto production jsx/jsxs. + */ +import { Fragment, jsx, jsxs } from "react/jsx-runtime"; + +export { Fragment }; + +export function jsxDEV( + type: Parameters[0], + props: Parameters[1], + key?: Parameters[2], + isStaticChildren?: boolean, +) { + return isStaticChildren ? jsxs(type, props!, key) : jsx(type, props!, key); +} diff --git a/src/components/MobileActionsBar.tsx b/src/components/MobileActionsBar.tsx index f08b50df..a93c5928 100644 --- a/src/components/MobileActionsBar.tsx +++ b/src/components/MobileActionsBar.tsx @@ -11,7 +11,6 @@ import { useEffect, useRef, useState, type ReactNode } from "react"; import { cn } from "@/lib/utils"; import { useCoarsePointer } from "../hooks/use-coarse-pointer"; -import { useKeyboardViewport } from "../hooks/use-keyboard-viewport"; /** * The zero-arg command surface the bar drives. Each method resolves the focused @@ -143,22 +142,28 @@ export function MobileActionsBar({ }) { const coarse = useCoarsePointer(); const editing = useOutlineEditing(findFocusedId); - const keyboardOffset = useKeyboardViewport(); // Presence gate: a mouse user never mounts the bar. Visibility gate: no bar // without a focused bullet, so every action has a valid target by construction. if (!coarse || !editing) return null; return ( - // Outer layer owns positioning: fixed to the bottom, lifted above the software - // keyboard by the visualViewport gap, and the safe-area pad when it sits at the - // real bottom (no keyboard). The pill inside centers within this. + // Outer layer owns positioning: fixed to the bottom and lifted above the + // software keyboard by `--kb-inset` (styles.css -- the VirtualKeyboard API's + // inset, native on Chromium and polyfilled on Safari). The pill inside + // centers within this. + // + // Both declarations are branchless on purpose. The lift is 0px whenever no + // keyboard is up, and the safe-area pad SUBTRACTS the lift because a raised + // keyboard already covers the home indicator -- padding for it on top of the + // lift would float the bar a thumb's width too high. `max(0px, ...)` is what + // makes the two cases one expression instead of a ternary on a JS number.
{ const el = textRef.current; if (!el || composingRef.current) return; if (syncedRef.current === content.text) return; - if ( - document.activeElement === el && - echoedTextFor(content.id) === content.text - ) { - return; + if (document.activeElement === el) { + if (echoedTextFor(content.id) === content.text) return; + const dom = readSource(el); + if (dom !== content.text && dom.startsWith(content.text)) return; } const focused = document.activeElement === el; const revealOffset = focused ? getCaretOffset(el) : null; diff --git a/src/components/delete-confirm-dialog.tsx b/src/components/delete-confirm-dialog.tsx index c2d84ade..710a45a1 100644 --- a/src/components/delete-confirm-dialog.tsx +++ b/src/components/delete-confirm-dialog.tsx @@ -3,7 +3,9 @@ import { useEffect, useState } from "react"; import { toast } from "sonner"; import { nodesCollection } from "../data/collection"; +import { isLunoraSyncEnabled } from "../data/flags"; import { capture, drop } from "../data/history"; +import { getLunoraOutlineContext } from "../data/lunora-sync"; import { runStructuralSliced } from "../data/structural"; import { now, planRemoveSubtrees } from "../data/tree"; import { getTreeIndex } from "../data/tree-store"; @@ -73,6 +75,37 @@ export function DeleteConfirmDialog() { // ONE undo point BEFORE the batch: a single Cmd+Z restores everything. capture(index, captureKey); + + // Lunora: no classic `{ops}` batch — one `removeMany` mutator owns the + // subtree delete + watermark. Progress is optimistic (apply is sync). + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (!lunora) { + drop(); + setStage({ kind: "error" }); + return; + } + try { + setStage({ kind: "deleting", count, applied: count }); + const tx = lunora.store.mutators.removeMany({ + userId: lunora.userId, + nodeIds: [...rootIds], + updatedAt: now(), + }); + // Await persistence here (error stage below) — do not also + // trackLunoraMutation (would double-toast on failure). + await tx.isPersisted.promise; + setStage({ kind: "closed" }); + toast.success( + `Deleted ${count.toLocaleString()} bullets. Cmd+Z restores them.`, + ); + } catch { + drop(); + setStage({ kind: "error" }); + } + return; + } + let applied = 0; const slices: Array<() => void> = []; if (plan.repoints.length > 0) { diff --git a/src/components/header-more-menu.tsx b/src/components/header-more-menu.tsx index 951fa246..13926316 100644 --- a/src/components/header-more-menu.tsx +++ b/src/components/header-more-menu.tsx @@ -3,6 +3,7 @@ import { ChevronsDownUpIcon, ChevronsUpDownIcon, CircleCheckIcon, + ClipboardCopyIcon, FileTextIcon, FocusIcon, LogOutIcon, @@ -170,12 +171,11 @@ export function setViewCollapsed(collapsed: boolean) { /** * Header overflow ("More") menu. Since #171 the plan/billing, account (Connect - * Google, Delete account), connections (MCP), data (import/export/copy), and + * Google, Delete account), connections (MCP), data (import/export), and * appearance (theme, text size) controls all live on the dedicated `/settings` - * page -- so this menu is now just the outline-view actions (collapse/expand, - * show completed, spotlight), the read-only links (What's new, Report a bug, - * GitHub), and the two entry points that belong on every screen: Settings (top) - * and Sign out (bottom). + * page -- so this menu is outline-view actions first (copy, collapse/expand, + * show completed, spotlight), then read-only links (What's new, Report a bug, + * GitHub, legal) + Settings, with Sign out last. * * This is the static v1 of the header-action overflow: the pinned/overflow * split is a fixed default. User-customizable pinning (Chrome-extension style) @@ -215,6 +215,39 @@ export function HeaderMoreMenu() { } /> + void copyOutlineAsMarkdown()}> + + Copy as Markdown + + + setViewCollapsed(true)}> + + Collapse all + + + setViewCollapsed(false)}> + + Expand all + + + + + Show completed + + + + + Spotlight mode + + + + void navigate({ to: "/settings" })}> Settings @@ -280,34 +313,6 @@ export function HeaderMoreMenu() { - setViewCollapsed(true)}> - - Collapse all - - - setViewCollapsed(false)}> - - Expand all - - - - - Show completed - - - - - Spotlight mode - - - - signOutAndReload()} diff --git a/src/components/history-restore.tsx b/src/components/history-restore.tsx index 00a2d362..1c374575 100644 --- a/src/components/history-restore.tsx +++ b/src/components/history-restore.tsx @@ -2,12 +2,19 @@ import { Loader2Icon } from "lucide-react"; import { useEffect, useState } from "react"; import { toast } from "sonner"; +import type { OutlineNode } from "../data/outline-plans"; + +import { isLunoraSyncEnabled } from "../data/flags"; import { RESTORE_SLICE_OPS, redo, undo, type RestorePlan, } from "../data/history"; +import { + getLunoraOutlineContext, + trackLunoraMutation, +} from "../data/lunora-sync"; import { runStructural, runStructuralSliced } from "../data/structural"; import { getTreeIndex } from "../data/tree-store"; import { @@ -28,6 +35,10 @@ import { * paths keep the wire guarantees: ONE batch POST → one DO `applyBatch` → one * echo-hold. * + * Lunora flag ON: one `restoreNodes` mutator (full target snapshot → server + * re-diffs via `planRestoreNodes`) — single watermark even for large diffs; + * modal still shows while awaiting persistence. + * * `setPendingFocus` is only honored on the sync path: during a sliced restore * the modal owns focus, and by the time the batch commits the tree-change * effect window `FocusPass` consumes has passed — a pending focus set then @@ -41,6 +52,33 @@ export function runHistoryRestore( ): void { const plan = (kind === "undo" ? undo : redo)(getTreeIndex(), focusId); if (!plan) return; + + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + // Flag ON but sync host not ready — never fall through to classic DO. + if (!lunora) { + plan.revert(); + toast.error("Sync is still starting — try again in a moment."); + return; + } + const nodes: OutlineNode[] = plan.targetNodes.map((n) => ({ + ...n, + userId: lunora.userId, + })); + if (plan.opCount < RESTORE_SLICE_OPS) { + trackLunoraMutation( + lunora.store.mutators.restoreNodes({ + userId: lunora.userId, + nodes, + }), + ); + if (plan.focusId) setPendingFocus(plan.focusId); + return; + } + void runLunoraRestore(kind, plan, nodes, lunora.userId); + return; + } + if (plan.opCount < RESTORE_SLICE_OPS) { runStructural(() => { for (const slice of plan.slices) slice(); @@ -51,6 +89,44 @@ export function runHistoryRestore( void runSliced(kind, plan); } +async function runLunoraRestore( + kind: "undo" | "redo", + plan: RestorePlan, + nodes: OutlineNode[], + userId: string, +) { + const lunora = getLunoraOutlineContext(); + if (!lunora) { + plan.revert(); + return; + } + const label = kind === "undo" ? "Undoing" : "Redoing"; + openRestoreProgress?.({ + kind: "restoring", + label, + total: plan.opCount, + applied: 0, + }); + await new Promise((resolve) => setTimeout(resolve, 0)); + try { + const tx = lunora.store.mutators.restoreNodes({ userId, nodes }); + // Optimistic apply already flipped the collection; show full progress. + openRestoreProgress?.({ + kind: "restoring", + label, + total: plan.opCount, + applied: plan.opCount, + }); + await tx.isPersisted.promise; + openRestoreProgress?.({ kind: "closed" }); + toast.success(kind === "undo" ? "Undo complete." : "Redo complete."); + } catch { + plan.revert(); + openRestoreProgress?.({ kind: "closed" }); + toast.error(`${label} failed. Nothing was changed.`); + } +} + async function runSliced(kind: "undo" | "redo", plan: RestorePlan) { const label = kind === "undo" ? "Undoing" : "Redoing"; const show = (applied: number) => diff --git a/src/components/lunora-sync-host.tsx b/src/components/lunora-sync-host.tsx new file mode 100644 index 00000000..5a0cc8eb --- /dev/null +++ b/src/components/lunora-sync-host.tsx @@ -0,0 +1,55 @@ +/** + * Starts Lunora outline sync when `dotflowy:flag:lunora-sync` is ON (ADR 0055). + * Mounted inside AuthGate so a session userId is available. Flag OFF = pass- + * through (custom `/api/sync` path unchanged). + * + * Flag is read in an effect (not during SSR/prerender) so the SPA shell and + * client hydration agree on the first paint. + */ + +import { LunoraProvider } from "@lunora/react"; +import { useEffect, useState, type ReactNode } from "react"; + +import { isLunoraSyncEnabled } from "../data/flags"; +import { getLunoraClient } from "../data/lunora-client"; +import { + startLunoraOutlineSync, + stopLunoraOutlineSync, +} from "../data/lunora-sync"; +import { useSession } from "../lib/auth-client"; + +function LunoraOutlineBootstrap({ children }: { children: ReactNode }) { + const { data: session } = useSession(); + const userId = session?.user?.id; + + useEffect(() => { + if (!userId) return; + startLunoraOutlineSync(userId); + return () => { + stopLunoraOutlineSync(); + }; + }, [userId]); + + return <>{children}; +} + +/** + * When the Lunora sync flag is ON, wrap children in LunoraProvider and start + * the outline store. When OFF, pass children through unchanged (no Lunora + * client constructed — keeps prerender / default path clean). + */ +export function LunoraSyncHost({ children }: { children: ReactNode }) { + const [enabled, setEnabled] = useState(false); + + useEffect(() => { + setEnabled(isLunoraSyncEnabled()); + }, []); + + if (!enabled) return <>{children}; + + return ( + + {children} + + ); +} diff --git a/src/components/markdown-paste.ts b/src/components/markdown-paste.ts index 87970551..d98f495c 100644 --- a/src/components/markdown-paste.ts +++ b/src/components/markdown-paste.ts @@ -11,10 +11,17 @@ import { toast } from "sonner"; +import type { OutlineNode } from "../data/outline-plans"; + import { nodesCollection } from "../data/collection"; -import { isMirrorsEnabled } from "../data/flags"; +import { isLunoraSyncEnabled, isMirrorsEnabled } from "../data/flags"; import { focusKeyFor } from "../data/focus-key"; import { capture, drop, RESTORE_SLICE_OPS } from "../data/history"; +import { getLiveNodes, getLiveOutlineNodes } from "../data/live-nodes"; +import { + getLunoraOutlineContext, + trackLunoraMutation, +} from "../data/lunora-sync"; import { countForest, parseMarkdownForest, @@ -25,7 +32,7 @@ import { type MdPastePlan, } from "../data/markdown-import"; import { runStructural, runStructuralSliced } from "../data/structural"; -import { buildTreeIndex, makeNode, now, type Node } from "../data/tree"; +import { buildTreeIndex, makeNode, now } from "../data/tree"; import { getTreeIndex } from "../data/tree-store"; import { getViewFilter, @@ -126,6 +133,31 @@ export function pasteMarkdownTree(args: MarkdownPasteArgs): boolean { return true; const timestamp = now(); + + // Lunora flag-ON: classic `nodesCollection` is idle — land via one + // `restoreNodes` watermark (anchor patch + inserts + repoints) so paste + // doesn't throw CollectionOperationError on a missing classic key. + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (!lunora) { + toast.error("Sync is still starting — try pasting again in a moment."); + return true; + } + capture(index, activeKey); + runStructural(() => { + applyMarkdownPasteViaRestore(plan, anchorId, timestamp, lunora.userId); + }); + const seam = resolveSeam(plan, anchorId, count); + if (seam.id === anchorId) + focus.placeCaretHere(plan.anchor.text, seam.offset); + else { + const key = focusKeyFor(seam.id, activeKey); + focus.setPendingFocus(key, seam.offset); + scrollRowIntoView(key); + } + return true; + } + const writeAnchor = () => { nodesCollection.update(anchorId, (draft) => { draft.text = plan.anchor.text; @@ -197,6 +229,74 @@ export function pasteMarkdownTree(args: MarkdownPasteArgs): boolean { return true; } +/** Build the post-paste outline and commit via Lunora `restoreNodes`. */ +function applyMarkdownPasteViaRestore( + plan: MdPastePlan, + anchorId: string, + timestamp: number, + userId: string, +): void { + const lunora = getLunoraOutlineContext(); + if (!lunora) return; + + const byId = new Map( + getLiveOutlineNodes().map((n) => [n.id, { ...n } as OutlineNode]), + ); + const anchor = byId.get(anchorId); + if (!anchor) return; + + const nextAnchor: OutlineNode = { + ...anchor, + text: plan.anchor.text, + updatedAt: timestamp, + ...(plan.anchor.isTask !== null ? { isTask: plan.anchor.isTask } : {}), + ...(plan.anchor.completed !== null + ? { completed: plan.anchor.completed } + : {}), + ...(plan.anchor.kind !== null + ? { kind: plan.anchor.kind, isTask: false } + : plan.anchor.isTask + ? { kind: null } + : {}), + }; + byId.set(anchorId, nextAnchor); + + for (const ins of plan.inserts) { + byId.set(ins.id, { + id: ins.id, + userId, + parentId: ins.parentId, + prevSiblingId: ins.prevSiblingId, + text: ins.text, + isTask: ins.isTask, + completed: ins.completed, + collapsed: false, + bookmarkedAt: null, + mirrorOf: null, + createdAt: timestamp, + updatedAt: timestamp, + origin: null, + kind: ins.kind, + }); + } + for (const r of plan.repoints) { + const n = byId.get(r.id); + if (!n) continue; + byId.set(r.id, { + ...n, + prevSiblingId: r.prevSiblingId, + updatedAt: timestamp, + }); + } + + trackLunoraMutation( + lunora.store.mutators.restoreNodes({ + userId, + nodes: [...byId.values()], + }), + ); +} + /** * Where the caret actually lands, once the tree is on screen. * @@ -215,14 +315,15 @@ function resolveSeam( if (plan.focusId === anchorId) return { id: anchorId, offset: plan.focusOffset }; - // Build the visible set from a FRESH index off `nodesCollection.toArray` -- + // Build the visible set from a FRESH index off the live store -- // synchronously current after `runStructural` -- not `getTreeIndex()`, whose // change-notify can lag the optimistic apply and drop the just-inserted seam // node from the walk (the exact reason `focusKeyFor`, called right after this, - // rebuilds the same way; ADR 0044 / ADR 0022 Stage 2c). + // rebuilds the same way; ADR 0044 / ADR 0022 Stage 2c). Classic = + // `nodesCollection`; Lunora = `wholeOutline` via `getLiveNodes`. const visible = new Set( buildVisibleRows( - buildTreeIndex(nodesCollection.toArray as Node[]), + buildTreeIndex(getLiveNodes()), getViewRootId(), getViewIsHidden(), getViewFilter(), diff --git a/src/components/node-switcher.tsx b/src/components/node-switcher.tsx index 4be60a64..f0b856d7 100644 --- a/src/components/node-switcher.tsx +++ b/src/components/node-switcher.tsx @@ -328,8 +328,11 @@ function SwitcherDialog({ } function runAction(action: CommandCenterAction) { - close(); + // Run BEFORE close: verbs like Delete prefer `findFocusedId() ?? id`, and + // closing the dialog first lets Radix restore focus onto an unrelated row + // (Lunora tree remounts make this common) — deleting the wrong bullet. action.run(); + close(); } const actions: SearchAction[] = q diff --git a/src/components/opml-import-dialog.tsx b/src/components/opml-import-dialog.tsx index 574dd747..c51539e4 100644 --- a/src/components/opml-import-dialog.tsx +++ b/src/components/opml-import-dialog.tsx @@ -4,7 +4,9 @@ import { CircleCheckIcon, Loader2Icon, TriangleAlertIcon } from "lucide-react"; import { useEffect, useRef, useState, type ChangeEvent } from "react"; import { nodesCollection } from "../data/collection"; +import { isLunoraSyncEnabled } from "../data/flags"; import { capture, drop } from "../data/history"; +import { getLunoraOutlineContext } from "../data/lunora-sync"; import { OPML_APP_MAX_NODES, OpmlEmpty, @@ -14,6 +16,7 @@ import { type OpmlImportResult, type OpmlImportReport, } from "../data/opml-import"; +import { makeOutlineNode, type OutlineNode } from "../data/outline-plans"; import { runStructuralSliced } from "../data/structural"; import { childrenOf, makeNode, now } from "../data/tree"; import { getTreeIndex } from "../data/tree-store"; @@ -37,13 +40,13 @@ import { * (More menu + Cmd+K) reach it through `openOpmlImport()`. * * The commit is the client write path, not a new endpoint: one history - * `capture` (a single Cmd+Z removes the whole import), then ONE - * `runStructuralSliced` transaction — every insert lands as one `POST - * /api/nodes {ops}` → DO `applyBatch`, whose reply carries the FINAL seq of the - * chunked changelog (>500-op batches echo as several frames) and `waitForSeq` - * holds the optimistic overlay across all of them. Any fault rejects the - * transaction, TanStack rolls the optimistic state back, and the dialog reports - * "nothing was imported" — retry-safe, never a half-import. + * `capture` (a single Cmd+Z removes the whole import), then — flag OFF — ONE + * `runStructuralSliced` transaction (every insert lands as one `POST + * /api/nodes {ops}` → DO `applyBatch`). Flag ON (ADR 0055): chunked Lunora + * `importNodes` mutators (clientSeq FIFO, ~500 nodes/watermark). A mid-import + * failure on the Lunora path can leave earlier chunks durable; the dialog still + * reports failure and does not claim success. Flag-OFF faults reject the + * transaction, TanStack rolls back, and nothing was imported. * * The optimistic inserts are applied in ~500-node SLICES that yield to the * event loop between applications (multiple `mutate` calls on the one @@ -234,6 +237,61 @@ export function OpmlImportDialog() { // ONE undo point BEFORE the batch: a single Cmd+Z removes the whole import. capture(index, null); + + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (!lunora) { + drop(); + setStage({ + kind: "error", + title: "Import failed", + detail: "Lunora sync is not ready. Try again in a moment.", + }); + return; + } + const outlineNodes: OutlineNode[] = [ + makeOutlineNode({ + id: containerId, + userId: lunora.userId, + parentId: null, + prevSiblingId: lastTop, + text: containerText(timestamp), + collapsed: true, + createdAt: timestamp, + updatedAt: timestamp, + }), + ]; + for (const op of plan.ops) { + if (op.op === "delete") continue; + outlineNodes.push({ ...op.value, userId: lunora.userId }); + } + try { + let applied = 0; + const total = outlineNodes.length; + for (let i = 0; i < outlineNodes.length; i += IMPORT_SLICE_NODES) { + const chunk = outlineNodes.slice(i, i + IMPORT_SLICE_NODES); + const tx = lunora.store.mutators.importNodes({ + userId: lunora.userId, + nodes: chunk, + }); + await tx.isPersisted.promise; + applied += chunk.length; + setStage({ kind: "importing", count: total, applied }); + await new Promise((r) => setTimeout(r, 0)); + } + setStage({ kind: "success", containerId, count: plan.count }); + } catch { + drop(); + setStage({ + kind: "error", + title: "Import failed", + detail: + "The outline could not be fully saved. Earlier chunks may have landed — undo or re-import carefully.", + }); + } + return; + } + // The plan is insert-only, emitted depth-first pre-order with the sibling // chain wired by construction — replayed verbatim into the collection, in // yielding slices so the progress counter below actually paints. `applied` diff --git a/src/components/quick-add.tsx b/src/components/quick-add.tsx index 89f4bc25..f082da04 100644 --- a/src/components/quick-add.tsx +++ b/src/components/quick-add.tsx @@ -95,7 +95,6 @@ import { import { getTreeIndex, useNode } from "../data/tree-store"; import { getViewRootId } from "../data/view-state"; import { useCoarsePointer } from "../hooks/use-coarse-pointer"; -import { useKeyboardViewport } from "../hooks/use-keyboard-viewport"; import { getCaptureDestination, keymapSpecs, @@ -634,7 +633,6 @@ function QuickAddOverlay({ onClose }: { onClose: () => void }) { // Position signal (ADR 0030): lift the panel above the software keyboard on a // coarse pointer; a fine pointer centers it and ignores the offset. const coarse = useCoarsePointer(); - const keyboardOffset = useKeyboardViewport(); // The destination for the CURRENT draft (resets to the default per node). The // default is the LAZY provider (label known now, node created only at born) -- @@ -1033,11 +1031,11 @@ function QuickAddOverlay({ onClose }: { onClose: () => void }) { style={ coarse ? { - transform: `translateY(-${keyboardOffset}px)`, + // Lift above the software keyboard via the VirtualKeyboard + // inset; branchless, same reasoning as MobileActionsBar. + transform: "translateY(calc(-1 * var(--kb-inset)))", marginBottom: - keyboardOffset === 0 - ? "env(safe-area-inset-bottom)" - : undefined, + "max(0px, calc(env(safe-area-inset-bottom) - var(--kb-inset)))", } : undefined } diff --git a/src/components/use-bullet-keymap.ts b/src/components/use-bullet-keymap.ts index 5fd853c5..c34dbad3 100644 --- a/src/components/use-bullet-keymap.ts +++ b/src/components/use-bullet-keymap.ts @@ -227,7 +227,8 @@ export function useBulletKeymap({ if (el.textContent !== "") return; e.preventDefault(); e.stopPropagation(); - commands.onDeleteNode(node.id); + // INSTANCE, not content: mirrors pass the source as `node` (ADR 0022). + commands.onDeleteNode(instanceId); }, options: { preventDefault: false, stopPropagation: false }, }, @@ -236,11 +237,11 @@ export function useBulletKeymap({ // regardless of text or caret position. On Mac "delete" is the // Backspace key; register Delete too for the forward-delete key. hotkey: "Mod+Shift+Backspace", - callback: () => commands.onDeleteNode(node.id), + callback: () => commands.onDeleteNode(instanceId), }, { hotkey: "Mod+Shift+Delete", - callback: () => commands.onDeleteNode(node.id), + callback: () => commands.onDeleteNode(instanceId), }, { // Shift+ArrowUp from the top visual line: ENTER node multi-selection diff --git a/src/data/account-prefs.ts b/src/data/account-prefs.ts new file mode 100644 index 00000000..17a78879 --- /dev/null +++ b/src/data/account-prefs.ts @@ -0,0 +1,162 @@ +/** + * Account-scoped preferences synced via classic DO `/api/kv` (ADR 0055 opt-in). + * + * Lunora beta opt-in lives here — not localStorage alone — so enabling on one + * device can converge others on next load. The runtime flag still mirrors to + * `dotflowy:flag:lunora-sync` so `LunoraSyncHost` remounts cleanly after reload. + */ + +import { queryCollectionOptions } from "@tanstack/query-db-collection"; +import { createCollection } from "@tanstack/react-db"; +import { Schema } from "effect"; +import { useSyncExternalStore } from "react"; + +import { hardReset } from "../lib/auth-client"; +import { isLunoraSyncEnabled, LUNORA_SYNC_FLAG_KEY } from "./flags"; +import { kvFetch, kvPut, toKvRows } from "./kv-api"; +import { queryClient } from "./query-client"; + +const prefRowSchema = Schema.Struct({ + id: Schema.String, + enabled: Schema.Boolean, +}); + +export type AccountPrefRow = Schema.Schema.Type; + +const KV = "account-prefs"; +export const LUNORA_BETA_ROW_ID = "lunora-beta"; + +const PREFS_RELOAD_GUARD = "dotflowy:lunora-pref-sync-reload"; + +export const accountPrefsCollection = createCollection( + queryCollectionOptions({ + id: "account-prefs", + queryKey: ["kv", KV], + queryClient, + queryFn: () => kvFetch(KV), + getKey: (row: AccountPrefRow) => row.id, + schema: Schema.toStandardSchemaV1(prefRowSchema), + onInsert: async ({ transaction }) => { + await kvPut(KV, toKvRows(transaction)); + return { refetch: false }; + }, + onUpdate: async ({ transaction }) => { + await kvPut(KV, toKvRows(transaction)); + return { refetch: false }; + }, + }), +); + +function lunoraBetaRow(): AccountPrefRow | null { + return ( + accountPrefsCollection.toArray.find((r) => r.id === LUNORA_BETA_ROW_ID) ?? + null + ); +} + +function mirrorLunoraFlag(enabled: boolean) { + try { + window.localStorage.setItem(LUNORA_SYNC_FLAG_KEY, enabled ? "on" : "off"); + } catch { + // Private mode — reload still picks up URL-less default until next success. + } +} + +/** + * Persist the preference via a direct `kvPut` — not the collection's + * insert/update handlers. Those fire async `onInsert`/`onUpdate` that + * `hardReset` aborts mid-flight, so the synced row never lands. + */ +async function writeLunoraBeta(enabled: boolean): Promise { + const row: AccountPrefRow = { id: LUNORA_BETA_ROW_ID, enabled }; + await kvPut(KV, [{ key: LUNORA_BETA_ROW_ID, value: row }]); +} + +/** Persist Lunora beta opt-in, mirror the runtime flag, and reload. */ +export async function setLunoraBetaEnabled(enabled: boolean): Promise { + await writeLunoraBeta(enabled); + mirrorLunoraFlag(enabled); + hardReset(window.location.pathname + window.location.search); +} + +// --- Reactive read ----------------------------------------------------------- + +const HIDDEN = { ready: false, enabled: false } as const; + +type LunoraBetaSnapshot = { ready: boolean; enabled: boolean }; + +let snapshot: LunoraBetaSnapshot = HIDDEN; +let collectionReady = false; +const listeners = new Set<() => void>(); +let started = false; + +function rebuild() { + const enabled = collectionReady ? (lunoraBetaRow()?.enabled ?? false) : false; + if (snapshot.ready === collectionReady && snapshot.enabled === enabled) + return; + snapshot = { ready: collectionReady, enabled }; + for (const l of listeners) l(); +} + +function ensureStarted() { + if (started || typeof window === "undefined") return; + started = true; + accountPrefsCollection.subscribeChanges(() => rebuild(), { + includeInitialState: true, + }); + void accountPrefsCollection + .toArrayWhenReady() + .then(() => { + collectionReady = true; + rebuild(); + maybeSyncLocalFlagFromAccount(); + }) + .catch(() => {}); +} + +function subscribe(cb: () => void): () => void { + ensureStarted(); + listeners.add(cb); + return () => { + listeners.delete(cb); + }; +} + +function getSnapshot(): LunoraBetaSnapshot { + ensureStarted(); + return snapshot; +} + +/** Synced Lunora beta preference. `enabled` is false until the kv row loads. */ +export function useLunoraBetaPref(): LunoraBetaSnapshot { + return useSyncExternalStore(subscribe, getSnapshot, () => HIDDEN); +} + +/** + * When account pref and localStorage disagree, mirror localStorage and reload + * once so `LunoraSyncHost` picks the synced value (multi-device opt-in). + */ +function maybeSyncLocalFlagFromAccount() { + if (typeof window === "undefined") return; + try { + if (sessionStorage.getItem(PREFS_RELOAD_GUARD)) return; + const q = new URLSearchParams(window.location.search).get("lunora-sync"); + if (q === "on" || q === "off" || q === "0" || q === "1") return; + + const synced = lunoraBetaRow()?.enabled === true; + const localOn = isLunoraSyncEnabled(); + if (synced === localOn) return; + + mirrorLunoraFlag(synced); + sessionStorage.setItem(PREFS_RELOAD_GUARD, "1"); + hardReset(window.location.pathname + window.location.search); + } catch { + // sessionStorage / localStorage unavailable — skip cross-device sync. + } +} + +/** Mount once inside AuthGate to start the pref subscription + sync pass. */ +export function AccountPrefsController() { + useLunoraBetaPref(); + return null; +} diff --git a/src/data/collection.ts b/src/data/collection.ts index 59eff099..58bcd20f 100644 --- a/src/data/collection.ts +++ b/src/data/collection.ts @@ -8,7 +8,7 @@ import type { Node } from "./schema"; import { createNodes, deleteNodes, updateNodes } from "./api"; import { noteServerVersion } from "./app-version"; -import { isMirrorsEnabled } from "./flags"; +import { isLunoraSyncEnabled, isMirrorsEnabled } from "./flags"; import { runPromise } from "./nodes-client-effect"; import { makeSyncStream } from "./realtime"; import { appRuntime } from "./runtime"; @@ -90,6 +90,11 @@ function markSyncReady(): void { for (const listener of syncReadyListeners) listener(); } +/** Lunora flag-swap path marks the shell ready once `wholeOutline` has seeded. */ +export function markNodesSyncReady(): void { + markSyncReady(); +} + /** Force the outline to reconcile against server truth now (a fresh snapshot). * Used by the daily plugin's claim loser-path; a no-op before the socket * connects (or during the `/` prerender). */ @@ -423,6 +428,15 @@ export const nodesCollection = createCollection({ return () => {}; } + // ADR 0055 flag-swap: Lunora owns outline sync. Keep this collection idle + // (ready+empty) so e2e / default OFF path is unchanged; tree-store feeds + // from the Lunora collection instead. Don't markSyncReady here — Lunora + // bootstrap does once `wholeOutline` lands. + if (isLunoraSyncEnabled()) { + markReady(); + return () => {}; + } + let ready = false; const ensureReady = () => { if (ready) return; diff --git a/src/data/flags.test.ts b/src/data/flags.test.ts new file mode 100644 index 00000000..d4d65df3 --- /dev/null +++ b/src/data/flags.test.ts @@ -0,0 +1,67 @@ +import { afterEach, beforeEach, describe, expect, test } from "bun:test"; + +import { + isLunoraSyncEnabled, + isMirrorsEnabled, + LUNORA_SYNC_FLAG_KEY, +} from "./flags"; + +// bun test has no DOM — stub the surfaces flags.ts reads (see realtime.test.ts). +const store = new Map(); +const location = { href: "http://localhost/", search: "" }; + +beforeEach(() => { + store.clear(); + location.href = "http://localhost/"; + location.search = ""; + (globalThis as { window?: unknown }).window = { + localStorage: { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => { + store.set(k, v); + }, + removeItem: (k: string) => { + store.delete(k); + }, + }, + location, + }; +}); + +afterEach(() => { + delete (globalThis as { window?: unknown }).window; +}); + +describe("isLunoraSyncEnabled", () => { + test("defaults OFF", () => { + expect(isLunoraSyncEnabled()).toBe(false); + }); + + test("localStorage on enables", () => { + store.set(LUNORA_SYNC_FLAG_KEY, "on"); + expect(isLunoraSyncEnabled()).toBe(true); + }); + + test("localStorage off disables", () => { + store.set(LUNORA_SYNC_FLAG_KEY, "off"); + expect(isLunoraSyncEnabled()).toBe(false); + }); + + test("URL ?lunora-sync=on wins over localStorage off", () => { + store.set(LUNORA_SYNC_FLAG_KEY, "off"); + location.search = "?lunora-sync=on"; + expect(isLunoraSyncEnabled()).toBe(true); + }); + + test("URL ?lunora-sync=off wins over localStorage on", () => { + store.set(LUNORA_SYNC_FLAG_KEY, "on"); + location.search = "?lunora-sync=off"; + expect(isLunoraSyncEnabled()).toBe(false); + }); +}); + +describe("isMirrorsEnabled (smoke)", () => { + test("still defaults ON", () => { + expect(isMirrorsEnabled()).toBe(true); + }); +}); diff --git a/src/data/flags.ts b/src/data/flags.ts index a9d0ee9a..3ade304c 100644 --- a/src/data/flags.ts +++ b/src/data/flags.ts @@ -30,3 +30,37 @@ export function isMirrorsEnabled(): boolean { } return MIRRORS_DEFAULT; } + +/** ADR 0055 Phase-2: outline sync via Lunora shapes/mutators instead of custom DO. */ +export const LUNORA_SYNC_FLAG_KEY = "dotflowy:flag:lunora-sync"; + +// Default OFF — Lunora is alpha; classic DO is production. Opt in via Settings +// (synced `account-prefs`) or localStorage / URL for e2e and local dogfood. +const LUNORA_SYNC_DEFAULT = false; + +/** + * Whether outline sync rides Lunora (`/_lunora` + `@lunora/db`) instead of the + * custom `/api/sync` + `nodesCollection` path (ADR 0055). Default OFF. + * + * Kill-switch pairing (ADR 0055): the browser reads this flag (mirrored from + * synced `account-prefs` on load); Worker MCP reads env force then the same + * preference on classic DO. Flip env + client together when debugging divergence. + * + * Enable: Settings beta toggle (persists + reload), `"on"` in localStorage, or + * `?lunora-sync=on`. Disable: Settings, `"off"` in localStorage, or + * `?lunora-sync=off` (URL wins for that load; does not persist). + */ +export function isLunoraSyncEnabled(): boolean { + if (typeof window === "undefined") return LUNORA_SYNC_DEFAULT; + try { + const q = new URLSearchParams(window.location.search).get("lunora-sync"); + if (q === "on" || q === "1") return true; + if (q === "off" || q === "0") return false; + const v = window.localStorage.getItem(LUNORA_SYNC_FLAG_KEY); + if (v === "on") return true; + if (v === "off") return false; + } catch { + // localStorage / URLSearchParams can throw; fall back to the default. + } + return LUNORA_SYNC_DEFAULT; +} diff --git a/src/data/focus-key.ts b/src/data/focus-key.ts index f2c8e65e..9d602c4c 100644 --- a/src/data/focus-key.ts +++ b/src/data/focus-key.ts @@ -1,7 +1,7 @@ import type { Node } from "./schema"; -import { nodesCollection } from "./collection"; import { isMirrorsEnabled } from "./flags"; +import { getLiveNodes } from "./live-nodes"; import { buildTreeIndex } from "./tree"; import { getViewIsHidden, getViewRootId } from "./view-state"; import { buildVisibleRows, focusKeyAfterEdit } from "./visible-order"; @@ -16,16 +16,16 @@ import { buildVisibleRows, focusKeyAfterEdit } from "./visible-order"; * * Off the flag (the 99% path) a node id is unique, so we return it directly and * skip the rebuild entirely. With the flag on we build a fresh index from - * `nodesCollection.toArray` -- synchronously current after `runStructural`, the - * same technique the structural invariant check uses -- rather than - * `getTreeIndex()`, whose change-notify can lag the optimistic apply. + * `getLiveNodes()` -- synchronously current after `runStructural` (classic + * `nodesCollection` or Lunora `wholeOutline`) -- rather than `getTreeIndex()`, + * whose change-notify can lag the optimistic apply. * * Lives here rather than beside its first caller because the markdown paste * (ADR 0044) needs it too, from a module the editor imports. */ export function focusKeyFor(instanceId: string, activeKey: string): string { if (!isMirrorsEnabled()) return instanceId; - const index = buildTreeIndex(nodesCollection.toArray as Node[]); + const index = buildTreeIndex(getLiveNodes() as Node[]); const rows = buildVisibleRows( index, getViewRootId(), diff --git a/src/data/history.ts b/src/data/history.ts index b2910dc7..d1ad3bc4 100644 --- a/src/data/history.ts +++ b/src/data/history.ts @@ -107,10 +107,15 @@ export const RESTORE_SLICE_OPS = 500; * slice, in order, inside ONE transaction -- a `runStructural` body for the * small case, one `runStructuralSliced` call for the big one -- or call * `revert` if the apply failed and rolled back. + * + * When Lunora sync is ON, prefer `targetNodes` + `restoreNodes` mutator (one + * watermark) over `slices` writing `nodesCollection`. */ export interface RestorePlan { /** Total collection writes the restore will make. */ opCount: number; + /** Full target outline (history snapshot) — Lunora `restoreNodes` input. */ + targetNodes: readonly Node[]; /** Apply closures in order; each makes at most RESTORE_SLICE_OPS writes. */ slices: ReadonlyArray<() => void>; /** Writes applied so far -- the sliced path's progress read. */ @@ -189,6 +194,7 @@ function planRestore( return { opCount: deletes.length + upserts.length, + targetNodes: entry.nodes, slices, applied: () => applied, // Only focus if the focused node still exists in the restored state. The focus diff --git a/src/data/keyboard-inset.ts b/src/data/keyboard-inset.ts new file mode 100644 index 00000000..13fc6b6a --- /dev/null +++ b/src/data/keyboard-inset.ts @@ -0,0 +1,105 @@ +/** + * Publishes `--kb-inset` on ``: how far a `position: fixed; bottom: 0` + * surface must lift to sit just above the software keyboard (ADR 0030). + * + * **It MEASURES the anchor instead of computing it.** Every previous version of + * this tried to derive the lift from a viewport property, and each one worked + * until iOS Safari moved its chrome. Measured on one iPhone across two samples, + * one keyboard session: + * + * | innerHeight | clientHeight | pre-keyboard band | vv.height | vv.offsetTop | + * | ----------- | ------------ | ----------------- | --------- | ------------ | + * | 526 | 498 | 590 | 234 | 108 | + * | 482 | 498 | 590 | 234 | 108 | + * + * Three candidate anchors, none of them agreeing, and `innerHeight` moving 44px + * between samples while nothing else did. Formulas built on `innerHeight`, + * `clientHeight`, or the pre-keyboard band are each correct only while the + * chrome is in the state they assumed — which is exactly why the bar was fine + * "for the most part" and then suddenly wasn't. + * + * So: append a zero-size `position: fixed; bottom: 0` PROBE and read its + * `getBoundingClientRect().bottom`. That IS where `bottom: 0` resolves, by + * definition, with no model in between — and a client rect is reported in the + * same space as `visualViewport.height`, so the band's bottom edge is just + * `vv.height` and the lift is their difference. Fed the two samples above, this + * yields the correct 228 in both even though the anchor itself measured 418 and + * 390. Any future chrome drift is absorbed for free. + * + * Writing a CSS custom property rather than returning a React value is + * deliberate: the keyboard animates over many frames, and no consumer should + * re-render per frame to follow it. `styles.css` declares the `0px` default. + */ + +/** Runs only while a text-editable is focused — the only time the value can be + * non-zero, and the only time a per-frame loop is worth paying for. */ +function isEditing(): boolean { + const el = document.activeElement; + return ( + el instanceof HTMLElement && + (el.isContentEditable || + el instanceof HTMLInputElement || + el instanceof HTMLTextAreaElement) + ); +} + +function install(): void { + const vv = window.visualViewport; + if (!vv) return; + + const probe = document.createElement("div"); + // `visibility: hidden` still produces a layout box (unlike `display: none`), + // which is the whole point — we need its rect, not its pixels. + probe.style.cssText = + "position:fixed;bottom:0;left:0;width:0;height:0;visibility:hidden;pointer-events:none"; + probe.setAttribute("aria-hidden", "true"); + document.body.appendChild(probe); + + const root = document.documentElement; + let current = -1; + let raf = 0; + + const measure = () => { + raf = 0; + // Not editing: no keyboard, so no lift. Cheap early exit that also stops the + // loop from fighting a `bottom: 0` element during ordinary page scrolling. + const lift = isEditing() + ? Math.max( + 0, + Math.round(probe.getBoundingClientRect().bottom - vv.height), + ) + : 0; + // Only touch the DOM when the value actually changes: iOS fires resize and + // scroll in bursts through the keyboard animation, and most frames repeat. + if (lift !== current) { + current = lift; + root.style.setProperty("--kb-inset", `${lift}px`); + } + if (isEditing()) raf = requestAnimationFrame(measure); + }; + + const start = () => { + if (!raf) raf = requestAnimationFrame(measure); + }; + const stop = () => { + // focusout fires before the next focusin when moving between bullets, so + // settle a frame before deciding the keyboard is really gone. + requestAnimationFrame(() => { + if (!isEditing()) measure(); + }); + }; + + // The rAF loop is the primary signal (Safari moves its chrome without firing + // anything useful); these just start it and catch the settle after blur. + document.addEventListener("focusin", start); + document.addEventListener("focusout", stop); + vv.addEventListener("resize", start); + vv.addEventListener("scroll", start); + measure(); +} + +// SPA-only, and the `/` prerender has no window (AGENTS.md SPA/no-SSR rule). +if (typeof window !== "undefined") { + if (document.body) install(); + else document.addEventListener("DOMContentLoaded", install, { once: true }); +} diff --git a/src/data/live-nodes.ts b/src/data/live-nodes.ts new file mode 100644 index 00000000..ccb4d14c --- /dev/null +++ b/src/data/live-nodes.ts @@ -0,0 +1,36 @@ +/** + * Live outline rows for event-time reads that must see optimistic writes + * synchronously (selection refresh, markdown paste seam, multi-node mirror). + * + * Flag OFF → classic `nodesCollection`. Flag ON → Lunora `wholeOutline` + * collection (not `getTreeIndex()`, whose notify can lag the mutator apply — + * same reason `refreshSelection` historically read the collection directly). + */ + +import type { Node } from "./schema"; + +import { nodesCollection } from "./collection"; +import { isLunoraSyncEnabled } from "./flags"; +import { outlineNodeToNode } from "./lunora-bridge"; +import { getLunoraOutlineContext } from "./lunora-sync"; +import { rowToNode, type OutlineNode } from "./outline-plans"; + +/** Wire-shaped nodes (no Lunora `userId`) — selection / tree-index callers. */ +export function getLiveNodes(): Node[] { + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + return lunora.store.collection.toArray.map((row) => + outlineNodeToNode(rowToNode(row)), + ); + } + } + return nodesCollection.toArray as Node[]; +} + +/** Planner nodes with shard `userId` — Lunora mutator args (restore/import). */ +export function getLiveOutlineNodes(): OutlineNode[] { + const lunora = getLunoraOutlineContext(); + if (!lunora) return []; + return lunora.store.collection.toArray.map(rowToNode); +} diff --git a/src/data/lunora-bridge.test.ts b/src/data/lunora-bridge.test.ts new file mode 100644 index 00000000..0977126f --- /dev/null +++ b/src/data/lunora-bridge.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, test } from "bun:test"; + +import { + bridgeOrderedChildren, + bridgeTreeIndex, + outlineNodeToNode, + rowsToOutlineNodes, +} from "./lunora-bridge"; +import { + applyPlan, + buildTreeIndex, + makeOutlineNode, + nodeToDocFields, + planIndent, + planInsertSibling, + planRemoveNode, + type OutlineNode, +} from "./outline-plans"; + +const USER = "user-bridge"; + +function toRows(nodes: OutlineNode[]) { + return nodes.map(nodeToDocFields); +} + +describe("lunora-bridge (ADR 0004 seam)", () => { + test("maps rows → OutlineNode via shared rowToNode", () => { + const rows = [ + { + _id: "a", + parentId: null, + prevSiblingId: null, + text: "hello", + isTask: false, + completed: false, + collapsed: false, + bookmarkedAt: null, + mirrorOf: null, + createdAt: 1, + updatedAt: 1, + origin: null, + kind: null, + userId: USER, + }, + ]; + expect(rowsToOutlineNodes(rows)).toEqual([ + expect.objectContaining({ id: "a", text: "hello", userId: USER }), + ]); + expect(outlineNodeToNode(rowsToOutlineNodes(rows)[0]!)).not.toHaveProperty( + "userId", + ); + }); + + test("bridge order matches planner apply (insert/indent/remove)", () => { + let nodes: OutlineNode[] = [ + makeOutlineNode({ + id: "a", + userId: USER, + parentId: null, + prevSiblingId: null, + text: "a", + createdAt: 0, + updatedAt: 0, + }), + makeOutlineNode({ + id: "b", + userId: USER, + parentId: null, + prevSiblingId: "a", + text: "b", + createdAt: 1, + updatedAt: 1, + }), + ]; + + { + const index = buildTreeIndex(nodes); + const plan = planInsertSibling(index, { + id: "c", + userId: USER, + parentId: null, + afterId: "a", + text: "c", + createdAt: 2, + updatedAt: 2, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + } + + { + const index = buildTreeIndex(nodes); + const plan = planIndent(index, "c", 3); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + } + + const bridged = bridgeTreeIndex(toRows(nodes)); + expect(bridgeOrderedChildren(bridged, null).map((n) => n.id)).toEqual([ + "a", + "b", + ]); + expect(bridgeOrderedChildren(bridged, "a").map((n) => n.id)).toEqual(["c"]); + + { + const index = buildTreeIndex(nodes); + const plan = planRemoveNode(index, "a", 4); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + } + + const afterRemove = bridgeTreeIndex(toRows(nodes)); + expect(bridgeOrderedChildren(afterRemove, null).map((n) => n.id)).toEqual([ + "b", + ]); + }); +}); diff --git a/src/data/lunora-bridge.ts b/src/data/lunora-bridge.ts new file mode 100644 index 00000000..e3cdf3e1 --- /dev/null +++ b/src/data/lunora-bridge.ts @@ -0,0 +1,35 @@ +/** + * ADR 0004 handoff seam — build Dotflowy-shaped `TreeIndex` / ordered children + * from Lunora collection rows (`wholeOutline`). + */ + +import type { NodeDocLike, OutlineNode, TreeIndex } from "./outline-plans"; +import type { Node } from "./schema"; + +import { buildTreeIndex, childrenOf, rowToNode } from "./outline-plans"; + +/** Map collection / query rows → planner nodes. */ +export function rowsToOutlineNodes(rows: Iterable): OutlineNode[] { + const out: OutlineNode[] = []; + for (const row of rows) out.push(rowToNode(row)); + return out; +} + +/** Drop Lunora-only `userId` so tree-store / editor see wire `Node`. */ +export function outlineNodeToNode(node: OutlineNode): Node { + const { userId: _userId, ...rest } = node; + return rest; +} + +/** Lunora rows → TreeIndex (ordered sibling ids per parent). */ +export function bridgeTreeIndex(rows: Iterable): TreeIndex { + return buildTreeIndex(rowsToOutlineNodes(rows)); +} + +/** Ordered children under `parentId` (`null` = top level). */ +export function bridgeOrderedChildren( + index: TreeIndex, + parentId: string | null, +): OutlineNode[] { + return childrenOf(index, parentId) as OutlineNode[]; +} diff --git a/src/data/lunora-checkpoints.test.ts b/src/data/lunora-checkpoints.test.ts new file mode 100644 index 00000000..8799fc5a --- /dev/null +++ b/src/data/lunora-checkpoints.test.ts @@ -0,0 +1,141 @@ +import { describe, expect, test } from "bun:test"; + +import { + DIRECT_TRANSACTION_METADATA_KEY, + SHAPE_CHECKPOINT_FALLBACK_MS, + shapeFirstCheckpoints, + withDirectOptimisticMetadata, + type CheckpointRegistry, +} from "./lunora-checkpoints"; + +function deferred() { + let resolve!: () => void; + const promise = new Promise((r) => { + resolve = r; + }); + return { promise, resolve }; +} + +function makeShapeGate(): CheckpointRegistry & { + pending: Map>; +} { + const pending = new Map>(); + return { + pending, + awaitCheckpoint: async () => undefined, + resolve: (watermark) => { + const id = watermark.mutationId; + if (id == null) return; + const d = pending.get(id); + if (d) { + pending.delete(id); + d.resolve(); + } + }, + awaitMutationId: (id) => { + let d = pending.get(id); + if (!d) { + d = deferred(); + pending.set(id, d); + } + return d.promise; + }, + }; +} + +describe("withDirectOptimisticMetadata", () => { + test("stamps __tanstack_db_direct without dropping serverRef", () => { + const raw = { + setText: (_args: never) => ({ + metadata: { serverRef: "mutators:setText" } as Record, + }), + }; + const bound = withDirectOptimisticMetadata(raw); + const tx = bound.setText({} as never); + expect(tx.metadata.serverRef).toBe("mutators:setText"); + expect(tx.metadata[DIRECT_TRANSACTION_METADATA_KEY]).toBe(true); + }); +}); + +describe("shapeFirstCheckpoints", () => { + test("resolves when the shape poke arrives (no fallback)", async () => { + const shape = makeShapeGate(); + const client = { confirmedMutationWatermark: () => 0 }; + const gate = shapeFirstCheckpoints(client, "u1", shape, { + fallbackMs: 5_000, + }); + + const wait = gate.awaitMutationId(1); + let done = false; + void wait.then(() => { + done = true; + }); + + await new Promise((r) => setTimeout(r, 30)); + expect(done).toBe(false); + + shape.resolve({ mutationId: 1 }); + await wait; + expect(done).toBe(true); + }); + + test("falls back after RPC watermark when shape never pokes", async () => { + const shape = makeShapeGate(); + let watermark = 0; + const client = { + confirmedMutationWatermark: () => watermark, + }; + const gate = shapeFirstCheckpoints(client, "u1", shape, { + fallbackMs: 40, + }); + + const wait = gate.awaitMutationId(7); + // Watermark still behind — fallback must not arm yet. + await new Promise((r) => setTimeout(r, 80)); + let settled = false; + void wait.then(() => { + settled = true; + }); + expect(settled).toBe(false); + + watermark = 7; + await wait; + expect(settled).toBe(true); + }); + + test("default fallback window is 3s", () => { + expect(SHAPE_CHECKPOINT_FALLBACK_MS).toBe(3000); + }); + + test("shape await rejection still falls back after RPC watermark", async () => { + const pending = new Map>(); + const shape: CheckpointRegistry = { + awaitCheckpoint: async () => undefined, + resolve: () => undefined, + awaitMutationId: (id) => { + let d = pending.get(id); + if (!d) { + d = deferred(); + pending.set(id, d); + } + // Reject instead of resolve — must not hang or throw unhandled. + return d.promise.then(() => { + throw new Error("shape poke missed"); + }); + }, + }; + let watermark = 0; + const gate = shapeFirstCheckpoints( + { confirmedMutationWatermark: () => watermark }, + "u1", + shape, + { fallbackMs: 40 }, + ); + + const wait = gate.awaitMutationId(3); + // Trigger the rejected shape wait. + pending.get(3)?.resolve(); + watermark = 3; + await wait; + }); +}); diff --git a/src/data/lunora-checkpoints.ts b/src/data/lunora-checkpoints.ts new file mode 100644 index 00000000..ce4944c6 --- /dev/null +++ b/src/data/lunora-checkpoints.ts @@ -0,0 +1,99 @@ +/** + * Lunora mutator checkpoint + optimistic-hold helpers (ADR 0055). + * + * Kept dependency-light so unit tests can pin the overlay/fallback policy + * without standing up a full outline store. + */ + +import type { lunoraCollectionOptions } from "@lunora/db"; +import type { LunoraClient } from "lunorash/client"; + +export type CheckpointRegistry = ReturnType< + typeof lunoraCollectionOptions +>["checkpoints"]; + +/** + * TanStack DB's "direct" transaction flag (same key `collection.insert`/ + * `update` stamp). Completing `mutationFn` with no pending shape sync drops + * optimistic rows as "stale" unless this is set — our checkpoint fallback + * then reverts typed text to the old synced value. + * + * String literal on purpose: `@tanstack/db` doesn't re-export the constant + * from its package root (lives under `collection/transaction-metadata`). + */ +export const DIRECT_TRANSACTION_METADATA_KEY = "__tanstack_db_direct"; + +/** Stamp TanStack's direct-tx flag before `mutationFn` settles. */ +export function withDirectOptimisticMetadata< + M extends Record< + string, + (args: never) => { metadata: Record } + >, +>(mutators: M): M { + const bound = {} as M; + for (const name of Object.keys(mutators) as Array) { + const run = mutators[name]!; + bound[name] = ((args: never) => { + const tx = run(args); + tx.metadata[DIRECT_TRANSACTION_METADATA_KEY] = true; + return tx; + }) as M[typeof name]; + } + return bound; +} + +/** + * Hold optimistic overlays until the shape poke lands — NOT until RPC ack. + * + * Short-circuiting on `confirmedMutationWatermark` (RPC ack) drops the + * overlay before `wholeOutline` has the new row. Always wait on the shape + * gate first; if a poke is missed, fall back after the RPC ack so Today + * can't hang forever. Paired with `withDirectOptimisticMetadata` so the + * fallback doesn't revert typed text. + */ +export const SHAPE_CHECKPOINT_FALLBACK_MS = 3000; + +export type ShapeFirstCheckpointsOpts = { + /** Override for unit tests (default {@link SHAPE_CHECKPOINT_FALLBACK_MS}). */ + fallbackMs?: number; +}; + +export function shapeFirstCheckpoints( + client: Pick, + shardKey: string, + shape: CheckpointRegistry, + opts: ShapeFirstCheckpointsOpts = {}, +): CheckpointRegistry { + const fallbackMs = opts.fallbackMs ?? SHAPE_CHECKPOINT_FALLBACK_MS; + return { + awaitCheckpoint: (cursor) => shape.awaitCheckpoint(cursor), + resolve: (watermark) => shape.resolve(watermark), + awaitMutationId: (id) => { + let settled = false; + return new Promise((resolve) => { + const finish = () => { + if (settled) return; + settled = true; + resolve(); + }; + // Shape wait failure must not become an unhandled rejection — the + // RPC-watermark fallback below still settles the overlay. + void shape.awaitMutationId(id).then(finish, () => undefined); + + const armFallback = () => { + if (settled) return; + if (id > client.confirmedMutationWatermark(shardKey)) { + setTimeout(armFallback, 50); + return; + } + setTimeout(() => { + if (settled) return; + shape.resolve({ mutationId: id }); + finish(); + }, fallbackMs); + }; + armFallback(); + }); + }, + }; +} diff --git a/src/data/lunora-client.ts b/src/data/lunora-client.ts new file mode 100644 index 00000000..b1fbc171 --- /dev/null +++ b/src/data/lunora-client.ts @@ -0,0 +1,23 @@ +/** + * Singleton LunoraClient for the ADR 0055 flag-swap path. + * Same-origin `/_lunora/*` (Vite proxies to wrangler in `bun run dev`). + * SPA/no-SSR: never construct during prerender. + */ + +import { LunoraClient } from "lunorash/client"; + +let client: LunoraClient | null = null; + +/** Lazily create the client once in the browser. */ +export function getLunoraClient(): LunoraClient { + if (typeof window === "undefined") { + throw new Error("getLunoraClient: browser only (SPA/no-SSR)"); + } + if (!client) { + const url = + (import.meta.env.VITE_LUNORA_URL as string | undefined) ?? + window.location.origin; + client = new LunoraClient({ url }); + } + return client; +} diff --git a/src/data/lunora-kv-store.ts b/src/data/lunora-kv-store.ts new file mode 100644 index 00000000..23957733 --- /dev/null +++ b/src/data/lunora-kv-store.ts @@ -0,0 +1,32 @@ +/** + * Lunora row types for kv side-collections (ADR 0055 phase 2b). + * Collections + mutators are wired in `lunora-outline-store.ts` (one + * `bindMutators` / clientSeq FIFO with outline writes). + */ + +export type TagColorRowDoc = { + _id: string; + tag: string; + color: string; + userId: string; + _creationTime?: number; +} & Record; + +export type SavedQueryRowDoc = { + _id: string; + name: string; + query: string; + createdAt: number; + userId: string; + _creationTime?: number; +} & Record; + +/** Daily scaffold key → nodeId (ADR 0052). Collection getKey = `key`. */ +export type DailyIndexRowDoc = { + _id: string; + key: string; + nodeId: string; + touchedAt: number; + userId: string; + _creationTime?: number; +} & Record; diff --git a/src/data/lunora-migrate.ts b/src/data/lunora-migrate.ts new file mode 100644 index 00000000..7debba38 --- /dev/null +++ b/src/data/lunora-migrate.ts @@ -0,0 +1,232 @@ +/** + * One-shot UserOutlineDO → Lunora shard migrate (ADR 0055). + * + * Safe default: if Lunora already has nodes, skip (do not replace). + * Classic DO data is left untouched. + * + * Auto-runs from `lunora-sync` when flag ON + Lunora empty + classic has data. + * Manual: `await window.__dotflowyMigrateToLunora()` or More menu. + */ + +import type { OutlineStore } from "./lunora-outline-store"; +import type { OutlineNode } from "./outline-plans"; + +import { notifySaveFailed } from "./save-failure"; + +export type MigrateResult = + | { status: "migrated"; nodes: number; kv: number } + | { status: "skipped-nonempty"; nodes: number } + | { status: "skipped-empty-source" } + | { status: "failed"; error: unknown }; + +type ClassicNode = { + id: string; + parentId: string | null; + prevSiblingId: string | null; + text: string; + isTask: boolean; + completed: boolean; + collapsed: boolean; + bookmarkedAt: number | null; + mirrorOf: string | null; + createdAt: number; + updatedAt: number; + origin: string | null; + kind: "paragraph" | null; +}; + +type KvRow = { key: string; value: unknown }; + +const IMPORT_CHUNK = 500; + +function asOutlineNode(n: ClassicNode, userId: string): OutlineNode { + return { + id: n.id, + parentId: n.parentId, + prevSiblingId: n.prevSiblingId, + text: n.text, + isTask: n.isTask, + completed: n.completed, + collapsed: n.collapsed, + bookmarkedAt: n.bookmarkedAt, + mirrorOf: n.mirrorOf, + createdAt: n.createdAt, + updatedAt: n.updatedAt, + origin: n.origin, + kind: n.kind === "paragraph" ? "paragraph" : null, + userId, + }; +} + +async function fetchClassicNodes(): Promise { + const res = await fetch("/api/nodes", { credentials: "include" }); + if (!res.ok) throw new Error(`GET /api/nodes ${res.status}`); + const body = (await res.json()) as ClassicNode[]; + return Array.isArray(body) ? body : []; +} + +async function fetchKv(collection: string): Promise { + const res = await fetch( + `/api/kv?collection=${encodeURIComponent(collection)}`, + { credentials: "include" }, + ); + if (!res.ok) throw new Error(`GET /api/kv ${collection} ${res.status}`); + const body = (await res.json()) as unknown[]; + if (!Array.isArray(body)) return []; + // /api/kv GET returns the stored values; daily-index/tag-colors/saved-queries + // each embed their key inside the value object. + return body.map((value) => { + const v = value as Record; + const key = + typeof v.key === "string" + ? v.key + : typeof v.tag === "string" + ? v.tag + : typeof v.id === "string" + ? v.id + : String(v.key ?? ""); + return { key, value }; + }); +} + +async function importNodeChunks( + store: OutlineStore, + userId: string, + nodes: OutlineNode[], +): Promise { + for (let i = 0; i < nodes.length; i += IMPORT_CHUNK) { + const chunk = nodes.slice(i, i + IMPORT_CHUNK); + const tx = store.mutators.importNodes({ userId, nodes: chunk }); + await tx.isPersisted.promise; + } +} + +async function importKv(store: OutlineStore, userId: string): Promise { + let count = 0; + const t = Date.now(); + + const tags = await fetchKv("tag-colors").catch(() => [] as KvRow[]); + for (const row of tags) { + const v = row.value as { tag?: string; color?: string }; + const tag = String(v.tag ?? row.key); + const color = String(v.color ?? ""); + if (!tag || !color) continue; + const tx = store.mutators.upsertTagColor({ userId, tag, color }); + await tx.isPersisted.promise; + count += 1; + } + + const saved = await fetchKv("saved-queries").catch(() => [] as KvRow[]); + for (const row of saved) { + const v = row.value as { + id?: string; + name?: string; + query?: string; + createdAt?: number; + }; + const id = String(v.id ?? row.key); + if (!id) continue; + const tx = store.mutators.upsertSavedQuery({ + userId, + id, + name: String(v.name ?? v.query ?? id), + query: String(v.query ?? ""), + createdAt: Number(v.createdAt ?? t), + }); + await tx.isPersisted.promise; + count += 1; + } + + const daily = await fetchKv("daily-index").catch(() => [] as KvRow[]); + for (const row of daily) { + const v = row.value as { key?: string; nodeId?: string }; + const key = String(v.key ?? row.key); + const nodeId = String(v.nodeId ?? ""); + if (!key || !nodeId) continue; + const tx = store.mutators.upsertDailyMapping({ + userId, + key, + nodeId, + touchedAt: t, + }); + await tx.isPersisted.promise; + count += 1; + } + + return count; +} + +/** + * Import classic DO outline (+ kv) into an empty Lunora shard. + * @param force — unused for replace (replace is out of scope); reserved. + */ +export async function migrateClassicToLunora( + store: OutlineStore, + userId: string, + opts: { force?: boolean } = {}, +): Promise { + void opts.force; + const lunoraCount = store.collection.toArray.length; + if (lunoraCount > 0) { + return { status: "skipped-nonempty", nodes: lunoraCount }; + } + + try { + const classic = await fetchClassicNodes(); + if (classic.length === 0) { + return { status: "skipped-empty-source" }; + } + const nodes = classic.map((n) => asOutlineNode(n, userId)); + await importNodeChunks(store, userId, nodes); + const kv = await importKv(store, userId); + return { status: "migrated", nodes: nodes.length, kv }; + } catch (error) { + return { status: "failed", error }; + } +} + +/** Auto path: migrate when Lunora empty; returns whether seedIfEmpty should run. */ +export async function maybeAutoMigrateToLunora( + store: OutlineStore, + userId: string, +): Promise<"seed" | "ready"> { + const result = await migrateClassicToLunora(store, userId); + switch (result.status) { + case "migrated": + console.info( + `[lunora-migrate] imported ${result.nodes} nodes + ${result.kv} kv rows from classic DO`, + ); + return "ready"; + case "skipped-nonempty": + return "ready"; + case "skipped-empty-source": + return "seed"; + case "failed": + console.warn("[lunora-migrate] failed", result.error); + notifySaveFailed(result.error); + // Don't seed demo bullets over a failed migrate of real data — leave empty + // so the operator can retry via __dotflowyMigrateToLunora. + return "ready"; + } +} + +/** DevTools / More-menu entry. */ +export function installMigrateConsoleHelper( + getStore: () => { store: OutlineStore; userId: string } | null, +): void { + if (typeof window === "undefined") return; + ( + window as unknown as { + __dotflowyMigrateToLunora?: () => Promise; + } + ).__dotflowyMigrateToLunora = async () => { + const ctx = getStore(); + if (!ctx) { + return { + status: "failed", + error: new Error("Lunora sync not started (flag off?)"), + }; + } + return migrateClassicToLunora(ctx.store, ctx.userId); + }; +} diff --git a/src/data/lunora-outline-store.ts b/src/data/lunora-outline-store.ts new file mode 100644 index 00000000..db6ab844 --- /dev/null +++ b/src/data/lunora-outline-store.ts @@ -0,0 +1,694 @@ +/** + * Client outline store for the Lunora flag-swap path (ADR 0055). + * `wholeOutline` shape + `bindMutators` with watermark checkpoints (replaces + * `waitForSeq`). + */ + +import type { LunoraClient } from "lunorash/client"; + +import { lunoraCollectionOptions } from "@lunora/db"; +import { bindMutators, defineMutator } from "@lunora/db/mutators"; +import { createCollection, type Collection } from "@tanstack/db"; + +import type { + DailyIndexRowDoc, + SavedQueryRowDoc, + TagColorRowDoc, +} from "./lunora-kv-store"; + +import { + shapeFirstCheckpoints, + withDirectOptimisticMetadata, + type CheckpointRegistry, +} from "./lunora-checkpoints"; +import { + buildTreeIndex, + nodeToRow, + planAppendChild, + planImportNodes, + planIndent, + planIndentMany, + planInsertChildAtStart, + planInsertSibling, + planMaterializeDailyNodes, + planMirrorNode, + planMoveMany, + planMoveNode, + planOutdent, + planOutdentMany, + planRemoveMany, + planRemoveNode, + planRestoreNodes, + planSeedIfEmpty, + planSetBookmarkedAt, + planSetCollapsed, + planSetCompleted, + planSetIsTask, + planSetKind, + planSetText, + planSplitNode, + rowToNode, + type NodeDocLike, + type OutlineNode, + type OutlinePlan, +} from "./outline-plans"; + +/** + * Kv-only mutators poke their own shape, not `wholeOutline`. Fan those pokes + * into the mutator gate so a shape-based wait can still complete (e2e force- + * pokes `wholeOutline` for the same reason). + */ +function relayCheckpoints( + from: CheckpointRegistry, + to: CheckpointRegistry, +): void { + const orig = from.resolve.bind(from); + from.resolve = (watermark) => { + orig(watermark); + to.resolve(watermark); + }; +} + +/** Row shape for TanStack — Lunora Doc + index signature for collection drafts. */ +export type NodeRow = NodeDocLike & + Record & { _creationTime?: number }; + +function applyPlanToCollection( + collection: Collection, + plan: OutlinePlan, +): void { + for (const id of plan.deletes) { + collection.delete(id); + } + for (const patch of plan.patches) { + collection.update(patch.id, (draft) => { + Object.assign(draft, patch.fields); + }); + } + for (const insert of plan.inserts) { + collection.insert(nodeToRow(insert) as NodeRow); + } +} + +function snapshotNodes(collection: Collection): OutlineNode[] { + return collection.toArray.map(rowToNode); +} + +export type OutlineStore = { + collection: Collection; + /** Phase 2b — Lunora tag colors (flag ON). */ + tagColors: Collection; + /** Phase 2b — Lunora saved queries (flag ON). */ + savedQueries: Collection; + /** Phase 2b — Lunora daily index (flag ON). */ + dailyIndex: Collection; + mutators: ReturnType; +}; + +function bindOutlineMutators( + client: LunoraClient, + collection: Collection, + tagColors: Collection, + savedQueries: Collection, + dailyIndex: Collection, + checkpoints: ReturnType< + typeof lunoraCollectionOptions + >["checkpoints"], + userId: string, +) { + return bindMutators( + client, + { + checkpoints, + collections: { + nodes: collection as never, + tagColors: tagColors as never, + savedQueries: savedQueries as never, + dailyIndex: dailyIndex as never, + }, + shardKey: userId, + }, + { + insertSibling: defineMutator<{ + id: string; + userId: string; + parentId: string | null; + afterId: string | null; + text: string; + isTask?: boolean; + kind?: "paragraph" | null; + createdAt: number; + updatedAt: number; + }>({ + serverRef: "mutators:insertSibling", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planInsertSibling(index, args); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + insertChildAtStart: defineMutator<{ + id: string; + userId: string; + parentId: string | null; + text: string; + isTask?: boolean; + kind?: "paragraph" | null; + createdAt: number; + updatedAt: number; + }>({ + serverRef: "mutators:insertChildAtStart", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planInsertChildAtStart(index, args); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + appendChild: defineMutator<{ + id: string; + userId: string; + parentId: string | null; + text: string; + isTask?: boolean; + kind?: "paragraph" | null; + createdAt: number; + updatedAt: number; + }>({ + serverRef: "mutators:appendChild", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planAppendChild(index, args); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + importNodes: defineMutator<{ + userId: string; + nodes: OutlineNode[]; + }>({ + serverRef: "mutators:importNodes", + apply: (_ctx, args) => { + applyPlanToCollection(collection, planImportNodes(args.nodes)); + }, + }), + splitNode: defineMutator<{ + id: string; + newId: string; + userId: string; + parentId: string | null; + afterId: string; + leftText: string; + rightText: string; + isTask?: boolean; + kind?: "paragraph" | null; + createdAt: number; + updatedAt: number; + }>({ + serverRef: "mutators:splitNode", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planSplitNode(index, args); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + indent: defineMutator<{ + id: string; + userId: string; + updatedAt: number; + resolveMirror?: boolean; + }>({ + serverRef: "mutators:indent", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planIndent( + index, + args.id, + args.updatedAt, + args.resolveMirror ?? false, + ); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + outdent: defineMutator<{ id: string; userId: string; updatedAt: number }>( + { + serverRef: "mutators:outdent", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planOutdent(index, args.id, args.updatedAt); + if (plan) applyPlanToCollection(collection, plan); + }, + }, + ), + removeNode: defineMutator<{ + id: string; + userId: string; + updatedAt: number; + }>({ + serverRef: "mutators:removeNode", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planRemoveNode(index, args.id, args.updatedAt); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + moveNode: defineMutator<{ + id: string; + userId: string; + newParentId: string | null; + afterSiblingId: string | null; + updatedAt: number; + expandIds?: string[]; + }>({ + serverRef: "mutators:moveNode", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planMoveNode(index, args); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + setText: defineMutator<{ + id: string; + userId: string; + text: string; + updatedAt: number; + }>({ + serverRef: "mutators:setText", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planSetText(index, args.id, args.text, args.updatedAt); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + setCompleted: defineMutator<{ + id: string; + userId: string; + completed: boolean; + updatedAt: number; + }>({ + serverRef: "mutators:setCompleted", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planSetCompleted( + index, + args.id, + args.completed, + args.updatedAt, + ); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + setCollapsed: defineMutator<{ + id: string; + userId: string; + collapsed: boolean; + updatedAt: number; + }>({ + serverRef: "mutators:setCollapsed", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planSetCollapsed( + index, + args.id, + args.collapsed, + args.updatedAt, + ); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + setIsTask: defineMutator<{ + id: string; + userId: string; + isTask: boolean; + updatedAt: number; + }>({ + serverRef: "mutators:setIsTask", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planSetIsTask( + index, + args.id, + args.isTask, + args.updatedAt, + ); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + setKind: defineMutator<{ + id: string; + userId: string; + kind: "paragraph" | null; + updatedAt: number; + }>({ + serverRef: "mutators:setKind", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planSetKind(index, args.id, args.kind, args.updatedAt); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + setBookmarkedAt: defineMutator<{ + id: string; + userId: string; + bookmarkedAt: number | null; + updatedAt: number; + }>({ + serverRef: "mutators:setBookmarkedAt", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planSetBookmarkedAt( + index, + args.id, + args.bookmarkedAt, + args.updatedAt, + ); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + restoreNodes: defineMutator<{ + userId: string; + nodes: OutlineNode[]; + }>({ + serverRef: "mutators:restoreNodes", + apply: (_ctx, args) => { + const plan = planRestoreNodes(snapshotNodes(collection), args.nodes); + applyPlanToCollection(collection, plan); + }, + }), + mirrorNode: defineMutator<{ + id: string; + userId: string; + sourceId: string; + targetParentId: string | null; + createdAt: number; + updatedAt: number; + }>({ + serverRef: "mutators:mirrorNode", + apply: (_ctx, args) => { + const index = buildTreeIndex(snapshotNodes(collection)); + const plan = planMirrorNode(index, args); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + removeMany: defineMutator<{ + userId: string; + nodeIds: string[]; + updatedAt: number; + }>({ + serverRef: "mutators:removeMany", + apply: (_ctx, args) => { + const plan = planRemoveMany( + snapshotNodes(collection), + args.nodeIds, + args.updatedAt, + ); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + moveMany: defineMutator<{ + userId: string; + targetId: string | null; + nodeIds: string[]; + updatedAt: number; + }>({ + serverRef: "mutators:moveMany", + apply: (_ctx, args) => { + const plan = planMoveMany(snapshotNodes(collection), { + targetId: args.targetId, + nodeIds: args.nodeIds, + updatedAt: args.updatedAt, + }); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + indentMany: defineMutator<{ + userId: string; + nodeIds: string[]; + updatedAt: number; + resolveMirror?: boolean; + }>({ + serverRef: "mutators:indentMany", + apply: (_ctx, args) => { + const plan = planIndentMany( + snapshotNodes(collection), + args.nodeIds, + args.updatedAt, + args.resolveMirror ?? false, + ); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + outdentMany: defineMutator<{ + userId: string; + nodeIds: string[]; + updatedAt: number; + }>({ + serverRef: "mutators:outdentMany", + apply: (_ctx, args) => { + const plan = planOutdentMany( + snapshotNodes(collection), + args.nodeIds, + args.updatedAt, + ); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + materializeDailyNodes: defineMutator<{ + userId: string; + inserts: Array<{ + id: string; + parentId: string | null; + afterId: string | null; + text: string; + }>; + createdAt: number; + updatedAt: number; + }>({ + serverRef: "mutators:materializeDailyNodes", + apply: (_ctx, args) => { + const plan = planMaterializeDailyNodes( + snapshotNodes(collection), + args, + ); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + seedIfEmpty: defineMutator<{ userId: string; createdAt: number }>({ + serverRef: "mutators:seedIfEmpty", + apply: (_ctx, args) => { + const plan = planSeedIfEmpty(snapshotNodes(collection), args); + if (plan) applyPlanToCollection(collection, plan); + }, + }), + // --- phase 2b kv (same clientSeq FIFO as outline) --- + upsertTagColor: defineMutator<{ + userId: string; + tag: string; + color: string; + }>({ + serverRef: "mutators:upsertTagColor", + apply: (_ctx, args) => { + if (tagColors.has(args.tag)) { + tagColors.update(args.tag, (draft) => { + draft.color = args.color; + }); + } else { + tagColors.insert({ + _id: args.tag, + tag: args.tag, + color: args.color, + userId: args.userId, + _creationTime: Date.now(), + }); + } + }, + }), + deleteTagColor: defineMutator<{ userId: string; tag: string }>({ + serverRef: "mutators:deleteTagColor", + apply: (_ctx, args) => { + if (tagColors.has(args.tag)) tagColors.delete(args.tag); + }, + }), + upsertSavedQuery: defineMutator<{ + userId: string; + id: string; + name: string; + query: string; + createdAt: number; + }>({ + serverRef: "mutators:upsertSavedQuery", + apply: (_ctx, args) => { + if (savedQueries.has(args.id)) { + savedQueries.update(args.id, (draft) => { + draft.name = args.name; + draft.query = args.query; + draft.createdAt = args.createdAt; + }); + } else { + savedQueries.insert({ + _id: args.id, + name: args.name, + query: args.query, + createdAt: args.createdAt, + userId: args.userId, + _creationTime: args.createdAt, + }); + } + }, + }), + patchSavedQuery: defineMutator<{ + userId: string; + id: string; + name?: string; + query?: string; + }>({ + serverRef: "mutators:patchSavedQuery", + apply: (_ctx, args) => { + if (!savedQueries.has(args.id)) return; + savedQueries.update(args.id, (draft) => { + if (args.name !== undefined) draft.name = args.name; + if (args.query !== undefined) draft.query = args.query; + }); + }, + }), + deleteSavedQueryRow: defineMutator<{ userId: string; id: string }>({ + serverRef: "mutators:deleteSavedQuery", + apply: (_ctx, args) => { + if (savedQueries.has(args.id)) savedQueries.delete(args.id); + }, + }), + // --- dailyIndex --- + claimDailyMapping: defineMutator<{ + userId: string; + key: string; + nodeId: string; + touchedAt: number; + }>({ + serverRef: "mutators:claimDailyMapping", + apply: (_ctx, args) => { + if (dailyIndex.has(args.key)) { + // Keep existing nodeId (pre-existing wins); bump touchedAt. + dailyIndex.update(args.key, (draft) => { + draft.touchedAt = args.touchedAt; + }); + return; + } + dailyIndex.insert({ + _id: args.key, + key: args.key, + nodeId: args.nodeId, + touchedAt: args.touchedAt, + userId: args.userId, + _creationTime: args.touchedAt, + }); + }, + }), + upsertDailyMapping: defineMutator<{ + userId: string; + key: string; + nodeId: string; + touchedAt: number; + }>({ + serverRef: "mutators:upsertDailyMapping", + apply: (_ctx, args) => { + if (dailyIndex.has(args.key)) { + dailyIndex.update(args.key, (draft) => { + draft.nodeId = args.nodeId; + draft.touchedAt = args.touchedAt; + }); + } else { + dailyIndex.insert({ + _id: args.key, + key: args.key, + nodeId: args.nodeId, + touchedAt: args.touchedAt, + userId: args.userId, + _creationTime: args.touchedAt, + }); + } + }, + }), + deleteDailyMapping: defineMutator<{ userId: string; key: string }>({ + serverRef: "mutators:deleteDailyMapping", + apply: (_ctx, args) => { + if (dailyIndex.has(args.key)) dailyIndex.delete(args.key); + }, + }), + }, + ); +} + +/** Build outline + phase-2b kv collections + one bound mutator surface. */ +export function createOutlineStore( + client: LunoraClient, + userId: string, +): OutlineStore { + const { config, checkpoints } = lunoraCollectionOptions({ + client, + id: `nodes:${userId}`, + shape: { + name: "wholeOutline", + args: { userId }, + shardKey: userId, + }, + load: "eager", + }); + const tagOpts = lunoraCollectionOptions({ + client, + id: `tagColors:${userId}`, + // Natural key = tag (server `_id` is a UUID — tag names aren't valid clientIds). + getKey: (row) => row.tag, + shape: { + name: "userTagColors", + args: { userId }, + shardKey: userId, + }, + load: "eager", + }); + const savedOpts = lunoraCollectionOptions({ + client, + id: `savedQueries:${userId}`, + shape: { + name: "userSavedQueries", + args: { userId }, + shardKey: userId, + }, + load: "eager", + }); + const dailyOpts = lunoraCollectionOptions({ + client, + id: `dailyIndex:${userId}`, + // Natural key = scaffold/day key (server `_id` is a UUID). + getKey: (row) => row.key, + shape: { + name: "userDailyIndex", + args: { userId }, + shardKey: userId, + }, + load: "eager", + }); + + // Fan side-collection shape pokes into the wholeOutline gate (belt for the + // offline/outbox path where RPC ack hasn't advanced the watermark yet). + relayCheckpoints(tagOpts.checkpoints, checkpoints); + relayCheckpoints(savedOpts.checkpoints, checkpoints); + relayCheckpoints(dailyOpts.checkpoints, checkpoints); + + const collection = createCollection(config); + const tagColors = createCollection(tagOpts.config); + const savedQueries = createCollection(savedOpts.config); + const dailyIndex = createCollection(dailyOpts.config); + // Shared clientSeq FIFO; hold overlays until shape poke (shapeFirstCheckpoints). + // Stamp TanStack "direct" metadata so a missed shape poke's 3s fallback + // doesn't drop optimistic typed text as stale. + const mutators = withDirectOptimisticMetadata( + bindOutlineMutators( + client, + collection, + tagColors, + savedQueries, + dailyIndex, + shapeFirstCheckpoints(client, userId, checkpoints), + userId, + ), + ); + return { collection, tagColors, savedQueries, dailyIndex, mutators }; +} diff --git a/src/data/lunora-sync.ts b/src/data/lunora-sync.ts new file mode 100644 index 00000000..eac8591c --- /dev/null +++ b/src/data/lunora-sync.ts @@ -0,0 +1,191 @@ +/** + * Lunora outline sync lifecycle for the ADR 0055 flag-swap (default OFF). + * + * When `isLunoraSyncEnabled()`: + * - creates `@lunora/db` `wholeOutline` collection + bound mutators + * - feeds ADR 0004 `tree-store` from collection rows + * - marks sync ready (shell spinner) + `seedIfEmpty` when the outline is empty + * AFTER auto-migrate from classic DO settles (success or skip) + * + * SPA/no-SSR: never start during prerender. Custom `/api/sync` stays cold + * (see `collection.ts` early-return when the flag is ON). + */ + +import { + bindLunoraDailyIndex, + unbindLunoraDailyIndex, +} from "../plugins/daily/daily-index"; +import { markNodesSyncReady } from "./collection"; +import { isLunoraSyncEnabled } from "./flags"; +import { outlineNodeToNode, rowsToOutlineNodes } from "./lunora-bridge"; +import { getLunoraClient } from "./lunora-client"; +import { + installMigrateConsoleHelper, + maybeAutoMigrateToLunora, +} from "./lunora-migrate"; +import { createOutlineStore, type OutlineStore } from "./lunora-outline-store"; +import { shouldSeedOutline, seedEmptyOutline } from "./outline-plans"; +import { notifySaveFailed } from "./save-failure"; +import { + bindLunoraSavedQueries, + unbindLunoraSavedQueries, +} from "./saved-queries"; +import { bindLunoraTagColors, unbindLunoraTagColors } from "./tag-colors"; +import { resetTreeFromNodes } from "./tree-store"; + +export type LunoraOutlineContext = { + userId: string; + store: OutlineStore; +}; + +let ctx: LunoraOutlineContext | null = null; +let collectionSub: { unsubscribe: () => void } | null = null; +let seedStarted = false; + +/** Active Lunora outline context, or null when flag OFF / not started. */ +export function getLunoraOutlineContext(): LunoraOutlineContext | null { + return ctx; +} + +function feedTreeFromCollection(store: OutlineStore): void { + const nodes = rowsToOutlineNodes(store.collection.toArray).map( + outlineNodeToNode, + ); + resetTreeFromNodes(nodes); +} + +/** + * Start Lunora outline sync for `userId`. Idempotent for the same user. + * No-op when the flag is OFF or during SSR. + */ +export function startLunoraOutlineSync(userId: string): void { + if (!isLunoraSyncEnabled()) return; + if (typeof window === "undefined") return; + if (ctx?.userId === userId) return; + + stopLunoraOutlineSync(); + + const store = createOutlineStore(getLunoraClient(), userId); + ctx = { userId, store }; + + // Phase 2b: side-collections ride the same flag. + bindLunoraTagColors(store.tagColors, { + upsert: (tag, color) => + trackLunoraMutation( + store.mutators.upsertTagColor({ userId, tag, color }), + ), + remove: (tag) => + trackLunoraMutation(store.mutators.deleteTagColor({ userId, tag })), + }); + bindLunoraSavedQueries(store.savedQueries, { + upsert: (row) => + trackLunoraMutation( + store.mutators.upsertSavedQuery({ + userId, + id: row.id, + name: row.name, + query: row.query, + createdAt: row.createdAt, + }), + ), + patchName: (id, name) => + trackLunoraMutation(store.mutators.patchSavedQuery({ userId, id, name })), + remove: (id) => + trackLunoraMutation(store.mutators.deleteSavedQueryRow({ userId, id })), + }); + bindLunoraDailyIndex(store.dailyIndex, { + upsert: (key, nodeId) => + trackLunoraMutation( + store.mutators.upsertDailyMapping({ + userId, + key, + nodeId, + touchedAt: Date.now(), + }), + ), + claimTx: (key, nodeId) => + store.mutators.claimDailyMapping({ + userId, + key, + nodeId, + touchedAt: Date.now(), + }), + }); + + installMigrateConsoleHelper(() => ctx); + + collectionSub = store.collection.subscribeChanges( + () => { + feedTreeFromCollection(store); + }, + { includeInitialState: true }, + ); + + void store.collection + .toArrayWhenReady() + .then(async () => { + if (!ctx || ctx.store !== store) return; + feedTreeFromCollection(store); + // One-shot classic DO → Lunora when shard empty (skip if already has rows). + // Shell stays gated until migrate settles — otherwise the user can edit/ + // seed into an empty shard while import chunks land. + const next = await maybeAutoMigrateToLunora(store, userId); + if (!ctx || ctx.store !== store) return; + feedTreeFromCollection(store); + markNodesSyncReady(); + if (next === "seed") maybeSeed(store, userId); + }) + .catch((err) => { + console.error("[lunora-sync] wholeOutline load failed", err); + // Surface the shell anyway — empty outline + save toast on writes. + markNodesSyncReady(); + notifySaveFailed(err); + }); +} + +function maybeSeed(store: OutlineStore, userId: string): void { + if (seedStarted) return; + const nodeCount = store.collection.toArray.length; + if (!shouldSeedOutline({ isReady: true, nodeCount })) return; + seedStarted = true; + void seedEmptyOutline({ + userId, + seedIfEmpty: (args) => { + const tx = store.mutators.seedIfEmpty(args); + return tx.isPersisted.promise.then(() => undefined); + }, + }).catch((err) => { + seedStarted = false; + console.error("[lunora-sync] seedIfEmpty failed", err); + notifySaveFailed(err); + }); +} + +/** Tear down Lunora sync (account switch / flag OFF). */ +export function stopLunoraOutlineSync(): void { + collectionSub?.unsubscribe(); + collectionSub = null; + unbindLunoraTagColors(); + unbindLunoraSavedQueries(); + unbindLunoraDailyIndex(); + ctx = null; + seedStarted = false; +} + +/** Fire-and-forget helper: await watermark hold, toast on failure. */ +export function trackLunoraMutation(tx: { + isPersisted: { promise: Promise }; +}): void { + tx.isPersisted.promise.catch(notifySaveFailed); +} + +// HMR: `startLunoraOutlineSync` is idempotent per userId, so a store-module +// edit would otherwise keep the old mutator bindings (and a hung isPersisted +// waiter) alive across Fast Refresh. Tear down + restart with the new store. +if (import.meta.hot) { + import.meta.hot.accept("./lunora-outline-store", () => { + const userId = ctx?.userId; + stopLunoraOutlineSync(); + if (userId) startLunoraOutlineSync(userId); + }); +} diff --git a/src/data/mutations.ts b/src/data/mutations.ts index 3d892f18..91135e17 100644 --- a/src/data/mutations.ts +++ b/src/data/mutations.ts @@ -1,4 +1,14 @@ import { nodesCollection } from "./collection"; +import { isLunoraSyncEnabled } from "./flags"; +import { getLiveNodes } from "./live-nodes"; +import { getLunoraOutlineContext, trackLunoraMutation } from "./lunora-sync"; +import { + planIndent, + planIndentMany, + planMoveMany, + planOutdentMany, + rowToNode, +} from "./outline-plans"; import { type Node, type NodeKind, @@ -54,6 +64,28 @@ export function insertSibling( kind: NodeKind = null, id = createId(), ): string { + // ADR 0055: Lunora mutator owns optimistic plan + watermark (dogfood surface). + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + const t = now(); + trackLunoraMutation( + lunora.store.mutators.insertSibling({ + id, + userId: lunora.userId, + parentId, + afterId, + text, + isTask, + kind, + createdAt: t, + updatedAt: t, + }), + ); + return id; + } + } + const prevSiblingId = afterId; // The node currently following `afterId` becomes the new node's follower. @@ -97,6 +129,26 @@ export function insertChildAtStart( id = createId(), kind: NodeKind = null, ): string { + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + const t = now(); + trackLunoraMutation( + lunora.store.mutators.insertChildAtStart({ + id, + userId: lunora.userId, + parentId, + text, + isTask, + kind, + createdAt: t, + updatedAt: t, + }), + ); + return id; + } + } + const head = childrenOf(index, parentId)[0] ?? null; nodesCollection.insert( @@ -110,21 +162,112 @@ export function insertChildAtStart( } /** - * Append a node at the end of `parentId`'s children. Used by the - * first-run seed, where we don't have a live TreeIndex in scope and the - * caller knows the parent is empty or has a known last child. + * Enter mid-split: leave `leftText` on `nodeId`, insert a sibling carrying + * `rightText`. Lunora path is ONE mutator (single watermark); custom-DO path + * is insertSibling + setText inside the caller's `runStructural` batch. + */ +export function splitNode( + index: TreeIndex, + args: { + nodeId: string; + parentId: string | null; + afterId: string; + leftText: string; + rightText: string; + isTask?: boolean; + kind?: NodeKind; + newId?: string; + }, +): string { + const newId = args.newId ?? createId(); + const isTask = args.isTask ?? false; + const kind = args.kind ?? null; + + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + const t = now(); + trackLunoraMutation( + lunora.store.mutators.splitNode({ + id: args.nodeId, + newId, + userId: lunora.userId, + parentId: args.parentId, + afterId: args.afterId, + leftText: args.leftText, + rightText: args.rightText, + isTask, + kind, + createdAt: t, + updatedAt: t, + }), + ); + return newId; + } + } + + insertSibling( + index, + args.parentId, + args.afterId, + isTask, + args.rightText, + kind, + newId, + ); + setText(args.nodeId, args.leftText); + return newId; +} + +/** + * Append a node at the end of `parentId`'s children. Used by quick-add born + * capture and the legacy first-run seed. * - * Pass `prevSiblingId` explicitly so seed code owns the wiring. `id` lets a - * caller supply the node id up front (the daily plugin's claimed container id); - * defaults to a fresh id. + * Flag OFF: pass `prevSiblingId` explicitly (caller owns the wiring). Flag ON: + * Lunora `appendChild` resolves the last sibling server-side (one watermark); + * `prevSiblingId` is ignored for the mutator path. + * + * `id` lets a caller supply the node id up front; defaults to a fresh id. + * Optional `isTask` / `kind` let quick-add fold `/todo`/`/paragraph` into the + * same born mutator when known at create time. */ export function appendChild( parentId: string | null, prevSiblingId: string | null = null, text = "", id = createId(), + opts?: { isTask?: boolean; kind?: NodeKind }, ): string { - nodesCollection.insert(makeNode({ id, parentId, prevSiblingId, text })); + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + const t = now(); + trackLunoraMutation( + lunora.store.mutators.appendChild({ + id, + userId: lunora.userId, + parentId, + text, + isTask: opts?.isTask, + kind: opts?.kind, + createdAt: t, + updatedAt: t, + }), + ); + return id; + } + } + + nodesCollection.insert( + makeNode({ + id, + parentId, + prevSiblingId, + text, + isTask: opts?.isTask, + kind: opts?.kind, + }), + ); return id; } @@ -154,9 +297,33 @@ export function mirrorNode( const trueSourceId = trueSourceOf(index, sourceId); if (wouldMirrorCycle(index, trueSourceId, targetId)) return null; + const id = createId(); + + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + // Resolve destination + cycle on the server planner (trueSourceOf parent). + // Pre-check above matches the legacy client path for early no-op. + const t = now(); + const resolvedParent = + targetId !== null ? trueSourceOf(index, targetId) : null; + if (wouldMirrorCycle(index, trueSourceId, resolvedParent)) return null; + trackLunoraMutation( + lunora.store.mutators.mirrorNode({ + id, + userId: lunora.userId, + sourceId, + targetParentId: targetId, + createdAt: t, + updatedAt: t, + }), + ); + return id; + } + } + const siblings = childrenOf(index, targetId); const after = siblings.length ? siblings[siblings.length - 1]!.id : null; - const id = createId(); nodesCollection.insert( makeNode({ id, @@ -182,7 +349,9 @@ export function mirrorManyNodes( ): number { let made = 0; for (const id of ids) { - const index = buildTreeIndex(nodesCollection.toArray); + // Live store (classic or Lunora) — nodesCollection is empty when the + // Lunora flag is ON, so rebuilding from it would no-op every mirror. + const index = buildTreeIndex(getLiveNodes()); if (mirrorNode(index, id, targetId)) made++; } return made; @@ -212,6 +381,24 @@ export function indent( const node = index.byId.get(nodeId); if (!node || !node.prevSiblingId) return false; + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + const updatedAt = now(); + // Match classic false on no-op / mirror cycle (ADR 0022). + if (!planIndent(index, nodeId, updatedAt, resolveMirror)) return false; + trackLunoraMutation( + lunora.store.mutators.indent({ + id: nodeId, + userId: lunora.userId, + updatedAt, + resolveMirror, + }), + ); + return true; + } + } + const newParent = index.byId.get(node.prevSiblingId); if (!newParent) return false; @@ -287,6 +474,20 @@ export function outdent(index: TreeIndex, nodeId: string): boolean { const node = index.byId.get(nodeId); if (!node || node.parentId === null) return false; + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + trackLunoraMutation( + lunora.store.mutators.outdent({ + id: nodeId, + userId: lunora.userId, + updatedAt: now(), + }), + ); + return true; + } + } + const oldParent = index.byId.get(node.parentId); if (!oldParent) return false; @@ -374,9 +575,9 @@ function reparentIntoParentPrevSibling( : null; const uncle = index.byId.get(uncleId); - if (uncle?.collapsed) update(uncle.id, { collapsed: false }); + const expandIds = uncle?.collapsed ? [uncle.id] : []; - return moveNode(index, node.id, uncleContentId, afterSiblingId); + return moveNode(index, node.id, uncleContentId, afterSiblingId, expandIds); } /** @@ -401,12 +602,11 @@ function reparentIntoParentNextSibling( : null; if (!aunt) return false; - if (aunt.collapsed) update(aunt.id, { collapsed: false }); - // ADR 0022: a mirror aunt windows its SOURCE's children; parent into the // source (off-flag it's the id itself). Collapse stays on the instance. const auntContentId = resolveMirror ? trueSourceOf(index, aunt.id) : aunt.id; - return moveNode(index, node.id, auntContentId, null); + const expandIds = aunt.collapsed ? [aunt.id] : []; + return moveNode(index, node.id, auntContentId, null, expandIds); } /** @@ -447,13 +647,8 @@ export function moveUp( opts.resolveMirror ?? false, ); - // Swap: detach node, then re-insert it immediately before vp. A hidden - // sibling between them stays put (rides along below vp). - const rawNext = i + 1 < siblings.length ? siblings[i + 1]! : null; - if (rawNext) update(rawNext.id, { prevSiblingId: node.prevSiblingId }); - update(nodeId, { prevSiblingId: vp.prevSiblingId }); - update(vp.id, { prevSiblingId: nodeId }); - return true; + // Swap via moveNode: land immediately before vp (same parent). + return moveNode(index, nodeId, node.parentId, vp.prevSiblingId ?? null); } /** @@ -494,14 +689,9 @@ export function moveDown( ); } - // Swap: detach node, then re-insert it immediately after vn. + // Swap via moveNode: land immediately after the nearest visible sibling below. const vn = siblings[k]!; - const vnNext = k + 1 < siblings.length ? siblings[k + 1]! : null; - const rawNext = siblings[i + 1]!; // exists: there's a sibling at k > i - update(rawNext.id, { prevSiblingId: node.prevSiblingId }); - update(nodeId, { prevSiblingId: vn.id }); - if (vnNext) update(vnNext.id, { prevSiblingId: nodeId }); - return true; + return moveNode(index, nodeId, node.parentId, vn.id); } /** @@ -525,6 +715,7 @@ export function moveNode( nodeId: string, newParentId: string | null, afterSiblingId: string | null, + expandIds: readonly string[] = [], ): boolean { const node = index.byId.get(nodeId); if (!node) return false; @@ -545,11 +736,43 @@ export function moveNode( // Already exactly here? Nothing to do (same parent, same predecessor). if ( newParentId === node.parentId && - (afterSiblingId ?? null) === (node.prevSiblingId ?? null) + (afterSiblingId ?? null) === (node.prevSiblingId ?? null) && + expandIds.length === 0 ) { return false; } + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + trackLunoraMutation( + lunora.store.mutators.moveNode({ + id: nodeId, + userId: lunora.userId, + newParentId, + afterSiblingId, + updatedAt: now(), + expandIds: expandIds.length ? [...expandIds] : undefined, + }), + ); + return true; + } + } + + for (const expandId of expandIds) { + update(expandId, { collapsed: false }); + } + + // Same-spot with only expands (edge move that lands where we already are but + // still needed to open the uncle) — already handled above when expandIds + // empty; with expands and same spot, skip chain surgery. + if ( + newParentId === node.parentId && + (afterSiblingId ?? null) === (node.prevSiblingId ?? null) + ) { + return expandIds.length > 0; + } + // The node currently following us under the OLD parent inherits our old prev. const oldSiblings = childrenOf(index, node.parentId); const oi = oldSiblings.findIndex((n) => n.id === nodeId); @@ -592,6 +815,31 @@ export function moveNode( * moves land as ONE atomic batch (ADR 0009). */ export function moveManyNodes(targetId: string | null, ids: string[]): number { + if (ids.length === 0) return 0; + + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + const updatedAt = now(); + const nodes = lunora.store.collection.toArray.map(rowToNode); + const plan = planMoveMany(nodes, { + targetId, + nodeIds: ids, + updatedAt, + }); + if (!plan) return 0; + trackLunoraMutation( + lunora.store.mutators.moveMany({ + userId: lunora.userId, + targetId, + nodeIds: [...ids], + updatedAt, + }), + ); + return ids.length; + } + } + let moved = 0; // `after` walks forward: start at the target's current last child, then each // successful move becomes the predecessor of the next. @@ -626,6 +874,26 @@ export function indentManyNodes( resolveMirror = false, ): number { if (rootIds.length === 0) return 0; + + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + const updatedAt = now(); + const nodes = lunora.store.collection.toArray.map(rowToNode); + const plan = planIndentMany(nodes, rootIds, updatedAt, resolveMirror); + if (!plan) return 0; + trackLunoraMutation( + lunora.store.mutators.indentMany({ + userId: lunora.userId, + nodeIds: [...rootIds], + updatedAt, + resolveMirror, + }), + ); + return rootIds.length; + } + } + const index = buildTreeIndex(nodesCollection.toArray); // The run is contiguous, so the first root's prev sibling sits OUTSIDE it -- // the node everything indents under. Absent => first child => can't indent. @@ -665,6 +933,25 @@ export function indentManyNodes( */ export function outdentManyNodes(rootIds: string[]): number { if (rootIds.length === 0) return 0; + + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + const updatedAt = now(); + const nodes = lunora.store.collection.toArray.map(rowToNode); + const plan = planOutdentMany(nodes, rootIds, updatedAt); + if (!plan) return 0; + trackLunoraMutation( + lunora.store.mutators.outdentMany({ + userId: lunora.userId, + nodeIds: [...rootIds], + updatedAt, + }), + ); + return rootIds.length; + } + } + const start = buildTreeIndex(nodesCollection.toArray); const oldParentId = start.byId.get(rootIds[0]!)?.parentId; if (!oldParentId) return 0; // already top-level -> can't outdent @@ -693,17 +980,7 @@ export function removeNode(index: TreeIndex, nodeId: string): string | null { const node = index.byId.get(nodeId); if (!node) return null; - // Collect subtree ids (depth-first). - const toDelete: string[] = []; - const stack = [nodeId]; - while (stack.length) { - const id = stack.pop()!; - toDelete.push(id); - const kids = childrenOf(index, id); - for (const k of kids) stack.push(k.id); - } - - // Determine focus target before mutating. + // Determine focus target before mutating (shared by Lunora + custom-DO paths). const siblings = childrenOf(index, node.parentId); const i = siblings.findIndex((n) => n.id === nodeId); let focusId: string | null = null; @@ -715,6 +992,30 @@ export function removeNode(index: TreeIndex, nodeId: string): string | null { focusId = node.parentId; } + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + trackLunoraMutation( + lunora.store.mutators.removeNode({ + id: nodeId, + userId: lunora.userId, + updatedAt: now(), + }), + ); + return focusId; + } + } + + // Collect subtree ids (depth-first). + const toDelete: string[] = []; + const stack = [nodeId]; + while (stack.length) { + const id = stack.pop()!; + toDelete.push(id); + const kids = childrenOf(index, id); + for (const k of kids) stack.push(k.id); + } + // Relink the follower of the last-deleted-in-chain. For the deleted node // itself, its old next sibling needs to point at node.prevSiblingId. if (i !== -1 && i + 1 < siblings.length) { @@ -739,16 +1040,60 @@ export function removeNode(index: TreeIndex, nodeId: string): string | null { * Focus handling is the caller's (computed before deletion). */ export function removeManyNodes(ids: string[]): void { + if (ids.length === 0) return; + + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + trackLunoraMutation( + lunora.store.mutators.removeMany({ + userId: lunora.userId, + nodeIds: [...ids], + updatedAt: now(), + }), + ); + return; + } + } + for (const id of ids) { removeNode(buildTreeIndex(nodesCollection.toArray), id); } } export function setText(nodeId: string, text: string) { + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + trackLunoraMutation( + lunora.store.mutators.setText({ + id: nodeId, + userId: lunora.userId, + text, + updatedAt: now(), + }), + ); + return; + } + } update(nodeId, { text }); } export function toggleCompleted(nodeId: string, completed: boolean) { + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + trackLunoraMutation( + lunora.store.mutators.setCompleted({ + id: nodeId, + userId: lunora.userId, + completed, + updatedAt: now(), + }), + ); + return; + } + } update(nodeId, { completed }); } @@ -766,6 +1111,20 @@ export function toggleCompleted(nodeId: string, completed: boolean) { * forgotten at a call site. */ export function setIsTask(nodeId: string, isTask: boolean) { + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + trackLunoraMutation( + lunora.store.mutators.setIsTask({ + id: nodeId, + userId: lunora.userId, + isTask, + updatedAt: now(), + }), + ); + return; + } + } update(nodeId, { isTask, kind: null }); } @@ -778,10 +1137,38 @@ export function setIsTask(nodeId: string, isTask: boolean) { * wrap it in `runStructural`. */ export function setKind(nodeId: string, kind: NodeKind) { + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + trackLunoraMutation( + lunora.store.mutators.setKind({ + id: nodeId, + userId: lunora.userId, + kind, + updatedAt: now(), + }), + ); + return; + } + } update(nodeId, { kind, isTask: false }); } export function toggleCollapsed(nodeId: string, collapsed: boolean) { + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + trackLunoraMutation( + lunora.store.mutators.setCollapsed({ + id: nodeId, + userId: lunora.userId, + collapsed, + updatedAt: now(), + }), + ); + return; + } + } update(nodeId, { collapsed }); } @@ -790,5 +1177,20 @@ export function toggleCollapsed(nodeId: string, collapsed: boolean) { * bookmarks list sorts by it) or `null` to unpin. See ADR 0011. */ export function toggleBookmark(nodeId: string, bookmarked: boolean) { + if (isLunoraSyncEnabled()) { + const lunora = getLunoraOutlineContext(); + if (lunora) { + const t = now(); + trackLunoraMutation( + lunora.store.mutators.setBookmarkedAt({ + id: nodeId, + userId: lunora.userId, + bookmarkedAt: bookmarked ? t : null, + updatedAt: t, + }), + ); + return; + } + } update(nodeId, { bookmarkedAt: bookmarked ? now() : null }); } diff --git a/src/data/node-count.ts b/src/data/node-count.ts index ff2abd3b..252a5dca 100644 --- a/src/data/node-count.ts +++ b/src/data/node-count.ts @@ -2,37 +2,41 @@ * Live total node count — the number the free-tier ceiling (#170) is measured * against, read reactively for the Settings page's usage meter. * - * Modelled on `changelog-cursor.ts`: `subscribeChanges` + `useSyncExternalStore`, - * NEVER `useLiveQuery` (which hard-fails the `/` prerender, and Settings shares - * the same bundle). Subscribing here also STARTS the collection's sync if nothing - * else has yet — a direct visit to `/settings` (no OutlineEditor mounted) still - * gets a real count once the snapshot lands. + * Modelled on `changelog-cursor.ts`: `useSyncExternalStore` over the shared + * tree index + sync-ready signal, NEVER `useLiveQuery` (which hard-fails the + * `/` prerender, and Settings shares the same bundle). * - * `toArray.length` is the same basis the DO caps on (every live row, including - * the daily scaffold), so the meter and the wall agree. + * Count comes from `getTreeIndex().byId.size` so both sync backends agree: + * classic DO feeds the tree via `nodesCollection`, Lunora (ADR 0055) via + * `resetTreeFromNodes`. Reading classic `nodesCollection` alone shows 0 when + * the Lunora flag is ON (that collection stays idle + empty). + * + * `byId.size` is the same basis the free-tier wall measures (every live row, + * including the daily scaffold). */ import { useSyncExternalStore } from "react"; -import { nodesCollection } from "./collection"; +import { isSyncReady, subscribeSyncReady } from "./collection"; +import { getTreeIndex, subscribeTree } from "./tree-store"; export interface NodeCountSnapshot { /** Total live nodes, or `0` until the first snapshot lands. */ count: number; - /** False until the collection has loaded at least once — the meter shows a - * muted placeholder while false so we never flash "0 of 10,000". */ + /** False until sync is ready — the meter shows a muted placeholder while + * false so we never flash "0 of 10,000" for a still-loading outline. */ ready: boolean; } const HIDDEN: NodeCountSnapshot = { count: 0, ready: false }; let snapshot: NodeCountSnapshot = HIDDEN; -let ready = false; -let started = false; const listeners = new Set<() => void>(); +let started = false; function rebuild() { - const count = ready ? nodesCollection.toArray.length : 0; + const ready = isSyncReady(); + const count = ready ? getTreeIndex().byId.size : 0; // Referential stability: useSyncExternalStore re-renders on identity change. if (snapshot.ready === ready && snapshot.count === count) return; snapshot = { ready, count }; @@ -42,18 +46,11 @@ function rebuild() { function ensureStarted() { if (started || typeof window === "undefined") return; started = true; - // subscribeChanges starts the collection syncing if it hasn't already. - nodesCollection.subscribeChanges(() => rebuild(), { - includeInitialState: true, - }); - void nodesCollection - .toArrayWhenReady() - .then(() => { - ready = true; - rebuild(); - }) - // A snapshot that never lands leaves the meter in its muted placeholder. - .catch(() => {}); + // Tree subscription starts classic collection sync when the Lunora flag is + // OFF; when ON, LunoraSyncHost feeds the tree and marks sync ready. + subscribeTree(() => rebuild()); + subscribeSyncReady(() => rebuild()); + rebuild(); } function subscribe(cb: () => void): () => void { diff --git a/src/data/outline-plans/change-ops.test.ts b/src/data/outline-plans/change-ops.test.ts new file mode 100644 index 00000000..399207ee --- /dev/null +++ b/src/data/outline-plans/change-ops.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from "bun:test"; + +import { planFromChangeOps } from "./change-ops"; +import { makeOutlineNode } from "./planners"; + +describe("planFromChangeOps", () => { + test("maps insert/update/delete into one OutlinePlan", () => { + const insert = makeOutlineNode({ + id: "n1", + userId: "u", + text: "hello", + }); + const { userId: _u, ...insertWire } = insert; + const plan = planFromChangeOps("u", [ + { op: "insert", value: insertWire }, + { + op: "update", + value: { ...insertWire, text: "hello!" }, + }, + { op: "delete", key: "gone" }, + ]); + expect(plan.deletes).toEqual(["gone"]); + expect(plan.inserts).toHaveLength(1); + expect(plan.inserts[0]!.text).toBe("hello"); + expect(plan.inserts[0]!.userId).toBe("u"); + expect(plan.patches).toHaveLength(1); + expect(plan.patches[0]!.id).toBe("n1"); + expect(plan.patches[0]!.fields.text).toBe("hello!"); + }); +}); diff --git a/src/data/outline-plans/change-ops.ts b/src/data/outline-plans/change-ops.ts new file mode 100644 index 00000000..b58ad758 --- /dev/null +++ b/src/data/outline-plans/change-ops.ts @@ -0,0 +1,62 @@ +/** + * Map classic DO `ChangeOp` batches (MCP outline-ops planners) onto an + * OutlinePlan for Lunora `commitPlan` / applyChangeOps. + */ + +import type { OutlineNode, OutlinePlan } from "./types"; + +import { emptyPlan } from "./types"; + +/** Wire ChangeOp shape without importing the Worker wire module. */ +export type ChangeOpLike = + | { op: "insert"; value: Omit & { userId?: string } } + | { op: "update"; value: Omit & { userId?: string } } + | { op: "delete"; key: string }; + +function toOutlineNode( + userId: string, + value: Omit & { userId?: string }, +): OutlineNode { + return { + id: value.id, + parentId: value.parentId ?? null, + prevSiblingId: value.prevSiblingId ?? null, + text: value.text ?? "", + isTask: Boolean(value.isTask), + completed: Boolean(value.completed), + collapsed: Boolean(value.collapsed), + bookmarkedAt: value.bookmarkedAt ?? null, + mirrorOf: value.mirrorOf ?? null, + createdAt: Number(value.createdAt ?? 0), + updatedAt: Number(value.updatedAt ?? 0), + origin: value.origin ?? null, + kind: value.kind === "paragraph" ? "paragraph" : null, + userId, + }; +} + +/** + * Convert a classic `{ops}` batch into one OutlinePlan (deletes → patches → + * inserts). Updates become full-field patches so Lunora can patch in place. + */ +export function planFromChangeOps( + userId: string, + ops: readonly ChangeOpLike[], +): OutlinePlan { + const plan = emptyPlan(); + for (const op of ops) { + if (op.op === "delete") { + plan.deletes.push(op.key); + continue; + } + const node = toOutlineNode(userId, op.value); + if (op.op === "insert") { + plan.inserts.push(node); + continue; + } + // update — patch every field except id/userId + const { id: _id, userId: _uid, ...fields } = node; + plan.patches.push({ id: node.id, fields }); + } + return plan; +} diff --git a/src/data/outline-plans/index.ts b/src/data/outline-plans/index.ts new file mode 100644 index 00000000..1fc754f4 --- /dev/null +++ b/src/data/outline-plans/index.ts @@ -0,0 +1,57 @@ +export type { OutlineNode, OutlinePlan, PlanPatch, NodeKind } from "./types"; +export { emptyPlan } from "./types"; + +export { orderSiblings, chainDisagreements } from "../sibling-chain"; +export type { ChainDisagreement } from "../sibling-chain"; + +export { buildTreeIndex, childrenOf, makeNode, parentKeyOf } from "../tree"; +export type { TreeIndex } from "../tree"; + +export { + makeOutlineNode, + planInsertSibling, + planInsertChildAtStart, + planAppendChild, + planImportNodes, + planIndent, + planOutdent, + planRemoveNode, + planRemoveMany, + planSetText, + planSetCompleted, + planSetCollapsed, + planSetIsTask, + planSetKind, + planSetBookmarkedAt, + planMoveNode, + planMoveMany, + planIndentMany, + planOutdentMany, + planMaterializeDailyNodes, + planSplitNode, + sameNodeFields, + planRestoreNodes, + planMirrorNode, + applyPlan, +} from "./planners"; + +export { planFromChangeOps } from "./change-ops"; +export type { ChangeOpLike } from "./change-ops"; + +export { + rowToNode, + docToNode, + nodeToDocFields, + nodeToRow, + nodeToInsertFields, +} from "./map-node"; +export type { NodeDocLike } from "./map-node"; + +export { + DEMO_SEED_TEXTS, + DEMO_SEED_IDS, + shouldSeedOutline, + planSeedIfEmpty, + seedEmptyOutline, +} from "./seed"; +export type { SeedIfEmptyArgs, SeedIfEmptyFn } from "./seed"; diff --git a/src/data/outline-plans/map-node.ts b/src/data/outline-plans/map-node.ts new file mode 100644 index 00000000..ecd98b1b --- /dev/null +++ b/src/data/outline-plans/map-node.ts @@ -0,0 +1,82 @@ +import type { OutlineNode } from "./types"; + +/** + * Loose Lunora / TanStack row shape. Codegen Doc types currently erase + * `.nullable()`, so boundaries cast through this helper once. + */ +export type NodeDocLike = { + _id: string; + parentId?: unknown; + prevSiblingId?: unknown; + text?: unknown; + isTask?: unknown; + completed?: unknown; + collapsed?: unknown; + bookmarkedAt?: unknown; + mirrorOf?: unknown; + createdAt?: unknown; + updatedAt?: unknown; + origin?: unknown; + kind?: unknown; + userId?: unknown; +}; + +/** Shared Doc/row → planner node. Use at every Lunora↔outline boundary. */ +export function rowToNode(doc: NodeDocLike): OutlineNode { + return { + id: doc._id, + parentId: (doc.parentId as string | null) ?? null, + prevSiblingId: (doc.prevSiblingId as string | null) ?? null, + text: String(doc.text ?? ""), + isTask: Boolean(doc.isTask), + completed: Boolean(doc.completed), + collapsed: Boolean(doc.collapsed), + bookmarkedAt: (doc.bookmarkedAt as number | null) ?? null, + mirrorOf: (doc.mirrorOf as string | null) ?? null, + createdAt: Number(doc.createdAt ?? 0), + updatedAt: Number(doc.updatedAt ?? 0), + origin: (doc.origin as string | null) ?? null, + kind: doc.kind === "paragraph" ? "paragraph" : null, + userId: String(doc.userId ?? ""), + }; +} + +/** Alias for server mutator docs (`_id` rows from `ctx.db.query`). */ +export const docToNode = rowToNode; + +/** + * Planner node → outbound Doc/row fields (one helper for optimistic insert + + * tests). `_creationTime` mirrors Lunora’s system field for TanStack rows. + */ +export function nodeToDocFields( + node: OutlineNode, +): Omit & { _id: string; _creationTime: number } { + return { + _id: node.id, + _creationTime: node.createdAt, + parentId: node.parentId, + prevSiblingId: node.prevSiblingId, + text: node.text, + isTask: node.isTask, + completed: node.completed, + collapsed: node.collapsed, + bookmarkedAt: node.bookmarkedAt, + mirrorOf: node.mirrorOf, + createdAt: node.createdAt, + updatedAt: node.updatedAt, + origin: node.origin, + kind: node.kind, + userId: node.userId, + }; +} + +/** Alias — same outbound map (was a near-dup in outline-store). */ +export const nodeToRow = nodeToDocFields; + +/** Server insert payload: Doc fields without `_id` / `_creationTime`. */ +export function nodeToInsertFields( + node: OutlineNode, +): Omit, "_id" | "_creationTime"> { + const { _id: _, _creationTime: __, ...fields } = nodeToDocFields(node); + return fields; +} diff --git a/src/data/outline-plans/planners.test.ts b/src/data/outline-plans/planners.test.ts new file mode 100644 index 00000000..cbf1bd3d --- /dev/null +++ b/src/data/outline-plans/planners.test.ts @@ -0,0 +1,742 @@ +import { describe, expect, it } from "bun:test"; + +import { + applyPlan, + buildTreeIndex, + chainDisagreements, + childrenOf, + makeOutlineNode, + orderSiblings, + planIndent, + planAppendChild, + planImportNodes, + planInsertChildAtStart, + planInsertSibling, + planIndentMany, + planMaterializeDailyNodes, + planMirrorNode, + planMoveMany, + planMoveNode, + planOutdent, + planOutdentMany, + planRemoveMany, + planRemoveNode, + planRestoreNodes, + planSetBookmarkedAt, + planSetCollapsed, + planSetCompleted, + planSetIsTask, + planSetKind, + planSetText, + planSplitNode, + type OutlineNode, +} from "./index"; + +const USER = "user-1"; + +function assertChainOk(nodes: OutlineNode[], parentId: string | null) { + const index = buildTreeIndex(nodes); + const kids = childrenOf(index, parentId); + const ordered = orderSiblings(kids); + expect(chainDisagreements(ordered)).toEqual([]); + return ordered.map((n) => n.id); +} + +function seedFlat(ids: string[]): OutlineNode[] { + return ids.map((id, i) => + makeOutlineNode({ + id, + userId: USER, + parentId: null, + prevSiblingId: i === 0 ? null : ids[i - 1]!, + text: id, + createdAt: i, + updatedAt: i, + }), + ); +} + +describe("sibling-chain invariant (ADR 0009) via outline-plans", () => { + it("orderSiblings follows prevSiblingId chain", () => { + const nodes = seedFlat(["a", "b", "c"]); + const scrambled = [nodes[2]!, nodes[0]!, nodes[1]!]; + expect(orderSiblings(scrambled).map((n) => n.id)).toEqual(["a", "b", "c"]); + }); + + it("chainDisagreements empty for a valid chain", () => { + const nodes = seedFlat(["a", "b", "c"]); + expect(chainDisagreements(orderSiblings(nodes))).toEqual([]); + }); + + it("rapid structural sequences leave chain intact", () => { + let nodes = seedFlat(["a", "b", "c"]); + let t = 100; + + { + const index = buildTreeIndex(nodes); + const plan = planInsertSibling(index, { + id: "d", + userId: USER, + parentId: null, + afterId: "b", + text: "d", + createdAt: t, + updatedAt: t, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + t += 1; + } + expect(assertChainOk(nodes, null)).toEqual(["a", "b", "d", "c"]); + + { + const index = buildTreeIndex(nodes); + const plan = planIndent(index, "d", t++); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + } + expect(assertChainOk(nodes, null)).toEqual(["a", "b", "c"]); + expect(assertChainOk(nodes, "b")).toEqual(["d"]); + + { + const index = buildTreeIndex(nodes); + const plan = planInsertSibling(index, { + id: "e", + userId: USER, + parentId: null, + afterId: "a", + text: "e", + createdAt: t, + updatedAt: t, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + t += 1; + } + expect(assertChainOk(nodes, null)).toEqual(["a", "e", "b", "c"]); + + { + const index = buildTreeIndex(nodes); + const plan = planOutdent(index, "d", t++); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + } + expect(assertChainOk(nodes, null)).toEqual(["a", "e", "b", "d", "c"]); + expect(assertChainOk(nodes, "b")).toEqual([]); + + { + const index = buildTreeIndex(nodes); + const plan = planRemoveNode(index, "e", t++); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + } + expect(assertChainOk(nodes, null)).toEqual(["a", "b", "d", "c"]); + + { + const index = buildTreeIndex(nodes); + const plan = planInsertSibling(index, { + id: "b1", + userId: USER, + parentId: "b", + afterId: null, + text: "b1", + createdAt: t, + updatedAt: t, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + t += 1; + } + expect(assertChainOk(nodes, "b")).toEqual(["b1"]); + + { + const index = buildTreeIndex(nodes); + const plan = planRemoveNode(index, "b", t++); + expect(plan).not.toBeNull(); + expect(plan!.deletes.sort()).toEqual(["b", "b1"].sort()); + nodes = applyPlan(nodes, plan!); + } + expect(assertChainOk(nodes, null)).toEqual(["a", "d", "c"]); + expect(nodes.find((n) => n.id === "b1")).toBeUndefined(); + + { + const index = buildTreeIndex(nodes); + const plan = planSetText(index, "a", "alpha", t++); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + } + expect(assertChainOk(nodes, null)).toEqual(["a", "d", "c"]); + expect(nodes.find((n) => n.id === "a")!.text).toBe("alpha"); + }); + + it("burst of mid-list inserts preserves totality", () => { + let nodes = seedFlat(["root"]); + let afterId: string | null = "root"; + let t = 1; + + for (let i = 0; i < 20; i++) { + const id = `n${i}`; + const index = buildTreeIndex(nodes); + const plan = planInsertSibling(index, { + id, + userId: USER, + parentId: null, + afterId, + text: id, + createdAt: t, + updatedAt: t, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + afterId = id; + t += 1; + } + + const ordered = assertChainOk(nodes, null); + expect(ordered).toEqual([ + "root", + ...Array.from({ length: 20 }, (_, i) => `n${i}`), + ]); + }); +}); + +describe("planAppendChild", () => { + it("appends after the current last sibling", () => { + let nodes = seedFlat(["a", "b"]); + const plan = planAppendChild(buildTreeIndex(nodes), { + id: "c", + userId: USER, + parentId: null, + text: "c", + createdAt: 10, + updatedAt: 10, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, null)).toEqual(["a", "b", "c"]); + expect(nodes.find((n) => n.id === "c")!.prevSiblingId).toBe("b"); + }); + + it("inserts as sole child when parent is empty", () => { + let nodes = seedFlat(["p"]); + const plan = planAppendChild(buildTreeIndex(nodes), { + id: "c", + userId: USER, + parentId: "p", + text: "c", + createdAt: 10, + updatedAt: 10, + }); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, "p")).toEqual(["c"]); + }); +}); + +describe("planImportNodes", () => { + it("is insert-only with no patches", () => { + const batch = [ + makeOutlineNode({ + id: "x", + userId: USER, + parentId: null, + prevSiblingId: null, + text: "x", + }), + makeOutlineNode({ + id: "y", + userId: USER, + parentId: null, + prevSiblingId: "x", + text: "y", + }), + ]; + const plan = planImportNodes(batch); + expect(plan.deletes).toEqual([]); + expect(plan.patches).toEqual([]); + expect(plan.inserts.map((n) => n.id)).toEqual(["x", "y"]); + }); +}); + +describe("planInsertChildAtStart", () => { + it("prepends under parent and repoints the old head", () => { + let nodes = seedFlat(["p"]); + let t = 10; + { + const index = buildTreeIndex(nodes); + const plan = planInsertSibling(index, { + id: "c1", + userId: USER, + parentId: "p", + afterId: null, + text: "c1", + createdAt: t, + updatedAt: t, + }); + nodes = applyPlan(nodes, plan!); + t += 1; + } + { + const index = buildTreeIndex(nodes); + const plan = planInsertChildAtStart(index, { + id: "c0", + userId: USER, + parentId: "p", + text: "c0", + createdAt: t, + updatedAt: t, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + } + expect(assertChainOk(nodes, "p")).toEqual(["c0", "c1"]); + expect(nodes.find((n) => n.id === "c1")!.prevSiblingId).toBe("c0"); + }); +}); + +describe("field planners (kind exclusivity)", () => { + it("planSetIsTask clears kind", () => { + let nodes = [ + makeOutlineNode({ + id: "a", + userId: USER, + kind: "paragraph", + isTask: false, + text: "a", + }), + ]; + const plan = planSetIsTask(buildTreeIndex(nodes), "a", true, 1); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(nodes[0]!.isTask).toBe(true); + expect(nodes[0]!.kind).toBeNull(); + }); + + it("planSetKind clears isTask", () => { + let nodes = [ + makeOutlineNode({ + id: "a", + userId: USER, + isTask: true, + text: "a", + }), + ]; + const plan = planSetKind(buildTreeIndex(nodes), "a", "paragraph", 1); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(nodes[0]!.kind).toBe("paragraph"); + expect(nodes[0]!.isTask).toBe(false); + }); + + it("planSetCompleted / collapsed / bookmarkedAt patch fields", () => { + let nodes = seedFlat(["a"]); + nodes = applyPlan( + nodes, + planSetCompleted(buildTreeIndex(nodes), "a", true, 1)!, + ); + expect(nodes[0]!.completed).toBe(true); + nodes = applyPlan( + nodes, + planSetCollapsed(buildTreeIndex(nodes), "a", true, 2)!, + ); + expect(nodes[0]!.collapsed).toBe(true); + nodes = applyPlan( + nodes, + planSetBookmarkedAt(buildTreeIndex(nodes), "a", 99, 3)!, + ); + expect(nodes[0]!.bookmarkedAt).toBe(99); + }); +}); + +describe("planMoveNode", () => { + it("swaps siblings (move up before previous)", () => { + let nodes = seedFlat(["a", "b", "c"]); + const plan = planMoveNode(buildTreeIndex(nodes), { + id: "c", + newParentId: null, + afterSiblingId: "a", + updatedAt: 1, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, null)).toEqual(["a", "c", "b"]); + }); + + it("reparents as first child and can expand destination", () => { + let nodes = seedFlat(["a", "b"]); + nodes = nodes.map((n) => (n.id === "a" ? { ...n, collapsed: true } : n)); + { + const plan = planInsertSibling(buildTreeIndex(nodes), { + id: "a1", + userId: USER, + parentId: "a", + afterId: null, + text: "a1", + createdAt: 1, + updatedAt: 1, + }); + nodes = applyPlan(nodes, plan!); + } + const plan = planMoveNode(buildTreeIndex(nodes), { + id: "b", + newParentId: "a", + afterSiblingId: null, + updatedAt: 2, + expandIds: ["a"], + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, null)).toEqual(["a"]); + expect(assertChainOk(nodes, "a")).toEqual(["b", "a1"]); + expect(nodes.find((n) => n.id === "a")!.collapsed).toBe(false); + }); + + it("no-ops when already at destination without expands", () => { + const nodes = seedFlat(["a", "b"]); + const plan = planMoveNode(buildTreeIndex(nodes), { + id: "b", + newParentId: null, + afterSiblingId: "a", + updatedAt: 1, + }); + expect(plan).toBeNull(); + }); +}); + +describe("planSplitNode", () => { + it("patches left text and inserts right sibling atomically", () => { + let nodes = seedFlat(["a", "b"]); + nodes = nodes.map((n) => (n.id === "a" ? { ...n, text: "alphabravo" } : n)); + const plan = planSplitNode(buildTreeIndex(nodes), { + id: "a", + newId: "a2", + userId: USER, + parentId: null, + afterId: "a", + leftText: "alpha", + rightText: "bravo", + createdAt: 5, + updatedAt: 5, + }); + expect(plan).not.toBeNull(); + expect(plan!.inserts).toHaveLength(1); + expect( + plan!.patches.some((p) => p.id === "a" && p.fields.text === "alpha"), + ).toBe(true); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, null)).toEqual(["a", "a2", "b"]); + expect(nodes.find((n) => n.id === "a")!.text).toBe("alpha"); + expect(nodes.find((n) => n.id === "a2")!.text).toBe("bravo"); + expect(nodes.find((n) => n.id === "b")!.prevSiblingId).toBe("a2"); + }); +}); + +describe("planRestoreNodes", () => { + it("deletes added, inserts removed, patches changed", () => { + const current = seedFlat(["a", "b", "c"]); + const target = seedFlat(["a", "b"]).map((n) => + n.id === "a" ? { ...n, text: "alpha" } : n, + ); + target.push( + makeOutlineNode({ + id: "d", + userId: USER, + parentId: null, + prevSiblingId: "b", + text: "d", + createdAt: 9, + updatedAt: 9, + }), + ); + const plan = planRestoreNodes(current, target); + expect(plan.deletes).toEqual(["c"]); + expect(plan.inserts.map((n) => n.id)).toEqual(["d"]); + expect(plan.patches).toEqual([ + expect.objectContaining({ + id: "a", + fields: expect.objectContaining({ text: "alpha" }), + }), + ]); + const next = applyPlan(current, plan); + expect(assertChainOk(next, null)).toEqual(["a", "b", "d"]); + expect(next.find((n) => n.id === "a")!.text).toBe("alpha"); + }); + + it("no-ops when current already matches target", () => { + const nodes = seedFlat(["a", "b"]); + const plan = planRestoreNodes( + nodes, + nodes.map((n) => ({ ...n })), + ); + expect(plan.deletes).toEqual([]); + expect(plan.inserts).toEqual([]); + expect(plan.patches).toEqual([]); + }); +}); + +describe("planMirrorNode", () => { + it("appends a flattened mirror as last child", () => { + let nodes = seedFlat(["src", "dest"]); + nodes = [ + ...nodes, + makeOutlineNode({ + id: "child", + userId: USER, + parentId: "src", + prevSiblingId: null, + text: "child", + createdAt: 1, + updatedAt: 1, + }), + ]; + const plan = planMirrorNode(buildTreeIndex(nodes), { + id: "m1", + userId: USER, + sourceId: "src", + targetParentId: "dest", + createdAt: 2, + updatedAt: 2, + }); + expect(plan).not.toBeNull(); + expect(plan!.inserts).toHaveLength(1); + expect(plan!.inserts[0]!.mirrorOf).toBe("src"); + expect(plan!.inserts[0]!.parentId).toBe("dest"); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, "dest")).toEqual(["m1"]); + }); + + it("flattens mirror-of-mirror to the true source", () => { + let nodes = seedFlat(["src", "dest"]); + { + const plan = planMirrorNode(buildTreeIndex(nodes), { + id: "m1", + userId: USER, + sourceId: "src", + targetParentId: null, + createdAt: 1, + updatedAt: 1, + }); + nodes = applyPlan(nodes, plan!); + } + const plan = planMirrorNode(buildTreeIndex(nodes), { + id: "m2", + userId: USER, + sourceId: "m1", + targetParentId: "dest", + createdAt: 2, + updatedAt: 2, + }); + expect(plan).not.toBeNull(); + expect(plan!.inserts[0]!.mirrorOf).toBe("src"); + }); + + it("refuses a cycle (mirror into own subtree)", () => { + let nodes = seedFlat(["src"]); + nodes = [ + ...nodes, + makeOutlineNode({ + id: "child", + userId: USER, + parentId: "src", + prevSiblingId: null, + text: "child", + createdAt: 1, + updatedAt: 1, + }), + ]; + const plan = planMirrorNode(buildTreeIndex(nodes), { + id: "m1", + userId: USER, + sourceId: "src", + targetParentId: "child", + createdAt: 2, + updatedAt: 2, + }); + expect(plan).toBeNull(); + }); + + it("parents under the true source when target is a mirror instance", () => { + let nodes = seedFlat(["src", "other"]); + { + const plan = planMirrorNode(buildTreeIndex(nodes), { + id: "mDest", + userId: USER, + sourceId: "other", + targetParentId: null, + createdAt: 1, + updatedAt: 1, + }); + nodes = applyPlan(nodes, plan!); + } + const plan = planMirrorNode(buildTreeIndex(nodes), { + id: "m1", + userId: USER, + sourceId: "src", + targetParentId: "mDest", + createdAt: 2, + updatedAt: 2, + }); + expect(plan).not.toBeNull(); + expect(plan!.inserts[0]!.parentId).toBe("other"); + }); +}); + +describe("planIndent resolveMirror", () => { + it("parents into the SOURCE when prev sibling is a mirror", () => { + let nodes = seedFlat(["src", "m", "x"]); + // Turn m into a mirror of src (same sibling chain position). + nodes = nodes.map((n) => + n.id === "m" ? { ...n, mirrorOf: "src", text: "src" } : n, + ); + const plan = planIndent(buildTreeIndex(nodes), "x", 10, true); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(nodes.find((n) => n.id === "x")!.parentId).toBe("src"); + expect(assertChainOk(nodes, "src")).toEqual(["x"]); + }); + + it("refuses a cycle when mirror prev sibling resolves into self", () => { + let nodes = seedFlat(["x", "m"]); + nodes = nodes.map((n) => + n.id === "m" ? { ...n, mirrorOf: "x", text: "x" } : n, + ); + // Indenting nothing after m that would cycle — indent m under x is fine. + // Cycle: indent a node whose prev sibling mirrors THAT node. + nodes = seedFlat(["a", "m", "b"]); + nodes = nodes.map((n) => + n.id === "m" ? { ...n, mirrorOf: "b", text: "b" } : n, + ); + // Indent b under m → would parent b under b (trueSourceOf m = b). + expect(planIndent(buildTreeIndex(nodes), "b", 10, true)).toBeNull(); + }); +}); + +describe("multi-select planners (ADR 0018)", () => { + it("planRemoveMany deletes contiguous siblings without tearing the chain", () => { + let nodes = seedFlat(["a", "b", "c", "d"]); + const plan = planRemoveMany(nodes, ["b", "c"], 10); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, null)).toEqual(["a", "d"]); + }); + + it("planMoveMany preserves order under the target", () => { + let nodes = seedFlat(["t", "a", "b", "c"]); + const plan = planMoveMany(nodes, { + targetId: "t", + nodeIds: ["a", "b"], + updatedAt: 10, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, null)).toEqual(["t", "c"]); + expect(assertChainOk(nodes, "t")).toEqual(["a", "b"]); + }); + + it("planIndentMany indents a run under the previous sibling", () => { + let nodes = seedFlat(["a", "b", "c", "d"]); + const plan = planIndentMany(nodes, ["b", "c"], 10); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, null)).toEqual(["a", "d"]); + expect(assertChainOk(nodes, "a")).toEqual(["b", "c"]); + }); + + it("planIndentMany resolveMirror parents into the SOURCE", () => { + let nodes = seedFlat(["src", "m", "b", "c"]); + nodes = nodes.map((n) => + n.id === "m" ? { ...n, mirrorOf: "src", text: "src" } : n, + ); + const plan = planIndentMany(nodes, ["b", "c"], 10, true); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, "src")).toEqual(["b", "c"]); + }); + + it("planOutdentMany lifts a run after the former parent", () => { + let nodes = seedFlat(["p", "z"]); + nodes = [ + ...nodes, + makeOutlineNode({ + id: "a", + userId: USER, + parentId: "p", + prevSiblingId: null, + text: "a", + createdAt: 1, + updatedAt: 1, + }), + makeOutlineNode({ + id: "b", + userId: USER, + parentId: "p", + prevSiblingId: "a", + text: "b", + createdAt: 2, + updatedAt: 2, + }), + ]; + const plan = planOutdentMany(nodes, ["a", "b"], 10); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, null)).toEqual(["p", "a", "b", "z"]); + }); +}); + +describe("planMaterializeDailyNodes", () => { + it("inserts scaffold + day + seed in chain order", () => { + let nodes: OutlineNode[] = []; + const plan = planMaterializeDailyNodes(nodes, { + userId: USER, + inserts: [ + { id: "container", parentId: null, afterId: null, text: "Daily" }, + { + id: "year", + parentId: "container", + afterId: null, + text: "2026", + }, + { id: "day", parentId: "year", afterId: null, text: "Tuesday" }, + { id: "seed", parentId: "day", afterId: null, text: "" }, + ], + createdAt: 1, + updatedAt: 1, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, null)).toEqual(["container"]); + expect(assertChainOk(nodes, "container")).toEqual(["year"]); + expect(assertChainOk(nodes, "year")).toEqual(["day"]); + expect(assertChainOk(nodes, "day")).toEqual(["seed"]); + }); + + it("skips ids already present", () => { + let nodes = [ + makeOutlineNode({ + id: "container", + userId: USER, + parentId: null, + prevSiblingId: null, + text: "Daily", + createdAt: 0, + updatedAt: 0, + }), + ]; + const plan = planMaterializeDailyNodes(nodes, { + userId: USER, + inserts: [ + { id: "container", parentId: null, afterId: null, text: "Daily" }, + { + id: "day", + parentId: "container", + afterId: null, + text: "Tue", + }, + ], + createdAt: 1, + updatedAt: 1, + }); + expect(plan).not.toBeNull(); + nodes = applyPlan(nodes, plan!); + expect(assertChainOk(nodes, "container")).toEqual(["day"]); + }); +}); diff --git a/src/data/outline-plans/planners.ts b/src/data/outline-plans/planners.ts new file mode 100644 index 00000000..4410758a --- /dev/null +++ b/src/data/outline-plans/planners.ts @@ -0,0 +1,849 @@ +import type { Node } from "../schema"; +import type { TreeIndex } from "../tree"; +import type { OutlineNode, OutlinePlan, PlanPatch } from "./types"; + +import { + buildTreeIndex, + childrenOf, + makeNode, + trueSourceOf, + wouldMirrorCycle, +} from "../tree"; +import { emptyPlan } from "./types"; + +/** Dotflowy `makeNode` + Lunora shard `userId`. */ +export function makeOutlineNode( + partial: Partial & Pick, +): OutlineNode { + const { userId, id, ...rest } = partial; + return { ...makeNode({ id, ...rest }), userId }; +} + +/** + * Mid-list insert: new node after `afterId` under `parentId`, repointing the + * follower. Port of Dotflowy `insertSibling` + worker `planAddNode` mid-list. + */ +export function planInsertSibling( + index: TreeIndex, + args: { + id: string; + userId: string; + parentId: string | null; + afterId: string | null; + text: string; + isTask?: boolean; + kind?: "paragraph" | null; + createdAt: number; + updatedAt: number; + }, +): OutlinePlan | null { + if (args.parentId !== null && !index.byId.has(args.parentId)) return null; + + const siblings = childrenOf(index, args.parentId); + let nextSiblingId: string | null = null; + if (args.afterId) { + const i = siblings.findIndex((n) => n.id === args.afterId); + if (i === -1) return null; + if (i + 1 < siblings.length) nextSiblingId = siblings[i + 1]!.id; + } else if (siblings.length > 0) { + // afterId null = insert as head + nextSiblingId = siblings[0]!.id; + } + + const plan = emptyPlan(); + plan.inserts.push( + makeOutlineNode({ + id: args.id, + userId: args.userId, + parentId: args.parentId, + prevSiblingId: args.afterId, + text: args.text, + isTask: args.isTask ?? false, + kind: args.kind ?? null, + createdAt: args.createdAt, + updatedAt: args.updatedAt, + }), + ); + + if (nextSiblingId) { + plan.patches.push({ + id: nextSiblingId, + fields: { prevSiblingId: args.id, updatedAt: args.updatedAt }, + }); + } + + return plan; +} + +/** + * Indent: become last child of previous sibling. Port of Dotflowy `indent`. + * + * `resolveMirror` (ADR 0022): when the previous sibling is a mirror, parent into + * its SOURCE (`trueSourceOf`) so the node windows into every instance — matching + * classic `mutations.indent(…, resolveMirror)`. Collapse still targets the + * visible instance. + */ +export function planIndent( + index: TreeIndex, + nodeId: string, + updatedAt: number, + resolveMirror = false, +): OutlinePlan | null { + const node = index.byId.get(nodeId); + if (!node || !node.prevSiblingId) return null; + + const newParent = index.byId.get(node.prevSiblingId); + if (!newParent) return null; + + const newParentContentId = resolveMirror + ? trueSourceOf(index, newParent.id) + : newParent.id; + + if (resolveMirror) { + let cursor: Node | undefined = index.byId.get(newParentContentId); + let guard = index.byId.size + 1; + while (cursor && guard-- > 0) { + if (cursor.id === nodeId) return null; + cursor = cursor.parentId ? index.byId.get(cursor.parentId) : undefined; + } + } + + const oldSiblings = childrenOf(index, node.parentId); + const i = oldSiblings.findIndex((n) => n.id === nodeId); + const oldNext = + i !== -1 && i + 1 < oldSiblings.length ? oldSiblings[i + 1]! : null; + + const newSiblings = childrenOf(index, newParentContentId); + const lastExisting = + newSiblings.length > 0 ? newSiblings[newSiblings.length - 1]! : null; + + const plan = emptyPlan(); + plan.patches.push({ + id: nodeId, + fields: { + parentId: newParentContentId, + prevSiblingId: lastExisting ? lastExisting.id : null, + updatedAt, + }, + }); + + if (newParent.collapsed) { + plan.patches.push({ + id: newParent.id, + fields: { collapsed: false, updatedAt }, + }); + } + + if (oldNext) { + plan.patches.push({ + id: oldNext.id, + fields: { prevSiblingId: node.prevSiblingId, updatedAt }, + }); + } + + return plan; +} + +/** + * Outdent: become sibling immediately after former parent. Port of `outdent`. + */ +export function planOutdent( + index: TreeIndex, + nodeId: string, + updatedAt: number, +): OutlinePlan | null { + const node = index.byId.get(nodeId); + if (!node || node.parentId === null) return null; + + const oldParent = index.byId.get(node.parentId); + if (!oldParent) return null; + + const newParentId = oldParent.parentId; + + const oldSiblings = childrenOf(index, oldParent.id); + const i = oldSiblings.findIndex((n) => n.id === nodeId); + const oldNext = + i !== -1 && i + 1 < oldSiblings.length ? oldSiblings[i + 1]! : null; + + const newSiblings = childrenOf(index, newParentId); + const parentIdx = newSiblings.findIndex((n) => n.id === oldParent.id); + const afterParent = + parentIdx !== -1 && parentIdx + 1 < newSiblings.length + ? newSiblings[parentIdx + 1]! + : null; + + const plan = emptyPlan(); + plan.patches.push({ + id: nodeId, + fields: { + parentId: newParentId, + prevSiblingId: oldParent.id, + updatedAt, + }, + }); + + if (oldNext) { + plan.patches.push({ + id: oldNext.id, + fields: { prevSiblingId: node.prevSiblingId, updatedAt }, + }); + } + + if (afterParent) { + plan.patches.push({ + id: afterParent.id, + fields: { prevSiblingId: nodeId, updatedAt }, + }); + } + + return plan; +} + +/** + * Cascade delete subtree + relink follower. Port of `planDeleteNode`. + */ +export function planRemoveNode( + index: TreeIndex, + nodeId: string, + updatedAt: number, +): OutlinePlan | null { + const node = index.byId.get(nodeId); + if (!node) return null; + + const deletedIds: string[] = []; + const stack = [nodeId]; + while (stack.length) { + const id = stack.pop()!; + deletedIds.push(id); + for (const child of childrenOf(index, id)) stack.push(child.id); + } + + const plan = emptyPlan(); + const siblings = childrenOf(index, node.parentId); + const i = siblings.findIndex((n) => n.id === nodeId); + if (i !== -1 && i + 1 < siblings.length) { + const next = siblings[i + 1]!; + plan.patches.push({ + id: next.id, + fields: { prevSiblingId: node.prevSiblingId, updatedAt }, + }); + } + plan.deletes.push(...deletedIds); + return plan; +} + +/** + * Insert as FIRST child of `parentId` (push current head down). Port of + * Dotflowy `insertChildAtStart` / worker `planAddNode` position `'first'`. + * Same chain surgery as `planInsertSibling` with `afterId: null`. + */ +export function planInsertChildAtStart( + index: TreeIndex, + args: { + id: string; + userId: string; + parentId: string | null; + text: string; + isTask?: boolean; + kind?: "paragraph" | null; + createdAt: number; + updatedAt: number; + }, +): OutlinePlan | null { + return planInsertSibling(index, { ...args, afterId: null }); +} + +/** + * Append as LAST child of `parentId` (server resolves the current last sibling). + * Port of Dotflowy `appendChild` / quick-add born capture — one watermark. + */ +export function planAppendChild( + index: TreeIndex, + args: { + id: string; + userId: string; + parentId: string | null; + text: string; + isTask?: boolean; + kind?: "paragraph" | null; + createdAt: number; + updatedAt: number; + }, +): OutlinePlan | null { + if (args.parentId !== null && !index.byId.has(args.parentId)) return null; + const siblings = childrenOf(index, args.parentId); + const afterId = siblings.length ? siblings[siblings.length - 1]!.id : null; + return planInsertSibling(index, { ...args, afterId }); +} + +/** + * Bulk insert-only plan (OPML import chunks). Chains are pre-wired by + * `planOpmlImport`; no patches. Used by Lunora `importNodes`. + */ +export function planImportNodes(nodes: readonly OutlineNode[]): OutlinePlan { + const plan = emptyPlan(); + for (const node of nodes) plan.inserts.push(node); + return plan; +} + +/** Field-only text update. */ +export function planSetText( + index: TreeIndex, + nodeId: string, + text: string, + updatedAt: number, +): OutlinePlan | null { + if (!index.byId.has(nodeId)) return null; + const plan = emptyPlan(); + plan.patches.push({ id: nodeId, fields: { text, updatedAt } }); + return plan; +} + +export function planSetCompleted( + index: TreeIndex, + nodeId: string, + completed: boolean, + updatedAt: number, +): OutlinePlan | null { + if (!index.byId.has(nodeId)) return null; + const plan = emptyPlan(); + plan.patches.push({ id: nodeId, fields: { completed, updatedAt } }); + return plan; +} + +export function planSetCollapsed( + index: TreeIndex, + nodeId: string, + collapsed: boolean, + updatedAt: number, +): OutlinePlan | null { + if (!index.byId.has(nodeId)) return null; + const plan = emptyPlan(); + plan.patches.push({ id: nodeId, fields: { collapsed, updatedAt } }); + return plan; +} + +/** + * Make task / plain bullet. Clears `kind` (ADR 0045 exclusivity — mirrors + * `setIsTask` / worker `planUpdateNode`). + */ +export function planSetIsTask( + index: TreeIndex, + nodeId: string, + isTask: boolean, + updatedAt: number, +): OutlinePlan | null { + if (!index.byId.has(nodeId)) return null; + const plan = emptyPlan(); + plan.patches.push({ id: nodeId, fields: { isTask, kind: null, updatedAt } }); + return plan; +} + +/** + * Paragraph ↔ bullet. Always clears `isTask` (ADR 0045 — mirrors `setKind`). + */ +export function planSetKind( + index: TreeIndex, + nodeId: string, + kind: "paragraph" | null, + updatedAt: number, +): OutlinePlan | null { + if (!index.byId.has(nodeId)) return null; + const plan = emptyPlan(); + plan.patches.push({ + id: nodeId, + fields: { kind, isTask: false, updatedAt }, + }); + return plan; +} + +export function planSetBookmarkedAt( + index: TreeIndex, + nodeId: string, + bookmarkedAt: number | null, + updatedAt: number, +): OutlinePlan | null { + if (!index.byId.has(nodeId)) return null; + const plan = emptyPlan(); + plan.patches.push({ id: nodeId, fields: { bookmarkedAt, updatedAt } }); + return plan; +} + +/** + * Reparent + sibling-chain splice (port of Dotflowy `moveNode` / + * worker `applyMoveInPlace`). Optional `expandIds` uncollapse uncle/aunt on + * edge keyboard moves. + */ +export function planMoveNode( + index: TreeIndex, + args: { + id: string; + newParentId: string | null; + afterSiblingId: string | null; + updatedAt: number; + expandIds?: readonly string[]; + }, +): OutlinePlan | null { + const node = index.byId.get(args.id); + if (!node) return null; + if (args.afterSiblingId === args.id || args.newParentId === args.id) + return null; + + if (args.newParentId !== null) { + let cursor = index.byId.get(args.newParentId); + let guard = index.byId.size + 1; + while (cursor && guard-- > 0) { + if (cursor.id === args.id) return null; + cursor = cursor.parentId ? index.byId.get(cursor.parentId) : undefined; + } + } + + if ( + args.newParentId === node.parentId && + (args.afterSiblingId ?? null) === (node.prevSiblingId ?? null) + ) { + if (!args.expandIds?.length) return null; + const plan = emptyPlan(); + for (const expandId of args.expandIds) { + if (index.byId.has(expandId)) { + plan.patches.push({ + id: expandId, + fields: { collapsed: false, updatedAt: args.updatedAt }, + }); + } + } + return plan.patches.length ? plan : null; + } + + const oldSiblings = childrenOf(index, node.parentId); + const oi = oldSiblings.findIndex((n) => n.id === args.id); + const oldNext = + oi !== -1 && oi + 1 < oldSiblings.length ? oldSiblings[oi + 1]! : null; + + const newSiblings = childrenOf(index, args.newParentId); + let newNext: { id: string } | null = null; + if (args.afterSiblingId === null) { + newNext = newSiblings[0] ?? null; + } else { + const ni = newSiblings.findIndex((n) => n.id === args.afterSiblingId); + newNext = + ni !== -1 && ni + 1 < newSiblings.length ? newSiblings[ni + 1]! : null; + } + + const plan = emptyPlan(); + if (args.expandIds) { + for (const expandId of args.expandIds) { + if (index.byId.has(expandId)) { + plan.patches.push({ + id: expandId, + fields: { collapsed: false, updatedAt: args.updatedAt }, + }); + } + } + } + if (oldNext) { + plan.patches.push({ + id: oldNext.id, + fields: { + prevSiblingId: node.prevSiblingId, + updatedAt: args.updatedAt, + }, + }); + } + plan.patches.push({ + id: args.id, + fields: { + parentId: args.newParentId, + prevSiblingId: args.afterSiblingId, + updatedAt: args.updatedAt, + }, + }); + if (newNext && newNext.id !== args.id) { + plan.patches.push({ + id: newNext.id, + fields: { prevSiblingId: args.id, updatedAt: args.updatedAt }, + }); + } + return plan; +} + +/** + * Enter mid-split: setText(left) + insertSibling(right) in ONE plan so Lunora + * commits them under a single watermark (avoids two mutator round-trips). + */ +export function planSplitNode( + index: TreeIndex, + args: { + id: string; + userId: string; + parentId: string | null; + afterId: string; + newId: string; + leftText: string; + rightText: string; + isTask?: boolean; + kind?: "paragraph" | null; + createdAt: number; + updatedAt: number; + }, +): OutlinePlan | null { + if (!index.byId.has(args.id)) return null; + const insert = planInsertSibling(index, { + id: args.newId, + userId: args.userId, + parentId: args.parentId, + afterId: args.afterId, + text: args.rightText, + isTask: args.isTask, + kind: args.kind, + createdAt: args.createdAt, + updatedAt: args.updatedAt, + }); + if (!insert) return null; + + const plan = emptyPlan(); + plan.inserts.push(...insert.inserts); + plan.patches.push(...insert.patches); + plan.patches.push({ + id: args.id, + fields: { text: args.leftText, updatedAt: args.updatedAt }, + }); + return plan; +} + +/** + * Flat-record equality for restore diffs. Nodes are shallow; `userId` is + * Lunora-only and ignored so history snapshots (`Node`) compare cleanly. + */ +export function sameNodeFields(a: Node, b: Node): boolean { + const ra = a as Record; + const rb = b as Record; + for (const key of Object.keys(ra)) { + if (key === "userId") continue; + if (ra[key] !== rb[key]) return false; + } + for (const key of Object.keys(rb)) { + if (key === "userId") continue; + if (!(key in ra)) return false; + } + return true; +} + +/** Full field snapshot for a restore patch (every Node field except `id`). */ +function restorePatchFields(node: OutlineNode): PlanPatch["fields"] { + return { + parentId: node.parentId, + prevSiblingId: node.prevSiblingId, + text: node.text, + isTask: node.isTask, + completed: node.completed, + collapsed: node.collapsed, + bookmarkedAt: node.bookmarkedAt, + mirrorOf: node.mirrorOf, + createdAt: node.createdAt, + updatedAt: node.updatedAt, + origin: node.origin, + kind: node.kind, + }; +} + +/** + * Snapshot restore → one OutlinePlan (deletes + inserts + full-field patches). + * Port of `history.ts` planRestore diff — used by Lunora `restoreNodes` and + * unit-tested here so undo/redo doesn't invent a second planner. + */ +export function planRestoreNodes( + current: readonly OutlineNode[], + target: readonly OutlineNode[], +): OutlinePlan { + const targetById = new Map(target.map((n) => [n.id, n])); + const currentById = new Map(current.map((n) => [n.id, n])); + const plan = emptyPlan(); + + for (const id of currentById.keys()) { + if (!targetById.has(id)) plan.deletes.push(id); + } + + for (const [id, node] of targetById) { + const live = currentById.get(id); + if (!live) { + plan.inserts.push(node); + } else if (!sameNodeFields(live, node)) { + plan.patches.push({ id, fields: restorePatchFields(node) }); + } + } + + return plan; +} + +/** + * Create a mirror of `sourceId` as last child of `targetParentId` (null = + * top level). Flattens to the TRUE source; resolves the destination through + * `trueSourceOf` (worker `planMirrorNode` / ADR 0022); refuses cycles. + */ +export function planMirrorNode( + index: TreeIndex, + args: { + id: string; + userId: string; + sourceId: string; + targetParentId: string | null; + createdAt: number; + updatedAt: number; + }, +): OutlinePlan | null { + if (!index.byId.has(args.sourceId)) return null; + + let parentId: string | null = null; + if (args.targetParentId !== null) { + if (!index.byId.has(args.targetParentId)) return null; + parentId = trueSourceOf(index, args.targetParentId); + } + + const trueSourceId = trueSourceOf(index, args.sourceId); + if (wouldMirrorCycle(index, trueSourceId, parentId)) return null; + + const siblings = childrenOf(index, parentId); + const after = siblings.length ? siblings[siblings.length - 1]!.id : null; + + const plan = emptyPlan(); + plan.inserts.push( + makeOutlineNode({ + id: args.id, + userId: args.userId, + parentId, + prevSiblingId: after, + text: index.byId.get(trueSourceId)?.text ?? "", + mirrorOf: trueSourceId, + createdAt: args.createdAt, + updatedAt: args.updatedAt, + }), + ); + return plan; +} + +/** Apply a plan to an in-memory node list (for unit tests / working copies). */ +export function applyPlan( + nodes: OutlineNode[], + plan: OutlinePlan, +): OutlineNode[] { + const byId = new Map(nodes.map((n) => [n.id, { ...n }])); + + // deletes → patches → inserts (restore-safe; matches server commitPlan) + for (const id of plan.deletes) byId.delete(id); + + for (const patch of plan.patches) { + const row = byId.get(patch.id); + if (row) Object.assign(row, patch.fields); + } + + for (const insert of plan.inserts) { + byId.set(insert.id, { ...insert }); + } + + return [...byId.values()]; +} + +/** True when a plan would change the outline. */ +function planHasWork(plan: OutlinePlan): boolean { + return ( + plan.deletes.length > 0 || + plan.patches.length > 0 || + plan.inserts.length > 0 + ); +} + +/** + * Diff `before` → `after` into one OutlinePlan. Used by multi-step planners that + * rebuild a working copy between sibling ops (ADR 0018), then emit a single + * watermarked mutator plan. + */ +function planFromWorkingCopy( + before: readonly OutlineNode[], + after: readonly OutlineNode[], +): OutlinePlan | null { + const plan = planRestoreNodes(before, after); + return planHasWork(plan) ? plan : null; +} + +/** + * Delete several roots (+ subtrees) in one plan. Rebuilds the working index + * between each remove so contiguous-sibling deletes don't tear the chain + * (port of `removeManyNodes`). + */ +export function planRemoveMany( + nodes: readonly OutlineNode[], + ids: readonly string[], + updatedAt: number, +): OutlinePlan | null { + if (ids.length === 0) return null; + let working = [...nodes]; + for (const id of ids) { + const step = planRemoveNode(buildTreeIndex(working), id, updatedAt); + if (!step) continue; + working = applyPlan(working, step); + } + return planFromWorkingCopy(nodes, working); +} + +/** + * Move several nodes to be last children of `targetId`, preserving order. + * Rebuilds between each move (port of `moveManyNodes`). + */ +export function planMoveMany( + nodes: readonly OutlineNode[], + args: { + targetId: string | null; + nodeIds: readonly string[]; + updatedAt: number; + }, +): OutlinePlan | null { + if (args.nodeIds.length === 0) return null; + let working = [...nodes]; + const firstSiblings = childrenOf(buildTreeIndex(working), args.targetId); + let after: string | null = firstSiblings.length + ? firstSiblings[firstSiblings.length - 1]!.id + : null; + for (const id of args.nodeIds) { + const step = planMoveNode(buildTreeIndex(working), { + id, + newParentId: args.targetId, + afterSiblingId: after, + updatedAt: args.updatedAt, + }); + if (!step) continue; + working = applyPlan(working, step); + after = id; + } + return planFromWorkingCopy(nodes, working); +} + +/** + * Indent a contiguous sibling run under the first root's previous sibling + * (port of `indentManyNodes`). `resolveMirror` parents into the SOURCE when + * that previous sibling is a mirror instance. + */ +export function planIndentMany( + nodes: readonly OutlineNode[], + rootIds: readonly string[], + updatedAt: number, + resolveMirror = false, +): OutlinePlan | null { + if (rootIds.length === 0) return null; + let working = [...nodes]; + const index = buildTreeIndex(working); + const targetId = index.byId.get(rootIds[0]!)?.prevSiblingId; + if (!targetId) return null; + + if (index.byId.get(targetId)?.collapsed) { + const expand = planSetCollapsed( + buildTreeIndex(working), + targetId, + false, + updatedAt, + ); + if (expand) working = applyPlan(working, expand); + } + + const live = buildTreeIndex(working); + const target = resolveMirror ? trueSourceOf(live, targetId) : targetId; + + if (resolveMirror && target !== targetId) { + const selected = new Set(rootIds); + let cursor: string | null = target; + let guard = live.byId.size + 1; + while (cursor && guard-- > 0) { + if (selected.has(cursor)) return null; + cursor = live.byId.get(cursor)?.parentId ?? null; + } + } + + // Inline move-many against `working` so the final diff includes expand + + // moves relative to the ORIGINAL `nodes` (not a post-expand base). + const firstSiblings = childrenOf(buildTreeIndex(working), target); + let after: string | null = firstSiblings.length + ? firstSiblings[firstSiblings.length - 1]!.id + : null; + for (const id of rootIds) { + const step = planMoveNode(buildTreeIndex(working), { + id, + newParentId: target, + afterSiblingId: after, + updatedAt, + }); + if (!step) continue; + working = applyPlan(working, step); + after = id; + } + return planFromWorkingCopy(nodes, working); +} + +/** + * Outdent a contiguous sibling run one level (port of `outdentManyNodes`). + * Rebuilds between each move so order is preserved after the former parent. + */ +export function planOutdentMany( + nodes: readonly OutlineNode[], + rootIds: readonly string[], + updatedAt: number, +): OutlinePlan | null { + if (rootIds.length === 0) return null; + let working = [...nodes]; + const start = buildTreeIndex(working); + const oldParentId = start.byId.get(rootIds[0]!)?.parentId; + if (!oldParentId) return null; + const newParentId = start.byId.get(oldParentId)?.parentId ?? null; + + let after: string = oldParentId; + for (const id of rootIds) { + const step = planMoveNode(buildTreeIndex(working), { + id, + newParentId, + afterSiblingId: after, + updatedAt, + }); + if (!step) continue; + working = applyPlan(working, step); + after = id; + } + return planFromWorkingCopy(nodes, working); +} + +/** + * Daily scaffold + day (+ optional seed) inserts in ONE plan after kv claims + * settle client-side. Each entry is already placed (`afterId` = predecessor, or + * null for head). Skips ids already present. Port of `materializeNewDay`'s + * node half — kv `claimMapping` stays on `/api/kv` (phase 2b). + */ +export function planMaterializeDailyNodes( + nodes: readonly OutlineNode[], + args: { + userId: string; + inserts: readonly { + id: string; + parentId: string | null; + afterId: string | null; + text: string; + }[]; + createdAt: number; + updatedAt: number; + }, +): OutlinePlan | null { + if (args.inserts.length === 0) return null; + let working = [...nodes]; + for (const ins of args.inserts) { + if (working.some((n) => n.id === ins.id)) continue; + const step = planInsertSibling(buildTreeIndex(working), { + id: ins.id, + userId: args.userId, + parentId: ins.parentId, + afterId: ins.afterId, + text: ins.text, + createdAt: args.createdAt, + updatedAt: args.updatedAt, + }); + if (!step) return null; + working = applyPlan(working, step); + } + return planFromWorkingCopy(nodes, working); +} diff --git a/src/data/outline-plans/seed.test.ts b/src/data/outline-plans/seed.test.ts new file mode 100644 index 00000000..20e300bc --- /dev/null +++ b/src/data/outline-plans/seed.test.ts @@ -0,0 +1,99 @@ +import { describe, expect, it } from "bun:test"; + +import { applyPlan, buildTreeIndex, childrenOf } from "./index"; +import { + DEMO_SEED_IDS, + DEMO_SEED_TEXTS, + planSeedIfEmpty, + seedEmptyOutline, + shouldSeedOutline, +} from "./seed"; + +describe("planSeedIfEmpty", () => { + it("shouldSeedOutline only when ready and empty", () => { + expect(shouldSeedOutline({ isReady: false, nodeCount: 0 })).toBe(false); + expect(shouldSeedOutline({ isReady: true, nodeCount: 1 })).toBe(false); + expect(shouldSeedOutline({ isReady: true, nodeCount: 0 })).toBe(true); + }); + + it("returns null when any nodes exist (idempotent no-op)", () => { + const plan = planSeedIfEmpty( + [ + { + id: "x", + parentId: null, + prevSiblingId: null, + text: "existing", + isTask: false, + completed: false, + collapsed: false, + bookmarkedAt: null, + mirrorOf: null, + createdAt: 1, + updatedAt: 1, + origin: null, + kind: null, + userId: "u1", + }, + ], + { userId: "u1", createdAt: 1000 }, + ); + expect(plan).toBeNull(); + }); + + it("inserts demo chain with deterministic ids + timestamps", () => { + const plan = planSeedIfEmpty([], { + userId: "u1", + createdAt: 1000, + texts: ["one", "two"], + ids: ["id-1", "id-2"], + }); + expect(plan).not.toBeNull(); + expect(plan!.inserts).toEqual([ + expect.objectContaining({ + id: "id-1", + userId: "u1", + parentId: null, + prevSiblingId: null, + text: "one", + createdAt: 1000, + updatedAt: 1000, + }), + expect.objectContaining({ + id: "id-2", + userId: "u1", + parentId: null, + prevSiblingId: "id-1", + text: "two", + createdAt: 1001, + updatedAt: 1001, + }), + ]); + expect(plan!.patches).toEqual([]); + expect(plan!.deletes).toEqual([]); + + const index = buildTreeIndex(applyPlan([], plan!)); + expect(childrenOf(index, null).map((n) => n.id)).toEqual(["id-1", "id-2"]); + }); + + it("default texts/ids cover the demo bullets", () => { + const plan = planSeedIfEmpty([], { userId: "u1", createdAt: 1 }); + expect(plan).not.toBeNull(); + expect(plan!.inserts.map((n) => n.text)).toEqual([...DEMO_SEED_TEXTS]); + expect(plan!.inserts.map((n) => n.id)).toEqual([...DEMO_SEED_IDS]); + }); +}); + +describe("seedEmptyOutline", () => { + it("calls seedIfEmpty once with userId + createdAt", async () => { + const calls: Array<{ userId: string; createdAt: number }> = []; + await seedEmptyOutline({ + userId: "u1", + now: () => 42, + seedIfEmpty: async (args) => { + calls.push(args); + }, + }); + expect(calls).toEqual([{ userId: "u1", createdAt: 42 }]); + }); +}); diff --git a/src/data/outline-plans/seed.ts b/src/data/outline-plans/seed.ts new file mode 100644 index 00000000..3dc8cdfe --- /dev/null +++ b/src/data/outline-plans/seed.ts @@ -0,0 +1,105 @@ +/** + * Idempotent first-run demo seed. + * + * Idempotency is server-authoritative: `seedIfEmpty` loads the shard, no-ops if + * any nodes exist, else inserts 4 demo bullets with **deterministic clientIds**. + * Watermark FIFO on the DO serializes concurrent calls — the second sees + * non-empty and no-ops. Client optimistic apply uses the same ids so multi-tab + * overlays converge. + */ + +import type { OutlineNode, OutlinePlan } from "./types"; + +import { makeNode } from "../tree"; +import { emptyPlan } from "./types"; + +export const DEMO_SEED_TEXTS = [ + "Welcome to the Lunora outline spike", + "Open a second tab — edits sync live", + "Try indent / outdent / delete", + "Hard reload restores from wholeOutline", +] as const; + +/** + * Fixed UUID clientIds for the 4 demo bullets (shard-local). + * Same ids every seed → multi-tab optimistic rows converge; second server call no-ops. + */ +export const DEMO_SEED_IDS = [ + "d0ef1001-5eed-4000-8000-000000000001", + "d0ef1002-5eed-4000-8000-000000000002", + "d0ef1003-5eed-4000-8000-000000000003", + "d0ef1004-5eed-4000-8000-000000000004", +] as const; + +export type SeedIfEmptyArgs = { + userId: string; + /** Base timestamp; bullet i uses createdAt/updatedAt = createdAt + i. */ + createdAt: number; + texts?: readonly string[]; + ids?: readonly string[]; +}; + +/** Gate: ready + zero nodes. Callers still guard in-flight / StrictMode. */ +export function shouldSeedOutline(opts: { + isReady: boolean; + nodeCount: number; +}): boolean { + return opts.isReady && opts.nodeCount === 0; +} + +/** + * Pure planner: empty outline → insert demo chain; non-empty → null (no-op). + */ +export function planSeedIfEmpty( + nodes: readonly OutlineNode[], + args: SeedIfEmptyArgs, +): OutlinePlan | null { + if (nodes.length > 0) return null; + + const texts = args.texts ?? DEMO_SEED_TEXTS; + const ids = args.ids ?? DEMO_SEED_IDS; + if (texts.length !== ids.length) { + throw new Error("planSeedIfEmpty: texts and ids length mismatch"); + } + + const plan = emptyPlan(); + let prev: string | null = null; + for (let i = 0; i < texts.length; i++) { + const id = ids[i]!; + const t = args.createdAt + i; + plan.inserts.push({ + ...makeNode({ + id, + parentId: null, + prevSiblingId: prev, + text: texts[i]!, + createdAt: t, + updatedAt: t, + }), + userId: args.userId, + }); + prev = id; + } + return plan; +} + +export type SeedIfEmptyFn = (args: { + userId: string; + createdAt: number; +}) => Promise; + +/** + * Fire the server-authoritative `seedIfEmpty` mutator (optimistic apply mirrors + * `planSeedIfEmpty` with the same deterministic clientIds). + */ +export async function seedEmptyOutline(opts: { + userId: string; + seedIfEmpty: SeedIfEmptyFn; + now?: () => number; +}): Promise { + const now = opts.now ?? (() => Date.now()); + await opts.seedIfEmpty({ + userId: opts.userId, + createdAt: now(), + }); +} diff --git a/src/data/outline-plans/types.ts b/src/data/outline-plans/types.ts new file mode 100644 index 00000000..ed3136ad --- /dev/null +++ b/src/data/outline-plans/types.ts @@ -0,0 +1,46 @@ +/** + * Shared outline plan types for Lunora mutators + client optimism. + * Converges on Dotflowy `Node` (wire-schema / schema) — `userId` is the + * Lunora shard key only (not on the custom-DO `Node` wire type). + */ + +import type { Node } from "../schema"; + +/** Planner node = Dotflowy Node + Lunora shard `userId`. */ +export type OutlineNode = Node & { userId: string }; + +export type NodeKind = Node["kind"]; + +export type PlanPatch = { + id: string; + fields: Partial< + Pick< + OutlineNode, + | "parentId" + | "prevSiblingId" + | "text" + | "isTask" + | "completed" + | "collapsed" + | "bookmarkedAt" + | "mirrorOf" + | "createdAt" + | "updatedAt" + | "origin" + | "kind" + > + >; +}; + +/** Structural plan applied identically by client optimistic apply + server mutator. */ +export type OutlinePlan = { + inserts: OutlineNode[]; + patches: PlanPatch[]; + deletes: string[]; +}; + +export const emptyPlan = (): OutlinePlan => ({ + inserts: [], + patches: [], + deletes: [], +}); diff --git a/src/data/saved-queries.ts b/src/data/saved-queries.ts index 6eb4d76a..ae03020f 100644 --- a/src/data/saved-queries.ts +++ b/src/data/saved-queries.ts @@ -3,6 +3,7 @@ import { createCollection } from "@tanstack/react-db"; import { Schema } from "effect"; import { useCallback, useSyncExternalStore } from "react"; +import { isLunoraSyncEnabled } from "./flags"; import { kvDelete, kvFetch, kvPut, toKvKeys, toKvRows } from "./kv-api"; import { queryClient } from "./query-client"; import { @@ -71,26 +72,47 @@ export const savedQueriesCollection = createCollection( // --- Mutations -------------------------------------------------------------- +type LunoraSavedQueryWrites = { + list: () => SavedQueryRow[]; + upsert: (row: SavedQueryRow) => void; + patchName: (id: string, name: string) => void; + remove: (id: string) => void; +}; + +let lunoraWrites: LunoraSavedQueryWrites | null = null; + +function liveRows(): SavedQueryRow[] { + if (lunoraWrites) return lunoraWrites.list(); + return savedQueriesCollection.toArray; +} + /** Save the current query, name defaulting to the query text (ADR 0048 * decision 3). No-op on an empty query or one already saved (idempotent, so a * double-save can't create a duplicate). Returns the row id, or null. */ export function saveQuery(query: string, name?: string): string | null { const q = normalizeQuery(query); if (!q) return null; - const existing = findSavedQuery(savedQueriesCollection.toArray, q); + const existing = findSavedQuery(liveRows(), q); if (existing) return existing.id; const id = typeof crypto !== "undefined" && "randomUUID" in crypto ? crypto.randomUUID() : `sq_${Date.now()}_${Math.random().toString(36).slice(2)}`; const trimmedName = name?.trim(); - savedQueriesCollection.insert({ + const nameVal = + trimmedName && trimmedName.length > 0 ? trimmedName : defaultQueryName(q); + const createdAt = Date.now(); + const row: SavedQueryRow = { id, - name: - trimmedName && trimmedName.length > 0 ? trimmedName : defaultQueryName(q), + name: nameVal, query: q, - createdAt: Date.now(), - }); + createdAt, + }; + if (lunoraWrites) { + lunoraWrites.upsert(row); + return id; + } + savedQueriesCollection.insert(row); return id; } @@ -98,14 +120,19 @@ export function saveQuery(query: string, name?: string): string | null { export function unsaveQuery(query: string): void { const q = normalizeQuery(query); if (!q) return; - for (const row of savedQueriesCollection.toArray) { - if (normalizeQuery(row.query) === q) savedQueriesCollection.delete(row.id); + for (const row of liveRows()) { + if (normalizeQuery(row.query) !== q) continue; + if (lunoraWrites) { + lunoraWrites.remove(row.id); + continue; + } + savedQueriesCollection.delete(row.id); } } /** Pin toggle: save if this query isn't saved, else unsave it. */ export function toggleSavedQuery(query: string): void { - if (isQuerySaved(savedQueriesCollection.toArray, query)) unsaveQuery(query); + if (isQuerySaved(liveRows(), query)) unsaveQuery(query); else saveQuery(query); } @@ -114,16 +141,22 @@ export function toggleSavedQuery(query: string): void { export function renameSavedQuery(id: string, name: string): void { const n = name.trim(); if (!n) return; - if (savedQueriesCollection.toArray.some((r) => r.id === id)) { - savedQueriesCollection.update(id, (draft) => void (draft.name = n)); + if (!liveRows().some((r) => r.id === id)) return; + if (lunoraWrites) { + lunoraWrites.patchName(id, n); + return; } + savedQueriesCollection.update(id, (draft) => void (draft.name = n)); } /** Delete a saved query by id (the popover row's X). */ export function deleteSavedQuery(id: string): void { - if (savedQueriesCollection.toArray.some((r) => r.id === id)) { - savedQueriesCollection.delete(id); + if (!liveRows().some((r) => r.id === id)) return; + if (lunoraWrites) { + lunoraWrites.remove(id); + return; } + savedQueriesCollection.delete(id); } // --- Reactive read (mirrors tag-colors.ts; prerender-safe) ------------------ @@ -136,15 +169,69 @@ let rows: SavedQueryRow[] = EMPTY; let sorted: SavedQueryRow[] = EMPTY; const listeners = new Set<() => void>(); let started = false; +let lunoraUnsub: (() => void) | null = null; -function rebuild() { - rows = savedQueriesCollection.toArray; +function rebuildFrom(source: SavedQueryRow[]) { + rows = source; sorted = rows.length === 0 ? EMPTY : sortSavedNewestFirst(rows); for (const l of listeners) l(); } +function rebuild() { + rebuildFrom(savedQueriesCollection.toArray); +} + +/** + * Called from `lunora-sync` when flag ON — subscribe to the Lunora shape and + * skip `/api/kv` for this collection. + */ +export function bindLunoraSavedQueries( + collection: { + toArray: Array<{ + _id: string; + name?: unknown; + query?: unknown; + createdAt?: unknown; + }>; + subscribeChanges: ( + cb: () => void, + opts?: { includeInitialState?: boolean }, + ) => { unsubscribe: () => void }; + }, + writes: Omit, +): void { + lunoraUnsub?.(); + const mapRows = (): SavedQueryRow[] => + collection.toArray.map((r) => ({ + id: r._id, + name: String(r.name ?? ""), + query: String(r.query ?? ""), + createdAt: Number(r.createdAt ?? 0), + })); + lunoraWrites = { + list: mapRows, + ...writes, + }; + const sub = collection.subscribeChanges(() => rebuildFrom(mapRows()), { + includeInitialState: true, + }); + lunoraUnsub = () => sub.unsubscribe(); + started = true; +} + +/** Tear down Lunora feed (flag OFF / account switch). */ +export function unbindLunoraSavedQueries(): void { + lunoraUnsub?.(); + lunoraUnsub = null; + lunoraWrites = null; + rows = EMPTY; + sorted = EMPTY; + started = false; +} + function ensureStarted() { if (started || typeof window === "undefined") return; + if (isLunoraSyncEnabled()) return; started = true; savedQueriesCollection.subscribeChanges(() => rebuild(), { includeInitialState: true, diff --git a/src/data/seed.ts b/src/data/seed.ts index 660e5a3f..db1b4a98 100644 --- a/src/data/seed.ts +++ b/src/data/seed.ts @@ -1,10 +1,27 @@ import { Effect } from "effect"; -import { nodesCollection, nodesLoadError } from "./collection"; +import { + isSyncReady, + nodesCollection, + nodesLoadError, + subscribeSyncReady, +} from "./collection"; import { BootstrapError } from "./errors"; +import { isLunoraSyncEnabled } from "./flags"; import { appendChild } from "./mutations"; import { createId, makeNode, now } from "./tree"; +/** Wait until the shell's sync-ready signal flips (custom DO or Lunora). */ +function waitUntilSyncReady(): Promise { + if (isSyncReady()) return Promise.resolve(); + return new Promise((resolve) => { + const unsub = subscribeSyncReady(() => { + unsub(); + resolve(); + }); + }); +} + // One-shot guard, set synchronously before the first await. bootstrapOutline is // the single mount entry point; this guard means React StrictMode's // double-mounted effect can't run two competing seed chains on the same empty @@ -31,6 +48,24 @@ let bootstrapped = false; export async function bootstrapOutline(): Promise { if (bootstrapped) return; bootstrapped = true; + + // ADR 0055: Lunora path seeds via `seedIfEmpty` mutator in lunora-sync. + // Just wait for wholeOutline ready so the editor doesn't race an empty feed. + if (isLunoraSyncEnabled()) { + return Effect.runPromise( + Effect.match( + Effect.tryPromise({ + try: () => waitUntilSyncReady(), + catch: (cause) => new BootstrapError({ cause }), + }), + { + onFailure: (error) => error, + onSuccess: () => undefined, + }, + ), + ); + } + // One Effect program. Wait for the first load (tryPromise covers the rare // synchronous sync-init throw); then the typed-failure gate — if the sync // failed (the common 500/offline case settles ready-but-empty with the error diff --git a/src/data/selection-state.ts b/src/data/selection-state.ts index 7ba3be07..51b3f07e 100644 --- a/src/data/selection-state.ts +++ b/src/data/selection-state.ts @@ -2,7 +2,7 @@ import { useSelector } from "@xstate/react"; import { Schema } from "effect"; import { createActor, setup } from "xstate"; -import { nodesCollection } from "./collection"; +import { getLiveNodes } from "./live-nodes"; import { buildTreeIndex, childrenOf, type Node, type TreeIndex } from "./tree"; import { getTreeIndex } from "./tree-store"; import { getViewIsHidden, getViewRootId } from "./view-state"; @@ -217,16 +217,17 @@ const selectionMachine = setup({ }, // Re-derive (parentId + rootIds) from the LIVE collection, same // anchor/focus, after a structural mutation relocates the run - // (indent/outdent). Reads `nodesCollection` directly so it's correct + // (indent/outdent). Reads the live store directly so it's correct // synchronously inside the same `runStructural` batch, before the tree - // store's subscription has rebuilt. ids + order are unchanged by an + // store's subscription has rebuilt (classic `nodesCollection` or Lunora + // `wholeOutline` — `getLiveNodes`). ids + order are unchanged by an // indent/outdent, so only `parentId` shifts. refresh: ({ context }) => { if (!context.data) return undefined; const d = computeRange( context.data.anchorId, context.data.focusId, - buildTreeIndex(nodesCollection.toArray), + buildTreeIndex(getLiveNodes()), ); return d ? { context: { data: d } } diff --git a/src/data/structural.ts b/src/data/structural.ts index d22421fc..74bb2800 100644 --- a/src/data/structural.ts +++ b/src/data/structural.ts @@ -8,6 +8,7 @@ import type { Node } from "./schema"; import { openSettings } from "../components/settings-nav"; import { persistBatchE } from "./api"; import { nodesCollection, waitForSeqE } from "./collection"; +import { isLunoraSyncEnabled } from "./flags"; import { NodesLimitError, runPromise } from "./nodes-client-effect"; import { notifySaveFailed } from "./save-failure"; import { chainDisagreements } from "./sibling-chain"; @@ -107,6 +108,13 @@ export function runStructuralTracked(body: () => T): { if (getActiveTransaction()) return { result: body(), persisted: Promise.resolve() }; + // ADR 0055 Lunora flag-swap: mutators own optimistic apply + watermark hold + // (checkpoints). Body calls Lunora-aware mutations which fire `bindMutators` + // handles — no custom `{ops}` batch / `waitForSeq`. + if (isLunoraSyncEnabled()) { + return { result: body(), persisted: Promise.resolve() }; + } + let result!: T; const tx = createTransaction({ mutationFn: async ({ transaction }) => { @@ -157,6 +165,16 @@ export async function runStructuralSliced( for (const slice of slices) slice(); return; } + // Lunora dogfood: no large-batch wire path yet — apply slices locally via + // mutator-backed mutations (same as runStructuralTracked when flag ON). + if (isLunoraSyncEnabled()) { + for (const slice of slices) { + slice(); + onProgress?.(); + await new Promise((resolve) => setTimeout(resolve, 0)); + } + return; + } const tx = createTransaction({ autoCommit: false, mutationFn: async ({ transaction }) => { diff --git a/src/data/tag-colors.ts b/src/data/tag-colors.ts index e161ffc7..aeb91aa7 100644 --- a/src/data/tag-colors.ts +++ b/src/data/tag-colors.ts @@ -3,6 +3,7 @@ import { createCollection } from "@tanstack/react-db"; import { Schema } from "effect"; import { useCallback, useSyncExternalStore } from "react"; +import { isLunoraSyncEnabled } from "./flags"; import { kvDelete, kvFetch, kvPut, toKvKeys, toKvRows } from "./kv-api"; import { queryClient } from "./query-client"; import { normalizeTag } from "./tags"; @@ -131,10 +132,21 @@ export const tagColorsCollection = createCollection( }), ); +type LunoraTagColorWrites = { + upsert: (tag: string, color: TagColor) => void; + remove: (tag: string) => void; +}; + +let lunoraWrites: LunoraTagColorWrites | null = null; + /** Set (or change) a tag's color -- applies to every instance of the tag. */ export function setTagColor(tag: string, color: TagColor) { const key = normalizeTag(tag); if (!key) return; + if (lunoraWrites) { + lunoraWrites.upsert(key, color); + return; + } const exists = tagColorsCollection.toArray.some((r) => r.tag === key); if (exists) tagColorsCollection.update(key, (draft) => void (draft.color = color)); @@ -144,6 +156,11 @@ export function setTagColor(tag: string, color: TagColor) { /** Clear a tag's color -- back to the neutral outlined default ("Auto"). */ export function clearTagColor(tag: string) { const key = normalizeTag(tag); + if (!key) return; + if (lunoraWrites) { + lunoraWrites.remove(key); + return; + } if (tagColorsCollection.toArray.some((r) => r.tag === key)) { tagColorsCollection.delete(key); } @@ -175,14 +192,60 @@ const EMPTY: TagColorRow[] = []; let rows: TagColorRow[] = EMPTY; const listeners = new Set<() => void>(); let started = false; +let lunoraUnsub: (() => void) | null = null; -function rebuild() { - rows = tagColorsCollection.toArray; +function rebuildFrom(source: TagColorRow[]) { + rows = source; for (const l of listeners) l(); } +function rebuild() { + rebuildFrom(tagColorsCollection.toArray); +} + +/** + * Called from `lunora-sync` when flag ON — subscribe to the Lunora shape and + * skip `/api/kv` for this collection. + */ +export function bindLunoraTagColors( + collection: { + toArray: TagColorRowDocLike[]; + subscribeChanges: ( + cb: () => void, + opts?: { includeInitialState?: boolean }, + ) => { unsubscribe: () => void }; + }, + writes: LunoraTagColorWrites, +): void { + lunoraUnsub?.(); + lunoraWrites = writes; + const mapRows = (): TagColorRow[] => + collection.toArray.map((r) => ({ + tag: String(r.tag ?? r._id), + color: String(r.color ?? ""), + })); + const sub = collection.subscribeChanges(() => rebuildFrom(mapRows()), { + includeInitialState: true, + }); + lunoraUnsub = () => sub.unsubscribe(); + started = true; +} + +/** Tear down Lunora feed (flag OFF / account switch). */ +export function unbindLunoraTagColors(): void { + lunoraUnsub?.(); + lunoraUnsub = null; + lunoraWrites = null; + rows = EMPTY; + started = false; +} + +type TagColorRowDocLike = { _id: string; tag?: unknown; color?: unknown }; + function ensureStarted() { if (started || typeof window === "undefined") return; + // Flag ON: wait for bindLunoraTagColors — never open the /api/kv collection. + if (isLunoraSyncEnabled()) return; started = true; tagColorsCollection.subscribeChanges(() => rebuild(), { includeInitialState: true, diff --git a/src/data/tree-store.ts b/src/data/tree-store.ts index 87cbfcb7..0f2a8aa7 100644 --- a/src/data/tree-store.ts +++ b/src/data/tree-store.ts @@ -5,7 +5,7 @@ import { useCallback, useRef, useSyncExternalStore } from "react"; import type { QueryFilter } from "./filter-query"; import { isSyncReady, nodesCollection, subscribeSyncReady } from "./collection"; -import { isMirrorsEnabled } from "./flags"; +import { isLunoraSyncEnabled, isMirrorsEnabled } from "./flags"; import { parseNodeLinks } from "./node-links"; import { parseTags } from "./tags"; import { @@ -356,15 +356,32 @@ function removeTagOccurrence(tag: string) { * first read is already populated; every later change is folded into the shared * index incrementally and notifies. Skipped on the server (SPA + prerender, no * socket) -- see ADR 0004. + * + * Lunora flag-swap (ADR 0055): `lunora-sync.ts` owns the subscription and calls + * {@link resetTreeFromNodes} — do not also subscribe to the idle `nodesCollection`. */ function ensureStarted() { if (started || typeof window === "undefined") return; started = true; + if (isLunoraSyncEnabled()) return; nodesCollection.subscribeChanges((changes) => applyChanges(changes), { includeInitialState: true, }); } +/** + * Replace the shared index from a full node list (Lunora `wholeOutline` feed). + * Used when the Lunora sync flag is ON — a full rebuild is fine for dogfood + * outlines; the incremental `applyChanges` path stays on the custom-DO flag-OFF + * path. + */ +export function resetTreeFromNodes(nodes: readonly Node[]): void { + ensureStarted(); + index = buildTreeIndex([...nodes]); + structureRev++; + notify(); +} + /** * Subscribe to any change in the shared tree index. Exported so the editor * shell's own narrow slice hooks ({@link useTrail}, {@link useHasNodes}, and the diff --git a/src/hooks/use-keyboard-viewport.ts b/src/hooks/use-keyboard-viewport.ts deleted file mode 100644 index 9bfa4a23..00000000 --- a/src/hooks/use-keyboard-viewport.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { useEffect, useState } from "react"; - -/** - * The height (px) at the bottom of the layout viewport currently covered by the - * software keyboard, tracked via `window.visualViewport` (ADR 0030). - * - * When the on-screen keyboard opens, the VISUAL viewport shrinks but the LAYOUT - * viewport (what `position: fixed; bottom: 0` is measured against) does not, so a - * bottom-pinned element sits behind the keyboard. The covered gap is - * `innerHeight - (visualViewport.height + visualViewport.offsetTop)`; a caller - * translates its bar up by that amount to ride directly above the keyboard. - * - * Returns 0 whenever the viewport isn't shrunk (hardware keyboard / iPad / no - * `visualViewport` support) — the caller falls back to a real bottom anchor then. - * Listeners are rAF-throttled; iOS fires `resize`/`scroll` in bursts during the - * keyboard animation. - */ -export function useKeyboardViewport(): number { - const [offset, setOffset] = useState(0); - - useEffect(() => { - const vv = window.visualViewport; - if (!vv) return; - - let raf = 0; - const update = () => { - raf = 0; - // offsetTop covers the case where the page has scrolled within the visual - // viewport (iOS): the visible band's bottom edge, in layout coordinates, is - // offsetTop + height. Clamp negatives (transient over-scroll / rounding). - const gap = window.innerHeight - (vv.height + vv.offsetTop); - setOffset(gap > 0 ? gap : 0); - }; - const schedule = () => { - if (raf) return; - raf = requestAnimationFrame(update); - }; - - update(); - vv.addEventListener("resize", schedule); - vv.addEventListener("scroll", schedule); - return () => { - vv.removeEventListener("resize", schedule); - vv.removeEventListener("scroll", schedule); - if (raf) cancelAnimationFrame(raf); - }; - }, []); - - return offset; -} diff --git a/src/plugins/daily/claim-mapping.test.ts b/src/plugins/daily/claim-mapping.test.ts new file mode 100644 index 00000000..0bf4db4d --- /dev/null +++ b/src/plugins/daily/claim-mapping.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, test } from "bun:test"; + +import { resolveDailyClaim } from "./claim-mapping"; + +describe("resolveDailyClaim", () => { + test("empty existing → candidate wins", () => { + expect(resolveDailyClaim(null, "cand")).toEqual({ + winner: "cand", + won: true, + }); + expect(resolveDailyClaim(undefined, "cand")).toEqual({ + winner: "cand", + won: true, + }); + expect(resolveDailyClaim("", "cand")).toEqual({ + winner: "cand", + won: true, + }); + }); + + test("pre-existing mapping wins over a different candidate", () => { + expect(resolveDailyClaim("first", "second")).toEqual({ + winner: "first", + won: false, + }); + }); + + test("re-claim of the same id is idempotent and still won", () => { + expect(resolveDailyClaim("first", "first")).toEqual({ + winner: "first", + won: true, + }); + }); +}); diff --git a/src/plugins/daily/claim-mapping.ts b/src/plugins/daily/claim-mapping.ts new file mode 100644 index 00000000..73a0dee9 --- /dev/null +++ b/src/plugins/daily/claim-mapping.ts @@ -0,0 +1,28 @@ +/** + * Pure daily-index claim (ADR 0052 / DO `getOrCreateKv` twin). + * Pre-existing mapping wins; candidate wins only when the key is absent. + */ + +export type DailyClaimResult = { + winner: string; + won: boolean; +}; + +/** + * Resolve an atomic claim: if `existingNodeId` is set, that id wins and this + * caller lost; otherwise `candidate` wins. + */ +export function resolveDailyClaim( + existingNodeId: string | null | undefined, + candidate: string, +): DailyClaimResult { + if (existingNodeId != null && existingNodeId !== "") { + // DO twin: winner is whatever is stored; `won` iff our candidate matches + // (re-claim of the same id is a no-op insert but still "our" mapping). + return { + winner: existingNodeId, + won: existingNodeId === candidate, + }; + } + return { winner: candidate, won: true }; +} diff --git a/src/plugins/daily/daily-index.ts b/src/plugins/daily/daily-index.ts index b9d42977..1525624d 100644 --- a/src/plugins/daily/daily-index.ts +++ b/src/plugins/daily/daily-index.ts @@ -4,6 +4,7 @@ import { Effect, Schema } from "effect"; import { useCallback, useSyncExternalStore } from "react"; import { localDateKey } from "../../data/date-links"; +import { isLunoraSyncEnabled } from "../../data/flags"; import { kvDelete, kvFetch, @@ -13,6 +14,7 @@ import { } from "../../data/kv-api"; import { kvGetOrCreateE } from "../../data/kv-client-effect"; import { queryClient } from "../../data/query-client"; +import { resolveDailyClaim } from "./claim-mapping"; /** * The daily index -- the *identity* of a daily note (ADR 0001). A row maps a @@ -171,8 +173,22 @@ export function getKeyForNode(nodeId: string): string | null { return keyByNodeId.get(nodeId) ?? null; } +type LunoraDailyWrites = { + upsert: (key: string, nodeId: string) => void; + claim: ( + key: string, + candidate: string, + ) => Promise<{ winner: string; won: boolean }>; +}; + +let lunoraWrites: LunoraDailyWrites | null = null; + /** Upsert a `key -> nodeId` mapping (used when (re)creating a container/day). */ export function setMapping(key: string, nodeId: string): void { + if (lunoraWrites) { + lunoraWrites.upsert(key, nodeId); + return; + } if (dailyIndexCollection.toArray.some((r) => r.key === key)) { dailyIndexCollection.update(key, (draft) => void (draft.nodeId = nodeId)); } else { @@ -185,25 +201,28 @@ export function setMapping(key: string, nodeId: string): void { * itself — the caller supplies a `candidate` node id, and this returns the * AUTHORITATIVE winner plus whether this caller won (so it should create the * node under `candidate`). Two devices with a stale replica both miss the key - * locally and both claim; the single-threaded DO lets exactly one win, killing - * the duplicate-daily-note race at the source. + * locally and both claim; the single-threaded DO / Lunora mutator lets exactly + * one win, killing the duplicate-daily-note race at the source. * - * This is the boundary that degrades to a value on failure: on a network/server - * failure it logs and degrades to the optimistic local path (treats `candidate` - * as the winner), so the feature keeps working — the rare failure window just - * reopens the pre-fix race, no worse than before the claim existed. - * - * Why Effect here (and throwing everywhere else in the kv path): the TanStack - * DB mutation handlers signal failure by THROWING (a throw triggers optimistic - * rollback), so the rest of kv-api.ts stays throw-based on purpose. claimMapping - * has no TanStack caller — it's an awaitable from a click handler — so it can - * speak Effect's typed-error channel directly and route with catchTag, proving - * the ergonomics on real I/O. See kv-client-effect.ts. + * Flag ON → Lunora `claimDailyMapping` mutator. Flag OFF → `/api/kv?op=claim` + * (Effect path). On network/server failure both degrade to treating `candidate` + * as the winner so the feature keeps working. */ export async function claimMapping( key: string, candidate: string, ): Promise<{ winner: string; won: boolean }> { + if (lunoraWrites) { + try { + return await lunoraWrites.claim(key, candidate); + } catch (e) { + console.warn( + `daily: Lunora claim "${key}" failed, creating locally:`, + e instanceof Error ? e.message : e, + ); + return resolveDailyClaim(null, candidate); + } + } /** * Route every typed kv error to a single degraded outcome *inside* the Effect * pipeline, then runPromise never rejects — caller sees only plain success. @@ -225,7 +244,7 @@ export async function claimMapping( }), ), ); - return { winner: row.nodeId, won: row.nodeId === candidate }; + return resolveDailyClaim(row.nodeId, candidate); } // --- Reactive read (mirrors tag-colors.ts; prerender-safe) ------------------ @@ -237,17 +256,93 @@ let rows: DailyRow[] = EMPTY; let keyByNodeId = new Map(); const listeners = new Set<() => void>(); let started = false; +let lunoraUnsub: (() => void) | null = null; -function rebuild() { - rows = dailyIndexCollection.toArray; +function rebuildFrom(source: DailyRow[]) { + rows = source; const next = new Map(); for (const r of rows) next.set(r.nodeId, r.key); keyByNodeId = next; for (const l of listeners) l(); } +function rebuild() { + rebuildFrom(dailyIndexCollection.toArray); +} + +/** + * Called from `lunora-sync` when flag ON — subscribe to the Lunora shape and + * skip `/api/kv` for this collection. `claim` must await the watermark so the + * authoritative winner is readable from the local collection afterward. + */ +export function bindLunoraDailyIndex( + collection: { + has: (key: string) => boolean; + get: (key: string) => DailyIndexRowDocLike | undefined; + toArray: DailyIndexRowDocLike[]; + subscribeChanges: ( + cb: () => void, + opts?: { includeInitialState?: boolean }, + ) => { unsubscribe: () => void }; + }, + writes: { + upsert: (key: string, nodeId: string) => void; + claimTx: ( + key: string, + nodeId: string, + ) => { isPersisted: { promise: Promise } }; + }, +): void { + lunoraUnsub?.(); + const mapRows = (): DailyRow[] => + collection.toArray.map((r) => ({ + key: String(r.key ?? r._id), + nodeId: String(r.nodeId ?? ""), + })); + lunoraWrites = { + upsert: writes.upsert, + claim: async (key, candidate) => { + const local = collection.has(key) + ? String(collection.get(key)?.nodeId ?? "") + : null; + if (local) { + // Fast path: shape already has the key — no mutator round-trip. + return resolveDailyClaim(local, candidate); + } + const tx = writes.claimTx(key, candidate); + await tx.isPersisted.promise; + const row = collection.get(key); + const winner = row ? String(row.nodeId) : candidate; + return resolveDailyClaim(winner, candidate); + }, + }; + const sub = collection.subscribeChanges(() => rebuildFrom(mapRows()), { + includeInitialState: true, + }); + lunoraUnsub = () => sub.unsubscribe(); + started = true; +} + +/** Tear down Lunora feed (flag OFF / account switch). */ +export function unbindLunoraDailyIndex(): void { + lunoraUnsub?.(); + lunoraUnsub = null; + lunoraWrites = null; + rows = EMPTY; + keyByNodeId = new Map(); + started = false; +} + +type DailyIndexRowDocLike = { + _id: string; + key?: unknown; + nodeId?: unknown; +}; + function ensureStarted() { if (started || typeof window === "undefined") return; + // Flag ON: wait for bindLunoraDailyIndex — never open the /api/kv collection. + if (isLunoraSyncEnabled()) return; started = true; dailyIndexCollection.subscribeChanges(() => rebuild(), { includeInitialState: true, @@ -299,6 +394,8 @@ export function getDailyRows(): DailyRow[] { */ export async function refreshDailyIndex(): Promise { ensureStarted(); + // Lunora shape is live — no kv refetch (and /api/kv is cold when flag ON). + if (lunoraWrites) return; // Best-effort: a network failure here must NOT block day creation (the caller // proceeds with whatever mappings it has), but a silent swallow hid the cause // of a misplaced day (finding 2) -- so warn, don't rethrow. diff --git a/src/plugins/daily/get-or-create.ts b/src/plugins/daily/get-or-create.ts index 136aef2d..7195f62d 100644 --- a/src/plugins/daily/get-or-create.ts +++ b/src/plugins/daily/get-or-create.ts @@ -17,13 +17,16 @@ import { toast } from "sonner"; import type { PluginContext } from "../types"; import { setRestoreProgress } from "../../components/history-restore"; -import { nodesCollection, resyncNodes } from "../../data/collection"; +import { resyncNodes } from "../../data/collection"; import { dayKeyToScaffoldChain, parentScaffoldKey, scaffoldLabel, } from "../../data/date-links"; +import { isLunoraSyncEnabled } from "../../data/flags"; import { RESTORE_SLICE_OPS, capture } from "../../data/history"; +import { getLiveNodes } from "../../data/live-nodes"; +import { getLunoraOutlineContext } from "../../data/lunora-sync"; import { appendChild, insertChildAtStart, @@ -32,12 +35,21 @@ import { setText, } from "../../data/mutations"; import { isNodesLimitError } from "../../data/nodes-client-effect"; +import { + applyPlan, + buildTreeIndex, + childrenOf, + planInsertSibling, + rowToNode, + type OutlineNode, +} from "../../data/outline-plans"; import { runStructural, runStructuralSliced, runStructuralTracked, } from "../../data/structural"; -import { buildTreeIndex, childrenOf, createId } from "../../data/tree"; +import { createId } from "../../data/tree"; +import { getTreeIndex } from "../../data/tree-store"; import { CONTAINER_KEY, DAILY_CONTAINER_TEXT, @@ -59,8 +71,17 @@ import { // --- get-or-create ---------------------------------------------------------- +function liveOutlineNodes(): OutlineNode[] | null { + if (!isLunoraSyncEnabled()) return null; + const lunora = getLunoraOutlineContext(); + if (!lunora) return null; + return lunora.store.collection.toArray.map(rowToNode); +} + function hasNode(id: string): boolean { - return nodesCollection.toArray.some((n) => n.id === id); + const lunoraNodes = liveOutlineNodes(); + if (lunoraNodes) return lunoraNodes.some((n) => n.id === id); + return getLiveNodes().some((n) => n.id === id); } /** One atomic claim for a scaffold/day key: the authoritative id, whether this @@ -93,7 +114,7 @@ function insertScaffoldNode( text: string, id: string, ): void { - const index = buildTreeIndex(nodesCollection.toArray); + const index = buildTreeIndex(getLiveNodes()); const siblings = childrenOf(index, parentNodeId).map((n) => ({ id: n.id, key: getKeyForNode(n.id), @@ -116,14 +137,23 @@ function healExistingDay( key: string, seedEntryLine: boolean, ): void { - const node = nodesCollection.toArray.find((n) => n.id === dayId); + const lunoraNodes = liveOutlineNodes(); + const node = lunoraNodes + ? lunoraNodes.find((n) => n.id === dayId) + : getLiveNodes().find((n) => n.id === dayId); if (node && !node.text.trim()) setText(dayId, formatDayText(key)); // Seeding is opt-in at the OPEN boundary (ADR 0041): only a write-intent // surface (/today, Today button, Cmd+K "Go to Today") asks for an empty line. // A reopened-but-emptied day re-seeds in its own isolated batch. No capture() // -- stays out of undo like day creation. if (seedEntryLine && !hasChildInLiveCollection(dayId)) { - runStructural(() => appendChild(dayId, null, "")); + // Lunora: insertChildAtStart is already a watermarked mutator; classic + // path keeps runStructural + appendChild (last-child when empty = same). + if (isLunoraSyncEnabled()) { + insertChildAtStart(getTreeIndex(), dayId, false, ""); + } else { + runStructural(() => appendChild(dayId, null, "")); + } } } @@ -174,10 +204,27 @@ async function materializeNewDay( if (claimed.some((c) => !c.won && !c.present)) resyncNodes(); const parentId = chain && week ? week.id : container.id; + + // ADR 0055: flag ON → one Lunora mutator for all node writes (kv claims + // already done above). Classic path keeps runStructuralTracked + applyBatch. + if (isLunoraSyncEnabled()) { + return materializeNewDayLunora({ + container, + day, + key, + seedEntryLine, + chain, + year, + month, + week, + parentId, + }); + } + const { persisted } = runStructuralTracked(() => { // Container: appended at the end of the top level (special, not sorted). if (!hasNode(container.id)) { - const tops = childrenOf(buildTreeIndex(nodesCollection.toArray), null); + const tops = childrenOf(buildTreeIndex(getLiveNodes()), null); const after = tops.length ? tops[tops.length - 1]!.id : null; appendChild(null, after, DAILY_CONTAINER_TEXT, container.id); } @@ -235,10 +282,132 @@ async function materializeNewDay( return { id: null, cause: null }; } +/** Lunora flag-ON materialize: plan inserts client-side (sorted afterIds), one + * `materializeDailyNodes` mutator, await watermark. Ids claimed via Lunora + * `claimDailyMapping` (daily-index bind) before this runs. */ +async function materializeNewDayLunora(args: { + container: { id: string; won: boolean; present: boolean }; + day: { id: string; won: boolean; present: boolean }; + key: string; + seedEntryLine: boolean; + chain: ReturnType; + year: { id: string; won: boolean; present: boolean } | null; + month: { id: string; won: boolean; present: boolean } | null; + week: { id: string; won: boolean; present: boolean } | null; + parentId: string; +}): Promise { + const lunora = getLunoraOutlineContext(); + if (!lunora) return { id: null, cause: null }; + + const t = Date.now(); + let working = lunora.store.collection.toArray.map(rowToNode); + const inserts: Array<{ + id: string; + parentId: string | null; + afterId: string | null; + text: string; + }> = []; + + const pushInsert = ( + id: string, + parentId: string | null, + afterId: string | null, + text: string, + ) => { + if (working.some((n) => n.id === id)) return; + const step = planInsertSibling(buildTreeIndex(working), { + id, + userId: lunora.userId, + parentId, + afterId, + text, + createdAt: t, + updatedAt: t, + }); + if (!step) return; + inserts.push({ id, parentId, afterId, text }); + working = applyPlan(working, step); + }; + + const pushSorted = ( + parentNodeId: string, + scaffoldKey: string, + text: string, + id: string, + ) => { + if (working.some((n) => n.id === id)) return; + const index = buildTreeIndex(working); + const siblings = childrenOf(index, parentNodeId).map((n) => ({ + id: n.id, + key: getKeyForNode(n.id), + })); + const afterId = sortedInsertAfterId(siblings, scaffoldKey); + pushInsert(id, parentNodeId, afterId, text); + }; + + if (!working.some((n) => n.id === args.container.id)) { + const tops = childrenOf(buildTreeIndex(working), null); + const after = tops.length ? tops[tops.length - 1]!.id : null; + pushInsert(args.container.id, null, after, DAILY_CONTAINER_TEXT); + } + + if (args.chain && args.year && args.month && args.week) { + pushSorted( + args.container.id, + args.chain.yearKey, + scaffoldLabel(args.chain.yearKey), + args.year.id, + ); + pushSorted( + args.year.id, + args.chain.monthKey, + scaffoldLabel(args.chain.monthKey), + args.month.id, + ); + pushSorted( + args.month.id, + args.chain.weekKey, + scaffoldLabel(args.chain.weekKey), + args.week.id, + ); + } + + pushSorted(args.parentId, args.key, formatDayText(args.key), args.day.id); + + // ADR 0041 seedEntryLine: empty child in the SAME mutator when asked. + if (args.seedEntryLine && !working.some((n) => n.parentId === args.day.id)) { + pushInsert(createId(), args.day.id, null, ""); + } + + if (inserts.length === 0) { + // Day already present after concurrent heal — treat as success. + return hasNode(args.day.id) + ? { id: args.day.id } + : { id: null, cause: null }; + } + + const tx = lunora.store.mutators.materializeDailyNodes({ + userId: lunora.userId, + inserts, + createdAt: t, + updatedAt: t, + }); + try { + await tx.isPersisted.promise; + } catch (err) { + return { id: null, cause: err }; + } + if (hasNode(args.day.id)) return { id: args.day.id }; + resyncNodes(); + return { id: null, cause: null }; +} + /** Does `parentId` have any child in the LIVE nodes collection? Used for the * reopen-seed check, which must not trust a possibly-stale tree index. */ function hasChildInLiveCollection(parentId: string): boolean { - return nodesCollection.toArray.some((n) => n.parentId === parentId); + const lunoraNodes = liveOutlineNodes(); + if (lunoraNodes) return lunoraNodes.some((n) => n.parentId === parentId); + return getLiveNodes().some((n) => n.parentId === parentId); } // --- one-time flat -> nested migration (issue #271, decision 8) -------------- @@ -272,7 +441,7 @@ let dailyMigration: Promise | null = null; async function ensureDailyMigrated(containerId: string): Promise { if (dailyMigration) return dailyMigration; const plan = planDailyMigration( - buildTreeIndex(nodesCollection.toArray), + buildTreeIndex(getLiveNodes()), containerId, getDailyRows(), getKeyForNode, @@ -296,7 +465,7 @@ function moveDaySorted( weekId: string, containerId: string, ): void { - const index = buildTreeIndex(nodesCollection.toArray); + const index = buildTreeIndex(getLiveNodes()); const day = index.byId.get(dayNodeId); if (!day) return; // deleted between plan and apply const dayKey = getKeyForNode(dayNodeId); @@ -379,7 +548,7 @@ async function runDailyMigration( // One undo point: snapshot the whole pre-migration tree, then apply. const captureStep = () => - capture(buildTreeIndex(nodesCollection.toArray), containerId); + capture(buildTreeIndex(getLiveNodes()), containerId); if (estimatedWrites < RESTORE_SLICE_OPS) { runStructural(() => { captureStep(); diff --git a/src/routes/__root.tsx b/src/routes/__root.tsx index 2448ded3..581bf11f 100644 --- a/src/routes/__root.tsx +++ b/src/routes/__root.tsx @@ -1,6 +1,9 @@ // Sentry init must run before any app code (#227). SPA mode has no client entry // file, so the root route module is the earliest reliable place. Keep first. import "../instrument.client"; +// Installs the VirtualKeyboard API (native on Chromium, polyfilled on Safari) so +// `--kb-inset` in styles.css resolves. Side-effect import, SSR-safe (ADR 0030). +import "../data/keyboard-inset"; import type { ReactNode } from "react"; import { @@ -15,6 +18,7 @@ import { AuthScreen } from "../components/auth-screen"; import { ChangelogDialog } from "../components/changelog-dialog"; import { DeleteConfirmDialog } from "../components/delete-confirm-dialog"; import { HistoryRestoreDialog } from "../components/history-restore"; +import { LunoraSyncHost } from "../components/lunora-sync-host"; import { MirrorPlaces } from "../components/mirror-places"; import { MoveDialog } from "../components/move-dialog"; import { NodeSwitcher } from "../components/node-switcher"; @@ -28,6 +32,7 @@ import { TextSizeProvider } from "../components/text-size-provider"; import { ThemeProvider } from "../components/theme-provider"; import { Toaster } from "../components/ui/sonner"; import { UpdateAvailableToast } from "../components/update-available"; +import { AccountPrefsController } from "../data/account-prefs"; import { hardReset, useSession } from "../lib/auth-client"; import { FAVICON_DARK, FAVICON_LIGHT } from "../lib/favicon"; import { @@ -145,29 +150,33 @@ function RootComponent() { ) : ( - - - - - {/* Registers openSettings() so the node-limit toast's "Upgrade" + + {/* ADR 0055: no-op when lunora-sync flag OFF (default). */} + + + + + + {/* Registers openSettings() so the node-limit toast's "Upgrade" action can SPA-navigate to /settings from non-React code. */} - - - - - - - - - - {/* A distinct mechanism from the changelog (ADR 0046): the + + + + + + + + + + {/* A distinct mechanism from the changelog (ADR 0046): the changelog says WHAT changed; this says THIS TAB is stale. */} - - {/* Inside the gate: surfaces a failed "Connect Google" round + + {/* Inside the gate: surfaces a failed "Connect Google" round trip (signed-in). Signed-out failures render inline in AuthScreen via the same consume helper. */} - - + + + )} diff --git a/src/routes/settings.tsx b/src/routes/settings.tsx index 2b781ab1..b0473c2b 100644 --- a/src/routes/settings.tsx +++ b/src/routes/settings.tsx @@ -23,6 +23,8 @@ import { openOpmlImport } from "../components/opml-import-opener"; import { useTextSize, type TextSize } from "../components/text-size-provider"; import { useTheme } from "../components/theme-provider"; import { Button } from "../components/ui/button"; +import { Switch } from "../components/ui/switch"; +import { setLunoraBetaEnabled, useLunoraBetaPref } from "../data/account-prefs"; import { localDateKey } from "../data/date-links"; import { downloadTextFile } from "../data/download"; import { outlineToMarkdown } from "../data/markdown"; @@ -736,6 +738,38 @@ function AppearanceSection() { ); } +function BetaSection() { + const { ready, enabled } = useLunoraBetaPref(); + return ( +
+ + + Try Dotflowy's next sync engine. Your outline stays yours — + we never claim your data. Opting in helps us harden it before + everyone gets it. May have rough edges; your choice syncs across + devices, and toggling reloads the app. + + } + action={ + void setLunoraBetaEnabled(checked)} + aria-label="Upgraded outline sync beta" + /> + } + /> + +
+ ); +} + function SettingsPage() { // One subscription fetch for the whole page; Plan & billing and the // Connections nudge both read it (no double request, no divergent state). @@ -774,6 +808,7 @@ function SettingsPage() { + diff --git a/src/styles.css b/src/styles.css index 9536569f..0acc9ef2 100644 --- a/src/styles.css +++ b/src/styles.css @@ -216,6 +216,14 @@ */ :root { --node-deco-budget: 200px; + + /* How far a bottom-pinned surface must lift to clear the software keyboard + (ADR 0030). `data/keyboard-inset.ts` overwrites this inline on from a + MEASURED anchor probe; this declaration is the default that holds when JS + hasn't run, no keyboard is up, or the device has no software keyboard. + Consumers read this one var rather than a React hook, so the keyboard + animation costs zero re-renders. */ + --kb-inset: 0px; } .node-deco { display: flex; diff --git a/vite.config.ts b/vite.config.ts index 07eda503..70300d0f 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -32,8 +32,21 @@ export default defineConfig({ // (`bun run dev:api` -> wrangler dev on :8787). This keeps Vite HMR for the // UI while the real /api/nodes path is served by the Worker against a local // D1. In production the same Worker serves both. See docs/adr/0008-sync-via-a-per-user-durable-object.md. + // `ws: true` is required — Vite's string shorthand only sets + // `{ target, changeOrigin }` and skips the upgrade listener, so + // `/api/sync` and `/_lunora/ws` never reach wrangler (outline stuck on + // "Loading outline"). See ADR 0055 dogfood hang. proxy: { - "/api": "http://localhost:8787", + "/api": { + target: "http://localhost:8787", + changeOrigin: true, + ws: true, + }, + "/_lunora": { + target: "http://localhost:8787", + changeOrigin: true, + ws: true, + }, }, }, plugins: [ @@ -77,6 +90,12 @@ export default defineConfig({ resolve: { alias: { "@": new URL("./src", import.meta.url).pathname, + // @lunora/react ships precompiled `jsxDEV` imports; Vite's prod React + // stub leaves jsxDEV undefined (LunoraProvider crash under cf:dev). + "react/jsx-dev-runtime": new URL( + "./scripts/react-jsx-dev-runtime-shim.ts", + import.meta.url, + ).pathname, }, }, }); diff --git a/worker/auth.ts b/worker/auth.ts index c5049c1e..cf1661fb 100644 --- a/worker/auth.ts +++ b/worker/auth.ts @@ -12,6 +12,8 @@ * Durable Object. */ +import type { ShardNamespaceLike } from "lunorash/runtime"; + import { stripe } from "@better-auth/stripe"; import { betterAuth } from "better-auth"; import { APIError, createAuthMiddleware } from "better-auth/api"; @@ -28,6 +30,7 @@ import { import { sendEmail } from "./email"; import { isSignupOpen, matchesSharedInviteCode } from "./identity"; import { isRedeemableInvite, normalizeEmail, redeemInvite } from "./invites"; +import { wipeLunoraUserShard } from "./lunora-mcp-store"; import { FOUNDING_SEAT_LIMIT, countFoundingSeats } from "./plan"; /** The slice of the Worker env Better Auth needs. */ @@ -74,6 +77,9 @@ export interface AuthEnv { * /api/nodes through, resolved here from the authenticated session's user.id * (never a client-supplied id; the DO trust boundary, ADR 0014). */ USER_OUTLINE: DurableObjectNamespace; + /** Lunora shard DO namespace (ADR 0055). Self-serve deletion wipes this + * alongside USER_OUTLINE — keyed by `user.id`, not resolveUserId. */ + SHARD: ShardNamespaceLike; /** The owner's Better Auth `user.id`. When set, that one account routes to the * constant 'default' DO (worker/index.ts resolveUserId); self-serve deletion * refuses it (docs/adr/0051). */ @@ -243,6 +249,10 @@ export function createAuth( env.USER_OUTLINE.idFromName(user.id), ); await stub.wipe(); + // Lunora shard (ADR 0055): same Better Auth user.id the browser/MCP + // mutators use — NOT resolveUserId / 'default'. Throws on RPC failure + // so deletion aborts before identity rows vanish (ADR 0051 posture). + await wipeLunoraUserShard(env, user.id); }, // afterDelete runs once the identity rows are gone. Better Auth's core // deletes user/session/account; the mcp OAuth rows and the email-keyed diff --git a/worker/index.ts b/worker/index.ts index 9bf790d6..1da90566 100644 --- a/worker/index.ts +++ b/worker/index.ts @@ -32,7 +32,6 @@ import { } from "better-auth/plugins"; import { Data, Effect, Schema } from "effect"; -import type { AuthEnv } from "./auth"; import type { Node } from "./wire"; import { @@ -63,6 +62,11 @@ import { pendingWaitlistEmails, type InviteBatchResult, } from "./invites"; +import { lunoraApp, ShardDO, type LunoraEnv } from "./lunora-app"; +import { + createLunoraOutlineStore, + isLunoraOutlineEnabledForUser, +} from "./lunora-mcp-store"; import { handleMcp, mcpCorsPreflight } from "./mcp"; import { UserOutlineDO as BaseUserOutlineDO } from "./outline-do"; import { FREE_NODE_LIMIT, getPlan, nodeLimitForPlan } from "./plan"; @@ -94,7 +98,12 @@ export const UserOutlineDO = Sentry.instrumentDurableObjectWithSentry( ); type UserOutlineDO = BaseUserOutlineDO; -interface Env extends AuthEnv { +// Lunora ShardDO (ADR 0055) — re-export for wrangler `SHARD` binding. +// TEMP: not Sentry-wrapped — Lunora's ShardDOState.sql typing doesn't satisfy +// Sentry's DurableObjectState constraint (document in HANDOFF). +export { ShardDO }; + +interface Env extends LunoraEnv { /** Public Sentry DSN (a wrangler.jsonc var, not a secret; it ships in the * client bundle too). Unset => error monitoring is dormant. See worker/ * sentry.ts (ticket #227, decided in #156). */ @@ -159,6 +168,7 @@ const KV_COLLECTIONS = new Set([ "daily-index", "changelog", "saved-queries", + "account-prefs", ]); /** @@ -962,10 +972,6 @@ function handleApiRequest( }, }); } - const mcpUserId = resolveUserId(token.userId, env); - const mcpStub = env.USER_OUTLINE.get( - env.USER_OUTLINE.idFromName(mcpUserId), - ); // Provenance: which agent is calling. The bearer token's OAuth client maps // to a registered harness name; every node its write tools create is // stamped with it, so the editor can mark agent edits apart from the user's. @@ -980,7 +986,18 @@ function handleApiRequest( // (handleMcp), not a 500. An operator comps themselves with a manual // subscription row (getPlan treats it as paid). const mcpPlan = yield* Effect.promise(() => getPlan(token.userId, env)); - return yield* handleMcp(request, mcpStub, origin, mcpPlan !== "free"); + const classicStub = env.USER_OUTLINE.get( + env.USER_OUTLINE.idFromName(resolveUserId(token.userId, env)), + ); + const useLunora = yield* Effect.promise(() => + isLunoraOutlineEnabledForUser(env, () => + classicStub.getKv("account-prefs"), + ), + ); + const mcpStore = useLunora + ? createLunoraOutlineStore(env, token.userId) + : classicStub; + return yield* handleMcp(request, mcpStore, origin, mcpPlan !== "free"); } // Identity = the validated session's stable user id. No session → 401. @@ -1127,6 +1144,13 @@ const handler = { ); } + // Lunora reserved paths (ADR 0055 Phase-2 compose). Product Better Auth + // stays on `/api/auth/*`; Lunora has no dual signup here — identity is + // bridged from the product session inside `worker/lunora-app.ts`. + if (url.pathname === "/_lunora" || url.pathname.startsWith("/_lunora/")) { + return lunoraApp.fetch(request, env, ctx); + } + // The static shell + assets are PUBLIC so the login screen can load. Serve // them without instantiating auth — only the data API (and the token-gated // `/mcp`, handled in the pipeline below) is gated. diff --git a/worker/lunora-app.ts b/worker/lunora-app.ts new file mode 100644 index 00000000..7d5dad4e --- /dev/null +++ b/worker/lunora-app.ts @@ -0,0 +1,105 @@ +/// + +/** + * Lunora outline plane composed beside the product Worker (ADR 0055 Phase 2). + * + * - No `@lunora/auth` / dual signup — product Better Auth stays session authority. + * - `resolveIdentity` bridges the existing Better Auth session into Lunora. + * - Product fetch routes `/_lunora/*` here; everything else stays on UserOutlineDO. + */ + +import type { ShardNamespaceLike } from "lunorash/runtime"; + +import type { AuthEnv } from "./auth"; + +import { defineApp } from "../lunora/_generated/app"; +import { createAuth } from "./auth"; + +export type LunoraEnv = AuthEnv & { + SHARD: ShardNamespaceLike; + /** Optional Studio / admin bearer (unset = admin routes stay closed). */ + LUNORA_ADMIN_TOKEN?: string; + /** + * Default ON when unset — browser + MCP share the Lunora SHARD. Set + * `"0"` / `"false"` / `"off"` to route MCP through classic UserOutlineDO. + */ + LUNORA_OUTLINE?: string; + /** + * Extra origins for Lunora CSRF/CORS (comma-separated). Vite `:3000` / + * e2e `:3210` are always included — see `lunoraTrustedOrigins`. + */ + LUNORA_TRUSTED_ORIGINS?: string; + /** Same comma-list as `.dev.vars.example` for Better Auth CSRF (optional). */ + BETTER_AUTH_TRUSTED_ORIGINS?: string; +}; + +// defineApp requires `Record`; AuthEnv is a closed interface. +type LunoraAppEnv = LunoraEnv & Record; + +/** + * Origins the SPA may use when talking to Lunora through the Vite/dev proxy. + * + * Lunora's CSRF guard compares `Origin` to `new URL(request.url).origin`. In + * `bun run dev`, the browser Origin is Vite (`:3000`) while the Worker URL + * (after `changeOrigin`) is wrangler (`:8787`) — without these trusted, cookie + * WS upgrades return `FORBIDDEN_ORIGIN` 403 and the outline never leaves + * "Loading outline". Mirrors Better Auth's `trustedOrigins` in `auth.ts`. + */ +function lunoraTrustedOrigins(env: LunoraEnv): string[] { + const fromEnv = [ + ...(env.LUNORA_TRUSTED_ORIGINS ?? "").split(","), + ...(env.BETTER_AUTH_TRUSTED_ORIGINS ?? "").split(","), + ] + .map((s) => s.trim()) + .filter(Boolean); + const fromBase = env.BETTER_AUTH_URL + ? (() => { + try { + return [new URL(env.BETTER_AUTH_URL).origin]; + } catch { + return []; + } + })() + : []; + return [ + ...new Set([ + "http://localhost:3000", + "http://localhost:3210", + ...fromBase, + ...fromEnv, + ]), + ]; +} + +const app = defineApp() + .shard((env) => env.SHARD) + .extend((env) => { + const trustedOrigins = lunoraTrustedOrigins(env); + return { + adminToken: env.LUNORA_ADMIN_TOKEN, + security: { + // CORS allowlist also feeds CSRF `isTrustedOrigin` (see @lunora/runtime). + cors: { + allowedOrigins: trustedOrigins, + allowCredentials: true, + }, + csrf: { trustedOrigins }, + }, + resolveIdentity: async (request) => { + const url = new URL(request.url); + const auth = createAuth(env, url.origin); + const session = await auth.api.getSession({ headers: request.headers }); + const userId = session?.user?.id; + if (!userId) return null; + return { + userId, + email: session.user.email ?? undefined, + }; + }, + authorizeShard: (identity, shardKey) => identity?.userId === shardKey, + }; + }) + .build(); + +export const ShardDO = app.ShardDO; +export const lunoraApp = app; diff --git a/worker/lunora-mcp-bridge.test.ts b/worker/lunora-mcp-bridge.test.ts new file mode 100644 index 00000000..8561a838 --- /dev/null +++ b/worker/lunora-mcp-bridge.test.ts @@ -0,0 +1,24 @@ +/** + * Pure wiring: outline-ops ChangeOp batch → Lunora OutlinePlan + * (mcp:applyChangeOps input). Full shard RPC stays integration-only. + */ + +import { describe, expect, test } from "bun:test"; + +import { planFromChangeOps } from "../src/data/outline-plans"; +import { makeNode } from "../src/data/tree"; + +describe("MCP → Lunora applyChangeOps plan", () => { + test("planner batch becomes inserts/patches/deletes", () => { + const a = makeNode({ id: "a", text: "alpha" }); + const plan = planFromChangeOps("user-1", [ + { op: "insert", value: a }, + { op: "update", value: { ...a, text: "ALPHA" } }, + { op: "delete", key: "z" }, + ]); + expect(plan.inserts[0]!.userId).toBe("user-1"); + expect(plan.inserts[0]!.text).toBe("alpha"); + expect(plan.patches[0]!.fields.text).toBe("ALPHA"); + expect(plan.deletes).toEqual(["z"]); + }); +}); diff --git a/worker/lunora-mcp-store.test.ts b/worker/lunora-mcp-store.test.ts new file mode 100644 index 00000000..34789c6a --- /dev/null +++ b/worker/lunora-mcp-store.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, test } from "bun:test"; + +import { + decodeClaimDailyResult, + decodeDailyClaimValue, + decodeDailyIndexRows, + decodeMcpNodeList, + decodeShardRpcEnvelope, + isLunoraOutlineEnabledForUser, + isLunoraOutlineEnabledSync, + parseLunoraBetaPref, + resolveLunoraOutlineEnvForce, +} from "./lunora-mcp-store"; + +describe("resolveLunoraOutlineEnvForce", () => { + test("unset returns null", () => { + expect(resolveLunoraOutlineEnvForce({})).toBe(null); + expect(resolveLunoraOutlineEnvForce({ LUNORA_OUTLINE: "" })).toBe(null); + }); + + test("explicit on values force ON", () => { + expect(resolveLunoraOutlineEnvForce({ LUNORA_OUTLINE: "1" })).toBe(true); + expect(resolveLunoraOutlineEnvForce({ LUNORA_OUTLINE: "true" })).toBe(true); + expect(resolveLunoraOutlineEnvForce({ LUNORA_OUTLINE: "on" })).toBe(true); + }); + + test("explicit off values force OFF", () => { + expect(resolveLunoraOutlineEnvForce({ LUNORA_OUTLINE: "0" })).toBe(false); + expect(resolveLunoraOutlineEnvForce({ LUNORA_OUTLINE: "false" })).toBe( + false, + ); + expect(resolveLunoraOutlineEnvForce({ LUNORA_OUTLINE: "off" })).toBe(false); + }); +}); + +describe("parseLunoraBetaPref", () => { + test("missing or disabled rows → false", () => { + expect(parseLunoraBetaPref([])).toBe(false); + expect(parseLunoraBetaPref([{ id: "lunora-beta", enabled: false }])).toBe( + false, + ); + expect(parseLunoraBetaPref([{ id: "other", enabled: true }])).toBe(false); + }); + + test("enabled row → true", () => { + expect(parseLunoraBetaPref([{ id: "lunora-beta", enabled: true }])).toBe( + true, + ); + }); +}); + +describe("isLunoraOutlineEnabledSync", () => { + test("unset env → false (classic default)", () => { + expect(isLunoraOutlineEnabledSync({})).toBe(false); + }); + + test("respects env force", () => { + expect(isLunoraOutlineEnabledSync({ LUNORA_OUTLINE: "1" })).toBe(true); + expect(isLunoraOutlineEnabledSync({ LUNORA_OUTLINE: "0" })).toBe(false); + }); +}); + +describe("isLunoraOutlineEnabledForUser", () => { + test("env force on skips preference lookup", async () => { + let called = false; + expect( + await isLunoraOutlineEnabledForUser({ LUNORA_OUTLINE: "1" }, async () => { + called = true; + return []; + }), + ).toBe(true); + expect(called).toBe(false); + }); + + test("env force off skips preference lookup", async () => { + let called = false; + expect( + await isLunoraOutlineEnabledForUser({ LUNORA_OUTLINE: "0" }, async () => { + called = true; + return [{ id: "lunora-beta", enabled: true }]; + }), + ).toBe(false); + expect(called).toBe(false); + }); + + test("unset env uses account pref", async () => { + expect( + await isLunoraOutlineEnabledForUser({}, async () => [ + { id: "lunora-beta", enabled: true }, + ]), + ).toBe(true); + expect(await isLunoraOutlineEnabledForUser({}, async () => [])).toBe(false); + }); +}); + +describe("shard RPC decode (Worker→Lunora trust boundary)", () => { + test("decodeShardRpcEnvelope accepts ok + error shapes", () => { + expect(decodeShardRpcEnvelope({ result: 1 })).toEqual({ result: 1 }); + expect(decodeShardRpcEnvelope({ error: { message: "nope" } })).toEqual({ + error: { message: "nope" }, + }); + }); + + test("decodeShardRpcEnvelope rejects garbage", () => { + expect(() => decodeShardRpcEnvelope("nope")).toThrow(); + }); + + test("decodeMcpNodeList validates wire nodes", () => { + const node = { + id: "n1", + parentId: null, + prevSiblingId: null, + text: "hi", + isTask: false, + completed: false, + collapsed: false, + bookmarkedAt: null, + mirrorOf: null, + createdAt: 1, + updatedAt: 1, + origin: null, + kind: null, + }; + expect(decodeMcpNodeList([node])).toEqual([node]); + expect(() => decodeMcpNodeList([{ id: "x" }])).toThrow(); + }); + + test("decodeDailyIndexRows + claim helpers", () => { + expect(decodeDailyIndexRows([{ key: "k", nodeId: "n" }])).toEqual([ + { key: "k", nodeId: "n" }, + ]); + expect(decodeClaimDailyResult({ nodeId: "n" })).toEqual({ nodeId: "n" }); + expect(decodeDailyClaimValue({ nodeId: "n" })).toEqual({ nodeId: "n" }); + expect(() => decodeDailyClaimValue({})).toThrow(); + }); +}); diff --git a/worker/lunora-mcp-store.ts b/worker/lunora-mcp-store.ts new file mode 100644 index 00000000..3964e23e --- /dev/null +++ b/worker/lunora-mcp-store.ts @@ -0,0 +1,242 @@ +/// + +/** + * MCP OutlineStore backed by the Lunora SHARD (ADR 0055). + * + * When `LUNORA_OUTLINE=1`, Worker MCP tools keep planning via outline-ops + * (`ChangeOp[]`) but commit through `mutators:applyChangeOps` on the same + * user shard the browser mutators use — not classic UserOutlineDO.applyBatch. + * + * Identity is Worker-trusted: the MCP bearer was already validated; we forward + * `x-lunora-userid` (+ system) to the shard the same way Lunora's compose + * forwards authenticated RPCs. + */ + +import { Schema } from "effect"; +import { resolveShard, type ShardNamespaceLike } from "lunorash/runtime"; + +import type { OutlineStore } from "./mcp-tools"; + +import { NodeSchema, type ChangeOp, type Node } from "../src/data/wire-schema"; + +type LunoraRpcEnv = { + SHARD: ShardNamespaceLike; +}; + +const RpcEnvelopeSchema = Schema.Struct({ + result: Schema.optional(Schema.Unknown), + error: Schema.optional( + Schema.Struct({ + message: Schema.optional(Schema.String), + }), + ), +}); + +const DailyIndexRowSchema = Schema.Struct({ + key: Schema.String, + nodeId: Schema.String, +}); + +const ClaimDailyResultSchema = Schema.Struct({ + nodeId: Schema.String, +}); + +const DailyClaimValueSchema = Schema.Struct({ + nodeId: Schema.String, +}); + +/** Decode unknown JSON at the Worker→shard trust boundary (ADR 0014 twin). */ +export function decodeShardRpcEnvelope(raw: unknown): { + result?: unknown; + error?: { message?: string }; +} { + return Schema.decodeUnknownSync(RpcEnvelopeSchema)(raw); +} + +export function decodeMcpNodeList(raw: unknown): Node[] { + return [...Schema.decodeUnknownSync(Schema.Array(NodeSchema))(raw ?? [])]; +} + +export function decodeDailyIndexRows( + raw: unknown, +): Array<{ key: string; nodeId: string }> { + return [ + ...Schema.decodeUnknownSync(Schema.Array(DailyIndexRowSchema))(raw ?? []), + ]; +} + +export function decodeClaimDailyResult(raw: unknown): { nodeId: string } { + return Schema.decodeUnknownSync(ClaimDailyResultSchema)(raw); +} + +export function decodeDailyClaimValue(raw: unknown): { nodeId: string } { + return Schema.decodeUnknownSync(DailyClaimValueSchema)(raw); +} + +async function shardRpc( + env: LunoraRpcEnv, + userId: string, + functionPath: string, + args: Record, +): Promise { + const stub = resolveShard(env.SHARD, userId); + const res = await stub.fetch( + new Request("https://shard.internal/rpc", { + method: "POST", + headers: { + "content-type": "application/json", + "x-lunora-userid": userId, + // Trusted Worker→shard dispatch (same as compose cron/forward). + "x-lunora-system": "1", + }, + body: JSON.stringify({ functionPath, args }), + }), + ); + let json: unknown; + try { + json = await res.json(); + } catch { + throw new Error( + `lunora shard rpc ${functionPath}: non-JSON response (${res.status})`, + ); + } + let envelope: { result?: unknown; error?: { message?: string } }; + try { + envelope = decodeShardRpcEnvelope(json); + } catch (err) { + // Failed HTTP with a non-envelope body → status error, not a Schema dump. + if (!res.ok) { + throw new Error( + `lunora shard rpc ${functionPath} failed (${res.status})`, + ); + } + throw err instanceof Error + ? err + : new Error(`lunora shard rpc ${functionPath}: invalid response`); + } + if (!res.ok || envelope.error) { + throw new Error( + envelope.error?.message ?? + `lunora shard rpc ${functionPath} failed (${res.status})`, + ); + } + return envelope.result; +} + +/** + * OutlineStore that reads/writes the Lunora shard for `userId`. + * `userId` is the Better Auth id (shard key) — not resolveUserId('default'). + */ +export function createLunoraOutlineStore( + env: LunoraRpcEnv, + userId: string, +): OutlineStore { + return { + async getNodes() { + const raw = await shardRpc(env, userId, "mcp:listNodes", { userId }); + return decodeMcpNodeList(raw); + }, + + async applyBatch(ops: readonly ChangeOp[]) { + if (ops.length === 0) return 0; + await shardRpc(env, userId, "mcp:applyChangeOps", { + userId, + ops, + }); + // Classic DO returns a seq; Lunora watermarks are internal. Tools ignore + // the numeric return (commit() awaits applyBatch for side effects only). + return ops.length; + }, + + async getKv(collection: string) { + if (collection !== "daily-index") return []; + const raw = await shardRpc(env, userId, "mcp:listDailyIndex", { + userId, + }); + return decodeDailyIndexRows(raw); + }, + + async getOrCreateKv(collection: string, key: string, value: unknown) { + if (collection !== "daily-index") { + throw new Error( + `lunora mcp store: unsupported kv collection ${collection}`, + ); + } + let candidate: string; + try { + candidate = decodeDailyClaimValue(value).nodeId; + } catch { + throw new Error("lunora mcp store: daily claim needs { nodeId }"); + } + const raw = await shardRpc(env, userId, "mutators:claimDailyMapping", { + userId, + key, + nodeId: candidate, + touchedAt: Date.now(), + }); + const result = decodeClaimDailyResult(raw); + return { key, nodeId: result.nodeId }; + }, + }; +} + +export type LunoraOutlineEnv = { LUNORA_OUTLINE?: string }; + +export const LUNORA_BETA_PREF_ID = "lunora-beta"; + +/** Env force: ON, OFF, or unset (use synced account preference). */ +export function resolveLunoraOutlineEnvForce( + env: LunoraOutlineEnv, +): boolean | null { + const raw = env.LUNORA_OUTLINE?.trim().toLowerCase(); + if (!raw) return null; + if (raw === "0" || raw === "false" || raw === "off") return false; + if (raw === "1" || raw === "true" || raw === "on") return true; + return false; +} + +/** Parse synced `account-prefs` rows for Lunora beta opt-in. */ +export function parseLunoraBetaPref(rows: unknown[]): boolean { + const row = rows.find( + (r) => + r && + typeof r === "object" && + (r as { id?: string }).id === LUNORA_BETA_PREF_ID, + ) as { enabled?: unknown } | undefined; + return row?.enabled === true; +} + +/** + * Sync helper: env force only. Unset env → false (classic DO default). + * MCP uses {@link isLunoraOutlineEnabledForUser} for preference lookup. + */ +export function isLunoraOutlineEnabledSync(env: LunoraOutlineEnv): boolean { + const forced = resolveLunoraOutlineEnvForce(env); + if (forced !== null) return forced; + return false; +} + +/** + * Whether Worker MCP should use the Lunora shard for this user. + * + * Kill-switch pairing (ADR 0055): env force first; else synced + * `account-prefs` on classic DO; browser reads mirrored localStorage after + * {@link AccountPrefsController} sync. + */ +export async function isLunoraOutlineEnabledForUser( + env: LunoraOutlineEnv, + getAccountPrefs: () => Promise, +): Promise { + const forced = resolveLunoraOutlineEnvForce(env); + if (forced !== null) return forced; + const rows = await getAccountPrefs(); + return parseLunoraBetaPref(rows); +} + +/** Permanently erase this user's Lunora shard — account deletion (ADR 0051). */ +export async function wipeLunoraUserShard( + env: LunoraRpcEnv, + userId: string, +): Promise { + await shardRpc(env, userId, "mcp:wipeUserShard", { userId }); +} diff --git a/wrangler.jsonc b/wrangler.jsonc index 28d79e11..0e1752ac 100644 --- a/wrangler.jsonc +++ b/wrangler.jsonc @@ -88,11 +88,20 @@ // One Durable Object per user: USER_OUTLINE holds the user's whole outline + // side-collections in colocated SQLite. The Worker routes each /api request to // the caller's DO. See docs/adr/0008-sync-via-a-per-user-durable-object.md. + // + // SHARD = Lunora outline plane (ADR 0055 Phase-2 compose). Lives beside + // USER_OUTLINE until the collection cutover deletes the custom DO sync. "durable_objects": { - "bindings": [{ "name": "USER_OUTLINE", "class_name": "UserOutlineDO" }], + "bindings": [ + { "name": "USER_OUTLINE", "class_name": "UserOutlineDO" }, + { "name": "SHARD", "class_name": "ShardDO" }, + ], }, // SQLite-backed DO storage requires `new_sqlite_classes` (not new_classes). - "migrations": [{ "tag": "v1", "new_sqlite_classes": ["UserOutlineDO"] }], + "migrations": [ + { "tag": "v1", "new_sqlite_classes": ["UserOutlineDO"] }, + { "tag": "v2", "new_sqlite_classes": ["ShardDO"] }, + ], // Off-site outline backups (#221): the daily cron sweep exports every user // DO's snapshot into this bucket (`backups//.json`). // Create the bucket + its lifecycle expiry once before the first deploy —