comfy-ts 2.22.0 → 2.24.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 (99) hide show
  1. package/dist/{ServeApp-DuxYdaZZ.js → ServeApp-fsHtW5zG.js} +51 -17
  2. package/dist/ServeApp-fsHtW5zG.js.map +1 -0
  3. package/dist/cli.js +5 -5
  4. package/dist/{exampleAssets-1NHndnNB.js → exampleAssets-DZynSkZm.js} +405 -39
  5. package/dist/exampleAssets-DZynSkZm.js.map +1 -0
  6. package/dist/{findDefinedWorkflow-CRsBTTJK.js → findDefinedWorkflow-qyqFea7q.js} +2 -2
  7. package/dist/{findDefinedWorkflow-CRsBTTJK.js.map → findDefinedWorkflow-qyqFea7q.js.map} +1 -1
  8. package/dist/index.cjs +428 -46
  9. package/dist/index.cjs.map +1 -1
  10. package/dist/index.d.cts +147 -1
  11. package/dist/index.d.ts +147 -1
  12. package/dist/index.js +428 -47
  13. package/dist/index.js.map +1 -1
  14. package/dist/{run-run-Y5ZI48vV.js → run-run-Cn2JzKlE.js} +5 -5
  15. package/dist/{run-run-Y5ZI48vV.js.map → run-run-Cn2JzKlE.js.map} +1 -1
  16. package/dist/{run-serve-CICU_wTL.js → run-serve-BhGegaCI.js} +4 -4
  17. package/dist/{run-serve-CICU_wTL.js.map → run-serve-BhGegaCI.js.map} +1 -1
  18. package/dist/{run-tui-CViJXsHL.js → run-tui-CrM4ijkH.js} +4 -4
  19. package/dist/{run-tui-CViJXsHL.js.map → run-tui-CrM4ijkH.js.map} +1 -1
  20. package/dist/{schemaDrift-CzjaIwZX.js → schemaDrift-BGYJZGMD.js} +18 -3
  21. package/dist/{schemaDrift-CzjaIwZX.js.map → schemaDrift-BGYJZGMD.js.map} +1 -1
  22. package/dist/serve-web.js +46 -43
  23. package/dist/web.d.ts +147 -1
  24. package/dist/web.js +428 -47
  25. package/dist/web.js.map +1 -1
  26. package/examples/README.md +1 -0
  27. package/examples/comfy-cloud/sdk.d.ts +102 -1
  28. package/examples/depth-explorer/models.ts +6 -56
  29. package/examples/depth-explorer/serve.ts +12 -133
  30. package/examples/depth-explorer/web/App.tsx +20 -91
  31. package/examples/depth-explorer/web/index.html +1 -0
  32. package/examples/depth-explorer/web/state.ts +26 -109
  33. package/examples/depth-explorer/web/styles.css +1 -286
  34. package/examples/explorer-kit/catalog.ts +80 -0
  35. package/examples/explorer-kit/server.ts +167 -0
  36. package/examples/explorer-kit/web/base.css +289 -0
  37. package/examples/explorer-kit/web/runs.ts +160 -0
  38. package/examples/explorer-kit/web/ui.tsx +125 -0
  39. package/examples/rvion/17-relight.cflow.ts +2 -1
  40. package/examples/rvion/18-world.cflow.ts +101 -0
  41. package/examples/rvion/19-flythrough.cflow.ts +312 -0
  42. package/examples/rvion/20-grow-splat.cflow.ts +88 -0
  43. package/examples/rvion/21-photo-to-model.cflow.ts +191 -0
  44. package/examples/rvion/flythroughChain.ts +171 -0
  45. package/examples/rvion/flythroughColmap.ts +157 -0
  46. package/examples/rvion/flythroughFuse.ts +199 -0
  47. package/examples/rvion/flythroughGuide.ts +300 -0
  48. package/examples/rvion/flythroughPalette.ts +310 -0
  49. package/examples/rvion/flythroughPath.ts +177 -0
  50. package/examples/rvion/flythroughSplat.ts +73 -0
  51. package/examples/rvion/grow-splat/align.ts +114 -0
  52. package/examples/rvion/grow-splat/grow.ts +198 -0
  53. package/examples/rvion/grow-splat/ply.ts +166 -0
  54. package/examples/rvion/grow-splat/raster.ts +207 -0
  55. package/examples/rvion/grow-splat/sharp.ts +45 -0
  56. package/examples/rvion/splatDataset.ts +80 -0
  57. package/examples/rvion/splatEval.ts +380 -0
  58. package/examples/upscale-explorer/models.ts +341 -0
  59. package/examples/upscale-explorer/serve.ts +19 -0
  60. package/examples/upscale-explorer/web/App.tsx +250 -0
  61. package/examples/upscale-explorer/web/compare.tsx +285 -0
  62. package/examples/upscale-explorer/web/index.html +15 -0
  63. package/examples/upscale-explorer/web/main.tsx +12 -0
  64. package/examples/upscale-explorer/web/state.ts +279 -0
  65. package/examples/upscale-explorer/web/styles.css +241 -0
  66. package/examples/upscale-explorer/web/tsconfig.json +16 -0
  67. package/examples/upscale-explorer/web/viewport.tsx +130 -0
  68. package/examples/world-explorer/serve.ts +171 -0
  69. package/examples/world-explorer/web/index.html +14 -0
  70. package/examples/world-explorer/web/main.tsx +200 -0
  71. package/examples/world-explorer/web/state.ts +212 -0
  72. package/examples/world-explorer/web/styles.css +131 -0
  73. package/examples/world-explorer/web/thumb.ts +21 -0
  74. package/examples/world-explorer/web/tsconfig.json +11 -0
  75. package/examples/world-explorer/world-state.ts +40 -0
  76. package/package.json +7 -8
  77. package/src/cli/serve/ServeApp.ts +27 -2
  78. package/src/cli/serve/resultHistory.ts +22 -4
  79. package/src/cli/serve/thumbs.ts +19 -8
  80. package/src/cli/serve/web/api.ts +4 -0
  81. package/src/cli/serve/web/components/Gallery.tsx +24 -1
  82. package/src/cli/serve/web/styles.ts +3 -0
  83. package/src/coreExports.ts +6 -0
  84. package/src/graph/ComfyNode.ts +12 -2
  85. package/src/host/ComfyHost.ts +159 -2
  86. package/src/host/ResilientWebsocket.ts +10 -0
  87. package/src/manager/script-update-manager.bun.ts +0 -7
  88. package/src/runner/ComfyExecution.ts +185 -23
  89. package/src/runner/ComfyWorkflow.ts +22 -0
  90. package/src/runner/ComfyWsApi.ts +3 -1
  91. package/src/runner/comfyOrgApiKey.ts +44 -0
  92. package/src/runner/historyReplay.ts +53 -0
  93. package/src/runner/outputs3d.ts +18 -0
  94. package/src/sdk-generator/ComfyUIObjectInfoTypes.ts +2 -0
  95. package/src/sdk-generator/comfyui-sdk-codegen.ts +7 -2
  96. package/src/state.ts +2 -0
  97. package/src/vars/DefinedWorkflow.ts +1 -0
  98. package/dist/ServeApp-DuxYdaZZ.js.map +0 -1
  99. package/dist/exampleAssets-1NHndnNB.js.map +0 -1
