moi-computer 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (106) hide show
  1. package/LICENSE +95 -0
  2. package/README.md +71 -0
  3. package/bin/moi.mjs +25 -0
  4. package/bunfig.toml +3 -0
  5. package/client/CLAUDE.md +12 -0
  6. package/client/api/workspaces.ts +158 -0
  7. package/client/assets/claude.svg +3 -0
  8. package/client/assets/favicon.png +0 -0
  9. package/client/assets/hermes-nous.png +0 -0
  10. package/client/assets/mcp/.gitkeep +0 -0
  11. package/client/assets/mcp/atlassian.png +0 -0
  12. package/client/assets/mcp/discord.png +0 -0
  13. package/client/assets/mcp/figma.png +0 -0
  14. package/client/assets/mcp/github.png +0 -0
  15. package/client/assets/mcp/gitlab.png +0 -0
  16. package/client/assets/mcp/granola.png +0 -0
  17. package/client/assets/mcp/hubspot.png +0 -0
  18. package/client/assets/mcp/linear.png +0 -0
  19. package/client/assets/mcp/neon.png +0 -0
  20. package/client/assets/mcp/notion.png +0 -0
  21. package/client/assets/mcp/sentry.png +0 -0
  22. package/client/assets/mcp/slack.png +0 -0
  23. package/client/assets/mcp/stripe.png +0 -0
  24. package/client/assets/mcp/supabase.png +0 -0
  25. package/client/assets/mcp/vercel.png +0 -0
  26. package/client/assets/moi-logo.svg +11 -0
  27. package/client/assets/openclaw.svg +22 -0
  28. package/client/components/App.tsx +35 -0
  29. package/client/components/BottomPanel.tsx +33 -0
  30. package/client/components/ChatInput.tsx +62 -0
  31. package/client/components/ChatPanel.tsx +206 -0
  32. package/client/components/ChatPopup.tsx +60 -0
  33. package/client/components/CustomizePanel.tsx +117 -0
  34. package/client/components/HiddenPanel.tsx +79 -0
  35. package/client/components/HomePage.tsx +17 -0
  36. package/client/components/MarkdownContent.tsx +41 -0
  37. package/client/components/ThreadSelector.tsx +88 -0
  38. package/client/components/TurnView.tsx +618 -0
  39. package/client/components/WidgetErrorBoundary.tsx +46 -0
  40. package/client/components/WidgetFrame.tsx +66 -0
  41. package/client/components/WidgetGrid.tsx +113 -0
  42. package/client/components/WidgetShell.tsx +44 -0
  43. package/client/components/Widgets.tsx +132 -0
  44. package/client/components/WorkspacePreview.tsx +48 -0
  45. package/client/components/WorkspacesPage.tsx +237 -0
  46. package/client/components/layout/SidebarLayout.tsx +260 -0
  47. package/client/components/playground/LedLogo.tsx +181 -0
  48. package/client/components/playground/PixelPainter.tsx +105 -0
  49. package/client/components/playground/PlaygroundPage.tsx +71 -0
  50. package/client/components/routes/workspace/[id].tsx +282 -0
  51. package/client/components/ui/button.tsx +48 -0
  52. package/client/components/ui/dropdown-menu.tsx +257 -0
  53. package/client/components/ui/input.tsx +21 -0
  54. package/client/components/ui/popover.tsx +79 -0
  55. package/client/components/ui/textarea.tsx +18 -0
  56. package/client/externalize-react.ts +29 -0
  57. package/client/hooks/useChat.ts +88 -0
  58. package/client/hooks/useFitsSidebar.ts +34 -0
  59. package/client/hooks/useGridReconcile.ts +73 -0
  60. package/client/hooks/useMeiEvents.ts +66 -0
  61. package/client/hooks/useScrollFade.ts +38 -0
  62. package/client/hooks/useWidget.ts +72 -0
  63. package/client/hooks/useWidgetList.ts +30 -0
  64. package/client/hooks/useWorkspaceTheme.ts +76 -0
  65. package/client/index.css +182 -0
  66. package/client/index.html +43 -0
  67. package/client/index.tsx +19 -0
  68. package/client/lib/WorkspaceContext.tsx +24 -0
  69. package/client/lib/WorkspaceLayoutContext.tsx +92 -0
  70. package/client/lib/cn.ts +6 -0
  71. package/client/lib/grid-pack.ts +35 -0
  72. package/client/lib/group-turns.ts +44 -0
  73. package/client/lib/mcp-icons.ts +53 -0
  74. package/client/lib/ws.ts +129 -0
  75. package/client/main.tsx +23 -0
  76. package/client/store/chat.tsx +162 -0
  77. package/client/store/ui.ts +21 -0
  78. package/client/theme.css +66 -0
  79. package/lib/claude-adapter.ts +602 -0
  80. package/lib/format.ts +212 -0
  81. package/lib/themes.ts +89 -0
  82. package/lib/types.ts +144 -0
  83. package/package.json +117 -0
  84. package/server/CLAUDE.md +6 -0
  85. package/server/agent.ts +132 -0
  86. package/server/build-widget.ts +343 -0
  87. package/server/cli.ts +632 -0
  88. package/server/constants.ts +3 -0
  89. package/server/control.ts +98 -0
  90. package/server/functions-worker.ts +89 -0
  91. package/server/functions.ts +171 -0
  92. package/server/layout.ts +83 -0
  93. package/server/openclaw-adapter.ts +242 -0
  94. package/server/openclaw-gateway.ts +255 -0
  95. package/server/openclaw-session.ts +485 -0
  96. package/server/openclaw-strip.ts +134 -0
  97. package/server/openclaw.ts +206 -0
  98. package/server/registry.ts +150 -0
  99. package/server/skills-template.ts +21 -0
  100. package/server/state.ts +87 -0
  101. package/server/theme.ts +55 -0
  102. package/server/web.ts +321 -0
  103. package/server/widgets.ts +254 -0
  104. package/tsconfig.json +21 -0
  105. package/workspace/.claude/skills/widgets/DESIGN.md +630 -0
  106. package/workspace/.claude/skills/widgets/SKILL.md +176 -0
