package file→ .shtukbase/packages/chat/test/host.ts
test/host.ts
60 lines, 4.0 KB.
The file as it is in the package. Some comments in it may not be in English yet.
- // A wrapper host for trying the chat lens inside layout-basic's shell (contract §5), modelled
- // on layout-basic/test/fake-host.ts. The shell has no panel slot yet, so the chat is offered
- // as a lens for pages and collections. space.tools comes from apps/shtuk/src/core/tools.ts.
- // bun apps/standard/packages/chat/test/host.ts [port]
- import { existsSync } from 'node:fs';
- import { join, resolve } from 'node:path';
- import { toolAction, tools } from '../../../../shtuk/src/core/tools.ts';
- const packages = resolve(import.meta.dir, '../..');
- const kit = join(packages, 'kit-style/pages/design/kit-style');
- 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('/leads.md', { meta: { type: 'Collection', title: 'Заявки', icon: '📥', writeTo: '/leads', properties: {
- status: { kind: 'select', options: [{ name: 'new' }, { name: 'won' }] } } }, body: '' });
- ['Acme', 'Ромашка', 'Север'].forEach((n, i) => files.set(`/leads/lead-${i + 1}.md`, { meta: { title: n, status: 'new' }, body: `Заявка от ${n}.` }));
- const lenses = [
- { id: 'chat', package: 'chat', file: 'lens/chat.html', title: 'Чат', for: 'Record' },
- { id: 'chat', package: 'chat', file: 'lens/chat.html', title: 'Чат', for: 'Collection' },
- { id: 'table', package: 'lenses-records', file: 'lens/table.html', title: 'Таблица', for: 'Collection' },
- ];
- const title = (p: string, r: Rec) => String(r.meta.title ?? p.split('/').pop()!.replace(/\.md$/, ''));
- export const calls: string[] = [];
- const api: Record<string, (p: any) => unknown> = {
- 'space.info': () => ({ name: 'Демо', layout: { package: 'layout-basic', file: 'shell.html' }, lenses }),
- 'space.tools': () => tools.map((t) => ({ ...t, action: toolAction(t.name) })),
- tree: () => [...files.keys()].sort().map((path) => ({ path, type: String(files.get(path)!.meta.type ?? 'Record'), title: title(path, files.get(path)!), icon: files.get(path)!.meta.icon ?? null })),
- 'records.list': ({ collection }) => {
- const c = files.get(collection);
- if (!c) throw new Error('no collection ' + collection);
- const dir = String(c.meta.writeTo) + '/';
- return { collection: { path: collection, title: title(collection, c), 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, ...r }; },
- '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 }; },
- };
- const file = (p: string) => existsSync(p) ? new Response(Bun.file(p), { headers: { 'cache-control': 'no-cache' } }) : new Response('not found', { status: 404 });
- const port = Number(process.argv[2] ?? 4331);
- Bun.serve({
- port,
- async fetch(req) {
- const url = new URL(req.url);
- const p = decodeURIComponent(url.pathname);
- if (p.includes('..')) return new Response('bad', { status: 400 });
- if (p === '/') return file(join(packages, 'layout-basic/shell.html'));
- if (p === '/_api' && req.method === 'POST') {
- const { do: action, ...params } = await req.json();
- calls.push(action);
- if (process.env.LOG) console.log('api', action, JSON.stringify(params));
- const fn = api[action];
- if (!fn) return Response.json({ error: 'unknown action ' + action });
- try { return Response.json({ result: fn(params) }); } catch (e) { return Response.json({ error: (e as Error).message }); }
- }
- if (p.startsWith('/_kit/')) return file(join(kit, p.slice(6)));
- if (p.startsWith('/_pkg/')) return file(join(packages, p.slice(6)));
- return new Response('not found', { status: 404 });
- },
- });
- console.log(`chat host: http://127.0.0.1:${port}/?path=/index.md`);