@@ -0,0 +1,241 @@
1
+ /* the upscale explorer over the shared explorer look (examples/explorer-kit/web/base.css) */
2
+ :root {
3
+ --before: #ff6b6b;
4
+ --after: #4cd07d;
5
+ }
6
+ .toolbar {
7
+ display: flex;
8
+ align-items: center;
9
+ gap: 12px;
10
+ margin-bottom: 14px;
11
+ flex-wrap: wrap;
12
+ }
13
+ .toolbar > .seg {
14
+ width: auto;
15
+ }
16
+ .frame > img {
17
+ width: 100%;
18
+ height: 100%;
19
+ object-fit: contain;
20
+ display: block;
21
+ }
22
+ .facts {
23
+ display: flex;
24
+ flex-wrap: wrap;
25
+ gap: 4px;
26
+ padding: 8px 10px 0;
27
+ }
28
+ .chip {
29
+ font-size: 11px;
30
+ padding: 1px 6px;
31
+ border-radius: 4px;
32
+ background: var(--bg);
33
+ border: 1px solid var(--line);
34
+ color: var(--dim);
35
+ }
36
+ .chip.out {
37
+ color: var(--text);
38
+ }
39
+
40
+ /* a frame on the shared view */
41
+ .viewport {
42
+ position: relative;
43
+ overflow: hidden;
44
+ background: #0c0d0f;
45
+ cursor: grab;
46
+ touch-action: none;
47
+ user-select: none;
48
+ }
49
+ .viewport:active {
50
+ cursor: grabbing;
51
+ }
52
+ .layer {
53
+ position: absolute;
54
+ max-width: none;
55
+ display: block;
56
+ pointer-events: none;
57
+ }
58
+ .layer.px {
59
+ image-rendering: pixelated;
60
+ }
61
+ .fill {
62
+ position: absolute;
63
+ inset: 0;
64
+ }
65
+
66
+ /* the loupe */
67
+ .loupe {
68
+ display: grid;
69
+ gap: 12px;
70
+ }
71
+ .tile {
72
+ background: var(--card);
73
+ border: 1px solid var(--line);
74
+ border-radius: 8px;
75
+ overflow: hidden;
76
+ }
77
+ .tileHead {
78
+ display: flex;
79
+ justify-content: space-between;
80
+ gap: 8px;
81
+ padding: 6px 10px;
82
+ cursor: pointer;
83
+ }
84
+ .tileHead:hover .name {
85
+ color: var(--accent);
86
+ }
87
+ .tileView {
88
+ aspect-ratio: 1;
89
+ }
90
+ .nav {
91
+ position: relative;
92
+ cursor: crosshair;
93
+ touch-action: none;
94
+ border-radius: 6px;
95
+ overflow: hidden;
96
+ }
97
+ .nav img {
98
+ display: block;
99
+ width: 100%;
100
+ height: 100%;
101
+ }
102
+ .navBox {
103
+ position: absolute;
104
+ border: 2px solid var(--accent);
105
+ box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.45);
106
+ pointer-events: none;
107
+ min-width: 4px;
108
+ min-height: 4px;
109
+ }
110
+
111
+ /* the compared pair, over the page */
112
+ .pair {
113
+ position: fixed;
114
+ inset: 0;
115
+ z-index: 10;
116
+ background: var(--bg);
117
+ display: flex;
118
+ flex-direction: column;
119
+ }
120
+ .pairBar {
121
+ display: flex;
122
+ align-items: center;
123
+ gap: 8px;
124
+ padding: 8px 12px;
125
+ border-bottom: 1px solid var(--line);
126
+ flex-wrap: wrap;
127
+ }
128
+ .pairBar select {
129
+ max-width: 240px;
130
+ }
131
+ .pairBar .meta {
132
+ margin-left: auto;
133
+ }
134
+ .modes {
135
+ display: flex;
136
+ align-items: center;
137
+ gap: 6px;
138
+ }
139
+ .modes .seg button {
140
+ font-size: 15px;
141
+ padding: 2px 9px;
142
+ }
143
+ kbd {
144
+ font: 11px ui-monospace, monospace;
145
+ border: 1px solid var(--line);
146
+ border-radius: 4px;
147
+ padding: 1px 5px;
148
+ color: var(--dim);
149
+ }
150
+ .zoombar {
151
+ display: inline-flex;
152
+ align-items: center;
153
+ gap: 4px;
154
+ }
155
+ .zoombar button {
156
+ padding: 3px 8px;
157
+ }
158
+ .zoombar button.on {
159
+ border-color: var(--accent);
160
+ }
161
+ .zoompct {
162
+ min-width: 54px;
163
+ text-align: center;
164
+ font-variant-numeric: tabular-nums;
165
+ }
166
+ .stage {
167
+ flex: 1;
168
+ min-height: 0;
169
+ display: flex;
170
+ flex-direction: column;
171
+ padding: 10px;
172
+ gap: 6px;
173
+ }
174
+ .stage.side {
175
+ flex-direction: row;
176
+ }
177
+ .cell {
178
+ position: relative;
179
+ flex: 1;
180
+ min-height: 0;
181
+ min-width: 0;
182
+ display: flex;
183
+ }
184
+ .cell > .viewport {
185
+ flex: 1;
186
+ border-radius: 6px;
187
+ }
188
+ .viewport.side-before {
189
+ outline: 2px solid var(--before);
190
+ outline-offset: -2px;
191
+ }
192
+ .viewport.side-after {
193
+ outline: 2px solid var(--after);
194
+ outline-offset: -2px;
195
+ }
196
+ .sidetag {
197
+ position: absolute;
198
+ top: 8px;
199
+ right: 8px;
200
+ padding: 2px 8px;
201
+ border-radius: 4px;
202
+ font-size: 12px;
203
+ color: #0b1220;
204
+ pointer-events: none;
205
+ }
206
+ .sidetag.left {
207
+ right: auto;
208
+ left: 8px;
209
+ }
210
+ .sidetag.before {
211
+ background: var(--before);
212
+ }
213
+ .sidetag.after {
214
+ background: var(--after);
215
+ }
216
+ .curtain {
217
+ position: absolute;
218
+ top: 0;
219
+ bottom: 0;
220
+ width: 2px;
221
+ transform: translateX(-1px);
222
+ background: #fff;
223
+ box-shadow: 0 0 6px rgba(0, 0, 0, 0.7);
224
+ cursor: ew-resize;
225
+ pointer-events: none;
226
+ }
227
+ .caption {
228
+ color: var(--dim);
229
+ font-size: 12px;
230
+ text-align: center;
231
+ }
232
+ .keys {
233
+ padding: 0 12px 8px;
234
+ text-align: center;
235
+ }
236
+ aside label.first {
237
+ margin-top: 0;
238
+ }
239
+ .nav {
240
+ margin-bottom: 16px;
241
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ // the upscale explorer page: dom-typed like examples/web, so it keeps its own config; the
3
+ // explorer kit's web files come in through its imports
4
+ "extends": "../../../tsconfig.json",
5
+ "compilerOptions": {
6
+ "lib": ["ESNext", "DOM", "DOM.Iterable"],
7
+ "paths": {
8
+ "src/*": ["../../../src/*"],
9
+ "comfy-ts": ["../../../src/index.ts"]
10
+ },
11
+ "tsBuildInfoFile": "../../../node_modules/.cache/tsbuildinfo-upscale-explorer-web.json"
12
+ },
13
+ // MUST override the root's exclude, which lists this directory
14
+ "exclude": ["../../web"],
15
+ "include": ["."]
16
+ }
@@ -0,0 +1,130 @@
1
+ // a frame on the shared view: every picture inside it is drawn at the results' pixel size, placed by
2
+ // the view's centre and zoom, so every frame of the page shows the same crop. The wheel or a pinch
3
+ // zooms around the pointer, a drag pans, a double click goes from the whole image to 100 % where it
4
+ // landed and back.
5
+ import { observer } from 'mobx-react-lite'
6
+ import { useEffect, useRef, useState, type ReactNode } from 'react'
7
+ import type { AppSt } from './state.ts'
8
+
9
+ /** where the image sits in its frame, css px, and its zoom (device pixels per image pixel) */
10
+ export type Box = { left: number; top: number; width: number; height: number; z: number }
11
+
12
+ /** a picture at the results' pixel size, placed on the box; pixels stay square above 100 % */
13
+ export function Layer(p: { url: string; box: Box; style?: React.CSSProperties; alt?: string }) {
14
+ return (
15
+ <img
16
+ className={`layer ${p.box.z > 1.01 ? 'px' : ''}`}
17
+ src={p.url}
18
+ alt={p.alt ?? ''}
19
+ draggable={false}
20
+ style={{ left: p.box.left, top: p.box.top, width: p.box.width, height: p.box.height, ...p.style }}
21
+ />
22
+ )
23
+ }
24
+
25
+ export const Viewport = observer(function Viewport(p: {
26
+ st: AppSt
27
+ className?: string
28
+ /** a press the caller takes instead of a pan (the curtain's line): true = taken */
29
+ onPress?: (e: React.PointerEvent<HTMLDivElement>, frame: DOMRect) => boolean
30
+ onHover?: (inside: boolean) => void
31
+ children: (box: Box) => ReactNode
32
+ }) {
33
+ const { st } = p
34
+ const ref = useRef<HTMLDivElement>(null)
35
+ const [size, setSize] = useState({ w: 0, h: 0 })
36
+ const drag = useRef<{ x: number; y: number } | null>(null)
37
+
38
+ useEffect(() => {
39
+ const el = ref.current
40
+ if (el == null) return
41
+ const ro = new ResizeObserver(() => {
42
+ setSize({ w: el.clientWidth, h: el.clientHeight })
43
+ st.noteFrame(el.clientWidth, el.clientHeight)
44
+ })
45
+ ro.observe(el)
46
+ // non passive, so the page never scrolls under a zoom; a pinch arrives as a wheel with ctrlKey
47
+ const onWheel = (e: WheelEvent): void => {
48
+ e.preventDefault()
49
+ const r = el.getBoundingClientRect()
50
+ const k = Math.exp(-e.deltaY * (e.ctrlKey ? 0.01 : 0.0015))
51
+ st.zoomAt(k, e.clientX - r.left, e.clientY - r.top, r.width, r.height)
52
+ }
53
+ el.addEventListener('wheel', onWheel, { passive: false })
54
+ return () => {
55
+ ro.disconnect()
56
+ el.removeEventListener('wheel', onWheel)
57
+ }
58
+ }, [st])
59
+
60
+ const z = st.zoomIn(size.w, size.h)
61
+ const s = z / devicePixelRatio
62
+ const fit = st.view.z === 'fit'
63
+ const cx = fit ? 0.5 : st.view.cx
64
+ const cy = fit ? 0.5 : st.view.cy
65
+ const box: Box = {
66
+ width: st.outW * s,
67
+ height: st.outH * s,
68
+ left: size.w / 2 - cx * st.outW * s,
69
+ top: size.h / 2 - cy * st.outH * s,
70
+ z,
71
+ }
72
+ return (
73
+ <div
74
+ ref={ref}
75
+ className={`viewport ${p.className ?? ''}`}
76
+ onPointerDown={(e) => {
77
+ if (!e.isPrimary || e.button !== 0) return
78
+ const el = ref.current
79
+ if (el == null) return
80
+ if (p.onPress?.(e, el.getBoundingClientRect()) === true) return
81
+ drag.current = { x: e.clientX, y: e.clientY }
82
+ el.setPointerCapture(e.pointerId)
83
+ }}
84
+ onPointerMove={(e) => {
85
+ const d = drag.current
86
+ if (d == null) return
87
+ st.pan(e.clientX - d.x, e.clientY - d.y, size.w, size.h)
88
+ drag.current = { x: e.clientX, y: e.clientY }
89
+ }}
90
+ onPointerUp={() => (drag.current = null)}
91
+ onPointerCancel={() => (drag.current = null)}
92
+ onDoubleClick={(e) => {
93
+ const r = e.currentTarget.getBoundingClientRect()
94
+ if (z > 0.99 && !fit) return st.fit()
95
+ const u = (e.clientX - r.left - box.left) / box.width
96
+ const v = (e.clientY - r.top - box.top) / box.height
97
+ st.setView({ cx: u, cy: v, z: 1 })
98
+ }}
99
+ onMouseEnter={() => p.onHover?.(true)}
100
+ onMouseLeave={() => p.onHover?.(false)}
101
+ >
102
+ {st.outW > 0 && size.w > 0 ? p.children(box) : null}
103
+ </div>
104
+ )
105
+ })
106
+
107
+ /** the zoom as a percent of real pixels, and the buttons that set it */
108
+ export const ZoomBar = observer(function ZoomBar(p: { st: AppSt }) {
109
+ const { st } = p
110
+ const z = st.view.z
111
+ return (
112
+ <span className="zoombar">
113
+ <button title="zoom out (−)" onClick={() => st.step(1 / 1.5)}>
114
+ −
115
+ </button>
116
+ <span className="zoompct" title="device pixels per result pixel">
117
+ {z === 'fit' ? 'fit' : `${Math.round(z * 100)} %`}
118
+ </span>
119
+ <button title="zoom in (+)" onClick={() => st.step(1.5)}>
120
+ +
121
+ </button>
122
+ <button className={z === 'fit' ? 'on' : ''} title="the whole image (0)" onClick={() => st.fit()}>
123
+ fit
124
+ </button>
125
+ <button className={z === 1 ? 'on' : ''} title="100 %: one result pixel on one screen pixel (1)" onClick={() => st.actual()}>
126
+ 1:1
127
+ </button>
128
+ </span>
129
+ )
130
+ })
@@ -0,0 +1,171 @@
1
+ // world explorer: one world of .comfy-ts/worlds/<name>/ drawn in the browser (a panorama to look around, a mesh to
2
+ // walk, a splat to orbit, the source picture), the view page of the `world` thread kind (world-kind.shipkit.ts).
3
+ // bun examples/world-explorer/serve.ts → http://127.0.0.1:8293/?key=<world>
4
+ // the hub serves this page again through its proxy: every path the page asks is RELATIVE, so the bundle is built with
5
+ // publicPath './' and the world files answer under `worlds/<name>/<file>`
6
+ import { closeSync, existsSync, openSync, readdirSync, readSync, renameSync, statSync } from 'node:fs'
7
+ import { join, resolve } from 'pathe'
8
+
9
+ const PORT = Number(process.env.PORT ?? 8293)
10
+ const ROOT = resolve(import.meta.dir, '../..')
11
+ const WORLDS = join(ROOT, '.comfy-ts/worlds')
12
+ const WEB = join(import.meta.dir, 'web')
13
+
14
+ /** the files a world may hold, in the order the page shows their tabs */
15
+ const FILES = ['panorama.png', 'world.glb', 'splat.ply', 'source.png', 'thumb.webp'] as const
16
+ /** a thumbnail is a few tens of KB: anything far past it is not one */
17
+ const THUMB_MAX = 2_000_000
18
+
19
+ type WorldFile = { name: string; v: string }
20
+ type World = { name: string; files: WorldFile[]; splatFov: number | null }
21
+
22
+ /** the vertical fov of the camera a SHARP ply was made for, from its `intrinsic` (fy at index 4) and `image_size`
23
+ * elements after the vertices; null when the header names none of them */
24
+ function splatFov(path: string): number | null {
25
+ const fd = openSync(path, 'r')
26
+ try {
27
+ const head = Buffer.alloc(4096)
28
+ readSync(fd, head, 0, head.length, 0)
29
+ const end = head.indexOf('end_header\n')
30
+ if (end < 0) return null
31
+ const lines = head.subarray(0, end).toString('latin1').split('\n')
32
+ const sizes: Record<string, number> = { float: 4, uint: 4, int: 4, uchar: 1, double: 8 }
33
+ let offset = end + 'end_header\n'.length
34
+ let el: { name: string; count: number; stride: number } | null = null
35
+ const els: { name: string; count: number; stride: number; at: number }[] = []
36
+ for (const l of lines) {
37
+ const w = l.trim().split(/\s+/)
38
+ if (w[0] === 'element') {
39
+ el = { name: String(w[1]), count: Number(w[2]), stride: 0 }
40
+ els.push({ ...el, at: 0 })
41
+ } else if (w[0] === 'property' && el != null) {
42
+ const last = els[els.length - 1]
43
+ if (last != null) last.stride += sizes[String(w[1])] ?? 4
44
+ }
45
+ }
46
+ for (const e of els) {
47
+ e.at = offset
48
+ offset += e.count * e.stride
49
+ }
50
+ const intr = els.find((e) => e.name === 'intrinsic')
51
+ const size = els.find((e) => e.name === 'image_size')
52
+ if (intr == null || size == null) return null
53
+ const buf = Buffer.alloc(8)
54
+ readSync(fd, buf, 0, 4, intr.at + 4 * 4)
55
+ const fy = buf.readFloatLE(0)
56
+ readSync(fd, buf, 0, 8, size.at)
57
+ const h = buf.readUInt32LE(4)
58
+ if (!(fy > 0 && h > 0)) return null
59
+ return (2 * Math.atan(h / 2 / fy) * 180) / Math.PI
60
+ } finally {
61
+ closeSync(fd)
62
+ }
63
+ }
64
+
65
+ const fovCache = new Map<string, number | null>()
66
+
67
+ function worldOf(name: string): World | null {
68
+ if (!/^[a-z0-9][a-z0-9-]*$/.test(name)) return null
69
+ const dir = join(WORLDS, name)
70
+ if (!existsSync(dir)) return null
71
+ const files: WorldFile[] = []
72
+ for (const f of FILES) {
73
+ const p = join(dir, f)
74
+ if (!existsSync(p)) continue
75
+ const s = statSync(p)
76
+ files.push({ name: f, v: `${s.size.toString(36)}-${Math.round(s.mtimeMs).toString(36)}` })
77
+ }
78
+ const ply = files.find((f) => f.name === 'splat.ply')
79
+ let fov: number | null = null
80
+ if (ply != null) {
81
+ const k = `${name}/${ply.v}`
82
+ if (!fovCache.has(k)) fovCache.set(k, splatFov(join(dir, ply.name)))
83
+ fov = fovCache.get(k) ?? null
84
+ }
85
+ return { name, files, splatFov: fov }
86
+ }
87
+
88
+ function worlds(): World[] {
89
+ if (!existsSync(WORLDS)) return []
90
+ return readdirSync(WORLDS)
91
+ .sort()
92
+ .map(worldOf)
93
+ .filter((w): w is World => w != null && w.files.length > 0)
94
+ }
95
+
96
+ /** the page's bundle, in memory, built again when a file of web/ moved since */
97
+ let bundle: { stamp: string; files: Map<string, Blob> } | null = null
98
+
99
+ function webStamp(): string {
100
+ return readdirSync(WEB)
101
+ .map((f) => `${f}:${statSync(join(WEB, f)).mtimeMs}`)
102
+ .join('|')
103
+ }
104
+
105
+ async function built(): Promise<Map<string, Blob>> {
106
+ const stamp = webStamp()
107
+ if (bundle?.stamp === stamp) return bundle.files
108
+ const started = performance.now()
109
+ const r = await Bun.build({
110
+ entrypoints: [join(WEB, 'index.html')],
111
+ publicPath: './',
112
+ target: 'browser',
113
+ minify: true,
114
+ throw: false,
115
+ })
116
+ if (!r.success) throw new Error(`the page does not build:\n${r.logs.map(String).join('\n')}`)
117
+ const files = new Map<string, Blob>()
118
+ for (const o of r.outputs) files.set(o.path.replace(/^\.\//, ''), o)
119
+ bundle = { stamp, files }
120
+ console.log(`🟢 page built in ${Math.round(performance.now() - started)} ms (${[...files.keys()].join(', ')})`)
121
+ return files
122
+ }
123
+
124
+ const json = (data: unknown, status = 200): Response =>
125
+ Response.json(data, { status, headers: { 'cache-control': 'no-store' } })
126
+
127
+ const server = Bun.serve({
128
+ port: PORT,
129
+ hostname: '127.0.0.1',
130
+ idleTimeout: 120,
131
+ async fetch(req) {
132
+ const url = new URL(req.url)
133
+ const path = decodeURIComponent(url.pathname).replace(/^\/+/, '')
134
+ if (path === 'api/worlds') return json(worlds())
135
+ // the page renders a world's thumbnail from its first view at the default camera and sends it here
136
+ const t = /^api\/thumb\/([^/]+)$/.exec(path)
137
+ if (t != null && req.method === 'POST') {
138
+ const w = worldOf(String(t[1]))
139
+ if (w == null) return json({ error: `no world ${t[1]}` }, 404)
140
+ const bytes = new Uint8Array(await req.arrayBuffer())
141
+ const webp = bytes.length > 12 && new TextDecoder().decode(bytes.subarray(8, 12)) === 'WEBP'
142
+ if (!webp || bytes.length > THUMB_MAX) return json({ error: 'a thumbnail is a webp under 2 MB' }, 400)
143
+ const dest = join(WORLDS, w.name, 'thumb.webp')
144
+ await Bun.write(`${dest}.tmp`, bytes)
145
+ renameSync(`${dest}.tmp`, dest)
146
+ console.log(`🟢 thumbnail of ${w.name}: ${bytes.length} bytes`)
147
+ return json({ ok: true, bytes: bytes.length })
148
+ }
149
+ const m = /^worlds\/([^/]+)\/([^/]+)$/.exec(path)
150
+ if (m != null) {
151
+ const w = worldOf(String(m[1]))
152
+ const f = w?.files.find((x) => x.name === m[2])
153
+ if (w == null || f == null) return json({ error: `no ${m[2]} in world ${m[1]}` }, 404)
154
+ // a world file weighs 60 to 80 MB: under its stamp it never changes, so the browser keeps it
155
+ const cache = url.searchParams.get('v') === f.v ? 'public, max-age=31536000, immutable' : 'no-cache'
156
+ return new Response(Bun.file(join(WORLDS, w.name, f.name)), { headers: { 'cache-control': cache } })
157
+ }
158
+ try {
159
+ const files = await built()
160
+ const file = files.get(path === '' ? 'index.html' : path)
161
+ if (file == null) return json({ error: `no ${path}` }, 404)
162
+ return new Response(file, { headers: { 'cache-control': 'no-cache' } })
163
+ } catch (e) {
164
+ const message = e instanceof Error ? e.message : String(e)
165
+ console.error(`🔴 ${message}`)
166
+ return new Response(message, { status: 500, headers: { 'content-type': 'text/plain; charset=utf-8' } })
167
+ }
168
+ },
169
+ })
170
+
171
+ console.log(`world explorer → http://127.0.0.1:${server.port}/ (${worlds().length} worlds in ${WORLDS})`)
@@ -0,0 +1,14 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
6
+ <title>world explorer</title>
7
+ <meta name="shot-ready" content="wait" />
8
+ <link rel="stylesheet" href="./styles.css" />
9
+ </head>
10
+ <body>
11
+ <div id="root"></div>
12
+ <script type="module" src="./main.tsx"></script>
13
+ </body>
14
+ </html>