ShtukbaseStandard
archivo del paquete→ .shtukbase/packages/layout-basic/test/fake-host.ts

test/fake-host.ts

108 líneas, 5.6 KB.

El archivo tal como está en el paquete: el código y sus comentarios no se traducen.

  1. // A fake host for the layout: serves contract §5 with an in-memory /_api.
  2. // bun apps/standard/packages/layout-basic/test/fake-host.ts [port]
  3. import { existsSync } from 'node:fs';
  4. import { join, resolve } from 'node:path';
  5. const here = import.meta.dir;
  6. const pkg = resolve(here, '..');
  7. const packages = resolve(pkg, '..');
  8. const kit = join(packages, 'kit-style/pages/design/kit-style');
  9. const recordsPkg = join(packages, 'lenses-records');
  10. const useRealLenses = existsSync(join(recordsPkg, 'lens/table.html'));
  11. type Rec = { meta: Record<string, unknown>; body: string };
  12. const files = new Map<string, Rec>();
  13. files.set('/index.md', { meta: { type: 'Page', title: 'Главная', icon: '🏠' }, body: 'Добро пожаловать.' });
  14. files.set('/notes.md', { meta: { type: 'Page', title: 'Заметки', icon: '📝' }, body: 'Заметки.' });
  15. files.set('/notes/ideas.md', { meta: { type: 'Page', title: 'Идеи', icon: '💡' }, body: 'Идеи.' });
  16. files.set('/leads.md', {
  17. meta: {
  18. type: 'Collection', title: 'Заявки', icon: '📥', items: { mode: 'path', path: '/leads' }, writeTo: '/leads',
  19. properties: {
  20. status: { kind: 'select', label: 'Статус', options: [
  21. { name: 'new', label: 'Новая', color: 'blue' }, { name: 'talk', label: 'В работе', color: 'orange' },
  22. { name: 'won', label: 'Сделка', color: 'green' }, { name: 'lost', label: 'Отказ', color: 'gray' }] },
  23. source: { kind: 'select', label: 'Источник', options: [
  24. { name: 'site', label: 'Сайт', color: 'purple' }, { name: 'call', label: 'Звонок', color: 'teal' }] },
  25. amount: { kind: 'number', label: 'Сумма' },
  26. },
  27. },
  28. body: '',
  29. });
  30. const names = ['Acme', 'Ромашка', 'Север', 'Луч', 'Вектор', 'Орбита', 'Гранит', 'Прибой'];
  31. const statuses = ['new', 'talk', 'won', 'lost'];
  32. names.forEach((n, i) => files.set(`/leads/lead-${i + 1}.md`, {
  33. meta: { title: n, status: statuses[i % 4], source: i % 2 ? 'call' : 'site', amount: (i + 1) * 1000 },
  34. body: `Заявка от ${n}.`,
  35. }));
  36. const lenses = useRealLenses
  37. ? [
  38. { id: 'table', package: 'lenses-records', file: 'lens/table.html', title: 'Таблица', for: 'Collection' },
  39. { id: 'board', package: 'lenses-records', file: 'lens/board.html', title: 'Доска', for: 'Collection' },
  40. { id: 'record', package: 'lenses-records', file: 'lens/record.html', title: 'Запись', for: 'Record' },
  41. ]
  42. : [
  43. { id: 'table', package: 'demo', file: 'table.html', title: 'Таблица', for: 'Collection' },
  44. { id: 'board', package: 'demo', file: 'board.html', title: 'Доска', for: 'Collection' },
  45. { id: 'record', package: 'demo', file: 'record.html', title: 'Запись', for: 'Record' },
  46. ];
  47. function title(path: string, r: Rec) { return String(r.meta.title ?? path.split('/').pop()!.replace(/\.md$/, '')); }
  48. const api: Record<string, (p: any) => unknown> = {
  49. 'space.info': () => ({ name: 'Демо-пространство', layout: { package: 'layout-basic', file: 'shell.html' }, lenses }),
  50. tree: () => [...files.keys()].sort().map((path) => {
  51. const r = files.get(path)!;
  52. return { path, type: String(r.meta.type ?? 'Record'), title: title(path, r), icon: r.meta.icon ?? null };
  53. }),
  54. 'records.list': ({ collection }) => {
  55. const c = files.get(collection);
  56. if (!c) throw new Error('no collection ' + collection);
  57. const dir = collection.replace(/\.md$/, '/');
  58. return {
  59. collection: { path: collection, title: title(collection, c), icon: c.meta.icon, properties: c.meta.properties },
  60. items: [...files.keys()].sort().filter((p) => p.startsWith(dir)).map((p) => ({ path: p, meta: files.get(p)!.meta, title: title(p, files.get(p)!) })),
  61. };
  62. },
  63. 'records.read': ({ path }) => {
  64. const r = files.get(path);
  65. if (!r) throw new Error('not found ' + path);
  66. return { path, meta: r.meta, body: r.body };
  67. },
  68. 'records.write': ({ path, meta, body }) => {
  69. const r = files.get(path) ?? { meta: {}, body: '' };
  70. files.set(path, { meta: { ...r.meta, ...(meta ?? {}) }, body: body ?? r.body });
  71. return { path };
  72. },
  73. };
  74. function file(path: string) {
  75. if (!existsSync(path)) return new Response('not found', { status: 404 });
  76. return new Response(Bun.file(path), { headers: { 'cache-control': 'no-cache' } });
  77. }
  78. const port = Number(process.argv[2] ?? 4321);
  79. Bun.serve({
  80. port,
  81. async fetch(req) {
  82. const url = new URL(req.url);
  83. const p = decodeURIComponent(url.pathname);
  84. if (process.env.LOG) console.log(req.method, url.pathname + url.search, req.headers.get("sec-fetch-site") ?? "");
  85. if (p.includes('..')) return new Response('bad', { status: 400 });
  86. if (p === '/') return file(join(pkg, 'shell.html'));
  87. if (p === '/_api' && req.method === 'POST') {
  88. const { do: action, ...params } = await req.json();
  89. const fn = api[action];
  90. if (!fn) return Response.json({ error: 'unknown action ' + action });
  91. await Bun.sleep(5);
  92. try { return Response.json({ result: fn(params) }); } catch (e) { return Response.json({ error: String((e as Error).message) }); }
  93. }
  94. if (p.startsWith('/_kit/')) return file(join(kit, p.slice(6)));
  95. if (p.startsWith('/_pkg/layout-basic/')) return file(join(pkg, p.slice(19)));
  96. if (p.startsWith('/_pkg/lenses-records/')) return file(join(recordsPkg, p.slice(21)));
  97. if (p.startsWith('/_pkg/demo/')) return file(join(here, 'demo-lens.html'));
  98. return new Response('not found', { status: 404 });
  99. },
  100. });
  101. console.log(`fake host: http://127.0.0.1:${port}/ (lenses: ${useRealLenses ? 'lenses-records' : 'demo'})`);