foldkit-plus 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ export * from "foldkit-form-recipes/file";
@@ -0,0 +1,2 @@
1
+ export * from "foldkit-form-recipes/file";
2
+ export {};
@@ -0,0 +1 @@
1
+ export * from "foldkit-host";
package/dist/host.mjs ADDED
@@ -0,0 +1,2 @@
1
+ export * from "foldkit-host";
2
+ export {};
@@ -0,0 +1 @@
1
+ export * from "foldkit-mixins/vite";
@@ -0,0 +1,2 @@
1
+ export * from "foldkit-mixins/vite";
2
+ export {};
@@ -0,0 +1 @@
1
+ export * from "foldkit-remote-drizzle/pg";
@@ -0,0 +1,2 @@
1
+ export * from "foldkit-remote-drizzle/pg";
2
+ export {};
@@ -1 +1 @@
1
- {"version":3,"file":"setup.d.mts","names":[],"sources":["../src/setup.ts"],"mappings":";YAOY;;iBAGK;WACN;;WAEA,UAAU,SAAS;;WAEnB;;WAEA,cAAc;;WAEd,QAAQ;;;iBAIF;WACN;WACA;;;;;;iBAOM;WACN;WACA;WACA;;iBAGM;WACN,SAAS,OAAO,OAAO;WACvB,SAAS;WACT,UAAU;;;;;;;;qBAYR;;qBAMA,MAAM;WACR;WACA,SAAS;WACT;;;;;;;;;qBA+GE,UAAU;WACZ;WACA,WAAW;WACX;;;;;;;;;;qBAoDE,gBAAgB;;;;;;;;qBAkBhB,gBAAa,gBAAkB,QAAU;;;;;qBAqFzC,aAAU,SACZ,SAAO,UACN,uBAAqB;qBA8BpB,eAAU,SAAA,SAAA,YAAoC"}
1
+ {"version":3,"file":"setup.d.mts","names":[],"sources":["../src/setup.ts"],"mappings":";YAOY;;iBAGK;WACN;;WAEA,UAAU,SAAS;;WAEnB;;WAEA,cAAc;;WAEd,QAAQ;;;iBAIF;WACN;WACA;;;;;;iBAOM;WACN;WACA;WACA;;iBAGM;WACN,SAAS,OAAO,OAAO;WACvB,SAAS;WACT,UAAU;;;;;;;;qBAYR;;qBAMA,MAAM;WACR;WACA,SAAS;WACT;;;;;;;;;qBAmHE,UAAU;WACZ;WACA,WAAW;WACX;;;;;;;;;;qBAoDE,gBAAgB;;;;;;;;qBAkBhB,gBAAa,gBAAkB,QAAU;;;;;qBAqFzC,aAAU,SACZ,SAAO,UACN,uBAAqB;qBA8BpB,eAAU,SAAA,SAAA,YAAoC"}
package/dist/setup.mjs CHANGED
@@ -122,8 +122,8 @@ const jobs = [
122
122
  guide: "richtext"
123
123
  },
124
124
  {
125
- job: "Server rendering that hands the Model over",
126
- imports: ["ssr"],
125
+ job: "Server rendering that hands the Model over, and the server handler around it",
126
+ imports: ["ssr", "host"],
127
127
  guide: "ssr"
128
128
  },
