topotopo 0.2.0 → 0.4.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.
Files changed (132) hide show
  1. package/NOTICE +30 -0
  2. package/README.md +54 -16
  3. package/dist/cli.js +95 -14
  4. package/dist/core/analysis.d.ts +5 -1
  5. package/dist/core/analysis.js +8 -3
  6. package/dist/core/bake.d.ts +2 -5
  7. package/dist/core/bake.js +12 -25
  8. package/dist/core/bevel.js +165 -97
  9. package/dist/core/geometry.js +1 -1
  10. package/dist/core/imageops.d.ts +6 -0
  11. package/dist/core/imageops.js +51 -0
  12. package/dist/core/materials.d.ts +4 -0
  13. package/dist/core/materials.js +11 -0
  14. package/dist/core/packed.js +11 -0
  15. package/dist/core/particles.d.ts +1 -1
  16. package/dist/core/particles.js +1 -1
  17. package/dist/core/rbd.js +13 -1
  18. package/dist/core/scatter.d.ts +1 -1
  19. package/dist/core/scatter.js +1 -1
  20. package/dist/core/scene.d.ts +20 -0
  21. package/dist/core/scene.js +71 -0
  22. package/dist/core/snippet-lib.d.ts +1 -1
  23. package/dist/core/snippet-lib.js +1 -1
  24. package/dist/core/solidify.d.ts +38 -0
  25. package/dist/core/solidify.js +356 -0
  26. package/dist/core/tangents.d.ts +52 -0
  27. package/dist/core/tangents.js +214 -0
  28. package/dist/core/texcoord.d.ts +4 -0
  29. package/dist/core/texcoord.js +14 -0
  30. package/dist/core/topology.d.ts +22 -0
  31. package/dist/core/topology.js +70 -7
  32. package/dist/core/traceimage.d.ts +7 -0
  33. package/dist/core/traceimage.js +221 -0
  34. package/dist/core/tritri.d.ts +5 -0
  35. package/dist/core/tritri.js +120 -0
  36. package/dist/core/uv.d.ts +13 -0
  37. package/dist/core/uv.js +3 -3
  38. package/dist/core/uvreport.d.ts +66 -0
  39. package/dist/core/uvreport.js +308 -0
  40. package/dist/core/xatlas.js +32 -2
  41. package/dist/gallery/app/gallery.css +100 -0
  42. package/dist/gallery/app/gallery.js +80 -0
  43. package/dist/gallery/bake.d.ts +34 -0
  44. package/dist/gallery/bake.js +144 -0
  45. package/dist/gallery/cli.d.ts +4 -0
  46. package/dist/gallery/cli.js +157 -0
  47. package/dist/gallery/library.d.ts +124 -0
  48. package/dist/gallery/library.js +366 -0
  49. package/dist/gallery/pages.d.ts +94 -0
  50. package/dist/gallery/pages.js +148 -0
  51. package/dist/gallery/server.d.ts +21 -0
  52. package/dist/gallery/server.js +391 -0
  53. package/dist/graph/engine.js +14 -0
  54. package/dist/graph/types.d.ts +17 -0
  55. package/dist/host/artifacts.d.ts +21 -0
  56. package/dist/host/artifacts.js +58 -0
  57. package/dist/host/export-targets.d.ts +33 -0
  58. package/dist/host/export-targets.js +84 -0
  59. package/dist/index.d.ts +3 -1
  60. package/dist/index.js +2 -1
  61. package/dist/inspect.d.ts +6 -1
  62. package/dist/inspect.js +13 -1
  63. package/dist/io/common.d.ts +8 -0
  64. package/dist/io/gltf.js +236 -19
  65. package/dist/io/targets.d.ts +31 -0
  66. package/dist/io/targets.js +75 -0
  67. package/dist/mcp/docs.d.ts +1 -1
  68. package/dist/mcp/docs.js +73 -6
  69. package/dist/mcp/library.d.ts +12 -0
  70. package/dist/mcp/library.js +159 -0
  71. package/dist/mcp/server.js +29 -12
  72. package/dist/mcp/tools.d.ts +1 -1
  73. package/dist/mcp/tools.js +102 -43
  74. package/dist/nodes/bake.js +56 -36
  75. package/dist/nodes/bevel.js +4 -3
  76. package/dist/nodes/code.js +33 -7
  77. package/dist/nodes/curves.js +7 -0
  78. package/dist/nodes/generate.js +1 -1
  79. package/dist/nodes/imageops.d.ts +1 -0
  80. package/dist/nodes/imageops.js +206 -0
  81. package/dist/nodes/index.d.ts +3 -0
  82. package/dist/nodes/index.js +3 -0
  83. package/dist/nodes/material.js +3 -0
  84. package/dist/nodes/measure.js +3 -2
  85. package/dist/nodes/rbd.js +1 -1
  86. package/dist/nodes/scene.d.ts +1 -0
  87. package/dist/nodes/scene.js +53 -0
  88. package/dist/nodes/solidify.d.ts +1 -0
  89. package/dist/nodes/solidify.js +52 -0
  90. package/dist/nodes/transform.js +5 -1
  91. package/dist/nodes/util.d.ts +1 -1
  92. package/dist/nodes/wasmcall.js +1 -1
  93. package/dist/render/options.js +1 -1
  94. package/dist/render/pbr.d.ts +28 -0
  95. package/dist/render/pbr.js +378 -0
  96. package/dist/render/preview.d.ts +58 -0
  97. package/dist/render/preview.js +24 -0
  98. package/dist/render/raster.d.ts +12 -2
  99. package/dist/render/raster.js +98 -11
  100. package/dist/render/texview.d.ts +1 -1
  101. package/dist/render/texview.js +7 -2
  102. package/dist/viewer/app/camera.js +27 -7
  103. package/dist/viewer/app/embed.js +80 -0
  104. package/dist/viewer/app/export-popover.js +68 -0
  105. package/dist/viewer/app/grid.js +1 -1
  106. package/dist/viewer/app/guides.js +1 -1
  107. package/dist/viewer/app/image-view.js +114 -0
  108. package/dist/viewer/app/keymap.js +15 -3
  109. package/dist/viewer/app/layers.js +24 -5
  110. package/dist/viewer/app/main.js +71 -15
  111. package/dist/viewer/app/markers.js +1 -1
  112. package/dist/viewer/app/outliner.js +56 -15
  113. package/dist/viewer/app/outputs.css +73 -0
  114. package/dist/viewer/app/outputs.js +240 -0
  115. package/dist/viewer/app/props.js +1 -1
  116. package/dist/viewer/app/scene.js +6 -2
  117. package/dist/viewer/app/select.js +14 -3
  118. package/dist/viewer/app/selection.js +1 -1
  119. package/dist/viewer/app/status.js +20 -0
  120. package/dist/viewer/app/style.css +2 -1
  121. package/dist/viewer/app/units.js +1 -1
  122. package/dist/viewer/app/vars.js +1 -1
  123. package/dist/viewer/index.html +20 -6
  124. package/dist/viewer/outputs.d.ts +54 -0
  125. package/dist/viewer/outputs.js +436 -0
  126. package/dist/viewer/server.d.ts +19 -2
  127. package/dist/viewer/server.js +77 -9
  128. package/dist/workspace.d.ts +21 -2
  129. package/dist/workspace.js +124 -4
  130. package/kernels/pkg/README.md +21 -28
  131. package/kernels/pkg-simd/README.md +21 -28
  132. package/package.json +11 -4
