Files
pbakaus_impeccable/skill/scripts/live/frameworks/index.mjs
T
Paul BakausandClaude Code 17dabf4b7e Live v2: root manifest, mount-ack protocol, AST scaffolder, mechanical accept
A ground-up hardening of live mode, driven by a production session in a
nested-app monorepo that hit six distinct failure classes. Full design
rationale in docs/LIVE-REWRITE-PLAN.md; every Codex-reported failure now
has a mechanical fix and a regression test.

Roots: live/roots.mjs resolves appRoot/repoRoot/contextRoot once at boot
(keyed on dev-server configs, not monorepo brand markers), persists a
manifest, and every live CLI re-anchors onto it at startup, so a helper
run from the wrong directory can no longer fork session state. Context
files are discovered upward to the git root.

Render truth: variant_mounted / variant_mount_failed events give the
journal per-variant mount state; failures reach the agent's poll queue,
raise a persistent error card with Retry (no more localStorage wipe), and
an attach probe names root/dev-server mismatches explicitly. The browser
rehydrates from the server when localStorage is gone.

Svelte: the scaffolder now parses with the app's own svelte 5 compiler.
Control flow survives (an each collection crosses the contract as one
structured prop), keyed each blocks hydrate synthetic keys, and anything
a detached preview cannot support falls back to source-preview instead of
shipping a wrong scaffold. Preview modules live in per-publish revision
directories, defeating stale transform caches.

Accept: CSS is reconciled, not appended. Matching selectors are replaced,
params bake from params.json kinds, the compiler's unused-selector pass
prunes superseded rules (pre-existing dead rules protected), a selector-
loss postcondition refuses any write that would drop hand-written rules,
and live-complete refuses to finish while live plumbing remains in source.

Also: framework registry (live/frameworks/) with a crash-safe injection
journal, session-store snapshot caching with read-only reads, protocol
enum consolidation, steer Send button, honest DESIGN-panel empty states.

Testing: new unit suites (roots, AST scaffolder, accept CSS, accept
pipeline, framework conformance); e2e now fails on preview-tree 404s,
proves computed-style mount for every variant, drives the Tune panel
through baked params, and injects failures (broken mounts, republish,
storage loss). New runtime fixtures: monorepo-nested-vite (repo root !=
app root) and vite8-sveltekit-stateful (each blocks + state). Nightly
full-matrix cron. An independent adversarial review pass preceded this
commit; its blocker and major findings are fixed and regression-tested.

This work was produced with AI assistance (Claude Code).

Co-Authored-By: Claude Code <noreply@anthropic.com>
2026-07-27 15:09:40 -07:00

144 lines
5.7 KiB
JavaScript

