@lightblues/jig 0.1.3 → 0.1.5

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.
Files changed (43) hide show
  1. package/README.md +2 -0
  2. package/dist/canvas/artifact/assets/katex.css +1 -0
  3. package/dist/canvas/artifact/assets/manifest.json +13 -0
  4. package/dist/canvas/artifact/assets/runtime.js +382 -0
  5. package/dist/canvas/artifact/css.d.ts +29 -0
  6. package/dist/canvas/artifact/css.js +159 -0
  7. package/dist/canvas/artifact/entry.d.ts +1 -0
  8. package/dist/canvas/artifact/entry.js +10 -0
  9. package/dist/canvas/artifact/icons.d.ts +13 -0
  10. package/dist/canvas/artifact/icons.js +67 -0
  11. package/dist/canvas/artifact/icons.json +1 -0
  12. package/dist/canvas/artifact/index.d.ts +54 -0
  13. package/dist/canvas/artifact/index.js +111 -0
  14. package/dist/canvas/artifact/instructions.d.ts +2 -0
  15. package/dist/canvas/artifact/instructions.js +16 -0
  16. package/dist/canvas/artifact/kit.d.ts +32 -0
  17. package/dist/canvas/artifact/kit.js +88 -0
  18. package/dist/canvas/artifact/modules.d.ts +3 -0
  19. package/dist/canvas/artifact/modules.js +33 -0
  20. package/dist/canvas/artifact/names.d.ts +6 -0
  21. package/dist/canvas/artifact/names.js +30 -0
  22. package/dist/canvas/artifact/ui.d.ts +76 -0
  23. package/dist/canvas/artifact/ui.js +156 -0
  24. package/dist/canvas/build.d.ts +14 -0
  25. package/dist/canvas/build.js +27 -0
  26. package/dist/canvas/compile.d.ts +8 -0
  27. package/dist/canvas/compile.js +19 -4
  28. package/dist/canvas/kit/blocks.d.ts +118 -0
  29. package/dist/canvas/kit/blocks.js +276 -0
  30. package/dist/canvas/kit/charts.d.ts +66 -0
  31. package/dist/canvas/kit/charts.js +319 -0
  32. package/dist/canvas/kit/context.d.ts +33 -0
  33. package/dist/canvas/kit/context.js +38 -0
  34. package/dist/canvas/kit/index.d.ts +25 -0
  35. package/dist/canvas/kit/index.js +44 -0
  36. package/dist/canvas/kit/theme.d.ts +88 -0
  37. package/dist/canvas/kit/theme.js +63 -0
  38. package/dist/canvas/kit/ui.d.ts +55 -0
  39. package/dist/canvas/kit/ui.js +100 -0
  40. package/dist/canvas/runtime.d.ts +6 -1
  41. package/dist/canvas/runtime.js +4 -3
  42. package/dist/markdown/mermaid.js +8 -4
  43. package/package.json +34 -2