129
129
  {
@@ -1 +1 @@
1
- {"version":3,"file":"setup.mjs","names":[],"sources":["../src/setup.ts"],"sourcesContent":["/**\n * What `npx foldkit-plus setup` prints: instructions a coding agent can follow\n * in order, for the project it is run in. Pure: the CLI reads the project and\n * this package's manifest and passes them in, so a test can give any project.\n */\nimport { Option } from 'effect'\n\nexport type Manager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\n/** What the project's `package.json` says about the libraries Foldkit Plus needs. */\nexport interface Project {\n readonly name: string\n /** Each named library's version range, from any dependency field. */\n readonly versions: Readonly<Record<string, string>>\n /** Whether a `.gitattributes` applies here: in the project's folder or one above it in its repository. */\n readonly gitattributes: boolean\n /** Where pnpm reads this project's settings, which a workspace keeps at its root. */\n readonly pnpmSettings: PnpmSettings\n /** The versions of Effect's packages (`effectPackages`) its npm lockfile holds, nested copies included. */\n readonly locked: ReadonlyArray<string>\n}\n\n/** A file pnpm reads settings from, in `folder` relative to the project (`.`, `../..`). */\nexport interface PnpmSettings {\n readonly folder: string\n readonly file: 'package.json' | 'pnpm-workspace.yaml'\n}\n\n/**\n * The versions this release is built and tested against, from its own\n * manifest: the workspace's Foldkit and Effect.\n */\nexport interface Versions {\n readonly plus: string\n readonly effect: string\n readonly foldkit: string\n}\n\nexport interface SetupInput {\n readonly project: Option.Option<Project>\n readonly manager: Manager\n readonly versions: Versions\n}\n\nconst SITE = 'https://foldkit-plus.pages.dev'\nconst REPOSITORY = 'https://github.com/doeixd/foldkit-plus'\n\n/**\n * The `create-foldkit-app` release whose templates pin the Foldkit this\n * release needs (0.41.0 installs `foldkit`, `@foldkit/ui` and `@foldkit/devtools`\n * 0.170.0, `@foldkit/vite-plugin` 0.29.0 and `effect` 4.1.0). A release that\n * moves the `foldkit` peer moves this with it.\n */\nexport const SCAFFOLDER = 'create-foldkit-app@0.41.0'\n\nconst GREENFIELD = `${REPOSITORY}/blob/main/skills/foldkit-plus/references/greenfield.md`\nconst AGENTS_BLOCK = `${REPOSITORY}/blob/main/skills/foldkit-plus/references/agents-md.md`\n\n/** What each job needs, where to import it from, and where it is explained. */\nexport const jobs: ReadonlyArray<{\n readonly job: string\n readonly imports: ReadonlyArray<string>\n readonly guide: string\n}> = [\n {\n job: 'Name what a feature may read and which Messages it may send',\n imports: ['surface', 'metadata'],\n guide: 'surface',\n },\n {\n job: 'A reusable Submodel placed several times, every part wired',\n imports: ['bundle', 'bundle-surface'],\n guide: 'bundle',\n },\n {\n job: 'Restyle or extend views from outside, through typed slots',\n imports: ['mixins', 'mixins-surface', 'mixins-ui'],\n guide: 'mixins',\n },\n {\n job: 'Media queries, timers, sockets, clipboard, undo history',\n imports: ['primitives'],\n guide: 'primitives',\n },\n {\n job: 'Declare the domain once: entities, relations, queries',\n imports: ['entity'],\n guide: 'entity',\n },\n {\n job: 'Server-owned data in the Model: queries, mutations, live updates',\n imports: ['remote', 'remote-server', 'remote-drizzle'],\n guide: 'remote',\n },\n {\n job: 'Edits that survive offline and converge across devices',\n imports: ['sync', 'durable'],\n guide: 'sync',\n },\n { job: 'Who may do what, enforced on every seam', imports: ['guard'], guide: 'guard' },\n {\n job: 'Who is signed in: a Yielded Auth session as the principal',\n imports: ['auth'],\n guide: 'auth',\n },\n {\n job: 'A slice of the Model kept in the URL or in storage',\n imports: ['mirror'],\n guide: 'mirror',\n },\n {\n job: 'Forms: drafts, validation, a decoded value, and dates, times and addresses in them',\n imports: ['form', 'mixins-form', 'form-recipes'],\n guide: 'form',\n },\n {\n job: 'Edit, create and list screens over Remote',\n imports: ['crud', 'mixins-crud'],\n guide: 'crud',\n },\n {\n job: 'An interactive data grid over rows you own',\n imports: ['data-grid', 'mixins-data-grid'],\n guide: 'data-grid',\n },\n {\n job: 'Drafts, revisions and publishing for content',\n imports: ['cms', 'cms-drizzle'],\n guide: 'cms',\n },\n {\n job: 'Pages as data, and a builder that edits them',\n imports: ['composition', 'builder', 'mixins-builder'],\n guide: 'composition',\n },\n {\n job: 'Rich text: the document, its editor, Markdown and code',\n imports: [\n 'richtext',\n 'richtext-dom',\n 'mixins-richtext',\n 'richtext-markdown',\n 'richtext-code',\n 'richtext-code-shiki',\n ],\n guide: 'richtext',\n },\n { job: 'Server rendering that hands the Model over', imports: ['ssr'], guide: 'ssr' },\n {\n job: 'Responsive images, their variants and placeholders, and icons as data',\n imports: ['media'],\n guide: 'media',\n },\n { job: 'Route topology as data: nodes, typed targets, titles', imports: ['site'], guide: 'site' },\n {\n job: 'What an AI agent may see and do, over MCP, WebMCP, A2A or Agent Native',\n imports: ['agent', 'agent-mcp', 'agent-webmcp', 'agent-a2a', 'agent-native'],\n guide: 'agent',\n },\n {\n job: 'React components in a Foldkit view, or Foldkit inside React',\n imports: ['react', 'react-codegen'],\n guide: 'react',\n },\n]\n\n/**\n * The packages `foldkit-plus` does not install, since each needs a library of\n * its own, and that library at the range the adapter peers on: a manager\n * given a bare name installs the `latest` tag, which for `@yielded/auth` is a\n * beta older than the one `foldkit-auth` names. `test/generated.test.ts`\n * holds this to the manifests.\n */\nexport const adapters: ReadonlyArray<{\n readonly name: string\n readonly libraries: ReadonlyArray<string>\n readonly when: string\n}> = [\n {\n name: 'foldkit-agent-native',\n libraries: ['@agent-native/core@0.214.0'],\n when: 'agents through Agent Native',\n },\n {\n name: 'foldkit-auth',\n libraries: ['@yielded/auth@0.1.0-beta.47'],\n when: 'sign-in and sessions with Yielded Auth',\n },\n {\n name: 'foldkit-cms-drizzle',\n libraries: ['drizzle-orm@1.0.0-rc.5'],\n when: \"the CMS's server on Drizzle\",\n },\n {\n name: 'foldkit-mixins-ui',\n libraries: ['@foldkit/ui@^0.170.0'],\n when: 'styling `@foldkit/ui` components through slots',\n },\n {\n name: 'foldkit-react',\n libraries: ['react@^19.0.0', 'react-dom@^19.0.0'],\n when: 'React interop',\n },\n {\n name: 'foldkit-react-codegen',\n libraries: ['typescript@>=5.7.2 <7'],\n when: 'compiling Foldkit views to React TSX (a dev dependency)',\n },\n {\n name: 'foldkit-remote-drizzle',\n libraries: ['drizzle-orm@1.0.0-rc.5'],\n when: 'answering Remote reads with Drizzle',\n },\n {\n name: 'foldkit-richtext-code-shiki',\n libraries: ['shiki@^4.4.3'],\n when: 'highlighting code blocks with Shiki',\n },\n]\n\n/**\n * The Effect packages an application meets that something names at a version\n * of its own: Foldkit's peers and its Vite plugin's dependencies name one\n * minor (`~4.1.0`), and each `@effect/*` package peers on an `effect` at least\n * its own version. Setup holds all of them at the Effect this release is\n * tested on, as `pnpm-workspace.yaml` does here (`test/generated.test.ts`\n * keeps the two lists together).\n */\nexport const effectPackages: ReadonlyArray<string> = [\n 'effect',\n '@effect/platform-browser',\n '@effect/platform-node',\n '@effect/platform-node-shared',\n '@effect/sql-sqlite-node',\n]\n\nconst releaseOf = (version: string) =>\n /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version)?.slice(1).map(Number) ?? []\n\n/**\n * The Effect release setup pins: the one this release is tested on, or a later\n * patch of the same minor that the project's lockfile already holds. npm keeps\n * a locked package that an override contradicts rather than move it down, so\n * pinning 4.1.0 left the 4.1.1 that `@foldkit/vite-plugin`'s `~4.1.0` had\n * locked under it, which `npm ls` calls invalid.\n */\nexport const effectRelease = (tested: string, locked: ReadonlyArray<string>): string => {\n const [major, minor] = releaseOf(tested)\n return locked.reduce((newest, version) => {\n const [lockedMajor, lockedMinor, patch = -1] = releaseOf(version)\n return lockedMajor === major && lockedMinor === minor && patch > (releaseOf(newest)[2] ?? -1)\n ? version\n : newest\n }, tested)\n}\n\n/** Where the pins go, and the block that holds them. */\ninterface Pins {\n /** The file, as the step names it: `package.json`, `../../pnpm-workspace.yaml`. */\n readonly file: string\n readonly language: 'json' | 'yaml'\n readonly text: string\n}\n\n/** A YAML key, quoted where `@` would start something else. */\nconst yamlKey = (key: string) => (key.startsWith('@') ? `'${key}'` : key)\n\n/**\n * The settings that hold every Effect package at `effect`, to merge into the\n * file the manager reads them from. npm applies an override to a package the\n * project depends on only where the project names that same version, so its\n * block sets those dependencies too (a `$name` reference would follow them,\n * but npm 10 cannot resolve a scoped one); pnpm reads them only at a\n * workspace's root.\n */\nconst pinsOf = (\n manager: Manager,\n effect: string,\n direct: ReadonlySet<string>,\n pnpmSettings: PnpmSettings,\n): Pins => {\n const pins = Object.fromEntries(effectPackages.map(name => [name, effect]))\n const allowedVersions = { effect, '@effect/platform-browser': effect }\n if (manager === 'pnpm' && pnpmSettings.file === 'pnpm-workspace.yaml') {\n const lines = (entries: Readonly<Record<string, string>>, indent: string) =>\n Object.entries(entries).map(([name, version]) => `${indent}${yamlKey(name)}: ${version}`)\n return {\n file: `${pnpmSettings.folder}/pnpm-workspace.yaml`,\n language: 'yaml',\n text: [\n 'overrides:',\n ...lines(pins, ' '),\n 'peerDependencyRules:',\n ' allowedVersions:',\n ...lines(allowedVersions, ' '),\n ].join('\\n'),\n }\n }\n const fields = {\n npm: {\n dependencies: Object.fromEntries(\n effectPackages.filter(name => direct.has(name)).map(name => [name, effect]),\n ),\n overrides: pins,\n },\n pnpm: { pnpm: { overrides: pins, peerDependencyRules: { allowedVersions } } },\n yarn: { resolutions: pins },\n bun: { overrides: pins },\n }[manager]\n return {\n file:\n manager === 'pnpm' && pnpmSettings.folder !== '.'\n ? `${pnpmSettings.folder}/package.json`\n : 'package.json',\n language: 'json',\n text: JSON.stringify(fields, null, 2),\n }\n}\n\n/** Why `manager` needs the pins, after \"first merge this into `package.json`\". */\nconst pinsWhy: Readonly<Record<Manager, string>> = {\n npm: 'npm refuses a peer it does not match, and `overrides` lets one in without turning every peer check off; it overrides a dependency of the project only at the version the project names, so the block sets those too',\n pnpm: \"`overrides` sets the version, and `peerDependencyRules` lets Foldkit's exact peers accept it\",\n yarn: \"`resolutions` sets the version; Yarn warns of Foldkit's exact peers, and installs\",\n bun: \"`overrides` sets the version; Bun warns of Foldkit's exact peers, and installs\",\n}\n\n/**\n * The command that adds `packages` with `manager`, at exactly the versions\n * named when `exact`. A range a shell would read (`^`, `>`, a space) is quoted.\n */\nexport const addCommand = (\n manager: Manager,\n packages: ReadonlyArray<string>,\n exact = false,\n): string =>\n [\n manager,\n manager === 'npm' ? 'install' : 'add',\n ...(exact ? [manager === 'npm' || manager === 'pnpm' ? '--save-exact' : '--exact'] : []),\n ...packages.map(spec => (/^[\\w@/.-]+$/.test(spec) ? spec : `\"${spec}\"`)),\n ].join(' ')\n\n/** The major version a range asks for: `^4.0.0`, `~4.1`, `4.0.0-beta.1` all ask for 4. */\nconst majorOf = (range: string): Option.Option<number> =>\n Option.fromNullishOr(/(\\d+)/.exec(range)?.[1]).pipe(Option.map(Number))\n\n/** What the project has of a library against what this release needs, as a line to act on. */\nconst finding = (project: Project, library: string, wanted: string): string =>\n Option.match(Option.fromNullishOr(project.versions[library]), {\n onNone: () => `- \\`${library}\\` is not installed: step 2 adds \\`${library}@${wanted}\\`.`,\n onSome: range => {\n // Foldkit is 0.x, where a minor version breaks; Effect is past 1.\n const matches =\n library === 'foldkit'\n ? range.replace(/^[\\^~=v]*/, '').startsWith(wanted.split('.').slice(0, 2).join('.'))\n : Option.getOrUndefined(majorOf(range)) === Option.getOrUndefined(majorOf(wanted))\n return matches\n ? `- \\`${library}\\` ${range}: fits.`\n : `- \\`${library}\\` is ${range}, and Foldkit Plus needs ${wanted}: step 2 moves it to ${wanted}. Check the application builds after.`\n },\n })\n\nexport const setupGuide = ({ project, manager, versions }: SetupInput): string => {\n // Every Effect package the project names moves with `effect`, so the pins hold.\n const listed = Option.match(project, {\n onNone: () => [],\n onSome: found => effectPackages.filter(name => found.versions[name] !== undefined),\n })\n const moved = new Set(['effect', '@effect/platform-browser', ...listed])\n const effect = effectRelease(\n versions.effect,\n Option.match(project, { onNone: () => [], onSome: found => found.locked }),\n )\n const pins = pinsOf(\n manager,\n effect,\n moved,\n Option.match(project, {\n onNone: () => ({ folder: '.', file: 'package.json' }),\n onSome: found => found.pnpmSettings,\n }),\n )\n // Foldkit's devtools peer on `@foldkit/ui` at any release, and a manager left\n // to pick one takes the newest, which may peer on a newer Effect (#229).\n const uiPeer = Option.exists(\n project,\n found =>\n found.versions['@foldkit/devtools'] !== undefined &&\n found.versions['@foldkit/ui'] === undefined,\n )\n // npm's block already names the Effect packages the project depends on.\n const install = addCommand(\n manager,\n [\n ...(manager === 'npm'\n ? []\n : effectPackages.filter(name => moved.has(name)).map(name => `${name}@${effect}`)),\n `foldkit@${versions.foldkit}`,\n ...(uiPeer ? [`@foldkit/ui@${versions.foldkit}`] : []),\n 'foldkit-plus',\n ],\n true,\n )\n const check = Option.match(project, {\n onNone: () => [\n 'There is no `package.json` here: this is a new application. Do not scaffold yet. Follow the greenfield guide, which asks the user about the goals, the look and the domain before any code:',\n '',\n `- ${GREENFIELD} (in the skill of step 3, \\`references/greenfield.md\\`)`,\n '',\n `When its first step has a name and a rendering mode, it scaffolds with the command for that mode; \\`--example\\` is for spa alone, and an ssg or ssr scaffold refuses it${manager === 'npm' ? \". An ssg scaffold names `@foldkit/devtools` but not `@foldkit/ui`, its peer, so npm takes the newest `@foldkit/ui`, and refuses the install once that one needs a newer Effect than the scaffold's: `--force` lets it install with a warning, and step 2 replaces that `@foldkit/ui` with the one at the scaffold's Foldkit release (`--legacy-peer-deps` would also drop peers the scaffolder itself needs)\" : ''}:`,\n '',\n '```bash',\n `npx ${SCAFFOLDER} --name <name> --rendering spa --example counter --package-manager ${manager}`,\n `npx ${manager === 'npm' ? '--force ' : ''}${SCAFFOLDER} --name <name> --rendering ssg --package-manager ${manager}`,\n `npx ${SCAFFOLDER} --name <name> --rendering ssr --package-manager ${manager}`,\n '```',\n '',\n 'Then run `npx --legacy-peer-deps foldkit-plus setup` again in the new folder and continue from step 2.',\n ],\n onSome: found => [\n `This is \\`${found.name}\\`, installed with ${manager}.`,\n '',\n finding(found, 'effect', effect),\n finding(found, 'foldkit', versions.foldkit),\n ...(uiPeer\n ? [\n `- \\`@foldkit/devtools\\` peers on \\`@foldkit/ui\\`, which the project does not name: step 2 adds \\`@foldkit/ui@${versions.foldkit}\\`, since a manager left to choose takes the newest, which may need a newer Effect.`,\n ]\n : []),\n // Never overwritten: line endings are the project's to choose once chosen.\n ...(found.gitattributes\n ? ['- `.gitattributes` is there: leave it as it is.']\n : [\n \"- There is no `.gitattributes`. Write one at the repository's root (beside `package.json` if this is not yet a repository), so Git keeps the LF line endings the formatter writes and `git add` on Windows does not warn of every file:\",\n '',\n '```gitattributes',\n '* text=auto eol=lf',\n '*.wasm binary',\n '```',\n ]),\n ],\n })\n return [\n `# Foldkit Plus ${versions.plus}: setup`,\n '',\n 'Instructions for a coding agent, in order. Each step says what to run and why. Tell the user what you did at the end.',\n '',\n '## What these are',\n '',\n '- **Effect** (https://effect.website): TypeScript for typed effects, errors, schemas and streams. Foldkit Plus targets Effect 4.',\n '- **Foldkit** (https://foldkit.dev): an application is one state machine on Effect, a Schema-typed `Model`, a `Message` union and one pure `update`; I/O runs in Commands and Subscriptions.',\n '- **Foldkit Plus**: packages that extend a Foldkit application to agents, servers, other devices, the URL and design systems without a second place to keep state. An agent sends only Messages `update` already handles; server data lives in the Model; replicas replay the same Messages; the URL mirrors a slice of the Model.',\n '',\n '## 1. Check the project',\n '',\n ...check,\n '',\n '## 2. Install',\n '',\n `Foldkit and its tooling take one Effect minor, and Foldkit Plus is tested on ${versions.effect}.${effect === versions.effect ? '' : ` The lockfile already holds ${effect}, a later patch of that minor, and npm keeps a locked package rather than move it down to an override, so the pins name ${effect}.`} To install one copy of each Effect package, at that release, first merge this into \\`${pins.file}\\`, keeping what it holds (${pinsWhy[manager]}${pins.file === 'package.json' ? '' : '; pnpm reads them only at the workspace root'}):`,\n '',\n `\\`\\`\\`${pins.language}`,\n pins.text,\n '```',\n '',\n 'Then install:',\n '',\n '```bash',\n install,\n '```',\n '',\n '`foldkit-plus` brings every package except the adapters below, each of which needs a library of its own. Add one only when the application needs it:',\n '',\n ...adapters.map(\n each => `- ${each.when}: \\`${addCommand(manager, [each.name, ...each.libraries])}\\``,\n ),\n '',\n '## 3. Add the agent skill',\n '',\n '```bash',\n 'npx skills add doeixd/foldkit-plus --skill foldkit-plus',\n '```',\n '',\n 'It teaches you which package owns which kind of state, when to reach for each, and a working example of each. Read its `SKILL.md` before writing code with Foldkit Plus, and the reference for the package at hand before changing it. To look one symbol or topic up in the docs of the versions installed here, run `npx foldkit-plus docs <symbol or words>` (`--list` for what there is).',\n // An empty folder was sent to the guide in step 1.\n ...Option.match(project, {\n onNone: () => [],\n onSome: () => [\n '',\n `Paste the block in its \\`references/agents-md.md\\` (${AGENTS_BLOCK}) under Project Notes in the project's \\`AGENTS.md\\`: the house rules and known traps for an application on these packages.`,\n '',\n `Building a new application rather than extending one? Follow its \\`references/greenfield.md\\` (${GREENFIELD}): goals and the look, then the domain with the user, recorded in the project and mapped to these packages, then a plan for architecture, performance, SEO, testing, CI and deployment, before implementing.`,\n ],\n }),\n '',\n '## 4. Import',\n '',\n 'The namespaces most applications use come from the root:',\n '',\n '```ts',\n \"import { Surface, Projection, Remote, Sync, Mirror, Agent, Style } from 'foldkit-plus'\",\n '```',\n '',\n 'Everything else is a subpath named for its package, for example `foldkit-plus/remote-server` on the server, `foldkit-plus/sync/journal`, `foldkit-plus/mixins/theme`. Pick a package by who owns the data:',\n '',\n '| Job | Import from | Guide |',\n '| --- | --- | --- |',\n ...jobs.map(\n each =>\n `| ${each.job} | ${each.imports.map(name => `\\`foldkit-plus/${name}\\``).join(', ')} | ${SITE}/${each.guide} |`,\n ),\n '',\n '## 5. Rules every package keeps',\n '',\n '- One owner per datum: never keep a fact in the Model and again in a cache, a URL store or a second reducer.',\n '- Behaviour goes through Messages and `update`; agents, replicas and Behaviors never change the Model directly.',\n '- Rendering performs no I/O: fetching, syncing and mirroring run in Commands and Subscriptions.',\n '- Absence is an Effect `Option`, not `null`, except at a JSON, database or DOM boundary.',\n '',\n '## More',\n '',\n `- Guides and API: ${SITE}`,\n `- Demos: ${SITE}/demos`,\n `- Source and changelog: ${REPOSITORY}`,\n '',\n ].join('\\n')\n}\n"],"mappings":";;;;;;;AA4CA,MAAM,OAAO;AACb,MAAM,aAAa;;;;;;;AAQnB,MAAa,aAAa;AAE1B,MAAM,aAAa,GAAG,WAAW;AACjC,MAAM,eAAe,GAAG,WAAW;;AAGnC,MAAa,OAIR;CACH;EACE,KAAK;EACL,SAAS,CAAC,WAAW,UAAU;EAC/B,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,UAAU,gBAAgB;EACpC,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS;GAAC;GAAU;GAAkB;EAAW;EACjD,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,YAAY;EACtB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,QAAQ;EAClB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS;GAAC;GAAU;GAAiB;EAAgB;EACrD,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,QAAQ,SAAS;EAC3B,OAAO;CACT;CACA;EAAE,KAAK;EAA2C,SAAS,CAAC,OAAO;EAAG,OAAO;CAAQ;CACrF;EACE,KAAK;EACL,SAAS,CAAC,MAAM;EAChB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS,CAAC,QAAQ;EAClB,OAAO;CACT;CACA;EACE,KAAK;EACL,SAAS;GAAC;GAAQ;GAAe;EAAc;EAC/C,OAAO;C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GAAI,MAAM,gBACN,CAAC,iDAAiD,IAClD;IACE;IACA;IACA;IACA;IACA;IACA;GACF;EACN;CACF,CAAC;CACD,OAAO;EACL,kBAAkB,SAAS,KAAK;EAChC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG;EACH;EACA;EACA;EACA,gFAAgF,SAAS,OAAO,GAAG,WAAW,SAAS,SAAS,KAAK,+BAA+B,OAAO,0HAA0H,OAAO,GAAG,wFAAwF,KAAK,KAAK,6BAA6B,QAAQ,WAAW,KAAK,SAAS,iBAAiB,KAAK,+CAA+C;EACphB;EACA,SAAS,KAAK;EACd,KAAK;EACL;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG,SAAS,KACV,SAAQ,KAAK,KAAK,KAAK,MAAM,WAAW,SAAS,CAAC,KAAK,MAAM,GAAG,KAAK,SAAS,CAAC,EAAE,GACnF;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EAEA,GAAG,OAAO,MAAM,SAAS;GACvB,cAAc,CAAC;GACf,cAAc;IACZ;IACA,uDAAuD,aAAa;IACpE;IACA,kGAAkG,WAAW;GAC/G;EACF,CAAC;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG,KAAK,KACN,SACE,KAAK,KAAK,IAAI,KAAK,KAAK,QAAQ,KAAI,SAAQ,kBAAkB,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,KAAK,KAAK,GAAG,KAAK,MAAM,GAC/G;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,qBAAqB;EACrB,YAAY,KAAK;EACjB,2BAA2B;EAC3B;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
1
+ {"version":3,"file":"setup.mjs","names":[],"sources":["../src/setup.ts"],"sourcesContent":["/**\n * What `npx foldkit-plus setup` prints: instructions a coding agent can follow\n * in order, for the project it is run in. Pure: the CLI reads the project and\n * this package's manifest and passes them in, so a test can give any project.\n */\nimport { Option } from 'effect'\n\nexport type Manager = 'pnpm' | 'npm' | 'yarn' | 'bun'\n\n/** What the project's `package.json` says about the libraries Foldkit Plus needs. */\nexport interface Project {\n readonly name: string\n /** Each named library's version range, from any dependency field. */\n readonly versions: Readonly<Record<string, string>>\n /** Whether a `.gitattributes` applies here: in the project's folder or one above it in its repository. */\n readonly gitattributes: boolean\n /** Where pnpm reads this project's settings, which a workspace keeps at its root. */\n readonly pnpmSettings: PnpmSettings\n /** The versions of Effect's packages (`effectPackages`) its npm lockfile holds, nested copies included. */\n readonly locked: ReadonlyArray<string>\n}\n\n/** A file pnpm reads settings from, in `folder` relative to the project (`.`, `../..`). */\nexport interface PnpmSettings {\n readonly folder: string\n readonly file: 'package.json' | 'pnpm-workspace.yaml'\n}\n\n/**\n * The versions this release is built and tested against, from its own\n * manifest: the workspace's Foldkit and Effect.\n */\nexport interface Versions {\n readonly plus: string\n readonly effect: string\n readonly foldkit: string\n}\n\nexport interface SetupInput {\n readonly project: Option.Option<Project>\n readonly manager: Manager\n readonly versions: Versions\n}\n\nconst SITE = 'https://foldkit-plus.pages.dev'\nconst REPOSITORY = 'https://github.com/doeixd/foldkit-plus'\n\n/**\n * The `create-foldkit-app` release whose templates pin the Foldkit this\n * release needs (0.41.0 installs `foldkit`, `@foldkit/ui` and `@foldkit/devtools`\n * 0.170.0, `@foldkit/vite-plugin` 0.29.0 and `effect` 4.1.0). A release that\n * moves the `foldkit` peer moves this with it.\n */\nexport const SCAFFOLDER = 'create-foldkit-app@0.41.0'\n\nconst GREENFIELD = `${REPOSITORY}/blob/main/skills/foldkit-plus/references/greenfield.md`\nconst AGENTS_BLOCK = `${REPOSITORY}/blob/main/skills/foldkit-plus/references/agents-md.md`\n\n/** What each job needs, where to import it from, and where it is explained. */\nexport const jobs: ReadonlyArray<{\n readonly job: string\n readonly imports: ReadonlyArray<string>\n readonly guide: string\n}> = [\n {\n job: 'Name what a feature may read and which Messages it may send',\n imports: ['surface', 'metadata'],\n guide: 'surface',\n },\n {\n job: 'A reusable Submodel placed several times, every part wired',\n imports: ['bundle', 'bundle-surface'],\n guide: 'bundle',\n },\n {\n job: 'Restyle or extend views from outside, through typed slots',\n imports: ['mixins', 'mixins-surface', 'mixins-ui'],\n guide: 'mixins',\n },\n {\n job: 'Media queries, timers, sockets, clipboard, undo history',\n imports: ['primitives'],\n guide: 'primitives',\n },\n {\n job: 'Declare the domain once: entities, relations, queries',\n imports: ['entity'],\n guide: 'entity',\n },\n {\n job: 'Server-owned data in the Model: queries, mutations, live updates',\n imports: ['remote', 'remote-server', 'remote-drizzle'],\n guide: 'remote',\n },\n {\n job: 'Edits that survive offline and converge across devices',\n imports: ['sync', 'durable'],\n guide: 'sync',\n },\n { job: 'Who may do what, enforced on every seam', imports: ['guard'], guide: 'guard' },\n {\n job: 'Who is signed in: a Yielded Auth session as the principal',\n imports: ['auth'],\n guide: 'auth',\n },\n {\n job: 'A slice of the Model kept in the URL or in storage',\n imports: ['mirror'],\n guide: 'mirror',\n },\n {\n job: 'Forms: drafts, validation, a decoded value, and dates, times and addresses in them',\n imports: ['form', 'mixins-form', 'form-recipes'],\n guide: 'form',\n },\n {\n job: 'Edit, create and list screens over Remote',\n imports: ['crud', 'mixins-crud'],\n guide: 'crud',\n },\n {\n job: 'An interactive data grid over rows you own',\n imports: ['data-grid', 'mixins-data-grid'],\n guide: 'data-grid',\n },\n {\n job: 'Drafts, revisions and publishing for content',\n imports: ['cms', 'cms-drizzle'],\n guide: 'cms',\n },\n {\n job: 'Pages as data, and a builder that edits them',\n imports: ['composition', 'builder', 'mixins-builder'],\n guide: 'composition',\n },\n {\n job: 'Rich text: the document, its editor, Markdown and code',\n imports: [\n 'richtext',\n 'richtext-dom',\n 'mixins-richtext',\n 'richtext-markdown',\n 'richtext-code',\n 'richtext-code-shiki',\n ],\n guide: 'richtext',\n },\n {\n job: 'Server rendering that hands the Model over, and the server handler around it',\n imports: ['ssr', 'host'],\n guide: 'ssr',\n },\n {\n job: 'Responsive images, their variants and placeholders, and icons as data',\n imports: ['media'],\n guide: 'media',\n },\n { job: 'Route topology as data: nodes, typed targets, titles', imports: ['site'], guide: 'site' },\n {\n job: 'What an AI agent may see and do, over MCP, WebMCP, A2A or Agent Native',\n imports: ['agent', 'agent-mcp', 'agent-webmcp', 'agent-a2a', 'agent-native'],\n guide: 'agent',\n },\n {\n job: 'React components in a Foldkit view, or Foldkit inside React',\n imports: ['react', 'react-codegen'],\n guide: 'react',\n },\n]\n\n/**\n * The packages `foldkit-plus` does not install, since each needs a library of\n * its own, and that library at the range the adapter peers on: a manager\n * given a bare name installs the `latest` tag, which for `@yielded/auth` is a\n * beta older than the one `foldkit-auth` names. `test/generated.test.ts`\n * holds this to the manifests.\n */\nexport const adapters: ReadonlyArray<{\n readonly name: string\n readonly libraries: ReadonlyArray<string>\n readonly when: string\n}> = [\n {\n name: 'foldkit-agent-native',\n libraries: ['@agent-native/core@0.214.0'],\n when: 'agents through Agent Native',\n },\n {\n name: 'foldkit-auth',\n libraries: ['@yielded/auth@0.1.0-beta.47'],\n when: 'sign-in and sessions with Yielded Auth',\n },\n {\n name: 'foldkit-cms-drizzle',\n libraries: ['drizzle-orm@1.0.0-rc.5'],\n when: \"the CMS's server on Drizzle\",\n },\n {\n name: 'foldkit-mixins-ui',\n libraries: ['@foldkit/ui@^0.170.0'],\n when: 'styling `@foldkit/ui` components through slots',\n },\n {\n name: 'foldkit-react',\n libraries: ['react@^19.0.0', 'react-dom@^19.0.0'],\n when: 'React interop',\n },\n {\n name: 'foldkit-react-codegen',\n libraries: ['typescript@>=5.7.2 <7'],\n when: 'compiling Foldkit views to React TSX (a dev dependency)',\n },\n {\n name: 'foldkit-remote-drizzle',\n libraries: ['drizzle-orm@1.0.0-rc.5'],\n when: 'answering Remote reads with Drizzle',\n },\n {\n name: 'foldkit-richtext-code-shiki',\n libraries: ['shiki@^4.4.3'],\n when: 'highlighting code blocks with Shiki',\n },\n]\n\n/**\n * The Effect packages an application meets that something names at a version\n * of its own: Foldkit's peers and its Vite plugin's dependencies name one\n * minor (`~4.1.0`), and each `@effect/*` package peers on an `effect` at least\n * its own version. Setup holds all of them at the Effect this release is\n * tested on, as `pnpm-workspace.yaml` does here (`test/generated.test.ts`\n * keeps the two lists together).\n */\nexport const effectPackages: ReadonlyArray<string> = [\n 'effect',\n '@effect/platform-browser',\n '@effect/platform-node',\n '@effect/platform-node-shared',\n '@effect/sql-sqlite-node',\n]\n\nconst releaseOf = (version: string) =>\n /^(\\d+)\\.(\\d+)\\.(\\d+)$/.exec(version)?.slice(1).map(Number) ?? []\n\n/**\n * The Effect release setup pins: the one this release is tested on, or a later\n * patch of the same minor that the project's lockfile already holds. npm keeps\n * a locked package that an override contradicts rather than move it down, so\n * pinning 4.1.0 left the 4.1.1 that `@foldkit/vite-plugin`'s `~4.1.0` had\n * locked under it, which `npm ls` calls invalid.\n */\nexport const effectRelease = (tested: string, locked: ReadonlyArray<string>): string => {\n const [major, minor] = releaseOf(tested)\n return locked.reduce((newest, version) => {\n const [lockedMajor, lockedMinor, patch = -1] = releaseOf(version)\n return lockedMajor === major && lockedMinor === minor && patch > (releaseOf(newest)[2] ?? -1)\n ? version\n : newest\n }, tested)\n}\n\n/** Where the pins go, and the block that holds them. */\ninterface Pins {\n /** The file, as the step names it: `package.json`, `../../pnpm-workspace.yaml`. */\n readonly file: string\n readonly language: 'json' | 'yaml'\n readonly text: string\n}\n\n/** A YAML key, quoted where `@` would start something else. */\nconst yamlKey = (key: string) => (key.startsWith('@') ? `'${key}'` : key)\n\n/**\n * The settings that hold every Effect package at `effect`, to merge into the\n * file the manager reads them from. npm applies an override to a package the\n * project depends on only where the project names that same version, so its\n * block sets those dependencies too (a `$name` reference would follow them,\n * but npm 10 cannot resolve a scoped one); pnpm reads them only at a\n * workspace's root.\n */\nconst pinsOf = (\n manager: Manager,\n effect: string,\n direct: ReadonlySet<string>,\n pnpmSettings: PnpmSettings,\n): Pins => {\n const pins = Object.fromEntries(effectPackages.map(name => [name, effect]))\n const allowedVersions = { effect, '@effect/platform-browser': effect }\n if (manager === 'pnpm' && pnpmSettings.file === 'pnpm-workspace.yaml') {\n const lines = (entries: Readonly<Record<string, string>>, indent: string) =>\n Object.entries(entries).map(([name, version]) => `${indent}${yamlKey(name)}: ${version}`)\n return {\n file: `${pnpmSettings.folder}/pnpm-workspace.yaml`,\n language: 'yaml',\n text: [\n 'overrides:',\n ...lines(pins, ' '),\n 'peerDependencyRules:',\n ' allowedVersions:',\n ...lines(allowedVersions, ' '),\n ].join('\\n'),\n }\n }\n const fields = {\n npm: {\n dependencies: Object.fromEntries(\n effectPackages.filter(name => direct.has(name)).map(name => [name, effect]),\n ),\n overrides: pins,\n },\n pnpm: { pnpm: { overrides: pins, peerDependencyRules: { allowedVersions } } },\n yarn: { resolutions: pins },\n bun: { overrides: pins },\n }[manager]\n return {\n file:\n manager === 'pnpm' && pnpmSettings.folder !== '.'\n ? `${pnpmSettings.folder}/package.json`\n : 'package.json',\n language: 'json',\n text: JSON.stringify(fields, null, 2),\n }\n}\n\n/** Why `manager` needs the pins, after \"first merge this into `package.json`\". */\nconst pinsWhy: Readonly<Record<Manager, string>> = {\n npm: 'npm refuses a peer it does not match, and `overrides` lets one in without turning every peer check off; it overrides a dependency of the project only at the version the project names, so the block sets those too',\n pnpm: \"`overrides` sets the version, and `peerDependencyRules` lets Foldkit's exact peers accept it\",\n yarn: \"`resolutions` sets the version; Yarn warns of Foldkit's exact peers, and installs\",\n bun: \"`overrides` sets the version; Bun warns of Foldkit's exact peers, and installs\",\n}\n\n/**\n * The command that adds `packages` with `manager`, at exactly the versions\n * named when `exact`. A range a shell would read (`^`, `>`, a space) is quoted.\n */\nexport const addCommand = (\n manager: Manager,\n packages: ReadonlyArray<string>,\n exact = false,\n): string =>\n [\n manager,\n manager === 'npm' ? 'install' : 'add',\n ...(exact ? [manager === 'npm' || manager === 'pnpm' ? '--save-exact' : '--exact'] : []),\n ...packages.map(spec => (/^[\\w@/.-]+$/.test(spec) ? spec : `\"${spec}\"`)),\n ].join(' ')\n\n/** The major version a range asks for: `^4.0.0`, `~4.1`, `4.0.0-beta.1` all ask for 4. */\nconst majorOf = (range: string): Option.Option<number> =>\n Option.fromNullishOr(/(\\d+)/.exec(range)?.[1]).pipe(Option.map(Number))\n\n/** What the project has of a library against what this release needs, as a line to act on. */\nconst finding = (project: Project, library: string, wanted: string): string =>\n Option.match(Option.fromNullishOr(project.versions[library]), {\n onNone: () => `- \\`${library}\\` is not installed: step 2 adds \\`${library}@${wanted}\\`.`,\n onSome: range => {\n // Foldkit is 0.x, where a minor version breaks; Effect is past 1.\n const matches =\n library === 'foldkit'\n ? range.replace(/^[\\^~=v]*/, '').startsWith(wanted.split('.').slice(0, 2).join('.'))\n : Option.getOrUndefined(majorOf(range)) === Option.getOrUndefined(majorOf(wanted))\n return matches\n ? `- \\`${library}\\` ${range}: fits.`\n : `- \\`${library}\\` is ${range}, and Foldkit Plus needs ${wanted}: step 2 moves it to ${wanted}. Check the application builds after.`\n },\n })\n\nexport const setupGuide = ({ project, manager, versions }: SetupInput): string => {\n // Every Effect package the project names moves with `effect`, so the pins hold.\n const listed = Option.match(project, {\n onNone: () => [],\n onSome: found => effectPackages.filter(name => found.versions[name] !== undefined),\n })\n const moved = new Set(['effect', '@effect/platform-browser', ...listed])\n const effect = effectRelease(\n versions.effect,\n Option.match(project, { onNone: () => [], onSome: found => found.locked }),\n )\n const pins = pinsOf(\n manager,\n effect,\n moved,\n Option.match(project, {\n onNone: () => ({ folder: '.', file: 'package.json' }),\n onSome: found => found.pnpmSettings,\n }),\n )\n // Foldkit's devtools peer on `@foldkit/ui` at any release, and a manager left\n // to pick one takes the newest, which may peer on a newer Effect (#229).\n const uiPeer = Option.exists(\n project,\n found =>\n found.versions['@foldkit/devtools'] !== undefined &&\n found.versions['@foldkit/ui'] === undefined,\n )\n // npm's block already names the Effect packages the project depends on.\n const install = addCommand(\n manager,\n [\n ...(manager === 'npm'\n ? []\n : effectPackages.filter(name => moved.has(name)).map(name => `${name}@${effect}`)),\n `foldkit@${versions.foldkit}`,\n ...(uiPeer ? [`@foldkit/ui@${versions.foldkit}`] : []),\n 'foldkit-plus',\n ],\n true,\n )\n const check = Option.match(project, {\n onNone: () => [\n 'There is no `package.json` here: this is a new application. Do not scaffold yet. Follow the greenfield guide, which asks the user about the goals, the look and the domain before any code:',\n '',\n `- ${GREENFIELD} (in the skill of step 3, \\`references/greenfield.md\\`)`,\n '',\n `When its first step has a name and a rendering mode, it scaffolds with the command for that mode; \\`--example\\` is for spa alone, and an ssg or ssr scaffold refuses it${manager === 'npm' ? \". An ssg scaffold names `@foldkit/devtools` but not `@foldkit/ui`, its peer, so npm takes the newest `@foldkit/ui`, and refuses the install once that one needs a newer Effect than the scaffold's: `--force` lets it install with a warning, and step 2 replaces that `@foldkit/ui` with the one at the scaffold's Foldkit release (`--legacy-peer-deps` would also drop peers the scaffolder itself needs)\" : ''}:`,\n '',\n '```bash',\n `npx ${SCAFFOLDER} --name <name> --rendering spa --example counter --package-manager ${manager}`,\n `npx ${manager === 'npm' ? '--force ' : ''}${SCAFFOLDER} --name <name> --rendering ssg --package-manager ${manager}`,\n `npx ${SCAFFOLDER} --name <name> --rendering ssr --package-manager ${manager}`,\n '```',\n '',\n 'Then run `npx --legacy-peer-deps foldkit-plus setup` again in the new folder and continue from step 2.',\n ],\n onSome: found => [\n `This is \\`${found.name}\\`, installed with ${manager}.`,\n '',\n finding(found, 'effect', effect),\n finding(found, 'foldkit', versions.foldkit),\n ...(uiPeer\n ? [\n `- \\`@foldkit/devtools\\` peers on \\`@foldkit/ui\\`, which the project does not name: step 2 adds \\`@foldkit/ui@${versions.foldkit}\\`, since a manager left to choose takes the newest, which may need a newer Effect.`,\n ]\n : []),\n // Never overwritten: line endings are the project's to choose once chosen.\n ...(found.gitattributes\n ? ['- `.gitattributes` is there: leave it as it is.']\n : [\n \"- There is no `.gitattributes`. Write one at the repository's root (beside `package.json` if this is not yet a repository), so Git keeps the LF line endings the formatter writes and `git add` on Windows does not warn of every file:\",\n '',\n '```gitattributes',\n '* text=auto eol=lf',\n '*.wasm binary',\n '```',\n ]),\n ],\n })\n return [\n `# Foldkit Plus ${versions.plus}: setup`,\n '',\n 'Instructions for a coding agent, in order. Each step says what to run and why. Tell the user what you did at the end.',\n '',\n '## What these are',\n '',\n '- **Effect** (https://effect.website): TypeScript for typed effects, errors, schemas and streams. Foldkit Plus targets Effect 4.',\n '- **Foldkit** (https://foldkit.dev): an application is one state machine on Effect, a Schema-typed `Model`, a `Message` union and one pure `update`; I/O runs in Commands and Subscriptions.',\n '- **Foldkit Plus**: packages that extend a Foldkit application to agents, servers, other devices, the URL and design systems without a second place to keep state. An agent sends only Messages `update` already handles; server data lives in the Model; replicas replay the same Messages; the URL mirrors a slice of the Model.',\n '',\n '## 1. Check the project',\n '',\n ...check,\n '',\n '## 2. Install',\n '',\n `Foldkit and its tooling take one Effect minor, and Foldkit Plus is tested on ${versions.effect}.${effect === versions.effect ? '' : ` The lockfile already holds ${effect}, a later patch of that minor, and npm keeps a locked package rather than move it down to an override, so the pins name ${effect}.`} To install one copy of each Effect package, at that release, first merge this into \\`${pins.file}\\`, keeping what it holds (${pinsWhy[manager]}${pins.file === 'package.json' ? '' : '; pnpm reads them only at the workspace root'}):`,\n '',\n `\\`\\`\\`${pins.language}`,\n pins.text,\n '```',\n '',\n 'Then install:',\n '',\n '```bash',\n install,\n '```',\n '',\n '`foldkit-plus` brings every package except the adapters below, each of which needs a library of its own. Add one only when the application needs it:',\n '',\n ...adapters.map(\n each => `- ${each.when}: \\`${addCommand(manager, [each.name, ...each.libraries])}\\``,\n ),\n '',\n '## 3. Add the agent skill',\n '',\n '```bash',\n 'npx skills add doeixd/foldkit-plus --skill foldkit-plus',\n '```',\n '',\n 'It teaches you which package owns which kind of state, when to reach for each, and a working example of each. Read its `SKILL.md` before writing code with Foldkit Plus, and the reference for the package at hand before changing it. To look one symbol or topic up in the docs of the versions installed here, run `npx foldkit-plus docs <symbol or words>` (`--list` for what there is).',\n // An empty folder was sent to the guide in step 1.\n ...Option.match(project, {\n onNone: () => [],\n onSome: () => [\n '',\n `Paste the block in its \\`references/agents-md.md\\` (${AGENTS_BLOCK}) under Project Notes in the project's \\`AGENTS.md\\`: the house rules and known traps for an application on these packages.`,\n '',\n `Building a new application rather than extending one? Follow its \\`references/greenfield.md\\` (${GREENFIELD}): goals and the look, then the domain with the user, recorded in the project and mapped to these packages, then a plan for architecture, performance, SEO, testing, CI and deployment, before implementing.`,\n ],\n }),\n '',\n '## 4. Import',\n '',\n 'The namespaces most applications use come from the root:',\n '',\n '```ts',\n \"import { Surface, Projection, Remote, Sync, Mirror, Agent, Style } from 'foldkit-plus'\",\n '```',\n '',\n 'Everything else is a subpath named for its package, for example `foldkit-plus/remote-server` on the server, `foldkit-plus/sync/journal`, `foldkit-plus/mixins/theme`. Pick a package by who owns the data:',\n '',\n '| Job | Import from | Guide |',\n '| --- | --- | --- |',\n ...jobs.map(\n each =>\n `| ${each.job} | ${each.imports.map(name => `\\`foldkit-plus/${name}\\``).join(', ')} | ${SITE}/${each.guide} |`,\n ),\n '',\n '## 5. Rules every package keeps',\n '',\n '- One owner per datum: never keep a fact in the Model and again in a cache, a URL store or a second reducer.',\n '- Behaviour goes through Messages and `update`; agents, replicas and Behaviors never change the Model directly.',\n '- Rendering performs no I/O: fetching, syncing and mirroring run in Commands and Subscriptions.',\n '- Absence is an Effect `Option`, not `null`, except at a JSON, database or DOM boundary.',\n '',\n '## More',\n '',\n `- Guides and API: ${SITE}`,\n `- Demos: ${SITE}/demos`,\n `- Source and changelog: ${REPOSITORY}`,\n '',\n ].join('\\n')\n}\n"],"mappings":";;;;;;;AA4CA,MAAM,OAAO;AACb,MAAM,aAAa;;;;;;;AAQnB,MAAa,aAAa;AAE1B,MAAM,aAAa,GAAG,WAAW;AACjC,MAAM,eAAe,GAAG,WAAW;;AAGnC,MAAa,OAIR;CACH;EACE,KAAK;EACL,SAAS,CAAC,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A;EACA;EACA;EACA;EACA;EACA;EAEA,GAAG,OAAO,MAAM,SAAS;GACvB,cAAc,CAAC;GACf,cAAc;IACZ;IACA,uDAAuD,aAAa;IACpE;IACA,kGAAkG,WAAW;GAC/G;EACF,CAAC;EACD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,GAAG,KAAK,KACN,SACE,KAAK,KAAK,IAAI,KAAK,KAAK,QAAQ,KAAI,SAAQ,kBAAkB,KAAK,GAAG,CAAC,CAAC,KAAK,IAAI,EAAE,KAAK,KAAK,GAAG,KAAK,MAAM,GAC/G;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,qBAAqB;EACrB,YAAY,KAAK;EACjB,2BAA2B;EAC3B;CACF,CAAC,CAAC,KAAK,IAAI;AACb"}
@@ -0,0 +1 @@
1
+ export * from "foldkit-ssr/loader";
@@ -0,0 +1,2 @@
1
+ export * from "foldkit-ssr/loader";
2
+ export {};
@@ -1 +1 @@
1
- {"version":3,"file":"playwright.d.mts","names":[],"sources":["../../src/testing/playwright.ts"],"mappings":";;;;;;;;iBA6EiB;WACN,gBAAgB;;iBAGV;;WAEN,WAAW;;WAEX,OAAO;;;;;;;;WAQP,0BAA0B;;WAE1B,kBAAkB;;;;;;WAMlB,OAAO,SAAS;;WAEhB,SAAS,SAAS;;;;;;;;;;;;;;;;;;;;;cAwIvB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;iBAiIlD;;WAEN,eAAe;;;;;;WAMf,cAAc;;;;;;;cA2CnB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;;;;;cA6B7D,gBAAa,MAAU,gBAAc;;qBAU9B"}
1
+ {"version":3,"file":"playwright.d.mts","names":[],"sources":["../../src/testing/playwright.ts"],"mappings":";;;;;;;;iBA6EiB;WACN,gBAAgB;;iBAGV;;WAEN,WAAW;;WAEX,OAAO;;;;;;;;WAQP,0BAA0B;;WAE1B,kBAAkB;;;;;;WAMlB,OAAO,SAAS;;WAEhB,SAAS,SAAS;;;;;;;;;;;;;;;;;;;;;cAwIvB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;iBAoIlD;;WAEN,eAAe;;;;;;WAMf,cAAc;;;;;;;cA2CnB,aAAU,MAAgB,MAAI,SAAW,sBAAoB;;;;;cA6B7D,gBAAa,MAAU,gBAAc;;qBAU9B"}
@@ -215,7 +215,7 @@ const optimistic = async (page, options) => {
215
215
  }) : new Promise(() => {});
216
216
  if (!await Promise.race([acted.then(() => true), deadline])) {
217
217
  release();
218
- await acted;
218
+ acted.catch(() => {});
219
219
  throw new Error(`optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`);
220
220
  }
221
221
  const missed = await shown;
@@ -1 +1 @@
1
- {"version":3,"file":"playwright.mjs","names":[],"sources":["../../src/testing/playwright.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/playwright`: what a user sees, asserted on a running\n * page. A write shows before the server answers, holds still until it is\n * answered, and stays after; a step never shows a given text, at any moment;\n * the page logs no error.\n *\n * Each checks the page as drawn, over the real network: it proves that the\n * whole application (server, hydration, persistence, the Worker) delivers a\n * property. Which Message breaks a read's property is\n * `foldkit-plus/remote/testing`'s `Trace`, which records every Model without\n * a browser; reach for it once one of these fails.\n *\n * Playwright is an optional peer of `foldkit-plus`, needed only for its types:\n * this module calls nothing but the `Page` it is given.\n */\nimport { Duration, Option, Schema } from 'effect'\nimport { RemoteJsonRequest } from 'foldkit-remote'\nimport type { ConsoleMessage, Locator, Page, Request, Route } from 'playwright'\n\nconst decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest))\n\n/** The operation of a Remote request over HTTP, by the JSON request `Remote.http` sends. */\nconst remoteOperation = (request: Request): Option.Option<RemoteJsonRequest['operation']> => {\n const body = request.method() === 'POST' ? request.postData() : null\n return body === null ? Option.none() : Option.map(decodeRequest(body), sent => sent.operation)\n}\n\nconst isRemoteMutation = (request: Request): boolean =>\n Option.contains(remoteOperation(request), 'mutate')\n\nconst millis = (input: Duration.Input) => Duration.toMillis(Duration.fromInputUnsafe(input))\n\n/**\n * How long `act` may take at least before it is taken to wait for its own\n * write's answer. Only that case needs a limit, so it is far longer than a\n * click takes on a loaded runner, whatever `hold` is.\n */\nconst ACT_LIMIT = 10_000\n\n/**\n * Resolves once three frames in a row pass with no change to the document,\n * or after two seconds of changes: a Message an answer caused has been drawn.\n */\nconst quiet = (page: Page): Promise<void> =>\n page.evaluate(\n () =>\n new Promise<void>(resolve => {\n let calm = 0\n const observer = new MutationObserver(() => {\n calm = 0\n })\n const done = () => {\n observer.disconnect()\n resolve()\n }\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n setTimeout(done, 2000)\n const frame = () => {\n calm += 1\n if (calm >= 3) done()\n else requestAnimationFrame(frame)\n }\n requestAnimationFrame(frame)\n }),\n )\n\n/**\n * Writes that reach the server some way other than `Remote.http` (a port to a\n * SharedWorker, a sandbox in the page). The page holds its own answers (the\n * test opened it so), and `answered` resolves on the page's own evidence that\n * nothing it wrote is pending: an outbox emptied, a status gone.\n */\nexport interface PageWrites {\n readonly answered: () => Promise<unknown>\n}\n\nexport interface OptimisticOptions {\n /** The user's action that writes: a click, a key. */\n readonly act: () => Promise<unknown>\n /** What the page shows once the write is made. */\n readonly shows: Locator\n /**\n * What must hold still from the moment `shows` shows until the write is\n * answered and drawn: `'put'` (the default), each element `shows` resolves\n * to; a `Locator`, what it resolves to instead (the list around a row its\n * answer deliberately draws again); `'shown'`, nothing, so only that\n * `shows` shows again after the answer.\n */\n readonly stays?: 'put' | 'shown' | Locator\n /** How the writes travel: `'http'` (the default), `Remote.http`'s requests, held at the network. */\n readonly writes?: 'http' | PageWrites\n /**\n * How long each Remote mutation is held at the network at least: it is held\n * on until `act` has ended and `shows` has been looked for. `'3 seconds'`\n * unless given.\n */\n readonly hold?: Duration.Input\n /** How soon after `act` begins `shows` must show, while every write is held. `'1 second'` unless given. */\n readonly within?: Duration.Input\n}\n\n/** What the page script needs to keep what it watches apart from another watch's. */\ninterface StillWatch {\n readonly key: string\n}\n\n// Runs in the page over the elements to keep still. A node removed and put\n// back in one batch reads as attached in the callback, so removals and\n// `hidden` are replayed from the records; layout and visibility are sampled\n// every frame, as a reader sees them. Each element reports each kind of fault once.\nconst watchStill = (elements: ReadonlyArray<Element>, { key }: StillWatch): number => {\n const started = performance.now()\n const where = (element: Element) => {\n const box = element.getBoundingClientRect()\n return { x: box.left + window.scrollX, y: box.top + window.scrollY }\n }\n const named = (element: Element) => {\n const html = element.outerHTML.replace(/\\s+/g, ' ')\n return html.length > 80 ? `${html.slice(0, 77)}...` : html\n }\n const watched = elements.map(element => {\n const lineage = new Set<Node>()\n for (let node: Node | null = element; node !== null; node = node.parentNode) lineage.add(node)\n return { element, lineage, first: where(element), faults: new Map<string, string>() }\n })\n const fault = (each: (typeof watched)[number], kind: string, words: string) => {\n if (!each.faults.has(kind))\n each.faults.set(\n kind,\n `${named(each.element)} ${words}, ${Math.round(performance.now() - started)} ms after it showed`,\n )\n }\n const observer = new MutationObserver(records => {\n for (const record of records)\n for (const each of watched) {\n if ([...record.removedNodes].some(node => each.lineage.has(node)))\n fault(each, 'removed', 'was taken out of the page')\n if (\n record.type === 'attributes' &&\n record.attributeName === 'hidden' &&\n record.oldValue === null &&\n each.lineage.has(record.target)\n )\n fault(each, 'hidden', 'was hidden')\n }\n for (const each of watched)\n if (each.faults.has('removed') && each.element.isConnected)\n fault(each, 'moved', 'was taken out and put back')\n })\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['hidden'],\n attributeOldValue: true,\n })\n let frame = 0\n const sample = () => {\n for (const each of watched) {\n if (!each.element.isConnected) continue\n if (!each.element.checkVisibility({ visibilityProperty: true }))\n fault(each, 'hidden', 'was hidden')\n const now = where(each.element)\n const dx = now.x - each.first.x\n const dy = now.y - each.first.y\n const away = [\n ...(Math.abs(dx) > 1 ? [`${Math.round(Math.abs(dx))}px ${dx < 0 ? 'left' : 'right'}`] : []),\n ...(Math.abs(dy) > 1 ? [`${Math.round(Math.abs(dy))}px ${dy < 0 ? 'up' : 'down'}`] : []),\n ]\n if (away.length > 0) fault(each, 'shifted', `moved ${away.join(' and ')}`)\n }\n frame = requestAnimationFrame(sample)\n }\n sample()\n Reflect.set(window, key, () => {\n Reflect.deleteProperty(window, key)\n observer.disconnect()\n cancelAnimationFrame(frame)\n return watched.map(each => ({\n element: each.element,\n name: named(each.element),\n faults: each.faults,\n }))\n })\n return elements.length\n}\n\n/**\n * Stops the watch and lists what went wrong. `now` is what the locator\n * resolves to once settled: a watched element gone from the page while one\n * that was not watched stands there was replaced, not only removed.\n */\nconst stopStill = (now: ReadonlyArray<Element>, { key }: StillWatch): ReadonlyArray<string> => {\n const report: ReadonlyArray<{\n readonly element: Element\n readonly name: string\n readonly faults: ReadonlyMap<string, string>\n }> = Reflect.apply(Reflect.get(window, key), undefined, [])\n const newcomer = now.some(element => !report.some(each => each.element === element))\n return report.flatMap(each => {\n const replaced = newcomer && !each.element.isConnected\n return [\n ...[...each.faults].flatMap(([kind, words]) =>\n replaced && kind === 'removed' ? [] : [words],\n ),\n ...(replaced ? [`${each.name} was replaced by a new element`] : []),\n ]\n })\n}\n\nconst stopIfWatching = ({ key }: StillWatch) => {\n const stop: unknown = Reflect.get(window, key)\n if (typeof stop === 'function') stop()\n}\n\n/**\n * The write shows before the server answers, holds still until it has been\n * answered and drawn, and still shows after.\n *\n * Every Remote mutation the page sends is held at the network until `act`\n * has ended and `shows` has been looked for, and for `hold` at least, so\n * what shows was drawn before any answer however long `act` takes;\n * `shows` must be visible within `within` of `act` beginning. From\n * then until settled, what `stays` names must stay in the page as the same\n * nodes, in the same place in their parent, within 1px of where they were\n * drawn, and visible. Settled is evidence, not a wait: no Remote request of\n * the page in flight (an answer can lead to more, such as a placed list's\n * first page under `verifyPredictions`), or `writes.answered`, then the page\n * quiet for three frames. An error the page logs meanwhile fails it too: a\n * `PredictionMismatch` is logged as one. Throws otherwise, when `act` sent\n * no Remote mutation over HTTP, since nothing was then held, and when `act`\n * has not ended 10 seconds (or `hold`, if longer) after it began: one that\n * waits for its own write's answer would wait for good.\n */\nconst optimistic = async (page: Page, options: OptimisticOptions): Promise<void> => {\n const writes = options.writes ?? 'http'\n const hold = millis(options.hold ?? '3 seconds')\n const within = millis(options.within ?? '1 second')\n // Opened once `shows` has been looked for and is watched: no write is\n // answered before, so nothing shown by then is an answer.\n let release = () => {}\n const looked = new Promise<void>(resolve => {\n release = resolve\n })\n const held: Array<Promise<void>> = []\n // Every Remote request from `act` on that is not yet answered.\n const inFlight = new Set<Request>()\n const sent = (request: Request) => {\n if (Option.isSome(remoteOperation(request))) inFlight.add(request)\n }\n // How many have been answered: a quiet that began before the last answer\n // may have ended before the page drew it.\n let answers = 0\n const done = (request: Request) => {\n if (inFlight.delete(request)) answers += 1\n }\n const errors: Array<string> = []\n const logged = (message: ConsoleMessage) => {\n if (message.type() === 'error') errors.push(message.text())\n }\n const thrown = (error: Error) => errors.push(String(error))\n // Let through after `hold`, once looked. The answer is awaited apart from the\n // handler: Playwright passes a request on to the next handler only once this one returns.\n const letThrough = async (route: Route) => {\n await Promise.all([new Promise(resume => setTimeout(resume, hold)), looked])\n await route.fallback()\n }\n const answered = async (request: Request) => {\n const response = await request.response()\n if (response !== null) await response.finished()\n }\n const route = await page.route('**/*', (route, request) => {\n if (writes !== 'http' || !isRemoteMutation(request)) return route.fallback()\n held.push(answered(request))\n return letThrough(route)\n })\n page.on('request', sent)\n page.on('requestfinished', done)\n page.on('requestfailed', done)\n page.on('console', logged)\n page.on('pageerror', thrown)\n const shows = String(options.shows)\n const stays = options.stays ?? 'put'\n const watched =\n stays === 'shown'\n ? Option.none<Locator>()\n : Option.some(stays === 'put' ? options.shows : stays)\n const watch: StillWatch = { key: `__foldkitStill${crypto.randomUUID().replaceAll('-', '')}` }\n let overdue: ReturnType<typeof setTimeout> | undefined\n try {\n const shown = options.shows.waitFor({ state: 'visible', timeout: within }).then(\n () => Option.none<unknown>(),\n (error: unknown) => Option.some(error),\n )\n const acted = Promise.resolve().then(options.act)\n // An action waiting for its own write's answer would wait for good.\n const deadline =\n writes === 'http'\n ? new Promise<false>(resolve => {\n overdue = setTimeout(resolve, Math.max(hold, ACT_LIMIT), false)\n })\n : new Promise<never>(() => {})\n const ended = await Promise.race([acted.then(() => true), deadline])\n if (!ended) {\n release()\n await acted\n throw new Error(\n `optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`,\n )\n }\n const missed = await shown\n if (Option.isSome(missed))\n throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, {\n cause: missed.value,\n })\n if (Option.isSome(watched) && (await watched.value.evaluateAll(watchStill, watch)) === 0)\n throw new Error(`optimistic: ${String(watched.value)}, what stays, matches nothing`)\n release()\n if (writes === 'http') {\n if (held.length === 0)\n throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`)\n } else {\n await writes.answered()\n }\n // Every held write is in flight until answered, and an answer drawn can ask\n // for more: settled once the page asks nothing and stays quiet from after\n // the last answer. The network finishes before the page reads the answer,\n // and an app draws it on a later frame.\n for (;;) {\n const before = answers\n await quiet(page)\n if (inFlight.size === 0 && answers === before) break\n }\n if (Option.isSome(watched)) {\n const faults = await watched.value.evaluateAll(stopStill, watch)\n if (faults.length > 0)\n throw new Error(\n `optimistic: ${String(watched.value)} did not hold still until the write settled:\\n ${faults.join('\\n ')}`,\n )\n }\n if (!(await options.shows.isVisible()))\n throw new Error(\n `optimistic: ${shows} showed while the write was held, but not after its answer`,\n )\n if (errors.length > 0)\n throw new Error(\n `optimistic: the page logged an error while the write settled:\\n ${errors.join('\\n ')}`,\n )\n } finally {\n clearTimeout(overdue)\n release()\n // A check that failed before reading the watch leaves it sampling every frame.\n if (!page.isClosed()) await page.evaluate(stopIfWatching, watch)\n page.off('request', sent)\n page.off('requestfinished', done)\n page.off('requestfailed', done)\n page.off('console', logged)\n page.off('pageerror', thrown)\n await route.dispose()\n await Promise.allSettled(held)\n }\n}\n\nexport interface NeverShowsOptions {\n /** What the page must not show at any moment of `during`. */\n readonly text: string | RegExp\n /**\n * The steps to watch: a reload, a navigation away and back. End it on what\n * the page waits for (an answer, a row), since watching stops once it ends\n * and the page is quiet.\n */\n readonly during: () => Promise<unknown>\n}\n\n/** What the page script needs: the binding to report through, and the text as a pattern. */\ninterface Watch {\n readonly key: string\n readonly source: string\n readonly flags: string\n}\n\n// Runs in the page, in the open document and in each one loaded after: after\n// every change to the document, the rendered text (`innerText` leaves hidden\n// text out) is searched, so a text shown for one frame is seen, not sampled.\nconst watchText = ({ key, source, flags }: Watch) => {\n if (window !== window.top) return\n const pattern = new RegExp(source, flags)\n let reported = false\n const check = () => {\n if (reported) return\n const line = (document.body?.innerText ?? '').split('\\n').find(each => pattern.test(each))\n if (line === undefined) return\n reported = true\n Reflect.apply(Reflect.get(window, key), undefined, [line])\n }\n const observer = new MutationObserver(check)\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n Reflect.set(window, `${key}Stop`, () => observer.disconnect())\n check()\n}\n\nconst stopWatching = (key: string) =>\n Reflect.apply(Reflect.get(window, `${key}Stop`), undefined, [])\n\n/**\n * The page never shows `text` while `during` runs, nor until the page is\n * quiet after it: a cached page revisited never reads \"Loading…\", even for\n * one frame. Throws with the line that showed.\n */\nconst neverShows = async (page: Page, options: NeverShowsOptions): Promise<void> => {\n const key = `__foldkitNeverShows${crypto.randomUUID().replaceAll('-', '')}`\n const { text } = options\n const watch: Watch =\n typeof text === 'string'\n ? { key, source: text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), flags: '' }\n : { key, source: text.source, flags: text.flags }\n const shown: Array<string> = []\n const binding = await page.exposeBinding(key, (_, line: string) => {\n shown.push(line)\n })\n const script = await page.addInitScript(watchText, watch)\n try {\n await page.evaluate(watchText, watch)\n await options.during()\n await quiet(page)\n } finally {\n await script.dispose()\n if (!page.isClosed()) await page.evaluate(stopWatching, key)\n await binding.dispose()\n }\n if (shown.length > 0)\n throw new Error(`neverShows: the page showed ${String(text)}: \"${shown[0]}\"`)\n}\n\n/**\n * Collects every error the page logs (`console.error`) and every exception it\n * does not catch, from now until the page closes. Read the list at the end.\n */\nconst consoleErrors = (page: Page): (() => ReadonlyArray<string>) => {\n const errors: Array<string> = []\n page.on('console', message => {\n if (message.type() === 'error') errors.push(message.text())\n })\n page.on('pageerror', error => errors.push(String(error)))\n return () => [...errors]\n}\n\n/** Assertions on what a running page shows, for Playwright. */\nexport const Behaviors = { optimistic, neverShows, consoleErrors } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAM,gBAAgB,OAAO,oBAAoB,OAAO,eAAe,iBAAiB,CAAC;;AAGzF,MAAM,mBAAmB,YAAoE;CAC3F,MAAM,OAAO,QAAQ,OAAO,MAAM,SAAS,QAAQ,SAAS,IAAI;CAChE,OAAO,SAAS,OAAO,OAAO,KAAK,IAAI,OAAO,IAAI,cAAc,IAAI,IAAG,SAAQ,KAAK,SAAS;AAC/F;AAEA,MAAM,oBAAoB,YACxB,OAAO,SAAS,gBAAgB,OAAO,GAAG,QAAQ;AAEpD,MAAM,UAAU,UAA0B,SAAS,SAAS,SAAS,gBAAgB,KAAK,CAAC;;;;;;AAO3F,MAAM,YAAY;;;;;AAMlB,MAAM,SAAS,SACb,KAAK,eAED,IAAI,SAAc,YAAW;CAC3B,IAAI,OAAO;CACX,MAAM,WAAW,IAAI,uBAAuB;EAC1C,OAAO;CACT,CAAC;CACD,MAAM,aAAa;EACjB,SAAS,WAAW;EACpB,QAAQ;CACV;CACA,SAAS,QAAQ,UAAU;EACzB,WAAW;EACX,SAAS;EACT,eAAe;EACf,YAAY;CACd,CAAC;CACD,WAAW,MAAM,GAAI;CACrB,MAAM,cAAc;EAClB,QAAQ;EACR,IAAI,QAAQ,GAAG,KAAK;OACf,sBAAsB,KAAK;CAClC;CAC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K,QAAQ,uBAAuB,MAAM;EAAG,OAAO;CAAG,IACtE;EAAE;EAAK,QAAQ,KAAK;EAAQ,OAAO,KAAK;CAAM;CACpD,MAAM,QAAuB,CAAC;CAC9B,MAAM,UAAU,MAAM,KAAK,cAAc,MAAM,GAAG,SAAiB;EACjE,MAAM,KAAK,IAAI;CACjB,CAAC;CACD,MAAM,SAAS,MAAM,KAAK,cAAc,WAAW,KAAK;CACxD,IAAI;EACF,MAAM,KAAK,SAAS,WAAW,KAAK;EACpC,MAAM,QAAQ,OAAO;EACrB,MAAM,MAAM,IAAI;CAClB,UAAU;EACR,MAAM,OAAO,QAAQ;EACrB,IAAI,CAAC,KAAK,SAAS,GAAG,MAAM,KAAK,SAAS,cAAc,GAAG;EAC3D,MAAM,QAAQ,QAAQ;CACxB;CACA,IAAI,MAAM,SAAS,GACjB,MAAM,IAAI,MAAM,+BAA+B,OAAO,IAAI,EAAE,KAAK,MAAM,GAAG,EAAE;AAChF;;;;;AAMA,MAAM,iBAAiB,SAA8C;CACnE,MAAM,SAAwB,CAAC;CAC/B,KAAK,GAAG,YAAW,YAAW;EAC5B,IAAI,QAAQ,KAAK,MAAM,SAAS,OAAO,KAAK,QAAQ,KAAK,CAAC;CAC5D,CAAC;CACD,KAAK,GAAG,cAAa,UAAS,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC;CACxD,aAAa,CAAC,GAAG,MAAM;AACzB;;AAGA,MAAa,YAAY;CAAE;CAAY;CAAY;AAAc"}
1
+ {"version":3,"file":"playwright.mjs","names":[],"sources":["../../src/testing/playwright.ts"],"sourcesContent":["/**\n * `foldkit-plus/testing/playwright`: what a user sees, asserted on a running\n * page. A write shows before the server answers, holds still until it is\n * answered, and stays after; a step never shows a given text, at any moment;\n * the page logs no error.\n *\n * Each checks the page as drawn, over the real network: it proves that the\n * whole application (server, hydration, persistence, the Worker) delivers a\n * property. Which Message breaks a read's property is\n * `foldkit-plus/remote/testing`'s `Trace`, which records every Model without\n * a browser; reach for it once one of these fails.\n *\n * Playwright is an optional peer of `foldkit-plus`, needed only for its types:\n * this module calls nothing but the `Page` it is given.\n */\nimport { Duration, Option, Schema } from 'effect'\nimport { RemoteJsonRequest } from 'foldkit-remote'\nimport type { ConsoleMessage, Locator, Page, Request, Route } from 'playwright'\n\nconst decodeRequest = Schema.decodeUnknownOption(Schema.fromJsonString(RemoteJsonRequest))\n\n/** The operation of a Remote request over HTTP, by the JSON request `Remote.http` sends. */\nconst remoteOperation = (request: Request): Option.Option<RemoteJsonRequest['operation']> => {\n const body = request.method() === 'POST' ? request.postData() : null\n return body === null ? Option.none() : Option.map(decodeRequest(body), sent => sent.operation)\n}\n\nconst isRemoteMutation = (request: Request): boolean =>\n Option.contains(remoteOperation(request), 'mutate')\n\nconst millis = (input: Duration.Input) => Duration.toMillis(Duration.fromInputUnsafe(input))\n\n/**\n * How long `act` may take at least before it is taken to wait for its own\n * write's answer. Only that case needs a limit, so it is far longer than a\n * click takes on a loaded runner, whatever `hold` is.\n */\nconst ACT_LIMIT = 10_000\n\n/**\n * Resolves once three frames in a row pass with no change to the document,\n * or after two seconds of changes: a Message an answer caused has been drawn.\n */\nconst quiet = (page: Page): Promise<void> =>\n page.evaluate(\n () =>\n new Promise<void>(resolve => {\n let calm = 0\n const observer = new MutationObserver(() => {\n calm = 0\n })\n const done = () => {\n observer.disconnect()\n resolve()\n }\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n setTimeout(done, 2000)\n const frame = () => {\n calm += 1\n if (calm >= 3) done()\n else requestAnimationFrame(frame)\n }\n requestAnimationFrame(frame)\n }),\n )\n\n/**\n * Writes that reach the server some way other than `Remote.http` (a port to a\n * SharedWorker, a sandbox in the page). The page holds its own answers (the\n * test opened it so), and `answered` resolves on the page's own evidence that\n * nothing it wrote is pending: an outbox emptied, a status gone.\n */\nexport interface PageWrites {\n readonly answered: () => Promise<unknown>\n}\n\nexport interface OptimisticOptions {\n /** The user's action that writes: a click, a key. */\n readonly act: () => Promise<unknown>\n /** What the page shows once the write is made. */\n readonly shows: Locator\n /**\n * What must hold still from the moment `shows` shows until the write is\n * answered and drawn: `'put'` (the default), each element `shows` resolves\n * to; a `Locator`, what it resolves to instead (the list around a row its\n * answer deliberately draws again); `'shown'`, nothing, so only that\n * `shows` shows again after the answer.\n */\n readonly stays?: 'put' | 'shown' | Locator\n /** How the writes travel: `'http'` (the default), `Remote.http`'s requests, held at the network. */\n readonly writes?: 'http' | PageWrites\n /**\n * How long each Remote mutation is held at the network at least: it is held\n * on until `act` has ended and `shows` has been looked for. `'3 seconds'`\n * unless given.\n */\n readonly hold?: Duration.Input\n /** How soon after `act` begins `shows` must show, while every write is held. `'1 second'` unless given. */\n readonly within?: Duration.Input\n}\n\n/** What the page script needs to keep what it watches apart from another watch's. */\ninterface StillWatch {\n readonly key: string\n}\n\n// Runs in the page over the elements to keep still. A node removed and put\n// back in one batch reads as attached in the callback, so removals and\n// `hidden` are replayed from the records; layout and visibility are sampled\n// every frame, as a reader sees them. Each element reports each kind of fault once.\nconst watchStill = (elements: ReadonlyArray<Element>, { key }: StillWatch): number => {\n const started = performance.now()\n const where = (element: Element) => {\n const box = element.getBoundingClientRect()\n return { x: box.left + window.scrollX, y: box.top + window.scrollY }\n }\n const named = (element: Element) => {\n const html = element.outerHTML.replace(/\\s+/g, ' ')\n return html.length > 80 ? `${html.slice(0, 77)}...` : html\n }\n const watched = elements.map(element => {\n const lineage = new Set<Node>()\n for (let node: Node | null = element; node !== null; node = node.parentNode) lineage.add(node)\n return { element, lineage, first: where(element), faults: new Map<string, string>() }\n })\n const fault = (each: (typeof watched)[number], kind: string, words: string) => {\n if (!each.faults.has(kind))\n each.faults.set(\n kind,\n `${named(each.element)} ${words}, ${Math.round(performance.now() - started)} ms after it showed`,\n )\n }\n const observer = new MutationObserver(records => {\n for (const record of records)\n for (const each of watched) {\n if ([...record.removedNodes].some(node => each.lineage.has(node)))\n fault(each, 'removed', 'was taken out of the page')\n if (\n record.type === 'attributes' &&\n record.attributeName === 'hidden' &&\n record.oldValue === null &&\n each.lineage.has(record.target)\n )\n fault(each, 'hidden', 'was hidden')\n }\n for (const each of watched)\n if (each.faults.has('removed') && each.element.isConnected)\n fault(each, 'moved', 'was taken out and put back')\n })\n observer.observe(document, {\n childList: true,\n subtree: true,\n attributes: true,\n attributeFilter: ['hidden'],\n attributeOldValue: true,\n })\n let frame = 0\n const sample = () => {\n for (const each of watched) {\n if (!each.element.isConnected) continue\n if (!each.element.checkVisibility({ visibilityProperty: true }))\n fault(each, 'hidden', 'was hidden')\n const now = where(each.element)\n const dx = now.x - each.first.x\n const dy = now.y - each.first.y\n const away = [\n ...(Math.abs(dx) > 1 ? [`${Math.round(Math.abs(dx))}px ${dx < 0 ? 'left' : 'right'}`] : []),\n ...(Math.abs(dy) > 1 ? [`${Math.round(Math.abs(dy))}px ${dy < 0 ? 'up' : 'down'}`] : []),\n ]\n if (away.length > 0) fault(each, 'shifted', `moved ${away.join(' and ')}`)\n }\n frame = requestAnimationFrame(sample)\n }\n sample()\n Reflect.set(window, key, () => {\n Reflect.deleteProperty(window, key)\n observer.disconnect()\n cancelAnimationFrame(frame)\n return watched.map(each => ({\n element: each.element,\n name: named(each.element),\n faults: each.faults,\n }))\n })\n return elements.length\n}\n\n/**\n * Stops the watch and lists what went wrong. `now` is what the locator\n * resolves to once settled: a watched element gone from the page while one\n * that was not watched stands there was replaced, not only removed.\n */\nconst stopStill = (now: ReadonlyArray<Element>, { key }: StillWatch): ReadonlyArray<string> => {\n const report: ReadonlyArray<{\n readonly element: Element\n readonly name: string\n readonly faults: ReadonlyMap<string, string>\n }> = Reflect.apply(Reflect.get(window, key), undefined, [])\n const newcomer = now.some(element => !report.some(each => each.element === element))\n return report.flatMap(each => {\n const replaced = newcomer && !each.element.isConnected\n return [\n ...[...each.faults].flatMap(([kind, words]) =>\n replaced && kind === 'removed' ? [] : [words],\n ),\n ...(replaced ? [`${each.name} was replaced by a new element`] : []),\n ]\n })\n}\n\nconst stopIfWatching = ({ key }: StillWatch) => {\n const stop: unknown = Reflect.get(window, key)\n if (typeof stop === 'function') stop()\n}\n\n/**\n * The write shows before the server answers, holds still until it has been\n * answered and drawn, and still shows after.\n *\n * Every Remote mutation the page sends is held at the network until `act`\n * has ended and `shows` has been looked for, and for `hold` at least, so\n * what shows was drawn before any answer however long `act` takes;\n * `shows` must be visible within `within` of `act` beginning. From\n * then until settled, what `stays` names must stay in the page as the same\n * nodes, in the same place in their parent, within 1px of where they were\n * drawn, and visible. Settled is evidence, not a wait: no Remote request of\n * the page in flight (an answer can lead to more, such as a placed list's\n * first page under `verifyPredictions`), or `writes.answered`, then the page\n * quiet for three frames. An error the page logs meanwhile fails it too: a\n * `PredictionMismatch` is logged as one. Throws otherwise, when `act` sent\n * no Remote mutation over HTTP, since nothing was then held, and when `act`\n * has not ended 10 seconds (or `hold`, if longer) after it began: one that\n * waits for its own write's answer would wait for good.\n */\nconst optimistic = async (page: Page, options: OptimisticOptions): Promise<void> => {\n const writes = options.writes ?? 'http'\n const hold = millis(options.hold ?? '3 seconds')\n const within = millis(options.within ?? '1 second')\n // Opened once `shows` has been looked for and is watched: no write is\n // answered before, so nothing shown by then is an answer.\n let release = () => {}\n const looked = new Promise<void>(resolve => {\n release = resolve\n })\n const held: Array<Promise<void>> = []\n // Every Remote request from `act` on that is not yet answered.\n const inFlight = new Set<Request>()\n const sent = (request: Request) => {\n if (Option.isSome(remoteOperation(request))) inFlight.add(request)\n }\n // How many have been answered: a quiet that began before the last answer\n // may have ended before the page drew it.\n let answers = 0\n const done = (request: Request) => {\n if (inFlight.delete(request)) answers += 1\n }\n const errors: Array<string> = []\n const logged = (message: ConsoleMessage) => {\n if (message.type() === 'error') errors.push(message.text())\n }\n const thrown = (error: Error) => errors.push(String(error))\n // Let through after `hold`, once looked. The answer is awaited apart from the\n // handler: Playwright passes a request on to the next handler only once this one returns.\n const letThrough = async (route: Route) => {\n await Promise.all([new Promise(resume => setTimeout(resume, hold)), looked])\n await route.fallback()\n }\n const answered = async (request: Request) => {\n const response = await request.response()\n if (response !== null) await response.finished()\n }\n const route = await page.route('**/*', (route, request) => {\n if (writes !== 'http' || !isRemoteMutation(request)) return route.fallback()\n held.push(answered(request))\n return letThrough(route)\n })\n page.on('request', sent)\n page.on('requestfinished', done)\n page.on('requestfailed', done)\n page.on('console', logged)\n page.on('pageerror', thrown)\n const shows = String(options.shows)\n const stays = options.stays ?? 'put'\n const watched =\n stays === 'shown'\n ? Option.none<Locator>()\n : Option.some(stays === 'put' ? options.shows : stays)\n const watch: StillWatch = { key: `__foldkitStill${crypto.randomUUID().replaceAll('-', '')}` }\n let overdue: ReturnType<typeof setTimeout> | undefined\n try {\n const shown = options.shows.waitFor({ state: 'visible', timeout: within }).then(\n () => Option.none<unknown>(),\n (error: unknown) => Option.some(error),\n )\n const acted = Promise.resolve().then(options.act)\n // An action waiting for its own write's answer would wait for good.\n const deadline =\n writes === 'http'\n ? new Promise<false>(resolve => {\n overdue = setTimeout(resolve, Math.max(hold, ACT_LIMIT), false)\n })\n : new Promise<never>(() => {})\n const ended = await Promise.race([acted.then(() => true), deadline])\n if (!ended) {\n release()\n // The action is left running, so its eventual outcome is unobserved\n // here: a rejection after the deadline must not surface as an\n // unhandled rejection.\n void acted.catch(() => {})\n throw new Error(\n `optimistic: the action did not end within ${Math.max(hold, ACT_LIMIT)} ms, and every write is held until it does: does it wait for its own write's answer?`,\n )\n }\n const missed = await shown\n if (Option.isSome(missed))\n throw new Error(`optimistic: ${shows} did not show within ${within} ms of the action`, {\n cause: missed.value,\n })\n if (Option.isSome(watched) && (await watched.value.evaluateAll(watchStill, watch)) === 0)\n throw new Error(`optimistic: ${String(watched.value)}, what stays, matches nothing`)\n release()\n if (writes === 'http') {\n if (held.length === 0)\n throw new Error(`optimistic: ${shows} showed, but the action sent no Remote mutation`)\n } else {\n await writes.answered()\n }\n // Every held write is in flight until answered, and an answer drawn can ask\n // for more: settled once the page asks nothing and stays quiet from after\n // the last answer. The network finishes before the page reads the answer,\n // and an app draws it on a later frame.\n for (;;) {\n const before = answers\n await quiet(page)\n if (inFlight.size === 0 && answers === before) break\n }\n if (Option.isSome(watched)) {\n const faults = await watched.value.evaluateAll(stopStill, watch)\n if (faults.length > 0)\n throw new Error(\n `optimistic: ${String(watched.value)} did not hold still until the write settled:\\n ${faults.join('\\n ')}`,\n )\n }\n if (!(await options.shows.isVisible()))\n throw new Error(\n `optimistic: ${shows} showed while the write was held, but not after its answer`,\n )\n if (errors.length > 0)\n throw new Error(\n `optimistic: the page logged an error while the write settled:\\n ${errors.join('\\n ')}`,\n )\n } finally {\n clearTimeout(overdue)\n release()\n // A check that failed before reading the watch leaves it sampling every frame.\n if (!page.isClosed()) await page.evaluate(stopIfWatching, watch)\n page.off('request', sent)\n page.off('requestfinished', done)\n page.off('requestfailed', done)\n page.off('console', logged)\n page.off('pageerror', thrown)\n await route.dispose()\n await Promise.allSettled(held)\n }\n}\n\nexport interface NeverShowsOptions {\n /** What the page must not show at any moment of `during`. */\n readonly text: string | RegExp\n /**\n * The steps to watch: a reload, a navigation away and back. End it on what\n * the page waits for (an answer, a row), since watching stops once it ends\n * and the page is quiet.\n */\n readonly during: () => Promise<unknown>\n}\n\n/** What the page script needs: the binding to report through, and the text as a pattern. */\ninterface Watch {\n readonly key: string\n readonly source: string\n readonly flags: string\n}\n\n// Runs in the page, in the open document and in each one loaded after: after\n// every change to the document, the rendered text (`innerText` leaves hidden\n// text out) is searched, so a text shown for one frame is seen, not sampled.\nconst watchText = ({ key, source, flags }: Watch) => {\n if (window !== window.top) return\n const pattern = new RegExp(source, flags)\n let reported = false\n const check = () => {\n if (reported) return\n const line = (document.body?.innerText ?? '').split('\\n').find(each => pattern.test(each))\n if (line === undefined) return\n reported = true\n Reflect.apply(Reflect.get(window, key), undefined, [line])\n }\n const observer = new MutationObserver(check)\n observer.observe(document, {\n childList: true,\n subtree: true,\n characterData: true,\n attributes: true,\n })\n Reflect.set(window, `${key}Stop`, () => observer.disconnect())\n check()\n}\n\nconst stopWatching = (key: string) =>\n Reflect.apply(Reflect.get(window, `${key}Stop`), undefined, [])\n\n/**\n * The page never shows `text` while `during` runs, nor until the page is\n * quiet after it: a cached page revisited never reads \"Loading…\", even for\n * one frame. Throws with the line that showed.\n */\nconst neverShows = async (page: Page, options: NeverShowsOptions): Promise<void> => {\n const key = `__foldkitNeverShows${crypto.randomUUID().replaceAll('-', '')}`\n const { text } = options\n const watch: Watch =\n typeof text === 'string'\n ? { key, source: text.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'), flags: '' }\n : { key, source: text.source, flags: text.flags }\n const shown: Array<string> = []\n const binding = await page.exposeBinding(key, (_, line: string) => {\n shown.push(line)\n })\n const script = await page.addInitScript(watchText, watch)\n try {\n await page.evaluate(watchText, watch)\n await options.during()\n await quiet(page)\n } finally {\n await script.dispose()\n if (!page.isClosed()) await page.evaluate(stopWatching, key)\n await binding.dispose()\n }\n if (shown.length > 0)\n throw new Error(`neverShows: the page showed ${String(text)}: \"${shown[0]}\"`)\n}\n\n/**\n * Collects every error the page logs (`console.error`) and every exception it\n * does not catch, from now until the page closes. Read the list at the end.\n */\nconst consoleErrors = (page: Page): (() => ReadonlyArray<string>) => {\n const errors: Array<string> = []\n page.on('console', message => {\n if (message.type() === 'error') errors.push(message.text())\n })\n page.on('pageerror', error => errors.push(String(error)))\n return () => [...errors]\n}\n\n/** Assertions on what a running page shows, for Playwright. */\nexport const Behaviors = { optimistic, neverShows, consoleErrors } as const\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,MAAM,gBAAgB,OAAO,oBAAoB,OAAO,eAAe,iBAAiB,CAAC;;AAGzF,MAAM,mBAAmB,YAAoE;CAC3F,MAAM,OAAO,QAAQ,OAAO,MAAM,SAAS,QAAQ,SAAS,IAAI;CAChE,OAAO,SAAS,OAAO,OAAO,KAAK,IAAI,OAAO,IAAI,cAAc,IAAI,IAAG,SAAQ,KAAK,SAAS;AAC/F;AAEA,MAAM,oBAAoB,YACxB,OAA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KAAK,MAAM,SAAS,OAAO,KAAK,QAAQ,KAAK,CAAC;CAC5D,CAAC;CACD,KAAK,GAAG,cAAa,UAAS,OAAO,KAAK,OAAO,KAAK,CAAC,CAAC;CACxD,aAAa,CAAC,GAAG,MAAM;AACzB;;AAGA,MAAa,YAAY;CAAE;CAAY;CAAY;AAAc"}
@@ -121,13 +121,21 @@ export interface CpuReading {
121
121
  readonly status: number;
122
122
  /** The route's first request in this call: in a fresh stack, a cold isolate's. */
123
123
  readonly cold: number;
124
- /** The mean of the requests after the first. */
124
+ /**
125
+ * The most a request after the first spent, in milliseconds. A deployed
126
+ * Worker's limit applies to each request, not to their mean.
127
+ */
125
128
  readonly warm: number;
126
129
  }
127
130
  export interface CpuBudget {
128
131
  /** The routes, by the name a failure reports them with. */
129
132
  readonly routes: Readonly<Record<string, CpuRoute>>;
130
- /** Milliseconds a warm request may spend. */
133
+ /**
134
+ * Milliseconds each request after the first may spend. A meter's own
135
+ * resolution bounds how small this can be: Windows books a thread's CPU
136
+ * time in 15.6 ms ticks, so a budget near that reads one request's cost
137
+ * as a tick whether it spent it or not.
138
+ */
131
139
  readonly warm: number;
132
140
  /** Milliseconds the first request may spend; unchecked when not given. */
133
141
  readonly cold?: number;
@@ -136,9 +144,10 @@ export interface CpuBudget {
136
144
  }
137
145
  /**
138
146
  * Asks each route once, then `runs` times more, one request at a time, each
139
- * response read in full, and reads what each cost. Throws listing every
140
- * reading when a route spends more than the budget, or answers a 5xx, whose
141
- * cost says nothing of the route's.
147
+ * response read in full, and reads what each cost. Every warm request is
148
+ * checked, since a deployed Worker's limit applies to each rather than to
149
+ * their mean. Throws listing every reading when a route spends more than
150
+ * the budget, or answers a 5xx, whose cost says nothing of the route's.
142
151
  */
143
152
  declare const budget: (meter: CpuMeter, { routes, warm, cold, runs }: CpuBudget) => Promise<ReadonlyArray<CpuReading>>;
144
153
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"workers.d.mts","names":[],"sources":["../../src/testing/workers.ts"],"mapp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AAc;;;;;;;;WAQ1B,KAAK;;;;;;;WAOL,QAAQ,UAAU,kBAAkB;;;;;;;WAOpC,YAAY;;;YAIX,YAAY,KAAK;;iBAGZ;;WAEN;WACA,QAAQ,SAAS,YAAY,QAAQ;;WAErC,aAAa;;;;;;YAOZ,2BAA2B;;iBAGtB;WACN;;WAEA;;WAEA;;;;;WAKA;;iBAGM;;WAEN,QAAQ,SAAS,eAAe;;;;;;;WAOhC;;WAEA;;WAEA;;;;;;;;;cA+IL,SAAM,OACH,YAAQ,QAAA,MAAA,MAAA,QACmB,cACjC,QAAQ,cAAc;;;;;;cAoEnB,WAAQ,SACH,SAAS,YAAY,QAAQ,YAAU,oBAE/C;;;;;;qBAOU;;;;;cAyMP,cAAW,SAAmB,KAAK,sCAAoC;;;;;;cAyBvE,QAAe,KAAG,SAAW,iBAAe,QAAQ,MAAM;;;;;;qBA2PnD"}
@@ -120,9 +120,10 @@ const workerdMeter = (origin, dispatch, spawned) => {
120
120
  };
121
121
  /**
122
122
  * Asks each route once, then `runs` times more, one request at a time, each
123
- * response read in full, and reads what each cost. Throws listing every
124
- * reading when a route spends more than the budget, or answers a 5xx, whose
125
- * cost says nothing of the route's.
123
+ * response read in full, and reads what each cost. Every warm request is
124
+ * checked, since a deployed Worker's limit applies to each rather than to
125
+ * their mean. Throws listing every reading when a route spends more than
126
+ * the budget, or answers a 5xx, whose cost says nothing of the route's.
126
127
  */
127
128
  const budget = async (meter, { routes, warm, cold, runs = 5 }) => {
128
129
  if (!Number.isInteger(runs) || runs < 1) throw new Error(`Cpu.budget: runs must be a whole number from 1, not ${runs}.`);
@@ -139,13 +140,19 @@ const budget = async (meter, { routes, warm, cold, runs = 5 }) => {
139
140
  const start = await meter.spent();
140
141
  await ask();
141
142
  const first = await meter.spent();
142
- for (let run = 0; run < runs; run++) await ask();
143
- const end = await meter.spent();
143
+ let warmest = 0;
144
+ let previous = first;
145
+ for (let run = 0; run < runs; run++) {
146
+ await ask();
147
+ const now = await meter.spent();
148
+ warmest = Math.max(warmest, now - previous);
149
+ previous = now;
150
+ }
144
151
  readings.push({
145
152
  route: name,
146
153
  status,
147
154
  cold: first - start,
148
- warm: (end - first) / runs
155
+ warm: warmest
149
156
  });
150
157
  }
151
158
  const over = readings.filter((reading) => reading.warm > warm || cold !== void 0 && reading.cold > cold);