@a10k/iridium-dev-server 0.0.0-stage → 0.0.2

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.
package/lib/server.js ADDED
@@ -0,0 +1,295 @@
1
+ // The dev server: the Iridium editor at /<name>, notebook storage at /read,
2
+ // /save and /list, a searchable, paginated notebook list at /api/notebooks
3
+ // (DELETE /api/notebooks/<name> moves one to the Trash), live collaboration at /__live__/<name> (WebSocket), an MCP
4
+ // server at /mcp, and compiled modules plus static assets for embedding.
5
+ import { execFile, spawn } from 'node:child_process';
6
+ import { cpSync, existsSync, mkdirSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs';
7
+ import { createRequire } from 'node:module';
8
+ import { dirname, join, resolve } from 'node:path';
9
+ import Koa from 'koa';
10
+ import Router from '@koa/router';
11
+ import { bodyParser } from '@koa/bodyparser';
12
+ import cors from '@koa/cors';
13
+ import serve from 'koa-static';
14
+ import { WebSocketServer } from 'ws';
15
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
16
+ import { listNotebooks, notebookName, notebookPath, readNotebook, readNotebookMeta, writeNotebook } from './notebooks.js';
17
+ import { compileModule } from './define-module.js';
18
+ import { Relay } from './live.js';
19
+ import { createMcpServer } from './mcp.js';
20
+ import { viewerPage } from './viewer.js';
21
+
22
+ const require = createRequire(import.meta.url);
23
+ const IRIDIUM_PATH = '/__iridium__';
24
+ // A notebook's file attachments live in a folder named after it, next to its
25
+ // notebook file (<notebooks>/<name>/), and are served at /__files__/<name>/.
26
+ const FILES_PATH = '/__files__';
27
+ const iridiumPackage = require('@a10k/iridium/package.json');
28
+ const iridiumDist = join(dirname(require.resolve('@a10k/iridium/package.json')), 'dist');
29
+
30
+ const ownPackage = require('../package.json');
31
+ // The CDN copy matches the installed version of the npm package.
32
+ const IRIDIUM_CDN = `https://cdn.jsdelivr.net/npm/@a10k/iridium@${iridiumPackage.version}/dist`;
33
+
34
+ // The names of a notebook's file attachments (files in <notebooks>/<name>/).
35
+ const attachmentNames = (config, name) => {
36
+ const dir = join(config.notebooks, name);
37
+ if (!existsSync(dir) || !statSync(dir).isDirectory()) return [];
38
+ return readdirSync(dir).filter((file) => statSync(join(dir, file)).isFile());
39
+ };
40
+
41
+ export const compileNotebook = (config, name) => {
42
+ const path = notebookPath(config.notebooks, name);
43
+ if (!path) throw new Error(`No notebook named ${name}`);
44
+ // Attachments ship next to the module, in <compiled>/<name>/.
45
+ const files = attachmentNames(config, name);
46
+ const source = join(config.notebooks, name);
47
+ const target = join(config.compiled, name);
48
+ if (files.length && source !== target) {
49
+ rmSync(target, { recursive: true, force: true });
50
+ cpSync(source, target, { recursive: true });
51
+ }
52
+ const module = compileModule(readNotebook(path), { name: path, files: { folder: name, names: files } });
53
+ writeFileSync(join(config.compiled, `${name}.js`), module);
54
+ };
55
+
56
+ export const compileAll = (config) => {
57
+ for (const name of listNotebooks(config.notebooks)) {
58
+ try {
59
+ console.log('Compiling', name);
60
+ compileNotebook(config, name);
61
+ } catch (error) {
62
+ console.error('Error compiling', name, error);
63
+ }
64
+ }
65
+ };
66
+
67
+ // Opens a URL in the user's default browser, or in `browser` (an application
68
+ // name such as "Google Chrome", or IRIDIUM_BROWSER). IRIDIUM_OPEN_BROWSER=0
69
+ // disables this, e.g. when the assistant shows notebooks in its own browser.
70
+ export const openBrowser = (url, browser = process.env.IRIDIUM_BROWSER) => {
71
+ if (process.env.IRIDIUM_OPEN_BROWSER === '0') return;
72
+ const [command, ...args] =
73
+ process.platform === 'darwin' ? ['open', ...(browser ? ['-a', browser] : []), url]
74
+ : process.platform === 'win32' ? ['cmd', '/c', 'start', '', ...(browser ? [browser] : []), url]
75
+ : browser ? [browser, url] : ['xdg-open', url];
76
+ spawn(command, args, { stdio: 'ignore', detached: true }).on('error', () => {}).unref();
77
+ };
78
+
79
+ export const serverUrl = (config) =>
80
+ `http://${['0.0.0.0', '::'].includes(config.host) ? 'localhost' : config.host}:${config.port}`;
81
+
82
+ // Starts the server. `log` defaults to console.log (stdio MCP mode passes
83
+ // console.error, since stdout carries the protocol).
84
+ export const startServer = (config, { log = console.log } = {}) => {
85
+ const app = new Koa();
86
+ const router = new Router();
87
+ const live = new Relay();
88
+ // Writes a notebook's file: from a tab's Save, or a new empty notebook.
89
+ // Cells keep their original type (e.g. Markdown) while their code is unchanged.
90
+ const saveNotebook = (name, cells, meta = {}) => {
91
+ const path = notebookPath(config.notebooks, name);
92
+ const before = new Map((path ? readNotebook(path) : []).map((cell) => [cell.id, cell]));
93
+ const kept = cells.map((cell) => {
94
+ const previous = before.get(cell.id);
95
+ return previous?.mode && previous.sourceCode === cell.sourceCode ? { ...cell, mode: previous.mode } : cell;
96
+ });
97
+ writeNotebook(join(config.notebooks, `${name}.html`), kept, { title: name, ...readNotebookMeta(path), ...meta });
98
+ try {
99
+ compileNotebook(config, name);
100
+ } catch (error) {
101
+ console.error(`Error compiling ${name}:`, error.message);
102
+ }
103
+ };
104
+ const urlFor = (name) => `${serverUrl(config)}/${name}`;
105
+ const mcpOptions = {
106
+ live,
107
+ urlFor,
108
+ createNotebook: (name, title) => saveNotebook(name, [], { title }),
109
+ fileFor: (name) => { const path = notebookPath(config.notebooks, name); return path && resolve(path); },
110
+ openBrowser,
111
+ listNotebooks: () => listNotebooks(config.notebooks),
112
+ version: ownPackage.version,
113
+ };
114
+
115
+ // Requests that read or change notebooks must come from this machine and,
116
+ // from a browser, from this server's own pages: guards against other sites
117
+ // (CSRF) and DNS rebinding.
118
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', config.host]);
119
+ const trusted = (headers) => {
120
+ const host = String(headers.host ?? '').replace(/:\d+$/, '');
121
+ if (!LOCAL_HOSTS.has(host)) return false;
122
+ const origin = headers.origin;
123
+ return !origin || new URL(origin).host === headers.host;
124
+ };
125
+
126
+ // /read, /save and /list read and write files, so only accept them from
127
+ // this server's own pages: a JSON body, and no cross-site Origin.
128
+ const sameOrigin = async (ctx, next) => {
129
+ if (!trusted(ctx.headers)) ctx.throw(403, 'Cross-origin request');
130
+ if (!ctx.is('application/json')) ctx.throw(415, 'Expected JSON');
131
+ await next();
132
+ };
133
+
134
+ router.post('/list', sameOrigin, (ctx) => {
135
+ ctx.body = listNotebooks(config.notebooks);
136
+ });
137
+
138
+ // GET /api/notebooks?q=&page=1&per_page=25&sort=name|modified: notebooks
139
+ // whose name or title contains q (any case), one page at a time, as JSON:
140
+ // { q, sort, page, per_page, pages, total, items: [{ name, title, url, modified, cells, size }] }.
141
+ // The `index` notebook (the home page) isn't listed.
142
+ // Reading a title and cell count parses the file: keep them until it changes.
143
+ const summaries = new Map(); // path → { mtimeMs, title, cells }
144
+ const describeNotebook = (name) => {
145
+ const path = notebookPath(config.notebooks, name);
146
+ const { mtimeMs, mtime, size } = statSync(path);
147
+ let cached = summaries.get(path);
148
+ if (cached?.mtimeMs !== mtimeMs) {
149
+ cached = { mtimeMs, title: readNotebookMeta(path).title || name, cells: readNotebook(path).length };
150
+ summaries.set(path, cached);
151
+ }
152
+ return { name, title: cached.title, url: `/${name}`, modified: mtime.toISOString(), cells: cached.cells, size };
153
+ };
154
+ // Moves files to the Trash: the system's (macOS `trash`, restorable with Put
155
+ // Back), or else a .trash folder inside the notebooks folder.
156
+ const moveToTrash = async (paths) => {
157
+ if (process.platform === 'darwin' && existsSync('/usr/bin/trash')) {
158
+ await new Promise((done, fail) => execFile('/usr/bin/trash', paths, (error) => (error ? fail(error) : done())));
159
+ return 'the Trash';
160
+ }
161
+ const bin = join(config.notebooks, '.trash', new Date().toISOString().replace(/[:.]/g, '-'));
162
+ mkdirSync(bin, { recursive: true });
163
+ for (const path of paths) renameSync(path, join(bin, path.split(/[\\/]/).pop()));
164
+ return bin;
165
+ };
166
+
167
+ // DELETE /api/notebooks/<name>: moves the notebook file and its attachments
168
+ // folder to the Trash, and removes its compiled module (rebuilt on save).
169
+ router.delete('/api/notebooks/:name', async (ctx) => {
170
+ if (!trusted(ctx.headers)) ctx.throw(403, 'Cross-origin request');
171
+ const name = notebookName(ctx.params.name);
172
+ const path = notebookPath(config.notebooks, name);
173
+ if (!path) ctx.throw(404, `No notebook named ${name}`);
174
+ const attachments = join(config.notebooks, name);
175
+ const paths = [path, ...(existsSync(attachments) && statSync(attachments).isDirectory() ? [attachments] : [])];
176
+ const where = await moveToTrash(paths.map((p) => resolve(p)));
177
+ for (const compiled of [join(config.compiled, `${name}.js`), join(config.compiled, name)]) rmSync(compiled, { recursive: true, force: true });
178
+ summaries.delete(path);
179
+ ctx.body = { deleted: name, moved: paths.map((p) => resolve(p)), to: where };
180
+ });
181
+
182
+ router.get('/api/notebooks', (ctx) => {
183
+ if (!trusted(ctx.headers)) ctx.throw(403, 'Cross-origin request');
184
+ const q = String(ctx.query.q ?? '').trim().toLowerCase();
185
+ const sort = ctx.query.sort === 'modified' ? 'modified' : 'name';
186
+ const perPage = Math.min(200, Math.max(1, parseInt(ctx.query.per_page, 10) || 25));
187
+ const all = listNotebooks(config.notebooks)
188
+ .filter((name) => name !== 'index')
189
+ .map(describeNotebook)
190
+ .filter((item) => !q || item.name.toLowerCase().includes(q) || item.title.toLowerCase().includes(q))
191
+ .sort(sort === 'modified'
192
+ ? (a, b) => b.modified.localeCompare(a.modified)
193
+ : (a, b) => a.title.localeCompare(b.title, undefined, { sensitivity: 'base' }));
194
+ const pages = Math.max(1, Math.ceil(all.length / perPage));
195
+ const page = Math.min(pages, Math.max(1, parseInt(ctx.query.page, 10) || 1));
196
+ ctx.body = { q, sort, page, per_page: perPage, pages, total: all.length, items: all.slice((page - 1) * perPage, page * perPage) };
197
+ });
198
+
199
+ router.post('/read', sameOrigin, (ctx) => {
200
+ const path = notebookPath(config.notebooks, notebookName(ctx.request.body?.path));
201
+ ctx.body = path ? readNotebook(path).map(({ id, pin, sourceCode }) => ({ id, pin, sourceCode })) : []; // [] for a new notebook
202
+ });
203
+
204
+ router.post('/save', sameOrigin, (ctx) => {
205
+ const name = notebookName(ctx.request.body?.path);
206
+ const cells = ctx.request.body?.content;
207
+ if (!Array.isArray(cells)) ctx.throw(400, 'Expected content: an array of cells');
208
+ saveNotebook(name, cells);
209
+ ctx.body = {};
210
+ });
211
+
212
+ // MCP over Streamable HTTP (stateless: one server per request).
213
+ router.all('/mcp', async (ctx) => {
214
+ if (!trusted(ctx.headers)) ctx.throw(403, 'Cross-origin request');
215
+ const server = createMcpServer(mcpOptions);
216
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
217
+ ctx.respond = false;
218
+ ctx.res.on('close', () => {
219
+ transport.close();
220
+ server.close();
221
+ });
222
+ await server.connect(transport);
223
+ await transport.handleRequest(ctx.req, ctx.res, ctx.request.body);
224
+ });
225
+
226
+ // Serve the editor page for any URL that isn't a file, API route or asset.
227
+ app.use(async (ctx, next) => {
228
+ // A notebook's own .html file opens in the editor rather than as a page.
229
+ const asNotebook = ctx.path.match(/^\/([^/]+)\.html$/);
230
+ if (asNotebook && notebookPath(config.notebooks, asNotebook[1])?.endsWith('.html')) {
231
+ ctx.redirect(`/${notebookName(asNotebook[1])}`);
232
+ return;
233
+ }
234
+ if (ctx.path !== '/') await next();
235
+ // Missing attachments and editor files are real 404s, not editor pages.
236
+ const reserved =
237
+ ctx.path === '/mcp' || ctx.path.startsWith(`${FILES_PATH}/`) || ctx.path.startsWith(`${IRIDIUM_PATH}/`);
238
+ if (ctx.method === 'GET' && !reserved && (ctx.path === '/' || ctx.status === 404)) {
239
+ ctx.status = 200;
240
+ ctx.type = 'html';
241
+ const name = notebookName(ctx.path);
242
+ ctx.body = viewerPage({
243
+ name,
244
+ iridiumBase: config.localEditor ? IRIDIUM_PATH : IRIDIUM_CDN,
245
+ filesBase: `${FILES_PATH}/${name}/`,
246
+ head: config.head,
247
+ });
248
+ }
249
+ });
250
+
251
+ app.use(bodyParser({ enableTypes: ['json'], jsonLimit: '10mb' }));
252
+ app.use(router.routes()).use(router.allowedMethods());
253
+
254
+ // Compiled modules and assets may be imported from other origins (embeds).
255
+ app.use(cors({ allowMethods: 'GET,HEAD' }));
256
+
257
+ if (config.localEditor) {
258
+ const editor = serve(iridiumDist, { maxage: 0 });
259
+ app.use(async (ctx, next) => {
260
+ if (!ctx.path.startsWith(`${IRIDIUM_PATH}/`)) return next();
261
+ ctx.path = ctx.path.slice(IRIDIUM_PATH.length);
262
+ await editor(ctx, next);
263
+ });
264
+ }
265
+
266
+ // File attachments: /__files__/<name>/<file> from <notebooks>/<name>/<file>.
267
+ const files = serve(config.notebooks, { maxage: 0 });
268
+ app.use(async (ctx, next) => {
269
+ const match = ctx.path.match(/^\/__files__\/([^/]+)\/(.+)$/);
270
+ if (!match) return next();
271
+ if (match[1] !== notebookName(match[1]) || match[2].includes('..')) ctx.throw(404);
272
+ ctx.path = `/${match[1]}/${match[2]}`;
273
+ await files(ctx, next);
274
+ });
275
+
276
+ app.use(serve(config.compiled, { maxage: 0 }));
277
+ if (config.static && existsSync(config.static)) app.use(serve(config.static, { maxage: 0 }));
278
+
279
+ const server = app.listen(config.port, config.host, () => {
280
+ log(`\nIridium ${iridiumPackage.version} dev server`);
281
+ log(serverUrl(config));
282
+ log(`MCP: ${serverUrl(config)}/mcp`);
283
+ });
284
+
285
+ // Live collaboration: each editor tab connects to /__live__/<name>.
286
+ const sockets = new WebSocketServer({ noServer: true });
287
+ server.on('upgrade', (request, socket, head) => {
288
+ const match = request.url?.match(/^\/__live__\/([^/?#]+)/);
289
+ if (!match || !trusted(request.headers)) return socket.destroy();
290
+ const name = notebookName(decodeURIComponent(match[1]));
291
+ sockets.handleUpgrade(request, socket, head, (ws) => live.connect(name, ws));
292
+ });
293
+
294
+ return { server, live, mcpOptions };
295
+ };
package/lib/viewer.js ADDED
@@ -0,0 +1,210 @@
1
+ // The editor page: Iridium, wired to this server's /read and /save.
2
+ const json = (value) => JSON.stringify(value).replace(/</g, '\\u003c');
3
+
4
+ export const viewerPage = ({ name, iridiumBase, filesBase, head }) => `<!DOCTYPE html>
5
+ <html lang="en">
6
+ <head>
7
+ <meta charset="utf-8" />
8
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
9
+ <!-- FileAttachment("x") resolves against the base URL: the notebook's files folder. -->
10
+ <base href="${filesBase}" />
11
+ <!-- The tab's connection to the server: macOS-style green dot when connected, grey otherwise. -->
12
+ <link rel="icon" id="iridium-status" href="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3E%3Ccircle cx='8' cy='8' r='6.5' fill='%23c8c8c8' stroke='%23a6a6a6'/%3E%3C/svg%3E" />
13
+ <title>${name.replace(/[<&]/g, '')} · Iridium</title>
14
+ <script type="module" src="${iridiumBase}/iridium.js"></script>
15
+ ${head}
16
+ </head>
17
+ <body data-hint-view-only="IridiumViewOnly">
18
+ <style>
19
+ html { font-family: Verdana, Geneva, Tahoma, sans-serif; } /* as Iridium's own page */
20
+ </style>
21
+ <div id="iridium-root-wrapper">
22
+ <div id="iridium-root"></div>
23
+ </div>
24
+ <!-- type="module": runs after iridium.js (also a module), in document order. -->
25
+ <script type="module">
26
+ const name = ${json(name)};
27
+ const post = async (url, body) => {
28
+ const response = await fetch(url, {
29
+ method: 'POST',
30
+ headers: { 'Content-Type': 'application/json' },
31
+ body: JSON.stringify(body),
32
+ });
33
+ if (!response.ok) throw new Error(\`\${url}: \${response.status} \${await response.text()}\`);
34
+ return response.json();
35
+ };
36
+
37
+ // This page edits one notebook, named by the URL.
38
+ Iridium.get_recent = () => name;
39
+ Iridium.set_recent = () => {};
40
+ Iridium.list = () => post('/list', {});
41
+ Iridium.load = () => post('/read', { path: name });
42
+
43
+ // Assistants work on this tab through the server, a relay: it sends
44
+ // commands (add, edit, run or delete cells, save, read outputs,
45
+ // evaluate) and this tab carries them out on its own notebook, as if
46
+ // the user had. Nothing else is synced, and the file is only written by
47
+ // this tab's Save.
48
+ let lastSave = null;
49
+ Iridium.save = (_, cells) => (lastSave = post('/save', { path: name, content: cells }));
50
+
51
+ // Screenshots of cells, for assistants: Chrome's own tab capture
52
+ // (getDisplayMedia on this tab), cropped to each cell. Chrome only starts
53
+ // a capture from a click, so the first request shows a bar asking the
54
+ // user to allow it; the capture then stays on until they stop sharing.
55
+ let captureTrack = null;
56
+ let asking = null;
57
+ const askToCapture = () => asking ??= new Promise((resolve, reject) => {
58
+ const bar = document.createElement('div');
59
+ bar.style.cssText = 'position:fixed;top:10px;left:50%;transform:translateX(-50%);z-index:1000;display:flex;gap:8px;align-items:center;padding:8px 10px 8px 14px;border-radius:12px;background:#fff;box-shadow:0 0 0 .5px rgba(0,0,0,.12),0 6px 24px rgba(0,0,0,.18);font:13px -apple-system,BlinkMacSystemFont,system-ui,sans-serif;color:#1d1d1f';
60
+ bar.innerHTML = '<span>Claude wants to see cells of this notebook.</span>'
61
+ + '<button data-allow style="font:inherit;padding:4px 12px;border:0;border-radius:8px;background:#0071e3;color:#fff;cursor:pointer">Allow tab capture</button>'
62
+ + '<button data-deny style="font:inherit;padding:4px 10px;border:0;border-radius:8px;background:rgba(0,0,0,.06);cursor:pointer">Not now</button>';
63
+ document.body.append(bar);
64
+ const finish = (fn, value) => (bar.remove(), asking = null, fn(value));
65
+ bar.querySelector('[data-allow]').onclick = async () => {
66
+ try {
67
+ const stream = await navigator.mediaDevices.getDisplayMedia({
68
+ video: { displaySurface: 'browser' }, audio: false,
69
+ preferCurrentTab: true, selfBrowserSurface: 'include', surfaceSwitching: 'exclude',
70
+ });
71
+ const [track] = stream.getVideoTracks();
72
+ track.addEventListener('ended', () => { if (captureTrack === track) captureTrack = null; });
73
+ finish(resolve, track);
74
+ } catch (error) {
75
+ finish(reject, new Error('Tab capture was not allowed (' + error.message + ').'));
76
+ }
77
+ };
78
+ bar.querySelector('[data-deny]').onclick = () => finish(reject, new Error('The user declined tab capture.'));
79
+ });
80
+ const settle = () => new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(() => setTimeout(resolve, 150))));
81
+ // Captures element el, scrolling it through the window in slices when it
82
+ // is taller than the window; scale = output pixels per CSS pixel.
83
+ const captureElement = async (track, el, scale) => {
84
+ const box = el.getBoundingClientRect();
85
+ const top = box.top + scrollY, width = box.width, height = Math.min(box.height, 6000);
86
+ const start = [scrollX, scrollY];
87
+ const canvas = document.createElement('canvas');
88
+ canvas.width = Math.round(width * scale);
89
+ canvas.height = Math.round(height * scale);
90
+ const context = canvas.getContext('2d');
91
+ try {
92
+ for (let y = 0; y < height;) {
93
+ scrollTo(start[0], top + y);
94
+ await settle();
95
+ const frame = await new ImageCapture(track).grabFrame();
96
+ const ratio = frame.width / innerWidth; // frame pixels per CSS pixel
97
+ const offset = top + y - scrollY; // where this slice starts in the window
98
+ const left = el.getBoundingClientRect().left;
99
+ const slice = Math.min(height - y, innerHeight - offset);
100
+ if (slice <= 0) break;
101
+ context.drawImage(frame, left * ratio, offset * ratio, width * ratio, slice * ratio, 0, y * scale, width * scale, slice * scale);
102
+ frame.close();
103
+ y += slice;
104
+ }
105
+ } finally {
106
+ scrollTo(...start);
107
+ }
108
+ return { width: Math.round(width), height: Math.round(height), png: canvas.toDataURL('image/png').split(',')[1] };
109
+ };
110
+
111
+ Iridium.ready = (main, controller) => {
112
+ window.IridiumMain = main;
113
+ window.IridiumController = controller;
114
+ // Favicon dot: green (as macOS's traffic light) while connected, so
115
+ // assistants can work on this tab; grey while offline.
116
+ const dot = (fill, stroke) =>
117
+ 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><circle cx="8" cy="8" r="6.5" fill="' + fill + '" stroke="' + stroke + '"/></svg>');
118
+ const icon = document.getElementById('iridium-status');
119
+ const setStatus = (connected) => (icon.href = connected ? dot('#28c840', '#1aab29') : dot('#c8c8c8', '#a6a6a6'));
120
+ let socket;
121
+ const send = (message) => socket?.readyState === 1 && socket.send(JSON.stringify(message));
122
+ const unsaved = () => !!document.querySelector('.IridiumNotebookUnsaved');
123
+ // Where a new or moved cell goes: after/before a cell, at an index, or the end.
124
+ const position = ({ after, before, index }, cells = controller.cells()) => {
125
+ const at = (id) => {
126
+ const i = cells.findIndex((cell) => cell.id === id);
127
+ if (i < 0) throw new Error(\`No cell with id \${id}\`);
128
+ return i;
129
+ };
130
+ if (after !== undefined) return at(after) + 1;
131
+ if (before !== undefined) return at(before);
132
+ return index ?? cells.length;
133
+ };
134
+ const methods = {
135
+ cells: () => ({ cells: controller.cells(), unsaved: unsaved() }),
136
+ describe: ({ ids }) => ({ cells: controller.describe(ids), unsaved: unsaved() }),
137
+ insert: ({ cells, ...where }) => {
138
+ let index = position(where);
139
+ return { ids: cells.map(({ source, pinned = true }) => controller.insert({ sourceCode: source, pin: pinned }, index++)) };
140
+ },
141
+ update: ({ id, sourceCode, pin }) => (controller.update(id, { sourceCode, pin }), {}),
142
+ run: ({ id }) => (controller.run(id), {}),
143
+ remove: ({ id }) => (controller.remove(id), {}),
144
+ move: ({ id, ...where }) => {
145
+ const rest = controller.cells().filter((cell) => cell.id !== id);
146
+ controller.move(id, position(where, rest));
147
+ return { order: controller.cells().map((cell) => cell.id) };
148
+ },
149
+ // Saves exactly as Cmd+S in this tab does.
150
+ save: async () => {
151
+ lastSave = null;
152
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 's', metaKey: true, ctrlKey: true, bubbles: true }));
153
+ if (!lastSave) throw new Error('The tab did not save.');
154
+ await lastSave;
155
+ await new Promise((resolve) => setTimeout(resolve, 50)); // let the saved state render
156
+ return { saved: true, unsaved: unsaved() };
157
+ },
158
+ // PNGs of cells' outputs (or whole cells with includeCode), as shown here.
159
+ screenshot: async ({ ids, includeCode = false, scale = 1 }) => {
160
+ if (!navigator.mediaDevices?.getDisplayMedia || typeof ImageCapture === 'undefined') throw new Error('This browser has no tab capture; use Chrome.');
161
+ if (!captureTrack || captureTrack.readyState !== 'live') captureTrack = await askToCapture();
162
+ const order = controller.cells().map((cell) => cell.id);
163
+ const elements = [...document.querySelectorAll('.IridiumNotebook > .IridiumCell')];
164
+ const shots = [];
165
+ for (const id of ids) {
166
+ const cell = elements[order.indexOf(id)];
167
+ if (!cell) { shots.push({ id, error: 'No cell with id ' + id }); continue; }
168
+ const error = cell.querySelector('.CellError');
169
+ const target = includeCode ? cell : error && error.style.display !== 'none' ? error : cell.querySelector('.CellResults');
170
+ if (!target.getBoundingClientRect().height) { shots.push({ id, error: 'The cell has no visible output.' }); continue; }
171
+ shots.push({ id, ...(await captureElement(captureTrack, target, scale)) });
172
+ }
173
+ return { shots };
174
+ },
175
+ evaluate: ({ source, timeout }) => controller.evaluate(source, { timeout }),
176
+ };
177
+ const active = () => document.visibilityState === 'visible' && send({ type: 'active' });
178
+ addEventListener('focus', active);
179
+ document.addEventListener('visibilitychange', active);
180
+ const connect = () => {
181
+ socket = new WebSocket(\`\${location.protocol === 'https:' ? 'wss' : 'ws'}://\${location.host}/__live__/\${encodeURIComponent(name)}\`);
182
+ socket.onopen = () => {
183
+ setStatus(true);
184
+ active();
185
+ };
186
+ socket.onclose = () => {
187
+ setStatus(false);
188
+ setTimeout(connect, 1000);
189
+ };
190
+ socket.onmessage = async ({ data }) => {
191
+ const message = JSON.parse(data);
192
+ if (message.type !== 'request') return;
193
+ try {
194
+ const result = await methods[message.method](message.params ?? {});
195
+ send({ type: 'response', id: message.id, result });
196
+ } catch (error) {
197
+ send({ type: 'response', id: message.id, error: String(error?.message ?? error) });
198
+ }
199
+ };
200
+ };
201
+ connect();
202
+ };
203
+
204
+ Iridium.render(
205
+ Iridium.html\`<\${Iridium.IridiumApp} Ir=\${Iridium} />\`,
206
+ document.getElementById('iridium-root'),
207
+ );
208
+ </script>
209
+ </body>
210
+ </html>`;
package/package.json CHANGED
@@ -1,6 +1,46 @@
1
1
  {
2
2
  "name": "@a10k/iridium-dev-server",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "Local dev server for working with Observable notebooks.",
5
+ "main": "index.js",
6
+ "bin": {
7
+ "iridium-dev-server": "index.js"
8
+ },
9
+ "scripts": {
10
+ "start": "node index.js",
11
+ "build": "node index.js -build"
12
+ },
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/wishyoulization/iridium-dev-server.git"
16
+ },
17
+ "keywords": [
18
+ "notebook"
19
+ ],
20
+ "author": "a10k",
21
+ "license": "MIT",
22
+ "type": "module",
23
+ "engines": {
24
+ "node": ">=22"
25
+ },
26
+ "dependencies": {
27
+ "@a10k/iridium": "~0.0.2",
28
+ "@koa/bodyparser": "^6.1.0",
29
+ "@koa/cors": "^5.0.0",
30
+ "@koa/router": "^15.7.1",
31
+ "@modelcontextprotocol/sdk": "^1.32.2",
32
+ "@observablehq/notebook-kit": "^2.11.0",
33
+ "@observablehq/parser": "^6.1.0",
34
+ "acorn": "^8.19.0",
35
+ "jsdom": "^31.0.1",
36
+ "koa": "^3.3.0",
37
+ "koa-static": "^5.0.0",
38
+ "ws": "^8.23.0",
39
+ "zod": "^4.6.7"
40
+ },
41
+ "files": [
42
+ "index.js",
43
+ "lib",
44
+ "skill"
45
+ ]
46
+ }
package/skill/SKILL.md ADDED
@@ -0,0 +1,92 @@
1
+ ---
2
+ name: iridium-notebooks
3
+ description: Build, edit and explore live Iridium notebooks (reactive Observable notebooks) together with the user, through the iridium MCP server. Use whenever the user asks for an Iridium notebook, an Observable notebook, an interactive notebook, or a chart, dashboard, prototype or data exploration they want to watch being built and edit themselves.
4
+ ---
5
+
6
+ # Iridium notebooks
7
+
8
+ Iridium notebooks run in the user's browser and update live: every cell you add or edit through the `iridium` MCP tools appears in the user's tab as you make it, and every edit the user makes there is visible to you. Cells are reactive: when a cell changes, every cell that uses its value re-runs.
9
+
10
+ If the `iridium` tools (`create_notebook`, `add_cell`, …) aren't available, tell the user the iridium MCP server isn't connected (`claude mcp list`) instead of writing notebook files by hand.
11
+
12
+ ## Workflow
13
+
14
+ 1. **Start**: `create_notebook` with a short kebab-case `name`, a `title`, and the first cells (a `md` heading and intro, then the data). It opens the notebook in the user's default browser. For an existing notebook use `list_notebooks` and `open_notebook`.
15
+ - If the user names a browser ("on my Chrome"), pass `browser` (e.g. `"Google Chrome"`, `"Safari"`, `"Firefox"`): no browser extension or shell command needed.
16
+ - In an app with a built-in browser (e.g. the Claude desktop app), unless the user asked for another browser, pass `open: false` and open the returned `url` in that browser so the notebook sits next to the chat.
17
+ 2. **Build incrementally**: `add_cell` / `add_cells`, a few cells at a time, small and focused: load data, shape it, chart it, add controls. Each call returns the cells' live output once they have run.
18
+ 3. **Check every result**: read `status`, `value`, `text` and `error`, and `other_failing_cells`. Fix errors before moving on; never leave the notebook broken.
19
+ - To check how a chart, layout or styling *looks*, call `screenshot_cells` (by `cells` names or `ids`). It returns PNGs of the cells exactly as the user's tab shows them. Use it instead of driving a browser or taking screen screenshots. The first call in a tab asks the user to allow tab capture (a bar in the tab, then Chrome's share dialog), so say so when you make it. Use `evaluate` to inspect values (`data.length`, `Object.keys(data[0])`, `data.slice(0, 3)`) without adding cells.
20
+ 4. **Edit, don't append duplicates**: change a cell with `edit_cell`; remove one with `delete_cell`. Address cells by `id` or by the name they define (`cell: "data"`). A name may be defined by only one cell.
21
+ - For a small change to a long cell, patch it: `edit_cell` with `replace: [{old, new}]` (each `old` must appear exactly once). Don't resend the whole cell to add a line.
22
+ 5. **Finish**: unpin cells whose code the reader needn't see (`edit_cell` with `pinned: false`, e.g. prose and finished charts), and tell the user what the notebook does and how to use it.
23
+
24
+ ## Saving
25
+
26
+ You work on the notebook in the user's open tab, exactly as they would. Your edits are unsaved until saved, like theirs: results report `unsaved_changes`, and the tab shows it.
27
+ - Call `save_notebook` (the tab's own Save) only when the user asks you to save.
28
+ - When you finish with unsaved changes, say so briefly.
29
+ - Every tool except `list_notebooks` and `create_notebook` needs the notebook open in a tab. If one isn't, call `open_notebook`.
30
+
31
+ ## Working efficiently
32
+
33
+ - `read_notebook` with `brief: true` lists every cell in one line (id, name, status, first line of code). Use it to find cells; read full code only for the cells you'll change (`ids: [...]`).
34
+ - Edit results don't echo your code back. They return status, value and errors only.
35
+ - Notebooks that hold records the user adds to over time (a log, a tracker) work best with data in small data-only cells (e.g. one per week or month) and all calculations and views in separate cells. Then each update is one `replace` patch to one small cell.
36
+
37
+ ## Collaborating
38
+
39
+ - The user may be editing at the same time. Call `read_notebook` before editing cells you didn't just write, and don't overwrite or delete their cells without asking.
40
+ - Say briefly what you are changing ("adding a chart of sales by month") so the user can follow along in the tab.
41
+ - Outputs exist only in the browser. If a tool says no tab is showing the notebook, call `open_notebook`.
42
+
43
+ ## Writing cells
44
+
45
+ Cells are **Observable JavaScript** (classic Observable notebooks):
46
+
47
+ ```js
48
+ md`# Sales explorer
49
+ Data from *Q3*, updated daily.` // Markdown (also html`…`, svg`…`, tex`…`)
50
+
51
+ data = FileAttachment("sales.csv").csv({typed: true}) // a named cell; promises resolve automatically
52
+ total = d3.sum(data, d => d.amount)
53
+
54
+ viewof region = Inputs.select(["All", ...new Set(data.map(d => d.region))], {label: "Region"})
55
+ filtered = region === "All" ? data : data.filter(d => d.region === region)
56
+
57
+ Plot.plot({ // a chart; `width` keeps it responsive
58
+ width,
59
+ marks: [Plot.barY(filtered, {x: "month", y: "amount", fill: "region"}), Plot.ruleY([0])]
60
+ })
61
+
62
+ summary = { // a block: statements, then return
63
+ const byRegion = d3.rollup(filtered, v => d3.sum(v, d => d.amount), d => d.region);
64
+ return Array.from(byRegion, ([region, amount]) => ({region, amount}));
65
+ }
66
+
67
+ clock = { while (true) { yield new Date().toLocaleTimeString(); await Promises.delay(1000); } } // generators update live
68
+ mutable count = 0 // set elsewhere with `mutable count++`
69
+ import {Legend} from "@d3/color-legend" // reuse cells from notebooks on observablehq.com
70
+ ```
71
+
72
+ Rules: one cell per name; cells can reference each other in any order; a cell is an expression, `name = expression`, or a `{ … return … }` block. Use `viewof name = Inputs.*(…)` for controls (the cell's value is the input's value). `this` is the cell's previous value.
73
+
74
+ **Plain JavaScript cells** also work (as in Observable Notebooks 2.0): several statements, top-level `const`/`let`/`function` shared with other cells, `import {x} from "npm:package"`, and `display(value)` to show output.
75
+
76
+ ```js
77
+ import {csvParse} from "npm:d3-dsv";
78
+ const rows = csvParse(await (await fetch(url)).text());
79
+ display(Inputs.table(rows));
80
+ ```
81
+
82
+ **Pick one mode per notebook and never mix them.** A notebook is either all Observable JavaScript (`name = expr`, `viewof`, `mutable`, `md\`…\``) or all plain JavaScript (`const`, `display()`, `npm:` imports). Before adding cells to an existing notebook, read it and match the mode its cells already use. Mixing modes breaks when the notebook is copied to observablehq.com: a cell created in the other mode fails (e.g. `SyntaxError: Assignment to external variable 'x'` when a `name = …` cell lands in plain-JavaScript mode), and on Observable each such cell's mode then has to be fixed by hand.
83
+
84
+ **Built-ins**: `d3`, `Plot`, `Inputs` (range, select, radio, checkbox, text, table, search, button, toggle, date, color, file), `htl`, `_` (lodash), `md`, `html`, `svg`, `tex`, `dot`, `mermaid`, `DuckDBClient` (SQL: `db = DuckDBClient.of({sales: data})`, then `db.sql\`SELECT …\``), `FileAttachment`, `width`, `now`, `invalidation`, `Generators`, `Promises`, `DOM`, `require` (AMD libraries), sample datasets (`penguins`, `cars`, `aapl`, …). Other libraries: `import("npm:package")` / `import {x} from "npm:package"` in plain JavaScript cells, or `require("package@version")`.
85
+
86
+ ## Good notebooks
87
+
88
+ - Lead with a `md` title and a sentence on what the notebook shows; explain each section briefly.
89
+ - Prefer Plot for charts and Inputs for controls; label axes and units; use `width` for chart widths.
90
+ - Load data once in its own cell; derive views in separate cells so they react to controls.
91
+ - Keep cells short and named descriptively.
92
+ - Files the notebook reads with `FileAttachment("name")` live in a folder named after the notebook next to its `.html` file in the notebooks folder.
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.