@@ -0,0 +1,391 @@
1
+ // The gallery web server: every library's projects as a grid, a page per project with its 3D
2
+ // preview, and stable URLs a board pastes (link, thumbnail, iframe embed). It reads files and serves baked previews;
3
+ // it never cooks: bakes run in child processes (BakeQueue) and "Open in editor" starts a `topotopo edit` child.
4
+ // Bound to 127.0.0.1 on a fixed port (stable links); requests must name this server as their Host, and writes must
5
+ // come from its own pages.
6
+ import http from 'node:http';
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import zlib from 'node:zlib';
10
+ import { spawn } from 'node:child_process';
11
+ import { fileURLToPath } from 'node:url';
12
+ import { encodePNG } from '../render/png.js';
13
+ import { MIME, appDir, threeDir } from '../viewer/server.js';
14
+ import { galleryDir, graphNames, isStale, listFiles, loadConfig, readBakeState, readGraph, scanLibrary } from './library.js';
15
+ import { BakeQueue } from './bake.js';
16
+ import { embedPage, galleryPage, projectPage } from './pages.js';
17
+ const here = path.dirname(fileURLToPath(import.meta.url));
18
+ const assetDir = path.join(here, 'app');
19
+ const cli = path.resolve(here, '..', import.meta.url.endsWith('.ts') ? 'cli.ts' : 'cli.js');
20
+ const RESCAN_MS = 5 * 60_000;
21
+ const EDITOR_START_MS = 60_000;
22
+ const FILE_TYPES = {
23
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.avif': 'image/avif',
24
+ '.pdf': 'application/pdf', '.txt': 'text/plain; charset=utf-8', '.md': 'text/plain; charset=utf-8', '.json': 'application/json',
25
+ '.glb': 'model/gltf-binary', '.csv': 'text/csv; charset=utf-8',
26
+ };
27
+ /** shown inline; everything else (SVG and HTML among them: they run scripts) is a download */
28
+ const INLINE = new Set(['.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.pdf', '.txt', '.md', '.json', '.csv']);
29
+ class HttpError extends Error {
30
+ status;
31
+ constructor(status, msg) { super(msg); this.status = status; }
32
+ }
33
+ /** A gallery answers here already: its URL, or null. */
34
+ export async function runningGallery(port) {
35
+ try {
36
+ const res = await fetch(`http://127.0.0.1:${port}/api/health`, { signal: AbortSignal.timeout(1500) });
37
+ const j = await res.json();
38
+ return j?.gallery ? `http://127.0.0.1:${port}/` : null;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ export async function startGallery(o = {}) {
45
+ const cfg = o.config ?? loadConfig();
46
+ const log = o.log ?? (() => { });
47
+ const bakeOn = o.bake ?? true;
48
+ let base = '';
49
+ // ---------------------------------------------------------------- libraries
50
+ let scans = [];
51
+ const projects = new Map();
52
+ const keyOf = (p) => `${p.lib}/${p.id}`;
53
+ const rescan = () => {
54
+ scans = cfg.libraries.map(scanLibrary);
55
+ projects.clear();
56
+ for (const s of scans)
57
+ for (const p of s.projects)
58
+ projects.set(keyOf(p), p);
59
+ };
60
+ const find = (lib, id) => {
61
+ let p = projects.get(`${lib}/${id}`);
62
+ if (!p) {
63
+ rescan();
64
+ p = projects.get(`${lib}/${id}`);
65
+ } // made a moment ago, before the watch noticed
66
+ if (!p)
67
+ throw new HttpError(404, `no project "${id}" in library "${lib}"`);
68
+ return p;
69
+ };
70
+ // ---------------------------------------------------------------- events (SSE) and bakes
71
+ const clients = new Set();
72
+ const broadcast = (ev) => { const m = `data: ${JSON.stringify(ev)}\n\n`; for (const c of clients)
73
+ c.write(m); };
74
+ const queue = new BakeQueue({
75
+ log,
76
+ onDone: (dir, state) => {
77
+ const p = [...projects.values()].find((x) => x.dir === dir);
78
+ if (p)
79
+ broadcast({ project: keyOf(p), ok: state?.ok ?? false, version: state?.at ?? 0 });
80
+ },
81
+ });
82
+ const bakeIfStale = (p) => {
83
+ if (!bakeOn || queue.pending(p.dir))
84
+ return;
85
+ try {
86
+ if (isStale(p) && queue.add(p.dir))
87
+ broadcast({ project: keyOf(p), baking: true });
88
+ }
89
+ catch { /* removed meanwhile */ }
90
+ };
91
+ rescan();
92
+ for (const p of projects.values())
93
+ bakeIfStale(p);
94
+ // A change below a library: project.json, graphs/, assets/ and inputs/ may need a bake; anything else may be a
95
+ // project made, moved or removed, or attachments: read the libraries again and tell the pages.
96
+ const touched = new Set();
97
+ let changeTimer;
98
+ const onChange = () => {
99
+ clearTimeout(changeTimer);
100
+ changeTimer = setTimeout(() => {
101
+ const before = [...projects.keys()].join('\n');
102
+ rescan();
103
+ for (const k of touched) {
104
+ const p = projects.get(k);
105
+ if (p)
106
+ bakeIfStale(p);
107
+ }
108
+ for (const p of projects.values())
109
+ if (!readBakeState(p.dir))
110
+ bakeIfStale(p);
111
+ broadcast({ changed: [...touched], list: before !== [...projects.keys()].join('\n') });
112
+ touched.clear();
113
+ }, 500);
114
+ };
115
+ const watchers = [];
116
+ for (const s of scans) {
117
+ try {
118
+ const w = fs.watch(s.root, { recursive: true }, (_ev, f) => {
119
+ const rel = f ? String(f).split(path.sep).join('/') : '';
120
+ if (path.isAbsolute(rel))
121
+ return; // the root itself went away: the periodic rescan notices
122
+ const parts = rel.split('/');
123
+ if (parts.some((x) => x.startsWith('.') || x === 'node_modules'))
124
+ return; // .gallery/, .cache/, .part files
125
+ const p = scans.find((x) => x.root === s.root)?.projects.find((x) => rel === x.rel || rel.startsWith(x.rel + '/'));
126
+ if (p)
127
+ touched.add(keyOf(p));
128
+ onChange();
129
+ });
130
+ w.on('error', () => w.close());
131
+ w.unref();
132
+ watchers.push(w);
133
+ }
134
+ catch { /* no folder (a problem on the page) or no recursive watch: the periodic rescan covers it */ }
135
+ }
136
+ const periodic = setInterval(() => { rescan(); for (const p of projects.values())
137
+ bakeIfStale(p); }, RESCAN_MS);
138
+ periodic.unref();
139
+ // ---------------------------------------------------------------- editors
140
+ const editors = new Map();
141
+ const editorFor = (p) => {
142
+ const have = editors.get(p.dir);
143
+ if (have && have.child.exitCode === null)
144
+ return have.url;
145
+ const child = spawn(process.execPath, [cli, 'edit', p.dir, '--json'], { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true });
146
+ const url = new Promise((resolve, reject) => {
147
+ let out = '', err = '';
148
+ const t = setTimeout(() => { child.kill(); reject(new Error('the editor did not start within a minute')); }, EDITOR_START_MS);
149
+ child.stdout.on('data', (d) => {
150
+ out += d;
151
+ const line = out.split('\n').find((l) => l.startsWith('{'));
152
+ if (line) {
153
+ clearTimeout(t);
154
+ try {
155
+ resolve(JSON.parse(line).url);
156
+ }
157
+ catch (e) {
158
+ reject(e);
159
+ }
160
+ }
161
+ });
162
+ child.stderr.on('data', (d) => { if (err.length < 4000)
163
+ err += d; });
164
+ child.on('exit', (code) => { clearTimeout(t); editors.delete(p.dir); reject(new Error(`the editor stopped (exit ${code}): ${err.trim().split('\n').slice(-3).join(' ')}`)); });
165
+ });
166
+ url.catch(() => { });
167
+ editors.set(p.dir, { child, url });
168
+ return url;
169
+ };
170
+ const reveal = (dir) => {
171
+ const [cmd, args] = process.platform === 'win32' ? ['explorer.exe', [dir]] : process.platform === 'darwin' ? ['open', [dir]] : ['xdg-open', [dir]];
172
+ const c = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: false });
173
+ c.on('error', () => { });
174
+ c.unref();
175
+ };
176
+ // ---------------------------------------------------------------- page data
177
+ const enc = encodeURIComponent;
178
+ const urls = {
179
+ home: '/',
180
+ project: (lib, id) => `/p/${enc(lib)}/${enc(id)}`,
181
+ thumb: (lib, id, v) => `/p/${enc(lib)}/${enc(id)}/thumb.png${v ? `?v=${enc(String(v))}` : ''}`,
182
+ glb: (lib, id, v) => `/p/${enc(lib)}/${enc(id)}/preview.glb${v ? `?v=${enc(String(v))}` : ''}`,
183
+ embed: (lib, id) => `/embed/${enc(lib)}/${enc(id)}`,
184
+ file: (lib, id, rel) => `/p/${enc(lib)}/${enc(id)}/files/${rel.split('/').map(enc).join('/')}`,
185
+ edit: (lib, id) => `/p/${enc(lib)}/${enc(id)}/edit`,
186
+ asset: (name) => `/static/${name}`,
187
+ app: (name) => `/app/${name}`,
188
+ three: '/vendor/three/',
189
+ };
190
+ const status = (p, s) => (queue.pending(p.dir) ? 'baking' : !s ? 'new' : s.ok ? 'ok' : 'failed');
191
+ const cardOf = (p) => {
192
+ const s = readBakeState(p.dir);
193
+ const m = p.manifest;
194
+ return { lib: p.lib, id: p.id, title: m.title, collection: p.collection, tags: m.tags, description: m.description, updated: p.updated, status: status(p, s), version: String(s?.at ?? 0) };
195
+ };
196
+ const projectData = (p) => {
197
+ const s = readBakeState(p.dir);
198
+ const graphs = graphNames(p.dir).map((name) => {
199
+ const g = readGraph(p.dir, name) ?? {};
200
+ const meta = g.params ?? {};
201
+ return {
202
+ name, nodes: Object.keys(g.nodes ?? {}).length,
203
+ vars: Object.entries(g.vars ?? {}).map(([k, v]) => ({ name: k, value: v, desc: meta[k]?.desc ?? meta[k]?.label, min: meta[k]?.min, max: meta[k]?.max })),
204
+ };
205
+ });
206
+ const abs = (u) => base + u;
207
+ return {
208
+ ...cardOf(p), rel: p.rel, links: p.manifest.links, graph: p.manifest.graph, graphs, created: p.manifest.created,
209
+ attachments: listFiles(path.join(p.dir, 'attachments')), exports: listFiles(path.join(p.dir, 'exports')),
210
+ glb: fs.existsSync(path.join(galleryDir(p.dir), 'preview.glb')), bake: s,
211
+ share: { link: abs(urls.project(p.lib, p.id)), thumb: abs(urls.thumb(p.lib, p.id)), embed: abs(urls.embed(p.lib, p.id)) },
212
+ };
213
+ };
214
+ const listJSON = () => [...projects.values()].map((p) => {
215
+ const c = cardOf(p);
216
+ return {
217
+ lib: p.lib, id: p.id, title: c.title, description: c.description, tags: c.tags, collection: c.collection, updated: p.updated, status: c.status,
218
+ url: base + urls.project(p.lib, p.id), thumb: base + urls.thumb(p.lib, p.id, c.version), embed: base + urls.embed(p.lib, p.id),
219
+ };
220
+ });
221
+ let placeholder = null;
222
+ const placeholderPNG = () => {
223
+ if (!placeholder) {
224
+ const n = 64, rgba = new Uint8Array(n * n * 4);
225
+ for (let i = 0; i < n * n; i++)
226
+ rgba.set([0x2b, 0x2d, 0x31, 0xff], i * 4);
227
+ placeholder = encodePNG(rgba, n, n, (d) => zlib.deflateSync(d));
228
+ }
229
+ return placeholder;
230
+ };
231
+ /** `files/<rest>` of a project: below attachments/ or exports/, never outside them (links included). */
232
+ const projectFile = (p, rest) => {
233
+ const parts = rest.split('/').map((x) => decodeURIComponent(x));
234
+ // decoded segments: "%2F" and "%5C" must not smuggle separators (and so "..") past the split
235
+ if (!['attachments', 'exports'].includes(parts[0]) || parts.length < 2 || parts.some((x) => !x || x === '.' || x === '..' || /[\\/\0]/.test(x)))
236
+ throw new HttpError(400, 'files/ serves attachments/<path> and exports/<path>');
237
+ const root = path.join(p.dir, parts[0]);
238
+ const abs = path.join(root, ...parts.slice(1));
239
+ if (!abs.startsWith(root + path.sep))
240
+ throw new HttpError(400, 'the path leaves the project');
241
+ if (!fs.statSync(abs, { throwIfNoEntry: false })?.isFile())
242
+ throw new HttpError(404, `no file ${parts.join('/')}`);
243
+ const real = path.relative(fs.realpathSync(root), fs.realpathSync(abs));
244
+ if (real.startsWith('..') || path.isAbsolute(real))
245
+ throw new HttpError(400, 'the path leaves the project');
246
+ return abs;
247
+ };
248
+ const readStatic = (dir, rel) => {
249
+ const p = path.resolve(dir, decodeURIComponent(rel));
250
+ if (!p.startsWith(dir + path.sep) || !fs.statSync(p, { throwIfNoEntry: false })?.isFile())
251
+ return null;
252
+ return p;
253
+ };
254
+ // ---------------------------------------------------------------- routes
255
+ const server = http.createServer(async (req, res) => {
256
+ const head = (code, type, extra = {}) => res.writeHead(code, { 'content-type': type, 'cache-control': 'no-store', 'x-content-type-options': 'nosniff', ...extra });
257
+ const send = (code, body, type = 'text/plain; charset=utf-8', extra = {}) => { head(code, type, extra); res.end(req.method === 'HEAD' ? undefined : body); };
258
+ // pages may only be framed by the gallery itself; the embed page is made to be framed by a board
259
+ const html = (body, framable = false) => send(200, body, MIME['.html'], framable ? {} : { 'content-security-policy': "frame-ancestors 'self'" });
260
+ const json = (code, body, extra = {}) => send(code, JSON.stringify(body), MIME['.json'], extra);
261
+ try {
262
+ const host = String(req.headers.host ?? '');
263
+ if (!/^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/i.test(host))
264
+ return json(403, { error: `unexpected Host "${host}"` });
265
+ const origin = req.headers.origin;
266
+ const write = req.method !== 'GET' && req.method !== 'HEAD';
267
+ if (write && origin !== undefined && origin !== `http://${host}`)
268
+ return json(403, { error: `cross-origin ${req.method} refused (${origin})` });
269
+ const u = new URL(req.url ?? '/', 'http://localhost');
270
+ const seg = u.pathname.split('/').slice(1);
271
+ if (u.pathname === '/' || u.pathname === '/index.html') {
272
+ return html(galleryPage({ libraries: scans.map((s) => ({ name: s.name, cards: s.projects.map(cardOf) })), problems: scans.flatMap((s) => s.problems) }, urls));
273
+ }
274
+ if (seg[0] === 'static') {
275
+ const p = readStatic(assetDir, seg.slice(1).join('/'));
276
+ return p ? send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream') : send(404, 'not found');
277
+ }
278
+ if (seg[0] === 'app') {
279
+ const p = readStatic(appDir, seg.slice(1).join('/'));
280
+ return p ? send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream') : send(404, 'not found');
281
+ }
282
+ if (seg[0] === 'vendor' && seg[1] === 'three') {
283
+ const p = readStatic(threeDir, seg.slice(2).join('/'));
284
+ return p ? send(200, fs.readFileSync(p), MIME[path.extname(p)] ?? 'application/octet-stream', { 'cache-control': 'max-age=3600' }) : send(404, 'not found');
285
+ }
286
+ if (u.pathname === '/api/health')
287
+ return json(200, { gallery: true, libraries: scans.length, projects: projects.size, baking: queue.size });
288
+ if (u.pathname === '/api/events') {
289
+ res.writeHead(200, { 'content-type': 'text/event-stream', 'cache-control': 'no-store', connection: 'keep-alive' });
290
+ res.write(': hello\n\n');
291
+ clients.add(res);
292
+ req.on('close', () => clients.delete(res));
293
+ return;
294
+ }
295
+ if (u.pathname === '/api/projects') {
296
+ // a board on another origin may read the list when the config allows it (gallery.cors)
297
+ const cors = origin && cfg.gallery.cors.includes(origin) ? { 'access-control-allow-origin': origin, vary: 'Origin' } : { vary: 'Origin' };
298
+ if (req.method === 'OPTIONS')
299
+ return send(204, '', 'text/plain', { ...cors, 'access-control-allow-methods': 'GET' });
300
+ return json(200, { libraries: scans.map((s) => ({ name: s.name, projects: s.projects.length, problems: s.problems })), projects: listJSON() }, cors);
301
+ }
302
+ if (seg[0] === 'embed' && seg.length === 3) {
303
+ const p = find(decodeURIComponent(seg[1]), decodeURIComponent(seg[2]));
304
+ const s = readBakeState(p.dir);
305
+ const glb = fs.existsSync(path.join(galleryDir(p.dir), 'preview.glb'));
306
+ return html(embedPage({ lib: p.lib, id: p.id, title: p.manifest.title, glb, version: String(s?.at ?? 0), projectUrl: urls.project(p.lib, p.id) }, urls), true);
307
+ }
308
+ if (seg[0] === 'p' && seg.length >= 3) {
309
+ const p = find(decodeURIComponent(seg[1]), decodeURIComponent(seg[2]));
310
+ const rest = seg.slice(3);
311
+ if (!rest.length || (rest.length === 1 && !rest[0]))
312
+ return html(projectPage(projectData(p), urls));
313
+ if (rest[0] === 'thumb.png' || rest[0] === 'preview.glb') {
314
+ const s = readBakeState(p.dir);
315
+ const file = path.join(galleryDir(p.dir), rest[0]);
316
+ if (!fs.existsSync(file)) {
317
+ bakeIfStale(p);
318
+ if (rest[0] === 'thumb.png')
319
+ return send(200, placeholderPNG(), 'image/png');
320
+ return json(404, { error: s?.ok === false ? `the bake failed: ${s.error}` : 'not baked yet' });
321
+ }
322
+ const etag = `"${s?.key ?? 'x'}-${s?.at ?? 0}"`;
323
+ if (req.headers['if-none-match'] === etag) {
324
+ res.writeHead(304, { etag });
325
+ return res.end();
326
+ }
327
+ return send(200, fs.readFileSync(file), rest[0] === 'thumb.png' ? 'image/png' : MIME['.glb'], { etag, 'cache-control': 'no-cache' });
328
+ }
329
+ if (rest[0] === 'files' && rest.length > 1) {
330
+ const abs = projectFile(p, rest.slice(1).join('/'));
331
+ const ext = path.extname(abs).toLowerCase();
332
+ const disp = INLINE.has(ext) ? {} : { 'content-disposition': `attachment; filename="${path.basename(abs).replace(/["\\\r\n]/g, '_')}"` };
333
+ return send(200, fs.readFileSync(abs), FILE_TYPES[ext] ?? 'application/octet-stream', { ...disp, 'content-security-policy': 'sandbox' });
334
+ }
335
+ if (rest[0] === 'edit') {
336
+ const url = await editorFor(p);
337
+ res.writeHead(302, { location: url, 'cache-control': 'no-store' });
338
+ return res.end();
339
+ }
340
+ if (rest[0] === 'bake') {
341
+ if (req.method !== 'POST')
342
+ throw new HttpError(405, 'POST to bake again');
343
+ const queued = queue.add(p.dir);
344
+ if (queued)
345
+ broadcast({ project: keyOf(p), baking: true });
346
+ return json(200, { ok: true, queued });
347
+ }
348
+ if (rest[0] === 'reveal') {
349
+ if (req.method !== 'POST')
350
+ throw new HttpError(405, 'POST to show the folder');
351
+ reveal(p.dir);
352
+ return json(200, { ok: true });
353
+ }
354
+ }
355
+ send(404, 'not found');
356
+ }
357
+ catch (e) {
358
+ if (res.headersSent || res.destroyed)
359
+ return;
360
+ const code = e instanceof HttpError ? e.status : 500;
361
+ json(code, { ok: false, error: String(e?.message ?? e) });
362
+ }
363
+ });
364
+ const port = o.port ?? cfg.gallery.port;
365
+ await new Promise((resolve, reject) => {
366
+ server.once('error', reject);
367
+ server.listen(port, '127.0.0.1', () => resolve());
368
+ });
369
+ const actual = server.address().port;
370
+ base = `http://127.0.0.1:${actual}`;
371
+ const keepAlive = setInterval(() => { for (const c of clients)
372
+ c.write(': ping\n\n'); }, 20000);
373
+ keepAlive.unref();
374
+ return {
375
+ url: base + '/', port: actual, rescan, queue,
376
+ close: () => {
377
+ clearInterval(periodic);
378
+ clearInterval(keepAlive);
379
+ clearTimeout(changeTimer);
380
+ for (const w of watchers)
381
+ w.close();
382
+ queue.close();
383
+ for (const e of editors.values())
384
+ e.child.kill();
385
+ for (const c of clients)
386
+ c.end();
387
+ server.close();
388
+ server.closeAllConnections?.();
389
+ },
390
+ };
391
+ }
@@ -26,6 +26,7 @@ import { Geometry, isGeometry } from '../core/geometry.js';
26
26
  import { DEFAULT_TRANSFER, expandPacked } from '../core/packed.js';