package/server/web.ts ADDED
@@ -0,0 +1,321 @@
1
+ import type { ClientMessage } from '@/lib/types'
2
+
3
+ import index from '../client/index.html'
4
+ import { getMcpStatus, handleChat, stopChat } from './agent'
5
+ import { PORT } from './constants'
6
+ import { control } from './control'
7
+ import { callFunction, killAllWorkers } from './functions'
8
+ import { getWorkspacePreview, loadLayout, saveLayout } from './layout'
9
+ import { getOpenClawSessionMessages, getOpenClawSessions } from './openclaw'
10
+ import { toSessionInfo, toStreamEvents } from './openclaw-adapter'
11
+ import {
12
+ abortOpenClawRun,
13
+ ensureOpenClawSessionLive,
14
+ getLiveOpenClawEvents,
15
+ getOpenClawProcessingSessions,
16
+ sendOpenClawMessage
17
+ } from './openclaw-session'
18
+ import {
19
+ discoverWorkspaces,
20
+ getWorkspace,
21
+ listWorkspaces,
22
+ registerWorkspace,
23
+ removeWorkspace
24
+ } from './registry'
25
+ import {
26
+ addClient,
27
+ getProcessingSessions,
28
+ getSessionEvents,
29
+ getSessions,
30
+ removeClient,
31
+ sendToClient
32
+ } from './state'
33
+ import { listWidgets, serveWidget } from './widgets'
34
+
35
+ const MEI_TOPIC = 'mei'
36
+
37
+ type WsData = { channel: 'chat' | 'mei'; workspaceId: string }
38
+
39
+ function isClientMessage(value: unknown): value is ClientMessage {
40
+ if (typeof value !== 'object' || value === null || !('type' in value)) return false
41
+ const v = value as {
42
+ type: string
43
+ sessionId?: unknown
44
+ content?: unknown
45
+ isNew?: unknown
46
+ optimisticId?: unknown
47
+ }
48
+ if (v.type === 'chat')
49
+ return (
50
+ typeof v.content === 'string' &&
51
+ typeof v.sessionId === 'string' &&
52
+ typeof v.isNew === 'boolean' &&
53
+ (v.optimisticId === undefined || typeof v.optimisticId === 'string')
54
+ )
55
+ if (v.type === 'stop') return typeof v.sessionId === 'string'
56
+ return false
57
+ }
58
+
59
+ type Upgradable = { upgrade(req: Request, opts: { data: WsData }): boolean }
60
+
61
+ function upgrade(server: Upgradable, req: Request, data: WsData) {
62
+ return server.upgrade(req, { data })
63
+ ? new Response(null, { status: 101 })
64
+ : new Response('Upgrade failed', { status: 500 })
65
+ }
66
+
67
+ export const app = Bun.serve<WsData>({
68
+ port: PORT,
69
+ hostname: process.env.HOST ?? '127.0.0.1',
70
+ development: { hmr: true },
71
+ routes: {
72
+ // Client-side routes — serve the SPA shell
73
+ '/': index,
74
+ '/playground': index,
75
+ '/workspace/*': index,
76
+
77
+ // Workspace registry API
78
+ '/api/workspaces': async req => {
79
+ if (req.method === 'GET') return Response.json(await listWorkspaces())
80
+ if (req.method === 'POST') {
81
+ const body = await req.json()
82
+ if (!body?.path) return new Response('Missing path', { status: 400 })
83
+ const rawType = body?.type
84
+ const type = rawType === 'claude-code' || rawType === 'openclaw' ? rawType : undefined
85
+ const entry = await registerWorkspace(String(body.path), {
86
+ type,
87
+ name: typeof body?.name === 'string' ? body.name : undefined,
88
+ agentId: typeof body?.agentId === 'string' ? body.agentId : undefined,
89
+ isDefault: typeof body?.isDefault === 'boolean' ? body.isDefault : undefined,
90
+ lastRunAt: typeof body?.lastRunAt === 'string' ? body.lastRunAt : undefined
91
+ })
92
+ return Response.json(entry, { status: 201 })
93
+ }
94
+ return new Response('Method not allowed', { status: 405 })
95
+ },
96
+ '/api/workspaces/discover': async () => Response.json(await discoverWorkspaces()),
97
+ '/api/workspaces/:id/preview': async req => {
98
+ const ws = await getWorkspace(req.params.id)
99
+ if (!ws) return Response.json({ cols: 4, items: [] })
100
+ return Response.json(await getWorkspacePreview(ws.path))
101
+ },
102
+ '/api/workspaces/:id/layout': async req => {
103
+ const ws = await getWorkspace(req.params.id)
104
+ if (!ws) return new Response('Workspace not found', { status: 404 })
105
+ if (req.method === 'GET') {
106
+ return Response.json({
107
+ ...(await loadLayout(ws.path)),
108
+ cwd: ws.path,
109
+ name: ws.name,
110
+ agentId: ws.agentId
111
+ })
112
+ }
113
+ if (req.method === 'PUT') {
114
+ const body = await req.json()
115
+ if (!body || body.version !== 1) return new Response('Bad request', { status: 400 })
116
+ await saveLayout(body, ws.path)
117
+ return new Response(null, { status: 204 })
118
+ }
119
+ return new Response('Method not allowed', { status: 405 })
120
+ },
121
+ '/api/workspaces/:id/widgets': async req => {
122
+ const ws = await getWorkspace(req.params.id)
123
+ if (!ws) return new Response('Workspace not found', { status: 404 })
124
+ return listWidgets(ws.path)
125
+ },
126
+ '/api/workspaces/:id/sessions': async req => {
127
+ const ws = await getWorkspace(req.params.id)
128
+ if (!ws) return new Response('Workspace not found', { status: 404 })
129
+ if (ws.type === 'openclaw') {
130
+ const rows = await getOpenClawSessions(ws.path, ws.agentId)
131
+ return Response.json(rows.map(r => toSessionInfo(r, ws.path)))
132
+ }
133
+ return Response.json(await getSessions(ws.path))
134
+ },
135
+ // Widget bundle: the compiled ESM module for one widget, dynamically
136
+ // imported by the client (useWidget). Sits beside the GET .../widgets list
137
+ // above — the exact path lists, `/*` serves a bundle.
138
+ '/api/workspaces/:id/widgets/*': async req => {
139
+ const ws = await getWorkspace(req.params.id)
140
+ if (!ws) return new Response('Workspace not found', { status: 404 })
141
+ const name = new URL(req.url).pathname.split('/').pop()?.replace(/\.js$/, '')
142
+ return name ? serveWidget(name, ws.path) : new Response('Not found', { status: 404 })
143
+ },
144
+ '/api/workspaces/:id/sessions/:sessionId/events': async req => {
145
+ const ws = await getWorkspace(req.params.id)
146
+ if (!ws) return new Response('Workspace not found', { status: 404 })
147
+ if (ws.type === 'openclaw') {
148
+ // Prefer the live view if we already hold one — keeps REST + WS in
149
+ // agreement for any reload that lands while a run is active. The
150
+ // first cold call also primes the live subscription so subsequent
151
+ // WS frames upsert into the same view.
152
+ const live = getLiveOpenClawEvents(req.params.id, req.params.sessionId)
153
+ if (live) return Response.json(live)
154
+ if (ws.agentId) {
155
+ try {
156
+ const evs = await ensureOpenClawSessionLive({
157
+ workspaceId: req.params.id,
158
+ workspacePath: ws.path,
159
+ agentId: ws.agentId,
160
+ sessionId: req.params.sessionId
161
+ })
162
+ return Response.json(evs)
163
+ } catch {
164
+ // fall through to static path
165
+ }
166
+ }
167
+ const preview = await getOpenClawSessionMessages(req.params.sessionId, ws.path, ws.agentId)
168
+ return Response.json(toStreamEvents(preview))
169
+ }
170
+ return Response.json(await getSessionEvents(req.params.sessionId, ws.path))
171
+ },
172
+ '/api/workspaces/:id/mcp': async req => {
173
+ const ws = await getWorkspace(req.params.id)
174
+ if (!ws) return new Response('Workspace not found', { status: 404 })
175
+ return Response.json(await getMcpStatus(ws.path))
176
+ },
177
+ // Live widget-event stream (build/refresh pushes). A static path, so Bun
178
+ // routes it ahead of the `/api/workspaces/:id` param route below; the
179
+ // upgrade happens in-handler via the route's `server` argument.
180
+ '/api/workspaces/ws': (req, server) =>
181
+ upgrade(server, req, { channel: 'mei', workspaceId: '' }),
182
+ '/api/workspaces/:id': async req => {
183
+ if (req.method === 'DELETE') {
184
+ const ok = await removeWorkspace(req.params.id)
185
+ if (!ok) return new Response('Workspace not found', { status: 404 })
186
+ return new Response(null, { status: 204 })
187
+ }
188
+ return new Response('Method not allowed', { status: 405 })
189
+ },
190
+
191
+ // Widget RPC: a widget bundle POSTs here to call one of its `.server.ts`
192
+ // functions. Kept on its own internal `/_rpc/` prefix, off the public API.
193
+ '/_rpc/:wid/fn/*': async req => {
194
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
195
+ const ws = await getWorkspace(req.params.wid)
196
+ if (!ws) return new Response('Workspace not found', { status: 404 })
197
+ const prefix = `/_rpc/${req.params.wid}/fn/`
198
+ const tail = new URL(req.url).pathname.slice(prefix.length)
199
+ return handleFunctionCall(req, tail, ws.path)
200
+ }
201
+ },
202
+ fetch(req, server) {
203
+ const url = new URL(req.url)
204
+ // Chat websocket (per-workspace). The widget-event websocket lives in the
205
+ // routes table at /api/workspaces/ws.
206
+ if (url.pathname === '/ws') {
207
+ const workspaceId = url.searchParams.get('workspace') ?? ''
208
+ return upgrade(server, req, { channel: 'chat', workspaceId })
209
+ }
210
+ return new Response('Not found', { status: 404 })
211
+ },
212
+ websocket: {
213
+ open(ws) {
214
+ if (ws.data.channel === 'chat') {
215
+ addClient(ws.data.workspaceId, ws)
216
+ const seen = new Set<string>()
217
+ for (const sid of getProcessingSessions(ws.data.workspaceId)) {
218
+ seen.add(sid)
219
+ sendToClient(ws, { type: 'status', sessionId: sid, processing: true })
220
+ }
221
+ for (const sid of getOpenClawProcessingSessions(ws.data.workspaceId)) {
222
+ if (seen.has(sid)) continue
223
+ sendToClient(ws, { type: 'status', sessionId: sid, processing: true })
224
+ }
225
+ } else {
226
+ ws.subscribe(MEI_TOPIC)
227
+ }
228
+ },
229
+ async message(ws, message) {
230
+ if (ws.data.channel !== 'chat') return
231
+ try {
232
+ const data = JSON.parse(String(message))
233
+ if (!isClientMessage(data)) return
234
+
235
+ if (data.type === 'chat' && data.content?.trim()) {
236
+ const workspace = await getWorkspace(ws.data.workspaceId)
237
+ if (!workspace) return
238
+ if (workspace.type === 'openclaw' && workspace.agentId) {
239
+ sendOpenClawMessage({
240
+ workspaceId: ws.data.workspaceId,
241
+ workspacePath: workspace.path,
242
+ agentId: workspace.agentId,
243
+ sessionId: data.sessionId,
244
+ isNew: data.isNew,
245
+ content: data.content.trim(),
246
+ optimisticId: data.optimisticId
247
+ })
248
+ } else {
249
+ handleChat(
250
+ data.content.trim(),
251
+ data.sessionId,
252
+ data.isNew,
253
+ ws.data.workspaceId,
254
+ workspace.path,
255
+ data.optimisticId
256
+ )
257
+ }
258
+ }
259
+ if (data.type === 'stop') {
260
+ const workspace = await getWorkspace(ws.data.workspaceId)
261
+ if (workspace?.type === 'openclaw') {
262
+ abortOpenClawRun({ workspaceId: ws.data.workspaceId, sessionId: data.sessionId })
263
+ } else {
264
+ stopChat(data.sessionId, ws.data.workspaceId)
265
+ }
266
+ }
267
+ } catch {}
268
+ },
269
+ close(ws) {
270
+ if (ws.data.channel === 'chat') removeClient(ws.data.workspaceId, ws)
271
+ else ws.unsubscribe(MEI_TOPIC)
272
+ }
273
+ }
274
+ })
275
+
276
+ async function handleFunctionCall(
277
+ req: Request,
278
+ tail: string,
279
+ workspacePath: string
280
+ ): Promise<Response> {
281
+ const parts = tail.split('/')
282
+ if (parts.length !== 2) return new Response('Bad request', { status: 400 })
283
+
284
+ const [module, name] = parts
285
+ if (!/^[a-zA-Z0-9_$-]+$/.test(module) || !/^[a-zA-Z0-9_$]+$/.test(name)) {
286
+ return new Response('Invalid module or function name', { status: 400 })
287
+ }
288
+
289
+ try {
290
+ const contentLength = Number(req.headers.get('content-length') ?? 0)
291
+ if (contentLength > 1_000_000) {
292
+ return new Response('Request body too large', { status: 413 })
293
+ }
294
+ const args = await req.text()
295
+ const result = await callFunction(module, name, args, workspacePath)
296
+ return new Response(result, { headers: { 'Content-Type': 'application/json' } })
297
+ } catch (err) {
298
+ const message = err instanceof Error ? err.message : 'Unknown error'
299
+ return new Response(message, { status: 500 })
300
+ }
301
+ }
302
+
303
+ export function publishMei(msg: unknown) {
304
+ app.publish(MEI_TOPIC, JSON.stringify(msg))
305
+ }
306
+
307
+ // Graceful shutdown. In dev the supervisor sends SIGTERM on server-file
308
+ // changes; in any context Ctrl-C sends SIGINT. Close both servers and kill the
309
+ // per-workspace function workers so no child processes are orphaned.
310
+ function shutdown() {
311
+ try {
312
+ app.stop(true)
313
+ } catch {}
314
+ try {
315
+ control.stop(true)
316
+ } catch {}
317
+ killAllWorkers()
318
+ process.exit(0)
319
+ }
320
+ process.on('SIGTERM', shutdown)
321
+ process.on('SIGINT', shutdown)
@@ -0,0 +1,254 @@
1
+ import { mkdir, readdir, unlink } from 'node:fs/promises'
2
+ import { join } from 'path'
3
+
4
+ import type { WidgetConfig, WidgetInfo } from '@/lib/types'
5
+
6
+ import { buildWidget } from './build-widget'
7
+ import { reloadModules } from './functions'
8
+
9
+ const DEFAULT_CONFIG: WidgetConfig = { rowSpan: 1, colSpan: 2 }
10
+ const VALID_SPANS = [1, 2, 3, 4]
11
+
12
+ function getWidgetPaths(workspacePath: string) {
13
+ const sourceDir = join(workspacePath, '.widgets')
14
+ const buildDir = join(sourceDir, '.build', 'widgets')
15
+ const manifestPath = join(buildDir, 'manifest.json')
16
+ return { sourceDir, buildDir, manifestPath }
17
+ }
18
+
19
+ async function readManifest(workspacePath: string): Promise<Record<string, WidgetConfig>> {
20
+ const { manifestPath } = getWidgetPaths(workspacePath)
21
+ try {
22
+ const data = JSON.parse(await Bun.file(manifestPath).text())
23
+ return data.config ?? {}
24
+ } catch {
25
+ return {}
26
+ }
27
+ }
28
+
29
+ async function writeManifest(
30
+ workspacePath: string,
31
+ configs: Record<string, WidgetConfig>
32
+ ): Promise<void> {
33
+ const { manifestPath } = getWidgetPaths(workspacePath)
34
+ await Bun.write(manifestPath, JSON.stringify({ config: configs }, null, 2))
35
+ }
36
+
37
+ async function scanWidgets(workspacePath: string): Promise<string[]> {
38
+ const { sourceDir } = getWidgetPaths(workspacePath)
39
+ try {
40
+ const entries = await readdir(sourceDir)
41
+ return entries
42
+ .filter(f => /\.(tsx|ts)$/.test(f) && !f.endsWith('.server.ts'))
43
+ .map(f => f.replace(/\.tsx?$/, ''))
44
+ } catch {
45
+ return []
46
+ }
47
+ }
48
+
49
+ async function resolveWidgetSource(workspacePath: string, name: string): Promise<string | null> {
50
+ const { sourceDir } = getWidgetPaths(workspacePath)
51
+ for (const ext of ['.tsx', '.ts']) {
52
+ const path = join(sourceDir, `${name}${ext}`)
53
+ if (await Bun.file(path).exists()) return path
54
+ }
55
+ return null
56
+ }
57
+
58
+ async function needsRebuild(
59
+ workspacePath: string,
60
+ name: string,
61
+ srcPath: string
62
+ ): Promise<boolean> {
63
+ const { sourceDir, buildDir } = getWidgetPaths(workspacePath)
64
+ const built = Bun.file(join(buildDir, `${name}.js`))
65
+ if (!(await built.exists())) return true
66
+ // Also stat the sibling `<name>.server.ts` if it exists. The main `.tsx`
67
+ // imports `./<name>.server` and the build inlines RPC stubs for its
68
+ // exports, so a server-only edit must trigger a rebuild — but its mtime
69
+ // lives on a different file than `srcPath`.
70
+ const serverPath = join(sourceDir, `${name}.server.ts`)
71
+ const serverFile = Bun.file(serverPath)
72
+ const serverMtime = (await serverFile.exists()) ? serverFile.lastModified : 0
73
+ const sourceMtime = Math.max(Bun.file(srcPath).lastModified, serverMtime)
74
+ return sourceMtime >= built.lastModified
75
+ }
76
+
77
+ async function pruneStaleBuilds(workspacePath: string, sourceNames: Set<string>) {
78
+ const built = await listBuiltWidgets(workspacePath)
79
+ const { buildDir } = getWidgetPaths(workspacePath)
80
+ for (const name of built) {
81
+ if (!sourceNames.has(name)) {
82
+ try {
83
+ await unlink(join(buildDir, `${name}.js`))
84
+ } catch {}
85
+ }
86
+ }
87
+ }
88
+
89
+ export type WidgetBuildResult = {
90
+ name: string
91
+ status: 'built' | 'skipped' | 'failed'
92
+ error?: string
93
+ serverModules?: string[]
94
+ config?: WidgetConfig | null
95
+ }
96
+
97
+ export async function buildAllWidgets(
98
+ workspacePath: string,
99
+ force = false
100
+ ): Promise<WidgetBuildResult[]> {
101
+ const t0 = performance.now()
102
+ const { buildDir } = getWidgetPaths(workspacePath)
103
+ const names = await scanWidgets(workspacePath)
104
+
105
+ await mkdir(buildDir, { recursive: true })
106
+ await pruneStaleBuilds(workspacePath, new Set(names))
107
+
108
+ const manifest = await readManifest(workspacePath)
109
+
110
+ const jobs = await Promise.all(
111
+ names.map(async name => {
112
+ const srcPath = await resolveWidgetSource(workspacePath, name)
113
+ if (!srcPath) {
114
+ return { name, status: 'failed' as const, error: 'Source file not found' }
115
+ }
116
+ if (!force && !(await needsRebuild(workspacePath, name, srcPath))) {
117
+ return { name, status: 'skipped' as const }
118
+ }
119
+ return { name, srcPath, status: 'pending' as const }
120
+ })
121
+ )
122
+
123
+ const buildResults = await Promise.all(
124
+ jobs.map(async (job): Promise<WidgetBuildResult> => {
125
+ if (job.status === 'failed') return { name: job.name, status: 'failed', error: job.error }
126
+ if (job.status === 'skipped') return { name: job.name, status: 'skipped' }
127
+
128
+ const { buildDir: bd } = getWidgetPaths(workspacePath)
129
+ try {
130
+ const artifact = await buildWidget(job.srcPath!)
131
+ await Bun.write(join(bd, `${job.name}.js`), artifact.js)
132
+ manifest[job.name] = artifact.config ?? DEFAULT_CONFIG
133
+ return {
134
+ name: job.name,
135
+ status: 'built',
136
+ serverModules: artifact.serverModules.map(m => m.name),
137
+ config: artifact.config
138
+ }
139
+ } catch (err) {
140
+ return {
141
+ name: job.name,
142
+ status: 'failed',
143
+ error: err instanceof Error ? err.message : 'Unknown error'
144
+ }
145
+ }
146
+ })
147
+ )
148
+
149
+ for (const key of Object.keys(manifest)) {
150
+ if (!names.includes(key)) delete manifest[key]
151
+ }
152
+
153
+ await writeManifest(workspacePath, manifest)
154
+
155
+ const builtCount = buildResults.filter(r => r.status === 'built').length
156
+ const failed = buildResults.filter(r => r.status === 'failed')
157
+ console.log(
158
+ `[bundle] ${builtCount}/${names.length} built in ${Math.round(performance.now() - t0)}ms` +
159
+ (failed.length ? `, ${failed.length} failed` : '') +
160
+ (force ? ' (forced)' : '')
161
+ )
162
+ for (const r of failed) {
163
+ console.error(`[bundle] ${r.name}:\n${r.error}`)
164
+ }
165
+
166
+ return buildResults
167
+ }
168
+
169
+ export async function listBuiltWidgets(workspacePath: string): Promise<string[]> {
170
+ const { buildDir } = getWidgetPaths(workspacePath)
171
+ try {
172
+ const entries = await readdir(buildDir)
173
+ return entries.filter(f => f.endsWith('.js')).map(f => f.replace(/\.js$/, ''))
174
+ } catch {
175
+ return []
176
+ }
177
+ }
178
+
179
+ async function getWidgetList(workspacePath: string): Promise<WidgetInfo[]> {
180
+ const [names, manifest] = await Promise.all([
181
+ listBuiltWidgets(workspacePath),
182
+ readManifest(workspacePath)
183
+ ])
184
+ return names.map(id => {
185
+ const raw = manifest[id] ?? {}
186
+ const rowSpan = VALID_SPANS.includes(raw.rowSpan) ? raw.rowSpan : DEFAULT_CONFIG.rowSpan
187
+ const colSpan = VALID_SPANS.includes(raw.colSpan) ? raw.colSpan : DEFAULT_CONFIG.colSpan
188
+ return { id, config: { rowSpan, colSpan } as WidgetConfig }
189
+ })
190
+ }
191
+
192
+ export async function listWidgets(workspacePath: string): Promise<Response> {
193
+ return Response.json({ widgets: await getWidgetList(workspacePath) })
194
+ }
195
+
196
+ export async function handleBundle(
197
+ publish: (msg: unknown) => void,
198
+ workspacePath: string,
199
+ force = false
200
+ ) {
201
+ const before = new Set(await listBuiltWidgets(workspacePath))
202
+ const manifestBefore = await readManifest(workspacePath)
203
+ const results = await buildAllWidgets(workspacePath, force)
204
+ const after = new Set(await listBuiltWidgets(workspacePath))
205
+
206
+ const configChanged = results.some(r => {
207
+ if (r.status !== 'built' || !r.config) return false
208
+ const old = manifestBefore[r.name]
209
+ return !old || old.rowSpan !== r.config.rowSpan || old.colSpan !== r.config.colSpan
210
+ })
211
+
212
+ const layoutChanged =
213
+ configChanged ||
214
+ before.size !== after.size ||
215
+ [...before].some(n => !after.has(n)) ||
216
+ [...after].some(n => !before.has(n))
217
+
218
+ const changedServerModules = new Set<string>()
219
+ for (const r of results) {
220
+ if (r.status === 'built') {
221
+ publish({ type: 'widget:updated', name: r.name, config: r.config ?? null })
222
+ for (const m of r.serverModules ?? []) changedServerModules.add(m)
223
+ }
224
+ }
225
+
226
+ if (changedServerModules.size > 0) {
227
+ reloadModules([...changedServerModules], workspacePath)
228
+ }
229
+
230
+ if (layoutChanged) {
231
+ const widgets = await getWidgetList(workspacePath)
232
+ publish({ type: 'widget-layout:updated', widgets })
233
+ }
234
+
235
+ return results
236
+ }
237
+
238
+ export async function serveWidget(name: string, workspacePath: string): Promise<Response> {
239
+ if (!/^[a-zA-Z0-9_-]+$/.test(name)) {
240
+ return new Response('Invalid widget name', { status: 400 })
241
+ }
242
+
243
+ const { buildDir } = getWidgetPaths(workspacePath)
244
+ const buildPath = join(buildDir, `${name}.js`)
245
+ const file = Bun.file(buildPath)
246
+
247
+ if (!(await file.exists())) {
248
+ return new Response(`Widget "${name}" not built. Run: moi bundle`, { status: 404 })
249
+ }
250
+
251
+ return new Response(file, {
252
+ headers: { 'Content-Type': 'application/javascript' }
253
+ })
254
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ESNext",
4
+ "module": "ESNext",
5
+ "moduleResolution": "bundler",
6
+ "jsx": "react-jsx",
7
+ "strict": true,
8
+ "esModuleInterop": true,
9
+ "skipLibCheck": true,
10
+ "forceConsistentCasingInFileNames": true,
11
+ "resolveJsonModule": true,
12
+ "isolatedModules": true,
13
+ "noEmit": true,
14
+ "baseUrl": ".",
15
+ "paths": {
16
+ "@/*": ["./*"]
17
+ }
18
+ },
19
+ "include": ["**/*.ts", "**/*.tsx"],
20
+ "exclude": ["node_modules"]
21
+ }