mirror of
https://github.com/heygen-com/hyperframes.git
synced 2026-09-10 22:20:14 +00:00
feat(cli): registry resolver + installer (#254)
## What PR 3/17 of the catalog system rollout. Introduces the registry resolver/installer abstraction. No UX change — `init --template` still works identically. Stacks on #253. **New module: `packages/cli/src/registry/`** - `remote.ts` — fetches manifests (`registry.json`, `registry-item.json`) and item files from a GitHub-hosted registry. 24h cache on manifests; item files stream straight to `destDir` - `resolver.ts` — `listRegistryItems`, `loadAllItems` (parallel fetch for picker UX), `resolveItem` (single-item fetch with `Available:` error) - `installer.ts` — `assertSafeTarget` (runtime path-traversal guard) + `installItem` (parallel file download with up-front validation; all-or-nothing semantics) - `index.ts` — barrel **Registry content:** - `registry/registry.json` — top-level manifest in PR 1's `RegistryManifest` shape. 8 examples - `registry/examples/<id>/registry-item.json` — per-item manifest for each existing example, generated from legacy `templates.json` + HTML data-attribute probing - `registry/examples/templates.json` — **deleted**, replaced by the above **Compat layer:** - `packages/cli/src/templates/{remote,generators}.ts` — thin shims that delegate to `../registry/`, keeping `init.ts`'s existing imports stable. `init.ts` doesn't move to the new API until PR 5 where it's part of a larger UX pass **Tooling:** - `scripts/generate-registry-items.ts` — idempotent one-off generator for this PR, kept in-repo for future example additions (`--only <name>` flag) Design doc: [Hyperframes Catalog System](https://www.notion.so/heygen/Hyperframes-Catalog-System-Design-Plan-341449792c69813f899dcd53b4c0383a). Tracker entry in local `hyperframes-catalog-plan.md`. ## Why Every future PR (`hyperframes add`, seed blocks, seed components, custom registries) otherwise has to keep piling onto the ad-hoc fetch + `cpSync` pattern in the old `fetchRemoteTemplate`. The new module is the single place that understands the registry wire format and file layout. **This is also where PR 1's schema comes alive.** ## How ### Scope-trimmed from the plan - **No transitive dependency resolution yet.** Examples have no deps today. `resolveItem` doesn't walk `registryDependencies`; PR 5 adds that when blocks/components need it. - **No ajv schema validation yet.** TS types + runtime path-traversal guard are the only safety nets. Full JSON-Schema validation lands when the registry starts accepting third-party content (PR 14 / custom registries). - **init.ts refactor deferred to PR 5.** Compat shims keep this PR small and reviewable. PR 5 rewrites init alongside adding the `add` command. ### Safety - `assertSafeTarget` rejects absolute paths, `..` segments, Windows drive letters, and any target that `path.resolve` shows to escape `destDir`. Mirrors the PR 1 schema `pattern`/`not.anyOf` on `target`, but runs at install-time so a registry that bypasses schema validation still can't write outside the project - Up-front validation in `installItem` means a malformed item fails **before** any file is written. Atomic-ish semantics: all files land or none do ### Caching - 24h manifest cache lives at `~/.hyperframes/cache/` per existing convention, but now keyed by `<baseUrl>__<kind>__<name>.json` so PR 14 custom registries can coexist ## Test plan - [x] `bun run test` in `packages/cli`: **70 passed** (was 57 on #253, +13). Same 4 pre-existing failures (SRT/VTT whisper normalizer + `lintProject` clean-project test) — identical to main. No regressions - [x] **Resolver unit tests (8):** filter by type, parallel load with fail-safe, resolve-by-name with `Available:` error message, unreachable-registry handling - [x] **Installer unit tests (5):** accepts simple relative paths, rejects `..` segments, rejects Unix absolute paths, rejects Windows drive letters, permits `.` and dotfile-like names - [x] **Smoke test**: `hyperframes init /tmp/x --template blank` (bundled code path, unchanged) works end-to-end - [x] `bunx oxfmt --check` + `bunx oxlint`: clean - [x] Pre-commit typecheck (core + studio): clean. CLI typecheck has 2 pre-existing errors (`render.ts`, `studioServer.ts` — unrelated `"mov"` format issue on main) - [ ] **Smoke test remote fetch (`--template warm-grain`)** — verifiable only post-merge; registry paths live on `main` after this PR lands ## Breaking / migration **No end-user-visible UX change.** `init --template <name>` still works the same way. Internally, `templates.json` is gone and the CLI now reads `registry.json` + `registry-item.json` per example. Installed CLIs on old versions (`hyperframes@0.1.0`–`0.3.0`) already broke at PR 2 merge (see #253 rollout note). The next CLI release after this lands (`0.3.1`+) is the full fix. ## Commits 1. `generate-registry-items.ts` + generated manifests + deleted `templates.json` 2. Resolver + installer + compat shims 3. Unit tests (All squashed into one commit on this branch; see `git log feat/registry-resolver ^refactor/registry-examples-dir`.) ## Stacks on #253 — base branch. When #253 merges, this rebases onto `main`. ## Next in stack PR 4 — `feat(cli)!: rename --template to --example`. Single clean cut, no alias. Tiny PR (~150 lines) that mostly updates `init.ts`'s argument schema, help text, and docs. Depends on this PR so the new flag name can be applied against the refactored code path. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
This commit is contained in:
@@ -0,0 +1,133 @@
|
||||
/**
|
||||
* Remote Registry Fetching
|
||||
*
|
||||
* Fetches registry manifests and item files from a Hyperframes registry hosted
|
||||
* on GitHub (or any HTTPS endpoint serving the same file layout).
|
||||
*
|
||||
* Base URL layout:
|
||||
* <base>/registry.json → top-level manifest
|
||||
* <base>/<type-dir>/<name>/registry-item.json
|
||||
* <base>/<type-dir>/<name>/<file.path> → individual files referenced by the item
|
||||
*
|
||||
* `<type-dir>` comes from ITEM_TYPE_DIRS in @hyperframes/core.
|
||||
*/
|
||||
|
||||
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
||||
import { join, dirname } from "node:path";
|
||||
import { homedir } from "node:os";
|
||||
import {
|
||||
ITEM_TYPE_DIRS,
|
||||
type FileTarget,
|
||||
type ItemType,
|
||||
type RegistryItem,
|
||||
type RegistryManifest,
|
||||
} from "@hyperframes/core";
|
||||
|
||||
export const DEFAULT_REGISTRY_URL =
|
||||
"https://raw.githubusercontent.com/heygen-com/hyperframes/main/registry";
|
||||
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
|
||||
// ── Caching ─────────────────────────────────────────────────────────────────
|
||||
// 24h TTL on manifest fetches so the interactive picker stays snappy offline.
|
||||
// Item files aren't cached — they're written straight to destDir on install.
|
||||
|
||||
const CACHE_DIR = join(homedir(), ".hyperframes", "cache");
|
||||
const CACHE_TTL_MS = 24 * 60 * 60 * 1000;
|
||||
|
||||
interface CacheEntry<T> {
|
||||
fetchedAt: number;
|
||||
data: T;
|
||||
}
|
||||
|
||||
function cachePath(baseUrl: string, key: string): string {
|
||||
const slug = baseUrl.replace(/[^a-zA-Z0-9]/g, "_");
|
||||
return join(CACHE_DIR, `${slug}__${key}.json`);
|
||||
}
|
||||
|
||||
function readCache<T>(path: string): T | undefined {
|
||||
try {
|
||||
const entry = JSON.parse(readFileSync(path, "utf-8")) as CacheEntry<T>;
|
||||
if (Date.now() - entry.fetchedAt > CACHE_TTL_MS) return undefined;
|
||||
return entry.data;
|
||||
} catch {
|
||||
// Missing file or corrupt JSON → cache miss.
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache<T>(path: string, data: T): void {
|
||||
mkdirSync(dirname(path), { recursive: true });
|
||||
const entry: CacheEntry<T> = { fetchedAt: Date.now(), data };
|
||||
writeFileSync(path, JSON.stringify(entry), "utf-8");
|
||||
}
|
||||
|
||||
// ── Fetchers ────────────────────────────────────────────────────────────────
|
||||
|
||||
async function fetchJson<T>(url: string): Promise<T> {
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!res.ok) {
|
||||
throw new Error(`Registry fetch failed: ${url} — HTTP ${res.status}`);
|
||||
}
|
||||
return (await res.json()) as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the top-level registry.json manifest. Cached for 24h.
|
||||
* Returns undefined if the registry is unreachable (offline / 404).
|
||||
*/
|
||||
export async function fetchRegistryManifest(
|
||||
baseUrl: string = DEFAULT_REGISTRY_URL,
|
||||
): Promise<RegistryManifest | undefined> {
|
||||
const cacheFile = cachePath(baseUrl, "registry");
|
||||
const cached = readCache<RegistryManifest>(cacheFile);
|
||||
if (cached) return cached;
|
||||
|
||||
try {
|
||||
const manifest = await fetchJson<RegistryManifest>(`${baseUrl}/registry.json`);
|
||||
writeCache(cacheFile, manifest);
|
||||
return manifest;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single item's `registry-item.json` manifest. Cached for 24h.
|
||||
* Throws on network failure (callers decide whether to degrade gracefully).
|
||||
*/
|
||||
export async function fetchItemManifest(
|
||||
name: string,
|
||||
type: ItemType,
|
||||
baseUrl: string = DEFAULT_REGISTRY_URL,
|
||||
): Promise<RegistryItem> {
|
||||
const dir = ITEM_TYPE_DIRS[type];
|
||||
const cacheFile = cachePath(baseUrl, `${dir}__${name}`);
|
||||
const cached = readCache<RegistryItem>(cacheFile);
|
||||
if (cached) return cached;
|
||||
|
||||
const url = `${baseUrl}/${dir}/${name}/registry-item.json`;
|
||||
const item = await fetchJson<RegistryItem>(url);
|
||||
writeCache(cacheFile, item);
|
||||
return item;
|
||||
}
|
||||
|
||||
/**
|
||||
* Download a single file referenced by an item to a local destination.
|
||||
* Caller is responsible for target-path validation (see installer.ts).
|
||||
*/
|
||||
export async function fetchItemFile(
|
||||
item: RegistryItem,
|
||||
file: FileTarget,
|
||||
destPath: string,
|
||||
baseUrl: string = DEFAULT_REGISTRY_URL,
|
||||
): Promise<void> {
|
||||
const url = `${baseUrl}/${ITEM_TYPE_DIRS[item.type]}/${item.name}/${file.path}`;
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!res.ok) {
|
||||
throw new Error(`File fetch failed: ${url} — HTTP ${res.status}`);
|
||||
}
|
||||
const buf = new Uint8Array(await res.arrayBuffer());
|
||||
mkdirSync(dirname(destPath), { recursive: true });
|
||||
writeFileSync(destPath, buf);
|
||||
}
|
||||
Reference in New Issue
Block a user