ShtukbaseStandard
包文件→ .shtukbase/packages/lenses-records/test/serve-fake.ts

test/serve-fake.ts

128 行, 5.4 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. const packageRoot = new URL("../", import.meta.url);
  2. const kitRoot = new URL("../../kit-style/pages/design/kit-style/", import.meta.url);
  3. const client = Bun.file(new URL("../../layout-basic/lens.js", import.meta.url));
  4. const lensUrl = "/_pkg/lenses-records/lens/";
  5. const fakeClient = `
  6. window.shtuk = {
  7. path: new URLSearchParams(location.search).get("path"),
  8. async call(action, params) {
  9. const response = await fetch("/_api", {
  10. method: "POST",
  11. headers: { "Content-Type": "application/json" },
  12. body: JSON.stringify({ do: action, ...params }),
  13. });
  14. const { result, error } = await response.json();
  15. if (error) throw new Error(error);
  16. return result;
  17. },
  18. open(path) {
  19. location.assign("${lensUrl}record.html?path=" + encodeURIComponent(path));
  20. },
  21. ready() {},
  22. on(event, callback) { window.addEventListener(event, callback); },
  23. };
  24. `;
  25. const collection = {
  26. path: "/leads.md",
  27. title: "Заявки",
  28. icon: "📋",
  29. properties: {
  30. status: {
  31. kind: "select",
  32. label: "Статус",
  33. options: [
  34. { name: "new", label: "Новая", color: "blue" },
  35. { name: "contacted", label: "Связались", color: "orange" },
  36. { name: "won", label: "Принята", color: "green" },
  37. { name: "closed", label: "Закрыта" },
  38. ],
  39. },
  40. source: {
  41. kind: "select",
  42. label: "Источник",
  43. options: [
  44. { name: "site", label: "Сайт", color: "teal" },
  45. { name: "referral", label: "Рекомендация", color: "purple" },
  46. { name: "phone", label: "Звонок", color: "gray" },
  47. ],
  48. },
  49. amount: { kind: "number", label: "Сумма, ₽" },
  50. contact: { kind: "text", label: "Контакт" },
  51. next: { kind: "date", label: "Следующий шаг" },
  52. },
  53. };
  54. const samples = [
  55. ["atlas", "Студия «Атлас»", "new", "site", 45000, "Анна", "2026-12-01"],
  56. ["bereg", "Кафе «Берег»", "contacted", "referral", 32000, "Михаил", "2026-12-02"],
  57. ["contour", "Ателье «Контур»", "won", "site", 64000, "Лена", "2026-12-04"],
  58. ["delta", "Бюро «Дельта»", "contacted", "phone", 27000, "Олег", "2026-12-07"],
  59. ["etude", "Школа «Этюд»", "new", "referral", null, "Ирина", "2026-12-01"],
  60. ["forest", "Мастерская «Лес»", "won", "phone", 22000, "Роман", null],
  61. ["globe", "Клуб «Глобус»", "closed", "site", 0, "Яна", null],
  62. ["horizon", "Студия «Горизонт»", null, "referral", null, "‹hidden›", null],
  63. ] as const;
  64. const items = samples.map(([id, title, status, source, amount, contact, next]) => ({
  65. path: `/requests/${id}.md`,
  66. title,
  67. meta: { type: "Record", title, status, source, amount, contact, next },
  68. }));
  69. const tree = [
  70. { path: collection.path, type: "Collection", title: collection.title, icon: collection.icon },
  71. ...items.map(({ path, title }) => ({ path, type: "Record", title, icon: null })),
  72. ];
  73. const result = (value: unknown) => Response.json({ result: value });
  74. const failure = (error: string) => Response.json({ error }, { status: 400 });
  75. async function api(request: Request) {
  76. const input = await request.json().catch(() => null);
  77. if (input?.do === "tree") return result(tree);
  78. if (input?.do === "records.list" && input.collection === collection.path) return result({ collection, items });
  79. if (input?.do === "records.read") {
  80. if (input.path === collection.path) {
  81. const { path, ...meta } = collection;
  82. return result({ path, meta: { ...meta, type: "Collection", items: { path: "/requests" } }, body: "" });
  83. }
  84. const item = items.find(({ path }) => path === input.path);
  85. if (item) return result({
  86. path: item.path,
  87. meta: item.meta,
  88. body: "Нужна смета на первый этап.\nОбъём уточним после звонка.\n\nПодготовить два варианта.",
  89. });
  90. }
  91. return failure("Unknown request");
  92. }
  93. const server = Bun.serve({
  94. hostname: "127.0.0.1",
  95. port: Number(process.env.PORT ?? 0),
  96. async fetch(request) {
  97. const url = new URL(request.url);
  98. const { pathname } = url;
  99. if (pathname === "/_api" && request.method === "POST") return api(request);
  100. if (pathname === "/") {
  101. const path = url.searchParams.get("path") ?? collection.path;
  102. const lens = path === collection.path ? "table" : "record";
  103. return Response.redirect(new URL(`${lensUrl}${lens}.html?path=${encodeURIComponent(path)}`, url));
  104. }
  105. if (pathname === "/favicon.ico") return new Response(null, { status: 204 });
  106. if (pathname === "/_pkg/layout-basic/lens.js") {
  107. if (await client.exists()) return new Response(client);
  108. return new Response(fakeClient, { headers: { "Content-Type": "text/javascript" } });
  109. }
  110. const prefix = pathname.startsWith(lensUrl) ? lensUrl : "/_kit/";
  111. if (pathname.startsWith(prefix)) {
  112. const relative = pathname.slice(prefix.length);
  113. if (relative && relative.split("/").every((part) => /^[\w-][\w.-]*$/.test(part))) {
  114. const root = prefix === lensUrl ? new URL("lens/", packageRoot) : kitRoot;
  115. const file = Bun.file(new URL(relative, root));
  116. if (await file.exists()) return new Response(file);
  117. }
  118. }
  119. return new Response("Not found", { status: 404 });
  120. },
  121. });
  122. console.log(new URL(lensUrl + "table.html?path=/leads.md", server.url).href);