@templatical/template-tools 0.42.0 → 0.43.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/dist/bin.js +8 -5
- package/dist/bin.js.map +1 -1
- package/dist/index.js +1 -1
- package/dist/live/index.d.ts +10 -2
- package/dist/live/index.js +90 -11
- package/dist/live/index.js.map +1 -1
- package/dist/{src-CwsdECiz.js → src-CkO7GQ3s.js} +17 -5
- package/dist/{src-CwsdECiz.js.map → src-CkO7GQ3s.js.map} +1 -1
- package/live/index.html +904 -119
- package/package.json +13 -13
- package/schema.json +10 -1
package/dist/bin.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as validateTemplate, i as schema, r as runQualityLint, t as applyOperation } from "./src-
|
|
2
|
+
import { a as validateTemplate, i as schema, r as runQualityLint, t as applyOperation } from "./src-CkO7GQ3s.js";
|
|
3
3
|
import { DEFAULT_PORT, WORKING_DIR, listWorkingFiles, openBrowser, pidfilePath, processAlive, readPidfile, readWorkingFile, startBridgePreferring } from "./live/index.js";
|
|
4
4
|
import { existsSync, mkdirSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
|
|
5
5
|
import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
@@ -548,10 +548,11 @@ function runList(args) {
|
|
|
548
548
|
emit({ templates }, () => templates.length === 0 ? `No templates in ${WORKING_DIR}/` : templates.map((t) => ` ${t.name}${t.title ? ` - ${t.title}` : ""}`).join("\n"));
|
|
549
549
|
return EXIT.ok;
|
|
550
550
|
}
|
|
551
|
-
async function postTo(port, path) {
|
|
551
|
+
async function postTo(port, path, body) {
|
|
552
552
|
return fetch(`http://localhost:${port}${path}`, {
|
|
553
553
|
method: "POST",
|
|
554
|
-
headers: { "content-type": "application/json" }
|
|
554
|
+
headers: { "content-type": "application/json" },
|
|
555
|
+
body: body === void 0 ? void 0 : JSON.stringify(body)
|
|
555
556
|
});
|
|
556
557
|
}
|
|
557
558
|
async function runLive(args) {
|
|
@@ -561,10 +562,12 @@ async function runLive(args) {
|
|
|
561
562
|
const info = readPidfile(cwd);
|
|
562
563
|
if (!info || !processAlive(info.pid)) throw new UsageError(`No live server is running here (no live pidfile at ${WORKING_DIR}/live-server.pid).`);
|
|
563
564
|
if (sub === "reload") {
|
|
564
|
-
const
|
|
565
|
+
const consumeAnnotations = args.flags["consume-annotations"] === true;
|
|
566
|
+
const body = await (await postTo(info.port, "/reload", consumeAnnotations ? { consumeAnnotations: true } : void 0)).json().catch(() => ({}));
|
|
565
567
|
emit({
|
|
566
568
|
reloaded: true,
|
|
567
|
-
clients: body.clients ?? 0
|
|
569
|
+
clients: body.clients ?? 0,
|
|
570
|
+
consumed: body.consumed === true
|
|
568
571
|
}, () => `Pushed the working file to ${body.clients ?? 0} connected page(s).`);
|
|
569
572
|
return EXIT.ok;
|
|
570
573
|
}
|
package/dist/bin.js.map
CHANGED
|
@@ -1 +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// (ESM-only: `exports` exposes only the \"import\" condition, never \"require\"\n// 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(`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AC3B;CACA,IAAI,eAAe,wBAAwB;EACzC,KAAK,IAAI,OAAO;EAChB,QAAQ,KAAK,KAAK,UAAU;CAC9B;CACA,IAAI,eAAe,YAAY;EAC7B,KAAK,IAAI,OAAO;EAChB,QAAQ,KAAK,KAAK,KAAK;CACzB;CACA,KAAK,qBAAsB,KAAe,WAAW,OAAO,GAAG,GAAG;CAClE,QAAQ,KAAK,KAAK,KAAK;AACzB,CAAC"}
|
|
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// (ESM-only: `exports` exposes only the \"import\" condition, never \"require\"\n// 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(\n port: number,\n path: string,\n body?: unknown,\n): Promise<Response> {\n return fetch(`http://localhost:${port}${path}`, {\n method: \"POST\",\n headers: { \"content-type\": \"application/json\" },\n body: body === undefined ? undefined : JSON.stringify(body),\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 consumeAnnotations = args.flags[\"consume-annotations\"] === true;\n const res = await postTo(\n info.port,\n \"/reload\",\n consumeAnnotations ? { consumeAnnotations: true } : undefined,\n );\n const body = (await res.json().catch(() => ({}))) as {\n clients?: number;\n consumed?: boolean;\n };\n emit(\n {\n reloaded: true,\n clients: body.clients ?? 0,\n consumed: body.consumed === true,\n },\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;AACF,CAAC;AAUD,SAA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3B;CACA,IAAI,eAAe,wBAAwB;EACzC,KAAK,IAAI,OAAO;EAChB,QAAQ,KAAK,KAAK,UAAU;CAC9B;CACA,IAAI,eAAe,YAAY;EAC7B,KAAK,IAAI,OAAO;EAChB,QAAQ,KAAK,KAAK,KAAK;CACzB;CACA,KAAK,qBAAsB,KAAe,WAAW,OAAO,GAAG,GAAG;CAClE,QAAQ,KAAK,KAAK,KAAK;AACzB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as validateTemplate, i as schema, n as getColumnCount, r as runQualityLint, t as applyOperation } from "./src-
|
|
1
|
+
import { a as validateTemplate, i as schema, n as getColumnCount, r as runQualityLint, t as applyOperation } from "./src-CkO7GQ3s.js";
|
|
2
2
|
export { applyOperation, getColumnCount, runQualityLint, schema, validateTemplate };
|
package/dist/live/index.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Server } from "node:http";
|
|
2
2
|
//#region src/live/index.d.ts
|
|
3
|
-
export declare const EDITOR_VERSION = "0.
|
|
3
|
+
export declare const EDITOR_VERSION = "0.43.0";
|
|
4
4
|
export declare const DEFAULT_PORT = 4747;
|
|
5
5
|
export declare const WORKING_DIR = ".templatical";
|
|
6
6
|
export declare const PID_FILE: string;
|
|
@@ -32,6 +32,11 @@ export interface Annotation {
|
|
|
32
32
|
id: string;
|
|
33
33
|
/** null for a note about the template rather than one block. */
|
|
34
34
|
blockId: string | null;
|
|
35
|
+
/** The next data-block-id above the target. null at the top level and for a template note. */
|
|
36
|
+
parentBlockId: string | null;
|
|
37
|
+
blockType: string | null;
|
|
38
|
+
/** Snapshot of the block's text at save time, already truncated. */
|
|
39
|
+
label: string;
|
|
35
40
|
text: string;
|
|
36
41
|
createdAt: number;
|
|
37
42
|
}
|
|
@@ -48,9 +53,12 @@ export interface BridgeHandle {
|
|
|
48
53
|
annotations: Annotation[];
|
|
49
54
|
};
|
|
50
55
|
/** Re-read the working file and push it to every connected page. */
|
|
51
|
-
reload: (
|
|
56
|
+
reload: (options?: {
|
|
57
|
+
consumeAnnotations?: boolean;
|
|
58
|
+
}) => {
|
|
52
59
|
ok: boolean;
|
|
53
60
|
clients: number;
|
|
61
|
+
consumed: boolean;
|
|
54
62
|
};
|
|
55
63
|
close: () => Promise<void>;
|
|
56
64
|
}
|
package/dist/live/index.js
CHANGED
|
@@ -5,7 +5,7 @@ import { dirname, isAbsolute, join, resolve } from "node:path";
|
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
6
|
//#region src/live/index.ts
|
|
7
7
|
const here = dirname(fileURLToPath(import.meta.url));
|
|
8
|
-
const EDITOR_VERSION = "0.
|
|
8
|
+
const EDITOR_VERSION = "0.43.0";
|
|
9
9
|
const DEFAULT_PORT = 4747;
|
|
10
10
|
const WORKING_DIR = ".templatical";
|
|
11
11
|
const PID_FILE = join(WORKING_DIR, "live-server.pid");
|
|
@@ -97,6 +97,41 @@ function processAlive(pid) {
|
|
|
97
97
|
return false;
|
|
98
98
|
}
|
|
99
99
|
}
|
|
100
|
+
const NOTE_TEXT_MAX = 2e3;
|
|
101
|
+
const NOTE_LABEL_MAX = 80;
|
|
102
|
+
const NOTE_BLOCK_TYPE_MAX = 40;
|
|
103
|
+
const NOTE_QUEUE_MAX = 40;
|
|
104
|
+
function readNoteText(value) {
|
|
105
|
+
const text = typeof value === "string" ? value.trim() : "";
|
|
106
|
+
if (!text) return { error: "An annotation needs non-empty `text`." };
|
|
107
|
+
if (text.length > NOTE_TEXT_MAX) return { error: "A note can be at most 2000 characters." };
|
|
108
|
+
return { text };
|
|
109
|
+
}
|
|
110
|
+
function readOptionalId(value) {
|
|
111
|
+
return typeof value === "string" ? value : null;
|
|
112
|
+
}
|
|
113
|
+
function readBlockType(value) {
|
|
114
|
+
if (typeof value !== "string") return null;
|
|
115
|
+
return value.trim().slice(0, NOTE_BLOCK_TYPE_MAX);
|
|
116
|
+
}
|
|
117
|
+
function readLabel(value) {
|
|
118
|
+
if (typeof value !== "string") return "";
|
|
119
|
+
return value.replace(/\s+/g, " ").trim().slice(0, NOTE_LABEL_MAX);
|
|
120
|
+
}
|
|
121
|
+
function annotationIdFromPath(pathname) {
|
|
122
|
+
if (!pathname.startsWith("/annotations/")) return null;
|
|
123
|
+
const raw = pathname.slice(13);
|
|
124
|
+
if (!raw || raw.includes("/")) return null;
|
|
125
|
+
try {
|
|
126
|
+
return decodeURIComponent(raw);
|
|
127
|
+
} catch {
|
|
128
|
+
return null;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function noteNotFound(res) {
|
|
132
|
+
res.writeHead(404, { "content-type": "text/plain" });
|
|
133
|
+
res.end("No note with that id.");
|
|
134
|
+
}
|
|
100
135
|
/**
|
|
101
136
|
* Start the bridge HTTP server. Pure server + in-memory sync state; callers own
|
|
102
137
|
* process lifecycle. Resolves once listening.
|
|
@@ -114,6 +149,10 @@ function startBridge({ cwd = process.cwd(), port = 0, file = join(WORKING_DIR, "
|
|
|
114
149
|
divergent: false,
|
|
115
150
|
annotations: []
|
|
116
151
|
};
|
|
152
|
+
let nextAnnotationNumber = 1;
|
|
153
|
+
function mintAnnotationId() {
|
|
154
|
+
return `a${nextAnnotationNumber++}-${Date.now().toString(36)}`;
|
|
155
|
+
}
|
|
117
156
|
const clients = /* @__PURE__ */ new Set();
|
|
118
157
|
function broadcastTemplate(content) {
|
|
119
158
|
const payload = `event: template\ndata: ${JSON.stringify(content)}\n\n`;
|
|
@@ -126,16 +165,18 @@ function startBridge({ cwd = process.cwd(), port = 0, file = join(WORKING_DIR, "
|
|
|
126
165
|
annotations: state.annotations
|
|
127
166
|
};
|
|
128
167
|
}
|
|
129
|
-
function reload() {
|
|
168
|
+
function reload(options) {
|
|
130
169
|
const content = readWorkingFile(workingPath);
|
|
131
170
|
state.baseline = null;
|
|
132
171
|
state.editorCurrent = null;
|
|
133
172
|
state.divergent = false;
|
|
134
|
-
|
|
173
|
+
const consumed = options?.consumeAnnotations === true && content !== null;
|
|
174
|
+
if (consumed) state.annotations = [];
|
|
135
175
|
if (content !== null) broadcastTemplate(content);
|
|
136
176
|
return {
|
|
137
177
|
ok: true,
|
|
138
|
-
clients: clients.size
|
|
178
|
+
clients: clients.size,
|
|
179
|
+
consumed
|
|
139
180
|
};
|
|
140
181
|
}
|
|
141
182
|
const server = createServer(async (req, res) => {
|
|
@@ -194,16 +235,27 @@ function startBridge({ cwd = process.cwd(), port = 0, file = join(WORKING_DIR, "
|
|
|
194
235
|
}
|
|
195
236
|
if (method === "POST" && pathname === "/annotations") {
|
|
196
237
|
const body = await readJsonBody(req);
|
|
197
|
-
const
|
|
198
|
-
if (
|
|
238
|
+
const parsed = readNoteText(body?.text);
|
|
239
|
+
if ("error" in parsed) {
|
|
240
|
+
res.writeHead(400, { "content-type": "text/plain" });
|
|
241
|
+
res.end(parsed.error);
|
|
242
|
+
return;
|
|
243
|
+
}
|
|
244
|
+
if (state.annotations.length >= NOTE_QUEUE_MAX) {
|
|
199
245
|
res.writeHead(400, { "content-type": "text/plain" });
|
|
200
|
-
res.end("
|
|
246
|
+
res.end("The note queue is full (40).");
|
|
201
247
|
return;
|
|
202
248
|
}
|
|
249
|
+
const blockId = readOptionalId(body?.blockId);
|
|
250
|
+
let parentBlockId = readOptionalId(body?.parentBlockId);
|
|
251
|
+
if (parentBlockId === blockId) parentBlockId = null;
|
|
203
252
|
const annotation = {
|
|
204
|
-
id:
|
|
205
|
-
blockId
|
|
206
|
-
|
|
253
|
+
id: mintAnnotationId(),
|
|
254
|
+
blockId,
|
|
255
|
+
parentBlockId,
|
|
256
|
+
blockType: readBlockType(body?.blockType),
|
|
257
|
+
label: readLabel(body?.label),
|
|
258
|
+
text: parsed.text,
|
|
207
259
|
createdAt: Date.now()
|
|
208
260
|
};
|
|
209
261
|
state.annotations.push(annotation);
|
|
@@ -211,8 +263,35 @@ function startBridge({ cwd = process.cwd(), port = 0, file = join(WORKING_DIR, "
|
|
|
211
263
|
res.end(JSON.stringify(annotation));
|
|
212
264
|
return;
|
|
213
265
|
}
|
|
266
|
+
const noteId = annotationIdFromPath(pathname);
|
|
267
|
+
if (noteId && (method === "PUT" || method === "DELETE")) {
|
|
268
|
+
const index = state.annotations.findIndex((note) => note.id === noteId);
|
|
269
|
+
if (index < 0) {
|
|
270
|
+
noteNotFound(res);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (method === "DELETE") {
|
|
274
|
+
state.annotations.splice(index, 1);
|
|
275
|
+
res.writeHead(204).end();
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
const parsed = readNoteText((await readJsonBody(req))?.text);
|
|
279
|
+
if ("error" in parsed) {
|
|
280
|
+
res.writeHead(400, { "content-type": "text/plain" });
|
|
281
|
+
res.end(parsed.error);
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
284
|
+
const updated = {
|
|
285
|
+
...state.annotations[index],
|
|
286
|
+
text: parsed.text
|
|
287
|
+
};
|
|
288
|
+
state.annotations[index] = updated;
|
|
289
|
+
res.writeHead(200, { "content-type": "application/json" });
|
|
290
|
+
res.end(JSON.stringify(updated));
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
214
293
|
if (method === "POST" && pathname === "/reload") {
|
|
215
|
-
const result = reload();
|
|
294
|
+
const result = reload({ consumeAnnotations: (await readJsonBody(req))?.consumeAnnotations === true });
|
|
216
295
|
res.writeHead(200, { "content-type": "application/json" });
|
|
217
296
|
res.end(JSON.stringify(result));
|
|
218
297
|
return;
|