27
27
  import { splinesToPolylines } from '../core/splines.js';
28
28
  import { hashString } from '../core/random.js';
29
+ import { targetError } from '../io/targets.js';
29
30
  import { allAliases, getNodeDef } from './registry.js';
30
31
  import { DeferredExpr, REF_FUNCS, didYouMean, hasRefs, resolveParamName, resolveParams, scanNodeRefs, scanValue, vecOut, } from './params.js';
31
32
  import { migrateGraphDetailed } from './migrate.js';
@@ -453,6 +454,19 @@ export class Engine {
453
454
  return { errors, warnings };
454
455
  }
455
456
  const names = Object.keys(graph.nodes);
457
+ if (graph.outputs !== undefined) {
458
+ if (!graph.outputs || typeof graph.outputs !== 'object' || Array.isArray(graph.outputs))
459
+ errors.push({ node: path || '(graph)', message: 'outputs must be a map of names to {node, label?}' });
460
+ else
461
+ for (const [id, out] of Object.entries(graph.outputs)) {
462
+ if (!id || !out || typeof out !== 'object' || typeof out.node !== 'string' || !Object.hasOwn(graph.nodes, out.node) || (out.label !== undefined && typeof out.label !== 'string'))
463
+ errors.push({ node: path || '(graph)', message: `named output "${id}" must reference an existing node and have an optional string label` });
464
+ else if (out.export !== undefined && targetError(out.export))
465
+ errors.push({ node: path || '(graph)', message: `named output "${id}": ${targetError(out.export)}` });
466
+ }
467
+ }
468
+ if (graph.export !== undefined && targetError(graph.export))
469
+ errors.push({ node: path || '(graph)', message: targetError(graph.export) });
456
470
  if (!names.length)
