@schemacast/cli 0.0.0-stage → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wael Zohny
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,22 @@
1
- # Temporary Holding Version
1
+ # `@schemacast/cli`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Terminal ASCII renderer for schemacast; optional `--preview` opens a local browser view.
4
+
5
+ **0.x — API may change.**
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add -g @schemacast/cli
11
+ ```
12
+
13
+ Or from this monorepo after build, use the `schemacast` bin pointing at `packages/cli/dist/cli.js`.
14
+
15
+ ## Usage
16
+
17
+ ```bash
18
+ cat data.json | schemacast
19
+ cat data.json | schemacast --preview
20
+ schemacast --help
21
+ schemacast --version
22
+ ```
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Parses CLI flags and decides whether to print usage, version, preview, or cast stdin.
3
+ */
4
+ export type CliAction = {
5
+ readonly kind: 'help';
6
+ } | {
7
+ readonly kind: 'version';
8
+ } | {
9
+ readonly kind: 'preview';
10
+ } | {
11
+ readonly kind: 'cast';
12
+ } | {
13
+ readonly kind: 'usage';
14
+ };
15
+ /**
16
+ * Short usage for `--help` / `-h` and when the CLI is attached to a TTY with no input.
17
+ *
18
+ * @example
19
+ * ```ts
20
+ * process.stdout.write(formatCliUsage());
21
+ * ```
22
+ */
23
+ export declare function formatCliUsage(): string;
24
+ /**
25
+ * Resolves the CLI action from argv and whether stdin is a TTY.
26
+ *
27
+ * @example
28
+ * ```ts
29
+ * resolveCliAction(['--help'], { stdinIsTty: true }); // { kind: 'help' }
30
+ * ```
31
+ */
32
+ export declare function resolveCliAction(argv: readonly string[], options: {
33
+ readonly stdinIsTty: boolean;
34
+ }): CliAction;
35
+ //# sourceMappingURL=cli-args.d.ts.map
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Parses CLI flags and decides whether to print usage, version, preview, or cast stdin.
3
+ */
4
+ /**
5
+ * Short usage for `--help` / `-h` and when the CLI is attached to a TTY with no input.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * process.stdout.write(formatCliUsage());
10
+ * ```
11
+ */
12
+ export function formatCliUsage() {
13
+ return [
14
+ 'Usage: schemacast [options]',
15
+ '',
16
+ 'Read JSON from stdin and print an ASCII view of the best VisualSpec.',
17
+ '',
18
+ 'Options:',
19
+ ' --preview Open a local browser preview instead of ASCII output',
20
+ ' -h, --help Show this help and exit',
21
+ ' -v, --version Print the package version and exit',
22
+ '',
23
+ 'Examples:',
24
+ ' cat data.json | schemacast',
25
+ ' cat data.json | schemacast --preview',
26
+ '',
27
+ ].join('\n');
28
+ }
29
+ /**
30
+ * Resolves the CLI action from argv and whether stdin is a TTY.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * resolveCliAction(['--help'], { stdinIsTty: true }); // { kind: 'help' }
35
+ * ```
36
+ */
37
+ export function resolveCliAction(argv, options) {
38
+ if (argv.includes('--help') || argv.includes('-h')) {
39
+ return { kind: 'help' };
40
+ }
41
+ if (argv.includes('--version') || argv.includes('-v')) {
42
+ return { kind: 'version' };
43
+ }
44
+ if (wantsBrowserPreview(argv)) {
45
+ return { kind: 'preview' };
46
+ }
47
+ if (options.stdinIsTty) {
48
+ return { kind: 'usage' };
49
+ }
50
+ return { kind: 'cast' };
51
+ }
52
+ function wantsBrowserPreview(argv) {
53
+ if (argv.includes('--preview')) {
54
+ return true;
55
+ }
56
+ const first = argv[0];
57
+ return first === 'preview' && !first.startsWith('-');
58
+ }
59
+ //# sourceMappingURL=cli-args.js.map
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ export {};
3
+ //# sourceMappingURL=cli.d.ts.map
package/dist/cli.js ADDED
@@ -0,0 +1,34 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import { formatCliUsage, resolveCliAction } from './cli-args.js';
4
+ import { readCliPackageVersion } from './package-version.js';
5
+ async function main() {
6
+ const argv = process.argv.slice(2);
7
+ const action = resolveCliAction(argv, { stdinIsTty: Boolean(process.stdin.isTTY) });
8
+ if (action.kind === 'help' || action.kind === 'usage') {
9
+ process.stdout.write(formatCliUsage());
10
+ process.exit(0);
11
+ return;
12
+ }
13
+ if (action.kind === 'version') {
14
+ process.stdout.write(`${readCliPackageVersion()}\n`);
15
+ process.exit(0);
16
+ return;
17
+ }
18
+ const stdinText = readFileSync(0, 'utf8');
19
+ if (action.kind === 'preview') {
20
+ const { runBrowserPreview } = await import('./run-browser-preview.js');
21
+ const exitCode = await runBrowserPreview(stdinText);
22
+ process.exit(exitCode);
23
+ return;
24
+ }
25
+ const { runCli } = await import('./run-cli.js');
26
+ const result = runCli(stdinText);
27
+ process.stdout.write(result.stdout);
28
+ if (!result.stdout.endsWith('\n')) {
29
+ process.stdout.write('\n');
30
+ }
31
+ process.exit(result.exitCode);
32
+ }
33
+ void main();
34
+ //# sourceMappingURL=cli.js.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Reads `@schemacast/cli`'s version from the adjacent package.json.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * console.log(readCliPackageVersion()); // '0.5.0'
7
+ * ```
8
+ */
9
+ export declare function readCliPackageVersion(): string;
10
+ //# sourceMappingURL=package-version.d.ts.map
@@ -0,0 +1,17 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ /**
5
+ * Reads `@schemacast/cli`'s version from the adjacent package.json.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * console.log(readCliPackageVersion()); // '0.5.0'
10
+ * ```
11
+ */
12
+ export function readCliPackageVersion() {
13
+ const packageJsonPath = join(dirname(fileURLToPath(import.meta.url)), '../package.json');
14
+ const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf8'));
15
+ return packageJson.version;
16
+ }
17
+ //# sourceMappingURL=package-version.js.map
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Minimal HTML shell for the CLI browser preview (module bundle + data endpoint).
3
+ */
4
+ export declare function previewHtmlDocument(): string;
5
+ //# sourceMappingURL=preview-page.d.ts.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Minimal HTML shell for the CLI browser preview (module bundle + data endpoint).
3
+ */
4
+ export function previewHtmlDocument() {
5
+ return `<!DOCTYPE html>
6
+ <html lang="en">
7
+ <head>
8
+ <meta charset="UTF-8" />
9
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
10
+ <title>schemacast preview</title>
11
+ <link rel="stylesheet" href="/preview.bundle.css" />
12
+ <style>
13
+ body {
14
+ box-sizing: border-box;
15
+ min-height: 100vh;
16
+ margin: 0;
17
+ padding: 2rem 1rem;
18
+ background: #f0f4f8;
19
+ color: #202a36;
20
+ font-family: system-ui, sans-serif;
21
+ }
22
+ .preview-page { width: min(100%, 76rem); margin: 0 auto; }
23
+ .preview-header { margin-bottom: 1.5rem; }
24
+ .preview-header h1 { margin: 0; font-size: 1.75rem; }
25
+ .preview-header p { margin: 0.5rem 0 0; color: #637083; }
26
+ .preview-content { min-height: 12rem; }
27
+ @media (prefers-color-scheme: dark) {
28
+ body { background: #171d26; color: #e7edf5; }
29
+ .preview-header p { color: #a0adbd; }
30
+ }
31
+ </style>
32
+ </head>
33
+ <body>
34
+ <div class="preview-page">
35
+ <header class="preview-header">
36
+ <h1>schemacast</h1>
37
+ <p>Turn JSON into an interactive visual.</p>
38
+ </header>
39
+ <main class="preview-content" id="root"></main>
40
+ </div>
41
+ <script type="module" src="/preview.bundle.js"></script>
42
+ </body>
43
+ </html>`;
44
+ }
45
+ //# sourceMappingURL=preview-page.js.map
@@ -0,0 +1,14 @@
1
+ export interface PreviewPayload {
2
+ data: unknown;
3
+ isStreaming?: boolean;
4
+ }
5
+ /**
6
+ * Runtime check for `/preview-data.json` before passing data to {@link PreviewVisual}.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * isPreviewPayload({ data: [] }); // true
11
+ * ```
12
+ */
13
+ export declare function isPreviewPayload(value: unknown): value is PreviewPayload;
14
+ //# sourceMappingURL=preview-payload.d.ts.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Runtime check for `/preview-data.json` before passing data to {@link PreviewVisual}.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * isPreviewPayload({ data: [] }); // true
7
+ * ```
8
+ */
9
+ export function isPreviewPayload(value) {
10
+ if (typeof value !== 'object' || value === null) {
11
+ return false;
12
+ }
13
+ return 'data' in value;
14
+ }
15
+ //# sourceMappingURL=preview-payload.js.map
@@ -0,0 +1,12 @@
1
+ import { type VisualSpec } from '@schemacast/core';
2
+ /**
3
+ * Renders a `VisualSpec` to terminal text using only AST fields and bindings.
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * const text = renderVisualSpec(cast([{ x: 1, y: 2 }]));
8
+ * // primary: line-chart
9
+ * ```
10
+ */
11
+ export declare function renderVisualSpec(spec: VisualSpec): string;
12
+ //# sourceMappingURL=render-spec.d.ts.map
@@ -0,0 +1,90 @@
1
+ import { buildLongFormatLine, parseNumericValue, } from '@schemacast/core';
2
+ import { formatAsciiTable } from './table.js';
3
+ import { formatSparkline } from './sparkline.js';
4
+ /**
5
+ * Renders a `VisualSpec` to terminal text using only AST fields and bindings.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const text = renderVisualSpec(cast([{ x: 1, y: 2 }]));
10
+ * // primary: line-chart
11
+ * ```
12
+ */
13
+ export function renderVisualSpec(spec) {
14
+ const sections = [];
15
+ sections.push(`primary: ${spec.primaryView.archetype}`);
16
+ sections.push(`score: ${spec.primaryView.score.toFixed(2)}`);
17
+ sections.push('');
18
+ const columns = resolveTableColumns(spec);
19
+ const table = formatAsciiTable(columns, spec.data);
20
+ sections.push(table);
21
+ const sparkline = formatPrimarySparkline(spec);
22
+ if (sparkline !== undefined) {
23
+ sections.push('');
24
+ sections.push(sparkline);
25
+ }
26
+ sections.push('');
27
+ sections.push(`rows: ${spec.data.length}`);
28
+ return sections.join('\n');
29
+ }
30
+ function resolveTableColumns(spec) {
31
+ const bindingColumns = spec.primaryView.bindings.columns;
32
+ if (bindingColumns !== undefined && bindingColumns.length > 0) {
33
+ return [...bindingColumns];
34
+ }
35
+ return spec.fields
36
+ .filter((field) => field.semanticType !== 'nested')
37
+ .map((field) => field.key);
38
+ }
39
+ function formatPrimarySparkline(spec) {
40
+ const archetype = spec.primaryView.archetype;
41
+ if (archetype !== 'line-chart' && archetype !== 'bar-chart') {
42
+ return undefined;
43
+ }
44
+ const xKey = spec.primaryView.bindings.x;
45
+ const yKey = spec.primaryView.bindings.y?.[0];
46
+ if (xKey === undefined || yKey === undefined) {
47
+ return undefined;
48
+ }
49
+ const groupKey = spec.primaryView.bindings.groupBy;
50
+ if (archetype === 'line-chart' && groupKey !== undefined) {
51
+ return formatSeriesSparklines(spec, { xKey, groupKey, yKey });
52
+ }
53
+ const rows = archetype === 'bar-chart' ? (spec.primaryView.data ?? spec.data) : spec.data;
54
+ const yField = spec.fields.find((field) => field.key === yKey);
55
+ const metricValues = rows
56
+ .map((row) => parseNumericValue(row[yKey], yField?.semanticType))
57
+ .filter((value) => value !== null);
58
+ if (metricValues.length === 0) {
59
+ return undefined;
60
+ }
61
+ const spark = formatSparkline(metricValues);
62
+ const xRange = archetype === 'line-chart' ? describeNumericXRange(spec, xKey, rows) : undefined;
63
+ return xRange === undefined
64
+ ? `sparkline (${yKey}): ${spark}`
65
+ : `sparkline (${yKey}, ${xRange}): ${spark}`;
66
+ }
67
+ /** One sparkline per line of a long-format line chart; a missing point is gaps are skipped, not drawn as zero. */
68
+ function formatSeriesSparklines(spec, keys) {
69
+ const line = buildLongFormatLine(spec.data, keys, spec.fields);
70
+ const lines = line.series.map((series) => {
71
+ const present = series.values.filter((value) => value !== null);
72
+ return `sparkline (${keys.yKey}, ${keys.groupKey} ${series.name}): ${formatSparkline(present)}`;
73
+ });
74
+ return lines.length === 0 ? undefined : lines.join('\n');
75
+ }
76
+ /** A numeric x (a step, epoch or version) is named with its range, e.g. `epoch 1–10`. */
77
+ function describeNumericXRange(spec, xKey, rows) {
78
+ const xField = spec.fields.find((field) => field.key === xKey);
79
+ if (xField?.semanticType !== 'number') {
80
+ return undefined;
81
+ }
82
+ const xValues = rows
83
+ .map((row) => parseNumericValue(row[xKey], xField.semanticType))
84
+ .filter((value) => value !== null);
85
+ if (xValues.length === 0) {
86
+ return undefined;
87
+ }
88
+ return `${xKey} ${Math.min(...xValues)}–${Math.max(...xValues)}`;
89
+ }
90
+ //# sourceMappingURL=render-spec.js.map
@@ -0,0 +1,17 @@
1
+ export interface PreviewServerHandle {
2
+ url: string;
3
+ close: () => Promise<void>;
4
+ }
5
+ /**
6
+ * Builds or reuses the browser preview bundle (esbuild; not loaded on ASCII runs).
7
+ */
8
+ export declare function ensurePreviewBundle(): Promise<void>;
9
+ /**
10
+ * Serves stdin JSON through `<AutoVisual />` in the browser (isStreaming false for Step 4).
11
+ */
12
+ export declare function startPreviewServer(stdinText: string): Promise<PreviewServerHandle>;
13
+ /**
14
+ * Launches local browser preview for stdin JSON; blocks until the server is closed.
15
+ */
16
+ export declare function runBrowserPreview(stdinText: string): Promise<number>;
17
+ //# sourceMappingURL=run-browser-preview.d.ts.map
@@ -0,0 +1,226 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { execFile } from 'node:child_process';
3
+ import { createServer } from 'node:http';
4
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
5
+ import { dirname, join, relative, resolve } from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { promisify } from 'node:util';
8
+ import * as esbuild from 'esbuild';
9
+ import { previewHtmlDocument } from './preview/preview-page.js';
10
+ import { stdinToCastInput } from './stdin-payload.js';
11
+ const execFileAsync = promisify(execFile);
12
+ const moduleDir = dirname(fileURLToPath(import.meta.url));
13
+ const packageRoot = join(moduleDir, '..');
14
+ const cacheDir = join(packageRoot, '.preview-cache');
15
+ const bundlePath = join(cacheDir, 'preview.bundle.js');
16
+ const cssBundlePath = join(cacheDir, 'preview.bundle.css');
17
+ const metaPath = join(cacheDir, 'meta.json');
18
+ const entryPath = join(packageRoot, 'src/preview/preview-entry.tsx');
19
+ const repoRoot = join(packageRoot, '../..');
20
+ const builderPath = fileURLToPath(import.meta.url);
21
+ /**
22
+ * Builds or reuses the browser preview bundle (esbuild; not loaded on ASCII runs).
23
+ */
24
+ export async function ensurePreviewBundle() {
25
+ mkdirSync(cacheDir, { recursive: true });
26
+ if (!isPreviewBundleCurrent()) {
27
+ const result = await esbuild.build({
28
+ entryPoints: [entryPath],
29
+ absWorkingDir: repoRoot,
30
+ bundle: true,
31
+ outfile: bundlePath,
32
+ format: 'esm',
33
+ platform: 'browser',
34
+ target: 'es2022',
35
+ jsx: 'automatic',
36
+ sourcemap: true,
37
+ metafile: true,
38
+ alias: {
39
+ '@schemacast/react': join(repoRoot, 'packages/react/src/index.ts'),
40
+ '@schemacast/core': join(repoRoot, 'packages/core/src/index.ts'),
41
+ },
42
+ define: {
43
+ 'process.env.NODE_ENV': '"production"',
44
+ },
45
+ });
46
+ const inputPaths = [
47
+ ...Object.keys(result.metafile.inputs).map((inputPath) => resolve(repoRoot, inputPath)),
48
+ builderPath,
49
+ ];
50
+ writeMeta(metaPath, hashInputFiles(inputPaths));
51
+ }
52
+ }
53
+ function isPreviewBundleCurrent() {
54
+ if (!existsSync(bundlePath) || !existsSync(cssBundlePath) || !existsSync(metaPath)) {
55
+ return false;
56
+ }
57
+ const metadata = readMeta(metaPath);
58
+ if (metadata === null) {
59
+ return false;
60
+ }
61
+ const inputEntries = Object.entries(metadata.inputHashes);
62
+ const builderInput = relative(repoRoot, builderPath);
63
+ return (inputEntries.length > 0 &&
64
+ Object.hasOwn(metadata.inputHashes, builderInput) &&
65
+ inputEntries.every(([inputPath, expectedHash]) => {
66
+ const absolutePath = resolve(repoRoot, inputPath);
67
+ return existsSync(absolutePath) && hashFile(absolutePath) === expectedHash;
68
+ }));
69
+ }
70
+ function readMeta(path) {
71
+ let value;
72
+ try {
73
+ value = JSON.parse(readFileSync(path, 'utf8'));
74
+ }
75
+ catch (error) {
76
+ if (error instanceof SyntaxError) {
77
+ return null;
78
+ }
79
+ throw error;
80
+ }
81
+ if (!isRecord(value) || value.version !== 1 || !isStringRecord(value.inputHashes)) {
82
+ return null;
83
+ }
84
+ return {
85
+ version: 1,
86
+ inputHashes: value.inputHashes,
87
+ };
88
+ }
89
+ function isRecord(value) {
90
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
91
+ }
92
+ function isStringRecord(value) {
93
+ return isRecord(value) && Object.values(value).every((entry) => typeof entry === 'string');
94
+ }
95
+ function hashInputFiles(inputPaths) {
96
+ const inputHashes = {};
97
+ for (const inputPath of new Set(inputPaths)) {
98
+ const relativePath = relative(repoRoot, inputPath);
99
+ inputHashes[relativePath] = hashFile(inputPath);
100
+ }
101
+ return inputHashes;
102
+ }
103
+ function hashFile(path) {
104
+ return createHash('sha256').update(readFileSync(path)).digest('hex');
105
+ }
106
+ function writeMeta(path, inputHashes) {
107
+ const metadata = { version: 1, inputHashes };
108
+ writeFileSync(path, JSON.stringify(metadata));
109
+ }
110
+ /**
111
+ * Serves stdin JSON through `<AutoVisual />` in the browser (isStreaming false for Step 4).
112
+ */
113
+ export async function startPreviewServer(stdinText) {
114
+ await ensurePreviewBundle();
115
+ const data = stdinToCastInput(stdinText);
116
+ const payload = JSON.stringify({ data, isStreaming: false });
117
+ const server = createServer((request, response) => {
118
+ const path = request.url?.split('?')[0] ?? '/';
119
+ if (path === '/' || path === '/index.html') {
120
+ response.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
121
+ response.end(previewHtmlDocument());
122
+ return;
123
+ }
124
+ if (path === '/preview-data.json') {
125
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
126
+ response.end(payload);
127
+ return;
128
+ }
129
+ if (path === '/preview.bundle.js') {
130
+ response.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8' });
131
+ response.end(readFileSync(bundlePath));
132
+ return;
133
+ }
134
+ if (path === '/preview.bundle.css') {
135
+ response.writeHead(200, { 'content-type': 'text/css; charset=utf-8' });
136
+ response.end(readFileSync(cssBundlePath));
137
+ return;
138
+ }
139
+ if (path === '/preview.bundle.js.map') {
140
+ const mapPath = `${bundlePath}.map`;
141
+ if (existsSync(mapPath)) {
142
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
143
+ response.end(readFileSync(mapPath));
144
+ return;
145
+ }
146
+ }
147
+ if (path === '/preview.bundle.css.map') {
148
+ const mapPath = `${cssBundlePath}.map`;
149
+ if (existsSync(mapPath)) {
150
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
151
+ response.end(readFileSync(mapPath));
152
+ return;
153
+ }
154
+ }
155
+ response.writeHead(404);
156
+ response.end('Not found');
157
+ });
158
+ await listenOnFreePort(server);
159
+ const address = server.address();
160
+ if (address === null || typeof address === 'string') {
161
+ throw new Error('Preview server failed to bind');
162
+ }
163
+ const url = `http://127.0.0.1:${address.port}/`;
164
+ return {
165
+ url,
166
+ close: () => closeServer(server),
167
+ };
168
+ }
169
+ function listenOnFreePort(server) {
170
+ return new Promise((resolve, reject) => {
171
+ server.once('error', reject);
172
+ server.listen(0, '127.0.0.1', () => {
173
+ server.off('error', reject);
174
+ resolve();
175
+ });
176
+ });
177
+ }
178
+ function closeServer(server) {
179
+ return new Promise((resolve, reject) => {
180
+ server.close((error) => {
181
+ if (error !== undefined) {
182
+ reject(error);
183
+ return;
184
+ }
185
+ resolve();
186
+ });
187
+ });
188
+ }
189
+ async function openInBrowser(url) {
190
+ const platform = process.platform;
191
+ if (platform === 'darwin') {
192
+ await execFileAsync('open', [url]);
193
+ return;
194
+ }
195
+ if (platform === 'win32') {
196
+ await execFileAsync('cmd', ['/c', 'start', '', url]);
197
+ return;
198
+ }
199
+ await execFileAsync('xdg-open', [url]);
200
+ }
201
+ /**
202
+ * Launches local browser preview for stdin JSON; blocks until the server is closed.
203
+ */
204
+ export async function runBrowserPreview(stdinText) {
205
+ const handle = await startPreviewServer(stdinText);
206
+ process.stderr.write(`schemacast preview: ${handle.url}\n`);
207
+ process.stderr.write('Press Ctrl+C to stop the preview server.\n');
208
+ if (process.env.SCHEMACAST_PREVIEW_SKIP_OPEN !== '1') {
209
+ try {
210
+ await openInBrowser(handle.url);
211
+ }
212
+ catch {
213
+ process.stderr.write('Could not open a browser automatically; open the URL above manually.\n');
214
+ }
215
+ }
216
+ await new Promise((resolve) => {
217
+ process.on('SIGINT', () => {
218
+ void handle.close().then(resolve);
219
+ });
220
+ process.on('SIGTERM', () => {
221
+ void handle.close().then(resolve);
222
+ });
223
+ });
224
+ return 0;
225
+ }
226
+ //# sourceMappingURL=run-browser-preview.js.map
@@ -0,0 +1,15 @@
1
+ export interface CliRunResult {
2
+ exitCode: number;
3
+ stdout: string;
4
+ }
5
+ /**
6
+ * Parses stdin JSON (or empty input), runs `cast()` once, and returns terminal output.
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * const { stdout } = runCli('[{"revenue": 100}]');
11
+ * console.log(stdout.startsWith('primary:'));
12
+ * ```
13
+ */
14
+ export declare function runCli(stdinText: string): CliRunResult;
15
+ //# sourceMappingURL=run-cli.d.ts.map
@@ -0,0 +1,19 @@
1
+ import { cast } from '@schemacast/core';
2
+ import { renderVisualSpec } from './render-spec.js';
3
+ import { stdinToCastInput } from './stdin-payload.js';
4
+ /**
5
+ * Parses stdin JSON (or empty input), runs `cast()` once, and returns terminal output.
6
+ *
7
+ * @example
8
+ * ```ts
9
+ * const { stdout } = runCli('[{"revenue": 100}]');
10
+ * console.log(stdout.startsWith('primary:'));
11
+ * ```
12
+ */
13
+ export function runCli(stdinText) {
14
+ const parsed = stdinToCastInput(stdinText);
15
+ const spec = cast(parsed);
16
+ const stdout = renderVisualSpec(spec);
17
+ return { exitCode: 0, stdout };
18
+ }
19
+ //# sourceMappingURL=run-cli.js.map
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Renders a compact Unicode sparkline from numeric samples (read-only).
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * formatSparkline([1, 3, 2, 4]); // block chars ▁▃▂▅
7
+ * ```
8
+ */
9
+ export declare function formatSparkline(values: readonly number[]): string;
10
+ //# sourceMappingURL=sparkline.d.ts.map
@@ -0,0 +1,30 @@
1
+ const SPARKLINE_BLOCKS = '▁▂▃▄▅▆▇█';
2
+ /**
3
+ * Renders a compact Unicode sparkline from numeric samples (read-only).
4
+ *
5
+ * @example
6
+ * ```ts
7
+ * formatSparkline([1, 3, 2, 4]); // block chars ▁▃▂▅
8
+ * ```
9
+ */
10
+ export function formatSparkline(values) {
11
+ if (values.length === 0) {
12
+ return '';
13
+ }
14
+ const finiteValues = values.filter((value) => Number.isFinite(value));
15
+ if (finiteValues.length === 0) {
16
+ return '';
17
+ }
18
+ const min = Math.min(...finiteValues);
19
+ const max = Math.max(...finiteValues);
20
+ const span = max - min === 0 ? 1 : max - min;
21
+ const lastBlockIndex = SPARKLINE_BLOCKS.length - 1;
22
+ return finiteValues
23
+ .map((value) => {
24
+ const scaled = (value - min) / span;
25
+ const index = Math.min(lastBlockIndex, Math.max(0, Math.round(scaled * lastBlockIndex)));
26
+ return SPARKLINE_BLOCKS.charAt(index);
27
+ })
28
+ .join('');
29
+ }
30
+ //# sourceMappingURL=sparkline.js.map
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Parses a trimmed stdin fragment as JSON when valid; otherwise returns the raw string (same as CLI).
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * parseStdinPayload('{broken'); // returns the raw string unchanged
7
+ * ```
8
+ */
9
+ export declare function parseStdinPayload(text: string): unknown;
10
+ /**
11
+ * Normalizes full stdin (including empty) into the value passed to `cast()` / `<AutoVisual />`.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * stdinToCastInput(' '); // ''
16
+ * ```
17
+ */
18
+ export declare function stdinToCastInput(stdinText: string): unknown;
19
+ //# sourceMappingURL=stdin-payload.d.ts.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Parses a trimmed stdin fragment as JSON when valid; otherwise returns the raw string (same as CLI).
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * parseStdinPayload('{broken'); // returns the raw string unchanged
7
+ * ```
8
+ */
9
+ export function parseStdinPayload(text) {
10
+ try {
11
+ return JSON.parse(text);
12
+ }
13
+ catch {
14
+ return text;
15
+ }
16
+ }
17
+ /**
18
+ * Normalizes full stdin (including empty) into the value passed to `cast()` / `<AutoVisual />`.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * stdinToCastInput(' '); // ''
23
+ * ```
24
+ */
25
+ export function stdinToCastInput(stdinText) {
26
+ const trimmed = stdinText.trim();
27
+ if (trimmed.length === 0) {
28
+ return '';
29
+ }
30
+ return parseStdinPayload(trimmed);
31
+ }
32
+ //# sourceMappingURL=stdin-payload.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Formats `spec.data` rows as a fixed-width ASCII table without mutating input.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * formatAsciiTable(['a', 'b'], [{ a: 1, b: 2 }]);
7
+ * // a │ b
8
+ * // 1 │ 2
9
+ * ```
10
+ */
11
+ export declare function formatAsciiTable(columns: readonly string[], rows: readonly Record<string, unknown>[]): string;
12
+ //# sourceMappingURL=table.d.ts.map
package/dist/table.js ADDED
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Formats `spec.data` rows as a fixed-width ASCII table without mutating input.
3
+ *
4
+ * @example
5
+ * ```ts
6
+ * formatAsciiTable(['a', 'b'], [{ a: 1, b: 2 }]);
7
+ * // a │ b
8
+ * // 1 │ 2
9
+ * ```
10
+ */
11
+ export function formatAsciiTable(columns, rows) {
12
+ if (columns.length === 0) {
13
+ return '(no columns)';
14
+ }
15
+ const headers = columns.map((column) => column);
16
+ const cellTexts = rows.map((row) => columns.map((column) => formatCellValue(row[column])));
17
+ const widths = headers.map((header, columnIndex) => {
18
+ const cells = cellTexts.map((row) => row[columnIndex] ?? '');
19
+ return Math.max(header.length, ...cells.map((cell) => cell.length), 3);
20
+ });
21
+ const headerLine = headers
22
+ .map((header, index) => padEnd(header, widths[index] ?? header.length))
23
+ .join(' │ ');
24
+ const rule = widths.map((width) => '─'.repeat(width)).join('─┼─');
25
+ const bodyLines = cellTexts.map((row) => row.map((cell, index) => padEnd(cell, widths[index] ?? cell.length)).join(' │ '));
26
+ return [headerLine, rule, ...bodyLines].join('\n');
27
+ }
28
+ function formatCellValue(value) {
29
+ if (value === null || value === undefined) {
30
+ return '—';
31
+ }
32
+ if (typeof value === 'object') {
33
+ return JSON.stringify(value);
34
+ }
35
+ return String(value);
36
+ }
37
+ function padEnd(text, width) {
38
+ if (text.length >= width) {
39
+ return text;
40
+ }
41
+ return text + ' '.repeat(width - text.length);
42
+ }
43
+ //# sourceMappingURL=table.js.map
package/package.json CHANGED
@@ -1,6 +1,49 @@
1
1
  {
2
2
  "name": "@schemacast/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.5.0",
4
+ "description": "Terminal renderer for schemacast VisualSpec output.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "keywords": [
11
+ "schemacast",
12
+ "cli",
13
+ "terminal",
14
+ "json",
15
+ "visualization"
16
+ ],
17
+ "bin": {
18
+ "schemacast": "./dist/cli.js"
19
+ },
20
+ "exports": {
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "!dist/**/*.map"
26
+ ],
27
+ "dependencies": {
28
+ "@schemacast/core": "0.5.0",
29
+ "@schemacast/react": "0.5.0",
30
+ "esbuild": "^0.25.0",
31
+ "react": "^19.0.0",
32
+ "react-dom": "^19.0.0"
33
+ },
34
+ "devDependencies": {
35
+ "@testing-library/react": "^16.0.0",
36
+ "@types/node": "^22.0.0",
37
+ "@types/react": "^19.0.0",
38
+ "@types/react-dom": "^19.0.0",
39
+ "jsdom": "^25.0.0",
40
+ "typescript": "^5.7.0"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ },
45
+ "scripts": {
46
+ "typecheck": "tsc --noEmit",
47
+ "build": "tsc"
48
+ }
6
49
  }