@@ -0,0 +1,29 @@
1
+ import type { KitPalette } from '../kit/theme.ts';
2
+ /** A host's colours for tier-B pages, per kind: the tier-A `KitPalette`, so one palette serves both tiers. */
3
+ export interface ArtifactPalette {
4
+ light?: KitPalette;
5
+ dark?: KitPalette;
6
+ }
7
+ type Vars = Record<string, string>;
8
+ /** shadcn/ui's neutral theme (new-york, Tailwind v4), the default when the host passes no colour. */
9
+ export declare const SHADCN_NEUTRAL: Readonly<Record<'light' | 'dark', Vars>>;
10
+ /** shadcn's variables for one kind from a `KitPalette`: what the host sets wins, the rest is shadcn neutral. */
11
+ export declare function shadcnVars(kind: 'light' | 'dark', palette?: KitPalette): Vars;
12
+ /**
13
+ * The palette as CSS: `:root` for light, `[data-theme=dark]` for dark (the runtime sets `data-theme` from the host's
14
+ * theme). `compileArtifact` puts it in each page; a host may also serve it as a stylesheet (`styleUrls`) to change
15
+ * colours without recompiling stored pages.
16
+ */
17
+ export declare function artifactThemeCss(palette?: ArtifactPalette): string;
18
+ /** Class candidates in a source: every run of characters between whitespace, quotes and backticks. Tailwind drops what is not a class. */
19
+ export declare function classCandidates(source: string): string[];
20
+ /** Collapse Tailwind's indented output: comments dropped, each newline and its indent to one space, then trimmed around braces and semicolons. */
21
+ export declare function minifyCss(css: string): string;
22
+ export interface ArtifactCssOptions {
23
+ palette?: ArtifactPalette;
24
+ }
25
+ /** The candidates that Tailwind turns into a rule (used to keep the kit's class list to real classes). */
26
+ export declare function classCompiles(candidates: readonly string[]): Promise<string[]>;
27
+ /** The page's CSS: preflight, the theme variables, and the utilities the source and the kit use. */
28
+ export declare function artifactCss(source: string, options?: ArtifactCssOptions): Promise<string>;
29
+ export {};
@@ -0,0 +1,159 @@
1
+ // The page's CSS, generated on the server when the canvas is compiled (J009, jig-016): Tailwind v4's compiler over the
2
+ // class candidates in the source and the kit's own classes, with shadcn's CSS variables from the host palette. The
3
+ // frame then needs no Tailwind JIT (75 KB, and `unsafe-eval`-free either way) and no network.
4
+ import { readFile } from 'node:fs/promises';
5
+ import path from 'node:path';
6
+ import { fileURLToPath } from 'node:url';
7
+ import { ARTIFACT_KIT_CLASSES } from "./names.js";
8
+ /** shadcn/ui's neutral theme (new-york, Tailwind v4), the default when the host passes no colour. */
9
+ export const SHADCN_NEUTRAL = {
10
+ light: {
11
+ background: 'oklch(1 0 0)', foreground: 'oklch(0.145 0 0)', card: 'oklch(1 0 0)', 'card-foreground': 'oklch(0.145 0 0)',
12
+ popover: 'oklch(1 0 0)', 'popover-foreground': 'oklch(0.145 0 0)', primary: 'oklch(0.205 0 0)', 'primary-foreground': 'oklch(0.985 0 0)',
13
+ secondary: 'oklch(0.97 0 0)', 'secondary-foreground': 'oklch(0.205 0 0)', muted: 'oklch(0.97 0 0)', 'muted-foreground': 'oklch(0.556 0 0)',
14
+ accent: 'oklch(0.97 0 0)', 'accent-foreground': 'oklch(0.205 0 0)', destructive: 'oklch(0.577 0.245 27.325)', border: 'oklch(0.922 0 0)',
15
+ input: 'oklch(0.922 0 0)', ring: 'oklch(0.708 0 0)',
16
+ 'chart-1': 'oklch(0.646 0.222 41.116)', 'chart-2': 'oklch(0.6 0.118 184.704)', 'chart-3': 'oklch(0.398 0.07 227.392)', 'chart-4': 'oklch(0.828 0.189 84.429)', 'chart-5': 'oklch(0.769 0.188 70.08)',
17
+ },
18
+ dark: {
19
+ background: 'oklch(0.145 0 0)', foreground: 'oklch(0.985 0 0)', card: 'oklch(0.205 0 0)', 'card-foreground': 'oklch(0.985 0 0)',
20
+ popover: 'oklch(0.205 0 0)', 'popover-foreground': 'oklch(0.985 0 0)', primary: 'oklch(0.922 0 0)', 'primary-foreground': 'oklch(0.205 0 0)',
21
+ secondary: 'oklch(0.269 0 0)', 'secondary-foreground': 'oklch(0.985 0 0)', muted: 'oklch(0.269 0 0)', 'muted-foreground': 'oklch(0.708 0 0)',
22
+ accent: 'oklch(0.269 0 0)', 'accent-foreground': 'oklch(0.985 0 0)', destructive: 'oklch(0.704 0.191 22.216)', border: 'oklch(1 0 0 / 10%)',
23
+ input: 'oklch(1 0 0 / 15%)', ring: 'oklch(0.556 0 0)',
24
+ 'chart-1': 'oklch(0.488 0.243 264.376)', 'chart-2': 'oklch(0.696 0.17 162.48)', 'chart-3': 'oklch(0.769 0.188 70.08)', 'chart-4': 'oklch(0.627 0.265 303.9)', 'chart-5': 'oklch(0.645 0.246 16.439)',
25
+ },
26
+ };
27
+ const COLOR_NAMES = Object.keys(SHADCN_NEUTRAL.light);
28
+ /** A host colour or font as a CSS value; throws on anything that could end the declaration. */
29
+ function cssValue(value, what) {
30
+ const v = String(value).trim();
31
+ if (!v || v.length > 300 || /[;{}<>\\]|\/\*|\*\//.test(v))
32
+ throw new TypeError(`palette ${what} is not a plain CSS value: ${JSON.stringify(value)}`);
33
+ return v;
34
+ }
35
+ const mix = (a, share, b) => `color-mix(in srgb, ${a} ${share}%, ${b})`;
36
+ /** shadcn's variables for one kind from a `KitPalette`: what the host sets wins, the rest is shadcn neutral. */
37
+ export function shadcnVars(kind, palette = {}) {
38
+ const v = { ...SHADCN_NEUTRAL[kind] };
39
+ const p = palette;
40
+ const set = (names, value, what) => {
41
+ if (value != null)
42
+ for (const n of names)
43
+ v[n] = cssValue(value, what);
44
+ };
45
+ set(['background'], p.background, 'background');
46
+ set(['card', 'popover'], p.surface ?? p.background, 'surface');
47
+ set(['foreground', 'card-foreground', 'popover-foreground', 'secondary-foreground', 'accent-foreground'], p.text, 'text');
48
+ set(['muted-foreground'], p.textSecondary ?? p.textTertiary, 'textSecondary');
49
+ set(['border', 'input'], p.border, 'border');
50
+ set(['primary', 'ring'], p.accent, 'accent');
51
+ set(['primary-foreground'], p.onAccent, 'onAccent');
52
+ set(['destructive'], p.tone?.danger, 'tone.danger');
53
+ // Fills derived from the text on the background, as shadcn's neutral greys are.
54
+ if (p.text != null || p.background != null) {
55
+ const fill = mix(v.foreground, kind === 'dark' ? 12 : 4, v.background);
56
+ v.secondary = fill;
57
+ v.muted = fill;
58
+ v.accent = fill;
59
+ }
60
+ p.chart?.slice(0, 5).forEach((c, i) => {
61
+ v[`chart-${i + 1}`] = cssValue(c, `chart[${i}]`);
62
+ });
63
+ if (p.font?.body)
64
+ v['font-sans'] = cssValue(p.font.body, 'font.body');
65
+ if (p.font?.mono)
66
+ v['font-mono'] = cssValue(p.font.mono, 'font.mono');
67
+ return v;
68
+ }
69
+ const block = (selector, vars) => `${selector}{${Object.entries(vars).map(([k, val]) => `--${k}:${val}`).join(';')}}`;
70
+ /**
71
+ * The palette as CSS: `:root` for light, `[data-theme=dark]` for dark (the runtime sets `data-theme` from the host's
72
+ * theme). `compileArtifact` puts it in each page; a host may also serve it as a stylesheet (`styleUrls`) to change
73
+ * colours without recompiling stored pages.
74
+ */
75
+ export function artifactThemeCss(palette = {}) {
76
+ return `${block(':root', { radius: '0.625rem', ...shadcnVars('light', palette.light) })}${block('[data-theme=dark]', shadcnVars('dark', palette.dark))}`;
77
+ }
78
+ const THEME_INLINE = `@theme inline{${COLOR_NAMES.map((n) => `--color-${n}:var(--${n})`).join(';')};--radius-sm:calc(var(--radius) - 4px);--radius-md:calc(var(--radius) - 2px);--radius-lg:var(--radius);--radius-xl:calc(var(--radius) + 4px);--font-sans:var(--font-sans-host,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji");--font-mono:var(--font-mono-host,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace)}`;
79
+ /** Tailwind's input: the framework, the class-based dark variant, shadcn's tokens, and the base layer shadcn adds. */
80
+ function inputCss(palette) {
81
+ // In the `theme` layer, so a stylesheet the host adds (`styleUrls`, unlayered) can change colours without a recompile.
82
+ const theme = `@layer theme{${artifactThemeCss(palette).replace(/--font-(sans|mono):/g, '--font-$1-host:')}}`;
83
+ return [
84
+ '@import "tailwindcss";',
85
+ '@custom-variant dark (&:where([data-theme=dark], [data-theme=dark] *));',
86
+ THEME_INLINE,
87
+ theme,
88
+ '@layer base{*{border-color:var(--border);outline-color:color-mix(in oklab,var(--ring) 50%,transparent)}}',
89
+ // Unlayered, after the document's own `body{background}`: the page takes the palette's background.
90
+ 'html,body{background:var(--background);color:var(--foreground)}body{margin:0;font-family:var(--font-sans)}',
91
+ ].join('\n');
92
+ }
93
+ let tailwind = null;
94
+ function loadTailwind() {
95
+ tailwind ??= (async () => {
96
+ let tw;
97
+ try {
98
+ tw = (await import('tailwindcss'));
99
+ }
100
+ catch {
101
+ throw new Error('compileArtifact needs the optional peer tailwindcss 4.x');
102
+ }
103
+ const root = path.join(path.dirname(fileURLToPath(import.meta.resolve('tailwindcss'))), '..');
104
+ return { tw, root, files: new Map() };
105
+ })().catch((err) => {
106
+ tailwind = null;
107
+ throw err;
108
+ });
109
+ return tailwind;
110
+ }
111
+ /** Class candidates in a source: every run of characters between whitespace, quotes and backticks. Tailwind drops what is not a class. */
112
+ export function classCandidates(source) {
113
+ const out = new Set();
114
+ for (const word of source.split(/[\s'"`]+/)) {
115
+ if (word && word.length <= 200 && /[a-z]/.test(word))
116
+ out.add(word);
117
+ }
118
+ return [...out];
119
+ }
120
+ /** Collapse Tailwind's indented output: comments dropped, each newline and its indent to one space, then trimmed around braces and semicolons. */
121
+ export function minifyCss(css) {
122
+ return css.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\s*\n\s*/g, ' ').replace(/ ?([{};]) ?/g, '$1').trim();
123
+ }
124
+ /** The candidates that Tailwind turns into a rule (used to keep the kit's class list to real classes). */
125
+ export async function classCompiles(candidates) {
126
+ const out = [];
127
+ for (const c of candidates) {
128
+ const compiler = await tailwindCompiler({});
129
+ const empty = compiler.build([]);
130
+ if (compiler.build([c]).length > empty.length)
131
+ out.push(c);
132
+ }
133
+ return out;
134
+ }
135
+ async function tailwindCompiler(palette) {
136
+ const { tw, root, files } = await loadTailwind();
137
+ const read = async (file) => {
138
+ let text = files.get(file);
139
+ if (text == null) {
140
+ text = await readFile(file, 'utf8');
141
+ files.set(file, text);
142
+ }
143
+ return text;
144
+ };
145
+ return tw.compile(inputCss(palette), {
146
+ base: root,
147
+ loadStylesheet: async (id, base) => {
148
+ const file = id === 'tailwindcss' ? path.join(root, 'index.css') : path.resolve(base, id);
149
+ if (!file.startsWith(root + path.sep))
150
+ throw new Error(`the page CSS may not load ${id}`);
151
+ return { path: file, base: path.dirname(file), content: await read(file) };
152
+ },
153
+ });
154
+ }
155
+ /** The page's CSS: preflight, the theme variables, and the utilities the source and the kit use. */
156
+ export async function artifactCss(source, options = {}) {
157
+ const compiler = await tailwindCompiler(options.palette ?? {});
158
+ return minifyCss(compiler.build([...ARTIFACT_KIT_CLASSES, ...classCandidates(source)]));
159
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,10 @@
1
+ // The entry of the artifact `runtime.js` (`buildArtifactRuntime`): React, react-dom, recharts, the shadcn subset,
2
+ // KaTeX and the state bridge, with the module map of `modules.ts`. Running it installs `window.__jigCanvas.run`.
3
+ import { createElement as h } from 'react';
4
+ import { startCanvasRuntime } from "../runtime.js";
5
+ import { ARTIFACT_MODULE_MAP, ArtifactRoot } from "./modules.js";
6
+ function ArtifactError({ error }) {
7
+ const text = error instanceof Error ? `${error.name}: ${error.message}` : String(error);
8
+ return h('div', { role: 'alert', 'data-canvas-error': '1', className: 'rounded-lg border border-destructive/40 bg-card px-4 py-3 text-sm text-destructive font-mono whitespace-pre-wrap break-words' }, text);
9
+ }
10
+ startCanvasRuntime({ kit: {}, moduleMap: ARTIFACT_MODULE_MAP, Root: ArtifactRoot, ErrorView: ArtifactError });
@@ -0,0 +1,13 @@
1
+ import type { IconNode } from './kit.ts';
2
+ export interface IconTable {
3
+ /** lucide's version the table came from. */
4
+ version: string;
5
+ /** Every export name (`Heart`, `HeartIcon`, `LucideHeart`) → the icon's file name (`heart`). */
6
+ names: Record<string, string>;
7
+ /** File name → its SVG children. */
8
+ nodes: Record<string, IconNode>;
9
+ }
10
+ /** The table, loaded once per process. */
11
+ export declare function iconTable(): Promise<IconTable>;
12
+ /** Read the table from the installed `lucide-react` (needs it and React; the build and the source tree have both). */
13
+ export declare function iconTableFromLucide(): Promise<IconTable>;
@@ -0,0 +1,67 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // lucide's icons as data, for the server: `compileArtifact` puts the nodes of the icons a page imports into the page,
10
+ // so the runtime carries no icon set. `dist/canvas/artifact/icons.json` is written at build time
11
+ // (`scripts/build-artifact.ts`); in the source tree it is read from the installed `lucide-react`.
12
+ import { readFile } from 'node:fs/promises';
13
+ import path from 'node:path';
14
+ import { fileURLToPath, pathToFileURL } from 'node:url';
15
+ let table = null;
16
+ /** The table, loaded once per process. */
17
+ export function iconTable() {
18
+ table ??= load().catch((err) => {
19
+ table = null;
20
+ throw err;
21
+ });
22
+ return table;
23
+ }
24
+ async function load() {
25
+ const here = path.dirname(fileURLToPath(import.meta.url));
26
+ try {
27
+ return JSON.parse(await readFile(path.join(here, 'icons.json'), 'utf8'));
28
+ }
29
+ catch (err) {
30
+ if (err.code !== 'ENOENT')
31
+ throw err;
32
+ }
33
+ return iconTableFromLucide();
34
+ }
35
+ /** Read the table from the installed `lucide-react` (needs it and React; the build and the source tree have both). */
36
+ export async function iconTableFromLucide() {
37
+ let pkgFile;
38
+ try {
39
+ pkgFile = fileURLToPath(import.meta.resolve('lucide-react/package.json'));
40
+ }
41
+ catch {
42
+ throw new Error('compileArtifact needs lucide-react installed in the source tree (dist/ ships icons.json)');
43
+ }
44
+ const pkg = JSON.parse(await readFile(pkgFile, 'utf8'));
45
+ const dir = path.join(path.dirname(pkgFile), 'dist', 'esm');
46
+ const entry = path.join(dir, 'lucide-react.mjs');
47
+ const index = await readFile(entry, 'utf8');
48
+ const names = {};
49
+ for (const m of index.matchAll(/export \{([^}]*)\} from '\.\/icons\/([^']+)\.mjs'/g)) {
50
+ for (const part of m[1].split(',')) {
51
+ const name = part.trim().split(/\s+as\s+/)[1];
52
+ if (name)
53
+ names[name] = m[2];
54
+ }
55
+ }
56
+ const nodes = {};
57
+ await Promise.all([...new Set(Object.values(names))].map(async (file) => {
58
+ const mod = (await import(__rewriteRelativeImportExtension(pathToFileURL(path.join(dir, 'icons', `${file}.mjs`)).href)));
59
+ nodes[file] = mod.__iconData.node.map(([tag, attrs]) => {
60
+ const { key: _key, ...rest } = attrs;
61
+ return [tag, rest];
62
+ });
63
+ }));
64
+ if (Object.keys(names).length < 1000)
65
+ throw new Error(`lucide-react ${pkg.version}: found only ${Object.keys(names).length} icon names; its layout changed`);
66
+ return { version: pkg.version, names, nodes };
67
+ }