包文件→ .shtukbase/packages/layout-studio/test/fake-host.ts
test/fake-host.ts
119 行, 6.5 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // A fake host for layout-studio: serves contract §5 with an in-memory /_api.
- // bun apps/standard/packages/layout-studio/test/fake-host.ts [port] (CACHE=long: long cache for /_pkg and /_kit)
- import { existsSync } from 'node:fs';
- import { join, resolve } from 'node:path';
- const here = import.meta.dir;
- const pkg = resolve(here, '..');
- const packages = resolve(pkg, '..');
- const kit = join(packages, 'kit-style/pages/design/kit-style');
- const recordsPkg = join(packages, 'lenses-records');
- const basicPkg = join(packages, 'layout-basic');
- const longCache = process.env.CACHE === 'long';
- const useRealLenses = existsSync(join(recordsPkg, 'lens/table.html'));
- type Rec = { meta: Record<string, unknown>; body: string };
- const files = new Map<string, Rec>();
- files.set('/index.md', { meta: { type: 'Page', title: 'Главная', icon: '🏠' }, body: 'Добро пожаловать.' });
- files.set('/notes.md', { meta: { type: 'Page', title: 'Заметки', icon: '📝' }, body: 'Заметки.' });
- files.set('/notes/ideas.md', { meta: { type: 'Page', title: 'Идеи', icon: '💡' }, body: 'Идеи.' });
- files.set('/leads.md', {
- meta: {
- type: 'Collection', title: 'Заявки', icon: '📥', items: { mode: 'path', path: '/leads' }, writeTo: '/leads',
- properties: {
- status: { kind: 'select', label: 'Статус', options: [
- { name: 'new', label: 'Новая', color: 'blue' }, { name: 'talk', label: 'В работе', color: 'orange' },
- { name: 'won', label: 'Сделка', color: 'green' }, { name: 'lost', label: 'Отказ', color: 'gray' }] },
- source: { kind: 'select', label: 'Источник', options: [
- { name: 'site', label: 'Сайт', color: 'purple' }, { name: 'call', label: 'Звонок', color: 'teal' }] },
- amount: { kind: 'number', label: 'Сумма' },
- },
- },
- body: '',
- });
- const names = ['Acme', 'Ромашка', 'Север', 'Луч', 'Вектор', 'Орбита', 'Гранит', 'Прибой'];
- const statuses = ['new', 'talk', 'won', 'lost'];
- names.forEach((n, i) => files.set(`/leads/lead-${i + 1}.md`, {
- meta: { title: n, status: statuses[i % 4], source: i % 2 ? 'call' : 'site', amount: (i + 1) * 1000 },
- body: `Заявка от ${n}.`,
- }));
- const lenses = useRealLenses
- ? [
- { id: 'table', package: 'lenses-records', file: 'lens/table.html', title: 'Таблица', for: 'Collection' },
- { id: 'board', package: 'lenses-records', file: 'lens/board.html', title: 'Доска', for: 'Collection' },
- { id: 'record', package: 'lenses-records', file: 'lens/record.html', title: 'Запись', for: 'Record' },
- { id: 'props', package: 'studio-demo', file: 'props.html', title: 'Свойства', for: 'Record', slot: 'panel' },
- ]
- : [
- { id: 'table', package: 'demo', file: 'table.html', title: 'Таблица', for: 'Collection' },
- { id: 'board', package: 'demo', file: 'board.html', title: 'Доска', for: 'Collection' },
- { id: 'record', package: 'demo', file: 'record.html', title: 'Запись', for: 'Record' },
- { id: 'props', package: 'studio-demo', file: 'props.html', title: 'Свойства', for: 'Record', slot: 'panel' },
- ];
- function title(path: string, r: Rec) { return String(r.meta.title ?? path.split('/').pop()!.replace(/\.md$/, '')); }
- const api: Record<string, (p: any) => unknown> = {
- 'space.info': () => ({ name: 'Демо-пространство', layout: { package: 'layout-studio', file: 'shell.html' }, lenses,
- contributions: [
- ...lenses.map((l) => ({ package: l.package, lens: l.id, file: l.file, title: l.title, for: l.for, slot: l.slot ?? 'main' })),
- { package: 'studio-demo', lens: 'outline', file: 'props.html', title: 'Структура', slot: 'panel' },
- ] }),
- tree: () => [...files.keys()].sort().map((path) => {
- const r = files.get(path)!;
- return { path, type: String(r.meta.type ?? 'Record'), title: title(path, r), icon: r.meta.icon ?? null };
- }),
- 'records.list': ({ collection }) => {
- const c = files.get(collection);
- if (!c) throw new Error('no collection ' + collection);
- const dir = collection.replace(/\.md$/, '/');
- return {
- collection: { path: collection, title: title(collection, c), icon: c.meta.icon, properties: c.meta.properties },
- items: [...files.keys()].sort().filter((p) => p.startsWith(dir)).map((p) => ({ path: p, meta: files.get(p)!.meta, title: title(p, files.get(p)!) })),
- };
- },
- 'records.read': ({ path }) => {
- const r = files.get(path);
- if (!r) throw new Error('not found ' + path);
- return { path, meta: r.meta, body: r.body };
- },
- 'records.write': ({ path, meta, body }) => {
- const r = files.get(path) ?? { meta: {}, body: '' };
- files.set(path, { meta: { ...r.meta, ...(meta ?? {}) }, body: body ?? r.body });
- return { path };
- },
- };
- function file(path: string, cache = false) {
- if (!existsSync(path)) return new Response('not found', { status: 404 });
- const cc = cache && longCache ? 'public, max-age=31536000, immutable' : 'no-cache';
- return new Response(Bun.file(path), { headers: { 'cache-control': cc } });
- }
- const port = Number(process.argv[2] ?? 4321);
- Bun.serve({
- port,
- async fetch(req) {
- const url = new URL(req.url);
- const p = decodeURIComponent(url.pathname);
- if (process.env.LOG) console.log(req.method, url.pathname + url.search, req.headers.get("sec-fetch-site") ?? "");
- if (p.includes('..')) return new Response('bad', { status: 400 });
- if (p === '/') return file(join(pkg, 'shell.html'));
- if (p === '/_api' && req.method === 'POST') {
- const { do: action, ...params } = await req.json();
- const fn = api[action];
- if (!fn) return Response.json({ error: 'unknown action ' + action });
- await Bun.sleep(5);
- try { return Response.json({ result: fn(params) }); } catch (e) { return Response.json({ error: String((e as Error).message) }); }
- }
- if (p.startsWith('/_kit/')) return file(join(kit, p.slice(6)), true);
- if (p.startsWith('/_pkg/layout-studio/')) return file(join(pkg, p.slice(20)), true);
- if (p.startsWith('/_pkg/layout-basic/')) return file(join(basicPkg, p.slice(19)), true);
- if (p.startsWith('/_pkg/lenses-records/')) return file(join(recordsPkg, p.slice(21)), true);
- if (p.startsWith('/_pkg/studio-demo/')) return file(join(here, 'props-lens.html'), true);
- if (p.startsWith('/_pkg/demo/')) return file(join(basicPkg, 'test/demo-lens.html'), true);
- return new Response('not found', { status: 404 });
- },
- });
- console.log(`fake host: http://127.0.0.1:${port}/ (lenses: ${useRealLenses ? 'lenses-records' : 'demo'})`);