moi-computer 0.0.2 → 0.1.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 (246) hide show
  1. package/bin/moi.mjs +3 -1
  2. package/bunfig.toml +4 -0
  3. package/client/api/workspaces.ts +277 -6
  4. package/client/assets/mcp/agentation.png +0 -0
  5. package/client/assets/mcp/airtable.png +0 -0
  6. package/client/assets/mcp/apollo.png +0 -0
  7. package/client/assets/mcp/asana.png +0 -0
  8. package/client/assets/mcp/box.png +0 -0
  9. package/client/assets/mcp/chrome.svg +33 -0
  10. package/client/assets/mcp/clickup.png +0 -0
  11. package/client/assets/mcp/cloudflare.png +0 -0
  12. package/client/assets/mcp/context7.png +0 -0
  13. package/client/assets/mcp/datadog.png +0 -0
  14. package/client/assets/mcp/dropbox.png +0 -0
  15. package/client/assets/mcp/elevenlabs.png +0 -0
  16. package/client/assets/mcp/exa.png +0 -0
  17. package/client/assets/mcp/firecrawl.png +0 -0
  18. package/client/assets/mcp/gmail.png +0 -0
  19. package/client/assets/mcp/googlecalendar.png +0 -0
  20. package/client/assets/mcp/googledrive.png +0 -0
  21. package/client/assets/mcp/grafana.png +0 -0
  22. package/client/assets/mcp/huggingface.png +0 -0
  23. package/client/assets/mcp/intercom.png +0 -0
  24. package/client/assets/mcp/monday.png +0 -0
  25. package/client/assets/mcp/mongodb.png +0 -0
  26. package/client/assets/mcp/paper.png +0 -0
  27. package/client/assets/mcp/paypal.png +0 -0
  28. package/client/assets/mcp/perplexity.png +0 -0
  29. package/client/assets/mcp/postgresql.png +0 -0
  30. package/client/assets/mcp/posthog.png +0 -0
  31. package/client/assets/mcp/puppeteer.png +0 -0
  32. package/client/assets/mcp/railway.png +0 -0
  33. package/client/assets/mcp/redis.png +0 -0
  34. package/client/assets/mcp/salesforce.png +0 -0
  35. package/client/assets/mcp/shopify.png +0 -0
  36. package/client/assets/mcp/snowflake.png +0 -0
  37. package/client/assets/mcp/telegram.png +0 -0
  38. package/client/assets/mcp/twilio.png +0 -0
  39. package/client/assets/mcp/zapier.png +0 -0
  40. package/client/components/App.tsx +7 -1
  41. package/client/components/BottomPanel.tsx +2 -2
  42. package/client/components/ChatInput.tsx +195 -14
  43. package/client/components/ChatPanel.tsx +118 -49
  44. package/client/components/ChatPopup.tsx +2 -2
  45. package/client/components/CustomizePanel.tsx +8 -8
  46. package/client/components/HiddenPanel.tsx +1 -1
  47. package/client/components/HomePage.tsx +1 -1
  48. package/client/components/IconMcp.tsx +21 -0
  49. package/client/components/MarkdownContent.tsx +2 -2
  50. package/client/components/McpMenu.tsx +125 -0
  51. package/client/components/ModelPicker.tsx +147 -0
  52. package/client/components/Scratchpad.tsx +775 -0
  53. package/client/components/ShimmerText.tsx +20 -0
  54. package/client/components/ThreadSelector.tsx +2 -2
  55. package/client/components/TurnView.tsx +114 -534
  56. package/client/components/WidgetErrorBoundary.tsx +2 -2
  57. package/client/components/WidgetFrame.tsx +1 -1
  58. package/client/components/WidgetShell.tsx +2 -2
  59. package/client/components/Widgets.tsx +2 -2
  60. package/client/components/WorkspacePreview.tsx +3 -3
  61. package/client/components/WorkspacesPage.tsx +28 -20
  62. package/client/components/layout/SidebarLayout.tsx +24 -15
  63. package/client/components/playground/PixelPainter.tsx +2 -2
  64. package/client/components/playground/PlaygroundPage.tsx +1 -1
  65. package/client/components/playground/ToolCallsPage.tsx +81 -0
  66. package/client/components/routes/workspace/[id].tsx +534 -141
  67. package/client/components/routes/workspace/create.tsx +155 -0
  68. package/client/components/settings/IconPicker.tsx +590 -0
  69. package/client/components/settings/SettingsPages.tsx +307 -0
  70. package/client/components/settings/WorkspaceSettings.tsx +92 -0
  71. package/client/components/tool-group/CodeBlock.tsx +41 -0
  72. package/client/components/tool-group/Collapse.tsx +28 -0
  73. package/client/components/tool-group/ReadImagePreview.tsx +46 -0
  74. package/client/components/tool-group/SubagentCard.tsx +135 -0
  75. package/client/components/tool-group/TimelineRow.tsx +147 -0
  76. package/client/components/tool-group/ToolCallGroup.tsx +231 -0
  77. package/client/components/tool-group/ToolOutput.tsx +139 -0
  78. package/client/components/tool-group/detect.ts +93 -0
  79. package/client/components/tool-group/fixtures.ts +315 -0
  80. package/client/components/tool-group/format.ts +211 -0
  81. package/client/components/tool-group/index.ts +9 -0
  82. package/client/components/ui/button.tsx +4 -4
  83. package/client/components/ui/dialog.tsx +58 -0
  84. package/client/components/ui/dropdown-menu.tsx +9 -9
  85. package/client/components/ui/hover-card.tsx +44 -0
  86. package/client/components/ui/popover.tsx +1 -1
  87. package/client/components/ui/switch.tsx +23 -0
  88. package/client/components/ui/tooltip.tsx +54 -0
  89. package/client/externalize-react.ts +11 -5
  90. package/client/hooks/useApplet.ts +117 -0
  91. package/client/hooks/useChat.ts +162 -62
  92. package/client/hooks/useMeiEvents.ts +9 -2
  93. package/client/hooks/useStickToBottom.ts +86 -0
  94. package/client/hooks/useWorkspaceTheme.ts +8 -2
  95. package/client/index.css +49 -3
  96. package/client/index.html +22 -18
  97. package/client/index.tsx +29 -2
  98. package/client/lib/WorkspaceContext.tsx +5 -8
  99. package/client/lib/WorkspaceLayoutContext.tsx +30 -10
  100. package/client/lib/applet-cache.ts +54 -0
  101. package/client/lib/connection.ts +237 -0
  102. package/client/lib/flags.ts +10 -0
  103. package/client/lib/mcp-icons.ts +142 -10
  104. package/client/lib/preview-turn.ts +37 -0
  105. package/client/lib/render-icon.ts +173 -0
  106. package/client/lib/scratch-executor.ts +20 -0
  107. package/client/lib/uploads.ts +18 -0
  108. package/client/main.tsx +5 -0
  109. package/client/store/live.ts +282 -0
  110. package/client/structured-clone-shim.ts +14 -0
  111. package/client/theme.css +2 -2
  112. package/client/vendor/emojibase/en/data.json +1 -0
  113. package/client/vendor/emojibase/en/messages.json +1 -0
  114. package/client/vendor/react/development/_impl/react-dom-client.js +15871 -0
  115. package/client/vendor/react/development/_impl/react-dom.js +223 -0
  116. package/client/vendor/react/development/_impl/react-jsx-dev-runtime.js +256 -0
  117. package/client/vendor/react/development/_impl/react-jsx-runtime.js +260 -0
  118. package/client/vendor/react/development/_impl/react.js +863 -0
  119. package/client/vendor/react/development/react-dom-client.js +6 -0
  120. package/client/vendor/react/development/react-dom.js +17 -0
  121. package/client/vendor/react/development/react-jsx-dev-runtime.js +5 -0
  122. package/client/vendor/react/development/react-jsx-runtime.js +6 -0
  123. package/client/vendor/react/development/react.js +47 -0
  124. package/client/vendor/react/production/_impl/react-dom-client.js +10361 -0
  125. package/client/vendor/react/production/_impl/react-dom.js +184 -0
  126. package/client/vendor/react/production/_impl/react-jsx-dev-runtime.js +37 -0
  127. package/client/vendor/react/production/_impl/react-jsx-runtime.js +60 -0
  128. package/client/vendor/react/production/_impl/react.js +428 -0
  129. package/client/vendor/react/production/react-dom-client.js +6 -0
  130. package/client/vendor/react/production/react-dom.js +17 -0
  131. package/client/vendor/react/production/react-jsx-dev-runtime.js +5 -0
  132. package/client/vendor/react/production/react-jsx-runtime.js +6 -0
  133. package/client/vendor/react/production/react.js +47 -0
  134. package/dist/agentation-4s0nn45p.png +0 -0
  135. package/dist/airtable-hsa66v6q.png +0 -0
  136. package/dist/apollo-2ed5dy2d.png +0 -0
  137. package/dist/asana-tvgtwbx2.png +0 -0
  138. package/dist/atlassian-b3tq39hs.png +0 -0
  139. package/dist/box-w3n36t5g.png +0 -0
  140. package/dist/chrome-tspm94rw.svg +33 -0
  141. package/dist/chunk-kc6e9nd4.css +1 -0
  142. package/dist/chunk-yf3p7qg7.js +673 -0
  143. package/dist/claude-z2xnay0d.svg +3 -0
  144. package/dist/clickup-qqrqqvqb.png +0 -0
  145. package/dist/cloudflare-j9p931v6.png +0 -0
  146. package/dist/context7-8ht0xjfy.png +0 -0
  147. package/dist/datadog-70ne3yzt.png +0 -0
  148. package/dist/discord-vejhptwx.png +0 -0
  149. package/dist/dropbox-4m5s9mgr.png +0 -0
  150. package/dist/elevenlabs-2nzzej1t.png +0 -0
  151. package/dist/exa-qqj3vr0x.png +0 -0
  152. package/dist/favicon-nbmyjfjh.png +0 -0
  153. package/dist/figma-y9898rry.png +0 -0
  154. package/dist/firecrawl-w2t8nehx.png +0 -0
  155. package/dist/github-av5r5y3e.png +0 -0
  156. package/dist/gitlab-4pv5vm6b.png +0 -0
  157. package/dist/gmail-sg6a5v3x.png +0 -0
  158. package/dist/googlecalendar-nqhh2v7r.png +0 -0
  159. package/dist/googledrive-6s8xyab7.png +0 -0
  160. package/dist/grafana-1yfsnwr6.png +0 -0
  161. package/dist/granola-7j3b0nk2.png +0 -0
  162. package/dist/hermes-nous-pznd63x9.png +0 -0
  163. package/dist/hubspot-hghcmc2t.png +0 -0
  164. package/dist/huggingface-kxzaxj83.png +0 -0
  165. package/dist/index.html +47 -0
  166. package/dist/intercom-td763jt8.png +0 -0
  167. package/dist/linear-v9s3az2d.png +0 -0
  168. package/dist/monday-jdbs4wwf.png +0 -0
  169. package/dist/mongodb-emzxvhd5.png +0 -0
  170. package/dist/neon-zj4qar44.png +0 -0
  171. package/dist/notion-w034c0b8.png +0 -0
  172. package/dist/openclaw-a2pyfhpn.svg +22 -0
  173. package/dist/paper-zbt34fab.png +0 -0
  174. package/dist/paypal-kwwf7xsc.png +0 -0
  175. package/dist/perplexity-4y63rxvj.png +0 -0
  176. package/dist/postgresql-qsspbsr1.png +0 -0
  177. package/dist/posthog-sphppc4w.png +0 -0
  178. package/dist/puppeteer-2xjt1a9b.png +0 -0
  179. package/dist/railway-834de8d2.png +0 -0
  180. package/dist/redis-spm6w2m1.png +0 -0
  181. package/dist/salesforce-1mk56v4z.png +0 -0
  182. package/dist/sentry-hdwpmvek.png +0 -0
  183. package/dist/shopify-90dadaav.png +0 -0
  184. package/dist/slack-1c1wj62s.png +0 -0
  185. package/dist/snowflake-hfpykpgy.png +0 -0
  186. package/dist/stripe-zrfaqbj3.png +0 -0
  187. package/dist/supabase-4vg33zf2.png +0 -0
  188. package/dist/telegram-v6tjyrs7.png +0 -0
  189. package/dist/twilio-dpyjdwpj.png +0 -0
  190. package/dist/vercel-7d0ssw28.png +0 -0
  191. package/dist/zapier-p67qfch0.png +0 -0
  192. package/lib/attachment-note.ts +48 -0
  193. package/lib/claude-adapter.ts +219 -29
  194. package/lib/format.ts +32 -0
  195. package/lib/types.ts +314 -6
  196. package/package.json +21 -31
  197. package/server/CLAUDE.md +3 -0
  198. package/server/agent.ts +25 -118
  199. package/server/api.ts +593 -0
  200. package/server/applets.ts +396 -0
  201. package/server/build-applet.ts +580 -0
  202. package/server/cc-session.ts +611 -0
  203. package/server/cli-colors.ts +17 -0
  204. package/server/cli-ui.ts +52 -0
  205. package/server/cli.ts +970 -72
  206. package/server/control.ts +166 -19
  207. package/server/debug.ts +10 -0
  208. package/server/events.ts +24 -0
  209. package/server/functions-worker.ts +18 -2
  210. package/server/functions.ts +59 -12
  211. package/server/icon.ts +13 -0
  212. package/server/layout.ts +25 -3
  213. package/server/mcp.ts +125 -0
  214. package/server/moi-scaffold.ts +85 -0
  215. package/server/openclaw-session.ts +41 -10
  216. package/server/openclaw.ts +22 -0
  217. package/server/preview.ts +70 -0
  218. package/server/registry.ts +32 -2
  219. package/server/scratchpad-executor.ts +380 -0
  220. package/server/scratchpad-relay.ts +45 -0
  221. package/server/scratchpad.ts +171 -0
  222. package/server/skill-version.ts +146 -0
  223. package/server/skills-template.ts +6 -1
  224. package/server/state.ts +22 -36
  225. package/server/static.ts +23 -0
  226. package/server/status.ts +94 -0
  227. package/server/thread-config.ts +125 -0
  228. package/server/uploads.ts +0 -0
  229. package/server/vendor.ts +63 -0
  230. package/server/views.ts +0 -0
  231. package/server/web.ts +113 -223
  232. package/server/widgets.ts +52 -142
  233. package/server/workspace-config.ts +37 -0
  234. package/server/workspace-env.ts +407 -0
  235. package/server/workspace-init.ts +66 -0
  236. package/workspace/.claude/skills/moi-workspace/DESIGN.md +109 -0
  237. package/workspace/.claude/skills/moi-workspace/SCRATCHPAD.md +57 -0
  238. package/workspace/.claude/skills/moi-workspace/SKILL.md +252 -0
  239. package/workspace/.claude/skills/moi-workspace/VIEW-DESIGN.md +22 -0
  240. package/client/hooks/useWidget.ts +0 -72
  241. package/client/hooks/useWidgetList.ts +0 -30
  242. package/client/lib/ws.ts +0 -129
  243. package/client/store/chat.tsx +0 -162
  244. package/server/build-widget.ts +0 -343
  245. package/workspace/.claude/skills/widgets/DESIGN.md +0 -630
  246. package/workspace/.claude/skills/widgets/SKILL.md +0 -176