457
471
  errors.push({ node: path || '(graph)', message: 'graph has no nodes' });
458
472
  if (graph.output && !graph.nodes[graph.output])
@@ -91,11 +91,28 @@ export interface VarDef {
91
91
  export interface GraphMeta {
92
92
  [key: string]: any;
93
93
  }
94
+ /**
95
+ * Where a published output exports to: a format name ("glb"), written as exports/<output>.<ext>, or an object with
96
+ * the format, an optional path inside exports/ and the export tool's options ({format: "obj", up_axis: "z"}).
97
+ */
98
+ export type ExportTarget = string | {
99
+ format: string;
100
+ path?: string;
101
+ [option: string]: unknown;
102
+ };
94
103
  export interface GraphSpec {
95
104
  /** graph format version (see GRAPH_VERSION); missing = 0, migrated on load */
96
105
  version?: number;
97
106
  nodes: Record<string, NodeSpec>;
98
107
  output?: string;
108
+ /** where the default output exports to (io/targets.ts): a format ("glb"), or {format, path?, ...export options} */
109
+ export?: ExportTarget;
110
+ /** Named deliverables for the viewer. `output` remains the default cook target. */
111
+ outputs?: Record<string, {
112
+ node: string;
113
+ label?: string;
114
+ export?: ExportTarget;
115
+ }>;
99
116
  vars?: Record<string, any>;
100
117
  /** metadata for exposed vars: asset parameters, and the controls the live viewer shows for them */
101
118
  params?: Record<string, VarDef>;
@@ -0,0 +1,21 @@
1
+ export interface Artifact {
2
+ id: string;
3
+ label: string;
4
+ graph?: string;
5
+ node?: string;
6
+ format?: string;
7
+ sourceRevision?: string;
8
+ /** the published output a target export wrote ('' = the graph's default output) */
9
+ output?: string;
10
+ files: string[];
11
+ }
12
+ export declare const artifactId: (p: string) => string;
13
+ export declare class ArtifactStore {
14
+ dir: string;
15
+ constructor(dir: string);
16
+ get manifest(): string;
17
+ records(): Artifact[];
18
+ record(files: string[], info?: Partial<Omit<Artifact, 'id' | 'files'>>): Artifact;
19
+ /** Discover unregistered agent-written files too. Never follow symlinks/junctions while scanning. */
20
+ list(): Artifact[];
21
+ }
@@ -0,0 +1,58 @@
1
+ // Persistent output receipts shared by the CLI, MCP and viewer. Paths are registered by trusted host code;
2
+ // HTTP callers only receive identifiers, never a route that reads an arbitrary absolute path.
3
+ import fs from 'node:fs';
4
+ import path from 'node:path';
5
+ import { createHash } from 'node:crypto';
6
+ export const artifactId = (p) => createHash('sha256').update(path.resolve(p)).digest('hex').slice(0, 24);
7
+ export class ArtifactStore {
8
+ dir;
9
+ constructor(dir) { this.dir = path.resolve(dir); }
10
+ get manifest() { return path.join(this.dir, '.outputs.json'); }
11
+ records() {
12
+ try {
13
+ const j = JSON.parse(fs.readFileSync(this.manifest, 'utf8'));
14
+ return Array.isArray(j) ? j.filter((a) => a && typeof a.id === 'string' && Array.isArray(a.files) && a.files.every((p) => typeof p === 'string')) : [];
15
+ }
16
+ catch {
17
+ return [];
18
+ }
19
+ }
20
+ record(files, info = {}) {
21
+ if (!files.length)
22
+ throw new Error('an output needs at least one file');
23
+ files = files.map((p) => path.resolve(p));
24
+ const a = { id: artifactId(files[0]), label: path.basename(files[0]), ...info, files };
25
+ const all = this.records().filter((x) => x.id !== a.id);
26
+ all.push(a);
27
+ fs.mkdirSync(this.dir, { recursive: true });
28
+ const temp = this.manifest + '.part';
29
+ fs.writeFileSync(temp, JSON.stringify(all, null, 2) + '\n');
30
+ fs.renameSync(temp, this.manifest);
31
+ return a;
32
+ }
33
+ /** Discover unregistered agent-written files too. Never follow symlinks/junctions while scanning. */
34
+ list() {
35
+ const all = this.records().filter((a) => a.files.some((p) => fs.statSync(p, { throwIfNoEntry: false })?.isFile()));
36
+ const known = new Set(all.flatMap((a) => a.files.map((p) => path.resolve(p))));
37
+ const walk = (dir) => {
38
+ // a folder can be missing, or vanish between listing its parent and reading it
39
+ const entries = (() => { try {
40
+ return fs.readdirSync(dir, { withFileTypes: true });
41
+ }
42
+ catch {
43
+ return [];
44
+ } })();
45
+ for (const e of entries.sort((a, b) => a.name.localeCompare(b.name, 'en'))) {
46
+ if (e.name.startsWith('.') || e.isSymbolicLink())
47
+ continue;
48
+ const p = path.join(dir, e.name);
49
+ if (e.isDirectory())
50
+ walk(p);
51
+ else if (e.isFile() && !known.has(p))
52
+ all.push({ id: artifactId(p), label: path.relative(this.dir, p).split(path.sep).join('/'), files: [p] });
53
+ }
54
+ };
55
+ walk(this.dir);
56
+ return all;
57
+ }
58
+ }
@@ -0,0 +1,33 @@
1
+ import type { Geometry } from '../core/geometry.ts';
2
+ import type { ExportFormat } from '../io/export.ts';
3
+ import type { ExportFile } from '../io/files.ts';
4
+ import type { PublishedOutput, ResolvedTarget } from '../io/targets.ts';
5
+ import type { Host } from './types.ts';
6
+ /** The files an export writes, nothing written yet; `a` holds the export tool's snake_case options. */
7
+ export declare function serializeExport(geo: Geometry, format: ExportFormat, p: string, a: Record<string, any>, host: Host): Promise<{
8
+ files: ExportFile[];
9
+ summary: string;
10
+ warnings: string[];
11
+ outDir: string;
12
+ }>;
13
+ /** `p` resolved inside `root`, crossing no symbolic link or junction on the way; throws otherwise. */
14
+ export declare function insideRoot(root: string, p: string): string;
15
+ /** Write files, each through a .part renamed into place; with `root`, each must stay inside it. Returns the count. */
16
+ export declare function writeExportFiles(files: ExportFile[], root?: string): number;
17
+ /** A published output serialized to its target, ready to write. */
18
+ export interface PreparedTarget {
19
+ graph: string;
20
+ output: string | null;
21
+ label: string;
22
+ node: string;
23
+ target: ResolvedTarget;
24
+ files: ExportFile[];
25
+ summary: string;
26
+ warnings: string[];
27
+ }
28
+ /** Serialize one published output to its target inside `exportsDir` (nothing is written yet). */
29
+ export declare function prepareTarget(geo: Geometry, graph: string, p: PublishedOutput & {
30
+ target: ResolvedTarget;
31
+ }, exportsDir: string, host: Host): Promise<PreparedTarget>;
32
+ /** Write prepared targets and record their receipts; two targets writing one file are refused before any write. */
33
+ export declare function writeTargets(prepared: PreparedTarget[], exportsDir: string): number;
@@ -0,0 +1,84 @@
1
+ // Writing exports for the CLI, the MCP server and the viewer: serialize with the export tool's options, then write
2
+ // each file through a .part beside it, renamed into place. Published targets (io/targets.ts) write inside exports/
3
+ // only, and every target is serialized before any file is written, so a failed cook or format changes nothing.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import zlib from 'node:zlib';
7
+ import { exportFilesAsync } from '../io/files.js';
8
+ import { ArtifactStore } from './artifacts.js';
9
+ /** The files an export writes, nothing written yet; `a` holds the export tool's snake_case options. */
10
+ export async function serializeExport(geo, format, p, a, host) {
11
+ const warnings = [];
12
+ const outDir = format === 'unreal_landscape' && !/\.json$/i.test(p) ? p : path.dirname(p);
13
+ const res = await exportFilesAsync(geo, format, p, {
14
+ upAxis: a.up_axis, scale: a.scale, splitByName: a.split_by_name ?? true, custom: a.custom_attribs,
15
+ materials: a.materials, compress: a.compress, quantize: a.quantize, tangents: a.tangents, attributes: a.attributes, pcg: a.pcg || a.pcg_struct, pcgStruct: a.pcg_struct,
16
+ precision: a.precision, instancing: a.instancing, instances: a.instances, meshes: a.meshes,
17
+ layer: a.layer, layers: a.layers, heightMin: a.height_min, heightMax: a.height_max, heightfield: a.heightfield, tile_size: a.tile_size,
18
+ deflate: (d) => zlib.deflateSync(d, { level: 6 }),
19
+ readFile: (t) => host.readFile(t),
20
+ texturePath: (t) => {
21
+ const abs = host.resolvePath(t);
22
+ return /^[a-z][a-z0-9+.-]*:\/\//i.test(abs) ? abs : path.relative(outDir, abs).split(path.sep).join('/');
23
+ },
24
+ warn: (m) => warnings.push(m),
25
+ });
26
+ return { files: res.files, summary: res.summary, warnings: [...new Set(warnings)], outDir };
27
+ }
28
+ /** `p` resolved inside `root`, crossing no symbolic link or junction on the way; throws otherwise. */
29
+ export function insideRoot(root, p) {
30
+ const abs = path.resolve(p), rel = path.relative(path.resolve(root), abs);
31
+ if (!rel || rel.startsWith('..') || path.isAbsolute(rel))
32
+ throw new Error(`${p} is outside ${root}`);
33
+ let current = path.resolve(root);
34
+ for (const part of rel.split(path.sep)) {
35
+ current = path.join(current, part);
36
+ if (fs.lstatSync(current, { throwIfNoEntry: false })?.isSymbolicLink())
37
+ throw new Error(`export paths cannot pass through the link ${current}`);
38
+ }
39
+ return abs;
40
+ }
41
+ /** Write files, each through a .part renamed into place; with `root`, each must stay inside it. Returns the count. */
42
+ export function writeExportFiles(files, root) {
43
+ let written = 0;
44
+ try {
45
+ for (const f of files) {
46
+ const abs = root ? insideRoot(root, f.path) : path.resolve(f.path);
47
+ fs.mkdirSync(path.dirname(abs), { recursive: true });
48
+ fs.writeFileSync(abs + '.part', f.bytes);
49
+ fs.renameSync(abs + '.part', abs);
50
+ written++;
51
+ }
52
+ }
53
+ catch (e) {
54
+ throw new Error(`export stopped after writing ${written} of ${files.length} files: ${e.message}`);
55
+ }
56
+ return written;
57
+ }
58
+ /** Serialize one published output to its target inside `exportsDir` (nothing is written yet). */
59
+ export async function prepareTarget(geo, graph, p, exportsDir, host) {
60
+ const dest = insideRoot(exportsDir, path.join(exportsDir, ...p.target.path.split('/')));
61
+ const r = await serializeExport(geo, p.target.format, dest, p.target.options, host);
62
+ for (const f of r.files)
63
+ insideRoot(exportsDir, f.path);
64
+ return { graph, output: p.output, label: p.label, node: p.node, target: p.target, files: r.files, summary: r.summary, warnings: r.warnings };
65
+ }
66
+ /** Write prepared targets and record their receipts; two targets writing one file are refused before any write. */
67
+ export function writeTargets(prepared, exportsDir) {
68
+ const owner = new Map();
69
+ for (const p of prepared)
70
+ for (const f of p.files) {
71
+ const key = path.resolve(f.path).toLowerCase(), other = owner.get(key);
72
+ // status: the viewer answers 409 (the request conflicts with itself); the CLI and MCP print the message
73
+ if (other && other !== p)
74
+ throw Object.assign(new Error(`"${other.label}" (${other.graph}) and "${p.label}" (${p.graph}) both write ${path.relative(exportsDir, f.path)}: give one a different export path`), { status: 409 });
75
+ owner.set(key, p);
76
+ }
77
+ const store = new ArtifactStore(exportsDir);
78
+ let written = 0;
79
+ for (const p of prepared) {
80
+ written += writeExportFiles(p.files, exportsDir);
81
+ store.record(p.files.map((f) => f.path), { label: p.target.path, graph: p.graph, node: p.node, format: p.target.format, output: p.output ?? '' });
82
+ }
83
+ return written;
84
+ }