diff --git a/README.md b/README.md index d8587f4..fe9d89f 100644 --- a/README.md +++ b/README.md @@ -1,149 +1,211 @@ # LastState CLI -> **v1.2.0.** Scaffold + build + flash + test + mock + ingest + analyze + symbolicate + stack (`up/down/ps/logs/status/sim/deploy/doctor`) + brand logo in every banner. -> `test` is honest: anything it cannot verify prints `-`, never a false pass. Real validation via `protocol/test-vectors/` and `latch/hil/`. +One command line for the Latch → LEP → Relay → Trace loop: scaffold the Latch +integration, build and flash firmware, run the stack locally, and decode +captured envelopes. -## Installation +[![CI workflow status on master](https://github.com/laststate/cli/actions/workflows/ci.yml/badge.svg?branch=master)](https://github.com/laststate/cli/actions/workflows/ci.yml) +[![Licensed under Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue.svg)](LICENSE) +[![Requires Node 18 or newer](https://img.shields.io/badge/node-18%2B-339933.svg)](package.json) -Requires Node 18+: +> **Status:** `v1.2.0`, CI green on `master`. The first tagged release is +> pending; until it ships, install from source. Hardware evidence lives in the +> [Latch repository](https://github.com/laststate/latch). -```bash -npm install -g laststate-cli -laststate --help +## What it does + +- **Firmware:** `init` scaffolds the Latch integration files for ESP32, + Cortex-M, RISC-V, Zephyr, Arduino or host; `build` drives CMake and `ctest`; + `flash` calls `idf.py`, `west` or OpenOCD. +- **Stack:** `up` starts the LastState compose stack, `sim` runs a virtual + fleet, and `mock` serves Trace/Relay endpoints without Docker. +- **Evidence:** `test` checks the integration against LEP vectors; `ingest`, + `analyze` and `symbolicate` move and decode captures. +- **Operations:** `config` and `doctor` keep endpoints, secrets and toolchains + honest. + +The CLI is glue: it drives the component repos' public commands and APIs, and +prints `-` when it cannot verify something. + +## Install + +Node 18+. + +### From source (works today) + +```sh +git clone https://github.com/laststate/cli.git +cd cli +npm ci +npm run build +npm link # exposes `laststate` and `ls` laststate doctor ``` -Global flags on **every** command: +### From npm (pending first release) -```text ---json --yes --verbose --quiet --no-color --no-banner --profile +```sh +# 404 until the first tagged release is published +npm install -g laststate-cli ``` -`--json` disables colors/banners/spinners and emits machine-readable JSON. `CI=true` also disables the banner. +The package is not on the registry yet; the first tagged release will publish +it. Until then, use the source install above. + +## Quickstart -## Brand / logo +`laststate` is a driver, not a project generator: it runs against your firmware +checkout and the [LastState stack](https://github.com/laststate/laststate). -No animation, no images: every banner shows the **ASCII logo** (truecolor Braille generated from the real pixels of `cli/assets/brand.png` — swoosh, slashes and wordmark). Brand-tone spinners and `◆` as the success mark: +### Check the environment -```bash -laststate brand # ASCII logo -laststate brand --json # brand metadata for scripts +```sh +laststate doctor +``` + +`doctor` reports tools, config, secrets and live endpoints. It prints `-` for +anything it cannot check (a stack that is not running, for example) and exits +nonzero only when a required check fails. + +### Run the stack + +```sh +git clone --recurse-submodules https://github.com/laststate/laststate.git +cd laststate +laststate up --open +laststate sim run --scenario crash-storm +laststate status +laststate down ``` -To regenerate the PNG from the vector: `assets/brand-source.html` + headless Edge screenshot at 2176×266. +`up` runs `docker compose` from the repo root, waits for health and can open +the Trace UI. `--appliance` uses `docker-compose.appliance.yml`; `--no-sim` +skips the simulator. `sim run` accepts `demo`, `steady`, `crash-storm`, +`outage`, `recovery` or `boot-loop`. -## Quickstart (4 min) +### Add Latch to firmware -```bash +```sh laststate init --project-name Demo --target cortex-m --yes -cd Demo -laststate build --preset host-debug # cmake presets + ctest -laststate mock --port 8080 & # mock Trace/Relay -laststate test --verbose # probes + LEP vectors -laststate ingest crash.lep --to relay --url http://localhost:8384 -laststate analyze crash.lep ``` -Firmware (`main.c` generated): - -```c -#include - -void app_init(void) { - static ls_config_t cfg = { - .device_id = "demo-001", - .firmware_version = "v1.0.0", - .build_id = "dev-build", - }; - ls_init(&cfg); - /* ls_transport_register(uart_transport); -- before ls_boot() */ - ls_boot(); - ls_breadcrumb("app:init"); -} +`init` creates `Demo/` with `laststate.yaml`, a Latch `main.c`, `.gitignore` +and `CMakeLists.patch.txt` (plus `partition.csv` for ESP32). It does **not** +create a buildable project: merge the patch into your own `CMakeLists.txt`, +add Latch under `third_party/latch`, and provide the CMake preset that +`build` will use. Latch's own `CMakePresets.json` is the reference for +`host-debug`, `arm-cortex-m4`, `riscv32` and `riscv64`. + +With those in place, `laststate build`, `laststate flash` and +`laststate test` run against your project. `test` probes includes, +`ls_boot()` wiring and the LEP vectors it can find; anything it cannot +verify prints `-`, never a false pass. + +The generated `laststate.yaml` carries a local-only `dev-` ingest token. +Replace it before sharing the project or pointing it at a shared Relay; +`laststate config generate-secrets` writes strong values to `.env`, which take +precedence over the project file. + +## Inspect a capture + +```sh +laststate analyze capture.lep +laststate analyze capture.lep --output-format json +laststate ingest capture.lep --to relay --url http://localhost:8384 ``` -## Commands +`analyze` accepts `.lep`, `.hex` and `.bin`, checks the header and CRCs, walks +TLVs and can deframe `raw`, `latch-stream` or `cobs`. A protocol vector works +as a known-good input: +`laststate analyze ../protocol/test-vectors/valid/lep-v2-basic.hex`. + +`ingest` posts to Relay or Trace with a rate/ETA bar and reports the event ID. +`symbolicate upload-artifact` stores an ELF in Trace; `symbolicate resolve` +uses `llvm-symbolizer` or `addr2line` locally. + +## Common commands -### Project / firmware +### Firmware | Command | What it does | -|---|---| -| `laststate init [--project-name --target esp32\|cortex-m\|riscv\|riscv64\|zephyr\|arduino\|host --lep 1\|2 --storage --relay-url --trace-url --no-git --yes]` | Wizard (clack) + scaffold `laststate.yaml`, `main.c` (correct `ls_config_t` API), `CMakeLists.patch.txt`, `partition.csv` for ESP32, best-effort `git init` | -| `laststate build [--preset --clean --jobs]` | `cmake --preset + --build + ctest` as a live checklist, preset suggested from `target` | -| `laststate flash [--port --baud --no-monitor]` | `idf.py flash` (esp32) / `west flash` (zephyr) / `openocd` (cortex-m), confirms port | -| `laststate test [--verbose --filter --vectors-path]` | `✓/✗/-`: yaml schema, latch includes, `transport_register`+`ls_boot` grep, `protocol/test-vectors` (valid must pass, invalid must reject), spool/HIL as `-` | -| `laststate ingest|send [file\|dir] [--to relay\|trace --url --token]` | `POST octet-stream` with rate/ETA bar, `201/200+X-Event-ID` (relay) / `202` (trace), dev-token warning | -| `laststate analyze [--output-format json\|text]` | 24B header, `header_crc`+`payload_crc` (CRC32), TLVs `1..22/0x20/0x30/0x8000`, deframing `raw|latch-stream|cobs|len-prefix`, accepts `.hex` | -| `laststate symbolicate upload-artifact / resolve --elf ` | `POST /v1/artifacts` or local `llvm-symbolizer/addr2line` (checks `build_id`) | +| --- | --- | +| `laststate init` | Scaffold Latch integration files for `esp32`, `cortex-m`, `riscv`, `riscv64`, `zephyr`, `arduino` or `host`. | +| `laststate build` | Configure and build with CMake presets, then run `ctest`. | +| `laststate flash` | Flash through `idf.py`, `west` or OpenOCD. | +| `laststate test` | Static integration probes plus LEP vectors; `✓`/`✗`/`-` per check. | -### Mock / stack / deploy +### Stack | Command | What it does | -|---|---| -| `laststate mock [--port --host --require-auth --token --no-cors]` | Mirrors the real thing: `POST /v1/ingest→201/200`, `POST /v1/events→202`, `POST /v1/events:batch`, `GET /v1/{ingest,relay}/capabilities`, `/health/live\|ready`, `/metrics`, optional Bearer | -| `laststate up [--appliance --build --no-sim --services a,b --wait-timeout --open]` | `docker compose up -d` as a live checklist, Trace+Relay health-wait, URL table | -| `laststate down [--appliance --volumes]` / `ps` / `logs [svc] [--follow --tail]` / `status [--url]` | Manages and audits the stack | -| `laststate sim run [--scenario demo\|steady\|crash-storm\|outage\|recovery\|boot-loop --rate --devices --duration]` / `sim stop` | Brings up the `simulator` service with `SIM_*` | -| `laststate deploy --env local\|production\|appliance\|k8s` | `generate-secrets --only-missing` + `preflight` gate (prod) + `compose up --build`; k8s prints a hint | -| `laststate config list\|get\|set\|paths\|generate-secrets\|preflight` | Real YAML + masked `.env` + global `conf`; never logs a literal secret | -| `laststate doctor [--fix]` | Tools (git/docker/cmake/node), `laststate.yaml`, `.env`, `relay-config.yaml` (`env:` refs, no literals), preflight, live endpoints | -| `laststate update` | Checks `npm view laststate-cli version` | -| `laststate brand` | ASCII logo (braille dots) / `--json` metadata | - -### Config - -```bash -laststate config list -laststate config get trace_url -laststate config set trace_url http://localhost:8080 -laststate config generate-secrets --only-missing -laststate config preflight --deploy-env production -laststate config paths -``` +| --- | --- | +| `laststate up` / `down` / `ps` / `logs` / `status` | Start, stop, list, tail or health-check the compose stack. | +| `laststate sim run` / `sim stop` | Run the virtual fleet with a named scenario. | +| `laststate deploy` | Secrets, preflight and `compose up` for `local`, `production`, `appliance` or `k8s`. | +| `laststate doctor` | Audit tools, config, secrets and live endpoints. | +| `laststate mock` | Serve Trace/Relay endpoints for development without Docker. | -Precedence: `--flag > env (TRACE_URL, LASTSTATE_*_TOKEN) > laststate.yaml > global conf > default`. +### Captures and config -## Examples +| Command | What it does | +| --- | --- | +| `laststate ingest` (alias `send`) | POST `.lep` files to Relay or Trace. | +| `laststate analyze` | Decode header, CRCs, TLVs and framing; text or JSON. | +| `laststate symbolicate` | `upload-artifact` to Trace or `resolve` addresses locally. | +| `laststate config` | `list`, `get`, `set`, `paths`, `generate-secrets`, `preflight`. | +| `laststate billing` | `status`, `checkout`, `portal`, `watch` against billing-service. | +| `laststate update` | Check for a newer CLI version. | -```bash -# interactive init per target -laststate init --target esp32 +Per-command flags: `laststate --help`. Global flags on every command: -# vectors only + json for CI -laststate test --json --verbose +```text +--json --yes --verbose --quiet --no-color --no-banner --profile +``` -# whole directory analyze in json -laststate analyze ./captures --output-format json +`--json` disables colors, banners and spinners and emits machine-readable +output. `CI=true` also disables the banner. -# batch ingest to prod trace -laststate ingest ./captures --to trace --url https://trace.example.com --token $LASTSTATE_COMPANY_TOKEN +## Configuration -# appliance stack without sim -laststate up --appliance --build -laststate ps && laststate status -laststate logs relay --tail 50 -laststate down +Precedence: `--flag > env > laststate.yaml > global conf > default`. Common +environment names are `TRACE_URL`, `RELAY_URL` and `LASTSTATE_*_TOKEN`. -# prod deploy (fails on REPLACE_ME/weak) -laststate deploy --env production +```sh +laststate config list +laststate config get trace_url +laststate config set trace_url http://localhost:8080 +laststate config generate-secrets --only-missing +laststate config preflight --deploy-env production +laststate config paths ``` -## Experience (animations) - -- **Live checklist** in `init`, `build`, `up`, `deploy`: each step goes `○ → ◜ → ✓/✗` with duration; failures print the error and abort as before. -- **Spinners with duration**: every `withSpinner` ends in `◆ · 3.1s`; `up` shows URL + elapsed seconds during the health-check. -- **Bars with rate and ETA**: `ingest` shows `files/s`, KB sent and ETA; same base in `build`. -- **Wizard with `@clack/prompts`**: `init` (name + target), `flash` (port + confirmation), `sim` (scenario), `deploy` (env), `ingest` (file) — arrows, defaults and clean `Ctrl+C` ("Cancelled.", exit 1). -- **Closing line**: `◆ … · done in Xs` at the end of `init`, `build`, `up`, `deploy`. -- General rule: everything turns off with `--json` / `--quiet` / `--no-banner` / `CI=true` / no TTY (checklist becomes static lines, bars become noops). +`config generate-secrets` fills only missing or weak values. `config preflight` +fails on `REPLACE_ME` placeholders and weak secrets before a production deploy. -## Tests +## Development -```bash -npm test # vitest: lep, env-manager, validate, wiring, tasks, ui (40 tests) -npm run build # tsc → dist/ +```sh +npm ci +npm test # vitest: LEP codec, config, validation, wiring, tasks, UI +npm run build # tsc -> dist/ +npm run lint ``` +To release, push a `vX.Y.Z` tag equal to `package.json`. The release workflow +builds and tests, publishes to npm (OIDC trusted publishing or `NPM_TOKEN`), +packs the tarball, smoke-tests the published package and creates the GitHub +release. + ## Documentation -Full docs: https://docs.laststate.io — quickstarts in `docs/quickstarts/`, HIL in `latch/hil/`, vectors in `protocol/test-vectors/`. +| Topic | Where | +| --- | --- | +| Latch runtime and HIL evidence | [laststate/latch](https://github.com/laststate/latch) | +| LEP wire format and vectors | [laststate/protocol](https://github.com/laststate/protocol) | +| Relay gateway | [laststate/relay](https://github.com/laststate/relay) | +| Trace backend and UI | [laststate/trace](https://github.com/laststate/trace) | +| Full self-hosted stack | [laststate/laststate](https://github.com/laststate/laststate) | +| Billing realtime contract | [docs/BILLING_REALTIME.md](docs/BILLING_REALTIME.md) | + +## License + +Apache-2.0. See [LICENSE](LICENSE). diff --git a/src/commands/ingest.ts b/src/commands/ingest.ts index 6d64c53..963b4fa 100644 --- a/src/commands/ingest.ts +++ b/src/commands/ingest.ts @@ -64,7 +64,7 @@ export async function ingest(input: string | undefined, rawOpts: IngestOpts) { } const endpoint = to === "trace" ? `${url.replace(/\/$/, "")}/v1/ingest` : `${url.replace(/\/$/, "")}/v1/ingest`; - const bar = progressBar(files.length, "ingest", "arq"); + const bar = progressBar(files.length, "ingest", "file"); const results: Array<{ file: string; id?: string; status?: number; duplicate?: boolean; error?: string }> = []; let sentBytes = 0; for (const f of files) { @@ -81,7 +81,7 @@ export async function ingest(input: string | undefined, rawOpts: IngestOpts) { }); const body = await res.text().catch(() => ""); let parsed: { id?: string; duplicate?: boolean } = {}; - try { parsed = JSON.parse(body); } catch { /* noop */ } + try { parsed = JSON.parse(body); } catch { /* ignore */ } const id = res.headers.get("X-Last-State-Event-ID") ?? parsed.id; results.push({ file: basename(f), id: id ?? undefined, status: res.status, duplicate: parsed.duplicate }); if (![200, 201, 202].includes(res.status)) { diff --git a/src/commands/init.ts b/src/commands/init.ts index 086322f..b4db5ff 100644 --- a/src/commands/init.ts +++ b/src/commands/init.ts @@ -21,33 +21,62 @@ export interface InitOpts { yes?: boolean; } +const TARGET_ARCH: Record = { + esp32: "LS_ARCH_XTENSA", + "cortex-m": "LS_ARCH_CORTEX_M", + riscv: "LS_ARCH_RISCV", + riscv64: "LS_ARCH_RISCV64", + // Zephyr and Arduino run on many cores; pick the real one in main.c. + zephyr: "LS_ARCH_UNKNOWN", + arduino: "LS_ARCH_UNKNOWN", + host: "LS_ARCH_LINUX", +}; + const TARGET_PRESET: Record = { - esp32: "add_subdirectory(third_party/latch) # then idf_component_register / target_link_libraries(${PROJECT_NAME} PRIVATE laststate::latch)", + // ESP-IDF builds latch as an IDF component: latch/CMakeLists.txt returns + // early under ESP_PLATFORM, so the laststate::latch alias never exists + // there. Use the component manager and REQUIRES latch. + esp32: "# esp-idf: add latch as an IDF component (idf_component.yml -> latch: path: third_party/latch), then idf_component_register(SRCS \"main.c\" INCLUDE_DIRS \".\" REQUIRES latch)", "cortex-m": "add_subdirectory(third_party/latch)\ntarget_link_libraries(${PROJECT_NAME} PRIVATE laststate::latch)", riscv: "add_subdirectory(third_party/latch)\ntarget_link_libraries(${PROJECT_NAME} PRIVATE laststate::latch)", riscv64: "add_subdirectory(third_party/latch)\ntarget_link_libraries(${PROJECT_NAME} PRIVATE laststate::latch)", - zephyr: "# zephyr: add latch as west module, then target_link_libraries(app PRIVATE laststate::latch)", - arduino: "# arduino: copy latch/ into lib/, #include ", + // Zephyr builds latch as a west module whose library target is + // laststate_latch (zephyr/CMakeLists.txt), not laststate::latch. + zephyr: "# zephyr: add latch as a west module, then target_sources(app PRIVATE src/main.c) and target_link_libraries(app PRIVATE laststate_latch)", + arduino: "# arduino: copy latch/ into lib/, add -I lib/latch/src to the build flags, #include \"laststate/latch.h\"", host: "add_subdirectory(third_party/latch)\ntarget_link_libraries(${PROJECT_NAME} PRIVATE laststate::latch)", }; function mainC(project: string, target: string): string { const device = `${project.toLowerCase().replace(/[^a-z0-9]+/g, "-")}-001`; + const arch = TARGET_ARCH[target] ?? "LS_ARCH_UNKNOWN"; const heapNote = target === "arduino" ? "/* constrained profile: breadcrumbs 16 */\n" : ""; - return `#include + return `#include "laststate/latch.h" ${heapNote} -static ls_transport_t *s_transport; /* register your UART/TCP transport here */ +static ls_identity_t s_identity = { + .project_id = "${project}", + .device_id = "${device}", + .firmware_version = "v0.0.0", + .firmware_build_id = "dev-build", +}; + +static uint32_t timestamp_ms(void *context) { + (void)context; + return 0; /* return a monotonic millisecond counter */ +} void app_init(void) { - static ls_config_t cfg = { - .device_id = "${device}", - .firmware_version = "v1.0.0", - .build_id = "dev-build", - /* .storage = LS_STORAGE_FLASH, */ - /* .transport = s_transport, */ + static const ls_config_t cfg = { + .identity = &s_identity, + .architecture = ${arch}, + .timestamp_ms = timestamp_ms, }; - ls_init(&cfg); - /* ls_transport_register(s_transport); -- register BEFORE ls_boot() */ + if (ls_init(&cfg) != LS_OK) { + return; + } + /* Register the backend that reaches your Relay BEFORE ls_boot(): + * ls_transport_register(&my_uart_transport); // include/laststate/transport.h + */ ls_boot(); ls_breadcrumb("app:init"); } @@ -136,7 +165,7 @@ export async function init(rawOpts: InitOpts) { files: isNewDir ? [`${name}/laststate.yaml`, `${name}/main.c`, `${name}/CMakeLists.patch.txt`] : ["laststate.yaml", "main.c"], - next: ["add #include ", "cmake --preset host-debug", "laststate mock", "laststate test"], + next: ["add #include \"laststate/latch.h\"", "cmake --preset host-debug", "laststate mock", "laststate test"], }; if (isJson()) { diff --git a/src/commands/stack.ts b/src/commands/stack.ts index fd3817e..338a6cc 100644 --- a/src/commands/stack.ts +++ b/src/commands/stack.ts @@ -83,7 +83,7 @@ export async function up(rawOpts: UpOpts) { try { const open = (await import("open")).default; await open(urls.trace); - } catch { /* noop */ } + } catch { /* ignore */ } } celebrate(`Stack ${rawOpts.appliance ? "appliance " : ""}up`, elapsed()); console.log(""); diff --git a/src/commands/test.ts b/src/commands/test.ts index ecf8205..cba2cd1 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -38,7 +38,7 @@ function findVectorsDir(hint?: string): string | null { for (const c of candidates) { try { if (c && existsSync(join(resolve(c), "manifest.json"))) return resolve(c); - } catch { /* noop */ } + } catch { /* ignore */ } } return null; } @@ -85,7 +85,7 @@ function runVectorChecks(vectorsDir: string | null): Check[] { try { for (const f of readdirSync(join(vectorsDir, "valid"))) valid.push(`valid/${f}`); for (const f of readdirSync(join(vectorsDir, "invalid"))) invalid.push(`invalid/${f}`); - } catch { /* noop */ } + } catch { /* ignore */ } manifest = { valid, invalid }; } const checks: Check[] = []; diff --git a/src/lib/env-manager.ts b/src/lib/env-manager.ts index 62a140f..e764e0a 100644 --- a/src/lib/env-manager.ts +++ b/src/lib/env-manager.ts @@ -80,7 +80,7 @@ export function generateSecrets(opts: { onlyMissing?: boolean; envPath?: string continue; } if (v && !isWeak(v) && !opts.onlyMissing) { - // --force not set semantics: default regenerates weak only; keep strong unless forced elsewhere + // Keep existing strong values; only missing or weak values are regenerated. results.push({ key: spec.key, action: "kept" }); continue; } @@ -90,8 +90,8 @@ export function generateSecrets(opts: { onlyMissing?: boolean; envPath?: string const lines = Object.entries(cur).map(([k, v]) => `${k}=${v}`); writeFileSync(envPath, lines.join("\n") + "\n", { mode: 0o600 }); try { - // chmod best-effort on windows ignored - } catch { /* noop */ } + // chmod is best-effort; ignored on Windows + } catch { /* ignore */ } return results; } diff --git a/src/lib/exec.ts b/src/lib/exec.ts index a84cc52..e6ae8d1 100644 --- a/src/lib/exec.ts +++ b/src/lib/exec.ts @@ -10,7 +10,11 @@ export interface RunOpts { verbose?: boolean; } -export async function run(cmd: string, args: string[], opts: RunOpts = {}) { +export async function run( + cmd: string, + args: string[], + opts: RunOpts = {}, +): Promise>> { const execOpts: Options = { cwd: opts.cwd, env: { ...process.env, ...opts.env } as Record, diff --git a/src/ui/logo-image.ts b/src/ui/logo-image.ts index b5b28cf..fc6e066 100644 --- a/src/ui/logo-image.ts +++ b/src/ui/logo-image.ts @@ -22,7 +22,7 @@ import { hexToRgb, brandRgbAt } from "./palette.js"; type Pt = [number, number]; -// ─── Built-in raster geometry (SVG viewBox units, from assets/brand.svg) ──── +// Built-in raster geometry (SVG viewBox units, from assets/brand.svg) const STROKE_PTS: Pt[] = [ [24, 102], [101.775, 102], @@ -54,7 +54,7 @@ const FONT_SCALE = 6; const TEXT_X_SVG = 449; const TEXT_BASELINE_SVG = 116; -// ─── 5x7 bitmap font (only glyphs needed for "LastState") ──────────────────── +// 5x7 bitmap font (only glyphs needed for "LastState") export const FONT: Record = { L: ["#....", "#....", "#....", "#....", "#....", "#....", "#####"], a: [".....", ".....", ".###.", "....#", ".####", "#...#", ".###."], @@ -66,7 +66,7 @@ export const FONT: Record = { }; const FONT_ADVANCE = 6 * FONT_SCALE; -// ─── Pixel buffers ─────────────────────────────────────────────────────────── +// Pixel buffers export interface Pixels { w: number; h: number; @@ -188,7 +188,7 @@ export function renderLogoPixels(): Pixels { return { w: LOGO_W, h: LOGO_H, data }; } -// ─── PNG decoder (8-bit, RGB/RGBA, non-interlaced) ──────────────────────────── +// PNG decoder (8-bit, RGB/RGBA, non-interlaced) function paeth(a: number, b: number, c: number): number { const p = a + b - c; const pa = Math.abs(p - a); @@ -285,7 +285,7 @@ export function downscale(src: Pixels, targetW: number): Pixels { return { w, h, data }; } -// ─── PNG encoder (8-bit RGB, no filter) ─────────────────────────────────────── +// PNG encoder (8-bit RGB, no filter) function pngChunk(type: string, body: Uint8Array): Buffer { const len = Buffer.alloc(4); len.writeUInt32BE(body.length); @@ -312,7 +312,7 @@ export function renderLogoPng(): Buffer { return Buffer.concat([sig, pngChunk("IHDR", ihdr), pngChunk("IDAT", deflateSync(raw)), pngChunk("IEND", Buffer.alloc(0))]); } -// ─── Sixel encoder ──────────────────────────────────────────────────────────── +// Sixel encoder const RAMP: Array<[number, number, number]> = Array.from({ length: 8 }, (_, i) => { const t = i / 7; return hexToRgb( @@ -463,7 +463,7 @@ export function sixelFromPixels(px: Pixels): string { return sixelEncode(px, pal, at); } -// ─── Braille ASCII art (fallback for non-image terminals) ───────────────────── +// Braille ASCII art (fallback for non-image terminals) // Braille dot bits by (dx, dy): cols carry dots 1,2,3,7 / 4,5,6,8. const BRAILLE_COL = [ [0x01, 0x02, 0x04, 0x40], @@ -550,7 +550,7 @@ export function asciiFromPixels(px: Pixels, cols = 100): string { return lines.slice(start, end).join("\n"); } -// ─── Source resolution ─────────────────────────────────────────────────────── +// Source resolution function assetDir(): string { const here = dirname(fileURLToPath(import.meta.url)); const candidates = [join(here, "..", "assets"), join(here, "..", "..", "assets")];