@@ -0,0 +1,396 @@
1
+ // Shared machinery for the kinds of **applet** — agent-authored UI units
2
+ // embedded in a workspace: grid **widgets** (`.moi/widgets/`) and full-screen
3
+ // **views** (`.moi/views/`). Both compile through `buildApplet` and are served
4
+ // as ESM. This module holds the kind-agnostic mechanics (paths, scan,
5
+ // staleness, prune, serve, build loop); the per-kind manifest shape, config
6
+ // schema, and MEI events live in `widgets.ts` / `views.ts`.
7
+ //
8
+ // Each applet builds into its OWN directory `.build/<kind>/<name>/`, holding a
9
+ // fixed `index.js` entry plus any code chunks and bundled assets (hashed
10
+ // images/fonts). The client dynamic-imports `<name>/index.js`; assets and
11
+ // chunks resolve module-relative from there. `.js` files carry the
12
+ // `%%MOI_APPLET_API_BASE%%` sentinel (for RPC + `fileUrl`), swapped to the real
13
+ // `/api/workspaces/<id>` base when served — so the on-disk bundle is
14
+ // workspace-agnostic.
15
+ import { realpathSync } from 'node:fs'
16
+ import { mkdir, readdir, rm } from 'node:fs/promises'
17
+ import { dirname, join, resolve, sep } from 'path'
18
+
19
+ import {
20
+ APPLET_API_BASE_SENTINEL,
21
+ type AppletKind,
22
+ buildApplet,
23
+ scanAssetImports,
24
+ scanServerImports
25
+ } from './build-applet'
26
+
27
+ export type AppletPaths = {
28
+ moiRoot: string
29
+ sourceDir: string
30
+ buildDir: string
31
+ manifestPath: string
32
+ }
33
+
34
+ export function getAppletPaths(workspacePath: string, kind: AppletKind): AppletPaths {
35
+ const moiRoot = join(workspacePath, '.moi')
36
+ const dir = kind === 'widget' ? 'widgets' : 'views'
37
+ const sourceDir = join(moiRoot, dir)
38
+ const buildDir = join(moiRoot, '.build', dir)
39
+ const manifestPath = join(buildDir, 'manifest.json')
40
+ return { moiRoot, sourceDir, buildDir, manifestPath }
41
+ }
42
+
43
+ // Source module names in a kind's directory: `*.tsx`/`*.ts` minus `.server.ts`.
44
+ export async function scanSources(sourceDir: string): Promise<string[]> {
45
+ try {
46
+ const entries = await readdir(sourceDir)
47
+ return entries
48
+ .filter(f => /\.(tsx|ts)$/.test(f) && !f.endsWith('.server.ts'))
49
+ .map(f => f.replace(/\.tsx?$/, ''))
50
+ } catch {
51
+ return []
52
+ }
53
+ }
54
+
55
+ async function resolveSource(sourceDir: string, name: string): Promise<string | null> {
56
+ for (const ext of ['.tsx', '.ts']) {
57
+ const path = join(sourceDir, `${name}${ext}`)
58
+ if (await Bun.file(path).exists()) return path
59
+ }
60
+ return null
61
+ }
62
+
63
+ // A bundle is stale if its entry `index.js` is missing, or the source — or any
64
+ // `.server.ts` it imports (RPC stubs are inlined) or asset it imports (emitted
65
+ // into the bundle dir) — is newer than the built entry.
66
+ async function needsRebuild(buildDir: string, name: string, srcPath: string): Promise<boolean> {
67
+ const built = Bun.file(join(buildDir, name, 'index.js'))
68
+ if (!(await built.exists())) return true
69
+ let sourceMtime = Bun.file(srcPath).lastModified
70
+ const source = await Bun.file(srcPath).text()
71
+ const dir = dirname(srcPath)
72
+ for (const specifier of scanServerImports(source)) {
73
+ const serverFile = Bun.file(join(dir, `${specifier}.server.ts`))
74
+ if (await serverFile.exists()) {
75
+ sourceMtime = Math.max(sourceMtime, serverFile.lastModified)
76
+ }
77
+ }
78
+ for (const specifier of scanAssetImports(source)) {
79
+ const assetFile = Bun.file(join(dir, specifier))
80
+ if (await assetFile.exists()) {
81
+ sourceMtime = Math.max(sourceMtime, assetFile.lastModified)
82
+ }
83
+ }
84
+ return sourceMtime >= built.lastModified
85
+ }
86
+
87
+ // Built applet names: subdirectories of `buildDir` that hold an `index.js`
88
+ // entry. (`manifest.json` and any stray files are ignored.)
89
+ export async function listBuilt(buildDir: string): Promise<string[]> {
90
+ try {
91
+ const entries = await readdir(buildDir, { withFileTypes: true })
92
+ const names: string[] = []
93
+ for (const e of entries) {
94
+ if (!e.isDirectory()) continue
95
+ if (await Bun.file(join(buildDir, e.name, 'index.js')).exists()) names.push(e.name)
96
+ }
97
+ return names
98
+ } catch {
99
+ return []
100
+ }
101
+ }
102
+
103
+ async function pruneStaleBuilds(buildDir: string, sourceNames: Set<string>): Promise<void> {
104
+ let entries
105
+ try {
106
+ entries = await readdir(buildDir, { withFileTypes: true })
107
+ } catch {
108
+ return
109
+ }
110
+ for (const e of entries) {
111
+ // Drop build dirs whose source is gone…
112
+ if (e.isDirectory()) {
113
+ if (!sourceNames.has(e.name)) {
114
+ await rm(join(buildDir, e.name), { recursive: true, force: true }).catch(() => {})
115
+ }
116
+ continue
117
+ }
118
+ // …and sweep leftover flat `<name>.js` from the pre-directory layout (the
119
+ // new layout never writes `.js` directly under buildDir — entries live in
120
+ // `<name>/index.js`). manifest.json and other files are left alone.
121
+ if (e.isFile() && e.name.endsWith('.js')) {
122
+ await rm(join(buildDir, e.name), { force: true }).catch(() => {})
123
+ }
124
+ }
125
+ }
126
+
127
+ // Files an applet may serve from its build dir, by extension. JS is swapped +
128
+ // served as code; everything else streams raw (Bun infers content-type and
129
+ // supports range requests).
130
+ const CODE_FILE_RE = /\.js$/
131
+ // A single flat filename in the bundle dir: index.js, chunk-<hash>.js, or a
132
+ // hashed asset. First char may be `_`/`-` (asset stems derive from the source
133
+ // basename, e.g. `_icon.png` → `_icon-<hash>.png`) but never `.`, so no dotfile
134
+ // can be requested; `..` is rejected separately.
135
+ const ALLOWED_FILE_RE = /^[a-zA-Z0-9_-][a-zA-Z0-9._-]*$/
136
+
137
+ // Serve one file from a compiled applet directory: the `index.js` entry, a code
138
+ // chunk, or a bundled asset. `apiBase` is the workspace's `/api/workspaces/<id>`
139
+ // prefix — substituted for the build-time sentinel in every `.js` so RPC and
140
+ // `fileUrl` calls hit the right workspace. Assets stream untouched.
141
+ export async function serveApplet(
142
+ kind: AppletKind,
143
+ name: string,
144
+ file: string,
145
+ workspacePath: string,
146
+ apiBase: string
147
+ ): Promise<Response> {
148
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
149
+ return new Response('Invalid name', { status: 400 })
150
+ }
151
+ // Single path segment, no traversal — the bundle dir is flat.
152
+ if (!ALLOWED_FILE_RE.test(file) || file.includes('..')) {
153
+ return new Response('Invalid file', { status: 400 })
154
+ }
155
+ const { buildDir } = getAppletPaths(workspacePath, kind)
156
+ const path = join(buildDir, name, file)
157
+ const bunFile = Bun.file(path)
158
+ if (!(await bunFile.exists())) {
159
+ return new Response(`"${name}" not built. Run: moi bundle`, { status: 404 })
160
+ }
161
+ if (CODE_FILE_RE.test(file)) {
162
+ const swapped = (await bunFile.text()).replaceAll(APPLET_API_BASE_SENTINEL, apiBase)
163
+ return new Response(swapped, { headers: { 'Content-Type': 'text/javascript; charset=utf-8' } })
164
+ }
165
+ return new Response(bunFile)
166
+ }
167
+
168
+ // ---- route helpers ----------------------------------------------------------
169
+ // Pure helpers behind the applet/fs/rpc HTTP routes, kept here (not web.ts) so
170
+ // they're unit-testable without importing web.ts — which binds ports on load.
171
+
172
+ // The API base a served bundle's sentinel is rewritten to. RPC + `fileUrl`
173
+ // hang off it, matching what the compiled `rpc()` / `fileUrl()` prepend.
174
+ export function apiBaseFor(id: string): string {
175
+ return `/api/workspaces/${id}`
176
+ }
177
+
178
+ // Split an applet file request `…/<segment>/<name>/<file>` into name + file. A
179
+ // bare `…/<segment>/<name>` (or legacy `…/<name>.js`) targets the entry.
180
+ export function parseAppletTail(
181
+ url: string,
182
+ id: string,
183
+ segment: 'widgets' | 'views'
184
+ ): { name: string; file: string } {
185
+ const tail = new URL(url).pathname.split(`/api/workspaces/${id}/${segment}/`)[1] ?? ''
186
+ const slash = tail.indexOf('/')
187
+ if (slash === -1) return { name: tail.replace(/\.js$/, ''), file: 'index.js' }
188
+ return { name: tail.slice(0, slash), file: tail.slice(slash + 1) }
189
+ }
190
+
191
+ // Extensions `fileUrl()` may stream from the workspace. Media + image/doc
192
+ // assets only — deliberately excludes text/data (`.json`, `.env`, `.md`,
193
+ // source) so the route can't be used to exfiltrate arbitrary workspace data.
194
+ const FS_MEDIA_RE =
195
+ /\.(mp4|webm|mov|m4v|mkv|mp3|wav|ogg|oga|m4a|flac|aac|opus|png|jpe?g|gif|webp|avif|svg|ico|pdf|vtt|srt)$/i
196
+
197
+ // Resolve a `/fs/`-style tail to a real on-disk path inside the workspace root,
198
+ // or an error Response. Hard guards (defense in depth): reject empty/`.`/`..`/
199
+ // dotfile segments and anything resolving outside the root, and require a media
200
+ // extension. The workspace holds secrets (`.env`, `.moi/`) and the routes built
201
+ // on this are unauthenticated — these guards are the protection, not the
202
+ // localhost bind. Shared by the raw stream (`serveWorkspaceFile`) and the image
203
+ // preview route (server/preview.ts).
204
+ export function resolveWorkspaceMediaFile(workspaceRoot: string, tail: string): string | Response {
205
+ let rel: string
206
+ try {
207
+ rel = decodeURIComponent(tail)
208
+ } catch {
209
+ return new Response('Bad path', { status: 400 })
210
+ }
211
+ if (!rel || rel.includes('\0')) return new Response('Bad path', { status: 400 })
212
+
213
+ const segments = rel.split('/')
214
+ if (segments.some(s => s === '' || s === '.' || s === '..' || s.startsWith('.'))) {
215
+ return new Response('Forbidden', { status: 403 })
216
+ }
217
+ if (!FS_MEDIA_RE.test(rel)) return new Response('Unsupported file type', { status: 415 })
218
+
219
+ const root = resolve(workspaceRoot)
220
+ const target = resolve(workspaceRoot, rel)
221
+ if (target !== root && !target.startsWith(root + sep)) {
222
+ return new Response('Forbidden', { status: 403 })
223
+ }
224
+
225
+ // The lexical check above is not enough: a symlink that lives inside the root
226
+ // but points outside it would pass. Canonicalize both sides and re-check on
227
+ // the real paths — this blocks symlink escape while still allowing symlinks
228
+ // that stay within the workspace. realpathSync throws ENOENT for a missing
229
+ // file, which doubles as the existence check (→ 404). Both sides are
230
+ // canonicalized so a symlinked root (e.g. macOS /tmp → /private/tmp) isn't a
231
+ // false escape.
232
+ let realTarget: string
233
+ try {
234
+ realTarget = realpathSync(target)
235
+ } catch {
236
+ return new Response('Not found', { status: 404 })
237
+ }
238
+ let realRoot: string
239
+ try {
240
+ realRoot = realpathSync(root)
241
+ } catch {
242
+ return new Response('Forbidden', { status: 403 })
243
+ }
244
+ if (realTarget !== realRoot && !realTarget.startsWith(realRoot + sep)) {
245
+ return new Response('Forbidden', { status: 403 })
246
+ }
247
+ return realTarget
248
+ }
249
+
250
+ // Stream a media file from the workspace root (guards: see
251
+ // `resolveWorkspaceMediaFile`).
252
+ //
253
+ // Range is handled explicitly (slice the BunFile, 206 + Content-Range): Bun's
254
+ // implicit range handling for `new Response(Bun.file())` doesn't fire once any
255
+ // headers object is attached, and <video>/<audio> seeking needs byte ranges.
256
+ export async function serveWorkspaceFile(
257
+ workspaceRoot: string,
258
+ tail: string,
259
+ range?: string | null
260
+ ): Promise<Response> {
261
+ const realTarget = resolveWorkspaceMediaFile(workspaceRoot, tail)
262
+ if (realTarget instanceof Response) return realTarget
263
+ const file = Bun.file(realTarget)
264
+
265
+ const size = file.size
266
+ const type = file.type || 'application/octet-stream'
267
+ const parsed = range ? parseByteRange(range, size) : null
268
+
269
+ if (parsed === 'invalid') {
270
+ return new Response('Range Not Satisfiable', {
271
+ status: 416,
272
+ headers: { 'Content-Range': `bytes */${size}`, 'Accept-Ranges': 'bytes' }
273
+ })
274
+ }
275
+ if (parsed) {
276
+ const { start, end } = parsed
277
+ return new Response(file.slice(start, end + 1), {
278
+ status: 206,
279
+ headers: {
280
+ 'Content-Type': type,
281
+ 'Content-Length': String(end - start + 1),
282
+ 'Content-Range': `bytes ${start}-${end}/${size}`,
283
+ 'Accept-Ranges': 'bytes'
284
+ }
285
+ })
286
+ }
287
+ return new Response(file, {
288
+ headers: { 'Content-Type': type, 'Content-Length': String(size), 'Accept-Ranges': 'bytes' }
289
+ })
290
+ }
291
+
292
+ // Parse a single `bytes=start-end` (or suffix `bytes=-N`) range against a known
293
+ // size. Returns the inclusive [start, end], null when there's no usable range
294
+ // header, or 'invalid' for an unsatisfiable range (→ 416). Multi-range requests
295
+ // are not supported (we serve the whole file instead — null).
296
+ function parseByteRange(
297
+ header: string,
298
+ size: number
299
+ ): { start: number; end: number } | null | 'invalid' {
300
+ const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim())
301
+ if (!m) return null
302
+ const hasStart = m[1] !== ''
303
+ const hasEnd = m[2] !== ''
304
+ if (!hasStart && !hasEnd) return null
305
+ if (size === 0) return 'invalid'
306
+
307
+ let start: number
308
+ let end: number
309
+ if (!hasStart) {
310
+ // Suffix range: the last N bytes.
311
+ const n = parseInt(m[2], 10)
312
+ start = Math.max(0, size - n)
313
+ end = size - 1
314
+ } else {
315
+ start = parseInt(m[1], 10)
316
+ end = hasEnd ? Math.min(parseInt(m[2], 10), size - 1) : size - 1
317
+ }
318
+ if (start > end || start >= size || start < 0) return 'invalid'
319
+ return { start, end }
320
+ }
321
+
322
+ export type AppletBuildResult<C> = {
323
+ name: string
324
+ status: 'built' | 'skipped' | 'failed'
325
+ error?: string
326
+ serverModules?: string[]
327
+ config?: C | null
328
+ }
329
+
330
+ // Build every stale (or all, when `force`) source for one kind: prunes orphaned
331
+ // build dirs, writes fresh `<name>/` directories (entry + chunks + assets), and
332
+ // returns per-entry results with the parsed config and server-module names.
333
+ // Manifest persistence and MEI broadcasting are the caller's responsibility —
334
+ // they differ per kind.
335
+ export async function buildApplets<C>(
336
+ workspacePath: string,
337
+ kind: AppletKind,
338
+ force: boolean
339
+ ): Promise<{ names: string[]; results: AppletBuildResult<C>[]; ms: number }> {
340
+ const t0 = performance.now()
341
+ const { sourceDir, buildDir, moiRoot } = getAppletPaths(workspacePath, kind)
342
+ const names = await scanSources(sourceDir)
343
+
344
+ // Only scaffold the build dir once there's something to build — never
345
+ // fabricate a `.build/` (and the phantom nested `.moi/.moi/` it implies) for a
346
+ // directory with no sources. When sources have all been deleted we skip the
347
+ // mkdir but still prune so orphaned build dirs are swept (pruneStaleBuilds
348
+ // no-ops if buildDir doesn't exist).
349
+ if (names.length > 0) {
350
+ await mkdir(buildDir, { recursive: true })
351
+ }
352
+ await pruneStaleBuilds(buildDir, new Set(names))
353
+
354
+ const jobs = await Promise.all(
355
+ names.map(async name => {
356
+ const srcPath = await resolveSource(sourceDir, name)
357
+ if (!srcPath) return { name, status: 'failed' as const, error: 'Source file not found' }
358
+ if (!force && !(await needsRebuild(buildDir, name, srcPath))) {
359
+ return { name, status: 'skipped' as const }
360
+ }
361
+ return { name, srcPath, status: 'pending' as const }
362
+ })
363
+ )
364
+
365
+ const results = await Promise.all(
366
+ jobs.map(async (job): Promise<AppletBuildResult<C>> => {
367
+ if (job.status === 'failed') return { name: job.name, status: 'failed', error: job.error }
368
+ if (job.status === 'skipped') return { name: job.name, status: 'skipped' }
369
+ try {
370
+ const artifact = await buildApplet(job.srcPath!, moiRoot, kind)
371
+ // Clear the dir first so stale hashed assets from a prior build don't
372
+ // accumulate, then write the fresh entry + chunks + assets.
373
+ const dir = join(buildDir, job.name)
374
+ await rm(dir, { recursive: true, force: true })
375
+ await mkdir(dir, { recursive: true })
376
+ for (const f of artifact.files) {
377
+ await Bun.write(join(dir, f.name), f.data)
378
+ }
379
+ return {
380
+ name: job.name,
381
+ status: 'built',
382
+ serverModules: artifact.serverModules.map(m => m.name),
383
+ config: (artifact.config as C | null) ?? null
384
+ }
385
+ } catch (err) {
386
+ return {
387
+ name: job.name,
388
+ status: 'failed',
389
+ error: err instanceof Error ? err.message : 'Unknown error'
390
+ }
391
+ }
392
+ })
393
+ )
394
+
395
+ return { names, results, ms: Math.round(performance.now() - t0) }
396
+ }