/**
* The live-mode framework registry.
*
* Before this existed, framework knowledge was smeared across live-inject.mjs
* (detection order, the Nuxt adapter, the Astro `is:inline` branch), the two
* adapter modules, and live-wrap.mjs (which extension gets component preview,
* which gets Astro's global-prefixed CSS, which gets JSX comments). Adding or
* fixing a framework meant reading all of them.
*
* One entry per framework now declares everything the live scripts need:
*
* name stable identifier; also the `adapter` value in inject JSON.
* detect (cwd, config) → falsy when this is not the project, otherwise
* a truthy project descriptor that apply/remove/artifacts read.
* Order in FRAMEWORKS is priority order; first truthy wins.
* inject { kind: 'adapter', apply, remove, ignorePatterns, artifacts,
* unpatch } for frameworks that server-render their document
* shell, or { kind: 'tag' } for the generic marker-wrapped
* <script src> block.
* source how live-wrap treats files this framework authors:
* extensions, preview ('source' | 'component'), styleMode,
* styleTag, commentSyntax, injectScriptAttrs. Anything omitted
* falls back to SOURCE_TRAIT_DEFAULTS.
*
* Two rules hold the thing together:
*
* 1. **Detection order is injection priority.** SvelteKit → Nuxt → TanStack
* Start → Astro → Next → Vite → static HTML, exactly the order
* live-inject.mjs used to hard-code. static-html always matches, so
* resolveFramework never returns null.
* 2. **Source traits resolve by file extension, not by project.** A SvelteKit
* project's injection target is `src/app.html`; a Vite app can contain
* `.astro` partials. live-wrap has always keyed these off the target file,
* and resolveSourceTraits keeps it that way. Several entries may claim the
* same extension (`.tsx` belongs to three); when they do, the values must
* agree, which tests/live-frameworks.test.mjs asserts.
*/
import path from 'node:path';
import { sveltekit } from './sveltekit.mjs';
import { nuxt } from './nuxt.mjs';
import { tanstackStart } from './tanstack-start.mjs';
import { astro } from './astro.mjs';
import { nextjs } from './nextjs.mjs';
import { viteGeneric } from './vite-generic.mjs';
import { staticHtml } from './static-html.mjs';
import { TAG_PATCH_MARKERS, unpatchTagFile } from './tag-strategy.mjs';
/** Priority order. Do not reorder without re-reading rule 1 above. */
export const FRAMEWORKS = Object.freeze([
sveltekit,
nuxt,
tanstackStart,
astro,
nextjs,
viteGeneric,
staticHtml,
]);
export const PREVIEW_MODES = Object.freeze(['source', 'component']);
export const STYLE_MODES = Object.freeze(['scoped', 'astro-global-prefixed']);
export const COMMENT_SYNTAXES = Object.freeze(['html', 'jsx']);
export const INJECT_KINDS = Object.freeze(['adapter', 'tag']);
export const SOURCE_TRAIT_DEFAULTS = Object.freeze({
preview: 'source',
styleMode: 'scoped',
styleTag: '<style data-impeccable-css="SESSION_ID">',
commentSyntax: 'html',
injectScriptAttrs: '',
});
/** The patch kind the generic tag strategy records in the journal. */
export const TAG_PATCH_KIND = 'live-tag';
/**
* Undo functions keyed by the `patch` value an artifact carries. Built from
* the entries so a new adapter registers its own undo alongside its apply.
*/
export const PATCH_UNDOERS = Object.freeze(Object.assign(
{ [TAG_PATCH_KIND]: unpatchTagFile },
...FRAMEWORKS.map((framework) => framework.inject.unpatch || {}),
));
/**
* First entry whose detect() matches. Returns { framework, project } where
* project is the detector's descriptor (adapters read it; tag frameworks
* mostly ignore it).
*/
export function resolveFramework(cwd = process.cwd(), config = null) {
for (const framework of FRAMEWORKS) {
const project = framework.detect(cwd, config);
if (project) return { framework, project };
}
// Unreachable while static-html stays terminal, but a caller that reorders
// the array should get a diagnosable null rather than a silent tag inject.
return null;
}
/**
* Source-authoring traits for one file, merged over SOURCE_TRAIT_DEFAULTS.
* `framework` names the entry that claimed the extension, or null.
*/
export function resolveSourceTraits(filePath) {
const ext = path.extname(String(filePath || '')).toLowerCase();
for (const framework of FRAMEWORKS) {
const source = framework.source;
if (!source || !source.extensions.includes(ext)) continue;
const { extensions, ...traits } = source;
return { framework: framework.name, ...SOURCE_TRAIT_DEFAULTS, ...traits };
}
return { framework: null, ...SOURCE_TRAIT_DEFAULTS };
}
/**
* Extra gitignore patterns the resolved framework needs beyond the static
* LIVE_IGNORE_PATTERNS list (paths that depend on a detected srcDir or file
* extension and so cannot be written down ahead of time).
*/
export function frameworkIgnorePatterns(resolved) {
const fn = resolved?.framework?.inject?.ignorePatterns;
return typeof fn === 'function' ? (fn(resolved.project) || []) : [];
}
/**
* The files this injection will create or patch, in journal-artifact form.
* Adapters declare their own; the tag strategy patches exactly the resolved
* config files.
*/
export function describeInjectArtifacts(resolved, { cwd = process.cwd(), files = [] } = {}) {
if (!resolved) return [];
const { framework, project } = resolved;
if (framework.inject.kind === 'adapter') {
return (framework.inject.artifacts?.({ cwd, project }) || []).filter((a) => a && a.path);
}
return files.map((file) => ({
kind: 'patched',
path: file,
patch: TAG_PATCH_KIND,
markers: [...TAG_PATCH_MARKERS],
}));
}