dsh-artifact-studio 0.3.2 → 0.7.1

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.
@@ -0,0 +1,215 @@
1
+ import { Buffer } from 'node:buffer';
2
+ import fs from 'node:fs/promises';
3
+ import { SceneGraph } from '@open-pencil/scene-graph';
4
+ import { designJSXRenderer } from '@open-pencil/core/design-jsx';
5
+ import { fontManager } from '@open-pencil/core/text';
6
+ import { computeContentBounds, headlessRenderNodes } from '@open-pencil/core/io/formats/raster';
7
+ import { renderNodesToSVG } from '@open-pencil/core/io/formats/svg';
8
+ import { exportFigFile } from '@open-pencil/core/io/formats/fig';
9
+ import { bundledIconProvider } from '../../icon-set.js';
10
+ /** Fonts that ship with the package; any other family is substituted. */
11
+ const BUNDLED_FONTS = new Set(['Inter', 'Noto Naskh Arabic', 'Roboto']);
12
+ /** The Roboto faces the package ships, by style. */
13
+ const EXTRA_FONTS = [
14
+ ['Regular', 'Roboto-Regular.woff2'],
15
+ ['Medium', 'Roboto-Medium.woff2'],
16
+ ['Bold', 'Roboto-Bold.woff2'],
17
+ ];
18
+ /**
19
+ * Load the extra bundled faces into the font manager before anything compiles.
20
+ * The engine's own manifest only knows Inter and Noto, so a family is added here.
21
+ */
22
+ async function loadExtraFonts() {
23
+ for (const [style, file] of EXTRA_FONTS) {
24
+ const bytes = await fs.readFile(new URL('../../../assets/fonts/' + file, import.meta.url));
25
+ const copy = new Uint8Array(bytes.byteLength);
26
+ copy.set(bytes);
27
+ fontManager.markLoaded('Roboto', style, copy.buffer);
28
+ }
29
+ }
30
+ /** The bundled Material Design Icons set, read on the first icon. */
31
+ const { renderJSX } = designJSXRenderer(bundledIconProvider(async () => JSON.parse(await fs.readFile(new URL('../../../assets/icons.json', import.meta.url), 'utf8'))));
32
+ /**
33
+ * The message of a thrown value.
34
+ * @param error the value.
35
+ * @returns its message.
36
+ */
37
+ function messageOf(error) {
38
+ return error instanceof Error ? error.message : String(error);
39
+ }
40
+ /**
41
+ * Compile a source into a graph whose first page holds the top-level elements.
42
+ * @param source the Design JSX source.
43
+ * @returns the graph and page.
44
+ */
45
+ async function compile(source) {
46
+ const graph = new SceneGraph();
47
+ await renderJSX(graph, source);
48
+ const page = graph.getPages()[0];
49
+ if (page === undefined)
50
+ throw new Error('The design has no page.');
51
+ return { graph, page };
52
+ }
53
+ /**
54
+ * Every node below a page, depth first.
55
+ * @param graph the graph.
56
+ * @param page the page node.
57
+ * @returns the nodes.
58
+ */
59
+ function descendants(graph, page) {
60
+ const out = [];
61
+ const visit = (id) => {
62
+ const node = graph.getNode(id);
63
+ if (node === undefined)
64
+ return;
65
+ out.push(node);
66
+ for (const child of node.childIds)
67
+ visit(child);
68
+ };
69
+ for (const id of page.childIds)
70
+ visit(id);
71
+ return out;
72
+ }
73
+ /**
74
+ * Count the design's nodes, record its types and fonts, and warn about
75
+ * families the engine cannot load.
76
+ * @param graph the graph.
77
+ * @param page the page node.
78
+ * @returns the summary.
79
+ */
80
+ function summarize(graph, page) {
81
+ const nodes = descendants(graph, page);
82
+ const types = {};
83
+ const fonts = new Set();
84
+ for (const node of nodes) {
85
+ const type = String(node.type);
86
+ types[type] = (types[type] ?? 0) + 1;
87
+ if (typeof node.fontFamily === 'string' && node.fontFamily.trim() !== '')
88
+ fonts.add(node.fontFamily.trim());
89
+ }
90
+ const sorted = [...fonts].sort();
91
+ const warnings = sorted
92
+ .filter((family) => !BUNDLED_FONTS.has(family))
93
+ .map((family) => `Font "${family}" is not bundled. The preview substitutes a default face.`);
94
+ return { pages: graph.getPages().length, nodes: nodes.length, types, fonts: sorted, warnings };
95
+ }
96
+ /**
97
+ * Read a PNG's pixel size from its IHDR chunk.
98
+ * @param bytes the PNG file.
99
+ * @returns the size.
100
+ */
101
+ function pngSize(bytes) {
102
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
103
+ return { width: view.getUint32(16), height: view.getUint32(20) };
104
+ }
105
+ /**
106
+ * Rasterize the page, scaled down when it is wider or taller than the cap.
107
+ * @param compiled the graph.
108
+ * @param maxSide the longest side, or zero for the design's own size.
109
+ * @returns the PNG bytes, or null for an empty design.
110
+ */
111
+ async function renderPng(compiled, maxSide) {
112
+ const bounds = computeContentBounds(compiled.graph, compiled.page.childIds);
113
+ if (bounds === null)
114
+ return null;
115
+ const width = bounds.maxX - bounds.minX;
116
+ const height = bounds.maxY - bounds.minY;
117
+ const longest = Math.max(width, height);
118
+ const scale = maxSide > 0 && longest > maxSide ? maxSide / longest : 1;
119
+ return headlessRenderNodes(compiled.graph, compiled.page.id, compiled.page.childIds, {
120
+ scale,
121
+ format: 'PNG',
122
+ trimTransparent: true,
123
+ });
124
+ }
125
+ /**
126
+ * Answer one request.
127
+ * @param source the Design JSX source.
128
+ * @param request the request.
129
+ * @returns the response.
130
+ */
131
+ async function handle(source, request) {
132
+ let compiled;
133
+ try {
134
+ compiled = await compile(source);
135
+ }
136
+ catch (error) {
137
+ const message = messageOf(error);
138
+ const missing = /^Icon "([^"]+)" not found$/.exec(message);
139
+ if (missing !== null) {
140
+ return { ok: false, code: 'artifact/design-icon-not-found', message: 'The bundled mdi set has no "' + (missing[1] ?? '') + '". Use a name from the mdi set.' };
141
+ }
142
+ if (/^Icon set "[^"]+" is not bundled\./.test(message)) {
143
+ return { ok: false, code: 'artifact/design-icon-not-found', message };
144
+ }
145
+ return { ok: false, code: 'artifact/design-invalid', message };
146
+ }
147
+ const info = summarize(compiled.graph, compiled.page);
148
+ if (info.nodes === 0) {
149
+ return {
150
+ ok: false,
151
+ code: 'artifact/design-invalid',
152
+ message: 'The design has no top-level elements. Wrap the layout in a <Frame>.',
153
+ };
154
+ }
155
+ if (request.action === 'inspect')
156
+ return { ok: true, info };
157
+ try {
158
+ if (request.action === 'preview') {
159
+ const png = await renderPng(compiled, request.maxSide ?? 1600);
160
+ if (png === null)
161
+ return { ok: false, code: 'artifact/design-render-failed', message: 'The design produced no image.' };
162
+ const size = pngSize(png);
163
+ return { ok: true, info, mediaType: 'image/png', data: Buffer.from(png).toString('base64'), width: size.width, height: size.height };
164
+ }
165
+ if (request.format === 'fig') {
166
+ const bytes = await exportFigFile(compiled.graph);
167
+ return { ok: true, info, mediaType: 'application/octet-stream', data: Buffer.from(bytes).toString('base64') };
168
+ }
169
+ if (request.format === 'svg') {
170
+ const svg = renderNodesToSVG(compiled.graph, compiled.page.id, compiled.page.childIds, { xmlDeclaration: true });
171
+ if (svg === null)
172
+ return { ok: false, code: 'artifact/design-render-failed', message: 'The design produced no SVG.' };
173
+ return { ok: true, info, mediaType: 'image/svg+xml', data: Buffer.from(svg, 'utf8').toString('base64') };
174
+ }
175
+ const png = await renderPng(compiled, 0);
176
+ if (png === null)
177
+ return { ok: false, code: 'artifact/design-render-failed', message: 'The design produced no image.' };
178
+ const size = pngSize(png);
179
+ return { ok: true, info, mediaType: 'image/png', data: Buffer.from(png).toString('base64'), width: size.width, height: size.height };
180
+ }
181
+ catch (error) {
182
+ return { ok: false, code: 'artifact/design-render-failed', message: messageOf(error) };
183
+ }
184
+ }
185
+ /**
186
+ * Read the one JSON request from stdin.
187
+ * @returns the request.
188
+ */
189
+ async function readRequest() {
190
+ const chunks = [];
191
+ for await (const chunk of process.stdin)
192
+ chunks.push(Buffer.from(chunk));
193
+ const parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
194
+ if (parsed === null || typeof parsed !== 'object')
195
+ throw new Error('The design request is not an object.');
196
+ const fields = { ...parsed };
197
+ if (typeof fields.nonce !== 'string' || fields.nonce === '')
198
+ throw new Error('The design request has no nonce.');
199
+ if (typeof fields.source !== 'string')
200
+ throw new Error('The design request has no source.');
201
+ if (fields.action !== 'inspect' && fields.action !== 'preview' && fields.action !== 'export') {
202
+ throw new Error('The design request has an unknown action.');
203
+ }
204
+ return {
205
+ nonce: fields.nonce,
206
+ action: fields.action,
207
+ source: fields.source,
208
+ ...(typeof fields.maxSide === 'number' ? { maxSide: fields.maxSide } : {}),
209
+ ...(fields.format === 'png' || fields.format === 'svg' || fields.format === 'fig' ? { format: fields.format } : {}),
210
+ };
211
+ }
212
+ await loadExtraFonts();
213
+ const request = await readRequest();
214
+ const response = await handle(request.source, request);
215
+ process.stdout.write(request.nonce + JSON.stringify(response) + '\n', () => process.exit(0));
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,81 @@
1
+ import { createIconifyProvider } from '@open-pencil/core/icons';
2
+ /**
3
+ * Tell a bundled icon file from an unknown value.
4
+ * @param value the parsed JSON.
5
+ * @returns whether it has the shape the provider needs.
6
+ */
7
+ function isIconSet(value) {
8
+ if (value === null || typeof value !== 'object')
9
+ return false;
10
+ const fields = { ...value };
11
+ if (typeof fields['prefix'] !== 'string' || fields['prefix'] === '')
12
+ return false;
13
+ if (fields['icons'] === null || typeof fields['icons'] !== 'object')
14
+ return false;
15
+ return true;
16
+ }
17
+ /**
18
+ * Tell one icon body from an unknown value.
19
+ * @param value the entry.
20
+ * @returns whether it has a body.
21
+ */
22
+ function isBody(value) {
23
+ if (value === null || typeof value !== 'object')
24
+ return false;
25
+ return typeof value['body'] === 'string';
26
+ }
27
+ /**
28
+ * An icon provider over one bundled Iconify set. The file is loaded on the first
29
+ * icon, so a design without icons never reads it. Unknown sets and names fail
30
+ * with a message rather than falling back to the network.
31
+ * @param load reads and parses the bundled JSON.
32
+ * @returns the provider.
33
+ */
34
+ export function bundledIconProvider(load) {
35
+ let set = null;
36
+ const file = () => {
37
+ set ??= load().then((value) => {
38
+ if (!isIconSet(value))
39
+ throw new Error('The bundled icon set is malformed.');
40
+ return value;
41
+ });
42
+ set.catch(() => {
43
+ set = null;
44
+ });
45
+ return set;
46
+ };
47
+ const name = async () => (await file()).prefix;
48
+ return createIconifyProvider({
49
+ async fetchCollection(prefix, iconNames) {
50
+ const data = await file();
51
+ if (prefix !== data.prefix)
52
+ throw new Error('Icon set "' + prefix + '" is not bundled. Use ' + data.prefix + ':<name>.');
53
+ const icons = {};
54
+ for (const iconName of iconNames) {
55
+ const entry = data.icons[iconName];
56
+ if (isBody(entry))
57
+ icons[iconName] = { body: entry.body, width: entry.width, height: entry.height };
58
+ }
59
+ return { prefix, width: data.width, height: data.height, icons, aliases: data.aliases };
60
+ },
61
+ async collections() {
62
+ const data = await file();
63
+ return [{ prefix: data.prefix, name: 'Material Design Icons', total: Object.keys(data.icons).length, category: 'General', license: 'Apache-2.0', multicolor: false }];
64
+ },
65
+ async collectionIcons() {
66
+ const data = await file();
67
+ return Object.keys(data.icons).map((iconName) => data.prefix + ':' + iconName);
68
+ },
69
+ async search(query, options) {
70
+ const data = await file();
71
+ const prefix = await name();
72
+ const limit = options?.limit ?? 20;
73
+ const needle = query.toLowerCase();
74
+ const icons = Object.keys(data.icons)
75
+ .filter((iconName) => iconName.toLowerCase().includes(needle))
76
+ .slice(0, limit)
77
+ .map((iconName) => prefix + ':' + iconName);
78
+ return { icons, total: icons.length, collections: { [prefix]: { name: 'Material Design Icons', total: Object.keys(data.icons).length, category: 'General' } } };
79
+ },
80
+ });
81
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-artifact-studio",
3
- "version": "0.3.2",
3
+ "version": "0.7.1",
4
4
  "type": "module",
5
5
  "description": "Local-first artifacts for DeepSeek Harness: the agent creates pages and documents as versioned files, and you open, edit, restore, and export them beside the chat.",
6
6
  "keywords": [
@@ -27,11 +27,14 @@
27
27
  "dist",
28
28
  "client.js",
29
29
  "client.doc.js",
30
+ "client.canvas.js",
31
+ "assets",
30
32
  "cordis.patch.yml",
31
33
  "locale/*.json",
32
34
  "icon.svg",
33
35
  "LICENSE",
34
- "README.md"
36
+ "README.md",
37
+ "THIRD_PARTY_NOTICES.md"
35
38
  ],
36
39
  "dsh": {
37
40
  "bundle": {
@@ -59,10 +62,13 @@
59
62
  "prepack": "node scripts/check-icon.mjs"
60
63
  },
61
64
  "dependencies": {
65
+ "@open-pencil/core": "0.16.0",
62
66
  "docx": "9.15.3",
63
67
  "marked": "^17.0.1"
64
68
  },
65
69
  "devDependencies": {
70
+ "@iconify-json/mdi": "1.2.3",
71
+ "@open-pencil/vue": "0.16.0",
66
72
  "@tiptap/core": "3.33.1",
67
73
  "@tiptap/extension-list": "^3.33.1",
68
74
  "@tiptap/extension-table": "^3.33.1",
@@ -72,10 +78,13 @@
72
78
  "@types/node": "^22.20.5",
73
79
  "@types/react": "^18.3.31",
74
80
  "@types/react-dom": "^18.3.7",
81
+ "canvaskit-wasm": "0.41.1",
75
82
  "esbuild": "^0.25.0",
76
83
  "jsdom": "^25.0.1",
77
84
  "react": "18.3.1",
78
85
  "react-dom": "18.3.1",
79
- "typescript": "^5.9.3"
86
+ "roboto-fontface": "0.10.0",
87
+ "typescript": "^5.9.3",
88
+ "vue": "3.5.41"
80
89
  }
81
90
  }