@templatical/template-tools 0.38.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +109 -0
- package/README.md +48 -0
- package/dist/bin.d.ts +5 -0
- package/dist/bin.js +698 -0
- package/dist/bin.js.map +1 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.js +2 -0
- package/dist/live/index.d.ts +87 -0
- package/dist/live/index.js +279 -0
- package/dist/live/index.js.map +1 -0
- package/dist/src-unNYVMlC.js +1278 -0
- package/dist/src-unNYVMlC.js.map +1 -0
- package/live/index.html +978 -0
- package/package.json +107 -0
- package/schema.json +1504 -0
package/dist/bin.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bin.js","names":["FORMATS","content"],"sources":["../src/cli/args.ts","../src/cli/output.ts","../src/cli/io.ts","../src/cli/commands/schema.ts","../src/cli/commands/validate.ts","../src/cli/resolve-optional.ts","../src/cli/commands/render.ts","../src/cli/commands/edit.ts","../src/cli/commands/import.ts","../src/cli/commands/live.ts","../src/bin.ts"],"sourcesContent":["// Argv parsing for the CLI. Deliberately hand-rolled: the package has no\n// runtime dependency for this, and the surface is a dozen flags.\n\n/** Flags that consume the next argv entry as their value. */\nconst VALUE_FLAGS = new Set([\n \"format\",\n \"out\",\n \"o\",\n \"op\",\n \"ops\",\n \"file\",\n \"port\",\n \"cwd\",\n]);\n\nexport interface ParsedArgs {\n command?: string;\n /** Everything that is not the command and not a flag — including subcommands. */\n positional: string[];\n json: boolean;\n flags: Record<string, string | true>;\n}\n\nexport function parseArgs(argv: string[]): ParsedArgs {\n const positional: string[] = [];\n const flags: Record<string, string | true> = {};\n let json = false;\n\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n if (!arg.startsWith(\"-\")) {\n positional.push(arg);\n continue;\n }\n\n const bare = arg.replace(/^--?/, \"\");\n const eq = bare.indexOf(\"=\");\n if (eq !== -1) {\n flags[bare.slice(0, eq)] = bare.slice(eq + 1);\n continue;\n }\n if (bare === \"json\") {\n json = true;\n continue;\n }\n // A value flag at the end of argv has no value; record it as present so the\n // command reports a useful usage error rather than reading `undefined`.\n flags[bare] =\n VALUE_FLAGS.has(bare) && i + 1 < argv.length ? argv[++i] : true;\n }\n\n return { command: positional.shift(), positional, json, flags };\n}\n\n/** Read a value flag as a string, or undefined when absent or valueless. */\nexport function flagValue(\n args: ParsedArgs,\n ...names: string[]\n): string | undefined {\n for (const name of names) {\n const v = args.flags[name];\n if (typeof v === \"string\") return v;\n }\n return undefined;\n}\n","// The ONLY module in this package that writes to stdout.\n//\n// `--json` promises callers exactly one parseable document on stdout, and a\n// future stdio-based caller — an MCP server reserving stdout for JSON-RPC —\n// would need that to hold just as strictly. Either way a second writer\n// breaks the contract. tests/cli-output-discipline.test.ts asserts no other\n// source file touches stdout.\n\nlet jsonMode = false;\n\nexport function setJsonMode(on: boolean): void {\n jsonMode = on;\n}\n\nexport function isJsonMode(): boolean {\n return jsonMode;\n}\n\n/**\n * Emit a command's result. Under `--json` the payload is serialized; otherwise\n * `human()` is called for the readable form — as a thunk, so building the\n * pretty output costs nothing in JSON mode.\n */\nexport function emit(payload: unknown, human: () => string): void {\n process.stdout.write(\n jsonMode ? `${JSON.stringify(payload)}\\n` : `${human()}\\n`,\n );\n}\n\n/** Diagnostics, progress and errors. Always stderr, in both modes. */\nexport function note(message: string): void {\n process.stderr.write(`${message}\\n`);\n}\n","// Shared file IO and the error→exit-code contract.\n\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, resolve } from \"node:path\";\n\nexport const EXIT = {\n ok: 0,\n /** Structural errors, or quality issues of severity \"error\". */\n invalid: 1,\n /** Bad flags, missing arguments, unreadable input. */\n usage: 2,\n /** An optional dependency is not installed; the message names the install. */\n missingDep: 3,\n} as const;\n\nexport class UsageError extends Error {}\n\nexport class InvalidTemplateError extends Error {\n constructor(\n message: string,\n readonly errors: string[] = [],\n ) {\n super(message);\n }\n}\n\nexport class MissingDependencyError extends Error {\n constructor(\n readonly pkg: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport function resolveFrom(file: string, cwd = process.cwd()): string {\n return isAbsolute(file) ? file : resolve(cwd, file);\n}\n\nexport function readTemplateFile(file: string, cwd = process.cwd()): unknown {\n const path = resolveFrom(file, cwd);\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch {\n throw new UsageError(`Could not read ${file}`);\n }\n try {\n return JSON.parse(raw);\n } catch (err) {\n throw new UsageError(\n `${file} is not valid JSON: ${(err as Error).message}`,\n );\n }\n}\n\n/** Write a template, creating the parent directory. Returns the path written. */\nexport function writeTemplateFile(\n file: string,\n content: unknown,\n cwd = process.cwd(),\n): string {\n const path = resolveFrom(file, cwd);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, `${JSON.stringify(content, null, 2)}\\n`, \"utf8\");\n return path;\n}\n","import { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport { EXIT, writeTemplateFile } from \"../io\";\nimport { schema } from \"../../index\";\n\nexport function runSchema(args: ParsedArgs): number {\n const out = flagValue(args, \"out\", \"o\");\n if (out) {\n // writeTemplateFile JSON-stringifies with the same shape this command\n // wrote by hand, and creates the parent directory as a side effect.\n const path = writeTemplateFile(out, schema);\n // stdout stays empty: the caller asked for a file, and under --json a path\n // string would not be the document they are parsing for.\n note(`Wrote ${path}`);\n return EXIT.ok;\n }\n emit(schema, () => JSON.stringify(schema, null, 2));\n return EXIT.ok;\n}\n","import { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport { EXIT, readTemplateFile, UsageError } from \"../io\";\nimport { runQualityLint, validateTemplate } from \"../../index\";\n\nexport function runValidate(args: ParsedArgs): number {\n const file = args.positional[0];\n if (!file) throw new UsageError(\"validate needs a template file.\");\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n\n const data = readTemplateFile(file, cwd);\n const { valid, errors } = validateTemplate(data);\n\n if (!valid) {\n emit({ valid: false, errors, issues: [] }, () =>\n [\n `✗ Structural validation failed (${errors.length}):`,\n ...errors.map((e) => ` - ${e}`),\n ].join(\"\\n\"),\n );\n return EXIT.invalid;\n }\n\n // The linter assumes a structurally-valid template, so it runs only here.\n const quality = runQualityLint(data);\n if (quality.error) {\n note(`Quality lint could not run: ${quality.error}`);\n }\n\n const issues = quality.issues;\n const blocking = issues.filter((i) => i.severity === \"error\");\n\n emit({ valid: true, errors: [], issues }, () => {\n if (issues.length === 0) return \"✓ Valid — no quality issues\";\n const lines = issues.map(\n (i) => ` - [${i.severity}] ${i.ruleId}: ${i.message}`,\n );\n return [\n `✓ Structurally valid · ${issues.length} quality issue(s):`,\n ...lines,\n ].join(\"\\n\");\n });\n\n // A severity-\"error\" issue is a real defect, not advice, so it fails the\n // command — matching the script this replaces. Warnings and info do not.\n return blocking.length > 0 ? EXIT.invalid : EXIT.ok;\n}\n","//\n// Optional dependencies must resolve from the CONSUMER'S cwd, not from this\n// module's location. When the CLI runs via npx it lives in npm's cache, so a\n// package the user installs in their own project is invisible to the CLI's own\n// resolution — and the remediation message (\"npm install mjml\") would be\n// impossible to satisfy. Anchoring the walk at the cwd fixes that; the CLI's\n// own directory is tried second, as a fallback — not for ajv (a hard\n// `dependencies` entry, imported statically in src/validate.ts, so it never\n// passes through this function at all), but for a global install (`npm\n// install -g mjml` places the optional peer as a sibling of this package\n// under one shared global node_modules that only this anchor can reach) and\n// for this package's own tests, which anchor at a throwaway cwd outside the\n// repo and rely on this anchor climbing from inside the repo tree up to the\n// root node_modules holding the @templatical/import-* converters as root\n// devDependencies.\n//\n// Resolution deliberately does NOT go through require.resolve()/createRequire.\n// That API performs Node's CJS-invoked exports resolution, which checks the\n// condition list [\"require\", \"node\", \"default\"] and never \"import\" — so it\n// throws ERR_PACKAGE_PATH_NOT_EXPORTED for any package whose exports map\n// declares only \"import\", which is every first-party package in this monorepo\n// (CLAUDE.md's ESM-only rule: `exports` exposes only the \"import\" condition,\n// never \"require\" or \"main\"). That map also omits \"./package.json\", so\n// require.resolve can't even read the manifest to look further. The result\n// under the old createRequire-based resolution: every @templatical/import-*\n// converter reported as \"not installed\" even when built and present on disk.\n// The ESM-native alternative, import.meta.resolve(specifier, parentURL),\n// would honor the right condition set and resolve this cwd-anchored — but its\n// second (parentURL) parameter, the one needed to anchor anywhere other than\n// this module's own URL, is documented as requiring the\n// --experimental-import-meta-resolve flag, and a published CLI that must run\n// un-flagged on Node 20 and 22 cannot bet a core resolution path on that.\n//\n// The fix walks node_modules directories by hand (findPackageDir) — a plain\n// filesystem read bypasses the exports map entirely — then reads the found\n// package's own package.json and picks its entry file directly\n// (entryFileFor), honoring exports[\".\"].import, a string exports[\".\"],\n// exports[\".\"].default, a root-string exports field, \"module\", then \"main\",\n// in that order.\n//\n// Returning null instead of throwing lets callers distinguish \"not installed\"\n// (exit 3, name the install command) from \"installed but broken\" (a real error\n// worth surfacing). Same discipline as tryLoadRenderer() in\n// packages/editor/src/utils/toMjml.ts: findPackageDir returning null is the\n// only thing that continues to the next anchor — a found package's own entry\n// resolution or import() is never caught, so a genuinely broken install\n// propagates as a real error rather than a misleading install hint.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath, pathToFileURL } from \"node:url\";\n\ninterface ExportsConditions {\n import?: string;\n default?: string;\n}\n\ninterface PackageManifest {\n exports?: string | Record<string, string | ExportsConditions>;\n module?: string;\n main?: string;\n}\n\n/**\n * Walk up from `dir` through every ancestor's node_modules looking for\n * <specifier>/package.json — the same directory-walk Node's own resolver uses\n * to locate a package, without then asking Node to apply exports-map\n * resolution. `dir` is normalized to an absolute path via `resolve()` before\n * the walk starts, so a relative anchor (e.g. \".\") climbs real ancestors —\n * unnormalized, `dirname(\".\")` is \".\" forever and the walk would give up\n * after the first miss.\n */\nfunction findPackageDir(specifier: string, dir: string): string | null {\n let current = resolve(dir);\n for (;;) {\n const candidate = join(current, \"node_modules\", specifier);\n if (existsSync(join(candidate, \"package.json\"))) return candidate;\n const parent = dirname(current);\n if (parent === current) return null;\n current = parent;\n }\n}\n\n/**\n * Pick a found package's entry file straight from its own manifest, honoring\n * exports[\".\"].import, a string exports[\".\"], exports[\".\"].default, a\n * root-string exports field, \"module\", then \"main\" — the fields an ESM\n * consumer needs, read without Node's exports-map gating.\n */\nfunction entryFileFor(pkgDir: string): string {\n const manifest = JSON.parse(\n readFileSync(join(pkgDir, \"package.json\"), \"utf8\"),\n ) as PackageManifest;\n\n const dot =\n manifest.exports && typeof manifest.exports === \"object\"\n ? manifest.exports[\".\"]\n : undefined;\n const conditions = dot && typeof dot === \"object\" ? dot : undefined;\n // \"exports\": \"./dist/index.js\" — no \".\" key at all. PackageManifest already\n // types this shape; the code just never read it.\n const rootExports =\n typeof manifest.exports === \"string\" ? manifest.exports : undefined;\n\n const entry =\n conditions?.import ??\n (typeof dot === \"string\" ? dot : undefined) ??\n conditions?.default ??\n rootExports ??\n manifest.module ??\n manifest.main;\n\n // typeof, not just truthiness: the tsup/tsdown types-first shape nests\n // exports[\".\"].import as a further conditions object ({ types, default }),\n // not a string. Without this check that object flows into join() below and\n // throws a raw `TypeError: The \"path\" argument must be of type string`\n // instead of this function's own, actionable error.\n if (!entry || typeof entry !== \"string\") {\n throw new Error(\n `${pkgDir} has no resolvable entry point (exports/module/main).`,\n );\n }\n return join(pkgDir, entry);\n}\n\nexport async function resolveOptional<T>(\n specifier: string,\n cwd: string = process.cwd(),\n): Promise<T | null> {\n const anchors = [cwd, dirname(fileURLToPath(import.meta.url))];\n\n for (const anchor of anchors) {\n const pkgDir = findPackageDir(specifier, anchor);\n if (!pkgDir) continue; // not found from this anchor — try the next\n // Deliberately outside the try below: a manifest that names no usable\n // entry is a packaging fault the caller can act on, and it keeps throwing.\n const resolved = entryFileFor(pkgDir);\n try {\n return (await import(pathToFileURL(resolved).href)) as T;\n } catch {\n // The manifest is fine but the file it names isn't there — a workspace\n // package whose dist/ hasn't been built is the everyday case. \"Optional\"\n // has to cover this, or `import --list-formats`, whose whole job is to\n // report which converters resolve, crashes on the first one that doesn't.\n // Keep looking: a later anchor may hold a complete copy.\n continue;\n }\n }\n return null;\n}\n","import { mkdirSync, writeFileSync } from \"node:fs\";\nimport { dirname } from \"node:path\";\nimport { renderToMjml } from \"@templatical/renderer\";\nimport type { TemplateContent } from \"@templatical/types\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport {\n EXIT,\n InvalidTemplateError,\n MissingDependencyError,\n readTemplateFile,\n resolveFrom,\n UsageError,\n} from \"../io\";\nimport { resolveOptional } from \"../resolve-optional\";\nimport { validateTemplate } from \"../../index\";\n\n// The mjml npm package's own top-level function (lib/index.js) is declared\n// `async`, so it always returns a Promise even though mjml-core's underlying\n// compile is synchronous — calling it without awaiting silently hands back a\n// pending Promise instead of { html, errors }.\ntype Mjml2Html = (\n mjml: string,\n options?: Record<string, unknown>,\n) => Promise<{ html: string; errors: unknown[] }>;\n\nconst FORMATS = new Set([\"mjml\", \"html\"]);\n\nexport async function runRender(args: ParsedArgs): Promise<number> {\n const file = args.positional[0];\n if (!file) throw new UsageError(\"render needs a template file.\");\n\n const format = flagValue(args, \"format\") ?? \"mjml\";\n if (!FORMATS.has(format)) {\n throw new UsageError(`Unknown --format \"${format}\". Use mjml or html.`);\n }\n\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n const data = readTemplateFile(file, cwd);\n\n // A structurally invalid template must fail with the error list (exit 1),\n // not surface as a renderer-internals crash (exit 2) — edit.ts validates\n // for the same reason before it writes.\n const { valid, errors } = validateTemplate(data);\n if (!valid) {\n throw new InvalidTemplateError(\n `${file} is not structurally valid (${errors.length} error(s)).`,\n errors,\n );\n }\n\n const content = data as TemplateContent;\n const mjml = await renderToMjml(content);\n\n let output = mjml;\n if (format === \"html\") {\n // The SDK bundles no MJML compiler by design, so there is no fallback to\n // reach for: a missing peer is a hard stop with an actionable message.\n const mod = await resolveOptional<{ default: Mjml2Html }>(\"mjml\", cwd);\n if (!mod) {\n throw new MissingDependencyError(\n \"mjml\",\n \"Rendering HTML needs the optional `mjml` package, which isn't installed.\\n npm install mjml\",\n );\n }\n output = (await mod.default(mjml, { validationLevel: \"soft\" })).html;\n }\n\n const out = flagValue(args, \"out\", \"o\");\n if (out) {\n const path = resolveFrom(out, cwd);\n // render writes raw text, not JSON, so it can't reuse writeTemplateFile —\n // create the parent directory directly instead.\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, output, \"utf8\");\n note(`Wrote ${path}`);\n return EXIT.ok;\n }\n\n emit({ format, output }, () => output);\n return EXIT.ok;\n}\n","import type {\n TemplateContent,\n TemplateOperationPayload,\n} from \"@templatical/types\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit } from \"../output\";\nimport {\n EXIT,\n InvalidTemplateError,\n readTemplateFile,\n UsageError,\n writeTemplateFile,\n} from \"../io\";\nimport { applyOperation, validateTemplate } from \"../../index\";\n\n/** What a caller supplies; `timestamp` is ours to fill. */\ninterface OperationInput {\n operation: TemplateOperationPayload[\"operation\"];\n data?: Record<string, unknown>;\n}\n\nfunction parseOperations(args: ParsedArgs, cwd: string): OperationInput[] {\n const inline = flagValue(args, \"op\");\n const batchFile = flagValue(args, \"ops\");\n // !== undefined, not truthy: flagValue returns \"\" for an explicitly-empty\n // flag, and a truthy check would let --op \"\" --ops <file> silently run the\n // batch instead of reporting that both were passed.\n if (inline !== undefined && batchFile !== undefined) {\n throw new UsageError(\"Pass either --op or --ops, not both.\");\n }\n if (inline) {\n try {\n return [JSON.parse(inline) as OperationInput];\n } catch (err) {\n throw new UsageError(`--op is not valid JSON: ${(err as Error).message}`);\n }\n }\n if (batchFile) {\n const parsed = readTemplateFile(batchFile, cwd);\n if (!Array.isArray(parsed)) {\n throw new UsageError(\"--ops must point at a JSON array of operations.\");\n }\n return parsed as OperationInput[];\n }\n throw new UsageError(\n \"edit needs --op '<json>' for one operation or --ops <file> for a batch.\",\n );\n}\n\nexport function runEdit(args: ParsedArgs): number {\n const file = args.positional[0];\n if (!file) throw new UsageError(\"edit needs a template file.\");\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n\n const operations = parseOperations(args, cwd);\n let content = readTemplateFile(file, cwd) as TemplateContent;\n\n // All-or-nothing: applyOperation returns the unchanged input on rejection, so\n // stopping at the first failure and discarding needs no rollback. Nothing is\n // written until every operation has succeeded.\n for (const [index, input] of operations.entries()) {\n const result = applyOperation(content, {\n operation: input.operation,\n data: input.data ?? {},\n timestamp: Date.now(),\n });\n if (!result.ok) {\n throw new UsageError(\n `Operation ${index + 1} (${String(input.operation)}) was rejected: ${result.error}`,\n );\n }\n content = result.content;\n }\n\n // An operation can produce a structurally invalid document, so validate\n // before writing: the working file must always be valid.\n const { valid, errors } = validateTemplate(content);\n if (!valid) {\n throw new InvalidTemplateError(\n `The edited template is not structurally valid (${errors.length} error(s)); ${file} was not written.`,\n errors,\n );\n }\n\n const path = writeTemplateFile(file, content, cwd);\n emit(\n { applied: operations.length, file: path },\n () => `Applied ${operations.length} operation(s) to ${path}`,\n );\n return EXIT.ok;\n}\n","// The format registry. A new @templatical/import-* converter is ONE entry here\n// and nothing else: reference/import.md documents the routing rule rather than\n// the list, and `--list-formats` answers what is resolvable at runtime. That is\n// what lets a new importer ship without a skill edit.\n\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { basename, extname } from \"node:path\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit } from \"../output\";\nimport {\n EXIT,\n MissingDependencyError,\n resolveFrom,\n UsageError,\n writeTemplateFile,\n} from \"../io\";\nimport { resolveOptional } from \"../resolve-optional\";\nimport { WORKING_DIR } from \"../../live/index\";\n\ninterface FormatSpec {\n pkg: string;\n /** The converter's exported function name. */\n fn: string;\n /**\n * What the converter is handed. `json` parses the source first, `text` passes\n * it through, and `stripo` unpacks a `{ html, css }` envelope — Stripo is the\n * one format whose export may arrive as either shape.\n */\n input: \"json\" | \"text\" | \"stripo\";\n}\n\nexport const FORMATS: Record<string, FormatSpec> = {\n unlayer: {\n pkg: \"@templatical/import-unlayer\",\n fn: \"convertUnlayerTemplate\",\n input: \"json\",\n },\n beefree: {\n pkg: \"@templatical/import-beefree\",\n fn: \"convertBeeFreeTemplate\",\n input: \"json\",\n },\n stripo: {\n pkg: \"@templatical/import-stripo\",\n fn: \"convertStripoTemplate\",\n input: \"stripo\",\n },\n topol: {\n pkg: \"@templatical/import-topol\",\n fn: \"convertTopolTemplate\",\n input: \"json\",\n },\n chamaileon: {\n pkg: \"@templatical/import-chamaileon\",\n fn: \"convertChamaileonTemplate\",\n input: \"json\",\n },\n \"easy-email-pro\": {\n pkg: \"@templatical/import-easy-email-pro\",\n fn: \"convertEasyEmailProTemplate\",\n input: \"json\",\n },\n mjml: {\n pkg: \"@templatical/import-mjml\",\n fn: \"convertMjmlTemplate\",\n input: \"text\",\n },\n html: {\n pkg: \"@templatical/import-html\",\n fn: \"convertHtmlTemplate\",\n input: \"text\",\n },\n};\n\n/** Strip a tag and its contents, so class scanning never reads CSS or script. */\nfunction withoutElements(html: string, tag: string): string {\n const open = `<${tag}`;\n const close = `</${tag}`;\n const lower = html.toLowerCase();\n let out = \"\";\n let pos = 0;\n while (pos < html.length) {\n const start = lower.indexOf(open, pos);\n if (start === -1) {\n out += html.slice(pos);\n break;\n }\n const next = lower[start + open.length];\n // `<style` matches `<styles>` too unless the next char ends the tag name.\n if (next !== undefined && /[a-z0-9-]/.test(next)) {\n out += html.slice(pos, start + open.length);\n pos = start + open.length;\n continue;\n }\n out += html.slice(pos, start);\n const gt = html.indexOf(\">\", start);\n if (gt === -1) break;\n const closeAt = lower.indexOf(close, gt + 1);\n if (closeAt === -1) break;\n const closeGt = html.indexOf(\">\", closeAt);\n if (closeGt === -1) break;\n out += \" \";\n pos = closeGt + 1;\n }\n return out;\n}\n\n/** Every class token in the markup, ignoring <style> and <script> contents. */\nfunction markupClassTokens(html: string): string[] {\n const stripped = withoutElements(withoutElements(html, \"style\"), \"script\");\n const tokens: string[] = [];\n const re = /\\bclass\\s*=\\s*([\"'])([^\"']*)\\1/gi;\n let m: RegExpExecArray | null;\n while ((m = re.exec(stripped))) {\n tokens.push(...m[2].trim().split(/\\s+/).filter(Boolean));\n }\n return tokens;\n}\n\n/** Stripo's own class prefixes, which survive both of its export shapes. */\nfunction looksLikeStripoHtml(html: unknown): boolean {\n if (typeof html !== \"string\" || html.trim().length === 0) return false;\n const tokens = markupClassTokens(html);\n if (\n tokens.some(\n (t) =>\n t === \"esd-stripe\" ||\n t === \"esd-structure\" ||\n t === \"esd-container-frame\" ||\n t.startsWith(\"esd-block-\"),\n )\n ) {\n return true;\n }\n return tokens.some(\n (t) =>\n t === \"es-wrapper\" || t === \"es-content-body\" || t === \"es-header-body\",\n );\n}\n\n/** Easy Email Pro marks its own nodes `standard-*`; OSS Easy Email does not. */\nfunction hasStandardType(node: unknown): boolean {\n if (!node || typeof node !== \"object\") return false;\n const n = node as { type?: unknown; children?: unknown };\n if (typeof n.type === \"string\" && n.type.startsWith(\"standard-\")) return true;\n if (Array.isArray(n.children)) return n.children.some(hasStandardType);\n return false;\n}\n\n/** Guess the source format, or null when the caller must pass --format. */\nexport function detectFormat(fileName: string, content: string): string | null {\n const ext = extname(fileName).toLowerCase();\n const trimmed = content.trimStart();\n\n // MJML is decided before both the extension check and the generic `<` branch:\n // an MJML document saved as .html is still MJML, and reading it as HTML\n // silently produces a table-soup import that looks like a bad converter.\n if (ext === \".mjml\") return \"mjml\";\n if (/^<(\\?xml[^>]*\\?>\\s*)?<?\\s*mjml[\\s>]/i.test(trimmed)) return \"mjml\";\n if (/^<\\s*mj-body[\\s>]/i.test(trimmed)) return \"mjml\";\n\n // Stripo's compiled File→HTML and its plugin storage are both `.html` (or a\n // JSON `{ html, css }` blob), so the class check must run before the generic\n // html branch or every Stripo export imports as table soup.\n if (looksLikeStripoHtml(content)) return \"stripo\";\n\n if (ext === \".html\" || ext === \".htm\") return \"html\";\n if (trimmed.startsWith(\"<\")) return \"html\";\n if (trimmed.startsWith(\"{\")) {\n let obj: {\n body?: { rows?: unknown; type?: unknown };\n page?: { rows?: unknown };\n tagName?: unknown;\n content?: { type?: unknown };\n type?: unknown;\n html?: unknown;\n };\n try {\n obj = JSON.parse(content);\n } catch {\n return null;\n }\n // Unlayer designs come from editor.saveDesign(): { body: { rows } }.\n if (obj?.body?.rows) return \"unlayer\";\n // BeeFree templates: { page: { rows } }.\n if (obj?.page?.rows) return \"beefree\";\n // Topol designs are an MJML-shaped tree rooted at the global style.\n if (obj?.tagName === \"mj-global-style\") return \"topol\";\n // Chamaileon getDocument(): { body: { type: \"body\" } }. Unlayer's\n // { body: { rows } } is matched above, so the order between them matters.\n if (obj?.body?.type === \"body\") return \"chamaileon\";\n // Easy Email Pro persist: { content: { type: \"page\" } } or a bare page,\n // distinguished from OSS Easy Email by its `standard-*` node types.\n const page =\n obj?.content?.type === \"page\"\n ? obj.content\n : obj?.type === \"page\"\n ? obj\n : null;\n if (page && hasStandardType(page)) return \"easy-email-pro\";\n // A plugin host often persists the whole getTemplateData() object.\n if (typeof obj?.html === \"string\" && looksLikeStripoHtml(obj.html)) {\n return \"stripo\";\n }\n return null;\n }\n return null;\n}\n\n/** Split a Stripo source into html + css, whichever shape it arrived in. */\nexport function unpackStripoSource(source: string): {\n html: string;\n css?: string;\n} {\n const trimmed = source.trimStart();\n if (trimmed.startsWith(\"{\")) {\n try {\n const obj = JSON.parse(source) as { html?: unknown; css?: unknown };\n if (typeof obj?.html === \"string\") {\n return {\n html: obj.html,\n css: typeof obj.css === \"string\" ? obj.css : undefined,\n };\n }\n } catch {\n // Not an envelope after all — treat the whole thing as markup.\n }\n }\n return { html: source };\n}\n\n/** The stylesheet a plugin host wrote beside an HTML export, if there is one. */\nfunction siblingCss(sourcePath: string, source: string): string | undefined {\n // A JSON envelope carries its own css; only a bare .html file has a sibling.\n if (source.trimStart().startsWith(\"{\")) return undefined;\n const cssPath = sourcePath.replace(/\\.[^.]+$/, \".css\");\n if (cssPath === sourcePath || !existsSync(cssPath)) return undefined;\n return readFileSync(cssPath, \"utf8\");\n}\n\nexport interface ReportCounts {\n total: number;\n converted: number;\n approximated: number;\n htmlFallback: number;\n skipped: number;\n warnings: string[];\n}\n\n/**\n * Status counts from a converter's report. Derived from `report.entries` (every\n * entry carries a `status`) rather than each package's own `summary` shape, so\n * it works identically across all three converters and any future one.\n */\nexport function summarizeReport(report: unknown): ReportCounts {\n const r = report as\n { entries?: Array<{ status?: string }>; warnings?: string[] } | undefined;\n const counts: ReportCounts = {\n total: 0,\n converted: 0,\n approximated: 0,\n htmlFallback: 0,\n skipped: 0,\n warnings: r?.warnings ?? [],\n };\n for (const e of r?.entries ?? []) {\n counts.total++;\n if (e.status === \"converted\") counts.converted++;\n else if (e.status === \"approximated\") counts.approximated++;\n else if (e.status === \"html-fallback\") counts.htmlFallback++;\n else if (e.status === \"skipped\") counts.skipped++;\n }\n return counts;\n}\n\nasync function listFormats(cwd: string): Promise<number> {\n const formats: Array<{\n format: string;\n package: string;\n available: boolean;\n }> = [];\n for (const [format, spec] of Object.entries(FORMATS)) {\n formats.push({\n format,\n package: spec.pkg,\n available: (await resolveOptional(spec.pkg, cwd)) !== null,\n });\n }\n emit({ formats }, () =>\n formats\n .map(\n (f) =>\n ` ${f.format.padEnd(14)} ${f.package}${f.available ? \"\" : \" (not installed)\"}`,\n )\n .join(\"\\n\"),\n );\n return EXIT.ok;\n}\n\nexport async function runImport(args: ParsedArgs): Promise<number> {\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n if (args.flags[\"list-formats\"]) return listFormats(cwd);\n\n const file = args.positional[0];\n if (!file) throw new UsageError(\"import needs a source file.\");\n const path = resolveFrom(file, cwd);\n\n let source: string;\n try {\n source = readFileSync(path, \"utf8\");\n } catch {\n throw new UsageError(`Could not read ${file}`);\n }\n\n const known = Object.keys(FORMATS).join(\", \");\n const requested = flagValue(args, \"format\");\n if (requested && !FORMATS[requested]) {\n throw new UsageError(\n `Unknown --format \"${requested}\". Known formats: ${known}.`,\n );\n }\n const format = requested ?? detectFormat(path, source);\n if (!format) {\n throw new UsageError(\n `Could not detect the format of ${file}. Pass --format with one of: ${known}.`,\n );\n }\n\n const spec = FORMATS[format];\n const mod = await resolveOptional<Record<string, unknown>>(spec.pkg, cwd);\n if (!mod) {\n throw new MissingDependencyError(\n spec.pkg,\n `Importing ${format} needs ${spec.pkg}, which isn't installed.\\n npm install ${spec.pkg}`,\n );\n }\n const convert = mod[spec.fn] as (\n input: unknown,\n options?: unknown,\n ) => {\n content: unknown;\n report: unknown;\n };\n\n let content: unknown;\n let report: unknown;\n if (spec.input === \"stripo\") {\n // Plugin storage keeps the stylesheet out of the markup — either beside the\n // html in one JSON envelope, or as a sibling .css file the host wrote next\n // to it. Without the CSS every block imports unstyled, which reads as a\n // broken converter rather than a missing file.\n const unpacked = unpackStripoSource(source);\n const css = unpacked.css ?? siblingCss(path, source);\n ({ content, report } = convert(unpacked.html, css ? { css } : undefined));\n } else {\n const input = spec.input === \"json\" ? JSON.parse(source) : source;\n ({ content, report } = convert(input));\n }\n\n const outName = flagValue(args, \"out\") ?? basename(path, extname(path));\n const written = writeTemplateFile(\n `${WORKING_DIR}/${outName}.json`,\n content,\n cwd,\n );\n\n const counts = summarizeReport(report);\n const lossy = counts.htmlFallback + counts.skipped > 0;\n emit({ format, file: written, report: counts }, () =>\n [\n `Imported ${format} to ${written}`,\n ` ${counts.converted} converted, ${counts.approximated} approximated, ${counts.htmlFallback} html fallback, ${counts.skipped} skipped`,\n ...counts.warnings.map((w) => ` ! ${w}`),\n lossy\n ? \" Import is lossy. Open it in live mode and refine the fallback blocks.\"\n : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n );\n return EXIT.ok;\n}\n","import { mkdirSync, rmSync, writeFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { flagValue, type ParsedArgs } from \"../args\";\nimport { emit, note } from \"../output\";\nimport { EXIT, resolveFrom, UsageError } from \"../io\";\nimport {\n DEFAULT_PORT,\n listWorkingFiles,\n openBrowser,\n pidfilePath,\n processAlive,\n readPidfile,\n readWorkingFile,\n startBridgePreferring,\n WORKING_DIR,\n} from \"../../live/index\";\n\n/**\n * The first title block's text in document order, as a hint for `list`.\n *\n * It must descend into a section's columns, not scan top-level blocks only:\n * templates put their content inside sections (that is the documented\n * structure), so a top-level scan finds nothing for a real template. Measured\n * across all five of the templatical skill's examples — event-invite, newsletter,\n * product-sale, receipt, welcome — none has a top-level title block, so a\n * shallow version of this returns null every time and the hint is dead code.\n */\nfunction titleHint(content: unknown): string | null {\n return findTitle((content as { blocks?: unknown })?.blocks);\n}\n\nfunction findTitle(blocks: unknown): string | null {\n if (!Array.isArray(blocks)) return null;\n for (const block of blocks as Array<{\n type?: string;\n content?: string;\n children?: unknown[];\n }>) {\n if (block?.type === \"title\" && typeof block.content === \"string\") {\n return block.content;\n }\n if (block?.type === \"section\" && Array.isArray(block.children)) {\n for (const column of block.children) {\n const hit = findTitle(column);\n if (hit) return hit;\n }\n }\n }\n return null;\n}\n\nexport function runList(args: ParsedArgs): number {\n const cwd = flagValue(args, \"cwd\") ?? process.cwd();\n const templates = listWorkingFiles(cwd).map((name) => ({\n name,\n title: titleHint(readWorkingFile(join(cwd, WORKING_DIR, name))),\n }));\n emit({ templates }, () =>\n templates.length === 0\n ? `No templates in ${WORKING_DIR}/`\n : templates\n .map((t) => ` ${t.name}${t.title ? ` - ${t.title}` : \"\"}`)\n .join(\"\\n\"),\n );\n return EXIT.ok;\n}\n\nasync function postTo(port: number, path: string): Promise<Response> {\n return fetch(`http://localhost:${port}${path}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n });\n}\n\nexport async function runLive(args: ParsedArgs): Promise<number> {\n const sub = args.positional[0];\n const cwd = resolveFrom(flagValue(args, \"cwd\") ?? \".\", process.cwd());\n\n if (sub === \"reload\" || sub === \"stop\") {\n const info = readPidfile(cwd);\n if (!info || !processAlive(info.pid)) {\n throw new UsageError(\n `No live server is running here (no live pidfile at ${WORKING_DIR}/live-server.pid).`,\n );\n }\n if (sub === \"reload\") {\n const res = await postTo(info.port, \"/reload\");\n const body = (await res.json().catch(() => ({}))) as { clients?: number };\n emit(\n { reloaded: true, clients: body.clients ?? 0 },\n () =>\n `Pushed the working file to ${body.clients ?? 0} connected page(s).`,\n );\n return EXIT.ok;\n }\n try {\n process.kill(info.pid, \"SIGTERM\");\n } catch {\n /* already gone */\n }\n rmSync(pidfilePath(cwd), { force: true });\n emit({ stopped: true }, () => \"Stopped the live server.\");\n return EXIT.ok;\n }\n\n if (sub !== undefined) {\n throw new UsageError(\n `Unknown \"live ${sub}\". Use \\`live\\`, \\`live reload\\` or \\`live stop\\`.`,\n );\n }\n\n // start\n const portFlag = flagValue(args, \"port\");\n const preferredPort = portFlag ? Number(portFlag) : DEFAULT_PORT;\n const existing = readPidfile(cwd);\n if (existing && processAlive(existing.pid)) {\n emit(\n {\n url: `http://localhost:${existing.port}/`,\n pid: existing.pid,\n alreadyRunning: true,\n },\n () =>\n `Live server already running (pid ${existing.pid}) at http://localhost:${existing.port}/`,\n );\n return EXIT.ok;\n }\n if (existing) rmSync(pidfilePath(cwd), { force: true }); // stale\n\n const file = flagValue(args, \"file\");\n const handle = await startBridgePreferring({ cwd, preferredPort, file });\n\n mkdirSync(dirname(pidfilePath(cwd)), { recursive: true });\n writeFileSync(\n pidfilePath(cwd),\n JSON.stringify({ pid: process.pid, port: handle.port }),\n \"utf8\",\n );\n\n const cleanup = () => {\n rmSync(pidfilePath(cwd), { force: true });\n handle.close().finally(() => process.exit(EXIT.ok));\n };\n process.on(\"SIGINT\", cleanup);\n process.on(\"SIGTERM\", cleanup);\n\n // Emit before blocking: the caller needs the URL and the working path now,\n // not when the server shuts down.\n emit(\n {\n url: handle.url,\n port: handle.port,\n preferredPort,\n fellBack: handle.fellBack,\n workingFile: handle.workingPath,\n },\n () =>\n [\n `Templatical live preview running at ${handle.url}`,\n handle.fellBack\n ? `(port ${preferredPort} was busy - using ${handle.port})`\n : \"\",\n `Working file: ${handle.workingPath}`,\n ]\n .filter(Boolean)\n .join(\"\\n\"),\n );\n\n if (args.flags[\"no-open\"]) {\n note(`Open ${handle.url} in a browser.`);\n } else {\n note(`Opening ${handle.url} in your default browser...`);\n openBrowser(handle.url);\n }\n note(\"After writing the working file, run: templatical live reload\");\n\n // Block: the bridge owns the process until a signal arrives.\n return new Promise<number>(() => {});\n}\n","#!/usr/bin/env node\n// The CLI entry point.\n//\n// Every command is a thin shell over this package's library functions; the\n// dispatch below owns argument handling, the error→exit-code mapping, and\n// nothing else. Human-facing output goes through cli/output.ts.\n\nimport { realpathSync } from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport { parseArgs } from \"./cli/args\";\nimport { note, setJsonMode } from \"./cli/output\";\nimport {\n EXIT,\n InvalidTemplateError,\n MissingDependencyError,\n UsageError,\n} from \"./cli/io\";\nimport { runSchema } from \"./cli/commands/schema\";\nimport { runValidate } from \"./cli/commands/validate\";\nimport { runRender } from \"./cli/commands/render\";\nimport { runEdit } from \"./cli/commands/edit\";\nimport { runImport } from \"./cli/commands/import\";\nimport { runList, runLive } from \"./cli/commands/live\";\n\nconst USAGE = `templatical <command> [options]\n\n validate <file> structural + quality lint\n schema [--out <file>] print the block JSON Schema\n render <file> [--format mjml|html] [-o <file>] render to MJML or HTML\n edit <file> --op '<json>' | --ops <file> apply operations, write the result\n import <file> [--format <fmt>] | --list-formats convert a design to Templatical JSON\n live [--file <f>] [--port <n>] [--cwd <d>] [--no-open]\n live reload | live stop\n list working files in .templatical/\n\nOptions:\n --json machine-readable output on stdout\n`;\n\nexport async function main(argv: string[]): Promise<number> {\n const args = parseArgs(argv);\n setJsonMode(args.json);\n\n switch (args.command) {\n case \"validate\":\n return runValidate(args);\n case \"schema\":\n return runSchema(args);\n case \"render\":\n return await runRender(args);\n case \"edit\":\n return runEdit(args);\n case \"import\":\n return await runImport(args);\n case \"live\":\n return await runLive(args);\n case \"list\":\n return runList(args);\n case \"help\":\n note(USAGE);\n return EXIT.ok;\n case undefined:\n // parseArgs strips leading dashes into flags, so `--help`/`-h` never\n // reach args.command — they land here, not on a (dead) case \"--help\".\n // Asking for help is not a usage error; a bare invocation still is.\n if (args.flags.help === true || args.flags.h === true) {\n note(USAGE);\n return EXIT.ok;\n }\n note(USAGE);\n return EXIT.usage;\n default:\n note(`Unknown command \"${args.command}\".\\n\\n${USAGE}`);\n return EXIT.usage;\n }\n}\n\n// Only self-invoke when run as the CLI entry point, not when imported — this\n// package's own tests import `main` directly to exercise the dispatch above\n// without spawning a subprocess.\n//\n// import.meta.url is always a realpath, but process.argv[1] is not: npm's\n// `bin` field links a real symlink into the consumer's node_modules/.bin\n// (e.g. node_modules/.bin/templatical -> ../@templatical/template-tools/dist/bin.js),\n// and Node leaves argv[1] as that symlink path instead of resolving it.\n// Comparing them directly is false for every consumer who runs the published\n// binary, so main() would silently never run. realpathSync(argv[1]) resolves\n// the symlink so both sides name the same file.\nexport function isEntryPoint(): boolean {\n const argv1 = process.argv[1];\n if (!argv1) return false;\n try {\n return pathToFileURL(realpathSync(argv1)).href === import.meta.url;\n } catch {\n // realpathSync throws (e.g. ENOENT) if argv[1] doesn't exist or can't be\n // read. This guard runs at module load, so failing open into a crash\n // would be worse than just not self-invoking.\n return false;\n }\n}\n\nif (isEntryPoint()) {\n main(process.argv.slice(2))\n .then((code) => process.exit(code))\n .catch((err: unknown) => {\n if (err instanceof InvalidTemplateError) {\n note(err.message);\n for (const e of err.errors) note(` - ${e}`);\n process.exit(EXIT.invalid);\n }\n if (err instanceof MissingDependencyError) {\n note(err.message);\n process.exit(EXIT.missingDep);\n }\n if (err instanceof UsageError) {\n note(err.message);\n process.exit(EXIT.usage);\n }\n note(`Unexpected error: ${(err as Error)?.message ?? String(err)}`);\n process.exit(EXIT.usage);\n });\n}\n"],"mappings":";;;;;;;;;AAIA,MAAM,8BAAc,IAAI,IAAI;CAC1B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;A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,KAAK,KAAK,KAAK;CACzB;CACA,KAAK,qBAAsB,KAAe,WAAW,OAAO,GAAG,GAAG;CAClE,QAAQ,KAAK,KAAK,KAAK;AACzB,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { LintIssue } from "@templatical/quality";
|
|
2
|
+
import { ColumnLayout, TemplateContent, TemplateOperationPayload } from "@templatical/types";
|
|
3
|
+
//#region src/validate.d.ts
|
|
4
|
+
interface SchemaDefinition {
|
|
5
|
+
properties?: {
|
|
6
|
+
type?: {
|
|
7
|
+
const?: unknown;
|
|
8
|
+
};
|
|
9
|
+
} & Record<string, unknown>;
|
|
10
|
+
[key: string]: unknown;
|
|
11
|
+
}
|
|
12
|
+
interface SchemaDocument {
|
|
13
|
+
definitions: Record<string, SchemaDefinition>;
|
|
14
|
+
[key: string]: unknown;
|
|
15
|
+
}
|
|
16
|
+
/** The generated JSON Schema for `TemplateContent`, as a plain object. */
|
|
17
|
+
export declare const schema: SchemaDocument;
|
|
18
|
+
interface ValidationResult {
|
|
19
|
+
valid: boolean;
|
|
20
|
+
errors: string[];
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* Structural validation. Synchronous, depends only on ajv + the committed
|
|
24
|
+
* schema.json (no build of the workspace packages required).
|
|
25
|
+
*/
|
|
26
|
+
export declare function validateTemplate(data: unknown): ValidationResult;
|
|
27
|
+
interface QualityLintResult {
|
|
28
|
+
issues: LintIssue[];
|
|
29
|
+
/** Set when the linter itself threw — the template is structurally suspect. */
|
|
30
|
+
error?: string;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Quality layer — accessibility / structure / link linting.
|
|
34
|
+
*
|
|
35
|
+
* Assumes structurally-valid input, so callers should run `validateTemplate`
|
|
36
|
+
* first; the try/catch is a guard against a malformed template crashing the
|
|
37
|
+
* linter rather than a substitute for that ordering.
|
|
38
|
+
*/
|
|
39
|
+
export declare function runQualityLint(data: unknown): QualityLintResult;
|
|
40
|
+
//#endregion
|
|
41
|
+
//#region src/operations.d.ts
|
|
42
|
+
/** Columns a layout declares. Mirrors the helper in core's editor. */
|
|
43
|
+
export declare function getColumnCount(layout: ColumnLayout): number;
|
|
44
|
+
interface OperationResult {
|
|
45
|
+
ok: boolean;
|
|
46
|
+
/** The new document on success; the unchanged input on failure. */
|
|
47
|
+
content: TemplateContent;
|
|
48
|
+
error?: string;
|
|
49
|
+
}
|
|
50
|
+
/** Apply one operation, returning a new document. Never mutates the input. */
|
|
51
|
+
export declare function applyOperation(content: TemplateContent, payload: TemplateOperationPayload): OperationResult;
|
|
52
|
+
//#endregion
|
|
53
|
+
export type { OperationResult, QualityLintResult, ValidationResult };
|
|
54
|
+
//# sourceMappingURL=index.d.ts.map
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import { Server } from "node:http";
|
|
2
|
+
//#region src/live/index.d.ts
|
|
3
|
+
export declare const EDITOR_VERSION = "0.38.0";
|
|
4
|
+
export declare const DEFAULT_PORT = 4747;
|
|
5
|
+
export declare const WORKING_DIR = ".templatical";
|
|
6
|
+
export declare const PID_FILE: string;
|
|
7
|
+
/** Order-insensitive structural equality for parsed-JSON template content. */
|
|
8
|
+
export declare function deepEqual(a: unknown, b: unknown): boolean;
|
|
9
|
+
/** Read + parse the working file, or return null when it is absent/unparseable. */
|
|
10
|
+
export declare function readWorkingFile(path: string): unknown;
|
|
11
|
+
/** List the working templates in a project's `.templatical/` folder, by name. */
|
|
12
|
+
export declare function listWorkingFiles(cwd: string): string[];
|
|
13
|
+
/**
|
|
14
|
+
* Open a URL in the user's default browser — best-effort and cross-platform.
|
|
15
|
+
* A silent no-op where there's no browser (headless / CI / sandbox); callers
|
|
16
|
+
* always surface the URL too, so nothing is lost when this does nothing.
|
|
17
|
+
*/
|
|
18
|
+
export declare function openBrowser(url: string): void;
|
|
19
|
+
export interface PidfileInfo {
|
|
20
|
+
pid: number;
|
|
21
|
+
port: number;
|
|
22
|
+
}
|
|
23
|
+
export declare function pidfilePath(cwd: string): string;
|
|
24
|
+
export declare function readPidfile(cwd: string): PidfileInfo | null;
|
|
25
|
+
export declare function processAlive(pid: number): boolean;
|
|
26
|
+
/**
|
|
27
|
+
* A note the user left in the browser, against a block or the template as a
|
|
28
|
+
* whole. Delivered on GET /content - the call the agent already makes before
|
|
29
|
+
* every change - so notes need no polling and no separate endpoint to drain.
|
|
30
|
+
*/
|
|
31
|
+
export interface Annotation {
|
|
32
|
+
id: string;
|
|
33
|
+
/** null for a note about the template rather than one block. */
|
|
34
|
+
blockId: string | null;
|
|
35
|
+
text: string;
|
|
36
|
+
createdAt: number;
|
|
37
|
+
}
|
|
38
|
+
export interface BridgeHandle {
|
|
39
|
+
server: Server;
|
|
40
|
+
port: number;
|
|
41
|
+
url: string;
|
|
42
|
+
/** The absolute path of the working file this bridge is serving. */
|
|
43
|
+
workingPath: string;
|
|
44
|
+
/** The page's latest state, for callers that drive the bridge in-process. */
|
|
45
|
+
getEditorState: () => {
|
|
46
|
+
divergent: boolean;
|
|
47
|
+
content: unknown;
|
|
48
|
+
annotations: Annotation[];
|
|
49
|
+
};
|
|
50
|
+
/** Re-read the working file and push it to every connected page. */
|
|
51
|
+
reload: () => {
|
|
52
|
+
ok: boolean;
|
|
53
|
+
clients: number;
|
|
54
|
+
};
|
|
55
|
+
close: () => Promise<void>;
|
|
56
|
+
}
|
|
57
|
+
export interface StartBridgeOptions {
|
|
58
|
+
cwd?: string;
|
|
59
|
+
port?: number;
|
|
60
|
+
file?: string;
|
|
61
|
+
harnessFile?: string;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Start the bridge HTTP server. Pure server + in-memory sync state; callers own
|
|
65
|
+
* process lifecycle. Resolves once listening.
|
|
66
|
+
*
|
|
67
|
+
* The returned handle exposes `getEditorState` and `reload` directly, so an
|
|
68
|
+
* in-process caller (the MCP server) never has to make an HTTP request to its
|
|
69
|
+
* own bridge — that is the whole reason live mode can work inside a sandboxed
|
|
70
|
+
* agent. The equivalent HTTP endpoints stay for the skill's out-of-process CLI.
|
|
71
|
+
*/
|
|
72
|
+
export declare function startBridge({ cwd, port, file, harnessFile }?: StartBridgeOptions): Promise<BridgeHandle>;
|
|
73
|
+
export interface PreferringHandle extends BridgeHandle {
|
|
74
|
+
fellBack: boolean;
|
|
75
|
+
preferredPort?: number;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Start the bridge on `preferredPort`, falling back to an OS-assigned free port
|
|
79
|
+
* when that one is occupied — so a busy port never fails the launch. The page
|
|
80
|
+
* uses relative URLs, so the actual port is discovered, not assumed. The
|
|
81
|
+
* returned handle carries `fellBack: true` when it landed on a different port.
|
|
82
|
+
*/
|
|
83
|
+
export declare function startBridgePreferring({ preferredPort, ...opts }?: StartBridgeOptions & {
|
|
84
|
+
preferredPort?: number;
|
|
85
|
+
}): Promise<PreferringHandle>;
|
|
86
|
+
//#endregion
|
|
87
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { createServer } from "node:http";
|
|
2
|
+
import { spawn } from "node:child_process";
|
|
3
|
+
import { existsSync, readFileSync, readdirSync } from "node:fs";
|
|
4
|
+
import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
5
|
+
import { fileURLToPath } from "node:url";
|
|
6
|
+
//#region src/live/index.ts
|
|
7
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
8
|
+
const EDITOR_VERSION = "0.38.0";
|
|
9
|
+
const DEFAULT_PORT = 4747;
|
|
10
|
+
const WORKING_DIR = ".templatical";
|
|
11
|
+
const PID_FILE = join(WORKING_DIR, "live-server.pid");
|
|
12
|
+
const HARNESS_FILE = resolve(here, "../../live/index.html");
|
|
13
|
+
/** Order-insensitive structural equality for parsed-JSON template content. */
|
|
14
|
+
function deepEqual(a, b) {
|
|
15
|
+
if (a === b) return true;
|
|
16
|
+
if (a === null || b === null) return false;
|
|
17
|
+
if (typeof a !== "object" || typeof b !== "object") return false;
|
|
18
|
+
const aArr = Array.isArray(a);
|
|
19
|
+
if (aArr !== Array.isArray(b)) return false;
|
|
20
|
+
if (aArr) {
|
|
21
|
+
const aList = a;
|
|
22
|
+
const bList = b;
|
|
23
|
+
if (aList.length !== bList.length) return false;
|
|
24
|
+
for (let i = 0; i < aList.length; i++) if (!deepEqual(aList[i], bList[i])) return false;
|
|
25
|
+
return true;
|
|
26
|
+
}
|
|
27
|
+
const aObj = a;
|
|
28
|
+
const bObj = b;
|
|
29
|
+
const ak = Object.keys(aObj);
|
|
30
|
+
const bk = Object.keys(bObj);
|
|
31
|
+
if (ak.length !== bk.length) return false;
|
|
32
|
+
for (const k of ak) {
|
|
33
|
+
if (!Object.prototype.hasOwnProperty.call(bObj, k)) return false;
|
|
34
|
+
if (!deepEqual(aObj[k], bObj[k])) return false;
|
|
35
|
+
}
|
|
36
|
+
return true;
|
|
37
|
+
}
|
|
38
|
+
/** Read + parse the working file, or return null when it is absent/unparseable. */
|
|
39
|
+
function readWorkingFile(path) {
|
|
40
|
+
if (!existsSync(path)) return null;
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/** List the working templates in a project's `.templatical/` folder, by name. */
|
|
48
|
+
function listWorkingFiles(cwd) {
|
|
49
|
+
const dir = resolve(cwd, WORKING_DIR);
|
|
50
|
+
if (!existsSync(dir)) return [];
|
|
51
|
+
return readdirSync(dir).filter((f) => f.endsWith(".json")).sort();
|
|
52
|
+
}
|
|
53
|
+
async function readJsonBody(req) {
|
|
54
|
+
const chunks = [];
|
|
55
|
+
for await (const chunk of req) chunks.push(chunk);
|
|
56
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
57
|
+
return raw ? JSON.parse(raw) : void 0;
|
|
58
|
+
}
|
|
59
|
+
/**
|
|
60
|
+
* Open a URL in the user's default browser — best-effort and cross-platform.
|
|
61
|
+
* A silent no-op where there's no browser (headless / CI / sandbox); callers
|
|
62
|
+
* always surface the URL too, so nothing is lost when this does nothing.
|
|
63
|
+
*/
|
|
64
|
+
function openBrowser(url) {
|
|
65
|
+
const [cmd, cmdArgs] = process.platform === "darwin" ? ["open", [url]] : process.platform === "win32" ? ["cmd", [
|
|
66
|
+
"/c",
|
|
67
|
+
"start",
|
|
68
|
+
"",
|
|
69
|
+
url
|
|
70
|
+
]] : ["xdg-open", [url]];
|
|
71
|
+
try {
|
|
72
|
+
const child = spawn(cmd, cmdArgs, {
|
|
73
|
+
stdio: "ignore",
|
|
74
|
+
detached: true
|
|
75
|
+
});
|
|
76
|
+
child.on("error", () => {});
|
|
77
|
+
child.unref();
|
|
78
|
+
} catch {}
|
|
79
|
+
}
|
|
80
|
+
function pidfilePath(cwd) {
|
|
81
|
+
return resolve(cwd, PID_FILE);
|
|
82
|
+
}
|
|
83
|
+
function readPidfile(cwd) {
|
|
84
|
+
const p = pidfilePath(cwd);
|
|
85
|
+
if (!existsSync(p)) return null;
|
|
86
|
+
try {
|
|
87
|
+
return JSON.parse(readFileSync(p, "utf8"));
|
|
88
|
+
} catch {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
function processAlive(pid) {
|
|
93
|
+
try {
|
|
94
|
+
process.kill(pid, 0);
|
|
95
|
+
return true;
|
|
96
|
+
} catch {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
/**
|
|
101
|
+
* Start the bridge HTTP server. Pure server + in-memory sync state; callers own
|
|
102
|
+
* process lifecycle. Resolves once listening.
|
|
103
|
+
*
|
|
104
|
+
* The returned handle exposes `getEditorState` and `reload` directly, so an
|
|
105
|
+
* in-process caller (the MCP server) never has to make an HTTP request to its
|
|
106
|
+
* own bridge — that is the whole reason live mode can work inside a sandboxed
|
|
107
|
+
* agent. The equivalent HTTP endpoints stay for the skill's out-of-process CLI.
|
|
108
|
+
*/
|
|
109
|
+
function startBridge({ cwd = process.cwd(), port = 0, file = join(WORKING_DIR, "template.json"), harnessFile = HARNESS_FILE } = {}) {
|
|
110
|
+
const workingPath = isAbsolute(file) ? file : resolve(cwd, file);
|
|
111
|
+
const state = {
|
|
112
|
+
baseline: null,
|
|
113
|
+
editorCurrent: null,
|
|
114
|
+
divergent: false,
|
|
115
|
+
annotations: []
|
|
116
|
+
};
|
|
117
|
+
const clients = /* @__PURE__ */ new Set();
|
|
118
|
+
function broadcastTemplate(content) {
|
|
119
|
+
const payload = `event: template\ndata: ${JSON.stringify(content)}\n\n`;
|
|
120
|
+
for (const res of clients) res.write(payload);
|
|
121
|
+
}
|
|
122
|
+
function getEditorState() {
|
|
123
|
+
return {
|
|
124
|
+
divergent: state.divergent,
|
|
125
|
+
content: state.editorCurrent,
|
|
126
|
+
annotations: state.annotations
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function reload() {
|
|
130
|
+
const content = readWorkingFile(workingPath);
|
|
131
|
+
state.baseline = null;
|
|
132
|
+
state.editorCurrent = null;
|
|
133
|
+
state.divergent = false;
|
|
134
|
+
state.annotations = [];
|
|
135
|
+
if (content !== null) broadcastTemplate(content);
|
|
136
|
+
return {
|
|
137
|
+
ok: true,
|
|
138
|
+
clients: clients.size
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
const server = createServer(async (req, res) => {
|
|
142
|
+
const { pathname } = new URL(req.url ?? "/", "http://localhost");
|
|
143
|
+
const method = req.method ?? "GET";
|
|
144
|
+
try {
|
|
145
|
+
if (method === "GET" && (pathname === "/" || pathname === "/index.html")) {
|
|
146
|
+
const html = readFileSync(harnessFile, "utf8").replaceAll("{{EDITOR_VERSION}}", EDITOR_VERSION);
|
|
147
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
148
|
+
res.end(html);
|
|
149
|
+
return;
|
|
150
|
+
}
|
|
151
|
+
if (method === "GET" && pathname === "/template") {
|
|
152
|
+
const content = readWorkingFile(workingPath);
|
|
153
|
+
if (content === null) {
|
|
154
|
+
res.writeHead(204).end();
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
158
|
+
res.end(JSON.stringify(content));
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (method === "GET" && pathname === "/events") {
|
|
162
|
+
res.writeHead(200, {
|
|
163
|
+
"content-type": "text/event-stream",
|
|
164
|
+
"cache-control": "no-cache",
|
|
165
|
+
connection: "keep-alive"
|
|
166
|
+
});
|
|
167
|
+
res.write("event: ready\ndata: {}\n\n");
|
|
168
|
+
clients.add(res);
|
|
169
|
+
const ping = setInterval(() => res.write(": ping\n\n"), 15e3);
|
|
170
|
+
req.on("close", () => {
|
|
171
|
+
clearInterval(ping);
|
|
172
|
+
clients.delete(res);
|
|
173
|
+
});
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (method === "POST" && pathname === "/content") {
|
|
177
|
+
const body = await readJsonBody(req);
|
|
178
|
+
const content = body?.content;
|
|
179
|
+
if (body?.baseline) {
|
|
180
|
+
state.baseline = content ?? null;
|
|
181
|
+
state.editorCurrent = content ?? null;
|
|
182
|
+
state.divergent = false;
|
|
183
|
+
} else {
|
|
184
|
+
state.editorCurrent = content ?? null;
|
|
185
|
+
state.divergent = state.baseline !== null && !deepEqual(content, state.baseline);
|
|
186
|
+
}
|
|
187
|
+
res.writeHead(204).end();
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if (method === "GET" && pathname === "/content") {
|
|
191
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
192
|
+
res.end(JSON.stringify(getEditorState()));
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
if (method === "POST" && pathname === "/annotations") {
|
|
196
|
+
const body = await readJsonBody(req);
|
|
197
|
+
const text = typeof body?.text === "string" ? body.text.trim() : "";
|
|
198
|
+
if (!text) {
|
|
199
|
+
res.writeHead(400, { "content-type": "text/plain" });
|
|
200
|
+
res.end("An annotation needs non-empty `text`.");
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
const annotation = {
|
|
204
|
+
id: `a${state.annotations.length + 1}-${Date.now().toString(36)}`,
|
|
205
|
+
blockId: typeof body?.blockId === "string" ? body.blockId : null,
|
|
206
|
+
text,
|
|
207
|
+
createdAt: Date.now()
|
|
208
|
+
};
|
|
209
|
+
state.annotations.push(annotation);
|
|
210
|
+
res.writeHead(201, { "content-type": "application/json" });
|
|
211
|
+
res.end(JSON.stringify(annotation));
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
if (method === "POST" && pathname === "/reload") {
|
|
215
|
+
const result = reload();
|
|
216
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
217
|
+
res.end(JSON.stringify(result));
|
|
218
|
+
return;
|
|
219
|
+
}
|
|
220
|
+
res.writeHead(404, { "content-type": "text/plain" }).end("Not found");
|
|
221
|
+
} catch (err) {
|
|
222
|
+
res.writeHead(400, { "content-type": "text/plain" });
|
|
223
|
+
res.end(`Bad request: ${err.message}`);
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
return new Promise((resolvePromise, rejectPromise) => {
|
|
227
|
+
const onListenError = (err) => rejectPromise(err);
|
|
228
|
+
server.once("error", onListenError);
|
|
229
|
+
server.listen(port, "127.0.0.1", () => {
|
|
230
|
+
server.removeListener("error", onListenError);
|
|
231
|
+
const address = server.address();
|
|
232
|
+
const actualPort = typeof address === "object" && address !== null ? address.port : port;
|
|
233
|
+
resolvePromise({
|
|
234
|
+
server,
|
|
235
|
+
port: actualPort,
|
|
236
|
+
url: `http://localhost:${actualPort}/`,
|
|
237
|
+
workingPath,
|
|
238
|
+
getEditorState,
|
|
239
|
+
reload,
|
|
240
|
+
close: () => new Promise((r) => {
|
|
241
|
+
for (const c of clients) c.end();
|
|
242
|
+
clients.clear();
|
|
243
|
+
server.close(() => r());
|
|
244
|
+
})
|
|
245
|
+
});
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Start the bridge on `preferredPort`, falling back to an OS-assigned free port
|
|
251
|
+
* when that one is occupied — so a busy port never fails the launch. The page
|
|
252
|
+
* uses relative URLs, so the actual port is discovered, not assumed. The
|
|
253
|
+
* returned handle carries `fellBack: true` when it landed on a different port.
|
|
254
|
+
*/
|
|
255
|
+
async function startBridgePreferring({ preferredPort = DEFAULT_PORT, ...opts } = {}) {
|
|
256
|
+
try {
|
|
257
|
+
return {
|
|
258
|
+
...await startBridge({
|
|
259
|
+
...opts,
|
|
260
|
+
port: preferredPort
|
|
261
|
+
}),
|
|
262
|
+
fellBack: false
|
|
263
|
+
};
|
|
264
|
+
} catch (err) {
|
|
265
|
+
if (err?.code !== "EADDRINUSE") throw err;
|
|
266
|
+
return {
|
|
267
|
+
...await startBridge({
|
|
268
|
+
...opts,
|
|
269
|
+
port: 0
|
|
270
|
+
}),
|
|
271
|
+
fellBack: true,
|
|
272
|
+
preferredPort
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
//#endregion
|
|
277
|
+
export { DEFAULT_PORT, EDITOR_VERSION, PID_FILE, WORKING_DIR, deepEqual, listWorkingFiles, openBrowser, pidfilePath, processAlive, readPidfile, readWorkingFile, startBridge, startBridgePreferring };
|
|
278
|
+
|
|
279
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/live/index.ts"],"sourcesContent":["// The local live-preview bridge.\n//\n// It serves live/index.html (which loads the REAL Templatical editor from the\n// CDN), streams agent-driven template updates to the page over Server-Sent\n// Events, and buffers the page's hand-edits so the caller can detect divergence\n// (a user edit in the browser) before overwriting.\n//\n// This package's own `live` CLI command drives it today, over localhost HTTP.\n// It stays side-effect free at import time and writes nothing to stdout so\n// that a future stdio-based caller — an MCP server reserving stdout for\n// JSON-RPC — can be added without auditing this module first: a stray write\n// here would corrupt that protocol. Keep all human-facing output in the\n// callers (cli/output.ts is the CLI's own single writer;\n// tests/cli-output-discipline.test.ts enforces that no other module under\n// src/ touches stdout).\n\nimport { createServer, type Server, type ServerResponse } from \"node:http\";\nimport { spawn } from \"node:child_process\";\nimport { existsSync, readFileSync, readdirSync } from \"node:fs\";\nimport { dirname, isAbsolute, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nconst here = dirname(fileURLToPath(import.meta.url));\n\n// The CDN editor version the live harness loads. It is PINNED to this package's\n// schema version: schema.json is generated from @templatical/types, and types +\n// editor bump in lockstep (changesets fixed group), so the editor at this\n// version has the same block model the schema describes.\n//\n// Kept in step automatically by scripts/sync-pins.mjs at release time.\n// tests/cdn-pin.test.ts is the safety net that fails CI if it ever drifts.\nexport const EDITOR_VERSION = \"0.38.0\";\n\nexport const DEFAULT_PORT = 4747;\nexport const WORKING_DIR = \".templatical\";\nexport const PID_FILE = join(WORKING_DIR, \"live-server.pid\");\n\n// Resolved from this module rather than the cwd so it works identically from\n// src/live/ (tests) and dist/live/ (published) — both sit two levels under the\n// package root, where live/index.html ships.\nconst HARNESS_FILE = resolve(here, \"../../live/index.html\");\n\n// --------------------------------------------------------------------------\n// Pure helpers\n// --------------------------------------------------------------------------\n\n/** Order-insensitive structural equality for parsed-JSON template content. */\nexport function deepEqual(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n if (a === null || b === null) return false;\n if (typeof a !== \"object\" || typeof b !== \"object\") return false;\n const aArr = Array.isArray(a);\n if (aArr !== Array.isArray(b)) return false;\n if (aArr) {\n const aList = a as unknown[];\n const bList = b as unknown[];\n if (aList.length !== bList.length) return false;\n for (let i = 0; i < aList.length; i++) {\n if (!deepEqual(aList[i], bList[i])) return false;\n }\n return true;\n }\n const aObj = a as Record<string, unknown>;\n const bObj = b as Record<string, unknown>;\n const ak = Object.keys(aObj);\n const bk = Object.keys(bObj);\n if (ak.length !== bk.length) return false;\n for (const k of ak) {\n if (!Object.prototype.hasOwnProperty.call(bObj, k)) return false;\n if (!deepEqual(aObj[k], bObj[k])) return false;\n }\n return true;\n}\n\n/** Read + parse the working file, or return null when it is absent/unparseable. */\nexport function readWorkingFile(path: string): unknown {\n if (!existsSync(path)) return null;\n try {\n return JSON.parse(readFileSync(path, \"utf8\"));\n } catch {\n return null;\n }\n}\n\n/** List the working templates in a project's `.templatical/` folder, by name. */\nexport function listWorkingFiles(cwd: string): string[] {\n const dir = resolve(cwd, WORKING_DIR);\n if (!existsSync(dir)) return [];\n return readdirSync(dir)\n .filter((f) => f.endsWith(\".json\"))\n .sort();\n}\n\nasync function readJsonBody(req: NodeJS.ReadableStream): Promise<\n | {\n content?: unknown;\n baseline?: boolean;\n blockId?: string;\n text?: string;\n }\n | undefined\n> {\n const chunks: Buffer[] = [];\n for await (const chunk of req) chunks.push(chunk as Buffer);\n const raw = Buffer.concat(chunks).toString(\"utf8\");\n return raw ? JSON.parse(raw) : undefined;\n}\n\n/**\n * Open a URL in the user's default browser — best-effort and cross-platform.\n * A silent no-op where there's no browser (headless / CI / sandbox); callers\n * always surface the URL too, so nothing is lost when this does nothing.\n */\nexport function openBrowser(url: string): void {\n const [cmd, cmdArgs]: [string, string[]] =\n process.platform === \"darwin\"\n ? [\"open\", [url]]\n : process.platform === \"win32\"\n ? [\"cmd\", [\"/c\", \"start\", \"\", url]]\n : [\"xdg-open\", [url]];\n try {\n const child = spawn(cmd, cmdArgs, { stdio: \"ignore\", detached: true });\n child.on(\"error\", () => {}); // no browser available — ignore\n child.unref();\n } catch {\n /* ignore — the URL is surfaced by the caller regardless */\n }\n}\n\n// --------------------------------------------------------------------------\n// Pidfile helpers (used by this package's own `live` CLI command; a future\n// stdio-based MCP server would own its process lifecycle directly and would\n// not need them)\n// --------------------------------------------------------------------------\n\nexport interface PidfileInfo {\n pid: number;\n port: number;\n}\n\nexport function pidfilePath(cwd: string): string {\n return resolve(cwd, PID_FILE);\n}\n\nexport function readPidfile(cwd: string): PidfileInfo | null {\n const p = pidfilePath(cwd);\n if (!existsSync(p)) return null;\n try {\n return JSON.parse(readFileSync(p, \"utf8\")) as PidfileInfo;\n } catch {\n return null;\n }\n}\n\nexport function processAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * A note the user left in the browser, against a block or the template as a\n * whole. Delivered on GET /content - the call the agent already makes before\n * every change - so notes need no polling and no separate endpoint to drain.\n */\nexport interface Annotation {\n id: string;\n /** null for a note about the template rather than one block. */\n blockId: string | null;\n text: string;\n createdAt: number;\n}\n\n// --------------------------------------------------------------------------\n// Bridge server\n// --------------------------------------------------------------------------\n\nexport interface BridgeHandle {\n server: Server;\n port: number;\n url: string;\n /** The absolute path of the working file this bridge is serving. */\n workingPath: string;\n /** The page's latest state, for callers that drive the bridge in-process. */\n getEditorState: () => {\n divergent: boolean;\n content: unknown;\n annotations: Annotation[];\n };\n /** Re-read the working file and push it to every connected page. */\n reload: () => { ok: boolean; clients: number };\n close: () => Promise<void>;\n}\n\nexport interface StartBridgeOptions {\n cwd?: string;\n port?: number;\n file?: string;\n harnessFile?: string;\n}\n\n/**\n * Start the bridge HTTP server. Pure server + in-memory sync state; callers own\n * process lifecycle. Resolves once listening.\n *\n * The returned handle exposes `getEditorState` and `reload` directly, so an\n * in-process caller (the MCP server) never has to make an HTTP request to its\n * own bridge — that is the whole reason live mode can work inside a sandboxed\n * agent. The equivalent HTTP endpoints stay for the skill's out-of-process CLI.\n */\nexport function startBridge({\n cwd = process.cwd(),\n port = 0,\n file = join(WORKING_DIR, \"template.json\"),\n harnessFile = HARNESS_FILE,\n}: StartBridgeOptions = {}): Promise<BridgeHandle> {\n const workingPath = isAbsolute(file) ? file : resolve(cwd, file);\n\n // Sync state. `baseline` is the editor's NORMALIZED view of the caller's last\n // content (captured by the page right after it applies an update), so the\n // editor's own load-time normalization never reads as a user edit.\n // `editorCurrent` is the page's latest getContent(); `divergent` is true when\n // it structurally differs from `baseline` — i.e. the user hand-edited.\n const state: {\n baseline: unknown;\n editorCurrent: unknown;\n divergent: boolean;\n annotations: Annotation[];\n } = {\n baseline: null,\n editorCurrent: null,\n divergent: false,\n annotations: [],\n };\n const clients = new Set<ServerResponse>();\n\n function broadcastTemplate(content: unknown): void {\n const payload = `event: template\\ndata: ${JSON.stringify(content)}\\n\\n`;\n for (const res of clients) res.write(payload);\n }\n\n function getEditorState(): {\n divergent: boolean;\n content: unknown;\n annotations: Annotation[];\n } {\n return {\n divergent: state.divergent,\n content: state.editorCurrent,\n annotations: state.annotations,\n };\n }\n\n function reload(): { ok: boolean; clients: number } {\n // The caller wrote the working file; re-read and push it to the page. The\n // freshly-written file is the new baseline, so any pending user edit is\n // superseded — reset the divergence tracker.\n const content = readWorkingFile(workingPath);\n state.baseline = null;\n state.editorCurrent = null;\n state.divergent = false;\n // The caller has read these by the time it writes and reloads, so reload is\n // the resolve step: no separate protocol, and a note is never acted on twice.\n state.annotations = [];\n if (content !== null) broadcastTemplate(content);\n return { ok: true, clients: clients.size };\n }\n\n const server = createServer(async (req, res) => {\n const { pathname } = new URL(req.url ?? \"/\", \"http://localhost\");\n const method = req.method ?? \"GET\";\n\n try {\n if (\n method === \"GET\" &&\n (pathname === \"/\" || pathname === \"/index.html\")\n ) {\n const html = readFileSync(harnessFile, \"utf8\").replaceAll(\n \"{{EDITOR_VERSION}}\",\n EDITOR_VERSION,\n );\n res.writeHead(200, { \"content-type\": \"text/html; charset=utf-8\" });\n res.end(html);\n return;\n }\n\n if (method === \"GET\" && pathname === \"/template\") {\n const content = readWorkingFile(workingPath);\n if (content === null) {\n res.writeHead(204).end(); // no working file yet — page inits empty\n return;\n }\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(content));\n return;\n }\n\n if (method === \"GET\" && pathname === \"/events\") {\n res.writeHead(200, {\n \"content-type\": \"text/event-stream\",\n \"cache-control\": \"no-cache\",\n connection: \"keep-alive\",\n });\n res.write(\"event: ready\\ndata: {}\\n\\n\");\n clients.add(res);\n const ping = setInterval(() => res.write(\": ping\\n\\n\"), 15000);\n req.on(\"close\", () => {\n clearInterval(ping);\n clients.delete(res);\n });\n return;\n }\n\n if (method === \"POST\" && pathname === \"/content\") {\n const body = await readJsonBody(req);\n const content = body?.content;\n if (body?.baseline) {\n // Post-apply snapshot: this is the editor's normalized view of the\n // caller's content, not a user edit.\n state.baseline = content ?? null;\n state.editorCurrent = content ?? null;\n state.divergent = false;\n } else {\n state.editorCurrent = content ?? null;\n state.divergent =\n state.baseline !== null && !deepEqual(content, state.baseline);\n }\n res.writeHead(204).end();\n return;\n }\n\n if (method === \"GET\" && pathname === \"/content\") {\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(getEditorState()));\n return;\n }\n\n if (method === \"POST\" && pathname === \"/annotations\") {\n const body = await readJsonBody(req);\n const text = typeof body?.text === \"string\" ? body.text.trim() : \"\";\n if (!text) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(\"An annotation needs non-empty `text`.\");\n return;\n }\n const annotation: Annotation = {\n id: `a${state.annotations.length + 1}-${Date.now().toString(36)}`,\n blockId: typeof body?.blockId === \"string\" ? body.blockId : null,\n text,\n createdAt: Date.now(),\n };\n state.annotations.push(annotation);\n res.writeHead(201, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(annotation));\n return;\n }\n\n if (method === \"POST\" && pathname === \"/reload\") {\n const result = reload();\n res.writeHead(200, { \"content-type\": \"application/json\" });\n res.end(JSON.stringify(result));\n return;\n }\n\n res.writeHead(404, { \"content-type\": \"text/plain\" }).end(\"Not found\");\n } catch (err) {\n res.writeHead(400, { \"content-type\": \"text/plain\" });\n res.end(`Bad request: ${(err as Error).message}`);\n }\n });\n\n return new Promise((resolvePromise, rejectPromise) => {\n // listen() reports failures (e.g. EADDRINUSE) as an 'error' event, not a\n // throw — without this the error would be unhandled and crash the process.\n const onListenError = (err: Error) => rejectPromise(err);\n server.once(\"error\", onListenError);\n server.listen(port, \"127.0.0.1\", () => {\n server.removeListener(\"error\", onListenError);\n const address = server.address();\n const actualPort =\n typeof address === \"object\" && address !== null ? address.port : port;\n resolvePromise({\n server,\n port: actualPort,\n url: `http://localhost:${actualPort}/`,\n workingPath,\n getEditorState,\n reload,\n close: () =>\n new Promise<void>((r) => {\n for (const c of clients) c.end();\n clients.clear();\n server.close(() => r());\n }),\n });\n });\n });\n}\n\nexport interface PreferringHandle extends BridgeHandle {\n fellBack: boolean;\n preferredPort?: number;\n}\n\n/**\n * Start the bridge on `preferredPort`, falling back to an OS-assigned free port\n * when that one is occupied — so a busy port never fails the launch. The page\n * uses relative URLs, so the actual port is discovered, not assumed. The\n * returned handle carries `fellBack: true` when it landed on a different port.\n */\nexport async function startBridgePreferring({\n preferredPort = DEFAULT_PORT,\n ...opts\n}: StartBridgeOptions & {\n preferredPort?: number;\n} = {}): Promise<PreferringHandle> {\n try {\n const handle = await startBridge({ ...opts, port: preferredPort });\n return { ...handle, fellBack: false };\n } catch (err) {\n if ((err as NodeJS.ErrnoException)?.code !== \"EADDRINUSE\") throw err;\n const handle = await startBridge({ ...opts, port: 0 });\n return { ...handle, fellBack: true, preferredPort };\n }\n}\n"],"mappings":";;;;;;AAsBA,MAAM,OAAO,QAAQ,cAAc,YAAY,GAAG,CAAC;AASnD,MAAa,iBAAiB;AAE9B,MAAa,eAAe;AAC5B,MAAa,cAAc;AAC3B,MAAa,WAAW,KAAK,aAAa,iBAAiB;AAK3D,MAAM,eAAe,QAAQ,MAAM,uBAAuB;;AAO1D,SAAgB,UAAU,GAAY,GAAqB;CACzD,IAAI,MAAM,GAAG,OAAO;CACpB,IAAI,MAAM,QAAQ,MAAM,MAAM,OAAO;CACrC,IAAI,OAAO,MAAM,YAAY,OAAO,MAAM,UAAU,OAAO;CAC3D,MAAM,OAAO,MAAM,QAAQ,CAAC;CAC5B,IAAI,SAAS,MAAM,QAAQ,CAAC,GAAG,OAAO;CACtC,IAAI,MAAM;EACR,MAAM,QAAQ;EACd,MAAM,QAAQ;EACd,I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