Code-first video & image, rendered natively on WebGPU.
cli
okanasl2367cbf47123
diff --git a/.changeset/ff-cli.md b/.changeset/ff-cli.mdnew file mode 100644index 00000000..4ca8ef35--- /dev/null+++ b/.changeset/ff-cli.md@@ -0,0 +1,10 @@+---+"framefields": minor+"@framefields/cli": minor+---++Add `framefields.json`, the project manifest, and `ff`, the command line.++- `framefields/project`: `loadProject`, `resolveComposition` and `buildComposition` read a project's compositions from `framefields.json` (or the implicit `src/film.ts#buildFilm`); the JSON Schema ships as `framefields/schemas/project.v1.json`.+- `startPreview({ project, composition })` previews a project's composition, and the page switches between its compositions.+- `@framefields/cli` (`ff`): `ls`, `check`, `frames`, `grid`, `preview`, `render --local` and `init` locally; `auth`, `repo`, `clone`, `push`, `pull`, `asset`, cloud `render`, `issue`, `pr` and `api` for Framefields Cloud.diff --git a/examples/24_audio_capabilities/framefields.json b/examples/24_audio_capabilities/framefields.jsonnew file mode 100644index 00000000..f9947067--- /dev/null+++ b/examples/24_audio_capabilities/framefields.json@@ -0,0 +1,55 @@+{+ "$schema": "https://framefields.dev/schemas/project.v1.json",+ "version": 1,+ "compositions": {+ "showcase": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildAudioShowcase",+ "title": "Audio showcase",+ "default": true+ },+ "step-1": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildStep1InitialAudio",+ "title": "Initial audio",+ "group": "Steps",+ "description": "Clean baseline soundtrack without DSP"+ },+ "step-2": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildStep2FadedAudio",+ "title": "Fade in/out",+ "group": "Steps"+ },+ "step-3": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildStep3FadedReverbAudio",+ "title": "Fade + reverb",+ "group": "Steps"+ },+ "step-4": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildStep4DelayAudio",+ "title": "Delay",+ "group": "Steps"+ },+ "step-5": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildStep5ParametricEqAudio",+ "title": "Parametric EQ",+ "group": "Steps"+ },+ "step-6": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildStep6CompressorAudio",+ "title": "Compressor",+ "group": "Steps"+ },+ "step-7": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildStep7StereoPanningAudio",+ "title": "Stereo panning",+ "group": "Steps"+ }+ }+}diff --git a/packages/cli/README.md b/packages/cli/README.mdnew file mode 100644index 00000000..e91ae717--- /dev/null+++ b/packages/cli/README.md@@ -0,0 +1,64 @@+# @framefields/cli++`ff`: the command line for [framefields](https://www.npmjs.com/package/framefields) projects. It previews, inspects and renders a project's compositions with the `framefields` installed in the project, and works with Framefields Cloud (repositories, asset sync, cloud renders, issues and pull requests) with `gh`-style commands.++```bash+npm install --save-dev @framefields/cli+npx ff ls+```++Design and rationale: [SPEC.md](./SPEC.md).++## The project manifest++`framefields.json` names the compositions. Without one, a project with `src/film.ts` exporting `buildFilm` has a single composition, `film`.++```json+{+ "$schema": "https://framefields.dev/schemas/project.v1.json",+ "version": 1,+ "compositions": {+ "showcase": { "entry": "src/audio.ts", "export": "buildShowcase", "default": true },+ "step-1": { "entry": "src/audio.ts", "export": "buildStep1", "group": "Steps" }+ }+}+```++Wherever a command takes `<composition>`: omit it for the default, pass an id (`step-1`), or point at an unlisted builder with `src/probe.ts#buildProbe` (local commands only).++## Local: the verification ladder++| Command | Writes |+|---|---|+| `ff ls` | Lists compositions |+| `ff check [<composition>…]` | `tsc --noEmit`, then builds each composition and validates its spec |+| `ff frames [<composition>] <frame…>` | `output/frames/<id>/f0060.png`; frames or timecodes (`60`, `2.5s`, `1500ms`, `00:02:15`) |+| `ff grid [<composition>]` | `output/<id>-grid.png` (`--count`, `--columns`, `--cell-width`, `--from`, `--to`) |+| `ff preview [<composition>]` | Live player URL; the page switches between the manifest's compositions |+| `ff render [<composition>] --local` | `output/<id>.mp4` (`--quality`, `--fps`, `--range ..5s`) |++## Cloud++```bash+echo $FF_KEY | ff auth login --with-token # or set FF_TOKEN (and FF_HOST) in CI+ff repo create --push # create, add origin, link, push with assets+ff clone my-film # git clone + verified asset download+ff push / ff pull # git plus framefields.assets.json+ff asset sync | pull | status+ff render step-1 --wait --download # render HEAD (must be pushed) in the cloud+ff issue create --title "…" / ff pr create / ff pr merge 12+ff api /v1/repos+```++## Output contract++- `--json` prints exactly one JSON value on stdout; progress and logs (the engine's included) go to stderr.+- No prompts without a terminal or with `--yes`; a missing value is an error naming the flag to pass.+- Errors: `error: <message>` and ` hint: <command>` on stderr (plus `{ "error": { code, message, hint } }` with `--json`).+- Exit codes: `0` ok, `1` failed, `2` usage, `3` not authenticated or missing scope, `4` project problem, `130` interrupted.++## Files++- Credentials: `~/.config/framefields/hosts.json` (mode 0600). `FF_TOKEN` and `FF_HOST` override it.+- Settings (`ff config`): `~/.config/framefields/config.json`.+- A directory's cloud repository: `git config framefields.repo` and `framefields.host` (never the manifest).diff --git a/packages/cli/SPEC.md b/packages/cli/SPEC.mdnew file mode 100644index 00000000..61a68f9e--- /dev/null+++ b/packages/cli/SPEC.md@@ -0,0 +1,420 @@+# `@framefields/cli` — the `ff` command++Status: **Draft v1** · Owner: engine team · Consumers: developers, coding agents (Claude, Codex), CI, Framefields Cloud++`ff` is the command line for Framefields projects. It does two jobs that today live in every+project's hand-written `src/render.ts`:++1. **Local work** — preview, inspect frames, render grids and videos of a project's compositions.+2. **Cloud work** — repositories, git auth, asset sync, cloud renders, issues and pull requests on+ Framefields Cloud, with `gh`-style ergonomics.++Both halves hinge on one new, small, static file: the project manifest `framefields.json`.++---++## 1. Why++Every example in `examples/` reimplements the same CLI by hand:++| Example | `render.ts` modes | Previewable compositions | Declared where |+|---|---|---|---|+| `19_framefields_film` | video, frames, grid, preview, track | `src/film.ts#buildFilm` | inside `render.ts` |+| `21_full_circle` | video, frames, grid, preview | `src/film.ts#buildFilm` | inside `render.ts` |+| `22_framefields_launch` | video, frames, grid, preview (+ fonts, song, images, precomp scripts) | `src/film.ts#buildFilm` | inside `render.ts` |+| `23_data_story` | video, frames, grid, preview | `src/film.ts#buildFilm` | inside `render.ts` |+| `24_audio_capabilities` | all / preview `<step>` | **8** builders in one file | a hard-coded `stepNames[]` array |++Consequences:++- **Nothing outside the project can tell what is previewable.** The cloud's Preview tab, render+ dispatch and agents see a tree of `.ts` files where most are scenes (`scenes/*.ts` return layers,+ not compositions), utilities (`theme.ts`, `grid.ts`), scripts (`generate-assets.ts`), tests, or+ dozens of `scratch/` probes.+- **Multi-composition projects need bespoke argument parsing** (`pnpm render preview 3` →+ `buildStep3FadedReverbAudio`).+- **The verification ladder** (typecheck → frames → grid → video, see the `framefields-render`+ skill) is re-typed in each project, with different output paths and flags.++## 2. Principles++1. **Agent-first, human-pleasant.** Every command has `--json`; output on stdout is data, progress+ and logs go to stderr. No prompts when stdin is not a TTY (or with `--yes`); a missing required+ value is an error with the exact flag to pass, never a hang.+2. **Static over executable configuration.** What the cloud and agents need to read lives in JSON+ that can be read from git at any commit without running code.+3. **Zero config for the common case.** A project with `src/film.ts` exporting `buildFilm` works+ with no manifest at all.+4. **`gh` parity where it maps.** Same nouns and verbs (`repo create`, `pr merge`, `issue list`,+ `auth login`, `api`), so muscle memory and agent priors transfer.+5. **The project's engine renders.** Local preview/render uses the `framefields` version installed+ in the project, never a copy bundled into the CLI, so output matches the project's lockfile.+6. **Idempotent and resumable.** `ff push`, `ff asset sync` and uploads can be re-run after any+ interruption and converge.++---++## 3. The project manifest: `framefields.json`++### 3.1 Format (v1)++```jsonc+{+ "$schema": "https://framefields.dev/schemas/project.v1.json",+ "version": 1,+ "compositions": {+ "showcase": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildAudioShowcase",+ "title": "Audio showcase",+ "default": true+ },+ "step-1": {+ "entry": "src/audio-pipeline.ts",+ "export": "buildStep1InitialAudio",+ "title": "Initial audio",+ "group": "Steps",+ "description": "Clean baseline soundtrack without DSP"+ }+ },+ // Optional sections; all have defaults.+ "assets": { "directory": "assets", "exclude": ["**/.DS_Store", "scratch/**"] },+ "output": "output"+}+```++| Field | Type | Rules |+|---|---|---|+| `version` | `1` | Optional; defaults to 1. |+| `compositions` | `Record<id, Composition>` | ≥ 1 entry. Insertion order is display order. |+| `id` (key) | string | `^[a-z0-9][a-z0-9-]{0,62}$`. Stable: used in URLs, `ff` arguments, render jobs, notes. |+| `entry` | string | Repo-relative path, no `..`, ends in `.ts` `.tsx` `.mts` `.js` `.mjs`. |+| `export` | string | JS identifier. Defaults to `"default"`. The export is a function returning `Composition` or `Promise<Composition>`. |+| `title` | string ≤ 120 | Defaults to the id, humanised (`step-1` → `Step 1`). |+| `description` | string ≤ 500 | Optional. |+| `group` | string ≤ 60 | Optional. Groups compositions in pickers ("Steps", "Scenes", "Cutdowns"). |+| `default` | boolean | At most one. Without one, the first composition is the default. |+| `assets.directory` | string | Defaults to `assets`. What `ff asset sync` scans. |+| `assets.exclude` | glob[] | Defaults to `["**/.DS_Store"]`. |+| `output` | string | Local render output directory. Defaults to `output`. |++- **Unknown keys are preserved and ignored**, so newer manifests parse with older tools.+- **Only things that can't be computed belong here.** Size, fps and duration come from the+ composition when it loads (as `startPreview` already does), so they can't drift.+- **No manifest ⇒ one implicit composition**+ `{ "film": { "entry": "src/film.ts", "export": "buildFilm", "default": true } }`.+ This is what `ff init` scaffolds and what four of the five examples already use.++### 3.2 Composition references on the command line++Anywhere a command takes `<composition>`:++| Form | Meaning |+|---|---|+| *(omitted)* | The default composition. |+| `step-1` | A manifest id. |+| `src/probe.ts#buildProbe` | An ad-hoc reference to an unlisted builder — for `scratch/` probes. Local commands only; the cloud renders manifest ids or explicit entry/export. |+| `src/probe.ts` | Same, with `export` = `default`. |++### 3.3 Why JSON and not `framefields.config.ts`++The earlier cloud spec proposed `framefields.config.ts`. A TypeScript config can't be read by the+cloud from a git tree, by an agent without executing code, or by tools in another language. The+manifest only holds declarative data, so nothing is lost. Projects that want typed authoring can+generate it; `framefields.json` stays the artifact of record.++### 3.4 Ownership: `framefields/project`++The engine package owns the format so `ff`, `startPreview`, the renderers and the cloud agree:++```ts+// packages/framefields/src/project/index.ts → export "framefields/project"+export const MANIFEST_FILE = "framefields.json";+export const projectManifestSchema: z.ZodType<ProjectManifest>; // the rules in §3.1+export interface ResolvedComposition {+ id: string; entry: string; export: string; title: string;+ description: string | null; group: string | null; default: boolean;+}+export interface Project {+ root: string; // directory containing framefields.json (or package.json)+ source: "manifest" | "default";+ compositions: ResolvedComposition[];+ defaultId: string;+ assets: { directory: string; exclude: string[] };+ output: string;+}+/** Finds the project root from `cwd` upwards and resolves its manifest. Throws ProjectError with a path + message on invalid input. */+export function loadProject(cwd?: string): Promise<Project>;+/** Resolves `<composition>` (id, `file#export`, or undefined) against a project. */+export function resolveComposition(project: Project, ref?: string): ResolvedComposition;+/** Imports the entry and calls the export: the one place that turns a reference into a Composition. */+export function buildComposition(project: Project, ref?: string): Promise<Composition>;+```++- `startPreview` gains `startPreview({ project, composition })` alongside today's `{ entry, export }`.+- The JSON Schema at `https://framefields.dev/schemas/project.v1.json` is generated from the zod+ schema at build time (`scripts/`), so editors validate the file.+- **Framefields Cloud** already implements a compatible reader+ (`framefields-cloud/src/services/project-manifest.ts`) and serves+ `GET /v1/repos/:id/compositions`. When `framefields/project` ships, the cloud should import it+ instead of keeping a copy.++---++## 4. Package++| | |+|---|---|+| Name | `@framefields/cli` |+| Location | `packages/cli` (this folder) |+| Binary | `ff` |+| License | Apache-2.0 (open source, per the repository boundary model) |+| Runtime | Node ≥ 22, ESM. Built with `tsdown` like the other packages. |+| Argument parsing | `citty` or `commander` — subcommands, typed flags, generated `--help`. |+| Dependencies | `framefields/project` (manifest only — tiny), an HTTP client, `@clack/prompts` (TTY only). **Not** the engine. |+| Engine resolution | Local render/preview commands `import()` `framefields` resolved from the **project** directory. If it isn't installed: error `framefields is not installed in <dir> — run: pnpm add framefields`. |++Layout:++```+packages/cli/+ src/+ bin.ts # entry: parses argv, dispatches+ commands/ # one file per noun: auth, init, repo, clone, push, pull, asset,+ # ls, preview, frames, grid, render, check, issue, pr, api, config+ cloud/client.ts # typed REST client for Framefields Cloud (§8)+ cloud/credentials.ts # hosts.json + keychain+ git/ # thin wrappers over the user's git binary+ output.ts # --json, tables, colors, stderr progress+ test/ # unit + golden-output tests; e2e against a local wrangler dev+```++---++## 5. Command reference++Global flags: `--json`, `--yes`, `-C <dir>` (run as if in `<dir>`), `--host <url>`+(default `https://framefields.dev`), `--quiet`, `--verbose`, `--no-color`.++### 5.1 Local (no account needed)++| Command | Does | Replaces |+|---|---|---|+| `ff ls` | Lists compositions: id, title, group, entry#export, default. `--json` emits `Project`. | — |+| `ff check [<composition>…]` | Ladder step 1: `tsc --noEmit` + builds each composition (all by default) and validates `toSpec()` against the program schema. Non-zero exit on any failure. | ad-hoc |+| `ff preview [<composition>]` | `startPreview` for the composition; prints the URL. `--open`, `--port`, `--no-audio`. In the player, compositions from the manifest are switchable. | `pnpm render preview` |+| `ff frames <composition> <frame…>` | Ladder step 2: PNGs to `<output>/frames/<id>/f0060.png`. Accepts frame numbers or timecodes (`2.5s`, `00:02:15`). | `render frames` |+| `ff grid [<composition>]` | Ladder step 3: contact sheet. `--count 16 --columns 4 --cell-width 480 --from --to`. Writes `<output>/<id>-grid.png`. | `render grid` |+| `ff render [<composition>] --local` | Ladder step 5: MP4 to `<output>/<id>.mp4`. `--quality`, `--fps`, `--range`. | `render video` |++All local commands print the files they wrote; with `--json`, `{ "files": [...] }`. Paths are+relative to the project root so agents can open them directly.++### 5.2 Project & repository++| Command | Does | Cloud API |+|---|---|---|+| `ff init [dir] [--template <slug>]` | Scaffolds `src/film.ts`, `framefields.json`, `framefields.assets.json`, `.gitignore`, `package.json` with `framefields`. Templates come from `examples/` (`--template data-story`). | — |+| `ff repo create [name] [--public\|--private] [--push]` | Creates the cloud repo, adds the `origin` remote, links the directory (§6.2). With `--push`, pushes. | `POST /v1/repos` |+| `ff repo view [repo] [--web]` | Name, visibility, default branch, remote, compositions. | `GET /v1/repos/:id`, `/compositions` |+| `ff repo list` | Repos in the active organization. | `GET /v1/repos` |+| `ff repo fork <repo> [--name] [--clone]` | Forks; shares assets server-side. | `POST /v1/repos/:id/fork` |+| `ff repo delete <repo> --yes` | Deletes. Requires `--yes` or typing the name. | `DELETE /v1/repos/:id` |+| `ff clone <repo> [dir]` | `git clone` with the credential helper, then `ff asset pull`. | `POST /v1/repos/:id/tokens`, `GET /v1/assets/:sha` |++### 5.3 Sync++| Command | Does | Cloud API |+|---|---|---|+| `ff push [remote] [branch]` | 1. `ff asset sync`. 2. If `framefields.assets.json` changed, commit it (`assets: sync external assets`). 3. `git push`. 4. Report the ref's lockfile. | `POST /v1/repos/:id/assets/diff`, upload endpoints, `PUT /v1/repos/:id/asset-refs` |+| `ff pull [remote] [branch]` | `git pull`, then `ff asset pull`. | `GET /v1/assets/:sha` |+| `ff asset sync [--dry-run]` | Hash `assets.directory`, upload what the cloud lacks (resumable multipart), rewrite the lockfile. No git. | as above |+| `ff asset pull [--force]` | Download lockfile entries missing on disk; verify SHA-256. | `GET /v1/assets/:sha` |+| `ff asset status` | Local vs lockfile vs cloud: new, modified, missing, unreferenced. | `POST /v1/assets/diff` |++Branch deletion: `ff push --delete <branch>` also calls `DELETE /v1/repos/:id/asset-refs?ref=…`.++### 5.4 Cloud renders++| Command | Does | Cloud API |+|---|---|---|+| `ff render [<composition>]` | Dispatches the composition at `HEAD` (must be pushed; otherwise error with `ff push` hint). `--ref`, `--type video\|frame\|sheet`, `--fps`, `--quality`, `--wait`, `--download`. Prints the job id (and URL). | `POST /v1/renders` with `composition` |+| `ff render status <job> [--watch]` | Status, progress, deliverable URL. | `GET /v1/renders/:id` |+| `ff render list [--status] [--composition]` | Jobs for the linked repo. | `GET /v1/renders?repositoryId=` |+| `ff render download <job> [-o file]` | Saves the deliverable. | `downloadUrl` from status |+| `ff render cancel <job>` | Cancels a queued/running job. | **gap** (§8.2) |++`--local` on `ff render` switches to §5.1 behaviour; the two never mix silently.++### 5.5 Issues & pull requests (`gh` parity)++Issues and pull requests share one number sequence per repository, as on GitHub.++| Command | Cloud API |+|---|---|+| `ff issue list [--state open\|closed\|all] [--search q]` | `GET /v1/repos/:id/issues` |+| `ff issue create --title --body [--label]…` (`--body-file -` reads stdin) | `POST /v1/repos/:id/issues` |+| `ff issue view <n> [--comments]` | `GET /v1/repos/:id/issues/:n` |+| `ff issue comment <n> --body` | `POST /v1/repos/:id/issues/:n/comments` |+| `ff issue close <n> [--comment]` / `reopen <n>` / `edit <n> --title --add-label --remove-label` | `PATCH /v1/repos/:id/issues/:n` |+| `ff pr create [--base] [--head] --title --body [--draft]` (head defaults to the current branch; pushes it first if needed) | `POST /v1/repos/:id/pulls` |+| `ff pr list` / `view` / `comment` / `close` / `reopen` / `ready <n>` | `/v1/repos/:id/pulls…` |+| `ff pr merge <n>` | Merges `head` into `base` with local git and pushes, **then** records it: `POST /v1/repos/:id/pulls/:n/merge`. Today the cloud only records merges, so the git half is the CLI's job. |+| `ff pr checkout <n>` | Fetches and checks out the head branch. |++### 5.6 Auth, config, escape hatch++| Command | Does |+|---|---|+| `ff auth login [--with-token]` | TTY: opens the browser to create an API key and pastes it back. Non-TTY: reads the key from stdin (`echo $KEY \| ff auth login --with-token`). Verifies with `GET /v1/organization`. |+| `ff auth status` | Host, organization, key prefix, scopes, expiry. |+| `ff auth logout` | Removes the stored key. |+| `ff auth setup-git` | Installs `ff` as git's credential helper for the cloud host (§6.3). |+| `ff config get\|set <key> [value]` | `host`, `editor`, `browser`, `prompt` (per user, `~/.config/framefields/config.json`). |+| `ff api <path> [-X method] [-f key=value] [--input file]` | Authenticated raw request, like `gh api`. |++---++## 6. Accounts, linking and git++### 6.1 Credentials++- Stored per host in `~/.config/framefields/hosts.json` (mode 0600), or the OS keychain when+ available. Shape: `{ "framefields.dev": { "apiKey": "ff_…", "organization": "org_…" } }`.+- `FF_TOKEN` and `FF_HOST` environment variables override the file — the CI and agent sandbox path.+- Keys are Framefields API keys (`ff_…`) with scopes (`repo:read`, `repo:write`, `render:create`,+ `assets:sync`, `admin`); a command needing a missing scope fails with the scope name.++### 6.2 Linking a directory to a cloud repo++`ff repo create` and `ff clone` write the repo id into **local git config**, not into the+manifest (the manifest is portable across hosts and forks):++```+git config framefields.repo repo_87123+git config framefields.host framefields.dev+```++Fallback when unset: look up `origin`'s URL among `GET /v1/repos` and offer to link.++### 6.3 Git authentication++Artifacts git tokens are short-lived, so they are never written to disk. `ff auth setup-git`+registers `ff auth git-credential` as a credential helper scoped to the Artifacts host; on each+git operation it mints a token (`POST /v1/repos/:id/tokens`, `scope` from the operation, 1 h TTL)+and hands it to git. `ff push`/`pull`/`clone` work without setup by passing the header for that one+invocation.++---++## 7. Output contract++- `--json` prints exactly one JSON value on stdout. Field names match the cloud API (camelCase).+- Human output: tables for lists, `key: value` for views, paths for written files.+- Exit codes:++| Code | Meaning |+|---|---|+| 0 | Success |+| 1 | Command failed (composition error, render failed, API 4xx/5xx) |+| 2 | Usage error (unknown flag, bad composition reference) |+| 3 | Not authenticated / missing scope |+| 4 | Project problem (no project found, invalid `framefields.json`, engine not installed) |+| 130 | Interrupted |++- Errors on stderr: one line `error: <message>`, then an indented `hint:` with the exact command to+ run. With `--json`, also `{ "error": { "code", "message", "hint" } }` on stdout.++Example:++```+$ ff render step-9+error: unknown composition 'step-9'+ hint: compositions in framefields.json: showcase, step-1 … step-7 (ff ls)+```++---++## 8. Cloud API++### 8.1 Used as-is++`/v1/repos` (list, create, get, patch, delete, fork, tokens, branches, compositions, bundle),+`/v1/repos/:id/assets/diff`, `/v1/repos/:id/asset-refs`, `/v1/assets/*` (diff, upload parts,+confirm, download), `/v1/renders` (list, create with `composition`, get),+`/v1/repos/:id/{issues,pulls}/*`, `/v1/api-keys`, `/v1/organization`.++### 8.2 Gaps to add in Framefields Cloud++| Need | Proposed endpoint |+|---|---|+| `ff render cancel` | `POST /v1/renders/:id/cancel` |+| `ff render --wait` without polling | `GET /v1/renders/:id/events` (SSE) — polling `GET /v1/renders/:id` is the v1 fallback |+| Link by remote URL | `GET /v1/repos?remote=<url>` |+| Real compositions/bundles | The cloud's `readRepoFiles` currently returns starter files; it needs tree/blob reads from Artifacts at a ref. |+| Render download | `GET /v1/renders/:id/download` (302 to a signed URL) |++---++## 9. Migrating the examples++Each example gains a `framefields.json`; its `render.ts` becomes optional (keep it only for+project-specific steps such as asset generation).++- `19`, `21`, `22`, `23`: no manifest needed (default `film`). Add one only to set a title.+ `19`'s `render-track.ts` and `22`'s `precomp.ts` stay scripts — they aren't compositions.+- `24_audio_capabilities`:++```json+{+ "$schema": "https://framefields.dev/schemas/project.v1.json",+ "version": 1,+ "compositions": {+ "showcase": { "entry": "src/audio-pipeline.ts", "export": "buildAudioShowcase", "title": "Audio showcase", "default": true },+ "step-1": { "entry": "src/audio-pipeline.ts", "export": "buildStep1InitialAudio", "title": "Initial audio", "group": "Steps" },+ "step-2": { "entry": "src/audio-pipeline.ts", "export": "buildStep2FadedAudio", "title": "Fade in/out", "group": "Steps" },+ "step-3": { "entry": "src/audio-pipeline.ts", "export": "buildStep3FadedReverbAudio", "title": "Fade + reverb", "group": "Steps" },+ "step-4": { "entry": "src/audio-pipeline.ts", "export": "buildStep4DelayAudio", "title": "Delay", "group": "Steps" },+ "step-5": { "entry": "src/audio-pipeline.ts", "export": "buildStep5ParametricEqAudio", "title": "Parametric EQ", "group": "Steps" },+ "step-6": { "entry": "src/audio-pipeline.ts", "export": "buildStep6CompressorAudio", "title": "Compressor", "group": "Steps" },+ "step-7": { "entry": "src/audio-pipeline.ts", "export": "buildStep7StereoPanningAudio", "title": "Stereo panning", "group": "Steps" }+ }+}+```++ `pnpm preview 3` becomes `ff preview step-3`.++- Scenes (`scenes/*.ts`) are not compositions and should not be listed. A later manifest version+ may add `chapters` (named frame ranges) so scenes appear as timeline markers in players.++The agent plugin (`plugins/framefields`) updates its `framefields` and `framefields-render`+skills to use `ff check` / `ff frames` / `ff grid` / `ff render --local` for the verification+ladder instead of inline scripts.++---++## 10. Milestones++| # | Scope | Done when |+|---|---|---|+| M1 | `framefields/project` (schema, `loadProject`, `resolveComposition`, `buildComposition`), JSON Schema generation, `startPreview({ project, composition })` | Unit tests cover §3.1 rules; `24_audio_capabilities` has a manifest. |+| M2 | `ff` local: `ls`, `check`, `preview`, `frames`, `grid`, `render --local`, `init` | All five examples work via `ff` with no `render.ts` changes; golden tests for output and exit codes. |+| M3 | Auth + repos + sync: `auth *`, `repo *`, `clone`, `push`, `pull`, `asset *`, credential helper | E2E against `wrangler dev --env dev`: create → push with assets → clone elsewhere → assets restored, hashes verified. |+| M4 | Cloud renders + issues/PRs: `render` (cloud), `render status/list/download`, `issue *`, `pr *`, `api` | E2E: dispatch by composition id; PR create → merge with git push. |+| M5 | Cloud gaps from §8.2; plugin skills switched to `ff` | Agents complete the verification ladder and a cloud render using only `ff`. |++Testing: commands are thin over a core that takes `(args, io, env)`, so unit tests run without a+terminal; the cloud client is tested against the real worker via `wrangler dev`; local render+commands run on the existing headless renderer in CI.++## 11. Open questions++1. **Command name.** `ff` is short but collides with some shell aliases (e.g. fast-forward git+ aliases). Ship `framefields` as an alias binary.+2. **Ad-hoc refs in the cloud.** Should `POST /v1/renders` accept `file#export` for unlisted+ builders, or require manifest ids (keeps the cloud's view of a repo authoritative)? Draft: ids+ or explicit entry/export, no `#` parsing server-side.+3. **Per-composition render defaults** (fps, quality, poster frame) in the manifest — useful, but+ only once a real need appears; computed metadata must stay out.+4. **Monorepos.** One `framefields.json` per package, found by walking up from `-C`/cwd; the cloud+ assumes the manifest at the repo root for now.diff --git a/packages/cli/package.json b/packages/cli/package.jsonnew file mode 100644index 00000000..6d6eda87--- /dev/null+++ b/packages/cli/package.json@@ -0,0 +1,49 @@+{+ "name": "@framefields/cli",+ "version": "2.0.8",+ "private": false,+ "description": "ff: the command line for Framefields projects. Preview, inspect and render compositions locally; sync, render and collaborate on Framefields Cloud.",+ "license": "Apache-2.0",+ "homepage": "https://gatewai.studio",+ "repository": {+ "type": "git",+ "url": "https://github.com/gatewai-dev/framefields.git",+ "directory": "packages/cli"+ },+ "publishConfig": {+ "access": "public"+ },+ "type": "module",+ "bin": {+ "ff": "./dist/bin.mjs",+ "framefields": "./dist/bin.mjs"+ },+ "files": [+ "dist/**",+ "SPEC.md"+ ],+ "engines": {+ "node": ">=22"+ },+ "scripts": {+ "build": "tsdown",+ "dev": "tsdown --watch",+ "clean": "rm -rf dist .turbo",+ "typecheck": "tsc --noEmit -p .",+ "test": "vitest run"+ },+ "dependencies": {+ "@clack/prompts": "^1.8.1",+ "commander": "^14.0.0",+ "tsx": "^4.20.3",+ "zod": "^4.3.6"+ },+ "devDependencies": {+ "@framefields/tsconfig": "workspace:*",+ "@types/node": "^24.1.0",+ "framefields": "workspace:*",+ "tsdown": "^0.19.0",+ "typescript": "^5.8.3",+ "vitest": "4.1.5"+ }+}diff --git a/packages/cli/src/assets.ts b/packages/cli/src/assets.tsnew file mode 100644index 00000000..5ebe9fbe--- /dev/null+++ b/packages/cli/src/assets.ts@@ -0,0 +1,491 @@+/**+ * External assets: files under `assets.directory` live in Framefields Cloud+ * blob storage, addressed by SHA-256, and `framefields.assets.json` (committed+ * to git) maps each path to its hash. Every step can be re-run after an+ * interruption: hashes are cached, the server resumes multipart uploads, and+ * downloads land in a temp file that is verified before it replaces anything.+ */+import { createHash } from "node:crypto";+import fs from "node:fs";+import path from "node:path";+import { Readable } from "node:stream";+import { pipeline } from "node:stream/promises";+import type { Project } from "framefields/project";+import type {+ AssetClaim,+ AssetDiff,+ AssetLockfile,+ CloudClient,+ RequestBody,+ UploadTicket,+} from "./cloud/client.js";+import { CliError } from "./errors.js";+import { matchesAny } from "./glob.js";++export const LOCKFILE = "framefields.assets.json";+export const LOCKFILE_SCHEMA = "https://framefields.dev/schemas/assets.v1.json";+const CACHE_FILE = path.join(".framefields", "asset-hashes.json");++export interface LocalAsset {+ /** Project-relative, forward slashes: the lockfile key. */+ path: string;+ sha256: string;+ size: number;+ mimeType: string;+}++// ── Scanning ──++/** Every file under the assets directory, minus exclusions, hashed (with a size+mtime cache). */+export async function scanAssets(project: Project): Promise<LocalAsset[]> {+ const dir = path.join(project.root, project.assets.directory);+ if (!fs.existsSync(dir)) return [];+ const cacheFile = path.join(project.root, CACHE_FILE);+ const cache = readCache(cacheFile);+ const next: HashCache = {};+ const assets: LocalAsset[] = [];+ for (const abs of walk(dir)) {+ const fromRoot = toPosix(path.relative(project.root, abs));+ const fromDir = toPosix(path.relative(dir, abs));+ if (+ matchesAny(project.assets.exclude, fromRoot) ||+ matchesAny(project.assets.exclude, fromDir)+ )+ continue;+ const stat = fs.statSync(abs);+ const key = `${stat.size}:${stat.mtimeMs}`;+ const sha256 =+ cache[fromRoot]?.key === key+ ? cache[fromRoot].sha256+ : await hashFile(abs);+ next[fromRoot] = { key, sha256 };+ assets.push({+ path: fromRoot,+ sha256,+ size: stat.size,+ mimeType: mimeType(abs),+ });+ }+ writeCache(cacheFile, next);+ return assets.sort((a, b) => a.path.localeCompare(b.path));+}++function* walk(dir: string): Generator<string> {+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {+ const abs = path.join(dir, entry.name);+ if (entry.isDirectory()) yield* walk(abs);+ else if (entry.isFile()) yield abs;+ }+}++export async function hashFile(file: string): Promise<string> {+ const hash = createHash("sha256");+ await pipeline(fs.createReadStream(file), hash);+ return hash.digest("hex");+}++type HashCache = Record<string, { key: string; sha256: string }>;++function readCache(file: string): HashCache {+ try {+ return JSON.parse(fs.readFileSync(file, "utf8")) as HashCache;+ } catch {+ return {};+ }+}++function writeCache(file: string, cache: HashCache) {+ try {+ fs.mkdirSync(path.dirname(file), { recursive: true });+ // `.framefields` keeps itself out of git, as the preview's notes do.+ const ignore = path.join(path.dirname(file), ".gitignore");+ if (!fs.existsSync(ignore)) fs.writeFileSync(ignore, "*\n");+ fs.writeFileSync(file, JSON.stringify(cache));+ } catch {+ // Only a cache.+ }+}++const toPosix = (p: string) => p.split(path.sep).join("/");++const MIME: Record<string, string> = {+ ".png": "image/png",+ ".jpg": "image/jpeg",+ ".jpeg": "image/jpeg",+ ".webp": "image/webp",+ ".gif": "image/gif",+ ".svg": "image/svg+xml",+ ".avif": "image/avif",+ ".mp4": "video/mp4",+ ".mov": "video/quicktime",+ ".webm": "video/webm",+ ".mkv": "video/x-matroska",+ ".mp3": "audio/mpeg",+ ".wav": "audio/wav",+ ".m4a": "audio/mp4",+ ".aac": "audio/aac",+ ".ogg": "audio/ogg",+ ".flac": "audio/flac",+ ".ttf": "font/ttf",+ ".otf": "font/otf",+ ".woff": "font/woff",+ ".woff2": "font/woff2",+ ".glb": "model/gltf-binary",+ ".gltf": "model/gltf+json",+ ".obj": "model/obj",+ ".onnx": "application/octet-stream",+ ".json": "application/json",+ ".lottie": "application/zip",+ ".cube": "text/plain",+ ".srt": "text/plain",+ ".vtt": "text/vtt",+ ".txt": "text/plain",+};++export const mimeType = (file: string) =>+ MIME[path.extname(file).toLowerCase()] ?? "application/octet-stream";++// ── Lockfile ──++export function lockfilePath(project: Project): string {+ return path.join(project.root, LOCKFILE);+}++export function readLockfile(project: Project): AssetLockfile | undefined {+ const file = lockfilePath(project);+ if (!fs.existsSync(file)) return undefined;+ try {+ const data = JSON.parse(fs.readFileSync(file, "utf8")) as AssetLockfile;+ return { ...data, assets: data.assets ?? {} };+ } catch (err) {+ throw new CliError(+ `${LOCKFILE} is not valid JSON: ${(err as Error).message}`,+ { code: "project" },+ );+ }+}++/** The lockfile for `assets`, keeping fields of unchanged entries (and unknown top-level keys). */+export function buildLockfile(+ previous: AssetLockfile | undefined,+ assets: LocalAsset[],+ repositoryId?: string,+): AssetLockfile {+ const entries: AssetLockfile["assets"] = {};+ for (const a of assets) {+ const old = previous?.assets[a.path];+ entries[a.path] =+ old?.sha256 === a.sha256+ ? { ...old, size: a.size, mimeType: a.mimeType }+ : {+ sha256: a.sha256,+ size: a.size,+ mimeType: a.mimeType,+ uploadedAt: new Date().toISOString(),+ };+ }+ return {+ ...previous,+ $schema: previous?.$schema ?? LOCKFILE_SCHEMA,+ version: previous?.version ?? 1,+ ...(repositoryId && { repository: repositoryId }),+ assets: entries,+ };+}++export const serializeLockfile = (lock: AssetLockfile) =>+ `${JSON.stringify(lock, null, "\t")}\n`;++/** Writes the lockfile if its content changed; true when it did. */+export function writeLockfile(project: Project, lock: AssetLockfile): boolean {+ const file = lockfilePath(project);+ const text = serializeLockfile(lock);+ const old = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : undefined;+ if (old !== undefined && sameAssets(old, lock)) return false;+ fs.writeFileSync(file, text);+ return true;+}++/** Equal up to formatting and `uploadedAt` stamps. */+function sameAssets(oldText: string, lock: AssetLockfile): boolean {+ try {+ const old = JSON.parse(oldText) as AssetLockfile;+ const strip = (l: AssetLockfile) =>+ JSON.stringify({+ ...l,+ assets: Object.fromEntries(+ Object.entries(l.assets ?? {})+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([k, { uploadedAt: _, ...v }]) => [k, v]),+ ),+ });+ return strip(old) === strip(lock);+ } catch {+ return false;+ }+}++// ── Sync (upload) ──++export interface SyncPlan {+ assets: LocalAsset[];+ /** Hashes the cloud already holds. */+ present: string[];+ /** Tickets for hashes it lacks. */+ missing: UploadTicket[];+ /** Lockfile paths that are no longer on disk. */+ removed: string[];+ skipped: { path: string; reason: string }[];+}++export async function planSync(+ client: CloudClient,+ repoId: string | undefined,+ project: Project,+): Promise<SyncPlan> {+ const scanned = await scanAssets(project);+ const skipped = scanned+ .filter((a) => a.size === 0)+ .map((a) => ({ path: a.path, reason: "empty file" }));+ const assets = scanned.filter((a) => a.size > 0);+ const lock = readLockfile(project);+ const onDisk = new Set(assets.map((a) => a.path));+ const removed = Object.keys(lock?.assets ?? {}).filter((p) => !onDisk.has(p));+ const diff: AssetDiff = assets.length+ ? await client.assetsDiff(+ repoId,+ assets.map<AssetClaim>((a) => ({+ path: a.path,+ sha256: a.sha256,+ size: a.size,+ mimeType: a.mimeType,+ })),+ )+ : { present: [], missing: [] };+ return {+ assets,+ present: diff.present,+ missing: diff.missing,+ removed,+ skipped,+ };+}++export type UploadProgress = (event: {+ path: string;+ sha256: string;+ bytes: number;+ total: number;+ done?: boolean;+}) => void;++/** Uploads one asset per its ticket, skipping parts the server already has, then confirms. */+export async function upload(+ client: CloudClient,+ ticket: UploadTicket,+ file: string,+ size: number,+ progress?: UploadProgress,+ label = file,+) {+ const report = (bytes: number, done?: boolean) =>+ progress?.({+ path: label,+ sha256: ticket.sha256,+ bytes,+ total: size,+ done,+ });+ if (ticket.transport === "direct") {+ const res = await client.raw(ticket.method, ticket.url, {+ anonymous: !ticket.url.startsWith(client.host),+ headers: { ...ticket.headers, "Content-Length": String(size) },+ rawBody: Readable.toWeb(+ fs.createReadStream(file),+ ) as unknown as RequestBody,+ duplex: true,+ });+ if (!res.ok)+ throw new CliError(+ `upload of ${label} failed: HTTP ${res.status} ${await res.text().catch(() => "")}`.trim(),+ );+ report(size);+ } else {+ const done = new Set(ticket.uploadedParts);+ let sent = [...done].reduce(+ (sum, n) => sum + partLength(n, ticket.partSize, ticket.partCount, size),+ 0,+ );+ report(sent);+ for (let n = 1; n <= ticket.partCount; n++) {+ if (done.has(n)) continue;+ const length = partLength(n, ticket.partSize, ticket.partCount, size);+ const start = (n - 1) * ticket.partSize;+ const res = await client.raw("PUT", `${ticket.partUrl}${n}`, {+ headers: {+ "Content-Type": "application/octet-stream",+ "Content-Length": String(length),+ },+ rawBody: Readable.toWeb(+ fs.createReadStream(file, { start, end: start + length - 1 }),+ ) as unknown as RequestBody,+ duplex: true,+ });+ if (!res.ok) {+ throw new CliError(+ `upload of ${label} (part ${n}/${ticket.partCount}) failed: HTTP ${res.status} ${await res.text().catch(() => "")}`.trim(),+ {+ hint: "run the command again to resume",+ },+ );+ }+ sent += length;+ report(sent);+ }+ }+ await client.confirmUpload(ticket.confirmUrl);+ report(size, true);+}++const partLength = (+ n: number,+ partSize: number,+ count: number,+ size: number,+) => (n < count ? partSize : size - partSize * (count - 1));++// ── Pull (download) ──++export interface PullResult {+ downloaded: string[];+ present: string[];+ failed: { path: string; error: string }[];+}++/** Downloads lockfile entries missing on disk (or all, with `force`), verifying each SHA-256. */+export async function pullAssets(+ client: CloudClient,+ project: Project,+ options: { force?: boolean; onFile?: (path: string) => void } = {},+): Promise<PullResult> {+ const lock = readLockfile(project);+ const result: PullResult = { downloaded: [], present: [], failed: [] };+ if (!lock) return result;+ for (const [rel, entry] of Object.entries(lock.assets)) {+ const file = path.resolve(project.root, rel);+ if (path.relative(project.root, file).startsWith("..")) {+ result.failed.push({ path: rel, error: "path is outside the project" });+ continue;+ }+ const size = entry.size ?? entry.sizeBytes;+ if (!options.force && fs.existsSync(file)) {+ const stat = fs.statSync(file);+ if (size === undefined || stat.size === size) {+ result.present.push(rel);+ continue;+ }+ }+ options.onFile?.(rel);+ try {+ await downloadBlob(client, entry.sha256, file);+ result.downloaded.push(rel);+ } catch (err) {+ result.failed.push({ path: rel, error: (err as Error).message });+ }+ }+ return result;+}++async function downloadBlob(client: CloudClient, sha256: string, file: string) {+ client.requireToken();+ // The server answers with the bytes or a redirect to a signed URL; fetch+ // drops the Authorization header on cross-origin redirects.+ const res = await client.raw("GET", `/v1/assets/${sha256}`);+ if (!res.ok || !res.body) throw new CliError(`HTTP ${res.status}`);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ const tmp = `${file}.ff-download`;+ const hash = createHash("sha256");+ const out = fs.createWriteStream(tmp);+ try {+ await pipeline(+ Readable.fromWeb(res.body as never),+ async function* (source) {+ for await (const chunk of source) {+ hash.update(chunk as Buffer);+ yield chunk;+ }+ },+ out,+ );+ const actual = hash.digest("hex");+ if (actual !== sha256)+ throw new CliError(+ `checksum mismatch (expected ${sha256.slice(0, 12)}…, got ${actual.slice(0, 12)}…)`,+ );+ fs.renameSync(tmp, file);+ } finally {+ fs.rmSync(tmp, { force: true });+ }+}++// ── Status ──++export interface AssetStatus {+ /** On disk, not in the lockfile. */+ new: string[];+ /** On disk with a different hash than the lockfile. */+ modified: string[];+ /** In the lockfile, not on disk (`ff asset pull`). */+ missing: string[];+ /** In the lockfile, but the cloud doesn't hold the blob (`ff asset sync`). */+ notUploaded: string[];+ /** Unchanged and uploaded. */+ ok: string[];+}++export async function assetStatus(+ client: CloudClient | undefined,+ repoId: string | undefined,+ project: Project,+): Promise<AssetStatus> {+ // Empty files are never synced (the cloud stores no zero-byte blobs).+ const local = (await scanAssets(project)).filter((a) => a.size > 0);+ const lock = readLockfile(project)?.assets ?? {};+ const byPath = new Map(local.map((a) => [a.path, a]));+ const status: AssetStatus = {+ new: [],+ modified: [],+ missing: [],+ notUploaded: [],+ ok: [],+ };+ for (const a of local) {+ const entry = lock[a.path];+ if (!entry) status.new.push(a.path);+ else if (entry.sha256 !== a.sha256) status.modified.push(a.path);+ }+ for (const p of Object.keys(lock)) if (!byPath.has(p)) status.missing.push(p);+ const locked = Object.entries(lock).filter(+ ([, e]) => (e.size ?? e.sizeBytes ?? 0) > 0,+ );+ let held = new Set<string>(locked.map(([, e]) => e.sha256));+ if (client?.token && locked.length) {+ const diff = await client.assetsDiff(+ repoId,+ locked.map(([p, e]) => ({+ path: p,+ sha256: e.sha256,+ size: (e.size ?? e.sizeBytes) as number,+ mimeType: e.mimeType ?? mimeType(p),+ })),+ );+ held = new Set(diff.present);+ }+ for (const [p, e] of Object.entries(lock)) {+ if (!held.has(e.sha256) && (e.size ?? e.sizeBytes ?? 0) > 0)+ status.notUploaded.push(p);+ else if (!status.modified.includes(p) && !status.missing.includes(p))+ status.ok.push(p);+ }+ return status;+}diff --git a/packages/cli/src/bin.ts b/packages/cli/src/bin.tsnew file mode 100644index 00000000..e6ef61cb--- /dev/null+++ b/packages/cli/src/bin.ts@@ -0,0 +1,14 @@+#!/usr/bin/env node+import { run } from "./cli.js";+import { EXIT } from "./errors.js";+import { processIo } from "./output.js";++process.on("SIGINT", () => process.exit(EXIT.interrupted));++const code = await run(process.argv.slice(2), {+ io: processIo(),+ env: process.env,+ cwd: process.cwd(),+});+// Engines and preview servers can hold the event loop open; the command is done.+process.exit(code);diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.tsnew file mode 100644index 00000000..ca726351--- /dev/null+++ b/packages/cli/src/cli.ts@@ -0,0 +1,146 @@+/**+ * The `ff` command line. `run()` is the whole CLI as a function of+ * `(args, io, env, cwd)`, so tests drive it without a terminal; `bin.ts` wires+ * it to the process.+ */+import { Command, CommanderError } from "commander";+import * as api from "./commands/api.js";+import * as asset from "./commands/asset.js";+import * as auth from "./commands/auth.js";+import * as check from "./commands/check.js";+import * as clone from "./commands/clone.js";+import * as config from "./commands/config.js";+import * as frames from "./commands/frames.js";+import * as grid from "./commands/grid.js";+import * as init from "./commands/init.js";+import * as issue from "./commands/issue.js";+import * as ls from "./commands/ls.js";+import * as pr from "./commands/pr.js";+import * as preview from "./commands/preview.js";+import * as render from "./commands/render.js";+import * as repo from "./commands/repo.js";+import * as sync from "./commands/sync.js";+import { Context, type Deps, type GlobalOptions } from "./context.js";+import { CliError, EXIT } from "./errors.js";+import { Output } from "./output.js";+import { VERSION } from "./version.js";++// biome-ignore lint/suspicious/noExplicitAny: commander passes positional arguments untyped+export type Handler = (ctx: Context, ...args: any[]) => Promise<void>;+// biome-ignore lint/suspicious/noExplicitAny: see Handler+export type Wrap = (handler: Handler) => (...args: any[]) => Promise<void>;++export function buildProgram(deps: Deps): Command {+ const program = new Command("ff")+ .description(+ "The command line for Framefields projects: preview and render compositions, and work with Framefields Cloud.",+ )+ .version(VERSION, "-V, --version")+ .option("--json", "print one JSON value on stdout")+ .option("--yes", "never prompt; assume yes for confirmations")+ .option("-C, --directory <dir>", "run as if started in <dir>")+ .option(+ "--host <url>",+ "Framefields Cloud host (default https://framefields.dev)",+ )+ .option("-q, --quiet", "no progress output on stderr")+ .option("--verbose", "more output on stderr")+ .option("--no-color", "no colors")+ .showHelpAfterError("(run with --help for usage)")+ .configureOutput({+ writeOut: (t) => deps.io.stdout(t),+ writeErr: (t) => deps.io.stderr(t),+ outputError: (t, write) => write(t),+ })+ .exitOverride();++ const wrap: Wrap =+ (handler) =>+ async (...args) => {+ const command = args[args.length - 1] as Command;+ const globals = command.optsWithGlobals() as GlobalOptions;+ const ctx = new Context(globals, deps);+ // commander passes (...operands, options, command); handlers take (ctx, ...operands, options).+ await handler(ctx, ...args.slice(0, -1));+ };++ for (const mod of [+ ls,+ check,+ preview,+ frames,+ grid,+ render,+ init,+ auth,+ config,+ repo,+ clone,+ sync,+ asset,+ issue,+ pr,+ api,+ ]) {+ mod.register(program, wrap);+ }+ // Subcommands inherit the global options' help text and error handling.+ const configure = (cmd: Command) => {+ cmd.exitOverride();+ cmd.configureOutput(program.configureOutput());+ cmd.showHelpAfterError("(run with --help for usage)");+ for (const sub of cmd.commands) configure(sub);+ };+ for (const cmd of program.commands) configure(cmd);+ return program;+}++/** Runs `ff` with `args` (without `node ff`) and returns the exit code. */+export async function run(args: string[], deps: Deps): Promise<number> {+ const program = buildProgram(deps);+ try {+ await program.parseAsync(args, { from: "user" });+ return EXIT.ok;+ } catch (err) {+ if (err instanceof CommanderError) {+ // --help and --version end here too.+ if (err.exitCode === 0) return EXIT.ok;+ return EXIT.usage;+ }+ return report(err, args, deps);+ }+}++function report(err: unknown, args: string[], deps: Deps): number {+ const json = args.includes("--json");+ const cliError =+ err instanceof CliError+ ? err+ : new CliError(err instanceof Error ? err.message : String(err), {+ cause: err,+ });+ const out = new Output(deps.io, {+ json,+ quiet: false,+ verbose: false,+ color:+ !args.includes("--no-color") &&+ deps.io.colorSupported &&+ deps.env.NO_COLOR === undefined,+ });+ deps.io.stderr(`${out.style("red", "error:")} ${cliError.message}\n`);+ if (cliError.hint) deps.io.stderr(` hint: ${cliError.hint}\n`);+ if (+ args.includes("--verbose") &&+ err instanceof Error &&+ !(err instanceof CliError)+ ) {+ deps.io.stderr(`${err.stack}\n`);+ }+ if (json) {+ deps.io.stdout(+ `${JSON.stringify({ error: { code: cliError.code, message: cliError.message, hint: cliError.hint ?? null } }, null, 2)}\n`,+ );+ }+ return cliError.exitCode;+}diff --git a/packages/cli/src/cloud/client.ts b/packages/cli/src/cloud/client.tsnew file mode 100644index 00000000..4b46d548--- /dev/null+++ b/packages/cli/src/cloud/client.ts@@ -0,0 +1,421 @@+/** Typed REST client for Framefields Cloud (SPEC §8). Field names match the API. */+import { CliError } from "../errors.js";++export interface Repository {+ id: string;+ organizationId: string;+ name: string;+ description: string | null;+ visibility: "public" | "private";+ defaultBranch: string;+ remoteUrl: string;+ createdAt: string;+ updatedAt: string;+ /** Present on create and fork: a git token for the first push. */+ token?: string;+ forkedFrom?: string;+}++export interface Organization {+ id: string;+ name: string;+ slug: string;+ role: string;+ artifactsNamespace?: string;+ createdAt?: string;+}++export interface CloudComposition {+ id: string;+ entry: string;+ export: string;+ title: string;+ description: string | null;+ group: string | null;+ default: boolean;+}++export interface CompositionsResponse {+ ref: string;+ source: "manifest" | "default" | "invalid";+ compositions: CloudComposition[];+ defaultId: string | null;+ error?: string;+}++export interface AssetClaim {+ path?: string;+ sha256: string;+ size: number;+ mimeType: string;+}++export type UploadTicket = {+ sha256: string;+ intentId: string;+ expiresAt: string;+ confirmUrl: string;+} & (+ | {+ transport: "direct";+ method: "PUT";+ url: string;+ headers: Record<string, string>;+ }+ | {+ transport: "parts";+ partSize: number;+ partCount: number;+ partUrl: string;+ uploadedParts: number[];+ }+);++export interface AssetDiff {+ present: string[];+ missing: UploadTicket[];+}++export interface AssetLockfile {+ $schema?: string;+ version: number;+ projectId?: string;+ repository?: string;+ assets: Record<+ string,+ {+ sha256: string;+ size?: number;+ sizeBytes?: number;+ mimeType?: string;+ r2Key?: string;+ uploadedAt?: string;+ [key: string]: unknown;+ }+ >;+ [key: string]: unknown;+}++export type RenderStatus =+ | "queued"+ | "running"+ | "completed"+ | "failed"+ | "cancelled";++export interface RenderJob {+ id: string;+ repositoryId: string;+ commitSha: string;+ composition: string | null;+ entryPath: string;+ exportName: string;+ jobType: "video" | "frame" | "sheet";+ status: RenderStatus;+ renderParams: Record<string, unknown>;+ outputR2Key: string | null;+ qaReport: unknown;+ errorMessage: string | null;+ createdAt: string;+ completedAt: string | null;+ downloadUrl: string | null;+ progress?: number;+}++export interface CreateRenderResponse {+ jobId: string;+ status: RenderStatus;+ repository: string;+ commitSha: string;+ composition: string | null;+}++export interface Author {+ id: string;+ name: string;+ image: string | null;+}++export interface Issue {+ id: string;+ number: number;+ kind: "issue" | "pull";+ title: string;+ body: string;+ state: "open" | "closed" | "merged";+ labels: string[];+ author: Author | null;+ headRef: string | null;+ baseRef: string | null;+ isDraft: boolean;+ commentCount: number;+ createdAt: string;+ updatedAt: string;+ closedAt: string | null;+ mergedAt: string | null;+ timeline?: {+ id: string;+ kind: "comment" | "closed" | "reopened" | "merged";+ body: string | null;+ author: Author | null;+ createdAt: string;+ }[];+}++export type IssueKind = "issues" | "pulls";++export interface RequestOptions {+ query?: Record<string, string | number | boolean | undefined>;+ body?: unknown;+ headers?: Record<string, string>;+ /** Skip the API key (pre-signed URLs). */+ anonymous?: boolean;+}++type Fetch = typeof fetch;+export type RequestBody = NonNullable<RequestInit["body"]>;++export class CloudClient {+ constructor(+ /** e.g. `https://framefields.dev` */+ readonly host: string,+ readonly token: string | undefined,+ private readonly fetchImpl: Fetch = fetch,+ ) {}++ url(path: string, query?: RequestOptions["query"]): string {+ const url = new URL(+ /^https?:\/\//.test(path)+ ? path+ : `${this.host}${path.startsWith("/") ? "" : "/"}${path}`,+ );+ for (const [k, v] of Object.entries(query ?? {})) {+ if (v !== undefined) url.searchParams.set(k, String(v));+ }+ return url.toString();+ }++ /** A raw request; the caller handles the status. Used by `ff api` and downloads. */+ async raw(+ method: string,+ path: string,+ options: RequestOptions & { rawBody?: RequestBody; duplex?: boolean } = {},+ ): Promise<Response> {+ const headers: Record<string, string> = { ...options.headers };+ if (!options.anonymous && this.token)+ headers.Authorization = `Bearer ${this.token}`;+ let body: RequestBody | undefined = options.rawBody;+ if (options.body !== undefined) {+ headers["Content-Type"] ??= "application/json";+ body = JSON.stringify(options.body);+ }+ try {+ return await this.fetchImpl(this.url(path, options.query), {+ method,+ headers,+ body,+ ...(options.duplex && { duplex: "half" }),+ } as RequestInit);+ } catch (err) {+ throw new CliError(+ `could not reach ${this.host}: ${(err as Error).cause ?? (err as Error).message}`,+ {+ hint: "check your connection, or pass --host",+ cause: err,+ },+ );+ }+ }++ async request<T>(+ method: string,+ path: string,+ options: RequestOptions = {},+ ): Promise<T> {+ this.requireToken();+ const res = await this.raw(method, path, options);+ const text = await res.text();+ let data: unknown;+ try {+ data = text ? JSON.parse(text) : undefined;+ } catch {+ data = text;+ }+ if (!res.ok) throw apiError(res.status, data, `${method} ${path}`);+ return data as T;+ }++ requireToken(): void {+ if (!this.token) {+ throw new CliError(`not logged in to ${new URL(this.host).host}`, {+ code: "auth",+ hint: "ff auth login (or set FF_TOKEN)",+ });+ }+ }++ // ── Organization ──+ organization = () =>+ this.request<{ organization: Organization }>(+ "GET",+ "/v1/organization",+ ).then((r) => r.organization);++ // ── Repositories ──+ listRepos = () =>+ this.request<{ repositories: Repository[] }>("GET", "/v1/repos").then(+ (r) => r.repositories,+ );+ getRepo = (id: string) =>+ this.request<Repository>("GET", `/v1/repos/${enc(id)}`);+ createRepo = (body: {+ name: string;+ description?: string;+ visibility: "public" | "private";+ }) => this.request<Repository>("POST", "/v1/repos", { body });+ deleteRepo = (id: string) =>+ this.request<{ ok: true; deleted: string }>(+ "DELETE",+ `/v1/repos/${enc(id)}`,+ );+ forkRepo = (id: string, body: { name?: string }) =>+ this.request<Repository>("POST", `/v1/repos/${enc(id)}/fork`, { body });+ gitToken = (id: string, scope: "read" | "write", ttl = 3600) =>+ this.request<{ token: string; expiresAt: string; scope: string }>(+ "POST",+ `/v1/repos/${enc(id)}/tokens`,+ {+ body: { scope, ttl },+ },+ );+ compositions = (id: string, ref?: string) =>+ this.request<CompositionsResponse>(+ "GET",+ `/v1/repos/${enc(id)}/compositions`,+ { query: { ref } },+ );++ // ── Assets ──+ assetsDiff = (repoId: string | undefined, assets: AssetClaim[]) =>+ this.request<AssetDiff>(+ "POST",+ repoId ? `/v1/repos/${enc(repoId)}/assets/diff` : "/v1/assets/diff",+ {+ body: { assets },+ },+ );+ confirmUpload = (confirmUrl: string) =>+ this.request<{ sha256: string; sizeBytes: number }>("POST", confirmUrl);+ putAssetRefs = (+ repoId: string,+ body: { ref: string; commitSha: string; lockfile: AssetLockfile },+ ) =>+ this.request<Record<string, unknown>>(+ "PUT",+ `/v1/repos/${enc(repoId)}/asset-refs`,+ { body },+ );+ deleteAssetRefs = (repoId: string, ref: string) =>+ this.request<Record<string, unknown>>(+ "DELETE",+ `/v1/repos/${enc(repoId)}/asset-refs`,+ { query: { ref } },+ );++ // ── Renders ──+ createRender = (body: {+ repositoryId: string;+ commitSha: string;+ composition?: string;+ entryPath?: string;+ exportName?: string;+ jobType: "video" | "frame" | "sheet";+ options: Record<string, unknown>;+ }) => this.request<CreateRenderResponse>("POST", "/v1/renders", { body });+ getRender = (id: string) =>+ this.request<RenderJob>("GET", `/v1/renders/${enc(id)}`);+ listRenders = (repositoryId?: string) =>+ this.request<{ renderJobs: RenderJob[] }>("GET", "/v1/renders", {+ query: { repositoryId },+ }).then((r) => r.renderJobs);+ cancelRender = (id: string) =>+ this.request<unknown>("POST", `/v1/renders/${enc(id)}/cancel`);++ // ── Issues and pull requests ──+ listIssues = (+ repoId: string,+ kind: IssueKind,+ query: { state?: string; q?: string },+ ) =>+ this.request<{ items: Issue[]; counts: { open: number; closed: number } }>(+ "GET",+ `/v1/repos/${enc(repoId)}/${kind}`,+ {+ query,+ },+ );+ getIssue = (repoId: string, kind: IssueKind, n: number) =>+ this.request<Issue>("GET", `/v1/repos/${enc(repoId)}/${kind}/${n}`);+ createIssue = (+ repoId: string,+ kind: IssueKind,+ body: Record<string, unknown>,+ ) =>+ this.request<Issue>("POST", `/v1/repos/${enc(repoId)}/${kind}`, { body });+ updateIssue = (+ repoId: string,+ kind: IssueKind,+ n: number,+ body: Record<string, unknown>,+ ) =>+ this.request<{ ok: true; number: number }>(+ "PATCH",+ `/v1/repos/${enc(repoId)}/${kind}/${n}`,+ { body },+ );+ commentIssue = (repoId: string, kind: IssueKind, n: number, body: string) =>+ this.request<{ ok: true }>(+ "POST",+ `/v1/repos/${enc(repoId)}/${kind}/${n}/comments`,+ { body: { body } },+ );+ mergePull = (repoId: string, n: number) =>+ this.request<{ ok: true; number: number; mergedAt: string }>(+ "POST",+ `/v1/repos/${enc(repoId)}/pulls/${n}/merge`,+ );+}++const enc = encodeURIComponent;++/** Maps an API error to the exit codes of SPEC §7. */+export function apiError(+ status: number,+ data: unknown,+ what: string,+): CliError {+ const message =+ (typeof data === "object" &&+ data &&+ "error" in data &&+ typeof data.error === "string" &&+ data.error) ||+ (typeof data === "string" && data.trim().slice(0, 200)) ||+ `HTTP ${status}`;+ if (status === 401) {+ return new CliError(`${message} (${what})`, {+ code: "auth",+ hint: "ff auth login (or set FF_TOKEN)",+ });+ }+ if (status === 403) {+ const scope = /scope:\s*(\S+)/.exec(message)?.[1];+ return new CliError(message, {+ code: "auth",+ hint: scope+ ? `create an API key with the '${scope}' scope, then: ff auth login`+ : undefined,+ });+ }+ return new CliError(`${message} (${what}: HTTP ${status})`);+}diff --git a/packages/cli/src/commands/api.ts b/packages/cli/src/commands/api.tsnew file mode 100644index 00000000..d529357b--- /dev/null+++ b/packages/cli/src/commands/api.ts@@ -0,0 +1,146 @@+import fs from "node:fs";+import path from "node:path";+import type { Command } from "commander";+import type { Wrap } from "../cli.js";+import { apiError } from "../cloud/client.js";+import { usageError } from "../errors.js";++const collect = (value: string, previous: string[] = []) => [+ ...previous,+ value,+];++function splitField(field: string): [string, string] {+ const i = field.indexOf("=");+ if (i <= 0) throw usageError(`'${field}' is not key=value`);+ return [field.slice(0, i), field.slice(i + 1)];+}++/** `-F`: true, false, null and numbers become JSON values; `@file` reads a file. */+function typedValue(value: string, cwd: string): unknown {+ if (value === "true") return true;+ if (value === "false") return false;+ if (value === "null") return null;+ if (/^-?\d+(\.\d+)?$/.test(value)) return Number(value);+ if (value.startsWith("@"))+ return fs.readFileSync(path.resolve(cwd, value.slice(1)), "utf8");+ return value;+}++export function register(program: Command, wrap: Wrap) {+ program+ .command("api")+ .description(+ "Make an authenticated request to the Framefields Cloud API (like gh api)",+ )+ .argument("<path>", "e.g. /v1/repos")+ .option(+ "-X, --method <method>",+ "HTTP method (default GET, or POST with fields or --input)",+ )+ .option(+ "-f, --raw-field <key=value>",+ "add a string field (repeatable)",+ collect,+ [],+ )+ .option(+ "-F, --field <key=value>",+ "add a typed field: numbers, true/false/null, @file (repeatable)",+ collect,+ [],+ )+ .option(+ "-H, --header <key:value>",+ "add a header (repeatable)",+ collect,+ [],+ )+ .option("--input <file>", "request body from a file (- for stdin)")+ .option("-i, --include", "print the status line and headers")+ .addHelpText(+ "after",+ "\nFields go in the query string for GET and in a JSON body otherwise.\n\nExamples:\n ff api /v1/repos\n ff api /v1/renders -f repositoryId=repo_123 -f commitSha=abc1234 -f composition=film",+ )+ .action(+ wrap(+ async (+ ctx,+ apiPath: string,+ opts: {+ method?: string;+ rawField: string[];+ field: string[];+ header: string[];+ input?: string;+ include?: boolean;+ },+ ) => {+ const client = await ctx.client();+ client.requireToken();+ const fields: Record<string, unknown> = {};+ for (const f of opts.rawField) {+ const [k, v] = splitField(f);+ fields[k] = v;+ }+ for (const f of opts.field) {+ const [k, v] = splitField(f);+ fields[k] = typedValue(v, ctx.cwd);+ }+ const hasFields = Object.keys(fields).length > 0;+ const method = (+ opts.method ?? (hasFields || opts.input ? "POST" : "GET")+ ).toUpperCase();+ const headers: Record<string, string> = {};+ for (const h of opts.header) {+ const i = h.indexOf(":");+ if (i <= 0) throw usageError(`'${h}' is not key:value`);+ headers[h.slice(0, i).trim()] = h.slice(i + 1).trim();+ }+ let rawBody: string | undefined;+ if (opts.input !== undefined) {+ if (hasFields) throw usageError("--input and fields are exclusive");+ rawBody =+ opts.input === "-"+ ? await ctx.io.readStdin()+ : fs.readFileSync(path.resolve(ctx.cwd, opts.input), "utf8");+ headers["Content-Type"] ??= "application/json";+ }+ const query =+ method === "GET" && hasFields+ ? (fields as Record<string, string>)+ : undefined;+ const body = method !== "GET" && hasFields ? fields : undefined;+ const p =+ apiPath.startsWith("/") || /^https?:/.test(apiPath)+ ? apiPath+ : `/${apiPath}`;+ const res = await client.raw(method, p, {+ query,+ body,+ rawBody,+ headers,+ });+ const text = await res.text();+ if (opts.include) {+ ctx.io.stdout(`HTTP ${res.status} ${res.statusText}\n`);+ for (const [k, v] of res.headers) ctx.io.stdout(`${k}: ${v}\n`);+ ctx.io.stdout("\n");+ }+ let pretty = text;+ try {+ pretty = JSON.stringify(JSON.parse(text), null, 2);+ } catch {}+ if (pretty)+ ctx.io.stdout(`${pretty}${pretty.endsWith("\n") ? "" : "\n"}`);+ if (!res.ok) {+ let data: unknown = text;+ try {+ data = JSON.parse(text);+ } catch {}+ throw apiError(res.status, data, `${method} ${p}`);+ }+ },+ ),+ );+}diff --git a/packages/cli/src/commands/asset.ts b/packages/cli/src/commands/asset.tsnew file mode 100644index 00000000..23c029bf--- /dev/null+++ b/packages/cli/src/commands/asset.ts@@ -0,0 +1,220 @@+import path from "node:path";+import type { Command } from "commander";+import type { Project } from "framefields/project";+import {+ assetStatus,+ buildLockfile,+ LOCKFILE,+ planSync,+ pullAssets,+ readLockfile,+ upload,+ writeLockfile,+} from "../assets.js";+import type { Wrap } from "../cli.js";+import type { Context } from "../context.js";+import { CliError } from "../errors.js";+import * as git from "../git/index.js";++export interface SyncSummary {+ uploaded: string[];+ present: string[];+ removed: string[];+ skipped: { path: string; reason: string }[];+ lockfileChanged: boolean;+ dryRun: boolean;+}++/** The linked repository's id, if this directory has one (asset diffs can be org-wide without it). */+async function linkedRepoId(ctx: Context): Promise<string | undefined> {+ const root = await git.topLevel(ctx.cwd);+ if (!root) return undefined;+ return git.configGet(root, "framefields.repo");+}++/** Hash, upload what the cloud lacks, rewrite the lockfile. No git. */+export async function syncAssets(+ ctx: Context,+ project: Project,+ options: { dryRun?: boolean; repoId?: string } = {},+): Promise<SyncSummary> {+ const client = await ctx.client();+ client.requireToken();+ const repoId = options.repoId ?? (await linkedRepoId(ctx));+ ctx.out.info(`hashing ${project.assets.directory}/`);+ const plan = await planSync(client, repoId, project);+ const byHash = new Map(plan.assets.map((a) => [a.sha256, a]));+ const uploaded: string[] = [];+ for (const s of plan.skipped) ctx.out.warn(`skipping ${s.path}: ${s.reason}`);+ if (!options.dryRun) {+ for (const ticket of plan.missing) {+ const asset = byHash.get(ticket.sha256);+ if (!asset) continue;+ let lastPct = -1;+ await upload(+ client,+ ticket,+ path.join(project.root, asset.path),+ asset.size,+ ({ bytes, total, done }) => {+ const pct = Math.floor((bytes / Math.max(1, total)) * 100);+ if (done)+ ctx.out.info(`uploaded ${asset.path} (${formatBytes(total)})`);+ else if (pct !== lastPct && pct % 10 === 0 && total > 8 * 1024 * 1024)+ ctx.out.info(` ${asset.path} ${pct}%`);+ lastPct = pct;+ },+ asset.path,+ );+ uploaded.push(asset.path);+ }+ }+ const missingHashes = new Set(plan.missing.map((t) => t.sha256));+ const toUpload = plan.assets+ .filter((a) => missingHashes.has(a.sha256))+ .map((a) => a.path);+ let lockfileChanged = false;+ if (!options.dryRun) {+ lockfileChanged = writeLockfile(+ project,+ buildLockfile(readLockfile(project), plan.assets, repoId),+ );+ }+ return {+ uploaded: options.dryRun ? toUpload : uploaded,+ present: plan.assets+ .filter((a) => !missingHashes.has(a.sha256))+ .map((a) => a.path),+ removed: plan.removed,+ skipped: plan.skipped,+ lockfileChanged,+ dryRun: !!options.dryRun,+ };+}++export function printSync(ctx: Context, s: SyncSummary) {+ const verb = s.dryRun ? "would upload" : "uploaded";+ ctx.out.line(+ `${verb} ${s.uploaded.length}, already in cloud ${s.present.length}${s.removed.length ? `, dropped ${s.removed.length} no longer on disk` : ""}`,+ );+ for (const p of s.uploaded) ctx.out.line(` + ${p}`);+ for (const p of s.removed) ctx.out.line(` - ${p}`);+ if (!s.dryRun)+ ctx.out.line(+ s.lockfileChanged ? `${LOCKFILE} updated` : `${LOCKFILE} unchanged`,+ );+}++export async function pullProjectAssets(+ ctx: Context,+ project: Project,+ force = false,+) {+ const client = await ctx.client();+ client.requireToken();+ const result = await pullAssets(client, project, {+ force,+ onFile: (p) => ctx.out.info(`downloading ${p}`),+ });+ for (const f of result.failed) ctx.out.warn(`${f.path}: ${f.error}`);+ return result;+}++export function register(program: Command, wrap: Wrap) {+ const asset = program+ .command("asset")+ .description("Sync external assets with Framefields Cloud");++ asset+ .command("sync")+ .description(+ `Hash the assets directory, upload what the cloud lacks, rewrite ${LOCKFILE}`,+ )+ .option("--dry-run", "show what would be uploaded")+ .action(+ wrap(async (ctx, opts: { dryRun?: boolean }) => {+ const project = await ctx.project();+ const summary = await syncAssets(ctx, project, { dryRun: opts.dryRun });+ ctx.out.result(summary, () => printSync(ctx, summary));+ }),+ );++ asset+ .command("pull")+ .description(+ `Download ${LOCKFILE} entries missing on disk, verifying each SHA-256`,+ )+ .option("--force", "download every entry again")+ .action(+ wrap(async (ctx, opts: { force?: boolean }) => {+ const project = await ctx.project();+ if (!readLockfile(project)) {+ ctx.out.result({ downloaded: [], present: [], failed: [] }, () =>+ ctx.out.line(`no ${LOCKFILE}: nothing to pull`),+ );+ return;+ }+ const result = await pullProjectAssets(ctx, project, opts.force);+ ctx.out.result(result, () => {+ ctx.out.line(+ `downloaded ${result.downloaded.length}, already present ${result.present.length}`,+ );+ for (const p of result.downloaded) ctx.out.line(` ${p}`);+ });+ if (result.failed.length)+ throw new CliError(+ `${result.failed.length} asset(s) failed to download`,+ { hint: "ff asset pull" },+ );+ }),+ );++ asset+ .command("status")+ .description(+ "Local files vs lockfile vs cloud: new, modified, missing, not uploaded",+ )+ .action(+ wrap(async (ctx) => {+ const project = await ctx.project();+ const client = await ctx.client();+ const status = await assetStatus(+ client.token ? client : undefined,+ await linkedRepoId(ctx),+ project,+ );+ ctx.out.result(status, () => {+ const groups: [keyof typeof status, string, string][] = [+ ["new", "new (not in the lockfile)", "ff asset sync"],+ ["modified", "modified", "ff asset sync"],+ ["missing", "missing on disk", "ff asset pull"],+ ["notUploaded", "not in the cloud", "ff asset sync"],+ ];+ let clean = true;+ for (const [key, label, fix] of groups) {+ if (status[key].length === 0) continue;+ clean = false;+ ctx.out.line(`${label} (${fix}):`);+ for (const p of status[key]) ctx.out.line(` ${p}`);+ }+ if (clean) ctx.out.line(`${status.ok.length} assets, all in sync`);+ if (!client.token)+ ctx.out.info(+ "not logged in: cloud state not checked (ff auth login)",+ );+ });+ }),+ );+}++export function formatBytes(n: number): string {+ if (n < 1024) return `${n} B`;+ const units = ["KB", "MB", "GB", "TB"];+ let v = n / 1024;+ let i = 0;+ while (v >= 1024 && i < units.length - 1) {+ v /= 1024;+ i++;+ }+ return `${v.toFixed(v < 10 ? 1 : 0)} ${units[i]}`;+}diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.tsnew file mode 100644index 00000000..ecc639a2--- /dev/null+++ b/packages/cli/src/commands/auth.ts@@ -0,0 +1,247 @@+import fs from "node:fs";+import type { Command } from "commander";+import type { Wrap } from "../cli.js";+import { CloudClient, type Repository } from "../cloud/client.js";+import { hostKey, readHosts, tokenFor, writeHosts } from "../config.js";+import type { Context } from "../context.js";+import { CliError, usageError } from "../errors.js";+import * as git from "../git/index.js";++export const keyPrefix = (key: string) =>+ `${key.slice(0, Math.min(10, key.length - 4))}…`;++export function register(program: Command, wrap: Wrap) {+ const auth = program+ .command("auth")+ .description("Log in to Framefields Cloud and set up git");++ auth+ .command("login")+ .description(+ "Store an API key for the host (verified with GET /v1/organization)",+ )+ .option("--with-token", "read the API key from stdin")+ .addHelpText(+ "after",+ "\nIn CI or agent sandboxes, set FF_TOKEN (and FF_HOST) instead of logging in.\n\nExample:\n echo $FF_KEY | ff auth login --with-token",+ )+ .action(+ wrap(async (ctx, opts: { withToken?: boolean }) => {+ const host = await ctx.host();+ let key: string;+ if (opts.withToken) {+ key = (await ctx.io.readStdin()).trim();+ } else if (await ctx.canPrompt()) {+ const url = `${host}/api-keys`;+ ctx.out.info(+ `Create an API key at ${url} (scopes: repo:read, repo:write, render:create, assets:sync), then paste it here.`,+ );+ ctx.io.openUrl(url);+ key = await ctx.io.prompt("API key", { secret: true });+ } else {+ throw usageError(+ "no terminal to paste a key into",+ "echo $FF_KEY | ff auth login --with-token",+ );+ }+ if (!key) throw usageError("no API key given");+ if (!key.startsWith("ff_"))+ throw usageError(+ "Framefields API keys start with ff_",+ `create one at ${host}/api-keys`,+ );+ const org = await new CloudClient(+ host,+ key,+ ctx.fetchImpl,+ ).organization();+ const hosts = await readHosts(ctx.env);+ hosts[hostKey(host)] = {+ apiKey: key,+ organization: org.id,+ organizationName: org.name,+ };+ await writeHosts(ctx.env, hosts);+ ctx.out.result({ host: hostKey(host), organization: org }, () =>+ ctx.out.line(+ `logged in to ${hostKey(host)} · ${org.name} (${org.id})`,+ ),+ );+ if (ctx.env.FF_TOKEN)+ ctx.out.warn(+ "FF_TOKEN is set and takes precedence over the stored key",+ );+ }),+ );++ auth+ .command("status")+ .description("Show the host, organization and API key in use")+ .action(+ wrap(async (ctx) => {+ const host = await ctx.host();+ const found = await tokenFor(ctx.env, host);+ if (!found) {+ throw new CliError(`not logged in to ${hostKey(host)}`, {+ code: "auth",+ hint: "ff auth login (or set FF_TOKEN)",+ });+ }+ const org = await new CloudClient(+ host,+ found.token,+ ctx.fetchImpl,+ ).organization();+ const status = {+ host: hostKey(host),+ organization: org,+ key: keyPrefix(found.token),+ source: found.source === "env" ? "FF_TOKEN" : "hosts.json",+ };+ ctx.out.result(status, () =>+ ctx.out.view([+ ["host", status.host],+ ["organization", `${org.name} (${org.id})`],+ ["role", org.role],+ ["key", `${status.key} (from ${status.source})`],+ ]),+ );+ }),+ );++ auth+ .command("logout")+ .description("Remove the stored API key for the host")+ .action(+ wrap(async (ctx) => {+ const host = hostKey(await ctx.host());+ const hosts = await readHosts(ctx.env);+ const had = host in hosts;+ delete hosts[host];+ await writeHosts(ctx.env, hosts);+ ctx.out.result({ host, removed: had }, () =>+ ctx.out.line(+ had ? `logged out of ${host}` : `no stored key for ${host}`,+ ),+ );+ if (ctx.env.FF_TOKEN)+ ctx.out.warn("FF_TOKEN is still set in the environment");+ }),+ );++ auth+ .command("setup-git")+ .description(+ "Install ff as git's credential helper for the cloud's git host",+ )+ .option(+ "--hostname <host>",+ "git host to configure (default: the hosts of your repositories' remotes)",+ )+ .action(+ wrap(async (ctx, opts: { hostname?: string }) => {+ let hosts: string[];+ if (opts.hostname)+ hosts = [+ opts.hostname.replace(/^https?:\/\//, "").replace(/\/.*$/, ""),+ ];+ else {+ const repos = await (await ctx.client()).listRepos();+ hosts = [...new Set(repos.map((r) => new URL(r.remoteUrl).host))];+ if (hosts.length === 0)+ throw usageError(+ "no repositories yet, so no git host to configure",+ "ff auth setup-git --hostname <git host>",+ );+ }+ const helper = `!${selfCommand()} auth git-credential`;+ for (const h of hosts) {+ const section = `credential.https://${h}`;+ // An empty helper first resets helpers inherited for this host.+ await git.gitOk(+ ["config", "--global", "--replace-all", `${section}.helper`, ""],+ { cwd: ctx.cwd },+ );+ await git.gitOk(+ ["config", "--global", "--add", `${section}.helper`, helper],+ { cwd: ctx.cwd },+ );+ await git.gitOk(+ ["config", "--global", `${section}.useHttpPath`, "true"],+ { cwd: ctx.cwd },+ );+ }+ ctx.out.result({ hosts, helper }, () => {+ for (const h of hosts)+ ctx.out.line(`git now asks ff for credentials for https://${h}`);+ });+ }),+ );++ // Called by git, not people: https://git-scm.com/docs/gitcredentials+ auth+ .command("git-credential", { hidden: true })+ .argument("<operation>", "get, store or erase")+ .action(+ wrap(async (ctx, operation: string) => {+ if (operation !== "get") return;+ const input = parseCredentialInput(await ctx.io.readStdin());+ const answer = await gitCredential(ctx, input);+ if (answer) ctx.io.stdout(answer);+ }),+ );+}++export function parseCredentialInput(text: string): Record<string, string[]> {+ const fields: Record<string, string[]> = {};+ for (const line of text.split("\n")) {+ const i = line.indexOf("=");+ if (i <= 0) continue;+ const key = line.slice(0, i);+ fields[key] = [...(fields[key] ?? []), line.slice(i + 1)];+ }+ return fields;+}++/**+ * Mints a short-lived git token for the repository git is talking to, matched+ * by URL among the organization's repositories. Answers with a bearer token+ * when git supports it (2.46+), else as a password.+ */+export async function gitCredential(+ ctx: Context,+ input: Record<string, string[]>,+): Promise<string | undefined> {+ const protocol = input.protocol?.[0];+ const host = input.host?.[0];+ if (protocol !== "https" || !host) return undefined;+ const wanted = git.normalizeRemote(+ `https://${host}/${input.path?.[0] ?? ""}`,+ );+ const client = await ctx.client();+ if (!client.token) return undefined;+ let repo: Repository | undefined;+ const linked = await git.configGet(ctx.cwd, "framefields.repo");+ const repos = await client.listRepos();+ repo = repos.find((r) => git.normalizeRemote(r.remoteUrl) === wanted);+ if (!repo && linked && !input.path) repo = repos.find((r) => r.id === linked);+ if (!repo) return undefined;+ let token: string;+ try {+ token = (await client.gitToken(repo.id, "write")).token;+ } catch (err) {+ if (!(err instanceof CliError) || err.code !== "auth") throw err;+ token = (await client.gitToken(repo.id, "read")).token;+ }+ const bearer = (input["capability[]"] ?? []).includes("authtype");+ return bearer+ ? `capability[]=authtype\nauthtype=Bearer\ncredential=${token}\nephemeral=true\n`+ : `username=x-token\npassword=${token}\n`;+}++/** How git should invoke this CLI: the same node and script. */+function selfCommand(): string {+ const script = process.argv[1] ? fs.realpathSync(process.argv[1]) : "ff";+ const quote = (s: string) => `'${s.replace(/'/g, "'\\''")}'`;+ return `${quote(process.execPath)} ${quote(script)}`;+}diff --git a/packages/cli/src/commands/check.ts b/packages/cli/src/commands/check.tsnew file mode 100644index 00000000..ce15aab8--- /dev/null+++ b/packages/cli/src/commands/check.ts@@ -0,0 +1,148 @@+import { execFile } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import type { Command } from "commander";+import { buildComposition, type Project } from "framefields/project";+import type { Wrap } from "../cli.js";+import { resolveTarget } from "../compositions.js";+import { findPackageDir, fromProjectError } from "../context.js";+import { CliError } from "../errors.js";++interface TypecheckResult {+ status: "passed" | "failed" | "skipped";+ reason?: string;+ output?: string;+}++interface CompositionResult {+ id: string;+ ok: boolean;+ error?: string;+ issues?: { path: string; message: string }[];+}++export function register(program: Command, wrap: Wrap) {+ program+ .command("check")+ .description(+ "Typecheck the project, then build each composition and validate its spec (verification ladder, step 1)",+ )+ .argument(+ "[compositions...]",+ "composition ids or file#export (all by default)",+ )+ .option("--no-typecheck", "skip tsc --noEmit")+ .action(+ wrap(async (ctx, refs: string[], opts: { typecheck: boolean }) => {+ const project = await ctx.project();+ const targets = refs.length+ ? refs.map((ref) => ({ ref, target: resolveTarget(project, ref) }))+ : project.compositions.map((target) => ({ ref: target.id, target }));++ const typecheck: TypecheckResult = opts.typecheck+ ? await runTsc(project, (t) => ctx.out.info(t))+ : { status: "skipped", reason: "--no-typecheck" };+ if (typecheck.status === "failed" && !ctx.out.json)+ ctx.io.stderr(typecheck.output ?? "");++ const engine = await ctx.engine(project);+ const results: CompositionResult[] = [];+ for (const { ref, target } of targets) {+ ctx.out.info(+ `building ${target.id} (${target.entry}#${target.export})`,+ );+ try {+ const comp = await buildComposition(project, ref);+ const parsed = engine.CompositorProgramSchema?.safeParse(+ comp.toSpec(),+ );+ if (parsed && !parsed.success) {+ results.push({+ id: target.id,+ ok: false,+ error: "the spec does not match the program schema",+ issues: (parsed.error?.issues ?? []).slice(0, 10).map((i) => ({+ path: i.path.map(String).join(".") || "(root)",+ message: i.message,+ })),+ });+ } else {+ results.push({ id: target.id, ok: true });+ }+ } catch (err) {+ const mapped = fromProjectError(err);+ results.push({+ id: target.id,+ ok: false,+ error: (mapped as Error).message ?? String(err),+ });+ }+ }++ const ok = typecheck.status !== "failed" && results.every((r) => r.ok);+ ctx.out.result({ ok, typecheck, compositions: results }, () => {+ const mark = (pass: boolean) =>+ pass ? ctx.out.style("green", "✓") : ctx.out.style("red", "✗");+ ctx.out.line(+ typecheck.status === "skipped"+ ? `- typecheck (skipped: ${typecheck.reason})`+ : `${mark(typecheck.status === "passed")} typecheck`,+ );+ for (const r of results) {+ ctx.out.line(+ `${mark(r.ok)} ${r.id}${r.error ? `: ${r.error}` : ""}`,+ );+ for (const i of r.issues ?? [])+ ctx.out.line(` ${i.path}: ${i.message}`);+ }+ });+ if (!ok) {+ const failed = results.filter((r) => !r.ok).map((r) => r.id);+ throw new CliError(+ [+ typecheck.status === "failed" && "typecheck failed",+ failed.length && `${failed.join(", ")} failed`,+ ]+ .filter(Boolean)+ .join("; "),+ {+ hint: failed.length+ ? `ff frames ${failed[0]} 0 (render a frame to see the failure)`+ : undefined,+ },+ );+ }+ }),+ );+}++async function runTsc(+ project: Project,+ info: (text: string) => void,+): Promise<TypecheckResult> {+ if (!fs.existsSync(path.join(project.root, "tsconfig.json"))) {+ return { status: "skipped", reason: "no tsconfig.json" };+ }+ const typescript = findPackageDir(project.root, "typescript");+ if (!typescript)+ return {+ status: "skipped",+ reason: "typescript is not installed in the project",+ };+ const tsc = path.join(typescript, "bin", "tsc");+ info("typechecking (tsc --noEmit)");+ return new Promise((resolve) => {+ execFile(+ process.execPath,+ [tsc, "--noEmit", "-p", project.root],+ { cwd: project.root, maxBuffer: 32 * 1024 * 1024 },+ (err, stdout, stderr) => {+ resolve(+ err+ ? { status: "failed", output: `${stdout}${stderr}` }+ : { status: "passed" },+ );+ },+ );+ });+}diff --git a/packages/cli/src/commands/clone.ts b/packages/cli/src/commands/clone.tsnew file mode 100644index 00000000..7f3d8c5d--- /dev/null+++ b/packages/cli/src/commands/clone.ts@@ -0,0 +1,74 @@+import fs from "node:fs";+import path from "node:path";+import type { Command } from "commander";+import { loadProject } from "framefields/project";+import { readLockfile } from "../assets.js";+import type { Wrap } from "../cli.js";+import type { Repository } from "../cloud/client.js";+import type { Context } from "../context.js";+import { CliError } from "../errors.js";+import * as git from "../git/index.js";+import { pullProjectAssets } from "./asset.js";++/** `git clone` with a read token for this one invocation, link the directory, then pull assets. */+export async function cloneRepo(ctx: Context, repo: Repository, dir?: string) {+ const target = path.resolve(ctx.cwd, dir ?? repo.name);+ if (fs.existsSync(target) && fs.readdirSync(target).length > 0) {+ throw new CliError(+ `${ctx.relativeCwd(target)} already exists and is not empty`,+ { hint: `ff clone ${repo.name} <dir>` },+ );+ }+ const client = await ctx.client();+ const { token } = await client.gitToken(repo.id, "read");+ const progress =+ ctx.out.options.quiet || ctx.out.json+ ? undefined+ : (t: string) => ctx.io.stderr(t);+ const result = await git.git(["clone", repo.remoteUrl, target], {+ cwd: ctx.cwd,+ token,+ onStderr: progress,+ });+ if (result.code !== 0) {+ throw new CliError(+ `git clone failed:\n ${(result.stderr || result.stdout).trim().split("\n").slice(-3).join("\n ")}`,+ );+ }+ await ctx.link(target, repo);+ const project = await loadProject(target).catch(() => undefined);+ const assets =+ project && readLockfile(project)+ ? await pullProjectAssets(ctx, project)+ : null;+ return { directory: ctx.relativeCwd(target), repository: repo, assets };+}++export function register(program: Command, wrap: Wrap) {+ program+ .command("clone")+ .description("Clone a Framefields Cloud repository and download its assets")+ .argument("<repo>", "repository name or id")+ .argument("[dir]", "directory (default: the repository name)")+ .action(+ wrap(async (ctx, ref: string, dir: string | undefined) => {+ const repo = await ctx.repo(ref);+ const result = await cloneRepo(ctx, repo, dir);+ ctx.out.result(result, () => {+ ctx.out.line(result.directory);+ if (result.assets)+ ctx.out.info(+ `assets: downloaded ${result.assets.downloaded.length}`,+ );+ });+ if (result.assets?.failed.length) {+ throw new CliError(+ `${result.assets.failed.length} asset(s) failed to download`,+ {+ hint: `cd ${result.directory} && ff asset pull`,+ },+ );+ }+ }),+ );+}diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.tsnew file mode 100644index 00000000..8a6b0de4--- /dev/null+++ b/packages/cli/src/commands/config.ts@@ -0,0 +1,70 @@+import type { Command } from "commander";+import type { Wrap } from "../cli.js";+import {+ assertConfigKey,+ CONFIG_KEYS,+ readConfig,+ writeConfig,+} from "../config.js";+import { usageError } from "../errors.js";++export function register(program: Command, wrap: Wrap) {+ const config = program+ .command("config")+ .description(+ "Read and write per-user settings (~/.config/framefields/config.json)",+ )+ .addHelpText(+ "after",+ `\nKeys:\n${Object.entries(CONFIG_KEYS)+ .map(([k, v]) => ` ${k.padEnd(8)} ${v}`)+ .join("\n")}`,+ );++ config+ .command("get")+ .argument("<key>")+ .description("Print a setting")+ .action(+ wrap(async (ctx, key: string) => {+ assertConfigKey(key);+ const value = (await readConfig(ctx.env))[key] ?? null;+ ctx.out.result({ [key]: value }, () => {+ if (value !== null) ctx.out.line(value);+ });+ }),+ );++ config+ .command("set")+ .argument("<key>")+ .argument("[value]", "omit to unset")+ .description("Change a setting")+ .action(+ wrap(async (ctx, key: string, value: string | undefined) => {+ assertConfigKey(key);+ if (+ key === "prompt" &&+ value !== undefined &&+ !["enabled", "disabled"].includes(value)+ ) {+ throw usageError("prompt is 'enabled' or 'disabled'");+ }+ const current = await readConfig(ctx.env);+ if (value === undefined) delete current[key];+ else current[key] = value;+ await writeConfig(ctx.env, current);+ ctx.out.result({ [key]: value ?? null }, () => {});+ }),+ );++ config+ .command("list")+ .description("Print all settings")+ .action(+ wrap(async (ctx) => {+ const current = await readConfig(ctx.env);+ ctx.out.result(current, () => ctx.out.view(Object.entries(current)));+ }),+ );+}diff --git a/packages/cli/src/commands/frames.ts b/packages/cli/src/commands/frames.tsnew file mode 100644index 00000000..6f4c100b--- /dev/null+++ b/packages/cli/src/commands/frames.ts@@ -0,0 +1,78 @@+import fs from "node:fs/promises";+import path from "node:path";+import type { Command } from "commander";+import type { Wrap } from "../cli.js";+import {+ isCompositionRef,+ loadComposition,+ outputDir,+} from "../compositions.js";+import { usageError } from "../errors.js";+import { frameFileName, looksLikeFrame, parseFrame } from "../timecode.js";++export function register(program: Command, wrap: Wrap) {+ program+ .command("frames")+ .description("Render frames to PNG (verification ladder, step 2)")+ .argument(+ "[composition]",+ "composition id or file#export; may be omitted for the default",+ )+ .argument(+ "[frames...]",+ "frame numbers or timecodes: 60, 2.5s, 1500ms, 00:02:15",+ )+ .addHelpText(+ "after",+ "\nWrites <output>/frames/<id>/f0060.png …\n\nExamples:\n ff frames 0 60 2.5s\n ff frames step-3 00:00:04",+ )+ .action(+ wrap(async (ctx, first: string | undefined, rest: string[]) => {+ const project = await ctx.project();+ let ref: string | undefined = first;+ let refs = rest;+ // `ff frames 60 120`: the first argument is a frame, not a composition.+ if (+ first !== undefined &&+ !isCompositionRef(project, first) &&+ looksLikeFrame(first)+ ) {+ ref = undefined;+ refs = [first, ...rest];+ }+ if (refs.length === 0) {+ throw usageError(+ "which frames?",+ "ff frames [composition] <frame…>, e.g. ff frames 0 60 2.5s",+ );+ }+ const { engine, target, composition, frameCount } =+ await loadComposition(ctx, ref);+ const frames = refs.map((r) => {+ const f = parseFrame(r, composition.fps);+ if (f >= frameCount) {+ throw usageError(+ `frame ${r} (${f}) is past the end: ${target.id} has ${frameCount} frames (0–${frameCount - 1})`,+ );+ }+ return f;+ });+ const dir = await outputDir(project, "frames", target.id);+ const renderer = new engine.HeadlessMediaRenderer();+ const files: string[] = [];+ for (const frame of frames) {+ const file = path.join(dir, frameFileName(frame));+ ctx.out.info(`rendering frame ${frame}`);+ const png = await composition.renderFrame({+ frame,+ renderer: renderer as never,+ });+ await fs.writeFile(file, png);+ const rel = ctx.relative(project, file);+ files.push(rel);+ if (!ctx.out.json) ctx.out.line(rel);+ }+ ctx.out.result({ files }, () => {});+ }),+ );+}diff --git a/packages/cli/src/commands/grid.ts b/packages/cli/src/commands/grid.tsnew file mode 100644index 00000000..090f3f18--- /dev/null+++ b/packages/cli/src/commands/grid.ts@@ -0,0 +1,78 @@+import fs from "node:fs/promises";+import path from "node:path";+import type { Command } from "commander";+import type { Wrap } from "../cli.js";+import { loadComposition, outputDir } from "../compositions.js";+import { usageError } from "../errors.js";+import { parseFrame, spreadFrames } from "../timecode.js";++const int = (name: string, value: string, min: number, max: number) => {+ const n = Number(value);+ if (!Number.isInteger(n) || n < min || n > max)+ throw usageError(`${name} must be a whole number from ${min} to ${max}`);+ return n;+};++export function register(program: Command, wrap: Wrap) {+ program+ .command("grid")+ .description(+ "Render a contact sheet of frames (verification ladder, step 3)",+ )+ .argument("[composition]", "composition id or file#export")+ .option("--count <n>", "frames in the sheet", "16")+ .option("--columns <n>", "columns", "4")+ .option("--cell-width <px>", "width of each cell", "480")+ .option("--from <frame>", "first frame or timecode (default 0)")+ .option("--to <frame>", "last frame or timecode (default the last frame)")+ .addHelpText("after", "\nWrites <output>/<id>-grid.png")+ .action(+ wrap(+ async (+ ctx,+ ref: string | undefined,+ opts: {+ count: string;+ columns: string;+ cellWidth: string;+ from?: string;+ to?: string;+ },+ ) => {+ const count = int("--count", opts.count, 1, 120);+ const columns = int("--columns", opts.columns, 1, 32);+ const cellWidth = int("--cell-width", opts.cellWidth, 120, 960);+ const { project, target, composition, frameCount } =+ await loadComposition(ctx, ref);+ const last = frameCount - 1;+ const from =+ opts.from === undefined+ ? 0+ : parseFrame(opts.from, composition.fps);+ const to =+ opts.to === undefined+ ? last+ : Math.min(last, parseFrame(opts.to, composition.fps));+ if (from > to)+ throw usageError(`--from (${from}) is after --to (${to})`);+ const frames = spreadFrames(from, to, count);+ ctx.out.info(`rendering ${frames.length} frames (${from}–${to})`);+ const png = await composition.renderFrameGrid({+ frames,+ columns: Math.min(columns, frames.length),+ cellWidth,+ showLabels: true,+ maxFrames: 120,+ headerText: target.title,+ });+ const file = path.join(+ await outputDir(project),+ `${target.id}-grid.png`,+ );+ await fs.writeFile(file, png);+ const rel = ctx.relative(project, file);+ ctx.out.result({ files: [rel], frames }, () => ctx.out.line(rel));+ },+ ),+ );+}diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsnew file mode 100644index 00000000..ba2e4c94--- /dev/null+++ b/packages/cli/src/commands/init.ts@@ -0,0 +1,392 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import type { Command } from "commander";+import { MANIFEST_FILE, MANIFEST_SCHEMA_URL } from "framefields/project";+import { LOCKFILE, LOCKFILE_SCHEMA } from "../assets.js";+import type { Wrap } from "../cli.js";+import { addCommand } from "../context.js";+import { CliError, usageError } from "../errors.js";+import * as git from "../git/index.js";+import { VERSION } from "../version.js";++const TEMPLATES_REPO = "https://github.com/gatewai-dev/framefields.git";++const FILM = `import { Composition, Layer, LayerAnimation } from "framefields";++const W = 1920;+const H = 1080;+const FPS = 30;+const DURATION = 3 * FPS; // frames++/** The film: \`ff preview\` shows it, \`ff render --local\` exports it. */+export async function buildFilm(): Promise<Composition> {+ const film = new Composition({+ width: W,+ height: H,+ fps: FPS,+ durationMs: (DURATION / FPS) * 1000,+ backgroundColor: "#0E0D0C",+ });++ const size = 360;+ film.add(+ Layer.shape("ellipse", {+ id: "disc",+ position: "absolute",+ x: (W - size) / 2,+ y: (H - size) / 2,+ width: size,+ height: size,+ fillColor: "#EEE9E0",+ }).animate(+ LayerAnimation.create()+ .fadeIn(0, 20, "power2.out")+ .fromTo("y", (H - size) / 2 + 80, (H - size) / 2, { start: 0, end: 30, ease: "expo.out" }),+ ),+ );++ return film;+}+`;++const TSCONFIG = {+ compilerOptions: {+ module: "NodeNext",+ moduleResolution: "NodeNext",+ target: "ES2022",+ strict: true,+ skipLibCheck: true,+ noEmit: true,+ types: ["node"],+ },+ include: ["src/**/*"],+};++const GITIGNORE = [+ "node_modules/",+ "output/",+ ".framefields/",+ `# External assets live in Framefields Cloud; ${LOCKFILE} tracks them (ff asset sync).`,+ "assets/",+];++/** Install-script approvals framefields needs (skia-canvas's native binary) and the rest it doesn't. */+const SCRIPT_POLICY = {+ allowScripts: {+ "skia-canvas": true,+ sharp: false,+ webgpu: false,+ "onnxruntime-node": false,+ "node-av": false,+ esbuild: false,+ },+ pnpm: {+ onlyBuiltDependencies: ["skia-canvas"],+ ignoredBuiltDependencies: [+ "sharp",+ "webgpu",+ "onnxruntime-node",+ "node-av",+ "esbuild",+ ],+ },+ trustedDependencies: ["skia-canvas"],+};++type Json = Record<string, unknown>;++const toSlug = (dir: string) =>+ dir.replace(/^\d+_/, "").replace(/_/g, "-").toLowerCase();++export function register(program: Command, wrap: Wrap) {+ program+ .command("init")+ .description(+ `Scaffold a project: src/film.ts, ${MANIFEST_FILE}, ${LOCKFILE}, .gitignore, package.json`,+ )+ .argument("[dir]", "directory (default: the current one)")+ .option(+ "-t, --template <slug>",+ "start from an example, e.g. data-story (from github.com/gatewai-dev/framefields/examples)",+ )+ .option("--name <name>", "package name (default: the directory name)")+ .action(+ wrap(+ async (+ ctx,+ dir: string | undefined,+ opts: { template?: string; name?: string },+ ) => {+ const target = path.resolve(ctx.cwd, dir ?? ".");+ fs.mkdirSync(target, { recursive: true });+ const name = (opts.name ?? path.basename(target))+ .toLowerCase()+ .replace(/[^a-z0-9._-]+/g, "-");+ const written: string[] = [];+ const skipped: string[] = [];+ const write = (rel: string, content: string) => {+ const file = path.join(target, rel);+ if (fs.existsSync(file)) {+ skipped.push(rel);+ return;+ }+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+ written.push(rel);+ };++ let title = "Film";+ if (opts.template) {+ const source = await fetchTemplate(ctx.env, opts.template, (t) =>+ ctx.out.info(t),+ );+ try {+ title = copyTemplate(source.dir, target, written, skipped);+ } finally {+ source.cleanup();+ }+ } else {+ write("src/film.ts", FILM);+ write("tsconfig.json", `${JSON.stringify(TSCONFIG, null, "\t")}\n`);+ }++ // Templates may bring their own manifest.+ if (+ !(opts.template && fs.existsSync(path.join(target, MANIFEST_FILE)))+ )+ write(+ MANIFEST_FILE,+ `${JSON.stringify(+ {+ $schema: MANIFEST_SCHEMA_URL,+ version: 1,+ compositions: {+ film: {+ entry: "src/film.ts",+ export: "buildFilm",+ title,+ default: true,+ },+ },+ },+ null,+ "\t",+ )}\n`,+ );+ write(+ LOCKFILE,+ `${JSON.stringify({ $schema: LOCKFILE_SCHEMA, version: 1, assets: {} }, null, "\t")}\n`,+ );+ fs.mkdirSync(path.join(target, "assets"), { recursive: true });+ mergeGitignore(target, written);+ mergePackageJson(target, name, written);+ if (!(await git.isRepo(target))) {+ const r = await git.git(["init", "--quiet", "-b", "main"], {+ cwd: target,+ });+ if (r.code === 0) written.push(".git/");+ }++ const packageManager = addCommand(target).split(" ")[0];+ const rel = path.relative(ctx.cwd, target) || ".";+ ctx.out.result({ directory: rel, files: written, skipped }, () => {+ for (const f of written) ctx.out.line(` + ${f}`);+ for (const f of skipped) ctx.out.line(` = ${f} (exists, kept)`);+ ctx.out.line();+ ctx.out.line("next:");+ if (rel !== ".") ctx.out.line(` cd ${rel}`);+ ctx.out.line(` ${packageManager} install`);+ ctx.out.line(" ff preview");+ });+ },+ ),+ );+}++function mergeGitignore(target: string, written: string[]) {+ const file = path.join(target, ".gitignore");+ const existing = fs.existsSync(file) ? fs.readFileSync(file, "utf8") : "";+ const lines = new Set(existing.split("\n").map((l) => l.trim()));+ const missing = GITIGNORE.filter((l) => !lines.has(l));+ if (missing.length === 0) return;+ fs.writeFileSync(+ file,+ `${existing}${existing && !existing.endsWith("\n") ? "\n" : ""}${missing.join("\n")}\n`,+ );+ written.push(".gitignore");+}++/** Creates package.json, or merges what framefields needs into an existing one. */+function mergePackageJson(target: string, name: string, written: string[]) {+ const file = path.join(target, "package.json");+ const exists = fs.existsSync(file);+ const pkg: Json = exists+ ? (JSON.parse(fs.readFileSync(file, "utf8")) as Json)+ : { name, private: true, version: "0.1.0" };+ pkg.type ??= "module";+ if (pkg.type !== "module")+ throw new CliError(+ `${file} has "type": "${pkg.type}"; framefields projects are ES modules`,+ );+ const scripts = (pkg.scripts ?? {}) as Record<string, string>;+ scripts.preview ??= "ff preview";+ scripts.check ??= "ff check";+ scripts.render ??= "ff render --local";+ pkg.scripts = scripts;+ const deps = (pkg.dependencies ?? {}) as Record<string, string>;+ deps.framefields =+ deps.framefields && deps.framefields !== "workspace:*"+ ? deps.framefields+ : `^${VERSION}`;+ pkg.dependencies = deps;+ const dev = (pkg.devDependencies ?? {}) as Record<string, string>;+ for (const k of Object.keys(dev))+ if (dev[k]?.startsWith("workspace:")) delete dev[k];+ dev["@framefields/cli"] ??= `^${VERSION}`;+ dev.typescript ??= "^5.8.3";+ dev["@types/node"] ??= "^24.1.0";+ pkg.devDependencies = dev;+ pkg.allowScripts = {+ ...SCRIPT_POLICY.allowScripts,+ ...(pkg.allowScripts as Json),+ };+ const pnpm = (pkg.pnpm ?? {}) as Json;+ pnpm.onlyBuiltDependencies ??= SCRIPT_POLICY.pnpm.onlyBuiltDependencies;+ pnpm.ignoredBuiltDependencies ??= SCRIPT_POLICY.pnpm.ignoredBuiltDependencies;+ pkg.pnpm = pnpm;+ pkg.trustedDependencies ??= SCRIPT_POLICY.trustedDependencies;+ fs.writeFileSync(file, `${JSON.stringify(pkg, null, "\t")}\n`);+ written.push(exists ? "package.json (merged)" : "package.json");+}++/**+ * The examples directory: `FF_TEMPLATES_DIR` (a local checkout's examples/),+ * else a shallow, sparse clone of the framefields repository.+ */+async function fetchTemplate(+ env: Record<string, string | undefined>,+ slug: string,+ info: (t: string) => void,+) {+ let examples: string;+ let cleanup = () => {};+ if (env.FF_TEMPLATES_DIR) examples = path.resolve(env.FF_TEMPLATES_DIR);+ else {+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "ff-template-"));+ cleanup = () => fs.rmSync(tmp, { recursive: true, force: true });+ const repo = env.FF_TEMPLATES_REPO ?? TEMPLATES_REPO;+ info(`fetching templates from ${repo}`);+ try {+ await git.gitOk(+ [+ "clone",+ "--quiet",+ "--depth",+ "1",+ "--filter=blob:none",+ "--sparse",+ repo,+ tmp,+ ],+ { cwd: os.tmpdir() },+ );+ await git.gitOk(["sparse-checkout", "set", "examples"], { cwd: tmp });+ } catch (err) {+ cleanup();+ throw err;+ }+ examples = path.join(tmp, "examples");+ }+ const dirs = fs.existsSync(examples)+ ? fs+ .readdirSync(examples, { withFileTypes: true })+ .filter((d) => d.isDirectory() && /^\d+_/.test(d.name))+ .map((d) => d.name)+ : [];+ const match = dirs.find(+ (d) => d === slug || toSlug(d) === slug.toLowerCase(),+ );+ if (!match) {+ cleanup();+ throw usageError(+ `unknown template '${slug}'`,+ `templates: ${dirs.map(toSlug).join(", ") || "(none found)"}`,+ );+ }+ return { dir: path.join(examples, match), cleanup };+}++const SKIP = new Set([+ "node_modules",+ "output",+ "scratch",+ "dist",+ ".turbo",+ "CHANGELOG.md",+ "tsconfig.dev.json",+ ".framefields",+]);++/** Copies an example, turning its monorepo wiring into a standalone project. Returns its title. */+function copyTemplate(+ from: string,+ to: string,+ written: string[],+ skipped: string[],+): string {+ const copy = (src: string, rel: string) => {+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {+ if (SKIP.has(entry.name)) continue;+ const s = path.join(src, entry.name);+ const r = rel ? `${rel}/${entry.name}` : entry.name;+ const d = path.join(to, r);+ // Follow symlinks: a linked folder (shared fonts, say) is copied as files.+ const stat = fs.statSync(s, { throwIfNoEntry: false });+ if (!stat) continue;+ if (stat.isDirectory()) {+ copy(s, r);+ continue;+ }+ if (r === "package.json") continue; // merged below+ if (fs.existsSync(d)) {+ skipped.push(r);+ continue;+ }+ fs.mkdirSync(path.dirname(d), { recursive: true });+ if (r === "tsconfig.json")+ fs.writeFileSync(d, `${JSON.stringify(TSCONFIG, null, "\t")}\n`);+ else fs.copyFileSync(s, d);+ written.push(r);+ }+ };+ copy(from, "");+ const src = path.join(from, "package.json");+ const dest = path.join(to, "package.json");+ if (fs.existsSync(src) && !fs.existsSync(dest)) {+ const pkg = JSON.parse(fs.readFileSync(src, "utf8")) as Json;+ const scripts = (pkg.scripts ?? {}) as Record<string, string>;+ for (const [k, v] of Object.entries(scripts))+ if (/tsconfig\.dev|--conditions/.test(v)) delete scripts[k];+ const { name: _n, version: _v, ...rest } = pkg;+ fs.writeFileSync(+ dest,+ JSON.stringify({+ name: path.basename(to),+ version: "0.1.0",+ ...rest,+ scripts,+ }),+ );+ }+ const readme = path.join(from, "README.md");+ const heading = fs.existsSync(readme)+ ? /^#\s+(.+)$/m.exec(fs.readFileSync(readme, "utf8"))?.[1]+ : undefined;+ return (+ heading?.trim().slice(0, 120) ||+ toSlug(path.basename(from))+ .replace(/-/g, " ")+ .replace(/^\w/, (c) => c.toUpperCase())+ );+}diff --git a/packages/cli/src/commands/issue.ts b/packages/cli/src/commands/issue.tsnew file mode 100644index 00000000..6ae7c740--- /dev/null+++ b/packages/cli/src/commands/issue.ts@@ -0,0 +1,340 @@+import { spawnSync } from "node:child_process";+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import type { Command } from "commander";+import type { Wrap } from "../cli.js";+import type { Issue, IssueKind } from "../cloud/client.js";+import { readConfig } from "../config.js";+import type { Context } from "../context.js";+import { usageError } from "../errors.js";++const collect = (value: string, previous: string[] = []) => [+ ...previous,+ value,+];++export function issueNumber(value: string): number {+ const n = Number(value.replace(/^#/, ""));+ if (!Number.isInteger(n) || n < 1)+ throw usageError(`'${value}' is not an issue or pull request number`);+ return n;+}++/** --body, --body-file (`-` for stdin), else the editor on a terminal, else `fallback`. */+export async function readBody(+ ctx: Context,+ opts: { body?: string; bodyFile?: string },+ fallback: string | undefined,+): Promise<string | undefined> {+ if (opts.body !== undefined && opts.bodyFile !== undefined)+ throw usageError("--body and --body-file are exclusive");+ if (opts.body !== undefined) return opts.body;+ if (opts.bodyFile === "-") return ctx.io.readStdin();+ if (opts.bodyFile !== undefined)+ return fs.readFileSync(path.resolve(ctx.cwd, opts.bodyFile), "utf8");+ if (fallback === undefined && (await ctx.canPrompt()))+ return editText(ctx, "");+ return fallback;+}++/** Opens the user's editor on a temp file and returns what they saved. */+async function editText(ctx: Context, initial: string): Promise<string> {+ const editor =+ (await readConfig(ctx.env)).editor ??+ ctx.env.VISUAL ??+ ctx.env.EDITOR ??+ "vi";+ const file = path.join(+ fs.mkdtempSync(path.join(os.tmpdir(), "ff-")),+ "BODY.md",+ );+ fs.writeFileSync(file, initial);+ try {+ const result = spawnSync(`${editor} "${file}"`, {+ stdio: "inherit",+ shell: true,+ });+ if (result.status !== 0)+ throw usageError(+ `${editor} exited with ${result.status}`,+ "pass --body or --body-file instead",+ );+ return fs.readFileSync(file, "utf8").trim();+ } finally {+ fs.rmSync(path.dirname(file), { recursive: true, force: true });+ }+}++const noun = (kind: IssueKind) => (kind === "pulls" ? "pull request" : "issue");++export function printIssue(ctx: Context, item: Issue, comments: boolean) {+ ctx.out.line(ctx.out.style("bold", `${item.title} #${item.number}`));+ ctx.out.view([+ ["state", item.isDraft && item.state === "open" ? "draft" : item.state],+ ["author", item.author?.name ?? null],+ ["labels", item.labels.length ? item.labels.join(", ") : undefined],+ [+ "branches",+ item.kind === "pull" ? `${item.headRef} → ${item.baseRef}` : undefined,+ ],+ ["comments", item.commentCount],+ ["created", item.createdAt],+ ["merged", item.mergedAt ?? undefined],+ ]);+ if (item.body.trim()) {+ ctx.out.line();+ ctx.out.line(item.body.trim());+ }+ if (comments) {+ for (const e of item.timeline ?? []) {+ ctx.out.line();+ const who = e.author?.name ?? "someone";+ if (e.kind === "comment") {+ ctx.out.line(ctx.out.style("dim", `${who} · ${e.createdAt}`));+ ctx.out.line(e.body ?? "");+ } else+ ctx.out.line(+ ctx.out.style("dim", `${who} ${e.kind} this · ${e.createdAt}`),+ );+ }+ }+}++/** list, view, comment, close, reopen and edit: the same for issues and pull requests. */+export function registerShared(parent: Command, kind: IssueKind, wrap: Wrap) {+ const what = noun(kind);++ parent+ .command("list")+ .description(`List ${what}s`)+ .option("-s, --state <state>", "open, closed or all", "open")+ .option("-S, --search <query>", "search titles and bodies")+ .option("-L, --limit <n>", "at most this many", "30")+ .action(+ wrap(+ async (+ ctx,+ opts: { state: string; search?: string; limit: string },+ ) => {+ if (!["open", "closed", "all"].includes(opts.state))+ throw usageError("--state is open, closed or all");+ const repo = await ctx.repo();+ const res = await (await ctx.client()).listIssues(repo.id, kind, {+ state: opts.state,+ q: opts.search,+ });+ const items = res.items.slice(+ 0,+ Math.max(1, Number(opts.limit) || 30),+ );+ ctx.out.result(items, () => {+ if (items.length === 0)+ ctx.out.info(+ `no ${opts.state === "all" ? "" : `${opts.state} `}${what}s in ${repo.name}`,+ );+ ctx.out.table(+ items.map((i) => ({+ number: `#${i.number}`,+ title: i.title,+ branch: i.headRef ? `${i.headRef} → ${i.baseRef}` : undefined,+ labels: i.labels.join(", "),+ state: i.isDraft && i.state === "open" ? "draft" : i.state,+ updated: i.updatedAt,+ })),+ [+ { key: "number", label: "#" },+ { key: "title", label: "title" },+ ...(kind === "pulls"+ ? [{ key: "branch", label: "branch" }]+ : [{ key: "labels", label: "labels" }]),+ { key: "state", label: "state" },+ { key: "updated", label: "updated" },+ ],+ );+ });+ },+ ),+ );++ parent+ .command("view")+ .description(`Show a ${what}`)+ .argument("<number>")+ .option("-c, --comments", "include comments and events")+ .action(+ wrap(async (ctx, n: string, opts: { comments?: boolean }) => {+ const repo = await ctx.repo();+ const item = await (await ctx.client()).getIssue(+ repo.id,+ kind,+ issueNumber(n),+ );+ ctx.out.result(item, () => printIssue(ctx, item, !!opts.comments));+ }),+ );++ parent+ .command("comment")+ .description(`Comment on a ${what}`)+ .argument("<number>")+ .option("-b, --body <text>", "comment text")+ .option(+ "-F, --body-file <file>",+ "read the comment from a file (- for stdin)",+ )+ .action(+ wrap(+ async (ctx, n: string, opts: { body?: string; bodyFile?: string }) => {+ const repo = await ctx.repo();+ const body = (await readBody(ctx, opts, undefined))?.trim();+ if (!body)+ throw usageError(+ "the comment is empty",+ `ff ${kind === "pulls" ? "pr" : "issue"} comment ${n} --body "…"`,+ );+ await (await ctx.client()).commentIssue(+ repo.id,+ kind,+ issueNumber(n),+ body,+ );+ ctx.out.result({ ok: true, number: issueNumber(n) }, () =>+ ctx.out.line(`commented on #${issueNumber(n)}`),+ );+ },+ ),+ );++ parent+ .command("close")+ .description(`Close a ${what}`)+ .argument("<number>")+ .option("-c, --comment <text>", "leave a comment first")+ .action(+ wrap(async (ctx, n: string, opts: { comment?: string }) => {+ const repo = await ctx.repo();+ const client = await ctx.client();+ const num = issueNumber(n);+ if (opts.comment)+ await client.commentIssue(repo.id, kind, num, opts.comment);+ await client.updateIssue(repo.id, kind, num, { state: "closed" });+ ctx.out.result({ ok: true, number: num, state: "closed" }, () =>+ ctx.out.line(`closed #${num}`),+ );+ }),+ );++ parent+ .command("reopen")+ .description(`Reopen a ${what}`)+ .argument("<number>")+ .action(+ wrap(async (ctx, n: string) => {+ const repo = await ctx.repo();+ const num = issueNumber(n);+ await (await ctx.client()).updateIssue(repo.id, kind, num, {+ state: "open",+ });+ ctx.out.result({ ok: true, number: num, state: "open" }, () =>+ ctx.out.line(`reopened #${num}`),+ );+ }),+ );++ parent+ .command("edit")+ .description(`Edit a ${what}'s title, body or labels`)+ .argument("<number>")+ .option("-t, --title <title>", "new title")+ .option("-b, --body <text>", "new body")+ .option("-F, --body-file <file>", "read the body from a file (- for stdin)")+ .option("--add-label <label>", "add a label (repeatable)", collect, [])+ .option(+ "--remove-label <label>",+ "remove a label (repeatable)",+ collect,+ [],+ )+ .action(+ wrap(+ async (+ ctx,+ n: string,+ opts: {+ title?: string;+ body?: string;+ bodyFile?: string;+ addLabel: string[];+ removeLabel: string[];+ },+ ) => {+ const repo = await ctx.repo();+ const client = await ctx.client();+ const num = issueNumber(n);+ const patch: Record<string, unknown> = {};+ if (opts.title !== undefined) patch.title = opts.title;+ const body =+ opts.body !== undefined || opts.bodyFile !== undefined+ ? await readBody(ctx, opts, "")+ : undefined;+ if (body !== undefined) patch.body = body;+ if (opts.addLabel.length || opts.removeLabel.length) {+ const current = await client.getIssue(repo.id, kind, num);+ const labels = new Set(current.labels);+ for (const l of opts.addLabel) labels.add(l);+ for (const l of opts.removeLabel) labels.delete(l);+ patch.labels = [...labels];+ }+ if (Object.keys(patch).length === 0)+ throw usageError(+ "nothing to change",+ "pass --title, --body, --add-label or --remove-label",+ );+ await client.updateIssue(repo.id, kind, num, patch);+ ctx.out.result({ ok: true, number: num, ...patch }, () =>+ ctx.out.line(`updated #${num}`),+ );+ },+ ),+ );+}++export function register(program: Command, wrap: Wrap) {+ const issue = program+ .command("issue")+ .description("Work with issues (gh-style)");++ issue+ .command("create")+ .description("Open an issue")+ .requiredOption("-t, --title <title>", "title")+ .option("-b, --body <text>", "body")+ .option("-F, --body-file <file>", "read the body from a file (- for stdin)")+ .option("-l, --label <label>", "add a label (repeatable)", collect, [])+ .action(+ wrap(+ async (+ ctx,+ opts: {+ title: string;+ body?: string;+ bodyFile?: string;+ label: string[];+ },+ ) => {+ const repo = await ctx.repo();+ const body = (await readBody(ctx, opts, undefined)) ?? "";+ const created = await (await ctx.client()).createIssue(+ repo.id,+ "issues",+ { title: opts.title, body, labels: opts.label },+ );+ const url = `${(await ctx.client()).host}/repos/${repo.id}/issues/${created.number}`;+ ctx.out.result({ ...created, url }, () => ctx.out.line(url));+ },+ ),+ );++ registerShared(issue, "issues", wrap);+}diff --git a/packages/cli/src/commands/ls.ts b/packages/cli/src/commands/ls.tsnew file mode 100644index 00000000..3780845a--- /dev/null+++ b/packages/cli/src/commands/ls.ts@@ -0,0 +1,43 @@+import fs from "node:fs";+import path from "node:path";+import type { Command } from "commander";+import type { Wrap } from "../cli.js";++export function register(program: Command, wrap: Wrap) {+ program+ .command("ls")+ .description("List the project's compositions")+ .action(+ wrap(async (ctx) => {+ const project = await ctx.project();+ ctx.out.result(project, () => {+ ctx.out.table(+ project.compositions.map((c) => ({+ id: c.id,+ title: c.title,+ group: c.group,+ entry: `${c.entry}#${c.export}`,+ default: c.default ? "yes" : "",+ })),+ [+ { key: "id", label: "id" },+ { key: "title", label: "title" },+ { key: "group", label: "group" },+ { key: "entry", label: "entry" },+ { key: "default", label: "default" },+ ],+ );+ });+ if (project.source === "default") {+ const film = project.compositions[0];+ const exists =+ film && fs.existsSync(path.join(project.root, film.entry));+ ctx.out.info(+ exists+ ? "no framefields.json: using the default composition"+ : `no framefields.json and no ${film?.entry}: create one, or run ff init`,+ );+ }+ }),+ );+}diff --git a/packages/cli/src/commands/pr.ts b/packages/cli/src/commands/pr.tsnew file mode 100644index 00000000..05fc36f2--- /dev/null+++ b/packages/cli/src/commands/pr.ts@@ -0,0 +1,309 @@+import type { Command } from "commander";+import { loadProject } from "framefields/project";+import { readLockfile } from "../assets.js";+import type { Wrap } from "../cli.js";+import type { Repository } from "../cloud/client.js";+import type { Context } from "../context.js";+import { CliError, usageError } from "../errors.js";+import * as git from "../git/index.js";+import { pullProjectAssets } from "./asset.js";+import { issueNumber, readBody, registerShared } from "./issue.js";+import { push } from "./sync.js";++const collect = (value: string, previous: string[] = []) => [+ ...previous,+ value,+];++export function register(program: Command, wrap: Wrap) {+ const pr = program+ .command("pr")+ .description("Work with pull requests (gh-style)");++ pr.command("create")+ .description("Open a pull request; pushes the head branch first if needed")+ .option(+ "-B, --base <branch>",+ "branch to merge into (default: the repository's default branch)",+ )+ .option(+ "-H, --head <branch>",+ "branch with the changes (default: the current branch)",+ )+ .option("-t, --title <title>", "title")+ .option("-b, --body <text>", "body")+ .option("-F, --body-file <file>", "read the body from a file (- for stdin)")+ .option("-l, --label <label>", "add a label (repeatable)", collect, [])+ .option("-d, --draft", "open as a draft")+ .option("--remote <name>", "git remote", "origin")+ .action(+ wrap(+ async (+ ctx,+ opts: {+ base?: string;+ head?: string;+ title?: string;+ body?: string;+ bodyFile?: string;+ label: string[];+ draft?: boolean;+ remote: string;+ },+ ) => {+ const root = await ctx.gitRoot();+ const repo = await ctx.repo();+ const client = await ctx.client();+ const head = opts.head ?? (await git.currentBranch(root));+ if (!head)+ throw usageError(+ "HEAD is detached: which branch?",+ "ff pr create --head <branch>",+ );+ const base = opts.base ?? repo.defaultBranch;+ if (head === base)+ throw usageError(+ `head and base are both '${base}'`,+ "create a branch for your changes: git switch -c <branch>",+ );+ let title = opts.title;+ if (!title && (await ctx.canPrompt()))+ title = await ctx.io.prompt("Title");+ if (!title)+ throw usageError(+ "a pull request needs a title",+ 'ff pr create --title "…"',+ );+ const body = (await readBody(ctx, opts, undefined)) ?? "";++ // Push the head branch when the remote doesn't have it as it is here.+ const local = await git.gitMaybe(+ ["rev-parse", "--verify", `refs/heads/${head}`],+ root,+ );+ if (local) {+ const remote = await git.gitMaybe(+ ["rev-parse", "--verify", `refs/remotes/${opts.remote}/${head}`],+ root,+ );+ if (remote !== local) {+ ctx.out.info(`pushing ${head}`);+ await push(ctx, { remote: opts.remote, branch: head, repo });+ }+ }+ const created = await client.createIssue(repo.id, "pulls", {+ title,+ body,+ labels: opts.label,+ headRef: head,+ baseRef: base,+ draft: !!opts.draft,+ });+ const url = `${client.host}/repos/${repo.id}/pulls/${created.number}`;+ ctx.out.result({ ...created, url }, () => ctx.out.line(url));+ },+ ),+ );++ registerShared(pr, "pulls", wrap);++ pr.command("ready")+ .description("Mark a draft pull request ready for review")+ .argument("<number>")+ .action(+ wrap(async (ctx, n: string) => {+ const repo = await ctx.repo();+ const num = issueNumber(n);+ await (await ctx.client()).updateIssue(repo.id, "pulls", num, {+ draft: false,+ });+ ctx.out.result({ ok: true, number: num, isDraft: false }, () =>+ ctx.out.line(`#${num} is ready for review`),+ );+ }),+ );++ pr.command("merge")+ .description(+ "Merge head into base with local git, push base, then record the merge",+ )+ .argument("<number>")+ .option("--squash", "squash the changes into one commit")+ .option("--merge", "create a merge commit (default)")+ .option("-d, --delete-branch", "delete the head branch afterwards")+ .option("--remote <name>", "git remote", "origin")+ .action(+ wrap(+ async (+ ctx,+ n: string,+ opts: {+ squash?: boolean;+ merge?: boolean;+ deleteBranch?: boolean;+ remote: string;+ },+ ) => {+ if (opts.squash && opts.merge)+ throw usageError("--squash and --merge are exclusive");+ const root = await ctx.gitRoot();+ const repo = await ctx.repo();+ const client = await ctx.client();+ const num = issueNumber(n);+ const pull = await client.getIssue(repo.id, "pulls", num);+ if (pull.state !== "open")+ throw new CliError(`#${num} is ${pull.state}`);+ if (pull.isDraft)+ throw new CliError(`#${num} is a draft`, {+ hint: `ff pr ready ${num}`,+ });+ const head = pull.headRef as string;+ const base = pull.baseRef as string;+ if ((await git.dirtyFiles(root)).length) {+ throw new CliError("you have uncommitted changes", {+ hint: "commit or stash them, then ff pr merge again",+ });+ }+ const original = await git.currentBranch(root);+ const remote = opts.remote;+ await fetchBranches(ctx, root, repo, remote, [base, head]);+ await checkoutTracking(root, remote, base);++ const message = opts.squash+ ? `${pull.title} (#${num})`+ : `Merge pull request #${num} from ${head}`;+ const merged = await git.git(+ opts.squash+ ? ["merge", "--squash", `${remote}/${head}`]+ : ["merge", "--no-ff", "-m", message, `${remote}/${head}`],+ { cwd: root },+ );+ if (merged.code !== 0) {+ await git.git(["merge", "--abort"], { cwd: root });+ await git.git(["reset", "--hard", "--quiet", "HEAD"], {+ cwd: root,+ });+ if (original && original !== base)+ await git.git(["checkout", "--quiet", original], { cwd: root });+ throw new CliError(`${head} does not merge cleanly into ${base}`, {+ hint: `merge ${base} into ${head}, resolve the conflicts, ff push, then ff pr merge ${num}`,+ });+ }+ if (opts.squash)+ await git.gitOk(["commit", "--quiet", "-m", message], {+ cwd: root,+ });++ const pushed = await push(ctx, { remote, branch: base, repo });+ const recorded = await client.mergePull(repo.id, num);++ if (opts.deleteBranch) {+ const { token } = await client.gitToken(repo.id, "write");+ await git.git(["push", remote, "--delete", head], {+ cwd: root,+ token,+ });+ await client+ .deleteAssetRefs(repo.id, `refs/heads/${head}`)+ .catch(() => {});+ if (original !== head)+ await git.git(["branch", "-D", head], { cwd: root });+ }+ const back =+ original &&+ original !== base &&+ !(opts.deleteBranch && original === head)+ ? original+ : undefined;+ if (back)+ await git.gitOk(["checkout", "--quiet", back], { cwd: root });+ ctx.out.result(+ { ...recorded, base, head, commitSha: pushed.commitSha },+ () =>+ ctx.out.line(+ `merged #${num} (${head} → ${base}, ${pushed.commitSha.slice(0, 7)})`,+ ),+ );+ },+ ),+ );++ pr.command("checkout")+ .description("Check out a pull request's head branch")+ .argument("<number>")+ .option("--remote <name>", "git remote", "origin")+ .action(+ wrap(async (ctx, n: string, opts: { remote: string }) => {+ const root = await ctx.gitRoot();+ const repo = await ctx.repo();+ const pull = await (await ctx.client()).getIssue(+ repo.id,+ "pulls",+ issueNumber(n),+ );+ const head = pull.headRef as string;+ if ((await git.dirtyFiles(root)).length) {+ throw new CliError("you have uncommitted changes", {+ hint: "commit or stash them first",+ });+ }+ await fetchBranches(ctx, root, repo, opts.remote, [head]);+ await checkoutTracking(root, opts.remote, head);+ const project = await loadProject(ctx.cwd).catch(() => undefined);+ const assets =+ project && readLockfile(project)+ ? await pullProjectAssets(ctx, project)+ : null;+ ctx.out.result({ branch: head, assets }, () =>+ ctx.out.line(`switched to ${head}`),+ );+ }),+ );+}++async function fetchBranches(+ ctx: Context,+ root: string,+ repo: Repository,+ remote: string,+ branches: string[],+) {+ const { token } = await (await ctx.client()).gitToken(repo.id, "read");+ await git.gitOk(+ [+ "fetch",+ "--quiet",+ remote,+ ...branches.map((b) => `+refs/heads/${b}:refs/remotes/${remote}/${b}`),+ ],+ { cwd: root, token },+ );+}++/** Checks out `branch`, creating it from (or fast-forwarding it to) `remote/branch`. */+async function checkoutTracking(root: string, remote: string, branch: string) {+ const exists = await git.gitMaybe(+ ["rev-parse", "--verify", `refs/heads/${branch}`],+ root,+ );+ if (!exists) {+ await git.gitOk(+ ["checkout", "--quiet", "-b", branch, "--track", `${remote}/${branch}`],+ { cwd: root },+ );+ return;+ }+ await git.gitOk(["checkout", "--quiet", branch], { cwd: root });+ const ff = await git.git(+ ["merge", "--ff-only", "--quiet", `${remote}/${branch}`],+ { cwd: root },+ );+ if (ff.code !== 0) {+ throw new CliError(+ `local ${branch} has diverged from ${remote}/${branch}`,+ {+ hint: `reconcile it (git pull --rebase ${remote} ${branch}), then try again`,+ },+ );+ }+}diff --git a/packages/cli/src/commands/preview.ts b/packages/cli/src/commands/preview.tsnew file mode 100644index 00000000..e156384d--- /dev/null+++ b/packages/cli/src/commands/preview.ts@@ -0,0 +1,66 @@+import path from "node:path";+import type { Command } from "commander";+import type { Wrap } from "../cli.js";+import { resolveTarget } from "../compositions.js";+import { usageError } from "../errors.js";++export function register(program: Command, wrap: Wrap) {+ program+ .command("preview")+ .description("Start the live preview of a composition and print its URL")+ .argument(+ "[composition]",+ "composition id or file#export (default composition when omitted)",+ )+ .option("--open", "open the page in the system browser")+ .option("--port <port>", "port to listen on (default: stable per project)")+ .option("--no-audio", "don't mix or play the soundtrack")+ .action(+ wrap(+ async (+ ctx,+ ref: string | undefined,+ opts: { open?: boolean; port?: string; audio: boolean },+ ) => {+ const project = await ctx.project();+ const target = resolveTarget(project, ref);+ const port = opts.port === undefined ? undefined : Number(opts.port);+ if (+ port !== undefined &&+ (!Number.isInteger(port) || port < 0 || port > 65535)+ ) {+ throw usageError(`--port ${opts.port} is not a port number`);+ }+ const engine = await ctx.engine(project);+ const options = {+ open: !!opts.open,+ port,+ audio: opts.audio,+ title: target.title,+ };+ // Engines that read framefields.json switch between compositions in the+ // page; older ones preview one entry.+ const session = ctx.engineHasProject(project)+ ? await engine.startPreview(+ { project, composition: ref },+ { ...options, title: undefined },+ )+ : await engine.startPreview(+ {+ entry: path.join(project.root, target.entry),+ export: target.export,+ },+ options,+ );+ ctx.out.result({ url: session.url, composition: target.id }, () =>+ ctx.out.line(session.url),+ );+ ctx.out.info(+ `previewing ${target.id}; serves until its tab closes or the next ff preview takes over (ctrl-c to stop)`,+ );+ const reason = await session.closed;+ ctx.out.debug(`preview stopped: ${reason}`);+ },+ ),+ );+}diff --git a/packages/cli/src/commands/render.ts b/packages/cli/src/commands/render.tsnew file mode 100644index 00000000..5a1eb5ff--- /dev/null+++ b/packages/cli/src/commands/render.ts@@ -0,0 +1,382 @@+import fs from "node:fs";+import path from "node:path";+import { Readable } from "node:stream";+import { pipeline } from "node:stream/promises";+import type { Command } from "commander";+import { isFileReference, loadProject } from "framefields/project";+import type { Wrap } from "../cli.js";+import type { RenderJob } from "../cloud/client.js";+import { loadComposition, outputDir, resolveTarget } from "../compositions.js";+import type { Context } from "../context.js";+import { CliError, usageError } from "../errors.js";+import * as git from "../git/index.js";+import { parseRange } from "../timecode.js";++interface RenderOptions {+ local?: boolean;+ quality?: string;+ fps?: string;+ range?: string;+ ref?: string;+ type: string;+ wait?: boolean;+ download?: boolean;+ remote: string;+}++const TERMINAL = new Set(["completed", "failed", "cancelled"]);+const POLL_MS = 2000;++export function register(program: Command, wrap: Wrap) {+ const render = program+ .command("render")+ .description(+ "Render a composition: on Framefields Cloud, or locally with --local (verification ladder, step 5)",+ )+ .argument("[composition]", "composition id or file#export")+ .option(+ "--local",+ "render here with the project's engine, to <output>/<id>.mp4",+ )+ .option("--quality <quality>", "encoder quality: low, medium, high")+ .option("--fps <fps>", "frames per second (default: the composition's)")+ .option(+ "--range <from..to>",+ "local only: render up to a frame or timecode, e.g. 0..120 or ..5s",+ )+ .option(+ "--ref <ref>",+ "cloud: the commit, branch or tag to render (default HEAD; must be pushed)",+ )+ .option("--type <type>", "cloud: video, frame or sheet", "video")+ .option("--wait", "cloud: wait until the render finishes")+ .option("--download", "cloud: wait, then save the deliverable to <output>/")+ .option(+ "--remote <name>",+ "cloud: the git remote HEAD must be pushed to",+ "origin",+ )+ .action(+ wrap(async (ctx, ref: string | undefined, opts: RenderOptions) => {+ if (opts.local) return renderLocal(ctx, ref, opts);+ return renderCloud(ctx, ref, opts);+ }),+ );++ render+ .command("status")+ .description("Show a render's status, progress and deliverable URL")+ .argument("<job>", "render job id")+ .option("--watch", "keep watching until it finishes")+ .action(+ wrap(async (ctx, jobId: string, opts: { watch?: boolean }) => {+ const job = opts.watch+ ? await waitFor(ctx, jobId)+ : await (await ctx.client()).getRender(jobId);+ ctx.out.result(job, () => printJob(ctx, job));+ if (opts.watch && job.status !== "completed")+ throw new CliError(+ `render ${job.status}${job.errorMessage ? `: ${job.errorMessage}` : ""}`,+ );+ }),+ );++ render+ .command("list")+ .description("List render jobs for the linked repository")+ .option(+ "--status <status>",+ "queued, running, completed, failed or cancelled",+ )+ .option("--composition <id>", "only this composition")+ .action(+ wrap(async (ctx, opts: { status?: string; composition?: string }) => {+ const repo = await ctx.repo();+ let jobs = await (await ctx.client()).listRenders(repo.id);+ if (opts.status) jobs = jobs.filter((j) => j.status === opts.status);+ if (opts.composition)+ jobs = jobs.filter((j) => j.composition === opts.composition);+ jobs.sort((a, b) =>+ String(b.createdAt).localeCompare(String(a.createdAt)),+ );+ ctx.out.result(jobs, () => {+ if (jobs.length === 0) ctx.out.info("no render jobs");+ ctx.out.table(+ jobs.map((j) => ({+ id: j.id,+ status: j.status,+ composition: j.composition ?? `${j.entryPath}#${j.exportName}`,+ type: j.jobType,+ commit: j.commitSha.slice(0, 7),+ created: j.createdAt,+ })),+ ["id", "status", "composition", "type", "commit", "created"].map(+ (key) => ({ key, label: key }),+ ),+ );+ });+ }),+ );++ render+ .command("download")+ .description("Save a render's deliverable")+ .argument("<job>", "render job id")+ .option(+ "-o, --output <file>",+ "where to save it (default <output>/<composition>-<job>.<ext>)",+ )+ .action(+ wrap(async (ctx, jobId: string, opts: { output?: string }) => {+ const job = await (await ctx.client()).getRender(jobId);+ const file = await download(ctx, job, opts.output);+ ctx.out.result({ files: [file] }, () => ctx.out.line(file));+ }),+ );++ render+ .command("cancel")+ .description("Cancel a queued or running render")+ .argument("<job>", "render job id")+ .action(+ wrap(async (ctx, jobId: string) => {+ const client = await ctx.client();+ try {+ await client.cancelRender(jobId);+ } catch (err) {+ if (err instanceof CliError && /HTTP (404|405)/.test(err.message)) {+ throw new CliError(+ `${client.host} does not support cancelling renders yet`,+ {+ hint: "this needs POST /v1/renders/:id/cancel on the server",+ },+ );+ }+ throw err;+ }+ const job = await client.getRender(jobId);+ ctx.out.result(job, () => ctx.out.line(`${job.id} ${job.status}`));+ }),+ );+}++async function renderLocal(+ ctx: Context,+ ref: string | undefined,+ opts: RenderOptions,+) {+ const { project, target, composition, frameCount } = await loadComposition(+ ctx,+ ref,+ );+ if (opts.fps !== undefined) {+ const fps = Number(opts.fps);+ if (!(fps > 0 && fps <= 240))+ throw usageError(`--fps ${opts.fps} must be between 1 and 240`);+ composition.fps = fps;+ }+ if (opts.range) {+ const { from, to } = parseRange(opts.range, composition.fps);+ if (from) {+ throw usageError(+ "local renders start at frame 0",+ `use --range ..${opts.range.split(/\.\.|-/)[1] ?? ""} or ff frames for single frames`,+ );+ }+ if (to !== undefined) {+ const end = Math.min(to, frameCount - 1);+ composition.durationMs = ((end + 1) / composition.fps) * 1000;+ }+ }+ const file = path.join(await outputDir(project), `${target.id}.mp4`);+ const started = Date.now();+ ctx.out.info(`rendering ${target.id} to ${ctx.relative(project, file)}`);+ const result = await composition.renderVideo({+ outputPath: file,+ quality: opts.quality ?? "high",+ });+ await result.cleanup?.().catch(() => {});+ const rel = ctx.relative(project, result.filePath);+ ctx.out.info(`done in ${((Date.now() - started) / 1000).toFixed(1)} s`);+ ctx.out.result({ files: [rel] }, () => ctx.out.line(rel));+}++async function renderCloud(+ ctx: Context,+ ref: string | undefined,+ opts: RenderOptions,+) {+ if (opts.range) throw usageError("--range is only supported with --local");+ if (!["video", "frame", "sheet"].includes(opts.type))+ throw usageError(`--type must be video, frame or sheet`);+ const client = await ctx.client();+ client.requireToken();+ const repo = await ctx.repo();+ const root = await ctx.gitRoot();+ const rev = opts.ref ?? "HEAD";+ const commitSha = await git.gitMaybe(+ ["rev-parse", "--verify", `${rev}^{commit}`],+ root,+ );+ if (!commitSha)+ throw usageError(`'${rev}' is not a commit in this repository`);+ const pushed = await git.gitMaybe(+ [+ "for-each-ref",+ "--contains",+ commitSha,+ "--format=%(refname)",+ `refs/remotes/${opts.remote}`,+ ],+ root,+ );+ if (!pushed) {+ throw new CliError(+ `${rev === "HEAD" ? "HEAD" : rev} (${commitSha.slice(0, 7)}) is not pushed to ${opts.remote}`,+ {+ hint: "ff push",+ },+ );+ }+ if (rev === "HEAD" && (await git.dirtyFiles(root)).length > 0) {+ ctx.out.warn("uncommitted changes are not part of the render");+ }++ const body: Parameters<typeof client.createRender>[0] = {+ repositoryId: repo.id,+ commitSha,+ jobType: opts.type as "video" | "frame" | "sheet",+ options: {+ ...(opts.fps !== undefined && { fps: Number(opts.fps) }),+ ...(opts.quality !== undefined && { quality: opts.quality }),+ },+ };+ if (ref && isFileReference(ref)) {+ // The cloud renders manifest ids or an explicit entry/export (no `#` parsing server-side).+ const project = await loadProject(ctx.cwd).catch(() => undefined);+ const target = project ? resolveTarget(project, ref) : undefined;+ const [entry, exportName = "default"] = ref.split("#");+ body.entryPath = target?.entry ?? entry;+ body.exportName = target?.export ?? exportName;+ } else if (ref) {+ body.composition = ref;+ const project = await loadProject(ctx.cwd).catch(() => undefined);+ if (project?.source === "manifest") resolveTarget(project, ref);+ }++ const created = await client.createRender(body);+ const url = `${client.host}/renders`;+ if (!opts.wait && !opts.download) {+ ctx.out.result({ ...created, url }, () => {+ ctx.out.line(created.jobId);+ ctx.out.info(+ `queued ${created.composition ?? body.entryPath} at ${commitSha.slice(0, 7)} · ${url}`,+ );+ ctx.out.info(`follow it: ff render status ${created.jobId} --watch`);+ });+ return;+ }+ ctx.out.info(+ `queued ${created.jobId} (${created.composition ?? body.entryPath} at ${commitSha.slice(0, 7)})`,+ );+ const job = await waitFor(ctx, created.jobId);+ if (job.status !== "completed") {+ ctx.out.result(job, () => printJob(ctx, job));+ throw new CliError(+ `render ${job.status}${job.errorMessage ? `: ${job.errorMessage}` : ""}`,+ {+ hint: `ff render status ${job.id}`,+ },+ );+ }+ const files = opts.download ? [await download(ctx, job)] : [];+ ctx.out.result({ ...job, files }, () => {+ if (files.length) for (const f of files) ctx.out.line(f);+ else printJob(ctx, job);+ });+}++/** Polls until the job finishes (`GET /v1/renders/:id/events` would replace this). */+async function waitFor(ctx: Context, jobId: string): Promise<RenderJob> {+ const client = await ctx.client();+ let last = "";+ for (;;) {+ const job = await client.getRender(jobId);+ const line = `${job.status}${typeof job.progress === "number" ? ` ${Math.round(job.progress * 100)}%` : ""}`;+ if (line !== last) ctx.out.info(`${jobId}: ${line}`);+ last = line;+ if (TERMINAL.has(job.status)) return job;+ await new Promise((r) => setTimeout(r, POLL_MS));+ }+}++function printJob(ctx: Context, job: RenderJob) {+ ctx.out.view([+ ["id", job.id],+ ["status", job.status],+ ["composition", job.composition ?? `${job.entryPath}#${job.exportName}`],+ ["type", job.jobType],+ ["commit", job.commitSha],+ [+ "progress",+ typeof job.progress === "number"+ ? `${Math.round(job.progress * 100)}%`+ : undefined,+ ],+ ["created", job.createdAt],+ ["completed", job.completedAt],+ ["error", job.errorMessage ?? undefined],+ ["download", job.downloadUrl],+ ]);+}++const EXTENSIONS: Record<string, string> = {+ video: "mp4",+ frame: "png",+ sheet: "png",+};++async function download(+ ctx: Context,+ job: RenderJob,+ output?: string,+): Promise<string> {+ if (job.status !== "completed" || !job.downloadUrl) {+ throw new CliError(+ `render ${job.id} has no deliverable (status: ${job.status})`,+ {+ hint:+ job.status === "completed"+ ? undefined+ : `ff render status ${job.id} --watch`,+ },+ );+ }+ const client = await ctx.client();+ const sameHost =+ !/^https?:\/\//.test(job.downloadUrl) ||+ job.downloadUrl.startsWith(client.host);+ const res = await client.raw("GET", job.downloadUrl, {+ anonymous: !sameHost,+ });+ if (!res.ok || !res.body)+ throw new CliError(`could not download ${job.id}: HTTP ${res.status}`);+ let file: string;+ if (output) file = path.resolve(ctx.cwd, output);+ else {+ const project = await ctx.project().catch(() => undefined);+ const dir = project ? await outputDir(project) : ctx.cwd;+ file = path.join(+ dir,+ `${job.composition ?? "render"}-${job.id}.${EXTENSIONS[job.jobType] ?? "bin"}`,+ );+ }+ await fs.promises.mkdir(path.dirname(file), { recursive: true });+ const tmp = `${file}.part`;+ await pipeline(+ Readable.fromWeb(res.body as never),+ fs.createWriteStream(tmp),+ );+ await fs.promises.rename(tmp, file);+ return path.relative(ctx.cwd, file) || file;+}diff --git a/packages/cli/src/commands/repo.ts b/packages/cli/src/commands/repo.tsnew file mode 100644index 00000000..58c3dab1--- /dev/null+++ b/packages/cli/src/commands/repo.ts@@ -0,0 +1,223 @@+import path from "node:path";+import type { Command } from "commander";+import type { Wrap } from "../cli.js";+import type { CompositionsResponse } from "../cloud/client.js";+import { CliError, usageError } from "../errors.js";+import * as git from "../git/index.js";+import { cloneRepo } from "./clone.js";+import { push } from "./sync.js";++const NAME = /^[A-Za-z0-9._-]{1,64}$/;++export function register(program: Command, wrap: Wrap) {+ const repo = program+ .command("repo")+ .description(+ "Create, view, fork and delete Framefields Cloud repositories",+ );++ repo+ .command("create")+ .description(+ "Create a cloud repository, add it as a git remote and link this directory",+ )+ .argument("[name]", "repository name (default: the directory name)")+ .option("--public", "anyone can fork it")+ .option("--private", "only your organization (default)")+ .option("-d, --description <text>", "description")+ .option("--remote <name>", "git remote to add", "origin")+ .option("--push", "push the current branch afterwards")+ .action(+ wrap(+ async (+ ctx,+ name: string | undefined,+ opts: {+ public?: boolean;+ private?: boolean;+ description?: string;+ remote: string;+ push?: boolean;+ },+ ) => {+ if (opts.public && opts.private)+ throw usageError("--public and --private are exclusive");+ const project = await ctx.project().catch(() => undefined);+ const dir = (await git.topLevel(ctx.cwd)) ?? project?.root ?? ctx.cwd;+ const repoName =+ name ?? path.basename(dir).replace(/[^A-Za-z0-9._-]+/g, "-");+ if (!NAME.test(repoName))+ throw usageError(+ `'${repoName}' is not a valid repository name`,+ "use letters, digits, '.', '_' and '-'",+ );+ const existing = await git.remoteUrl(dir, opts.remote);+ if (existing) {+ throw new CliError(+ `this repository already has a '${opts.remote}' remote (${existing})`,+ {+ hint: `ff repo create ${repoName} --remote framefields`,+ },+ );+ }+ const client = await ctx.client();+ const created = await client.createRepo({+ name: repoName,+ description: opts.description,+ visibility: opts.public ? "public" : "private",+ });+ const { token: _token, ...repository } = created;+ if (!(await git.isRepo(dir))) {+ await git.gitOk(["init", "--quiet", "-b", created.defaultBranch], {+ cwd: dir,+ });+ ctx.out.info(`initialized git in ${ctx.relativeCwd(dir)}`);+ }+ await git.gitOk(["remote", "add", opts.remote, created.remoteUrl], {+ cwd: dir,+ });+ await ctx.link(dir, repository);+ let pushed = null;+ if (opts.push) {+ if (!(await git.gitMaybe(["rev-parse", "--verify", "HEAD"], dir))) {+ ctx.out.warn("nothing to push yet: commit first, then ff push");+ } else+ pushed = await push(ctx, {+ remote: opts.remote,+ repo: repository,+ });+ }+ ctx.out.result({ ...repository, pushed }, () => {+ ctx.out.line(`created ${repository.name} (${repository.id})`);+ ctx.out.line(`remote ${opts.remote} → ${repository.remoteUrl}`);+ if (pushed)+ ctx.out.line(+ `pushed ${pushed.branch} (${pushed.commitSha.slice(0, 7)})`,+ );+ });+ },+ ),+ );++ repo+ .command("view")+ .description(+ "Show a repository: visibility, default branch, remote, compositions",+ )+ .argument("[repo]", "name or id (default: the linked repository)")+ .option("--web", "open it in the browser")+ .option("--ref <ref>", "branch to read compositions from")+ .action(+ wrap(+ async (+ ctx,+ ref: string | undefined,+ opts: { web?: boolean; ref?: string },+ ) => {+ const r = await ctx.repo(ref);+ const client = await ctx.client();+ if (opts.web) {+ const url = `${client.host}/repos/${r.id}`;+ ctx.io.openUrl(url);+ ctx.out.result({ url }, () => ctx.out.line(url));+ return;+ }+ const compositions: CompositionsResponse | null = await client+ .compositions(r.id, opts.ref)+ .catch(() => null);+ ctx.out.result({ ...r, compositions }, () => {+ ctx.out.view([+ ["name", r.name],+ ["id", r.id],+ ["description", r.description || undefined],+ ["visibility", r.visibility],+ ["default branch", r.defaultBranch],+ ["remote", r.remoteUrl],+ ["url", `${client.host}/repos/${r.id}`],+ ]);+ if (compositions?.source === "invalid")+ ctx.out.line(+ `compositions: invalid framefields.json: ${compositions.error}`,+ );+ else if (compositions) {+ ctx.out.line(`compositions (${compositions.ref}):`);+ for (const c of compositions.compositions) {+ ctx.out.line(+ ` ${c.id}${c.default ? " (default)" : ""} ${c.title} ${c.entry}#${c.export}`,+ );+ }+ }+ });+ },+ ),+ );++ repo+ .command("list")+ .description("List repositories in the organization")+ .action(+ wrap(async (ctx) => {+ const repos = await (await ctx.client()).listRepos();+ ctx.out.result(repos, () => {+ if (repos.length === 0)+ ctx.out.info("no repositories yet: ff repo create");+ ctx.out.table(+ repos.map((r) => ({ ...r, updated: r.updatedAt })),+ [+ { key: "name", label: "name" },+ { key: "id", label: "id" },+ { key: "visibility", label: "visibility" },+ { key: "defaultBranch", label: "branch" },+ { key: "updated", label: "updated" },+ ],+ );+ });+ }),+ );++ repo+ .command("fork")+ .description("Fork a repository (its assets are shared, not copied)")+ .argument("<repo>", "name or id")+ .option("--name <name>", "name of the fork (default <repo>-fork)")+ .option("--clone", "clone the fork")+ .action(+ wrap(+ async (ctx, ref: string, opts: { name?: string; clone?: boolean }) => {+ const source = await ctx.repo(ref);+ const { token: _token, ...fork } = await (+ await ctx.client()+ ).forkRepo(source.id, { name: opts.name });+ const cloned = opts.clone ? await cloneRepo(ctx, fork) : null;+ ctx.out.result({ ...fork, cloned }, () => {+ ctx.out.line(`forked ${source.name} → ${fork.name} (${fork.id})`);+ if (cloned) ctx.out.line(cloned.directory);+ });+ },+ ),+ );++ repo+ .command("delete")+ .description("Delete a repository")+ .argument("<repo>", "name or id")+ .action(+ wrap(async (ctx, ref: string) => {+ const r = await ctx.repo(ref);+ if (!ctx.yes) {+ if (!(await ctx.canPrompt()))+ throw usageError(+ `deleting ${r.name} needs confirmation`,+ `ff repo delete ${r.name} --yes`,+ );+ const typed = await ctx.io.prompt(`Type ${r.name} to delete it`);+ if (typed !== r.name)+ throw new CliError("not deleted: the name didn't match");+ }+ await (await ctx.client()).deleteRepo(r.id);+ ctx.out.result({ deleted: r.id, name: r.name }, () =>+ ctx.out.line(`deleted ${r.name}`),+ );+ }),+ );+}diff --git a/packages/cli/src/commands/sync.ts b/packages/cli/src/commands/sync.tsnew file mode 100644index 00000000..60695258--- /dev/null+++ b/packages/cli/src/commands/sync.ts@@ -0,0 +1,261 @@+/** `ff push` and `ff pull`: git plus external assets. */+import path from "node:path";+import type { Command } from "commander";+import { loadProject } from "framefields/project";+import { LOCKFILE, readLockfile } from "../assets.js";+import type { Wrap } from "../cli.js";+import type { Repository } from "../cloud/client.js";+import { type Context, fromProjectError } from "../context.js";+import { CliError, usageError } from "../errors.js";+import * as git from "../git/index.js";+import {+ formatBytes,+ printSync,+ pullProjectAssets,+ type SyncSummary,+ syncAssets,+} from "./asset.js";++export interface PushResult {+ remote: string;+ branch: string;+ ref: string;+ commitSha: string;+ assets: SyncSummary | null;+ lockfileCommitted: boolean;+ assetRefs: Record<string, unknown> | null;+ lockfile: { assets: number; bytes: number } | null;+}++/** Streams git's progress to stderr unless --quiet or --json. */+const gitProgress = (ctx: Context) =>+ ctx.out.options.quiet || ctx.out.json+ ? undefined+ : (t: string) => ctx.io.stderr(t);++/**+ * 1. ff asset sync. 2. Commit framefields.assets.json if it changed.+ * 3. git push with a short-lived token. 4. Record the ref's lockfile.+ */+export async function push(+ ctx: Context,+ options: { remote?: string; branch?: string; repo?: Repository } = {},+): Promise<PushResult> {+ const root = await ctx.gitRoot();+ const repo = options.repo ?? (await ctx.repo());+ const client = await ctx.client();+ const remote = options.remote ?? "origin";+ const branch = options.branch ?? (await git.currentBranch(root));+ if (!branch)+ throw usageError(+ "HEAD is detached: which branch?",+ `ff push ${remote} <branch>`,+ );+ if (!(await git.remoteUrl(root, remote))) {+ throw new CliError(`no git remote named '${remote}'`, {+ hint: `git remote add ${remote} ${repo.remoteUrl}`,+ });+ }++ // The project, if this repo has one (its assets ride along with the push).+ const project = await loadProject(ctx.cwd).catch((err: unknown) => {+ const mapped = fromProjectError(err);+ if (+ mapped instanceof CliError &&+ mapped.code === "project" &&+ /no framefields project/.test(mapped.message)+ )+ return undefined;+ throw mapped;+ });+ let assets: SyncSummary | null = null;+ let lockfileCommitted = false;+ if (project) {+ assets = await syncAssets(ctx, project, { repoId: repo.id });+ if (!ctx.out.json && (assets.uploaded.length || assets.removed.length))+ printSync(ctx, assets);+ const lockRel = path+ .relative(root, path.join(project.root, LOCKFILE))+ .split(path.sep)+ .join("/");+ const changed = await git.gitOk(["status", "--porcelain", "--", lockRel], {+ cwd: root,+ });+ if (changed) {+ const onBranch = await git.currentBranch(root);+ if (onBranch !== branch) {+ ctx.out.warn(+ `${LOCKFILE} changed but ${branch} is not checked out; commit it on ${branch} yourself`,+ );+ } else {+ await git.gitOk(["add", "--", lockRel], { cwd: root });+ await git.gitOk(+ [+ "commit",+ "--quiet",+ "-m",+ "assets: sync external assets",+ "--",+ lockRel,+ ],+ { cwd: root },+ );+ lockfileCommitted = true;+ ctx.out.info(`committed ${lockRel} (assets: sync external assets)`);+ }+ }+ }++ const { token } = await client.gitToken(repo.id, "write");+ const result = await git.git(+ [+ "push",+ "--porcelain",+ remote,+ `refs/heads/${branch}:refs/heads/${branch}`,+ ],+ {+ cwd: root,+ token,+ onStderr: gitProgress(ctx),+ },+ );+ if (result.code !== 0) {+ throw new CliError(+ `git push failed:\n ${(result.stderr || result.stdout).trim().split("\n").slice(-3).join("\n ")}`,+ {+ hint: /rejected|non-fast-forward|fetch first/.test(+ result.stderr + result.stdout,+ )+ ? "ff pull, then ff push again"+ : undefined,+ },+ );+ }+ const commitSha = await git.gitOk(["rev-parse", `refs/heads/${branch}`], {+ cwd: root,+ });+ const ref = `refs/heads/${branch}`;+ let assetRefs: Record<string, unknown> | null = null;+ let lockSummary: PushResult["lockfile"] = null;+ const lock = project ? readLockfile(project) : undefined;+ if (lock) {+ assetRefs = await client.putAssetRefs(repo.id, {+ ref,+ commitSha,+ lockfile: lock,+ });+ const entries = Object.values(lock.assets);+ lockSummary = {+ assets: entries.length,+ bytes: entries.reduce((s, e) => s + (e.size ?? e.sizeBytes ?? 0), 0),+ };+ }+ return {+ remote,+ branch,+ ref,+ commitSha,+ assets,+ lockfileCommitted,+ assetRefs,+ lockfile: lockSummary,+ };+}++export function register(program: Command, wrap: Wrap) {+ program+ .command("push")+ .description(+ `Sync assets, commit ${LOCKFILE} if it changed, git push, and record the ref's assets`,+ )+ .argument("[remote]", "git remote", "origin")+ .argument("[branch]", "branch (default: the current branch)")+ .option(+ "--delete <branch>",+ "delete a remote branch and release its assets",+ )+ .action(+ wrap(+ async (+ ctx,+ remote: string,+ branch: string | undefined,+ opts: { delete?: string },+ ) => {+ if (opts.delete) {+ const root = await ctx.gitRoot();+ const repo = await ctx.repo();+ const client = await ctx.client();+ const { token } = await client.gitToken(repo.id, "write");+ await git.gitOk(["push", remote, "--delete", opts.delete], {+ cwd: root,+ token,+ onStderr: gitProgress(ctx),+ });+ const released = await client.deleteAssetRefs(+ repo.id,+ `refs/heads/${opts.delete}`,+ );+ ctx.out.result({ deleted: opts.delete, released }, () =>+ ctx.out.line(`deleted ${remote}/${opts.delete}`),+ );+ return;+ }+ const result = await push(ctx, { remote, branch });+ ctx.out.result(result, () => {+ ctx.out.line(+ `pushed ${result.branch} → ${result.remote} (${result.commitSha.slice(0, 7)})`,+ );+ if (result.lockfile) {+ ctx.out.line(+ `${LOCKFILE}: ${result.lockfile.assets} assets, ${formatBytes(result.lockfile.bytes)} recorded for ${result.ref}`,+ );+ }+ });+ },+ ),+ );++ program+ .command("pull")+ .description("git pull, then download assets the lockfile needs")+ .argument("[remote]", "git remote", "origin")+ .argument("[branch]", "branch (default: the current branch's upstream)")+ .action(+ wrap(async (ctx, remote: string, branch: string | undefined) => {+ const root = await ctx.gitRoot();+ const repo = await ctx.repo();+ const client = await ctx.client();+ const { token } = await client.gitToken(repo.id, "read");+ const args = ["pull", "--ff", remote, ...(branch ? [branch] : [])];+ const result = await git.git(args, {+ cwd: root,+ token,+ onStderr: gitProgress(ctx),+ });+ if (result.code !== 0) {+ throw new CliError(+ `git pull failed:\n ${(result.stderr || result.stdout).trim().split("\n").slice(-3).join("\n ")}`,+ );+ }+ const project = await ctx.project().catch(() => undefined);+ const assets =+ project && readLockfile(project)+ ? await pullProjectAssets(ctx, project)+ : null;+ ctx.out.result({ git: result.stdout.trim(), assets }, () => {+ if (result.stdout.trim()) ctx.out.line(result.stdout.trim());+ if (assets)+ ctx.out.line(+ `assets: downloaded ${assets.downloaded.length}, already present ${assets.present.length}`,+ );+ });+ if (assets?.failed.length)+ throw new CliError(+ `${assets.failed.length} asset(s) failed to download`,+ { hint: "ff asset pull" },+ );+ }),+ );+}diff --git a/packages/cli/src/compositions.ts b/packages/cli/src/compositions.tsnew file mode 100644index 00000000..6a02f7d7--- /dev/null+++ b/packages/cli/src/compositions.ts@@ -0,0 +1,70 @@+import fs from "node:fs/promises";+import path from "node:path";+import type { Composition } from "framefields";+import {+ buildComposition,+ isFileReference,+ type Project,+ type ResolvedComposition,+ resolveComposition,+} from "framefields/project";+import { type Context, type Engine, fromProjectError } from "./context.js";++export interface Loaded {+ project: Project;+ engine: Engine;+ target: ResolvedComposition;+ composition: Composition;+ /** Frames in the composition (at least 1). */+ frameCount: number;+}++export function resolveTarget(+ project: Project,+ ref?: string,+): ResolvedComposition {+ try {+ return resolveComposition(project, ref);+ } catch (err) {+ throw fromProjectError(err);+ }+}++/** Builds a composition with the project's engine, ready to render. */+export async function loadComposition(+ ctx: Context,+ ref?: string,+): Promise<Loaded> {+ const project = await ctx.project();+ const target = resolveTarget(project, ref);+ const engine = await ctx.engine(project);+ ctx.out.info(`building ${target.id} (${target.entry}#${target.export})`);+ let composition: Composition;+ try {+ composition = await buildComposition(project, ref);+ } catch (err) {+ throw fromProjectError(err);+ }+ const durationMs =+ composition.durationMs ?? (await composition.computeDuration());+ composition.durationMs = durationMs;+ const frameCount = Math.max(+ 1,+ Math.round((durationMs / 1000) * composition.fps),+ );+ return { project, engine, target, composition, frameCount };+}++/** True when `ref` names a composition of the project (an id or a file reference). */+export function isCompositionRef(project: Project, ref: string): boolean {+ return isFileReference(ref) || project.compositions.some((c) => c.id === ref);+}++export async function outputDir(+ project: Project,+ ...parts: string[]+): Promise<string> {+ const dir = path.join(project.root, project.output, ...parts);+ await fs.mkdir(dir, { recursive: true });+ return dir;+}diff --git a/packages/cli/src/config.ts b/packages/cli/src/config.tsnew file mode 100644index 00000000..2337bf17--- /dev/null+++ b/packages/cli/src/config.ts@@ -0,0 +1,119 @@+/**+ * Per-user files under `~/.config/framefields` (or `$XDG_CONFIG_HOME`, or+ * `$FF_CONFIG_DIR`): `config.json` for `ff config`, `hosts.json` for+ * credentials (mode 0600).+ */+import fs from "node:fs/promises";+import os from "node:os";+import path from "node:path";+import { CliError, usageError } from "./errors.js";++export type Env = Record<string, string | undefined>;++export const DEFAULT_HOST = "https://framefields.dev";++export function configDir(env: Env): string {+ if (env.FF_CONFIG_DIR) return env.FF_CONFIG_DIR;+ const base =+ env.XDG_CONFIG_HOME || path.join(env.HOME || os.homedir(), ".config");+ return path.join(base, "framefields");+}++async function readJson<T>(file: string, fallback: T): Promise<T> {+ let raw: string;+ try {+ raw = await fs.readFile(file, "utf8");+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return fallback;+ throw err;+ }+ try {+ return JSON.parse(raw) as T;+ } catch (err) {+ throw new CliError(`${file} is not valid JSON: ${(err as Error).message}`);+ }+}++async function writeJson(file: string, value: unknown, mode?: number) {+ await fs.mkdir(path.dirname(file), { recursive: true, mode: 0o700 });+ const tmp = `${file}.${process.pid}.tmp`;+ await fs.writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`, { mode });+ await fs.rename(tmp, file);+ if (mode !== undefined) await fs.chmod(file, mode);+}++// ── ff config ──++export const CONFIG_KEYS = {+ host: "Framefields Cloud host used when no --host, FF_HOST or linked host is set",+ editor: "Editor for composing issue and pull request bodies",+ browser: "Browser command for --web and auth login",+ prompt: "Interactive prompts: enabled or disabled",+} as const;++export type ConfigKey = keyof typeof CONFIG_KEYS;+export type UserConfig = Partial<Record<ConfigKey, string>>;++export function assertConfigKey(key: string): asserts key is ConfigKey {+ if (!(key in CONFIG_KEYS)) {+ throw usageError(+ `unknown config key '${key}'`,+ `keys: ${Object.keys(CONFIG_KEYS).join(", ")}`,+ );+ }+}++export const readConfig = (env: Env) =>+ readJson<UserConfig>(path.join(configDir(env), "config.json"), {});++export async function writeConfig(env: Env, config: UserConfig) {+ await writeJson(path.join(configDir(env), "config.json"), config);+}++// ── Hosts and credentials ──++/** `framefields.dev` → `https://framefields.dev`; keeps explicit schemes and ports. */+export function hostUrl(host: string): string {+ const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(host)+ ? host+ : `https://${host}`;+ let url: URL;+ try {+ url = new URL(withScheme);+ } catch {+ throw usageError(+ `invalid host '${host}'`,+ "pass a URL such as https://framefields.dev",+ );+ }+ return `${url.protocol}//${url.host}`;+}++/** The key a host's credentials are stored under: its hostname (and port). */+export const hostKey = (host: string) => new URL(hostUrl(host)).host;++export interface HostCredentials {+ apiKey: string;+ organization?: string;+ organizationName?: string;+}++export type Hosts = Record<string, HostCredentials>;++const hostsFile = (env: Env) => path.join(configDir(env), "hosts.json");++export const readHosts = (env: Env) => readJson<Hosts>(hostsFile(env), {});++export async function writeHosts(env: Env, hosts: Hosts) {+ await writeJson(hostsFile(env), hosts, 0o600);+}++/** The API key for a host: `FF_TOKEN` first, then hosts.json. */+export async function tokenFor(+ env: Env,+ host: string,+): Promise<{ token: string; source: "env" | "file" } | undefined> {+ if (env.FF_TOKEN) return { token: env.FF_TOKEN, source: "env" };+ const entry = (await readHosts(env))[hostKey(host)];+ return entry?.apiKey ? { token: entry.apiKey, source: "file" } : undefined;+}diff --git a/packages/cli/src/context.ts b/packages/cli/src/context.tsnew file mode 100644index 00000000..37d43a48--- /dev/null+++ b/packages/cli/src/context.ts@@ -0,0 +1,333 @@+/**+ * Everything a command needs, built from the global flags: output, the+ * project, the project's engine, the cloud client and the linked repository.+ * Commands take a Context instead of touching process globals, so they run in+ * tests without a terminal.+ */+import fs from "node:fs";+import path from "node:path";+import { pathToFileURL } from "node:url";+import { loadProject, type Project, ProjectError } from "framefields/project";+import { CloudClient, type Repository } from "./cloud/client.js";+import {+ DEFAULT_HOST,+ type Env,+ hostKey,+ hostUrl,+ readConfig,+ tokenFor,+} from "./config.js";+import { CliError, usageError } from "./errors.js";+import * as git from "./git/index.js";+import type { Io } from "./output.js";+import { Output } from "./output.js";++export interface GlobalOptions {+ json?: boolean;+ yes?: boolean;+ directory?: string;+ host?: string;+ quiet?: boolean;+ verbose?: boolean;+ color?: boolean;+}++export interface Deps {+ io: Io;+ env: Env;+ cwd: string;+ fetch?: typeof fetch;+}++/** What `import("framefields")` from the project gives us; only what `ff` uses. */+export interface Engine {+ HeadlessMediaRenderer: new () => unknown;+ startPreview(+ source: unknown,+ options?: Record<string, unknown>,+ ): Promise<{ url: string; closed: Promise<string>; close(): Promise<void> }>;+ CompositorProgramSchema?: {+ safeParse(value: unknown): {+ success: boolean;+ error?: { issues: { path: PropertyKey[]; message: string }[] };+ };+ };+}++export class Context {+ readonly out: Output;+ readonly io: Io;+ readonly env: Env;+ /** Where the command runs: `-C <dir>` or the working directory. */+ readonly cwd: string;+ readonly yes: boolean;+ private readonly flagHost?: string;+ readonly fetchImpl?: typeof fetch;+ private projectPromise?: Promise<Project>;+ private clientPromise?: Promise<CloudClient>;++ constructor(options: GlobalOptions, deps: Deps) {+ this.io = deps.io;+ this.env = deps.env;+ this.cwd = path.resolve(deps.cwd, options.directory ?? ".");+ if (options.directory && !fs.existsSync(this.cwd)) {+ throw usageError(`-C ${options.directory}: no such directory`);+ }+ this.yes = !!options.yes;+ this.flagHost = options.host;+ this.fetchImpl = deps.fetch;+ this.out = new Output(deps.io, {+ json: !!options.json,+ quiet: !!options.quiet,+ verbose: !!options.verbose,+ color:+ options.color !== false &&+ deps.io.colorSupported &&+ deps.env.NO_COLOR === undefined,+ });+ }++ /** Prompts are allowed: a terminal, no --yes, and not disabled in config. */+ async canPrompt(): Promise<boolean> {+ if (!this.io.isTTY || this.yes || this.out.json) return false;+ return (await readConfig(this.env)).prompt !== "disabled";+ }++ // ── Project ──++ project(): Promise<Project> {+ this.projectPromise ??= loadProject(this.cwd).catch((err: unknown) => {+ throw fromProjectError(err);+ });+ return this.projectPromise;+ }++ /** Path relative to the project root, for printing. */+ relative(project: Project, file: string): string {+ return path.relative(project.root, file).split(path.sep).join("/") || ".";+ }++ /**+ * The `framefields` installed in the project (never a copy bundled with the+ * CLI), with a TypeScript loader registered so entries import.+ */+ async engine(project: Project): Promise<Engine> {+ const resolved = resolvePackage(project.root, "framefields");+ if (!resolved) {+ throw new CliError(`framefields is not installed in ${project.root}`, {+ code: "project",+ hint: `run: ${addCommand(project.root)} framefields`,+ });+ }+ await registerTypeScript();+ // Entries resolve assets and fonts against the project, like its own scripts.+ process.chdir(project.root);+ return (await import(pathToFileURL(resolved).href)) as Engine;+ }++ /** True when the project's engine reads framefields.json itself (`startPreview({ project })`). */+ engineHasProject(project: Project): boolean {+ return (+ resolvePackage(project.root, "framefields", "./project") !== undefined+ );+ }++ // ── Cloud ──++ /** --host, FF_HOST, the linked repo's host, `ff config set host`, the default. */+ async host(): Promise<string> {+ if (this.flagHost) return hostUrl(this.flagHost);+ if (this.env.FF_HOST) return hostUrl(this.env.FF_HOST);+ const linked = await git+ .configGet(this.cwd, "framefields.host")+ .catch(() => undefined);+ if (linked) return hostUrl(linked);+ const config = await readConfig(this.env);+ return hostUrl(config.host ?? DEFAULT_HOST);+ }++ client(): Promise<CloudClient> {+ this.clientPromise ??= (async () => {+ const host = await this.host();+ const token = await tokenFor(this.env, host);+ this.out.debug(+ `host ${host}${token ? ` (key from ${token.source === "env" ? "FF_TOKEN" : "hosts.json"})` : ""}`,+ );+ return new CloudClient(host, token?.token, this.fetchImpl);+ })();+ return this.clientPromise;+ }++ /** The git work tree for repo commands; errors outside one. */+ async gitRoot(): Promise<string> {+ const root = await git.topLevel(this.cwd);+ if (!root) {+ throw new CliError(`${this.cwd} is not a git repository`, {+ hint: "ff repo create (or ff clone <repo>)",+ });+ }+ return root;+ }++ /**+ * Finds a repository by id or name; without one, the repository this+ * directory is linked to (`git config framefields.repo`), falling back to+ * matching `origin` against the organization's repositories and linking it.+ */+ async repo(ref?: string): Promise<Repository> {+ const client = await this.client();+ if (ref) {+ if (/^repo_/.test(ref)) return client.getRepo(ref);+ const repos = await client.listRepos();+ const found = repos.find((r) => r.name === ref || r.id === ref);+ if (!found)+ throw new CliError(+ `no repository named '${ref}' in your organization`,+ { hint: "ff repo list" },+ );+ return found;+ }+ const root = await this.gitRoot();+ const linked = await git.configGet(root, "framefields.repo");+ if (linked) return client.getRepo(linked);+ const origin = await git.remoteUrl(root);+ if (origin) {+ const wanted = git.normalizeRemote(origin);+ const match = (await client.listRepos()).filter(+ (r) => git.normalizeRemote(r.remoteUrl) === wanted,+ );+ if (match.length === 1 && match[0]) {+ await this.link(root, match[0]);+ this.out.info(+ `linked ${this.relativeCwd(root)} to ${match[0].name} (${match[0].id}) by its origin remote`,+ );+ return match[0];+ }+ }+ throw new CliError(+ "this directory is not linked to a Framefields Cloud repository",+ {+ hint: "ff repo create, or: git config framefields.repo <repo id> (ff repo list)",+ },+ );+ }++ /** Writes the link into local git config (never the manifest: it is portable). */+ async link(root: string, repo: Repository): Promise<void> {+ await git.configSet(root, "framefields.repo", repo.id);+ await git.configSet(root, "framefields.host", hostKey(await this.host()));+ }++ relativeCwd(dir: string): string {+ return path.relative(this.cwd, dir) || ".";+ }+}++/** The nearest `node_modules/<name>` above `from`, as Node would find it. */+export function findPackageDir(from: string, name: string): string | undefined {+ for (let dir = path.resolve(from); ; dir = path.dirname(dir)) {+ const candidate = path.join(dir, "node_modules", name);+ if (fs.existsSync(path.join(candidate, "package.json")))+ return fs.realpathSync(candidate);+ if (path.dirname(dir) === dir) return undefined;+ }+}++/**+ * The file an `import` of `name` (or `name/subpath`) from `from` loads: the+ * package's `exports` (import, then default), else `module`/`main`.+ */+export function resolvePackage(+ from: string,+ name: string,+ subpath = ".",+): string | undefined {+ const dir = findPackageDir(from, name);+ if (!dir) return undefined;+ const pkg = JSON.parse(+ fs.readFileSync(path.join(dir, "package.json"), "utf8"),+ ) as {+ exports?: unknown;+ module?: string;+ main?: string;+ };+ const pick = (target: unknown): string | undefined => {+ if (typeof target === "string") return target;+ if (target && typeof target === "object") {+ for (const condition of ["import", "node", "default"]) {+ const found = pick((target as Record<string, unknown>)[condition]);+ if (found) return found;+ }+ }+ return undefined;+ };+ let target: string | undefined;+ if (pkg.exports !== undefined) {+ const exportsMap =+ typeof pkg.exports === "string" ||+ Object.keys(pkg.exports as object).every((k) => !k.startsWith("."))+ ? { ".": pkg.exports }+ : (pkg.exports as Record<string, unknown>);+ target = pick(exportsMap[subpath]);+ } else if (subpath === ".") target = pkg.module ?? pkg.main ?? "index.js";+ else target = subpath;+ return target ? path.join(dir, target) : undefined;+}++let registered: Promise<void> | undefined;+/**+ * tsx's loaders, so `.ts` entries (and their `./x.js` imports) load as under+ * `tsx src/render.ts`: both the ESM and the CommonJS hooks, as the tsx CLI+ * installs them (CommonJS dependencies requiring ESM need the latter).+ */+function registerTypeScript(): Promise<void> {+ registered ??= Promise.all([+ import("tsx/esm/api"),+ import("tsx/cjs/api"),+ ]).then(([esm, cjs]) => {+ // Node deprecates module.register(), which tsx uses; that's tsx's to change, not the user's.+ const quiet = process.noDeprecation;+ process.noDeprecation = true;+ try {+ cjs.register();+ esm.register();+ } finally {+ process.noDeprecation = quiet;+ }+ });+ return registered;+}++/** `pnpm add`, `yarn add`, `bun add` or `npm install`, by the project's lockfile. */+export function addCommand(root: string): string {+ for (let dir = root; ; dir = path.dirname(dir)) {+ if (fs.existsSync(path.join(dir, "pnpm-lock.yaml"))) return "pnpm add";+ if (fs.existsSync(path.join(dir, "yarn.lock"))) return "yarn add";+ if (+ fs.existsSync(path.join(dir, "bun.lock")) ||+ fs.existsSync(path.join(dir, "bun.lockb"))+ )+ return "bun add";+ if (fs.existsSync(path.join(dir, "package-lock.json")))+ return "npm install";+ if (path.dirname(dir) === dir) return "npm install";+ }+}++/** Maps a framefields/project error to a CLI error: project problems exit 4, bad references 2. */+export function fromProjectError(err: unknown): unknown {+ if (!(err instanceof ProjectError)) return err;+ const code =+ err.kind === "unknown-composition"+ ? "usage"+ : err.kind === "build"+ ? "failed"+ : "project";+ return new CliError(err.message, {+ code,+ hint:+ err.hint ??+ (err.kind === "invalid" && err.path ? `fix ${err.path}` : undefined),+ cause: err,+ });+}diff --git a/packages/cli/src/errors.ts b/packages/cli/src/errors.tsnew file mode 100644index 00000000..df0c482a--- /dev/null+++ b/packages/cli/src/errors.ts@@ -0,0 +1,32 @@+/** Exit codes (SPEC §7). */+export const EXIT = {+ ok: 0,+ failed: 1,+ usage: 2,+ auth: 3,+ project: 4,+ interrupted: 130,+} as const;++export type ErrorCode = keyof typeof EXIT;++/** An error the CLI reports as `error: <message>` plus an optional hint. */+export class CliError extends Error {+ override name = "CliError";+ readonly code: ErrorCode;+ readonly hint?: string;+ constructor(+ message: string,+ options: { code?: ErrorCode; hint?: string; cause?: unknown } = {},+ ) {+ super(message, { cause: options.cause });+ this.code = options.code ?? "failed";+ this.hint = options.hint;+ }+ get exitCode(): number {+ return EXIT[this.code];+ }+}++export const usageError = (message: string, hint?: string) =>+ new CliError(message, { code: "usage", hint });diff --git a/packages/cli/src/git/index.ts b/packages/cli/src/git/index.tsnew file mode 100644index 00000000..7213e733--- /dev/null+++ b/packages/cli/src/git/index.ts@@ -0,0 +1,140 @@+/**+ * Thin wrappers over the user's git binary. Short-lived cloud tokens reach git+ * through `GIT_CONFIG_*` environment variables for one invocation, so they are+ * never written to disk or shown in the process list.+ */+import { spawn } from "node:child_process";+import { CliError } from "../errors.js";++export interface GitOptions {+ cwd: string;+ /** A bearer token for the cloud remote, for this invocation only. */+ token?: string;+ /** Streams git's stderr (progress) here as it runs. */+ onStderr?: (text: string) => void;+ input?: string;+}++export interface GitResult {+ code: number;+ stdout: string;+ stderr: string;+}++export function git(args: string[], options: GitOptions): Promise<GitResult> {+ const env: NodeJS.ProcessEnv = {+ ...process.env,+ GIT_TERMINAL_PROMPT: "0",+ };+ if (options.token) {+ const n = Number(env.GIT_CONFIG_COUNT ?? 0);+ env.GIT_CONFIG_COUNT = String(n + 1);+ env[`GIT_CONFIG_KEY_${n}`] = "http.extraHeader";+ env[`GIT_CONFIG_VALUE_${n}`] = `Authorization: Bearer ${options.token}`;+ }+ return new Promise((resolve, reject) => {+ const child = spawn("git", args, {+ cwd: options.cwd,+ env,+ stdio: ["pipe", "pipe", "pipe"],+ });+ let stdout = "";+ let stderr = "";+ child.stdout.setEncoding("utf8").on("data", (d: string) => {+ stdout += d;+ });+ child.stderr.setEncoding("utf8").on("data", (d: string) => {+ stderr += d;+ options.onStderr?.(d);+ });+ child.on("error", (err) => {+ reject(+ (err as NodeJS.ErrnoException).code === "ENOENT"+ ? new CliError("git is not installed or not on PATH", {+ hint: "install git: https://git-scm.com/downloads",+ })+ : err,+ );+ });+ child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));+ child.stdin.end(options.input ?? "");+ });+}++/** Runs git and returns trimmed stdout; a non-zero exit becomes a CliError. */+export async function gitOk(+ args: string[],+ options: GitOptions,+): Promise<string> {+ const result = await git(args, options);+ if (result.code !== 0) {+ const detail = (result.stderr || result.stdout)+ .trim()+ .split("\n")+ .slice(-3)+ .join("\n ");+ throw new CliError(+ `git ${args[0]} failed${detail ? `:\n ${detail}` : ""}`,+ );+ }+ return result.stdout.trim();+}++/** Trimmed stdout, or undefined when git exits non-zero (an unset config key, say). */+export async function gitMaybe(+ args: string[],+ cwd: string,+): Promise<string | undefined> {+ const result = await git(args, { cwd });+ return result.code === 0 ? result.stdout.trim() || undefined : undefined;+}++export const isRepo = async (cwd: string) =>+ (await gitMaybe(["rev-parse", "--is-inside-work-tree"], cwd)) === "true";++export const topLevel = (cwd: string) =>+ gitMaybe(["rev-parse", "--show-toplevel"], cwd);++export const currentBranch = (cwd: string) =>+ gitMaybe(["symbolic-ref", "--quiet", "--short", "HEAD"], cwd);++export const remoteUrl = (cwd: string, remote = "origin") =>+ gitMaybe(["remote", "get-url", remote], cwd);++export const configGet = (cwd: string, key: string) =>+ gitMaybe(["config", "--get", key], cwd);++export async function configSet(+ cwd: string,+ key: string,+ value: string,+ scope: "local" | "global" = "local",+) {+ await gitOk(["config", `--${scope}`, key, value], { cwd });+}++/** Paths with uncommitted changes to tracked files (untracked files ignored). */+export async function dirtyFiles(cwd: string): Promise<string[]> {+ const out = await gitOk(["status", "--porcelain", "--untracked-files=no"], {+ cwd,+ });+ return out ? out.split("\n").map((l) => l.slice(3)) : [];+}++/** Normalises a remote URL for comparison: no credentials, no trailing `.git` or slash. */+export function normalizeRemote(url: string): string {+ try {+ const u = new URL(url);+ u.username = "";+ u.password = "";+ return `${u.host}${u.pathname}`+ .replace(/\.git$/, "")+ .replace(/\/+$/, "")+ .toLowerCase();+ } catch {+ return url+ .replace(/\.git$/, "")+ .replace(/\/+$/, "")+ .toLowerCase();+ }+}diff --git a/packages/cli/src/glob.ts b/packages/cli/src/glob.tsnew file mode 100644index 00000000..540c805b--- /dev/null+++ b/packages/cli/src/glob.ts@@ -0,0 +1,41 @@+/** Minimal globs for `assets.exclude`: `**`, `*`, `?` and `{a,b}`, matched against posix paths. */+const cache = new Map<string, RegExp>();++export function globToRegExp(glob: string): RegExp {+ const cached = cache.get(glob);+ if (cached) return cached;+ let re = "";+ for (let i = 0; i < glob.length; i++) {+ const c = glob[i] as string;+ if (c === "*") {+ if (glob[i + 1] === "*") {+ // `**/` matches zero or more directories; a trailing `**` anything.+ if (glob[i + 2] === "/") {+ re += "(?:.*/)?";+ i += 2;+ } else {+ re += ".*";+ i += 1;+ }+ } else re += "[^/]*";+ } else if (c === "?") re += "[^/]";+ else if (c === "{") {+ const end = glob.indexOf("}", i);+ if (end === -1) re += "\\{";+ else {+ re += `(?:${glob+ .slice(i + 1, end)+ .split(",")+ .map((s) => s.replace(/[.+^${}()|[\]\\]/g, "\\$&"))+ .join("|")})`;+ i = end;+ }+ } else re += c.replace(/[.+^${}()|[\]\\]/g, "\\$&");+ }+ const compiled = new RegExp(`^${re}$`);+ cache.set(glob, compiled);+ return compiled;+}++export const matchesAny = (globs: string[], file: string) =>+ globs.some((g) => globToRegExp(g).test(file));diff --git a/packages/cli/src/output.ts b/packages/cli/src/output.tsnew file mode 100644index 00000000..80791db1--- /dev/null+++ b/packages/cli/src/output.ts@@ -0,0 +1,164 @@+/**+ * Output contract (SPEC §7): stdout carries data — one JSON value with+ * `--json`, tables, `key: value` views or written paths otherwise — and+ * progress and logs go to stderr.+ */+import { spawn } from "node:child_process";+import * as clack from "@clack/prompts";+import { CliError } from "./errors.js";++/** The terminal, injected so commands run without one in tests. */+export interface Io {+ stdout(text: string): void;+ stderr(text: string): void;+ /** Reads all of stdin. */+ readStdin(): Promise<string>;+ /** True when stdin and stdout are terminals, so prompting is allowed. */+ isTTY: boolean;+ /** Whether stderr supports colors. */+ colorSupported: boolean;+ /** Asks a question on the terminal. Only called when `isTTY`. */+ prompt(question: string, options?: { secret?: boolean }): Promise<string>;+ /** Opens a URL in the user's browser. */+ openUrl(url: string): void;+}++export function processIo(): Io {+ // stdout is the CLI's data only. The engine's logger, the composition's+ // console.log and anything else writing to stdout go to stderr instead.+ const stdout = process.stdout.write.bind(process.stdout);+ process.stdout.write = process.stderr.write.bind(+ process.stderr,+ ) as typeof process.stdout.write;+ return {+ stdout: (t) => void stdout(t),+ stderr: (t) => void process.stderr.write(t),+ readStdin: async () => {+ const chunks: Buffer[] = [];+ for await (const chunk of process.stdin) chunks.push(chunk as Buffer);+ return Buffer.concat(chunks).toString("utf8");+ },+ isTTY: !!process.stdin.isTTY && !!process.stdout.isTTY,+ colorSupported:+ !!process.stderr.isTTY && process.env.NO_COLOR === undefined,+ prompt: async (question, options = {}) => {+ // Prompts draw on stderr: stdout is data.+ const common = { message: question, output: process.stderr };+ const answer = options.secret+ ? await clack.password(common)+ : await clack.text(common);+ if (clack.isCancel(answer)) {+ throw new CliError("cancelled", { code: "interrupted" });+ }+ return answer.trim();+ },+ openUrl: (url) => {+ const [cmd, args] =+ process.platform === "darwin"+ ? ["open", [url]]+ : process.platform === "win32"+ ? ["cmd", ["/c", "start", "", url]]+ : ["xdg-open", [url]];+ try {+ spawn(cmd, args, { stdio: "ignore", detached: true })+ .on("error", () => {})+ .unref();+ } catch {}+ },+ };+}++export interface OutputOptions {+ json: boolean;+ quiet: boolean;+ verbose: boolean;+ color: boolean;+}++const ANSI = {+ bold: [1, 22],+ dim: [2, 22],+ red: [31, 39],+ green: [32, 39],+ yellow: [33, 39],+ cyan: [36, 39],+} as const;++export class Output {+ constructor(+ readonly io: Io,+ readonly options: OutputOptions,+ ) {}++ get json(): boolean {+ return this.options.json;+ }++ style(name: keyof typeof ANSI, text: string): string {+ if (!this.options.color) return text;+ const [open, close] = ANSI[name];+ return `\u001b[${open}m${text}\u001b[${close}m`;+ }++ /** Prints a command's result: JSON with `--json`, else `human()`. */+ result(value: unknown, human: () => void): void {+ if (this.options.json)+ this.io.stdout(`${JSON.stringify(value, null, 2)}\n`);+ else human();+ }++ /** A line of human output on stdout (never with `--json`). */+ line(text = ""): void {+ if (!this.options.json) this.io.stdout(`${text}\n`);+ }++ /** Progress or a note on stderr, unless `--quiet`. */+ info(text: string): void {+ if (!this.options.quiet) this.io.stderr(`${text}\n`);+ }++ warn(text: string): void {+ this.io.stderr(`${this.style("yellow", "warning:")} ${text}\n`);+ }++ debug(text: string): void {+ if (this.options.verbose) this.io.stderr(`${this.style("dim", text)}\n`);+ }++ /** A table for lists. */+ table(+ rows: Record<string, unknown>[],+ columns: { key: string; label: string }[],+ ): void {+ if (rows.length === 0) return;+ const cells = rows.map((r) =>+ columns.map((c) =>+ r[c.key] === null || r[c.key] === undefined ? "" : String(r[c.key]),+ ),+ );+ const widths = columns.map((c, i) =>+ Math.max(c.label.length, ...cells.map((row) => (row[i] ?? "").length)),+ );+ const fmt = (row: string[]) =>+ row+ .map((cell, i) =>+ i === row.length - 1 ? cell : cell.padEnd(widths[i] ?? 0),+ )+ .join(" ")+ .trimEnd();+ this.line(+ this.style("bold", fmt(columns.map((c) => c.label.toUpperCase()))),+ );+ for (const row of cells) this.line(fmt(row));+ }++ /** `key: value` lines for views. */+ view(pairs: [string, unknown][]): void {+ for (const [key, value] of pairs) {+ if (value === undefined) continue;+ this.line(+ `${this.style("dim", `${key}:`)} ${value === null ? "-" : String(value)}`,+ );+ }+ }+}diff --git a/packages/cli/src/timecode.ts b/packages/cli/src/timecode.tsnew file mode 100644index 00000000..98a33822--- /dev/null+++ b/packages/cli/src/timecode.ts@@ -0,0 +1,71 @@+import { usageError } from "./errors.js";++/**+ * A frame reference: a frame number (`60`), seconds (`2.5s`), milliseconds+ * (`1500ms`), a clock time (`02:15`, `00:02:15`, `00:02:15.5`) or SMPTE+ * `hh:mm:ss:ff`. Returns the frame index at `fps`.+ */+export function parseFrame(value: string, fps: number): number {+ const v = value.trim();+ let frame: number | undefined;+ if (/^\d+$/.test(v)) frame = Number(v);+ else if (/^\d+(\.\d+)?s$/.test(v)) frame = Number(v.slice(0, -1)) * fps;+ else if (/^\d+(\.\d+)?ms$/.test(v))+ frame = (Number(v.slice(0, -2)) / 1000) * fps;+ else if (/^\d+(:\d{1,2}){1,2}(\.\d+)?$/.test(v)) {+ const parts = v.split(":").map(Number);+ const seconds = parts.reduce((acc, p) => acc * 60 + p, 0);+ frame = seconds * fps;+ } else if (/^\d+:\d{1,2}:\d{1,2}:\d{1,3}$/.test(v)) {+ const [h = 0, m = 0, s = 0, f = 0] = v.split(":").map(Number);+ if (f >= Math.ceil(fps))+ throw usageError(`'${value}': frame ${f} is past ${fps} fps`);+ frame = (h * 3600 + m * 60 + s) * fps + f;+ }+ if (frame === undefined || !Number.isFinite(frame)) {+ throw usageError(+ `'${value}' is not a frame or timecode`,+ "use a frame number (60), seconds (2.5s), milliseconds (1500ms) or a time (00:02:15)",+ );+ }+ return Math.round(frame);+}++export const looksLikeFrame = (value: string) =>+ /^(\d+|\d+(\.\d+)?m?s|\d+(:\d{1,2}){1,3}(\.\d+)?)$/.test(value.trim());++/** `from..to` or `from-to` (either side optional). */+export function parseRange(+ value: string,+ fps: number,+): { from?: number; to?: number } {+ const sep = value.includes("..") ? ".." : "-";+ const i = value.indexOf(sep);+ if (i === -1)+ throw usageError(+ `'${value}' is not a range`,+ "use --range <from>..<to>, e.g. 0..120 or 2s..5s",+ );+ const a = value.slice(0, i).trim();+ const b = value.slice(i + sep.length).trim();+ return {+ from: a ? parseFrame(a, fps) : undefined,+ to: b ? parseFrame(b, fps) : undefined,+ };+}++/** `count` frames spread evenly over [from, to], inclusive and distinct. */+export function spreadFrames(+ from: number,+ to: number,+ count: number,+): number[] {+ if (count <= 1 || to <= from) return [from];+ const frames = Array.from({ length: count }, (_, i) =>+ Math.round(from + (i * (to - from)) / (count - 1)),+ );+ return [...new Set(frames)];+}++export const frameFileName = (frame: number) =>+ `f${String(frame).padStart(4, "0")}.png`;diff --git a/packages/cli/src/version.ts b/packages/cli/src/version.tsnew file mode 100644index 00000000..3f3d325f--- /dev/null+++ b/packages/cli/src/version.ts@@ -0,0 +1,6 @@+import { createRequire } from "node:module";++/** The CLI's version, which is also the engine version `ff init` installs. */+export const VERSION: string = (+ createRequire(import.meta.url)("../package.json") as { version: string }+).version;diff --git a/packages/cli/test/cloud.test.ts b/packages/cli/test/cloud.test.tsnew file mode 100644index 00000000..44e75e98--- /dev/null+++ b/packages/cli/test/cloud.test.ts@@ -0,0 +1,582 @@+/**+ * The cloud half end to end against a fake Framefields Cloud whose+ * repositories are real bare git repos: create → push with assets → clone+ * elsewhere → assets restored and verified, then issues, pull requests and+ * renders.+ */+import { execFileSync } from "node:child_process";+import fs from "node:fs";+import path from "node:path";+import { afterAll, beforeAll, describe, expect, it } from "vitest";+import { type FakeCloud, startFakeCloud } from "./fake-cloud.js";+import {+ cleanupTmp,+ ff,+ gitEnv,+ type RunOptions,+ tmpdir,+ writeFiles,+} from "./helpers.js";++let cloud: FakeCloud;+let home: string;+let work: string;+let env: Record<string, string>;++const git = (cwd: string, ...args: string[]) =>+ execFileSync("git", args, { cwd, encoding: "utf8" }).trim();++beforeAll(async () => {+ home = tmpdir("ff-home-");+ gitEnv(home);+ cloud = await startFakeCloud(tmpdir("ff-cloud-"), { partSize: 8 });+ env = { FF_CONFIG_DIR: path.join(home, "config"), FF_HOST: cloud.url };+ work = tmpdir("ff-work-");+});+afterAll(async () => {+ await cloud.close();+ cleanupTmp();+});++const run = (args: string[], options: Partial<RunOptions> = {}) =>+ ff(args, { cwd: work, ...options, env: { ...env, ...options.env } });++describe("auth", () => {+ it("is not logged in at first (exit 3)", async () => {+ const r = await run(["repo", "list"]);+ expect(r.code).toBe(3);+ expect(r.stderr).toContain("hint: ff auth login (or set FF_TOKEN)");+ expect((await run(["auth", "status"])).code).toBe(3);+ });++ it("refuses to prompt without a terminal", async () => {+ const r = await run(["auth", "login"]);+ expect(r.code).toBe(2);+ expect(r.stderr).toContain("echo $FF_KEY | ff auth login --with-token");+ });++ it("rejects a bad key with exit 3", async () => {+ const r = await run(["auth", "login", "--with-token"], {+ stdin: "ff_wrong\n",+ });+ expect(r.code).toBe(3);+ });++ it("logs in with a key from stdin, stored 0600", async () => {+ const r = await run(["auth", "login", "--with-token", "--json"], {+ stdin: `${cloud.apiKey}\n`,+ });+ expect(r.code).toBe(0);+ expect(r.json()).toMatchObject({ organization: { id: "org_test" } });+ const file = path.join(env.FF_CONFIG_DIR as string, "hosts.json");+ expect(fs.statSync(file).mode & 0o777).toBe(0o600);+ const hosts = JSON.parse(fs.readFileSync(file, "utf8"));+ expect(Object.values(hosts)).toEqual([+ {+ apiKey: cloud.apiKey,+ organization: "org_test",+ organizationName: "Test Org",+ },+ ]);+ const status = await run(["auth", "status"]);+ expect(status.code).toBe(0);+ expect(status.stdout).toContain("Test Org (org_test)");+ expect(status.stdout).not.toContain(cloud.apiKey);+ });++ it("FF_TOKEN overrides the stored key", async () => {+ const r = await run(["auth", "status", "--json"], {+ env: { FF_TOKEN: "ff_other" },+ });+ expect(r.code).toBe(3);+ });++ it("maps a missing scope to exit 3 with the scope's name", async () => {+ cloud.scopes = ["repo:read"];+ try {+ const r = await run(["repo", "create", "nope"]);+ expect(r.code).toBe(3);+ expect(r.stderr).toContain("Missing required scope: repo:write");+ expect(r.stderr).toContain("'repo:write' scope");+ } finally {+ cloud.scopes = [+ "repo:read",+ "repo:write",+ "render:create",+ "assets:sync",+ ];+ }+ });+});++describe("repositories and sync", () => {+ let project: string;+ const plate = Buffer.from("0123456789abcdefghijklmnopqrstuvwxyz"); // 36 bytes → 5 parts of 8++ it("creates a repository, links the directory and pushes with assets", async () => {+ expect((await run(["init", "film", "-q"])).code).toBe(0);+ project = path.join(work, "film");+ writeFiles(project, {+ "assets/plate.bin": plate,+ "assets/fonts/Inter.ttf": "font bytes",+ "assets/.DS_Store": "junk",+ "assets/empty.txt": "",+ });+ git(project, "add", "-A");+ git(project, "commit", "-qm", "first");++ const created = await run(["repo", "create", "--push", "--json"], {+ cwd: project,+ });+ expect(created.code, created.stderr).toBe(0);+ const repo = created.json<{+ id: string;+ name: string;+ pushed: { lockfileCommitted: boolean };+ }>();+ expect(repo.name).toBe("film");+ expect(repo.pushed.lockfileCommitted).toBe(true);+ expect(git(project, "config", "framefields.repo")).toBe(repo.id);+ expect(git(project, "log", "-1", "--format=%s")).toBe(+ "assets: sync external assets",+ );++ const lock = JSON.parse(+ fs.readFileSync(path.join(project, "framefields.assets.json"), "utf8"),+ );+ expect(Object.keys(lock.assets).sort()).toEqual([+ "assets/fonts/Inter.ttf",+ "assets/plate.bin",+ ]);+ expect(cloud.blobs.get(lock.assets["assets/plate.bin"].sha256)).toEqual(+ plate,+ );+ expect(cloud.requests.filter((r) => r.includes("/parts/")).length).toBe(+ 5 + 2,+ );+ const refs = cloud.assetRefs.get(`${repo.id} refs/heads/main`);+ expect(refs?.commitSha).toBe(git(project, "rev-parse", "HEAD"));+ expect(git(project, "ls-remote", "origin", "main").split("\t")[0]).toBe(+ git(project, "rev-parse", "HEAD"),+ );+ });++ it("push is idempotent", async () => {+ const before = cloud.requests.length;+ const r = await run(["push", "--json"], { cwd: project });+ expect(r.code, r.stderr).toBe(0);+ expect(r.json()).toMatchObject({+ lockfileCommitted: false,+ assets: { uploaded: [], lockfileChanged: false },+ });+ expect(+ cloud.requests.slice(before).filter((x) => x.includes("/parts/")),+ ).toEqual([]);+ });++ it("asset sync resumes an interrupted upload", async () => {+ const big = Buffer.from("x".repeat(40));+ writeFiles(project, { "assets/big.bin": big });+ // Upload two parts by hand, as if the last run died midway.+ const { createHash } = await import("node:crypto");+ const sha256 = createHash("sha256").update(big).digest("hex");+ const repoId = git(project, "config", "framefields.repo");+ const diff = (await (+ await fetch(`${cloud.url}/v1/repos/${repoId}/assets/diff`, {+ method: "POST",+ headers: {+ Authorization: `Bearer ${cloud.apiKey}`,+ "Content-Type": "application/json",+ },+ body: JSON.stringify({+ assets: [{ sha256, size: 40, mimeType: "application/octet-stream" }],+ }),+ })+ ).json()) as { missing: { partUrl: string }[] };+ for (const n of [1, 2]) {+ await fetch(`${cloud.url}${diff.missing[0]?.partUrl}${n}`, {+ method: "PUT",+ headers: { Authorization: `Bearer ${cloud.apiKey}` },+ body: big.subarray((n - 1) * 8, n * 8),+ });+ }+ const before = cloud.requests.length;+ const dry = await run(["asset", "sync", "--dry-run", "--json"], {+ cwd: project,+ });+ expect(dry.json()).toMatchObject({+ dryRun: true,+ uploaded: ["assets/big.bin"],+ });+ const r = await run(["asset", "sync", "--json"], { cwd: project });+ expect(r.code, r.stderr).toBe(0);+ expect(r.json()).toMatchObject({+ uploaded: ["assets/big.bin"],+ lockfileChanged: true,+ });+ const parts = cloud.requests+ .slice(before)+ .filter((x) => x.includes("/parts/"));+ expect(parts.map((x) => x.split("/").pop())).toEqual(["3", "4", "5"]);+ expect(cloud.blobs.get(sha256)).toEqual(big);+ });++ it("asset status reports local vs lockfile vs cloud", async () => {+ writeFiles(project, {+ "assets/fonts/Inter.ttf": "changed font",+ "assets/new.bin": "new",+ });+ fs.rmSync(path.join(project, "assets/big.bin"));+ const r = await run(["asset", "status", "--json"], { cwd: project });+ expect(r.json()).toMatchObject({+ new: ["assets/new.bin"],+ modified: ["assets/fonts/Inter.ttf"],+ missing: ["assets/big.bin"],+ notUploaded: [],+ });+ git(project, "checkout", "--", ".");+ git(project, "clean", "-fdq", "--", "assets");+ writeFiles(project, { "assets/fonts/Inter.ttf": "font bytes" });+ });++ it("clones elsewhere and restores the assets, verified", async () => {+ const elsewhere = tmpdir("ff-clone-");+ const r = await run(["clone", "film", "copy", "--json"], {+ cwd: elsewhere,+ });+ expect(r.code, r.stderr).toBe(0);+ const dir = path.join(elsewhere, "copy");+ expect(fs.readFileSync(path.join(dir, "assets/plate.bin"))).toEqual(plate);+ expect(+ fs.readFileSync(path.join(dir, "assets/fonts/Inter.ttf"), "utf8"),+ ).toBe("font bytes");+ expect(git(dir, "config", "framefields.repo")).toBe(+ git(project, "config", "framefields.repo"),+ );+ expect(+ (await run(["asset", "status", "--json"], { cwd: dir })).json(),+ ).toMatchObject({ new: [], modified: [], missing: [] });++ // A corrupted blob is refused, and nothing is written.+ const lock = JSON.parse(+ fs.readFileSync(path.join(dir, "framefields.assets.json"), "utf8"),+ );+ const sha = lock.assets["assets/plate.bin"].sha256;+ const good = cloud.blobs.get(sha) as Buffer;+ cloud.blobs.set(sha, Buffer.from("tampered"));+ fs.rmSync(path.join(dir, "assets/plate.bin"));+ const pulled = await run(["asset", "pull"], { cwd: dir });+ expect(pulled.code).toBe(1);+ expect(pulled.stderr).toContain("checksum mismatch");+ expect(fs.existsSync(path.join(dir, "assets/plate.bin"))).toBe(false);+ cloud.blobs.set(sha, good);+ expect((await run(["asset", "pull"], { cwd: dir })).code).toBe(0);+ expect(fs.readFileSync(path.join(dir, "assets/plate.bin"))).toEqual(plate);+ });++ it("repo list, view and fork", async () => {+ const list = await run(["repo", "list"], { cwd: project });+ expect(list.stdout).toMatch(/^NAME {2}ID/);+ expect(list.stdout).toContain("film");+ const view = await run(["repo", "view", "--json"], { cwd: project });+ expect(view.json()).toMatchObject({+ name: "film",+ compositions: { defaultId: "film" },+ });+ const fork = await run(+ ["repo", "fork", "film", "--name", "film-2", "--json"],+ { cwd: project },+ );+ expect(fork.json()).toMatchObject({ name: "film-2" });+ expect(+ (await run(["repo", "delete", "film-2"], { cwd: project })).code,+ ).toBe(2);+ expect(+ (await run(["repo", "delete", "film-2", "--yes"], { cwd: project })).code,+ ).toBe(0);+ });++ it("links by origin when git config has no repo", async () => {+ const elsewhere = tmpdir("ff-relink-");+ const remote = [...cloud.repos.values()].find((r) => r.name === "film")+ ?.remoteUrl as string;+ git(elsewhere, "clone", "-q", remote, "plain");+ const dir = path.join(elsewhere, "plain");+ const r = await run(["repo", "view", "--json"], { cwd: dir });+ expect(r.code, r.stderr).toBe(0);+ expect(r.stderr).toContain("by its origin remote");+ expect(git(dir, "config", "framefields.repo")).toMatch(/^repo_/);+ });++ describe("issues and pull requests", () => {+ it("issue create, list, view, comment, edit, close", async () => {+ const created = await run(+ [+ "issue",+ "create",+ "--title",+ "Grain too strong",+ "--body",+ "In the intro",+ "--label",+ "look",+ ],+ { cwd: project },+ );+ expect(created.code, created.stderr).toBe(0);+ expect(created.stdout).toMatch(/\/issues\/1\n$/);+ const list = await run(["issue", "list"], { cwd: project });+ expect(list.stdout).toContain("#1 Grain too strong look");+ expect(+ (+ await run(["issue", "comment", "1", "--body-file", "-"], {+ cwd: project,+ stdin: "Agreed",+ })+ ).code,+ ).toBe(0);+ expect(+ (+ await run(+ [+ "issue",+ "edit",+ "#1",+ "--add-label",+ "p1",+ "--remove-label",+ "look",+ ],+ { cwd: project },+ )+ ).code,+ ).toBe(0);+ expect(+ (+ await run(["issue", "close", "1", "--comment", "Fixed"], {+ cwd: project,+ })+ ).code,+ ).toBe(0);+ const view = await run(["issue", "view", "1", "--comments", "--json"], {+ cwd: project,+ });+ expect(view.json()).toMatchObject({+ state: "closed",+ labels: ["p1"],+ commentCount: 2,+ });+ expect(+ (await run(["issue", "view", "1", "--comments"], { cwd: project }))+ .stdout,+ ).toContain("Agreed");+ expect(+ (await run(["issue", "list", "--json"], { cwd: project })).json(),+ ).toEqual([]);+ });++ it("pr create pushes the branch, pr merge merges with git and records it", async () => {+ git(project, "switch", "-qc", "softer-grain");+ writeFiles(project, {+ "src/film.ts": `${fs.readFileSync(path.join(project, "src/film.ts"), "utf8")}\n// softer\n`,+ "assets/grain.bin": "grain!",+ });+ git(project, "commit", "-qam", "softer grain");+ const created = await run(+ [+ "pr",+ "create",+ "--title",+ "Softer grain",+ "--body",+ "",+ "--draft",+ "--json",+ ],+ { cwd: project },+ );+ expect(created.code, created.stderr).toBe(0);+ const pr = created.json<{+ number: number;+ headRef: string;+ baseRef: string;+ }>();+ expect(pr).toMatchObject({+ number: 2,+ headRef: "softer-grain",+ baseRef: "main",+ });+ expect(git(project, "ls-remote", "origin", "softer-grain")).not.toBe("");++ const draft = await run(["pr", "merge", "2"], { cwd: project });+ expect(draft.code).toBe(1);+ expect(draft.stderr).toContain("hint: ff pr ready 2");+ expect((await run(["pr", "ready", "2"], { cwd: project })).code).toBe(0);++ const merged = await run(+ ["pr", "merge", "2", "--delete-branch", "--json"],+ { cwd: project },+ );+ expect(merged.code, merged.stderr).toBe(0);+ expect(git(project, "rev-parse", "--abbrev-ref", "HEAD")).toBe("main");+ expect(git(project, "log", "-1", "--format=%s", "origin/main")).toBe(+ "Merge pull request #2 from softer-grain",+ );+ expect(git(project, "ls-remote", "origin", "softer-grain")).toBe("");+ expect(cloud.issues.find((i) => i.number === 2)?.state).toBe("merged");+ const lock = JSON.parse(+ git(project, "show", "origin/main:framefields.assets.json"),+ );+ expect(Object.keys(lock.assets)).toContain("assets/grain.bin");+ expect(+ (+ await run(["pr", "list", "--state", "closed", "--json"], {+ cwd: project,+ })+ ).json(),+ ).toHaveLength(1);+ });++ it("pr checkout fetches the head branch", async () => {+ git(project, "switch", "-qc", "titles");+ writeFiles(project, { "notes.md": "titles" });+ git(project, "add", "notes.md");+ git(project, "commit", "-qm", "titles");+ expect(+ (+ await run(["pr", "create", "-t", "Titles", "-b", "x"], {+ cwd: project,+ })+ ).code,+ ).toBe(0);+ git(project, "switch", "-q", "main");+ git(project, "branch", "-qD", "titles");+ const r = await run(["pr", "checkout", "3"], { cwd: project });+ expect(r.code, r.stderr).toBe(0);+ expect(git(project, "rev-parse", "--abbrev-ref", "HEAD")).toBe("titles");+ git(project, "switch", "-q", "main");+ });+ });++ describe("renders", () => {+ it("refuses an unpushed HEAD with the ff push hint", async () => {+ writeFiles(project, { "local.md": "x" });+ git(project, "add", "local.md");+ git(project, "commit", "-qm", "local only");+ const r = await run(["render"], { cwd: project });+ expect(r.code).toBe(1);+ expect(r.stderr).toMatch(+ /HEAD \([0-9a-f]{7}\) is not pushed to origin\n {2}hint: ff push\n/,+ );+ expect((await run(["push"], { cwd: project })).code).toBe(0);+ });++ it("dispatches by composition id and prints the job", async () => {+ const r = await run(["render", "film", "--quality", "high", "--json"], {+ cwd: project,+ });+ expect(r.code, r.stderr).toBe(0);+ const job = r.json<{+ jobId: string;+ composition: string;+ commitSha: string;+ }>();+ expect(job).toMatchObject({+ composition: "film",+ commitSha: git(project, "rev-parse", "HEAD"),+ });+ expect(cloud.renders.get(job.jobId)?.renderParams).toEqual({+ quality: "high",+ });+ expect((await run(["render", "step-9"], { cwd: project })).code).toBe(2);+ });++ it("sends file#export as an explicit entry/export", async () => {+ const r = await run(["render", "src/film.ts#buildFilm", "--json"], {+ cwd: project,+ });+ const job = cloud.renders.get(r.json<{ jobId: string }>().jobId);+ expect(job).toMatchObject({+ entryPath: "src/film.ts",+ exportName: "buildFilm",+ });+ });++ it("--download waits and saves the deliverable", async () => {+ const r = await run(["render", "--download", "--json"], { cwd: project });+ expect(r.code, r.stderr).toBe(0);+ const result = r.json<{ status: string; files: string[] }>();+ expect(result.status).toBe("completed");+ expect(+ fs.readFileSync(path.join(project, result.files[0] as string), "utf8"),+ ).toMatch(/^fake video/);+ const list = await run(+ ["render", "list", "--status", "completed", "--json"],+ { cwd: project },+ );+ expect(list.json<unknown[]>().length).toBe(1);+ }, 20000);++ it("render cancel explains the missing endpoint", async () => {+ const [jobId] = [...cloud.renders.keys()];+ const r = await run(["render", "cancel", jobId as string], {+ cwd: project,+ });+ expect(r.code).toBe(1);+ expect(r.stderr).toContain("does not support cancelling renders yet");+ });+ });++ it("ff api makes raw authenticated requests", async () => {+ const r = await run(["api", "/v1/organization"], { cwd: project });+ expect(JSON.parse(r.stdout)).toMatchObject({+ organization: { id: "org_test" },+ });+ const created = await run(+ ["api", "/v1/repos", "-f", "name=via-api", "-F", "nothing=null"],+ { cwd: project },+ );+ expect(created.code, created.stderr).toBe(0);+ expect(JSON.parse(created.stdout)).toMatchObject({ name: "via-api" });+ const missing = await run(["api", "/v1/nope"], { cwd: project });+ expect(missing.code).toBe(1);+ });++ it("git credential helper answers with a bearer token when git can take one", async () => {+ const repo = [...cloud.repos.values()].find((r) => r.name === "film");+ const remote = new URL(+ (repo?.remoteUrl as string).replace("file://", "https://git.example"),+ );+ const stdin = `protocol=https\nhost=${remote.host}\npath=${remote.pathname.slice(1)}\ncapability[]=authtype\n\n`;+ // The fake's remotes are file:// URLs; point the lookup at an https twin.+ (repo as { remoteUrl: string }).remoteUrl = remote.toString();+ try {+ const bearer = await run(["auth", "git-credential", "get"], {+ cwd: project,+ stdin,+ });+ expect(bearer.stdout).toMatch(+ /^capability\[\]=authtype\nauthtype=Bearer\ncredential=art_write_\d+\nephemeral=true\n$/,+ );+ const basic = await run(["auth", "git-credential", "get"], {+ cwd: project,+ stdin: stdin.replace("capability[]=authtype\n", ""),+ });+ expect(basic.stdout).toMatch(+ /^username=x-token\npassword=art_write_\d+\n$/,+ );+ const other = await run(["auth", "git-credential", "get"], {+ cwd: project,+ stdin: "protocol=https\nhost=github.com\npath=x/y.git\n",+ });+ expect(other.stdout).toBe("");+ } finally {+ (repo as { remoteUrl: string }).remoteUrl = `file://${remote.pathname}`;+ }+ });++ it("auth logout removes the key", async () => {+ expect((await run(["auth", "logout"])).stdout).toContain("logged out");+ expect((await run(["repo", "list"])).code).toBe(3);+ });+});diff --git a/packages/cli/test/fake-cloud.ts b/packages/cli/test/fake-cloud.tsnew file mode 100644index 00000000..fcba2934--- /dev/null+++ b/packages/cli/test/fake-cloud.ts@@ -0,0 +1,506 @@+// biome-ignore-all lint/suspicious/noAssignInExpressions: route matching reads best as `if ((match = re.exec(path)))`+/**+ * An in-memory Framefields Cloud with the routes `ff` uses, shaped like the+ * real worker's responses. Repositories are bare git repos on disk, so push,+ * clone and merge run real git.+ */+import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import fs from "node:fs";+import http from "node:http";+import type { AddressInfo } from "node:net";+import path from "node:path";++interface Repo {+ id: string;+ organizationId: string;+ name: string;+ description: string | null;+ visibility: "public" | "private";+ defaultBranch: string;+ remoteUrl: string;+ createdAt: string;+ updatedAt: string;+}++interface Intent {+ id: string;+ sha256: string;+ size: number;+ mimeType: string;+ parts: Map<number, Buffer>;+}++interface IssueRow {+ id: string;+ repoId: string;+ number: number;+ kind: "issue" | "pull";+ title: string;+ body: string;+ state: "open" | "closed" | "merged";+ labels: string[];+ headRef: string | null;+ baseRef: string | null;+ isDraft: boolean;+ createdAt: string;+ updatedAt: string;+ closedAt: string | null;+ mergedAt: string | null;+ events: {+ id: string;+ kind: string;+ body: string | null;+ createdAt: string;+ }[];+}++export interface FakeCloud {+ url: string;+ apiKey: string;+ org: { id: string; name: string; slug: string; role: string };+ repos: Map<string, Repo>;+ blobs: Map<string, Buffer>;+ assetRefs: Map<string, { ref: string; commitSha: string; hashes: string[] }>;+ renders: Map<string, Record<string, unknown>>;+ issues: IssueRow[];+ requests: string[];+ /** Scopes of the API key; tests narrow it to provoke 403s. */+ scopes: string[];+ partSize: number;+ close(): Promise<void>;+}++export async function startFakeCloud(+ dir: string,+ options: { partSize?: number } = {},+): Promise<FakeCloud> {+ const apiKey = "ff_test_0123456789abcdef";+ let n = 0;+ const id = (prefix: string) =>+ `${prefix}_${(++n).toString(16).padStart(8, "0")}`;+ const now = () => new Date().toISOString();+ const intents = new Map<string, Intent>();++ const state: FakeCloud = {+ url: "",+ apiKey,+ org: { id: "org_test", name: "Test Org", slug: "test-org", role: "owner" },+ repos: new Map(),+ blobs: new Map(),+ assetRefs: new Map(),+ renders: new Map(),+ issues: [],+ requests: [],+ scopes: ["repo:read", "repo:write", "render:create", "assets:sync"],+ partSize: options.partSize ?? 8,+ close: async () => {},+ };++ const json = (res: http.ServerResponse, status: number, body: unknown) => {+ res.writeHead(status, { "content-type": "application/json" });+ res.end(JSON.stringify(body));+ };+ const readBody = (req: http.IncomingMessage) =>+ new Promise<Buffer>((resolve) => {+ const chunks: Buffer[] = [];+ req.on("data", (c: Buffer) => chunks.push(c));+ req.on("end", () => resolve(Buffer.concat(chunks)));+ });+ const need = (scope: string) =>+ state.scopes.includes(scope) || state.scopes.includes("admin");+ const serialize = (i: IssueRow) => {+ const { events, repoId: _r, ...rest } = i;+ return {+ ...rest,+ author: { id: "u1", name: "Tester", image: null },+ commentCount: events.filter((e) => e.kind === "comment").length,+ };+ };++ const server = http.createServer(async (req, res) => {+ const url = new URL(req.url ?? "/", "http://x");+ const p = url.pathname;+ const m = req.method ?? "GET";+ state.requests.push(`${m} ${p}`);+ if (req.headers.authorization !== `Bearer ${apiKey}`)+ return json(res, 401, { error: "Invalid API key" });+ const body = await readBody(req);+ const data = () => (body.length ? JSON.parse(body.toString("utf8")) : {});+ let match: RegExpExecArray | null;++ if (m === "GET" && p === "/v1/organization")+ return json(res, 200, { organization: state.org });++ // ── Repositories ──+ if (p.startsWith("/v1/repos") && !need("repo:read"))+ return json(res, 403, { error: "Missing required scope: repo:read" });+ if (m === "GET" && p === "/v1/repos")+ return json(res, 200, { repositories: [...state.repos.values()] });+ if (m === "POST" && p === "/v1/repos") {+ if (!need("repo:write"))+ return json(res, 403, { error: "Missing required scope: repo:write" });+ const { name, description, visibility = "private" } = data();+ if ([...state.repos.values()].some((r) => r.name === name))+ return json(res, 409, {+ error: `Repository '${name}' already exists in organization`,+ });+ const bare = path.join(dir, "remotes", `${name}.git`);+ fs.mkdirSync(bare, { recursive: true });+ execFileSync("git", ["init", "--quiet", "--bare", "-b", "main", bare]);+ const repo: Repo = {+ id: id("repo"),+ organizationId: state.org.id,+ name,+ description: description ?? null,+ visibility,+ defaultBranch: "main",+ remoteUrl: `file://${bare}`,+ createdAt: now(),+ updatedAt: now(),+ };+ state.repos.set(repo.id, repo);+ return json(res, 201, { ...repo, token: "art_git_initial" });+ }+ if ((match = /^\/v1\/repos\/([^/]+)(\/.*)?$/.exec(p))) {+ const repo = state.repos.get(decodeURIComponent(match[1] as string));+ if (!repo) return json(res, 404, { error: "Repository not found" });+ const rest = match[2] ?? "";+ if (m === "GET" && rest === "") return json(res, 200, repo);+ if (m === "DELETE" && rest === "") {+ state.repos.delete(repo.id);+ return json(res, 200, { ok: true, deleted: repo.id });+ }+ if (m === "POST" && rest === "/fork") {+ const { name = `${repo.name}-fork` } = data();+ const bare = path.join(dir, "remotes", `${name}.git`);+ execFileSync("git", [+ "clone",+ "--quiet",+ "--bare",+ repo.remoteUrl.slice(7),+ bare,+ ]);+ const fork: Repo = {+ ...repo,+ id: id("repo"),+ name,+ remoteUrl: `file://${bare}`,+ createdAt: now(),+ updatedAt: now(),+ };+ state.repos.set(fork.id, fork);+ return json(res, 201, {+ ...fork,+ token: "art_git_fork",+ forkedFrom: repo.id,+ });+ }+ if (m === "POST" && rest === "/tokens") {+ const { scope = "write" } = data();+ return json(res, 200, {+ token: `art_${scope}_${n++}`,+ expiresAt: now(),+ scope,+ });+ }+ if (m === "GET" && rest === "/compositions") {+ return json(res, 200, {+ ref: url.searchParams.get("ref") ?? repo.defaultBranch,+ source: "default",+ compositions: [+ {+ id: "film",+ entry: "src/film.ts",+ export: "buildFilm",+ title: "Film",+ description: null,+ group: null,+ default: true,+ },+ ],+ defaultId: "film",+ });+ }+ if (m === "POST" && rest === "/assets/diff")+ return diff(res, data().assets);+ if (m === "PUT" && rest === "/asset-refs") {+ const { ref, commitSha, lockfile } = data();+ const hashes = Object.values(+ lockfile.assets as Record<string, { sha256: string }>,+ ).map((a) => a.sha256);+ const unknown = hashes.filter((h) => !state.blobs.has(h));+ if (unknown.length)+ return json(res, 409, {+ error: `Blobs not uploaded: ${unknown.join(", ")}`,+ });+ state.assetRefs.set(`${repo.id} ${ref}`, { ref, commitSha, hashes });+ return json(res, 200, { ref, commitSha, assets: hashes.length });+ }+ if (m === "DELETE" && rest === "/asset-refs") {+ const ref = url.searchParams.get("ref") ?? "";+ state.assetRefs.delete(`${repo.id} ${ref}`);+ return json(res, 200, { released: ref });+ }+ if (+ (match = /^\/(issues|pulls)(?:\/(\d+))?(\/comments|\/merge)?$/.exec(+ rest,+ ))+ ) {+ const kind = match[1] === "pulls" ? "pull" : "issue";+ const num = match[2] ? Number(match[2]) : undefined;+ const action = match[3];+ if (m === "GET" && num === undefined) {+ const s = url.searchParams.get("state") ?? "open";+ const items = state.issues+ .filter((i) => i.repoId === repo.id && i.kind === kind)+ .filter(+ (i) =>+ s === "all" ||+ (s === "open" ? i.state === "open" : i.state !== "open"),+ )+ .sort((a, b) => b.number - a.number);+ return json(res, 200, {+ items: items.map(serialize),+ counts: { open: 0, closed: 0 },+ });+ }+ if (m === "POST" && num === undefined) {+ const d = data();+ const row: IssueRow = {+ id: id(kind === "pull" ? "pr" : "iss"),+ repoId: repo.id,+ number: state.issues.filter((i) => i.repoId === repo.id).length + 1,+ kind,+ title: d.title,+ body: d.body ?? "",+ state: "open",+ labels: d.labels ?? [],+ headRef: d.headRef ?? null,+ baseRef: d.baseRef ?? null,+ isDraft: !!d.draft,+ createdAt: now(),+ updatedAt: now(),+ closedAt: null,+ mergedAt: null,+ events: [],+ };+ state.issues.push(row);+ return json(res, 201, serialize(row));+ }+ const row = state.issues.find(+ (i) => i.repoId === repo.id && i.kind === kind && i.number === num,+ );+ if (!row)+ return json(res, 404, {+ error:+ kind === "pull" ? "Pull request not found" : "Issue not found",+ });+ if (m === "GET" && !action)+ return json(res, 200, { ...serialize(row), timeline: row.events });+ if (m === "PATCH" && !action) {+ const d = data();+ if (d.title !== undefined) row.title = d.title;+ if (d.body !== undefined) row.body = d.body;+ if (d.labels !== undefined) row.labels = d.labels;+ if (d.draft !== undefined) row.isDraft = d.draft;+ if (d.state && d.state !== row.state) {+ row.state = d.state;+ row.events.push({+ id: id("evt"),+ kind: d.state === "closed" ? "closed" : "reopened",+ body: null,+ createdAt: now(),+ });+ }+ return json(res, 200, { ok: true, number: row.number });+ }+ if (m === "POST" && action === "/comments") {+ row.events.push({+ id: id("evt"),+ kind: "comment",+ body: data().body,+ createdAt: now(),+ });+ return json(res, 201, { ok: true });+ }+ if (m === "POST" && action === "/merge") {+ if (row.state !== "open")+ return json(res, 409, {+ error: "Only open pull requests can be merged",+ });+ row.state = "merged";+ row.mergedAt = now();+ return json(res, 200, {+ ok: true,+ number: row.number,+ mergedAt: row.mergedAt,+ });+ }+ }+ return json(res, 404, { error: "not found" });+ }++ // ── Assets ──+ if (m === "POST" && p === "/v1/assets/diff")+ return diff(res, data().assets);+ if (+ m === "PUT" &&+ (match = /^\/v1\/assets\/uploads\/([^/]+)\/parts\/(\d+)$/.exec(p))+ ) {+ const intent = intents.get(match[1] as string);+ if (!intent) return json(res, 404, { error: "Upload not found." });+ const part = Number(match[2]);+ const count = Math.max(1, Math.ceil(intent.size / state.partSize));+ const expected =+ part < count+ ? state.partSize+ : intent.size - state.partSize * (count - 1);+ if (body.length !== expected)+ return json(res, 400, {+ error: `Part ${part} must be exactly ${expected} bytes.`,+ });+ intent.parts.set(part, body);+ return json(res, 200, { partNumber: part, etag: `etag${part}` });+ }+ if (+ m === "POST" &&+ (match = /^\/v1\/assets\/uploads\/([^/]+)\/confirm$/.exec(p))+ ) {+ const intent = intents.get(match[1] as string);+ if (!intent) return json(res, 404, { error: "Upload not found." });+ const count = Math.max(1, Math.ceil(intent.size / state.partSize));+ if (intent.parts.size !== count)+ return json(res, 409, {+ error: `Upload incomplete: ${intent.parts.size} of ${count} parts received.`,+ });+ const bytes = Buffer.concat(+ [...intent.parts.entries()].sort(([a], [b]) => a - b).map(([, b]) => b),+ );+ if (createHash("sha256").update(bytes).digest("hex") !== intent.sha256)+ return json(res, 422, { error: "checksum mismatch" });+ state.blobs.set(intent.sha256, bytes);+ intents.delete(intent.id);+ return json(res, 200, { sha256: intent.sha256, sizeBytes: bytes.length });+ }+ if (m === "GET" && (match = /^\/v1\/assets\/([0-9a-f]{64})$/.exec(p))) {+ const blob = state.blobs.get(match[1] as string);+ if (!blob) return json(res, 404, { error: "not found" });+ res.writeHead(200, {+ "content-type": "application/octet-stream",+ "content-length": blob.length,+ });+ res.end(blob);+ return;+ }++ // ── Renders ──+ if (p.startsWith("/v1/renders") && !need("render:create"))+ return json(res, 403, { error: "Missing required scope: render:create" });+ if (m === "POST" && p === "/v1/renders") {+ const d = data();+ const repo = state.repos.get(d.repositoryId);+ if (!repo) return json(res, 404, { error: "Repository not found" });+ const job = {+ id: id("rnd"),+ repositoryId: repo.id,+ commitSha: d.commitSha,+ composition: d.composition ?? (d.entryPath ? null : "film"),+ entryPath: d.entryPath ?? "src/film.ts",+ exportName: d.exportName ?? "buildFilm",+ jobType: d.jobType ?? "video",+ status: "queued",+ renderParams: d.options ?? {},+ outputR2Key: null as string | null,+ qaReport: null,+ errorMessage: null,+ createdAt: now(),+ completedAt: null as string | null,+ downloadUrl: null as string | null,+ polls: 0,+ };+ state.renders.set(job.id, job);+ return json(res, 202, {+ jobId: job.id,+ status: "queued",+ repository: repo.name,+ commitSha: job.commitSha,+ composition: job.composition,+ });+ }+ if (m === "GET" && p === "/v1/renders") {+ const repoId = url.searchParams.get("repositoryId");+ return json(res, 200, {+ renderJobs: [...state.renders.values()].filter(+ (j) => !repoId || j.repositoryId === repoId,+ ),+ });+ }+ if (m === "GET" && (match = /^\/v1\/renders\/(rnd_[^/]+)$/.exec(p))) {+ const job = state.renders.get(match[1] as string) as+ | (Record<string, unknown> & { polls: number })+ | undefined;+ if (!job) return json(res, 404, { error: "Render job not found" });+ // queued → running → completed over successive polls.+ job.polls++;+ if (job.polls === 2) job.status = "running";+ if (job.polls >= 3 && job.status === "running") {+ job.status = "completed";+ job.completedAt = now();+ job.outputR2Key = `renders/${job.id}.mp4`;+ job.downloadUrl = `/v1/renders/download/renders/${job.id}.mp4`;+ }+ return json(res, 200, job);+ }+ if (m === "GET" && (match = /^\/v1\/renders\/download\/(.+)$/.exec(p))) {+ res.writeHead(200, { "content-type": "video/mp4" });+ res.end(Buffer.from(`fake video ${match[1]}`));+ return;+ }+ return json(res, 404, { error: "not found" });++ function diff(+ response: http.ServerResponse,+ claims: { sha256: string; size: number; mimeType: string }[],+ ) {+ if (!need("assets:sync") && !need("repo:write"))+ return json(response, 403, {+ error: "Missing required scope: assets:sync",+ });+ const present = claims+ .filter((c) => state.blobs.has(c.sha256))+ .map((c) => c.sha256);+ const missing = claims+ .filter((c) => !state.blobs.has(c.sha256))+ .map((c) => {+ let intent = [...intents.values()].find((i) => i.sha256 === c.sha256);+ if (!intent) {+ intent = {+ id: id("upl"),+ sha256: c.sha256,+ size: c.size,+ mimeType: c.mimeType,+ parts: new Map(),+ };+ intents.set(intent.id, intent);+ }+ return {+ sha256: c.sha256,+ intentId: intent.id,+ expiresAt: now(),+ confirmUrl: `/v1/assets/uploads/${intent.id}/confirm`,+ transport: "parts",+ partSize: state.partSize,+ partCount: Math.max(1, Math.ceil(c.size / state.partSize)),+ partUrl: `/v1/assets/uploads/${intent.id}/parts/`,+ uploadedParts: [...intent.parts.keys()].sort(),+ };+ });+ return json(response, 200, { present: [...new Set(present)], missing });+ }+ });+ await new Promise<void>((r) => server.listen(0, "127.0.0.1", r));+ state.url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;+ state.close = () => new Promise<void>((r) => server.close(() => r()));+ return state;+}diff --git a/packages/cli/test/helpers.ts b/packages/cli/test/helpers.tsnew file mode 100644index 00000000..b9481287--- /dev/null+++ b/packages/cli/test/helpers.ts@@ -0,0 +1,93 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { run } from "../src/cli.js";+import type { Io } from "../src/output.js";++export interface RunResult {+ code: number;+ stdout: string;+ stderr: string;+ json<T = unknown>(): T;+}++export interface RunOptions {+ cwd: string;+ env?: Record<string, string | undefined>;+ stdin?: string;+ tty?: boolean;+ answers?: string[];+}++/** Runs `ff` in-process with a fake terminal. */+export async function ff(+ args: string[],+ options: RunOptions,+): Promise<RunResult> {+ let stdout = "";+ let stderr = "";+ const answers = [...(options.answers ?? [])];+ const io: Io = {+ stdout: (t) => {+ stdout += t;+ },+ stderr: (t) => {+ stderr += t;+ },+ readStdin: async () => options.stdin ?? "",+ isTTY: !!options.tty,+ colorSupported: false,+ prompt: async () => answers.shift() ?? "",+ openUrl: () => {},+ };+ const code = await run(args, {+ io,+ env: { ...options.env },+ cwd: options.cwd,+ });+ return {+ code,+ stdout,+ stderr,+ json: <T>() => JSON.parse(stdout) as T,+ };+}++const dirs: string[] = [];+export function tmpdir(prefix = "ff-cli-"): string {+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)));+ dirs.push(dir);+ return dir;+}+export function cleanupTmp() {+ for (const d of dirs.splice(0))+ fs.rmSync(d, { recursive: true, force: true });+}++export function writeFiles(+ root: string,+ files: Record<string, string | Buffer>,+) {+ for (const [rel, content] of Object.entries(files)) {+ const file = path.join(root, rel);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+ }+}++/** Commits by a test identity, without touching the user's git config. */+export function gitEnv(home: string) {+ Object.assign(process.env, {+ GIT_AUTHOR_NAME: "Test",+ GIT_AUTHOR_EMAIL: "[email protected]",+ GIT_COMMITTER_NAME: "Test",+ GIT_COMMITTER_EMAIL: "[email protected]",+ GIT_CONFIG_GLOBAL: path.join(home, "gitconfig"),+ GIT_CONFIG_NOSYSTEM: "1",+ GIT_ALLOW_PROTOCOL: "file",+ });+ fs.writeFileSync(+ path.join(home, "gitconfig"),+ '[init]\n\tdefaultBranch = main\n[protocol "file"]\n\tallow = always\n',+ );+}diff --git a/packages/cli/test/local.test.ts b/packages/cli/test/local.test.tsnew file mode 100644index 00000000..a6bdac2a--- /dev/null+++ b/packages/cli/test/local.test.ts@@ -0,0 +1,255 @@+/** Golden output and exit codes for project commands that don't render. */+import fs from "node:fs";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { cleanupTmp, ff, tmpdir, writeFiles } from "./helpers.js";++afterEach(cleanupTmp);++const MANIFEST = {+ version: 1,+ compositions: {+ showcase: {+ entry: "src/audio.ts",+ export: "buildShowcase",+ title: "Audio showcase",+ default: true,+ },+ "step-1": {+ entry: "src/audio.ts",+ export: "buildStep1",+ title: "Initial audio",+ group: "Steps",+ },+ "step-2": { entry: "src/audio.ts", export: "buildStep2", group: "Steps" },+ },+};++function project(manifest: unknown = MANIFEST) {+ const root = tmpdir();+ writeFiles(root, {+ "package.json": "{}",+ "framefields.json":+ typeof manifest === "string" ? manifest : JSON.stringify(manifest),+ "src/nested/.keep": "",+ });+ return root;+}++describe("ff ls", () => {+ it("prints a table", async () => {+ const r = await ff(["ls"], { cwd: path.join(project(), "src", "nested") });+ expect(r.code).toBe(0);+ expect(r.stdout).toBe(+ [+ "ID TITLE GROUP ENTRY DEFAULT",+ "showcase Audio showcase src/audio.ts#buildShowcase yes",+ "step-1 Initial audio Steps src/audio.ts#buildStep1",+ "step-2 Step 2 Steps src/audio.ts#buildStep2",+ "",+ ].join("\n"),+ );+ });++ it("--json emits the Project", async () => {+ const root = project();+ const r = await ff(["ls", "--json"], { cwd: root });+ expect(r.code).toBe(0);+ expect(r.json()).toMatchObject({+ root,+ source: "manifest",+ defaultId: "showcase",+ output: "output",+ assets: { directory: "assets", exclude: ["**/.DS_Store"] },+ });+ expect(r.json<{ compositions: unknown[] }>().compositions).toHaveLength(3);+ });++ it("-C runs elsewhere; a bare package gets the implicit film", async () => {+ const root = tmpdir();+ writeFiles(root, { "package.json": "{}", "src/film.ts": "" });+ const r = await ff(["-C", root, "ls", "--json"], { cwd: "/" });+ expect(r.json()).toMatchObject({ source: "default", defaultId: "film" });+ expect(r.stderr).toContain("no framefields.json");+ });+});++describe("exit codes and errors (§7)", () => {+ it("4 when there is no project", async () => {+ const r = await ff(["ls"], { cwd: tmpdir() });+ expect(r.code).toBe(4);+ expect(r.stderr).toMatch(+ /^error: no framefields project found in .+\n {2}hint: ff init\n$/,+ );+ expect(r.stdout).toBe("");+ });++ it("4 for an invalid manifest, with the file in the hint", async () => {+ const root = project({+ version: 1,+ compositions: { Bad: { entry: "a.ts" } },+ });+ const r = await ff(["ls"], { cwd: root });+ expect(r.code).toBe(4);+ expect(r.stderr).toContain("framefields.json at compositions.Bad");+ expect(r.stderr).toContain(+ `hint: fix ${path.join(root, "framefields.json")}`,+ );+ expect((await ff(["ls"], { cwd: project("{ nope") })).code).toBe(4);+ });++ it("2 for an unknown composition, matching the spec's example", async () => {+ const r = await ff(["frames", "step-9", "0"], { cwd: project() });+ expect(r.code).toBe(2);+ expect(r.stderr).toBe(+ "error: unknown composition 'step-9'\n hint: compositions in framefields.json: showcase, step-1, step-2 (ff ls)\n",+ );+ });++ it("2 for unknown flags and commands", async () => {+ expect((await ff(["ls", "--bogus"], { cwd: project() })).code).toBe(2);+ expect((await ff(["nope"], { cwd: project() })).code).toBe(2);+ expect((await ff(["frames"], { cwd: project() })).code).toBe(2);+ expect((await ff(["grid", "--count", "0"], { cwd: project() })).code).toBe(+ 2,+ );+ });++ it("--json errors are one JSON value on stdout", async () => {+ const r = await ff(["frames", "step-9", "0", "--json"], { cwd: project() });+ expect(r.code).toBe(2);+ expect(r.json()).toEqual({+ error: {+ code: "usage",+ message: "unknown composition 'step-9'",+ hint: "compositions in framefields.json: showcase, step-1, step-2 (ff ls)",+ },+ });+ });++ it("4 when framefields isn't installed in the project", async () => {+ const root = tmpdir();+ writeFiles(root, {+ "package.json": "{}",+ "pnpm-lock.yaml": "",+ "src/film.ts": "",+ });+ const r = await ff(["frames", "0"], { cwd: root });+ expect(r.code).toBe(4);+ expect(r.stderr).toContain(`framefields is not installed in ${root}`);+ expect(r.stderr).toContain("hint: run: pnpm add framefields");+ });++ it("0 for --help and --version", async () => {+ const help = await ff(["--help"], { cwd: "/" });+ expect(help.code).toBe(0);+ expect(help.stdout).toContain("Usage: ff");+ const version = await ff(["--version"], { cwd: "/" });+ expect(version.code).toBe(0);+ expect(version.stdout).toMatch(/^\d+\.\d+\.\d+/);+ });+});++describe("ff config", () => {+ it("sets, gets and unsets per-user settings", async () => {+ const env = { FF_CONFIG_DIR: tmpdir() };+ expect(+ (+ await ff(["config", "set", "host", "http://localhost:8787"], {+ cwd: "/",+ env,+ })+ ).code,+ ).toBe(0);+ expect(+ (await ff(["config", "get", "host"], { cwd: "/", env })).stdout,+ ).toBe("http://localhost:8787\n");+ expect(+ (await ff(["config", "get", "host", "--json"], { cwd: "/", env })).json(),+ ).toEqual({ host: "http://localhost:8787" });+ expect((await ff(["config", "set", "host"], { cwd: "/", env })).code).toBe(+ 0,+ );+ expect(+ (await ff(["config", "get", "host"], { cwd: "/", env })).stdout,+ ).toBe("");+ expect(+ (await ff(["config", "get", "colour"], { cwd: "/", env })).code,+ ).toBe(2);+ expect(+ (await ff(["config", "set", "prompt", "maybe"], { cwd: "/", env })).code,+ ).toBe(2);+ });+});++describe("ff init", () => {+ it("scaffolds a project ff can read, and keeps existing files", async () => {+ const root = tmpdir();+ writeFiles(root, { ".gitignore": "dist/\n" });+ const r = await ff(["init", "film-project", "--json"], { cwd: root });+ expect(r.code).toBe(0);+ const dir = path.join(root, "film-project");+ for (const f of [+ "src/film.ts",+ "framefields.json",+ "framefields.assets.json",+ "tsconfig.json",+ "package.json",+ ".gitignore",+ ]) {+ expect(fs.existsSync(path.join(dir, f)), f).toBe(true);+ }+ const pkg = JSON.parse(+ fs.readFileSync(path.join(dir, "package.json"), "utf8"),+ );+ expect(pkg).toMatchObject({+ name: "film-project",+ type: "module",+ scripts: { preview: "ff preview" },+ });+ expect(pkg.dependencies.framefields).toMatch(/^\^\d/);+ expect(fs.readFileSync(path.join(dir, ".gitignore"), "utf8")).toContain(+ "output/",+ );+ expect((await ff(["ls", "--json"], { cwd: dir })).json()).toMatchObject({+ source: "manifest",+ defaultId: "film",+ });++ const again = await ff(["init", "film-project", "--json"], { cwd: root });+ expect(again.json<{ skipped: string[] }>().skipped).toContain(+ "src/film.ts",+ );+ });++ it("copies a template from examples/ and makes it standalone", async () => {+ const examples = path.resolve(import.meta.dirname, "../../../examples");+ const root = tmpdir();+ const r = await ff(+ ["init", "audio", "--template", "audio-capabilities", "--json"],+ {+ cwd: root,+ env: { FF_TEMPLATES_DIR: examples },+ },+ );+ expect(r.code).toBe(0);+ const dir = path.join(root, "audio");+ const pkg = JSON.parse(+ fs.readFileSync(path.join(dir, "package.json"), "utf8"),+ );+ expect(JSON.stringify(pkg)).not.toContain("workspace:");+ expect(fs.existsSync(path.join(dir, "node_modules"))).toBe(false);+ expect(+ (await ff(["ls", "--json"], { cwd: dir })).json<{+ compositions: unknown[];+ }>().compositions,+ ).toHaveLength(8);++ const unknown = await ff(["init", "x", "--template", "nope"], {+ cwd: root,+ env: { FF_TEMPLATES_DIR: examples },+ });+ expect(unknown.code).toBe(2);+ expect(unknown.stderr).toContain("data-story");+ });+});diff --git a/packages/cli/test/units.test.ts b/packages/cli/test/units.test.tsnew file mode 100644index 00000000..5065a1a4--- /dev/null+++ b/packages/cli/test/units.test.ts@@ -0,0 +1,130 @@+import { describe, expect, it } from "vitest";+import { buildLockfile } from "../src/assets.js";+import { parseCredentialInput } from "../src/commands/auth.js";+import { hostKey, hostUrl } from "../src/config.js";+import { normalizeRemote } from "../src/git/index.js";+import { globToRegExp, matchesAny } from "../src/glob.js";+import {+ looksLikeFrame,+ parseFrame,+ parseRange,+ spreadFrames,+} from "../src/timecode.js";++describe("timecodes", () => {+ it("parses frames, seconds, milliseconds and clock times", () => {+ expect(parseFrame("60", 30)).toBe(60);+ expect(parseFrame("2.5s", 30)).toBe(75);+ expect(parseFrame("1500ms", 24)).toBe(36);+ expect(parseFrame("02:15", 30)).toBe(135 * 30);+ expect(parseFrame("00:02:15", 30)).toBe(135 * 30);+ expect(parseFrame("00:00:01.5", 30)).toBe(45);+ expect(parseFrame("00:00:01:12", 24)).toBe(36);+ });++ it("rejects other input as a usage error", () => {+ for (const bad of ["", "abc", "-1", "1.5", "2.5x", "00:00:01:30"]) {+ expect(() => parseFrame(bad, 30)).toThrow(+ expect.objectContaining({ code: "usage" }),+ );+ }+ });++ it("tells frames from composition ids", () => {+ expect(looksLikeFrame("60")).toBe(true);+ expect(looksLikeFrame("2.5s")).toBe(true);+ expect(looksLikeFrame("00:02:15")).toBe(true);+ expect(looksLikeFrame("step-1")).toBe(false);+ expect(looksLikeFrame("film")).toBe(false);+ });++ it("ranges and spreads", () => {+ expect(parseRange("0..120", 30)).toEqual({ from: 0, to: 120 });+ expect(parseRange("..5s", 30)).toEqual({ from: undefined, to: 150 });+ expect(parseRange("10-20", 30)).toEqual({ from: 10, to: 20 });+ expect(spreadFrames(0, 899, 4)).toEqual([0, 300, 599, 899]);+ expect(spreadFrames(0, 2, 16)).toEqual([0, 1, 2]);+ expect(spreadFrames(5, 5, 4)).toEqual([5]);+ });+});++describe("globs", () => {+ it("matches assets.exclude patterns", () => {+ expect(matchesAny(["**/.DS_Store"], ".DS_Store")).toBe(true);+ expect(matchesAny(["**/.DS_Store"], "assets/a/.DS_Store")).toBe(true);+ expect(matchesAny(["scratch/**"], "scratch/a/b.png")).toBe(true);+ expect(matchesAny(["scratch/**"], "assets/scratch.png")).toBe(false);+ expect(matchesAny(["*.{wav,mp3}"], "a.wav")).toBe(true);+ expect(matchesAny(["*.{wav,mp3}"], "x/a.wav")).toBe(false);+ expect(globToRegExp("a?.png").test("ab.png")).toBe(true);+ });+});++describe("hosts and remotes", () => {+ it("normalises hosts", () => {+ expect(hostUrl("framefields.dev")).toBe("https://framefields.dev");+ expect(hostUrl("http://localhost:8787/")).toBe("http://localhost:8787");+ expect(hostKey("http://localhost:8787")).toBe("localhost:8787");+ expect(() => hostUrl("http://")).toThrow(/invalid host/);+ });++ it("compares remotes without credentials or .git", () => {+ expect(+ normalizeRemote("https://user:[email protected]/ns/Film.git"),+ ).toBe(normalizeRemote("https://artifacts.example/ns/film"));+ });+});++describe("lockfile", () => {+ it("keeps unchanged entries' fields and unknown keys", () => {+ const prev = {+ version: 1,+ projectId: "proj_1",+ assets: {+ "assets/a.png": {+ sha256: "a".repeat(64),+ size: 1,+ uploadedAt: "2026-01-01T00:00:00Z",+ r2Key: "k",+ },+ },+ };+ const next = buildLockfile(prev, [+ {+ path: "assets/a.png",+ sha256: "a".repeat(64),+ size: 1,+ mimeType: "image/png",+ },+ {+ path: "assets/b.wav",+ sha256: "b".repeat(64),+ size: 2,+ mimeType: "audio/wav",+ },+ ]);+ expect(next.projectId).toBe("proj_1");+ expect(next.assets["assets/a.png"]).toMatchObject({+ uploadedAt: "2026-01-01T00:00:00Z",+ r2Key: "k",+ mimeType: "image/png",+ });+ expect(next.assets["assets/b.wav"]).toMatchObject({+ sha256: "b".repeat(64),+ size: 2,+ });+ });+});++it("parses git credential input", () => {+ expect(+ parseCredentialInput(+ "protocol=https\nhost=git.example\npath=ns/r.git\ncapability[]=authtype\ncapability[]=state\n\n",+ ),+ ).toEqual({+ protocol: ["https"],+ host: ["git.example"],+ path: ["ns/r.git"],+ "capability[]": ["authtype", "state"],+ });+});diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.jsonnew file mode 100644index 00000000..681bc1f7--- /dev/null+++ b/packages/cli/tsconfig.json@@ -0,0 +1,10 @@+{+ "extends": "@framefields/tsconfig/base.json",+ "compilerOptions": {+ "module": "NodeNext",+ "moduleResolution": "NodeNext",+ "types": ["node"],+ "noEmit": true+ },+ "include": ["src/**/*", "test/**/*"]+}diff --git a/packages/cli/tsdown.config.ts b/packages/cli/tsdown.config.tsnew file mode 100644index 00000000..fead7479--- /dev/null+++ b/packages/cli/tsdown.config.ts@@ -0,0 +1,15 @@+import { defineConfig } from "tsdown";++export default defineConfig({+ entry: ["src/bin.ts"],+ format: ["esm"],+ clean: true,+ dts: false,+ target: "node22",+ platform: "node",+ // The manifest reader is tiny and has no engine dependencies: bundle it so+ // installing the CLI never installs the engine. Rendering uses the+ // `framefields` installed in the project.+ noExternal: [/^framefields\/project$/],+ external: [/^node:/, /^@clack\//, "commander", "tsx", /^tsx\//, "zod"],+});diff --git a/packages/cli/vitest.config.ts b/packages/cli/vitest.config.tsnew file mode 100644index 00000000..8d253d91--- /dev/null+++ b/packages/cli/vitest.config.ts@@ -0,0 +1,12 @@+import { defineConfig } from "vitest/config";++export default defineConfig({+ resolve: { conditions: ["development"] },+ ssr: { resolve: { conditions: ["development"] } },+ test: {+ environment: "node",+ include: ["test/**/*.test.ts"],+ pool: "forks",+ testTimeout: 30000,+ },+});diff --git a/packages/framefields/package.json b/packages/framefields/package.jsonindex 73b3f3e5..7d4a9602 100644--- a/packages/framefields/package.json+++ b/packages/framefields/package.json@@ -71,13 +71,21 @@"development": "./src/preview/index.ts","import": "./dist/preview/index.mjs","default": "./dist/preview/index.mjs"- }+ },+ "./project": {+ "types": "./dist/project/index.d.mts",+ "development": "./src/project/index.ts",+ "import": "./dist/project/index.mjs",+ "default": "./dist/project/index.mjs"+ },+ "./schemas/project.v1.json": "./schemas/project.v1.json"},"files": [- "dist/**"+ "dist/**",+ "schemas/**"],"scripts": {- "build": "tsdown && node ../../scripts/sync-readme.mjs && node scripts/check-dts-bundle.mjs",+ "build": "tsdown && node scripts/generate-project-schema.mjs && node ../../scripts/sync-readme.mjs && node scripts/check-dts-bundle.mjs","dev": "tsdown --watch","clean": "rm -rf dist .turbo","prepack": "node ../../scripts/sync-readme.mjs",@@ -171,4 +179,4 @@"typescript": "^5.8.3","vitest": "4.1.5"}-}\ No newline at end of file+}diff --git a/packages/framefields/schemas/project.v1.json b/packages/framefields/schemas/project.v1.jsonnew file mode 100644index 00000000..49ef0596--- /dev/null+++ b/packages/framefields/schemas/project.v1.json@@ -0,0 +1,82 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "type": "object",+ "properties": {+ "$schema": {+ "type": "string"+ },+ "version": {+ "default": 1,+ "type": "number",+ "const": 1+ },+ "compositions": {+ "type": "object",+ "propertyNames": {+ "type": "string",+ "pattern": "^[a-z0-9][a-z0-9-]{0,62}$"+ },+ "additionalProperties": {+ "type": "object",+ "properties": {+ "entry": {+ "type": "string",+ "minLength": 1+ },+ "export": {+ "default": "default",+ "type": "string",+ "pattern": "^[A-Za-z_$][\\w$]*$"+ },+ "title": {+ "type": "string",+ "maxLength": 120+ },+ "description": {+ "type": "string",+ "maxLength": 500+ },+ "group": {+ "type": "string",+ "maxLength": 60+ },+ "default": {+ "type": "boolean"+ }+ },+ "required": [+ "entry"+ ],+ "additionalProperties": {}+ }+ },+ "assets": {+ "type": "object",+ "properties": {+ "directory": {+ "type": "string",+ "minLength": 1+ },+ "exclude": {+ "type": "array",+ "items": {+ "type": "string",+ "minLength": 1+ }+ }+ },+ "additionalProperties": {}+ },+ "output": {+ "type": "string",+ "minLength": 1+ }+ },+ "required": [+ "compositions"+ ],+ "additionalProperties": {},+ "$id": "https://framefields.dev/schemas/project.v1.json",+ "title": "framefields.json",+ "description": "Framefields project manifest: the project's compositions, by stable id."+}diff --git a/packages/framefields/scripts/generate-project-schema.mjs b/packages/framefields/scripts/generate-project-schema.mjsnew file mode 100644index 00000000..4e07573b--- /dev/null+++ b/packages/framefields/scripts/generate-project-schema.mjs@@ -0,0 +1,24 @@+// Writes schemas/project.v1.json, the JSON Schema for framefields.json, from+// the zod schema in src/project so editors validate the manifest. Runs after+// tsdown, against the built module.+import { mkdirSync, writeFileSync } from "node:fs";+import { z } from "zod";+import {+ MANIFEST_SCHEMA_URL,+ projectManifestSchema,+} from "../dist/project/index.mjs";++const schema = {+ ...z.toJSONSchema(projectManifestSchema, { io: "input" }),+ $id: MANIFEST_SCHEMA_URL,+ title: "framefields.json",+ description:+ "Framefields project manifest: the project's compositions, by stable id.",+};++mkdirSync("schemas", { recursive: true });+writeFileSync(+ "schemas/project.v1.json",+ `${JSON.stringify(schema, null, "\t")}\n`,+);+console.log("schemas/project.v1.json");diff --git a/packages/framefields/src/preview/index.ts b/packages/framefields/src/preview/index.tsindex 26b3c324..36e30f36 100644--- a/packages/framefields/src/preview/index.ts+++ b/packages/framefields/src/preview/index.ts@@ -7,6 +7,11 @@ import path from "node:path";import { fileURLToPath, pathToFileURL } from "node:url";import type { VirtualMediaData } from "@framefields/core";import { encodeStereoWav } from "../audio/index.js";+import {+ type Project,+ type ResolvedComposition,+ resolveComposition,+} from "../project/index.js";import { HeadlessMediaRenderer } from "../renderer/index.js";import {bundleProject,@@ -18,8 +23,11 @@ import {import { describeNote, type NewNote, NoteStore } from "./notes.js";import { previewPage } from "./page.js";-/** Where the composition comes from: the module that builds it. */-export interface PreviewSource {+/** Where the composition comes from: the module that builds it, or a project's composition. */+export type PreviewSource = PreviewEntrySource | PreviewProjectSource;++/** The module that builds the composition. */+export interface PreviewEntrySource {/** Path or file URL of the module, e.g. `new URL("./film.ts", import.meta.url)`. */entry: string | URL;/**@@ -29,6 +37,16 @@ export interface PreviewSource {export?: string;}+/**+ * A composition of a project (see `framefields/project`). The page can switch+ * between the project's compositions.+ */+export interface PreviewProjectSource {+ project: Project;+ /** A composition id, `file#export`, or undefined for the default. */+ composition?: string;+}+/** What the server needs from the composition: its size, timing and soundtrack. */interface PreviewTarget {toVirtualMedia?(): VirtualMediaData;@@ -109,6 +127,10 @@ export interface PreviewSession {interface PreviewMeta {session: string;+ /** The composition shown, when previewing a project. */+ composition: string | null;+ /** The project's compositions, for the page's picker. */+ compositions: { id: string; title: string; group: string | null }[];/** Where notes are kept; null when they are off. */notesDir: string | null;title: string;@@ -144,18 +166,42 @@ export async function startPreview(source: PreviewSource,options: PreviewOptions = {},): Promise<PreviewSession> {- const entry =- source.entry instanceof URL || String(source.entry).startsWith("file:")- ? fileURLToPath(source.entry)- : path.resolve(String(source.entry));- const exportName = source.export ?? "default";+ const project = "project" in source ? source.project : undefined;+ const pick = (ref?: string): Picked => {+ if (!project) {+ const s = source as PreviewEntrySource;+ const entry =+ s.entry instanceof URL || String(s.entry).startsWith("file:")+ ? fileURLToPath(s.entry)+ : path.resolve(String(s.entry));+ return { id: null, entry, exportName: s.export ?? "default" };+ }+ const c = resolveComposition(project, ref);+ return {+ id: c.id,+ entry: path.join(project.root, c.entry),+ exportName: c.export,+ composition: c,+ };+ };+ let current = pick("project" in source ? source.composition : undefined);+ const compositions = project+ ? [+ ...project.compositions,+ ...(current.composition &&+ !project.compositions.includes(current.composition)+ ? [current.composition]+ : []),+ ].map((c) => ({ id: c.id, title: c.title, group: c.group }))+ : [];+ const baseDir = project?.root ?? path.dirname(current.entry);// Vision nodes load their cached models, and onnxruntime-web's files when// the project has it installed.const modelsDir = visionModelsDir();- const ort = onnxRuntimeWeb(path.dirname(entry));+ const ort = onnxRuntimeWeb(baseDir);const roots = [...(options.root === undefined- ? [repoRoot(path.dirname(entry))]+ ? [repoRoot(baseDir)]: Array.isArray(options.root)? options.root: [options.root]),@@ -167,8 +213,8 @@ export async function startPreview(const sseClients = new Set<http.ServerResponse>();const idleCloseMs = options.idleCloseMs ?? 5000;let idleTimer: NodeJS.Timeout | undefined;- const title = options.title ?? "framefields preview";- const session = randomUUID();+ const titleFor = (p: Picked) =>+ options.title ?? p.composition?.title ?? "framefields preview";const log =options.log === false? () => {}@@ -178,25 +224,34 @@ export async function startPreview(const reported = new Set<string>();let pageOpened = false;- const notes =+ // Several compositions keep their notes apart, one folder each.+ const notesFor = (p: Picked) =>options.notesDir === false? undefined: new NoteStore(path.resolve(options.notesDir ??path.join(process.cwd(), ".framefields", "preview-notes"),+ compositions.length > 1 && p.id ? p.id : "",),);+ let notes = notesFor(current);// Changes run one at a time: each reads and rewrites notes.json.let noteQueue: Promise<unknown> = Promise.resolve();- const target = await loadTarget(entry, exportName);- const meta = await resolveMeta(target, title, session, notes?.dir ?? null);+ const describe = (target: PreviewTarget, p: Picked) =>+ resolveMeta(target, titleFor(p), randomUUID(), notes?.dir ?? null, {+ composition: p.id,+ compositions,+ });+ let target = await loadTarget(current.entry, current.exportName);+ let meta = await describe(target, current);// The project's own code, bundled against the browser engine; the engine// itself is prebuilt (or built once, running from source).let bundle: Promise<string> | undefined;const playerBundle = () => {if (!bundle) {+ const { entry, exportName } = current;const built = bundleProject({entry,exportName,@@ -222,6 +277,9 @@ export async function startPreview(state: options.audio === false ? "none" : "mixing",};let audioWav: Buffer | undefined;+ // Bumped on each switch, so a soundtrack still mixing for the last+ // composition is dropped.+ let generation = 0;function broadcast(event: string, data: unknown) {for (const client of sseClients) {@@ -241,13 +299,16 @@ export async function startPreview(return;}const renderer = options.renderer ?? new HeadlessMediaRenderer();+ const mixing = generation;+ const { fps } = meta;(async () => {const vm = target.toVirtualMediaAsync? await target.toVirtualMediaAsync(): (target.toVirtualMedia as () => VirtualMediaData)();- return renderer.renderAudio(vm, { fps: meta.fps });+ return renderer.renderAudio(vm, { fps });})().then(({ channels, sampleRate }) => {+ if (mixing !== generation) return;const left = channels[0] ?? new Float32Array(0);const right = channels[1] ?? left;const peaks = computePeaks(left, right, PEAK_BINS);@@ -263,6 +324,7 @@ export async function startPreview(});},(err: unknown) => {+ if (mixing !== generation) return;setAudio({state: "error",error: err instanceof Error ? err.message : String(err),@@ -390,6 +452,30 @@ export async function startPreview(});return;}+ // The page's composition picker: load the other composition, then+ // say hello with a new session so open tabs reload into it.+ if (+ project &&+ req.method === "POST" &&+ url.pathname === "/@framefields/composition" &&+ req.headers["content-type"] === "application/json"+ ) {+ const { id } = JSON.parse(await readBody(req, 4096)) as {+ id?: unknown;+ };+ if (typeof id !== "string" || !compositions.some((c) => c.id === id)) {+ sendJson(res, 404, { error: "no such composition" });+ return;+ }+ try {+ await switchTo(id);+ } catch (err) {+ sendJson(res, 422, { error: errorText(err) });+ return;+ }+ sendJson(res, 200, { ok: true, session: meta.session });+ return;+ }// A newer preview of the same project wants this port. The custom// header keeps web pages from triggering it (it forces a CORS preflight).if (@@ -424,9 +510,10 @@ export async function startPreview(res.writeHead(204).end();return;}- if (notes && url.pathname === "/@framefields/notes") {+ const store = notes;+ if (store && url.pathname === "/@framefields/notes") {if (req.method === "GET") {- sendJson(res, 200, await notes.list());+ sendJson(res, 200, await store.list());return;}if (@@ -441,11 +528,11 @@ export async function startPreview(note?: NewNote;};const change = noteQueue.then(() =>- changeNote(notes, body, meta.fps, say),+ changeNote(store, body, meta.fps, say),);noteQueue = change.catch(() => {});const note = await change;- broadcast("notes", await notes.list());+ broadcast("notes", await store.list());sendJson(res, note ? 200 : 404, note ?? { error: "no such note" });return;}@@ -502,6 +589,25 @@ export async function startPreview(}});+ async function switchTo(id: string) {+ if (id === current.id) return;+ const next = pick(id);+ const nextTarget = await loadTarget(next.entry, next.exportName);+ current = next;+ target = nextTarget;+ notes = notesFor(next);+ meta = await describe(nextTarget, next);+ bundle = undefined;+ generation++;+ audioWav = undefined;+ audio = { state: options.audio === false ? "none" : "mixing" };+ reported.clear();+ say(`switched to ${id}`);+ void playerBundle().catch(() => {});+ startAudio();+ broadcast("hello", { session: meta.session });+ }+let onClient: (() => void) | undefined;const host = options.host ?? "127.0.0.1";const port = options.port ?? stablePort();@@ -728,17 +834,27 @@ async function sendFile(fs.createReadStream(file, { start, end }).pipe(res);}+/** The composition being previewed. */+interface Picked {+ id: string | null;+ entry: string;+ exportName: string;+ composition?: ResolvedComposition;+}+async function resolveMeta(target: PreviewTarget,title: string,session: string,notesDir: string | null,+ project: Pick<PreviewMeta, "composition" | "compositions">,): Promise<PreviewMeta> {const fps = target.fps ?? 24;const durationMs =target.durationMs ?? (await target.computeDuration?.()) ?? 5000;return {session,+ ...project,notesDir,title,fps,diff --git a/packages/framefields/src/preview/page.ts b/packages/framefields/src/preview/page.tsindex 3fa752e7..13974b51 100644--- a/packages/framefields/src/preview/page.ts+++ b/packages/framefields/src/preview/page.ts@@ -62,6 +62,12 @@ export const previewPage = /* html */ `<!doctype html>.sep { width: 1px; height: 18px; background: var(--line-2); flex: none; margin: 0 2px; }.top h1 { font-size: 14px; font-weight: 600; margin: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.spec { color: var(--ink-3); font-size: 12px; white-space: nowrap; }+ .comp {+ height: 28px; max-width: 260px; padding: 0 8px; border: 1px solid var(--line); border-radius: 8px;+ background: var(--surface); color: var(--ink); font: inherit; font-size: 12.5px; flex: none; cursor: pointer;+ }+ .comp:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }+ .comp:disabled { opacity: .6; cursor: progress; }@media (max-width: 640px) { .spec { display: none; } }.chip {display: inline-flex; align-items: center; gap: 8px; height: 26px; padding: 0 10px; white-space: nowrap;@@ -286,6 +292,7 @@ export const previewPage = /* html */ `<!doctype html><svg class="logo" viewBox="0 0 512 512" aria-label="framefields" role="img"><g fill="none" stroke="currentColor" stroke-linecap="round"><path d="M184 56H86q-30 0-30 30v98M328 56h98q30 0 30 30v98M184 456H86q-30 0-30-30v-98M328 456h98q30 0 30-30v-98" stroke-width="34" stroke-linejoin="round"/><path d="M176 182v148m0-148c0 74 60 74 100 74" stroke-width="28"/></g><g fill="currentColor"><circle cx="176" cy="172" r="32"/><circle cx="176" cy="340" r="32"/><path d="M284 200l78 56-78 56z" stroke="currentColor" stroke-width="34" stroke-linejoin="round"/></g></svg><span class="sep" aria-hidden="true"></span><h1 id="title">framefields preview</h1>+ <select class="comp" id="comp" aria-label="Composition" title="Composition" hidden></select><span class="grow"></span><span class="spec tnum" id="spec"></span><span class="chip" id="chip" data-state="mixing" role="status" aria-live="polite"><span class="spinner"></span><span>Mixing audio</span></span>@@ -1161,11 +1168,51 @@ export const previewPage = /* html */ `<!doctype html>$("title").textContent = m.title;$("spec").textContent = m.width + "×" + m.height + " · " + m.fps + " fps · " + fmt(last());$("tcDur").textContent = fmt(last());+ renderPicker(m);stage.style.setProperty("--ar", m.width + " / " + m.height);stage.style.setProperty("--ar-n", String(m.width / m.height));renderRuler();}+ // A project's compositions: switching asks the server to load the other one,+ // and its hello with a new session reloads this tab into it.+ function renderPicker(m) {+ var sel = $("comp"), list = m.compositions || [];+ sel.hidden = list.length < 2;+ if (sel.hidden) return;+ sel.textContent = "";+ var groups = {};+ list.forEach(function (c) {+ var opt = document.createElement("option");+ opt.value = c.id;+ opt.textContent = c.title === c.id ? c.id : c.title + " (" + c.id + ")";+ opt.selected = c.id === m.composition;+ if (!c.group) { sel.appendChild(opt); return; }+ if (!groups[c.group]) {+ groups[c.group] = document.createElement("optgroup");+ groups[c.group].label = c.group;+ sel.appendChild(groups[c.group]);+ }+ groups[c.group].appendChild(opt);+ });+ }+ $("comp").addEventListener("change", function () {+ var sel = $("comp");+ sel.disabled = true;+ fetch("/@framefields/composition", {+ method: "POST",+ headers: { "content-type": "application/json" },+ body: JSON.stringify({ id: sel.value })+ }).then(function (r) { return r.json().then(function (b) { return [r.ok, b]; }); }).then(function (res) {+ if (!res[0]) throw new Error(res[1].error || "could not switch");+ location.reload();+ }).catch(function (err) {+ sel.disabled = false;+ sel.value = meta.composition;+ showError(err);+ });+ });+new ResizeObserver(function () {if (!meta) return;renderRuler();diff --git a/packages/framefields/src/project/index.ts b/packages/framefields/src/project/index.tsnew file mode 100644index 00000000..e6b6a18a--- /dev/null+++ b/packages/framefields/src/project/index.ts@@ -0,0 +1,415 @@+/**+ * `framefields.json`, the project manifest: names a project's compositions so+ * tools (the `ff` CLI, the preview, Framefields Cloud, agents) can tell what is+ * previewable without running code. Each composition is the `{ entry, export }`+ * pair `startPreview` already takes, under a stable id.+ *+ * This module only reads JSON and imports entries on request; it never loads+ * the engine itself, so the CLI can bundle it.+ */+import fs from "node:fs";+import path from "node:path";+import { pathToFileURL } from "node:url";+import { z } from "zod";+import type { Composition } from "../index.js";++export const MANIFEST_FILE = "framefields.json";+export const MANIFEST_SCHEMA_URL =+ "https://framefields.dev/schemas/project.v1.json";++/** Used when a project has no manifest: the layout `ff init` scaffolds. */+export const DEFAULT_COMPOSITION = {+ id: "film",+ entry: "src/film.ts",+ export: "buildFilm",+} as const;++const COMPOSITION_ID = /^[a-z0-9][a-z0-9-]{0,62}$/;+const IDENTIFIER = /^[A-Za-z_$][\w$]*$/;+const ENTRY_EXT = /\.(ts|tsx|mts|js|mjs)$/;++const isInsidePath = (p: string) =>+ !p.startsWith("/") &&+ !/^[A-Za-z]:/.test(p) &&+ !p.split(/[\\/]/).includes("..");++const entryPath = z+ .string()+ .min(1)+ .refine(isInsidePath, "entry must be a path inside the project")+ .regex(ENTRY_EXT, "entry must be a .ts, .tsx, .mts, .js or .mjs file");++const compositionSchema = z.looseObject({+ entry: entryPath,+ export: z+ .string()+ .regex(IDENTIFIER, "export must be a JavaScript identifier")+ .default("default"),+ title: z.string().max(120).optional(),+ description: z.string().max(500).optional(),+ /** Groups compositions in pickers, e.g. "Steps" or "Scenes". */+ group: z.string().max(60).optional(),+ /** The composition opened and rendered when none is named. At most one. */+ default: z.boolean().optional(),+});++const assetsSchema = z.looseObject({+ directory: z+ .string()+ .min(1)+ .refine(isInsidePath, "assets.directory must be inside the project")+ .optional(),+ exclude: z.array(z.string().min(1)).optional(),+});++export const projectManifestSchema = z.looseObject({+ $schema: z.string().optional(),+ version: z.literal(1).default(1),+ compositions: z+ .record(+ z+ .string()+ .regex(+ COMPOSITION_ID,+ "composition ids are lowercase letters, digits and dashes (max 63)",+ ),+ compositionSchema,+ )+ .refine(+ (c) => Object.keys(c).length > 0,+ "declare at least one composition",+ )+ .refine(+ (c) => Object.values(c).filter((x) => x.default).length <= 1,+ "only one composition can be the default",+ ),+ assets: assetsSchema.optional(),+ output: z+ .string()+ .min(1)+ .refine(isInsidePath, "output must be inside the project")+ .optional(),+});++export type ProjectManifest = z.input<typeof projectManifestSchema>;++export interface ResolvedComposition {+ id: string;+ entry: string;+ export: string;+ title: string;+ description: string | null;+ group: string | null;+ default: boolean;+}++export interface Project {+ /** Directory containing framefields.json (or package.json). */+ root: string;+ source: "manifest" | "default";+ compositions: ResolvedComposition[];+ defaultId: string;+ assets: { directory: string; exclude: string[] };+ output: string;+}++export type ProjectErrorKind =+ /** No framefields.json or package.json above the directory. */+ | "not-found"+ /** framefields.json is not valid JSON or breaks a rule. */+ | "invalid"+ /** A `<composition>` reference names nothing in the project. */+ | "unknown-composition"+ /** The entry could not be imported, or its export isn't a composition. */+ | "build";++/** A problem with a project, its manifest or a composition reference. */+export class ProjectError extends Error {+ override name = "ProjectError";+ constructor(+ message: string,+ readonly kind: ProjectErrorKind,+ /** The file the problem is in, when there is one. */+ readonly path?: string,+ /** A follow-up the user can run or check. */+ readonly hint?: string,+ ) {+ super(message);+ }+}++/** `step-1` → `Step 1`. */+export const humanize = (id: string) =>+ id.replace(/-+/g, " ").replace(/^\w/, (c) => c.toUpperCase());++/**+ * Parses manifest JSON (already decoded) into a project at `root`. Exposed for+ * readers that get the file from elsewhere, such as a git tree.+ */+export function resolveManifest(json: unknown, root: string): Project {+ const file = path.join(root, MANIFEST_FILE);+ const parsed = projectManifestSchema.safeParse(json);+ if (!parsed.success) {+ const issue = parsed.error.issues[0];+ const where = issue?.path.length ? ` at ${issue.path.join(".")}` : "";+ throw new ProjectError(+ `${MANIFEST_FILE}${where}: ${issue?.message ?? "invalid"}`,+ "invalid",+ file,+ );+ }+ const data = parsed.data;+ const entries = Object.entries(data.compositions);+ const defaultId =+ entries.find(([, c]) => c.default)?.[0] ?? (entries[0]?.[0] as string);+ return {+ root,+ source: "manifest",+ defaultId,+ compositions: entries.map(([id, c]) => ({+ id,+ entry: normalizeEntry(c.entry),+ export: c.export,+ title: c.title ?? humanize(id),+ description: c.description ?? null,+ group: c.group ?? null,+ default: id === defaultId,+ })),+ assets: {+ directory: data.assets?.directory ?? "assets",+ exclude: data.assets?.exclude ?? ["**/.DS_Store"],+ },+ output: data.output ?? "output",+ };+}++/** The project of a directory with no manifest: one composition, `film`. */+export function defaultProject(root: string): Project {+ const c = DEFAULT_COMPOSITION;+ return {+ root,+ source: "default",+ defaultId: c.id,+ compositions: [+ {+ ...c,+ title: humanize(c.id),+ description: null,+ group: null,+ default: true,+ },+ ],+ assets: { directory: "assets", exclude: ["**/.DS_Store"] },+ output: "output",+ };+}++/**+ * Finds the project root from `cwd` upwards and resolves its manifest. The+ * root is the nearest directory holding `framefields.json` or `package.json`;+ * a package without a manifest gets the default `film` composition.+ */+export async function loadProject(cwd = process.cwd()): Promise<Project> {+ const start = path.resolve(cwd);+ for (let dir = start; ; dir = path.dirname(dir)) {+ const manifest = path.join(dir, MANIFEST_FILE);+ if (fs.existsSync(manifest)) {+ const raw = await fs.promises.readFile(manifest, "utf8");+ let json: unknown;+ try {+ json = JSON.parse(raw);+ } catch (err) {+ throw new ProjectError(+ `${MANIFEST_FILE} is not valid JSON: ${(err as Error).message}`,+ "invalid",+ manifest,+ );+ }+ return resolveManifest(json, dir);+ }+ if (fs.existsSync(path.join(dir, "package.json")))+ return defaultProject(dir);+ if (path.dirname(dir) === dir) break;+ }+ throw new ProjectError(+ `no framefields project found in ${start} or any parent directory`,+ "not-found",+ undefined,+ "ff init",+ );+}++/** True when `ref` is a `file#export` or file reference rather than an id. */+export function isFileReference(ref: string): boolean {+ const file = ref.split("#")[0] ?? "";+ return ref.includes("#") || ENTRY_EXT.test(file) || file.includes("/");+}++/**+ * Resolves `<composition>` (an id, `file#export`, a bare file, or undefined+ * for the default) against a project.+ */+export function resolveComposition(+ project: Project,+ ref?: string,+): ResolvedComposition {+ if (ref === undefined || ref === "") {+ const found = project.compositions.find((c) => c.id === project.defaultId);+ if (found) return found;+ throw new ProjectError("the project has no default composition", "invalid");+ }+ if (isFileReference(ref)) return adHocComposition(project, ref);+ const found = project.compositions.find((c) => c.id === ref);+ if (found) return found;+ throw new ProjectError(+ `unknown composition '${ref}'`,+ "unknown-composition",+ undefined,+ `compositions${project.source === "manifest" ? ` in ${MANIFEST_FILE}` : ""}: ${listIds(project)} (ff ls)`,+ );+}++/** `a, b, c` or `a, b … h` for long lists. */+function listIds(project: Project): string {+ const ids = project.compositions.map((c) => c.id);+ return ids.length > 4+ ? `${ids.slice(0, 2).join(", ")} … ${ids[ids.length - 1]}`+ : ids.join(", ");+}++function adHocComposition(project: Project, ref: string): ResolvedComposition {+ const hash = ref.indexOf("#");+ const file = hash === -1 ? ref : ref.slice(0, hash);+ const exportName = hash === -1 ? "default" : ref.slice(hash + 1);+ const abs = path.resolve(project.root, file);+ const entry = normalizeEntry(path.relative(project.root, abs));+ if (entry.startsWith("..") || path.isAbsolute(entry)) {+ throw new ProjectError(+ `'${file}' is outside the project (${project.root})`,+ "unknown-composition",+ );+ }+ if (!ENTRY_EXT.test(entry)) {+ throw new ProjectError(+ `'${file}' is not a .ts, .tsx, .mts, .js or .mjs file`,+ "unknown-composition",+ );+ }+ if (!IDENTIFIER.test(exportName)) {+ throw new ProjectError(+ `'${exportName}' is not a JavaScript identifier`,+ "unknown-composition",+ );+ }+ const listed = project.compositions.find(+ (c) => c.entry === entry && c.export === exportName,+ );+ if (listed) return listed;+ const base = path+ .basename(entry)+ .replace(ENTRY_EXT, "")+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-");+ const suffix =+ exportName === "default"+ ? ""+ : `-${exportName+ .replace(/([a-z0-9])([A-Z])/g, "$1-$2")+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")}`;+ const id =+ `${base}${suffix}`.replace(/^-+|-+$/g, "").slice(0, 63) || "composition";+ return {+ id,+ entry,+ export: exportName,+ title: `${entry}#${exportName}`,+ description: null,+ group: null,+ default: false,+ };+}++function normalizeEntry(entry: string): string {+ return entry.split(path.sep).join("/").replace(/^\.\//, "");+}++/**+ * Imports the entry and calls the export: the one place that turns a+ * reference into a Composition. TypeScript entries need a loader (tsx, or a+ * Node that strips types); the `ff` CLI registers one.+ */+export async function buildComposition(+ project: Project,+ ref?: string,+): Promise<Composition> {+ const target = resolveComposition(project, ref);+ const file = path.join(project.root, target.entry);+ const where = `${target.entry}#${target.export}`;+ if (!fs.existsSync(file)) {+ throw new ProjectError(+ `${target.entry} does not exist (composition '${target.id}')`,+ "build",+ file,+ project.source === "default"+ ? `create it, or list your compositions in ${MANIFEST_FILE}`+ : undefined,+ );+ }+ let mod: Record<string, unknown>;+ try {+ mod = (await import(pathToFileURL(file).href)) as Record<string, unknown>;+ } catch (err) {+ throw new ProjectError(+ `could not import ${target.entry}: ${errorMessage(err)}`,+ "build",+ file,+ );+ }+ const exported = mod[target.export];+ if (exported === undefined) {+ const names = Object.keys(mod).filter((k) => typeof mod[k] === "function");+ throw new ProjectError(+ `${target.entry} has no export named '${target.export}'`,+ "build",+ file,+ names.length ? `function exports: ${names.join(", ")}` : undefined,+ );+ }+ let value: unknown;+ try {+ value =+ typeof exported === "function"+ ? await (exported as () => unknown)()+ : exported;+ } catch (err) {+ const error = new ProjectError(+ `${where} threw: ${errorMessage(err)}`,+ "build",+ file,+ );+ error.cause = err;+ throw error;+ }+ if (!isComposition(value)) {+ throw new ProjectError(+ `${where} did not return a Composition`,+ "build",+ file,+ );+ }+ return value as Composition;+}++function isComposition(value: unknown): boolean {+ return (+ typeof value === "object" &&+ value !== null &&+ typeof (value as { toSpec?: unknown }).toSpec === "function" &&+ typeof (value as { renderFrame?: unknown }).renderFrame === "function"+ );+}++function errorMessage(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}diff --git a/packages/framefields/src/project/project.test.ts b/packages/framefields/src/project/project.test.tsnew file mode 100644index 00000000..99d10da0--- /dev/null+++ b/packages/framefields/src/project/project.test.ts@@ -0,0 +1,307 @@+import fs from "node:fs";+import os from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import {+ buildComposition,+ humanize,+ loadProject,+ ProjectError,+ resolveComposition,+ resolveManifest,+} from "./index.js";++const dirs: string[] = [];+function tmp(files: Record<string, string>): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ff-project-"));+ dirs.push(dir);+ for (const [file, content] of Object.entries(files)) {+ fs.mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });+ fs.writeFileSync(path.join(dir, file), content);+ }+ return dir;+}+afterEach(() => {+ for (const d of dirs.splice(0))+ fs.rmSync(d, { recursive: true, force: true });+});++const manifest = (compositions: unknown, extra: object = {}) => ({+ version: 1,+ compositions,+ ...extra,+});++function invalid(json: unknown): string {+ try {+ resolveManifest(json, "/p");+ } catch (err) {+ expect(err).toBeInstanceOf(ProjectError);+ expect((err as ProjectError).kind).toBe("invalid");+ return (err as Error).message;+ }+ throw new Error("expected the manifest to be rejected");+}++describe("resolveManifest (§3.1 rules)", () => {+ it("resolves defaults: export, title, group, description, assets, output", () => {+ const p = resolveManifest(+ manifest({ "step-1": { entry: "src/a.ts" } }),+ "/p",+ );+ expect(p).toEqual({+ root: "/p",+ source: "manifest",+ defaultId: "step-1",+ compositions: [+ {+ id: "step-1",+ entry: "src/a.ts",+ export: "default",+ title: "Step 1",+ description: null,+ group: null,+ default: true,+ },+ ],+ assets: { directory: "assets", exclude: ["**/.DS_Store"] },+ output: "output",+ });+ });++ it("keeps insertion order and honours an explicit default", () => {+ const p = resolveManifest(+ manifest({+ b: { entry: "src/b.ts" },+ a: { entry: "src/a.ts", default: true, group: "Steps", title: "A!" },+ }),+ "/p",+ );+ expect(p.compositions.map((c) => c.id)).toEqual(["b", "a"]);+ expect(p.defaultId).toBe("a");+ expect(p.compositions.map((c) => c.default)).toEqual([false, true]);+ expect(p.compositions[1]).toMatchObject({ title: "A!", group: "Steps" });+ });++ it("version is optional and must be 1", () => {+ expect(() =>+ resolveManifest({ compositions: { a: { entry: "a.ts" } } }, "/p"),+ ).not.toThrow();+ expect(+ invalid({ version: 2, compositions: { a: { entry: "a.ts" } } }),+ ).toMatch(/version/);+ });++ it("requires at least one composition", () => {+ expect(invalid(manifest({}))).toMatch(/at least one/);+ expect(invalid({ version: 1 })).toMatch(/compositions/);+ });++ it("validates ids", () => {+ for (const id of ["Step1", "-a", "a_b", "a".repeat(64), ""]) {+ expect(invalid(manifest({ [id]: { entry: "a.ts" } }))).toMatch(+ /composition ids|compositions/,+ );+ }+ expect(() =>+ resolveManifest(manifest({ ["a".repeat(63)]: { entry: "a.ts" } }), "/p"),+ ).not.toThrow();+ });++ it("validates entries", () => {+ expect(invalid(manifest({ a: { entry: "../x.ts" } }))).toMatch(/inside/);+ expect(invalid(manifest({ a: { entry: "/abs/x.ts" } }))).toMatch(/inside/);+ expect(invalid(manifest({ a: { entry: "src/x.json" } }))).toMatch(/\.ts/);+ for (const ext of ["ts", "tsx", "mts", "js", "mjs"]) {+ expect(() =>+ resolveManifest(manifest({ a: { entry: `src/x.${ext}` } }), "/p"),+ ).not.toThrow();+ }+ });++ it("validates exports, lengths and the single default", () => {+ expect(+ invalid(manifest({ a: { entry: "a.ts", export: "not-ok" } })),+ ).toMatch(/identifier/);+ expect(+ invalid(manifest({ a: { entry: "a.ts", title: "x".repeat(121) } })),+ ).toMatch(/title/);+ expect(+ invalid(manifest({ a: { entry: "a.ts", description: "x".repeat(501) } })),+ ).toMatch(/description/);+ expect(+ invalid(manifest({ a: { entry: "a.ts", group: "x".repeat(61) } })),+ ).toMatch(/group/);+ expect(+ invalid(+ manifest({+ a: { entry: "a.ts", default: true },+ b: { entry: "b.ts", default: true },+ }),+ ),+ ).toMatch(/only one/);+ });++ it("preserves and ignores unknown keys", () => {+ const p = resolveManifest(+ manifest(+ { a: { entry: "a.ts", posterFrame: 12 } },+ { chapters: [], assets: { directory: "media", exclude: [], extra: 1 } },+ ),+ "/p",+ );+ expect(p.assets).toEqual({ directory: "media", exclude: [] });+ });+});++describe("loadProject", () => {+ it("reads framefields.json from the nearest parent", async () => {+ const root = tmp({+ "framefields.json": JSON.stringify(+ manifest({ show: { entry: "src/show.ts", export: "build" } }),+ ),+ "src/nested/x.txt": "",+ });+ const p = await loadProject(path.join(root, "src", "nested"));+ expect(p.root).toBe(root);+ expect(p.source).toBe("manifest");+ expect(p.defaultId).toBe("show");+ });++ it("falls back to the implicit film composition beside package.json", async () => {+ const root = tmp({ "package.json": "{}" });+ const p = await loadProject(root);+ expect(p.source).toBe("default");+ expect(p.compositions).toEqual([+ {+ id: "film",+ entry: "src/film.ts",+ export: "buildFilm",+ title: "Film",+ description: null,+ group: null,+ default: true,+ },+ ]);+ });++ it("reports invalid JSON with the file path", async () => {+ const root = tmp({ "framefields.json": "{ nope" });+ const err = await loadProject(root).catch((e: unknown) => e);+ expect(err).toBeInstanceOf(ProjectError);+ expect(err).toMatchObject({+ kind: "invalid",+ path: path.join(root, "framefields.json"),+ });+ });+});++describe("resolveComposition", () => {+ const project = resolveManifest(+ manifest({+ showcase: {+ entry: "src/audio.ts",+ export: "buildShowcase",+ default: true,+ },+ "step-1": { entry: "src/audio.ts", export: "buildStep1" },+ }),+ "/p",+ );++ it("resolves the default, ids and listed file refs", () => {+ expect(resolveComposition(project).id).toBe("showcase");+ expect(resolveComposition(project, "step-1").export).toBe("buildStep1");+ expect(resolveComposition(project, "src/audio.ts#buildStep1").id).toBe(+ "step-1",+ );+ });++ it("resolves ad-hoc file#export references", () => {+ expect(resolveComposition(project, "scratch/probe.ts#buildProbe")).toEqual({+ id: "probe-build-probe",+ entry: "scratch/probe.ts",+ export: "buildProbe",+ title: "scratch/probe.ts#buildProbe",+ description: null,+ group: null,+ default: false,+ });+ expect(resolveComposition(project, "./src/probe.ts")).toMatchObject({+ id: "probe",+ entry: "src/probe.ts",+ export: "default",+ });+ });++ it("rejects unknown ids with a hint listing the compositions", () => {+ try {+ resolveComposition(project, "step-9");+ expect.unreachable();+ } catch (err) {+ expect(err).toMatchObject({+ kind: "unknown-composition",+ message: "unknown composition 'step-9'",+ hint: "compositions in framefields.json: showcase, step-1 (ff ls)",+ });+ }+ });++ it("rejects refs outside the project or with bad exports", () => {+ expect(() => resolveComposition(project, "../x.ts")).toThrow(/outside/);+ expect(() => resolveComposition(project, "src/x.ts#not-ok")).toThrow(+ /identifier/,+ );+ expect(() => resolveComposition(project, "src/x.json#a")).toThrow(/\.ts/);+ });+});++describe("buildComposition", () => {+ const comp = `export function build() { return { toSpec() { return {}; }, renderFrame() {} }; }+export default async function () { return build(); }+export function notComp() { return 42; }+export function boom() { throw new Error("kaput"); }+`;++ it("imports the entry and calls the export", async () => {+ const root = tmp({+ "framefields.json": JSON.stringify(+ manifest({ a: { entry: "src/a.mjs", export: "build" } }),+ ),+ "src/a.mjs": comp,+ });+ const project = await loadProject(root);+ const built = await buildComposition(project);+ expect(typeof built.toSpec).toBe("function");+ expect(typeof (await buildComposition(project, "src/a.mjs")).toSpec).toBe(+ "function",+ );+ });++ it("explains missing files, missing exports, throws and non-compositions", async () => {+ const root = tmp({+ "framefields.json": JSON.stringify(+ manifest({ a: { entry: "src/a.mjs", export: "build" } }),+ ),+ "src/a.mjs": comp,+ });+ const project = await loadProject(root);+ await expect(buildComposition(project, "src/missing.mjs")).rejects.toThrow(+ /does not exist/,+ );+ await expect(buildComposition(project, "src/a.mjs#nope")).rejects.toThrow(+ /no export named 'nope'/,+ );+ await expect(buildComposition(project, "src/a.mjs#boom")).rejects.toThrow(+ /threw: kaput/,+ );+ await expect(+ buildComposition(project, "src/a.mjs#notComp"),+ ).rejects.toThrow(/did not return a Composition/);+ });+});++it("humanize", () => {+ expect(humanize("step-1")).toBe("Step 1");+ expect(humanize("film")).toBe("Film");+});diff --git a/packages/framefields/tsdown.config.ts b/packages/framefields/tsdown.config.tsindex 0e278c86..b4d69a88 100644--- a/packages/framefields/tsdown.config.ts+++ b/packages/framefields/tsdown.config.ts@@ -10,6 +10,7 @@ export default defineConfig({"src/renderer/index.ts","src/fonts/index.ts","src/preview/index.ts",+ "src/project/index.ts",],format: ["esm"],clean: true,diff --git a/plugins/framefields/skills/framefields-render/SKILL.md b/plugins/framefields/skills/framefields-render/SKILL.mdindex 0ad249f3..9580f57f 100644--- a/plugins/framefields/skills/framefields-render/SKILL.md+++ b/plugins/framefields/skills/framefields-render/SKILL.md@@ -19,6 +19,18 @@ Because video rendering is resource-intensive and native GPU pipelines run asyncAlways proceed through the ladder in order. Catching a layout or timing bug at step 1 or 2 takes seconds; catching it after a 30-second 4K video render wastes minutes.+**With the `ff` CLI.** When the project has `@framefields/cli` (`npx ff --version` succeeds), run the ladder with it instead of inline scripts. It reads the compositions from `framefields.json` (`npx ff ls`; without a manifest, `src/film.ts#buildFilm` is the `film` composition), prints the files it wrote relative to the project root, and with `--json` prints one JSON value on stdout:++| Step | Command |+|---|---|+| 1 | `npx ff check [<composition>…]`: `tsc --noEmit`, then builds each composition and validates `toSpec()` against `CompositorProgramSchema` |+| 2 | `npx ff frames [<composition>] 0 2.5s 00:00:04`: `output/frames/<id>/f0000.png` … |+| 3 | `npx ff grid [<composition>] --count 16`: `output/<id>-grid.png` |+| 4.5 | `npx ff preview [<composition>]`: prints the player URL |+| 5 | `npx ff render [<composition>] --local`: `output/<id>.mp4` |++`<composition>` is a manifest id, or `src/probe.ts#buildProbe` for an unlisted builder. Exit codes: 1 failed, 2 bad arguments or unknown composition, 4 project problem (no project, invalid manifest, framefields not installed). The sections below show the same steps in code.+### Step 1: Static Typecheck & Schema ValidationBefore touching the GPU, verify TypeScript types and parse the composition against the strict runtime schema:diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex bdac2fc5..adbab735 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -2066,6 +2066,40 @@ importers:specifier: ^0.4.0version: 0.4.0+ packages/cli:+ dependencies:+ '@clack/prompts':+ specifier: ^1.8.1+ version: 1.8.1+ commander:+ specifier: ^14.0.0+ version: 14.0.3+ tsx:+ specifier: ^4.20.3+ version: 4.21.0+ zod:+ specifier: ^4.3.6+ version: 4.3.6+ devDependencies:+ '@framefields/tsconfig':+ specifier: workspace:*+ version: link:../tsconfig+ '@types/node':+ specifier: ^24.1.0+ version: 24.10.14+ framefields:+ specifier: workspace:*+ version: link:../framefields+ tsdown:+ specifier: ^0.19.0+ version: 0.19.0([email protected])([email protected])+ typescript:+ specifier: ^5.8.3+ version: 5.9.3+ vitest:+ specifier: ^4.1.11+ version: 4.1.11(@opentelemetry/[email protected])(@types/[email protected])(@vitest/[email protected])([email protected](@noble/[email protected])([email protected]))([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))+packages/client-utils:dependencies:'@framefields/core':@@ -3219,6 +3253,14 @@ packages:'@changesets/[email protected]':resolution: {integrity: sha512-CdTLvIOPiCNuH71pyDu3rA+Q0n65cmAbXnwWH84rKGiFumFzkmHNT8KHTMEchcxN+Kl8I54xGUhJ7l3E7X396Q==}+ '@clack/[email protected]':+ resolution: {integrity: sha512-iHTrHA8MtVuLl2TfZySmcKv1qO2PoyC9Z7pfSDozEuV5vtY3/wcOPKJXlqJ5Oq2Cx5DDGQGAMVx6HZfRRoVEbQ==}+ engines: {node: '>= 20.12.0'}++ '@clack/[email protected]':+ resolution: {integrity: sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==}+ engines: {node: '>= 20.12.0'}+'@csstools/[email protected]':resolution: {integrity: sha512-LMGQLS9EuADloEFkcTBR3BwV/CGHV7zyDxVRtVDTwdI2Ca4it0CCVTT9wCkxSgokjE5Ho41hEPgb8OEUwoXr6Q==}engines: {node: '>=20.19.0'}@@ -5018,6 +5060,10 @@ packages:resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==}engines: {node: '>=0.8'}+ resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==}+ engines: {node: '>=20'}+resolution: {integrity: sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==}@@ -5222,6 +5268,15 @@ packages:resolution: {integrity: sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==}engines: {node: '>=8.6.0'}+ resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==}++ resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==}++ resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==}+resolution: {integrity: sha512-F74cZEdCvuw9P41GAC3rod4X04jjWGM1JPEv/GWSqFTWLsdyMSBMBMlm9Hk3GLBgLBbdBNY8yee0pQh2RBVESQ==}@@ -6037,6 +6092,9 @@ packages:resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==}+ resolution: {integrity: sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==}+resolution: {integrity: sha512-FSYKxp8Ng2vOeeOBiyPhnn6ui6FirPJXMyjk4PKl8N/OWzVrkMawUgY9zubIWHMdYtyWFn0gfX3QlRwg6HBmdg==}@@ -7200,6 +7258,18 @@ snapshots:human-id: 4.1.3prettier: 2.8.8+ '@clack/[email protected]':+ dependencies:+ fast-wrap-ansi: 0.2.2+ sisteransi: 1.0.5++ '@clack/[email protected]':+ dependencies:+ '@clack/core': 1.5.1+ fast-string-width: 3.0.2+ fast-wrap-ansi: 0.2.2+ sisteransi: 1.0.5+'@csstools/[email protected]': {}'@csstools/[email protected](@csstools/[email protected](@csstools/[email protected]))(@csstools/[email protected])':@@ -8738,6 +8808,8 @@ snapshots:+ [email protected]: {}+optional: true@@ -8938,6 +9010,16 @@ snapshots:merge2: 1.4.1micromatch: 4.0.8+ [email protected]: {}++ dependencies:+ fast-string-truncated-width: 3.0.3++ dependencies:+ fast-string-width: 3.0.2+dependencies:path-expression-matcher: 1.6.2@@ -9881,6 +9963,8 @@ snapshots:simple-concat: 1.0.1optional: true+ [email protected]: {}+dependencies:detect-libc: 2.1.2